text
stringlengths 54
60.6k
|
---|
<commit_before>#include <net/tcp/connection.hpp>
#include <net/stream.hpp>
// TCP stream
namespace net::tcp
{
/**
* @brief Exposes a TCP Connection as a Stream with only the most necessary features.
* May be overrided by extensions like TLS etc for additional functionality.
*/
class Stream final : public net::Stream {
public:
static const uint16_t SUBID = 1;
/**
* @brief Construct a Stream for a Connection ptr
*
* @param[in] conn The connection
*/
Stream(Connection_ptr conn)
: m_tcp{std::move(conn)}
{
// stream for a nullptr makes no sense
Expects(m_tcp != nullptr);
m_tcp->on_close({this, &Stream::close});
}
~Stream()
{
this->reset_callbacks();
m_tcp->close();
}
/**
* @brief Event when the stream is connected/established/ready to use.
*
* @param[in] cb The connect callback
*/
void on_connect(ConnectCallback cb) override
{
m_tcp->on_connect(Connection::ConnectCallback::make_packed(
[this, cb] (Connection_ptr conn)
{ if(conn) cb(*this); }));
}
/**
* @brief Event when data is received.
*
* @param[in] n The size of the receive buffer
* @param[in] cb The read callback
*/
void on_read(size_t n, ReadCallback cb) override
{ m_tcp->on_read(n, cb); }
/**
* @brief Event for when the Stream is being closed.
*
* @param[in] cb The close callback
*/
void on_close(CloseCallback cb) override
{
m_on_close = std::move(cb);
}
/**
* @brief Event for when data has been written.
*
* @param[in] cb The write callback
*/
void on_write(WriteCallback cb) override
{ m_tcp->on_write(cb); }
/**
* @brief Async write of a data with a length.
*
* @param[in] buf data
* @param[in] n length
*/
void write(const void* buf, size_t n) override
{ m_tcp->write(buf, n); }
/**
* @brief Async write of a shared buffer with a length.
*
* @param[in] buffer shared buffer
* @param[in] n length
*/
void write(buffer_t buffer) override
{ m_tcp->write(buffer); }
/**
* @brief Async write of a string.
* Calls write(const void* buf, size_t n)
*
* @param[in] str The string
*/
void write(const std::string& str) override
{ write(str.data(), str.size()); }
/**
* @brief Closes the stream.
*/
void close() override
{
auto onclose = std::move(this->m_on_close);
m_tcp->reset_callbacks();
m_tcp->close();
if (onclose) onclose();
}
/**
* @brief Resets all callbacks.
*/
void reset_callbacks() override
{ m_tcp->reset_callbacks(); }
/**
* @brief Returns the streams local socket.
*
* @return A TCP Socket
*/
Socket local() const override
{ return m_tcp->local(); }
/**
* @brief Returns the streams remote socket.
*
* @return A TCP Socket
*/
Socket remote() const override
{ return m_tcp->remote(); }
/**
* @brief Returns a string representation of the stream.
*
* @return String representation of the stream.
*/
std::string to_string() const override
{ return m_tcp->to_string(); }
/**
* @brief Determines if connected (established).
*
* @return True if connected, False otherwise.
*/
bool is_connected() const noexcept override
{ return m_tcp->is_connected(); }
/**
* @brief Determines if writable. (write is allowed)
*
* @return True if writable, False otherwise.
*/
bool is_writable() const noexcept override
{ return m_tcp->is_writable(); }
/**
* @brief Determines if readable. (data can be received)
*
* @return True if readable, False otherwise.
*/
bool is_readable() const noexcept override
{ return m_tcp->is_readable(); }
/**
* @brief Determines if closing.
*
* @return True if closing, False otherwise.
*/
bool is_closing() const noexcept override
{ return m_tcp->is_closing(); }
/**
* @brief Determines if closed.
*
* @return True if closed, False otherwise.
*/
bool is_closed() const noexcept override
{ return m_tcp->is_closed(); };
int get_cpuid() const noexcept override;
size_t serialize_to(void* p, const size_t) const override {
return m_tcp->serialize_to(p);
}
uint16_t serialization_subid() const override {
return SUBID;
}
Stream* transport() noexcept override {
return nullptr;
}
Connection_ptr tcp() {
return this->m_tcp;
}
protected:
Connection_ptr m_tcp;
CloseCallback m_on_close = nullptr;
}; // < class Connection::Stream
}
<commit_msg>tcp: At least call close when Stream connect fails<commit_after>#include <net/tcp/connection.hpp>
#include <net/stream.hpp>
// TCP stream
namespace net::tcp
{
/**
* @brief Exposes a TCP Connection as a Stream with only the most necessary features.
* May be overrided by extensions like TLS etc for additional functionality.
*/
class Stream final : public net::Stream {
public:
static const uint16_t SUBID = 1;
/**
* @brief Construct a Stream for a Connection ptr
*
* @param[in] conn The connection
*/
Stream(Connection_ptr conn)
: m_tcp{std::move(conn)}
{
// stream for a nullptr makes no sense
Expects(m_tcp != nullptr);
m_tcp->on_close({this, &Stream::close});
}
~Stream()
{
this->reset_callbacks();
m_tcp->close();
}
/**
* @brief Event when the stream is connected/established/ready to use.
*
* @param[in] cb The connect callback
*/
void on_connect(ConnectCallback cb) override
{
m_tcp->on_connect(Connection::ConnectCallback::make_packed(
[this, cb] (Connection_ptr conn)
{
// this will ensure at least close is called if the connect fails
if (conn != nullptr) {
cb(*this);
}
else {
if (this->m_on_close) this->m_on_close();
}
}));
}
/**
* @brief Event when data is received.
*
* @param[in] n The size of the receive buffer
* @param[in] cb The read callback
*/
void on_read(size_t n, ReadCallback cb) override
{ m_tcp->on_read(n, cb); }
/**
* @brief Event for when the Stream is being closed.
*
* @param[in] cb The close callback
*/
void on_close(CloseCallback cb) override
{
m_on_close = std::move(cb);
}
/**
* @brief Event for when data has been written.
*
* @param[in] cb The write callback
*/
void on_write(WriteCallback cb) override
{ m_tcp->on_write(cb); }
/**
* @brief Async write of a data with a length.
*
* @param[in] buf data
* @param[in] n length
*/
void write(const void* buf, size_t n) override
{ m_tcp->write(buf, n); }
/**
* @brief Async write of a shared buffer with a length.
*
* @param[in] buffer shared buffer
* @param[in] n length
*/
void write(buffer_t buffer) override
{ m_tcp->write(buffer); }
/**
* @brief Async write of a string.
* Calls write(const void* buf, size_t n)
*
* @param[in] str The string
*/
void write(const std::string& str) override
{ write(str.data(), str.size()); }
/**
* @brief Closes the stream.
*/
void close() override
{
auto onclose = std::move(this->m_on_close);
m_tcp->reset_callbacks();
m_tcp->close();
if (onclose) onclose();
}
/**
* @brief Resets all callbacks.
*/
void reset_callbacks() override
{ m_tcp->reset_callbacks(); }
/**
* @brief Returns the streams local socket.
*
* @return A TCP Socket
*/
Socket local() const override
{ return m_tcp->local(); }
/**
* @brief Returns the streams remote socket.
*
* @return A TCP Socket
*/
Socket remote() const override
{ return m_tcp->remote(); }
/**
* @brief Returns a string representation of the stream.
*
* @return String representation of the stream.
*/
std::string to_string() const override
{ return m_tcp->to_string(); }
/**
* @brief Determines if connected (established).
*
* @return True if connected, False otherwise.
*/
bool is_connected() const noexcept override
{ return m_tcp->is_connected(); }
/**
* @brief Determines if writable. (write is allowed)
*
* @return True if writable, False otherwise.
*/
bool is_writable() const noexcept override
{ return m_tcp->is_writable(); }
/**
* @brief Determines if readable. (data can be received)
*
* @return True if readable, False otherwise.
*/
bool is_readable() const noexcept override
{ return m_tcp->is_readable(); }
/**
* @brief Determines if closing.
*
* @return True if closing, False otherwise.
*/
bool is_closing() const noexcept override
{ return m_tcp->is_closing(); }
/**
* @brief Determines if closed.
*
* @return True if closed, False otherwise.
*/
bool is_closed() const noexcept override
{ return m_tcp->is_closed(); };
int get_cpuid() const noexcept override;
size_t serialize_to(void* p, const size_t) const override {
return m_tcp->serialize_to(p);
}
uint16_t serialization_subid() const override {
return SUBID;
}
Stream* transport() noexcept override {
return nullptr;
}
Connection_ptr tcp() {
return this->m_tcp;
}
protected:
Connection_ptr m_tcp;
CloseCallback m_on_close = nullptr;
}; // < class Connection::Stream
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autofill/autofill_cc_infobar_delegate.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/autofill/autofill_cc_infobar.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
AutoFillCCInfoBarDelegate::AutoFillCCInfoBarDelegate(TabContents* tab_contents,
AutoFillManager* host)
: ConfirmInfoBarDelegate(tab_contents),
browser_(NULL),
host_(host) {
if (tab_contents) {
// This is NULL for TestTabContents.
if (tab_contents->delegate())
browser_ = tab_contents->delegate()->GetBrowser();
tab_contents->AddInfoBar(this);
}
}
AutoFillCCInfoBarDelegate::~AutoFillCCInfoBarDelegate() {
}
bool AutoFillCCInfoBarDelegate::ShouldExpire(
const NavigationController::LoadCommittedDetails& details) const {
// The user has submitted a form, causing the page to navigate elsewhere. We
// don't want the infobar to be expired at this point, because the user won't
// get a chance to answer the question.
return false;
}
void AutoFillCCInfoBarDelegate::InfoBarClosed() {
if (host_) {
host_->OnInfoBarClosed(false);
host_ = NULL;
}
// This will delete us.
ConfirmInfoBarDelegate::InfoBarClosed();
}
std::wstring AutoFillCCInfoBarDelegate::GetMessageText() const {
return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_TEXT);
}
SkBitmap* AutoFillCCInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_AUTOFILL);
}
int AutoFillCCInfoBarDelegate::GetButtons() const {
return BUTTON_OK | BUTTON_CANCEL;
}
std::wstring AutoFillCCInfoBarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
if (button == BUTTON_OK)
return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_ACCEPT);
else if (button == BUTTON_CANCEL)
return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_DENY);
else
NOTREACHED();
return std::wstring();
}
bool AutoFillCCInfoBarDelegate::Accept() {
if (host_) {
host_->OnInfoBarClosed(true);
host_ = NULL;
}
return true;
}
bool AutoFillCCInfoBarDelegate::Cancel() {
if (host_) {
host_->OnInfoBarClosed(false);
host_ = NULL;
}
return true;
}
std::wstring AutoFillCCInfoBarDelegate::GetLinkText() {
return l10n_util::GetString(IDS_AUTOFILL_CC_LEARN_MORE);
}
bool AutoFillCCInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
browser_->OpenURL(GURL(kAutoFillLearnMoreUrl), GURL(), NEW_FOREGROUND_TAB,
PageTransition::TYPED);
return false;
}
#if defined(OS_WIN)
InfoBar* AutoFillCCInfoBarDelegate::CreateInfoBar() {
return CreateAutofillCcInfoBar(this);
}
#endif // defined(OS_WIN)
<commit_msg>AutoFill: Collect UMA stats for AutoFill CC InfoBar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autofill/autofill_cc_infobar_delegate.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/histogram.h"
#include "chrome/browser/autofill/autofill_cc_infobar.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
AutoFillCCInfoBarDelegate::AutoFillCCInfoBarDelegate(TabContents* tab_contents,
AutoFillManager* host)
: ConfirmInfoBarDelegate(tab_contents),
browser_(NULL),
host_(host) {
if (tab_contents) {
// This is NULL for TestTabContents.
if (tab_contents->delegate())
browser_ = tab_contents->delegate()->GetBrowser();
tab_contents->AddInfoBar(this);
}
}
AutoFillCCInfoBarDelegate::~AutoFillCCInfoBarDelegate() {
}
bool AutoFillCCInfoBarDelegate::ShouldExpire(
const NavigationController::LoadCommittedDetails& details) const {
// The user has submitted a form, causing the page to navigate elsewhere. We
// don't want the infobar to be expired at this point, because the user won't
// get a chance to answer the question.
return false;
}
void AutoFillCCInfoBarDelegate::InfoBarClosed() {
if (host_) {
host_->OnInfoBarClosed(false);
host_ = NULL;
}
// This will delete us.
ConfirmInfoBarDelegate::InfoBarClosed();
}
std::wstring AutoFillCCInfoBarDelegate::GetMessageText() const {
return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_TEXT);
}
SkBitmap* AutoFillCCInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_AUTOFILL);
}
int AutoFillCCInfoBarDelegate::GetButtons() const {
return BUTTON_OK | BUTTON_CANCEL;
}
std::wstring AutoFillCCInfoBarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
if (button == BUTTON_OK)
return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_ACCEPT);
else if (button == BUTTON_CANCEL)
return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_DENY);
else
NOTREACHED();
return std::wstring();
}
bool AutoFillCCInfoBarDelegate::Accept() {
UMA_HISTOGRAM_COUNTS("AutoFill.CCInfoBarAccepted", 1);
if (host_) {
host_->OnInfoBarClosed(true);
host_ = NULL;
}
return true;
}
bool AutoFillCCInfoBarDelegate::Cancel() {
UMA_HISTOGRAM_COUNTS("AutoFill.CCInfoBarDenied", 1);
if (host_) {
host_->OnInfoBarClosed(false);
host_ = NULL;
}
return true;
}
std::wstring AutoFillCCInfoBarDelegate::GetLinkText() {
return l10n_util::GetString(IDS_AUTOFILL_CC_LEARN_MORE);
}
bool AutoFillCCInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
browser_->OpenURL(GURL(kAutoFillLearnMoreUrl), GURL(), NEW_FOREGROUND_TAB,
PageTransition::TYPED);
return false;
}
#if defined(OS_WIN)
InfoBar* AutoFillCCInfoBarDelegate::CreateInfoBar() {
return CreateAutofillCcInfoBar(this);
}
#endif // defined(OS_WIN)
<|endoftext|> |
<commit_before>/*
webpresenceplugin.cpp
Kopete Web Presence plugin
Copyright (c) 2002 by Will Stephenson <[email protected]>
Kopete (c) 2002 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qtimer.h>
#include <qptrlist.h>
#include <qfile.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <ktempfile.h>
#include <kio/job.h>
#include <knotifyclient.h>
#include <kaction.h>
#include <kstdguiitem.h>
#include <kstandarddirs.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/DOCBparser.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include "kopetecontactlist.h"
#include "pluginloader.h"
#include "kopeteprotocol.h"
#include "kopetemetacontact.h"
#include "webpresenceplugin.h"
#include "webpresencepreferences.h"
K_EXPORT_COMPONENT_FACTORY( kopete_webpresence, KGenericFactory<WebPresencePlugin> );
WebPresencePlugin::WebPresencePlugin( QObject *parent, const char *name, const QStringList& /*args*/ )
: KopetePlugin( parent, name )
{
m_prefs = new WebPresencePreferences( "", this );
connect ( m_prefs, SIGNAL( saved() ), this, SLOT( slotSettingsChanged() ) );
m_timer = new QTimer();
connect ( m_timer, SIGNAL( timeout() ), this, SLOT( slotWriteFile() ) );
m_timer->start( m_prefs->frequency() * 1000 * 60);
}
WebPresencePlugin::~WebPresencePlugin()
{}
void WebPresencePlugin::slotWriteFile()
{
bool error = false;
// generate the (temporary) XML file representing the current contactlist
KTempFile* xml = generateFile();
xml->setAutoDelete( true );
kdDebug() << "WebPresencePlugin::slotWriteFile() : " << xml->name()
<< endl;
if ( m_prefs->justXml() )
{
m_output = xml;
xml = 0L;
}
else
{
// transform XML to the final format
m_output = new KTempFile();
m_output->setAutoDelete( true );
if ( !transform( xml, m_output ) )
{
error = true;
delete m_output;
}
delete xml; // might make debugging harder!
}
if ( !error )
{
// upload it to the specified URL
KURL src( m_output->name() );
KURL dest( m_prefs->url() );
KIO::FileCopyJob *job = KIO::file_copy( src, dest, -1, true, false, false );
connect( job, SIGNAL( result( KIO::Job * ) ),
SLOT( slotUploadJobResult( KIO::Job * ) ) );
}
}
void WebPresencePlugin::slotUploadJobResult( KIO::Job *job )
{
if ( job->error() ) {
kdDebug() << "Error uploading presence info." << endl;
job->showErrorDialog( 0 );
}
delete m_output;
return;
}
KTempFile* WebPresencePlugin::generateFile()
{
kdDebug() << "WebPresencePlugin::generateFile()" << endl;
// generate the (temporary) file representing the current contactlist
KTempFile* theFile = new KTempFile();
QTextStream* qout = theFile->textStream() ;
QPtrList<KopeteProtocol> protocols = allProtocols();
int depth = 0;
QString shift;
*qout << "<?xml version=\"1.0\"?>\n"
<< shift.fill( '\t', ++depth ) << "<contacts>\n";
*qout << shift.fill( '\t', ++depth ) << "<contact type=\"self\">\n";
*qout << shift.fill( '\t', ++depth ) << "<name>";
if ( !m_prefs->useImName() && !m_prefs->userName().isEmpty() )
*qout << m_prefs->userName();
else
*qout << protocols.first()->myself()->displayName();
*qout << "</name>\n";
*qout << shift.fill( '\t', depth++ ) << "<protocols>\n";
for ( KopeteProtocol *p = protocols.first();
p; p = protocols.next() )
{
Q_ASSERT( p );
kdDebug() << p->pluginId() << endl;
kdDebug() << statusAsString( p->myself()->status() ) << endl;
kdDebug() << p->myself()->contactId().latin1() << endl;
*qout << shift.fill( '\t', depth++ ) << "<protocol>\n";
*qout << shift.fill( '\t', depth ) << "<protoname>"
<< p->pluginId() << "</protoname>\n";
*qout << shift.fill( '\t', depth ) << "<protostatus>"
<< statusAsString( p->myself()->status() )
<< "</protostatus>\n";
if ( m_prefs->showAddresses() )
{
*qout << shift.fill( '\t', depth ) << "<protoaddress>"
<< p->myself()->contactId().latin1()
<< "</protoaddress>\n";
}
*qout << shift.fill( '\t', --depth ) << "</protocol>\n";
}
*qout << shift.fill( '\t', --depth ) << "</protocols>\n";
*qout << shift.fill( '\t', --depth ) << "</contact>\n";
*qout << shift.fill( '\t', --depth ) << "</contacts>\n" << endl;
theFile->close();
return theFile;
}
bool WebPresencePlugin::transform( KTempFile* src, KTempFile* dest )
{
xmlSubstituteEntitiesDefault( 1 );
xmlLoadExtDtdDefaultValue = 1;
// test if the stylesheet exists
QFile sheet;
if ( m_prefs->useDefaultStyleSheet() )
sheet.setName( locateLocal( "appdata", "webpresencedefault.xsl" ) );
else
sheet.setName( m_prefs->userStyleSheet() );
QString error = "";
if ( sheet.exists() )
{
// and if it is a valid stylesheet
xsltStylesheetPtr cur = NULL;
if ( ( cur = xsltParseStylesheetFile(
( const xmlChar *) sheet.name().latin1() ) ) )
{
// and if we can parse the input XML
xmlDocPtr doc = NULL;
if ( ( doc = xmlParseFile( src->name() ) ) )
{
// and if we can apply the stylesheet
xmlDocPtr res = NULL;
if ( ( res = xsltApplyStylesheet( cur, doc, 0 ) ) )
{
// and if we can save the result
if ( xsltSaveResultToFile(dest->fstream() , res, cur)
!= -1 )
{
// then it all worked!
dest->close();
}
else
error = "write result!";
}
else
{
error = "apply stylesheet!";
error += " Check the stylesheet works using xsltproc";
}
xmlFreeDoc(res);
}
else
error = "parse input XML!";
xmlFreeDoc(doc);
}
else
error = "parse stylesheet!";
xsltFreeStylesheet(cur);
}
else
error = "find stylesheet!";
xsltCleanupGlobals();
xmlCleanupParser();
if ( error.isEmpty() )
return true;
else
{
kdDebug() << "WebPresencePlugin::transform() - couldn't "
<< error << endl;
return false;
}
}
QPtrList<KopeteProtocol> WebPresencePlugin::allProtocols()
{
kdDebug() << "WebPresencePlugin::allProtocols()" << endl;
QPtrList<KopeteProtocol> protos;
QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();
for( KopetePlugin *p = plugins.first(); p; p = plugins.next() )
{
KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );
if( !proto )
continue;
protos.append( proto );
}
return protos;
}
QString WebPresencePlugin::statusAsString( KopeteContact::ContactStatus c )
{
QString status;
switch ( c )
{
case KopeteContact::Online:
status = "ONLINE";
break;
case KopeteContact::Away:
status = "AWAY";
break;
case KopeteContact::Offline:
status = "OFFLINE";
break;
default:
status = "UNKNOWN";
}
return status;
}
void WebPresencePlugin::slotSettingsChanged()
{
m_timer->start( m_prefs->frequency() * 1000 * 60);
}
// vim: set noet ts=4 sts=4 sw=4:
#include "webpresenceplugin.moc"
<commit_msg>Now looking for the default stylesheet where it gets installed.<commit_after>/*
webpresenceplugin.cpp
Kopete Web Presence plugin
Copyright (c) 2002 by Will Stephenson <[email protected]>
Kopete (c) 2002 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qtimer.h>
#include <qptrlist.h>
#include <qfile.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <ktempfile.h>
#include <kio/job.h>
#include <knotifyclient.h>
#include <kaction.h>
#include <kstdguiitem.h>
#include <kstandarddirs.h>
#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/DOCBparser.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include "kopetecontactlist.h"
#include "pluginloader.h"
#include "kopeteprotocol.h"
#include "kopetemetacontact.h"
#include "webpresenceplugin.h"
#include "webpresencepreferences.h"
K_EXPORT_COMPONENT_FACTORY( kopete_webpresence, KGenericFactory<WebPresencePlugin> );
WebPresencePlugin::WebPresencePlugin( QObject *parent, const char *name, const QStringList& /*args*/ )
: KopetePlugin( parent, name )
{
m_prefs = new WebPresencePreferences( "", this );
connect ( m_prefs, SIGNAL( saved() ), this, SLOT( slotSettingsChanged() ) );
m_timer = new QTimer();
connect ( m_timer, SIGNAL( timeout() ), this, SLOT( slotWriteFile() ) );
m_timer->start( m_prefs->frequency() * 1000 * 60);
}
WebPresencePlugin::~WebPresencePlugin()
{}
void WebPresencePlugin::slotWriteFile()
{
bool error = false;
// generate the (temporary) XML file representing the current contactlist
KTempFile* xml = generateFile();
xml->setAutoDelete( true );
kdDebug() << "WebPresencePlugin::slotWriteFile() : " << xml->name()
<< endl;
if ( m_prefs->justXml() )
{
m_output = xml;
xml = 0L;
}
else
{
// transform XML to the final format
m_output = new KTempFile();
m_output->setAutoDelete( true );
if ( !transform( xml, m_output ) )
{
error = true;
delete m_output;
}
delete xml; // might make debugging harder!
}
if ( !error )
{
// upload it to the specified URL
KURL src( m_output->name() );
KURL dest( m_prefs->url() );
KIO::FileCopyJob *job = KIO::file_copy( src, dest, -1, true, false, false );
connect( job, SIGNAL( result( KIO::Job * ) ),
SLOT( slotUploadJobResult( KIO::Job * ) ) );
}
}
void WebPresencePlugin::slotUploadJobResult( KIO::Job *job )
{
if ( job->error() ) {
kdDebug() << "Error uploading presence info." << endl;
job->showErrorDialog( 0 );
}
delete m_output;
return;
}
KTempFile* WebPresencePlugin::generateFile()
{
kdDebug() << "WebPresencePlugin::generateFile()" << endl;
// generate the (temporary) file representing the current contactlist
KTempFile* theFile = new KTempFile();
QTextStream* qout = theFile->textStream() ;
QPtrList<KopeteProtocol> protocols = allProtocols();
int depth = 0;
QString shift;
*qout << "<?xml version=\"1.0\"?>\n"
<< shift.fill( '\t', ++depth ) << "<contacts>\n";
*qout << shift.fill( '\t', ++depth ) << "<contact type=\"self\">\n";
*qout << shift.fill( '\t', ++depth ) << "<name>";
if ( !m_prefs->useImName() && !m_prefs->userName().isEmpty() )
*qout << m_prefs->userName();
else
*qout << protocols.first()->myself()->displayName();
*qout << "</name>\n";
*qout << shift.fill( '\t', depth++ ) << "<protocols>\n";
for ( KopeteProtocol *p = protocols.first();
p; p = protocols.next() )
{
Q_ASSERT( p );
kdDebug() << p->pluginId() << endl;
kdDebug() << statusAsString( p->myself()->status() ) << endl;
kdDebug() << p->myself()->contactId().latin1() << endl;
*qout << shift.fill( '\t', depth++ ) << "<protocol>\n";
*qout << shift.fill( '\t', depth ) << "<protoname>"
<< p->pluginId() << "</protoname>\n";
*qout << shift.fill( '\t', depth ) << "<protostatus>"
<< statusAsString( p->myself()->status() )
<< "</protostatus>\n";
if ( m_prefs->showAddresses() )
{
*qout << shift.fill( '\t', depth ) << "<protoaddress>"
<< p->myself()->contactId().latin1()
<< "</protoaddress>\n";
}
*qout << shift.fill( '\t', --depth ) << "</protocol>\n";
}
*qout << shift.fill( '\t', --depth ) << "</protocols>\n";
*qout << shift.fill( '\t', --depth ) << "</contact>\n";
*qout << shift.fill( '\t', --depth ) << "</contacts>\n" << endl;
theFile->close();
return theFile;
}
bool WebPresencePlugin::transform( KTempFile* src, KTempFile* dest )
{
xmlSubstituteEntitiesDefault( 1 );
xmlLoadExtDtdDefaultValue = 1;
// test if the stylesheet exists
QFile sheet;
if ( m_prefs->useDefaultStyleSheet() )
sheet.setName( locate( "appdata", "webpresencedefault.xsl" ) );
else
sheet.setName( m_prefs->userStyleSheet() );
QString error = "";
if ( sheet.exists() )
{
// and if it is a valid stylesheet
xsltStylesheetPtr cur = NULL;
if ( ( cur = xsltParseStylesheetFile(
( const xmlChar *) sheet.name().latin1() ) ) )
{
// and if we can parse the input XML
xmlDocPtr doc = NULL;
if ( ( doc = xmlParseFile( src->name() ) ) )
{
// and if we can apply the stylesheet
xmlDocPtr res = NULL;
if ( ( res = xsltApplyStylesheet( cur, doc, 0 ) ) )
{
// and if we can save the result
if ( xsltSaveResultToFile(dest->fstream() , res, cur)
!= -1 )
{
// then it all worked!
dest->close();
}
else
error = "write result!";
}
else
{
error = "apply stylesheet!";
error += " Check the stylesheet works using xsltproc";
}
xmlFreeDoc(res);
}
else
error = "parse input XML!";
xmlFreeDoc(doc);
}
else
error = "parse stylesheet!";
xsltFreeStylesheet(cur);
}
else
error = "find stylesheet!";
xsltCleanupGlobals();
xmlCleanupParser();
if ( error.isEmpty() )
return true;
else
{
kdDebug() << "WebPresencePlugin::transform() - couldn't "
<< error << endl;
return false;
}
}
QPtrList<KopeteProtocol> WebPresencePlugin::allProtocols()
{
kdDebug() << "WebPresencePlugin::allProtocols()" << endl;
QPtrList<KopeteProtocol> protos;
QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();
for( KopetePlugin *p = plugins.first(); p; p = plugins.next() )
{
KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );
if( !proto )
continue;
protos.append( proto );
}
return protos;
}
QString WebPresencePlugin::statusAsString( KopeteContact::ContactStatus c )
{
QString status;
switch ( c )
{
case KopeteContact::Online:
status = "ONLINE";
break;
case KopeteContact::Away:
status = "AWAY";
break;
case KopeteContact::Offline:
status = "OFFLINE";
break;
default:
status = "UNKNOWN";
}
return status;
}
void WebPresencePlugin::slotSettingsChanged()
{
m_timer->start( m_prefs->frequency() * 1000 * 60);
}
// vim: set noet ts=4 sts=4 sw=4:
#include "webpresenceplugin.moc"
<|endoftext|> |
<commit_before>#ifndef AL_PARAMETERMIDI_H
#define AL_PARAMETERMIDI_H
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012-2015. The Regents of the University of California.
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 University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Class to connect MIDI Input to Parameter objects
File author(s):
Andrés Cabrera [email protected]
*/
#include "allocore/io/al_MIDI.hpp"
#include "allocore/ui/al_Parameter.hpp"
namespace al
{
/**
* @brief The ParameterMIDI class connects Parameter objects to MIDI messages
*
*
@code
Parameter Size("Size", "", 1.0, "", 0, 1.0);
Parameter Speed("Speed", "", 0.05, "", 0.01, 0.3);
ParameterMIDI parameterMIDI;
parameterMIDI.connectControl(Size, 1, 1);
parameterMIDI.connectControl(Speed, 10, 1);
@endcode
*
*/
class ParameterMIDI : public MIDIMessageHandler {
public:
ParameterMIDI(int deviceIndex = 0, bool verbose = false) {
MIDIMessageHandler::bindTo(mMidiIn);
mVerbose = verbose;
try {
mMidiIn.openPort(deviceIndex);
printf("Opened port to %s\n", mMidiIn.getPortName(deviceIndex).c_str());
}
catch (al::MIDIError error) {
std::cout << "ParameterMIDI Warning: Could not open MIDI port " << deviceIndex << std::endl;
}
}
void connectControl(Parameter ¶m, int controlNumber, int channel)
{
connectControl(param, controlNumber, channel, (float) param.min(), (float) param.max());
}
void connectControl(Parameter ¶m, int controlNumber, int channel,
float min, float max) {
ControlBinding newBinding;
newBinding.controlNumber = controlNumber;
newBinding.channel = channel - 1;
newBinding.param = ¶m;
newBinding.min = min;
newBinding.max = max;
mBindings.push_back(newBinding);
}
/**
* @brief connectNoteToValue
* @param param the parameter to bind
* @param channel MIDI channel (1-16)
* @param min The parameter value to map the lowest note
* @param low The MIDI note number for the lowest (or only) note to map
* @param max The value unto which the highest note is mapped
* @param high The highest MIDI note number to map
*/
void connectNoteToValue(Parameter ¶m, int channel,
float min, int low,
float max = -1, int high = -1) {
if (high == -1) {
max = min;
high = low;
}
for (int num = low; num <= high; ++num) {
NoteBinding newBinding;
newBinding.noteNumber = num;
if (num != high) {
newBinding.value = min + (max - min) * (num - low)/(high - low);
} else {
newBinding.value = max;
}
newBinding.channel = channel - 1;
newBinding.param = ¶m;
mNoteBindings.push_back(newBinding);
}
}
void connectNoteToIncrement(Parameter ¶m, int channel, int note,
float increment) {
IncrementBinding newBinding;
newBinding.channel = channel - 1;
newBinding.noteNumber = note;
newBinding.increment = increment;
newBinding.param = ¶m;
mIncrementBindings.push_back(newBinding);
}
virtual void onMIDIMessage(const MIDIMessage& m) override {
if (m.type() & MIDIByte::CONTROL_CHANGE ) {
for(ControlBinding binding: mBindings) {
if (m.channel() == binding.channel
&& m.controlNumber() == binding.controlNumber) {
float newValue = binding.min + (m.controlValue() * (binding.max - binding.min));
binding.param->set(newValue);
}
}
}
if (m.type() & MIDIByte::NOTE_ON && m.velocity() > 0) {
for(NoteBinding binding: mNoteBindings) {
if (m.channel() == binding.channel
&& m.noteNumber() == binding.noteNumber) {
binding.param->set(binding.value);
}
}
for(IncrementBinding binding: mIncrementBindings) {
if (m.channel() == binding.channel
&& m.noteNumber() == binding.noteNumber) {
binding.param->set(binding.param->get() + binding.increment);
}
}
}
if (mVerbose) {
m.print();
}
}
private:
struct ControlBinding {
int controlNumber;
int channel;
Parameter *param;
float min, max;
};
struct NoteBinding {
int noteNumber;
int channel;
float value;
Parameter *param;
};
struct IncrementBinding {
int noteNumber;
int channel;
float increment;
Parameter *param;
};
MIDIIn mMidiIn;
bool mVerbose;
std::vector<ControlBinding> mBindings;
std::vector<NoteBinding> mNoteBindings;
std::vector<IncrementBinding> mIncrementBindings;
};
}
#endif // AL_PARAMETERMIDI_H
<commit_msg>Added connectNoteToToggle function to ParameterMIDI<commit_after>#ifndef AL_PARAMETERMIDI_H
#define AL_PARAMETERMIDI_H
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012-2015. The Regents of the University of California.
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 University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Class to connect MIDI Input to Parameter objects
File author(s):
Andrés Cabrera [email protected]
*/
#include "allocore/io/al_MIDI.hpp"
#include "allocore/ui/al_Parameter.hpp"
namespace al
{
/**
* @brief The ParameterMIDI class connects Parameter objects to MIDI messages
*
*
@code
Parameter Size("Size", "", 1.0, "", 0, 1.0);
Parameter Speed("Speed", "", 0.05, "", 0.01, 0.3);
ParameterMIDI parameterMIDI;
parameterMIDI.connectControl(Size, 1, 1);
parameterMIDI.connectControl(Speed, 10, 1);
@endcode
*
*/
class ParameterMIDI : public MIDIMessageHandler {
public:
ParameterMIDI(int deviceIndex = 0, bool verbose = false) {
MIDIMessageHandler::bindTo(mMidiIn);
mVerbose = verbose;
try {
mMidiIn.openPort(deviceIndex);
printf("Opened port to %s\n", mMidiIn.getPortName(deviceIndex).c_str());
}
catch (al::MIDIError error) {
std::cout << "ParameterMIDI Warning: Could not open MIDI port " << deviceIndex << std::endl;
}
}
void connectControl(Parameter ¶m, int controlNumber, int channel)
{
connectControl(param, controlNumber, channel, (float) param.min(), (float) param.max());
}
void connectControl(Parameter ¶m, int controlNumber, int channel,
float min, float max) {
ControlBinding newBinding;
newBinding.controlNumber = controlNumber;
newBinding.channel = channel - 1;
newBinding.param = ¶m;
newBinding.min = min;
newBinding.max = max;
mBindings.push_back(newBinding);
}
/**
* @brief connectNoteToValue
* @param param the parameter to bind
* @param channel MIDI channel (1-16)
* @param min The parameter value to map the lowest note
* @param low The MIDI note number for the lowest (or only) note to map
* @param max The value unto which the highest note is mapped
* @param high The highest MIDI note number to map
*/
void connectNoteToValue(Parameter ¶m, int channel,
float min, int low,
float max = -1, int high = -1) {
if (high == -1) {
max = min;
high = low;
}
for (int num = low; num <= high; ++num) {
NoteBinding newBinding;
newBinding.noteNumber = num;
if (num != high) {
newBinding.value = min + (max - min) * (num - low)/(high - low);
} else {
newBinding.value = max;
}
newBinding.channel = channel - 1;
newBinding.param = ¶m;
mNoteBindings.push_back(newBinding);
}
}
void connectNoteToToggle(ParameterBool ¶m, int channel, int note) {
ToggleBinding newBinding;
newBinding.noteNumber = note;
newBinding.toggle = true;
newBinding.channel = channel - 1;
newBinding.param = ¶m;
mToggleBindings.push_back(newBinding);
}
void connectNoteToIncrement(Parameter ¶m, int channel, int note,
float increment) {
IncrementBinding newBinding;
newBinding.channel = channel - 1;
newBinding.noteNumber = note;
newBinding.increment = increment;
newBinding.param = ¶m;
mIncrementBindings.push_back(newBinding);
}
virtual void onMIDIMessage(const MIDIMessage& m) override {
if (m.type() & MIDIByte::CONTROL_CHANGE ) {
for(ControlBinding binding: mBindings) {
if (m.channel() == binding.channel
&& m.controlNumber() == binding.controlNumber) {
float newValue = binding.min + (m.controlValue() * (binding.max - binding.min));
binding.param->set(newValue);
}
}
}
if (m.type() & MIDIByte::NOTE_ON && m.velocity() > 0) {
for(NoteBinding binding: mNoteBindings) {
if (m.channel() == binding.channel
&& m.noteNumber() == binding.noteNumber) {
binding.param->set(binding.value);
}
}
for(IncrementBinding binding: mIncrementBindings) {
if (m.channel() == binding.channel
&& m.noteNumber() == binding.noteNumber) {
binding.param->set(binding.param->get() + binding.increment);
}
}
for(ToggleBinding binding: mToggleBindings) {
if (m.channel() == binding.channel
&& m.noteNumber() == binding.noteNumber) {
if (binding.toggle == true) {
binding.param->set(
binding.param->get() == binding.param->max() ?
binding.param->min() : binding.param->max() );
} else {
binding.param->set(binding.param->max());
}
}
}
} else if (m.type() & MIDIByte::NOTE_OFF
|| (m.type() & MIDIByte::NOTE_ON && m.velocity() == 0)) {
for(ToggleBinding binding: mToggleBindings) {
if (m.channel() == binding.channel
&& m.noteNumber() == binding.noteNumber) {
if (binding.toggle != true) {
binding.param->set( binding.param->min() );
}
}
}
}
if (mVerbose) {
m.print();
}
}
private:
struct ControlBinding {
int controlNumber;
int channel;
Parameter *param;
float min, max;
};
struct NoteBinding {
int noteNumber;
int channel;
float value;
Parameter *param;
};
struct ToggleBinding {
int noteNumber;
int channel;
bool toggle;
ParameterBool *param;
};
struct IncrementBinding {
int noteNumber;
int channel;
float increment;
Parameter *param;
};
MIDIIn mMidiIn;
bool mVerbose;
std::vector<ControlBinding> mBindings;
std::vector<NoteBinding> mNoteBindings;
std::vector<ToggleBinding> mToggleBindings;
std::vector<IncrementBinding> mIncrementBindings;
};
}
#endif // AL_PARAMETERMIDI_H
<|endoftext|> |
<commit_before>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 "LIEF/PE/utils.hpp"
#include "LIEF/MachO/utils.hpp"
#include "LIEF/ELF/utils.hpp"
#include "LIEF/OAT.hpp"
#include "LIEF/DEX.hpp"
#include "LIEF/VDEX.hpp"
#include "LIEF/ART.hpp"
#include "pyLIEF.hpp"
void init_utils_functions(py::module& m) {
m.def("shell",
[] (void) {
auto&& InteractiveShellEmbed = py::module::import("IPython").attr("terminal").attr("embed").attr("InteractiveShellEmbed");
auto&& ipshell = InteractiveShellEmbed("banner1"_a = "Dropping into IPython", "exit_msg"_a = "Leaving Interpreter, back to program.");
return ipshell();
},
"Drop into an IPython Interpreter");
m.def("demangle", [] (const std::string& name) -> py::object {
#if defined(__unix__)
int status;
char* demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
if (status == 0) {
std::string realname = demangled_name;
free(demangled_name);
return py::str(realname);
} else {
return py::none();
}
#else
return nullptr;
#endif
});
m.def("breakp",
[] (void) {
py::object set_trace = py::module::import("pdb").attr("set_trace");
return set_trace();
},
"Trigger 'pdb.set_trace()'");
#if defined(LIEF_PE_SUPPORT)
m.def("is_pe",
static_cast<bool (*)(const std::string&)>(&LIEF::PE::is_pe),
"Check if the given file is a ``PE`` (from filename)",
"filename"_a);
m.def("is_pe",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::PE::is_pe),
"Check if the given raw data is a ``PE``",
"raw"_a);
#endif
#if defined(LIEF_ELF_SUPPORT)
m.def("is_elf",
static_cast<bool (*)(const std::string&)>(&LIEF::ELF::is_elf),
"Check if the given file is an ``ELF``",
"filename"_a);
m.def("is_elf",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ELF::is_elf),
"Check if the given raw data is an ``ELF``",
"raw"_a);
#endif
#if defined(LIEF_MACHO_SUPPORT)
m.def("is_macho",
static_cast<bool (*)(const std::string&)>(&LIEF::MachO::is_macho),
"Check if the given file is a ``MachO`` (from filename)",
"filename"_a);
m.def("is_macho",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::MachO::is_macho),
"Check if the given raw data is a ``MachO``",
"raw"_a);
#endif
#if defined(LIEF_OAT_SUPPORT)
m.def("is_oat",
static_cast<bool (*)(const std::string&)>(&LIEF::OAT::is_oat),
"Check if the given file is an ``OAT`` (from filename)",
"filename"_a);
m.def("is_oat",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::is_oat),
"Check if the given raw data is an ``OAT``",
"raw"_a);
m.def("is_oat",
static_cast<bool (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::is_oat),
"Check if the given " RST_CLASS_REF(lief.ELF.Binary) " is an ``OAT``",
"elf"_a);
m.def("oat_version",
static_cast<LIEF::OAT::oat_version_t (*)(const std::string&)>(&LIEF::OAT::version),
"Return the OAT version of the given file",
"filename"_a);
m.def("oat_version",
static_cast<LIEF::OAT::oat_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::version),
"Return the OAT version of the raw data",
"raw"_a);
m.def("oat_version",
static_cast<LIEF::OAT::oat_version_t (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::version),
"Return the OAT version of the given " RST_CLASS_REF(lief.ELF.Binary) "",
"elf"_a);
#endif
#if defined(LIEF_DEX_SUPPORT)
m.def("is_dex",
static_cast<bool (*)(const std::string&)>(&LIEF::DEX::is_dex),
"Check if the given file is a ``DEX`` (from filename)",
"filename"_a);
m.def("is_dex",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::is_dex),
"Check if the given raw data is a ``DEX``",
"raw"_a);
m.def("dex_version",
static_cast<LIEF::DEX::dex_version_t (*)(const std::string&)>(&LIEF::DEX::version),
"Return the OAT version of the given file",
"filename"_a);
m.def("dex_version",
static_cast<LIEF::DEX::dex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::version),
"Return the DEX version of the raw data",
"raw"_a);
#endif
#if defined(LIEF_VDEX_SUPPORT)
m.def("is_vdex",
static_cast<bool (*)(const std::string&)>(&LIEF::VDEX::is_vdex),
"Check if the given file is a ``VDEX`` (from filename)",
"filename"_a);
m.def("is_vdex",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::is_vdex),
"Check if the given raw data is a ``VDEX``",
"raw"_a);
m.def("vdex_version",
static_cast<LIEF::VDEX::vdex_version_t (*)(const std::string&)>(&LIEF::VDEX::version),
"Return the VDEX version of the given file",
"filename"_a);
m.def("vdex_version",
static_cast<LIEF::VDEX::vdex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::version),
"Return the VDEX version of the raw data",
"raw"_a);
#endif
#if defined(LIEF_ART_SUPPORT)
m.def("is_art",
static_cast<bool (*)(const std::string&)>(&LIEF::ART::is_art),
"Check if the given file is an ``ART`` (from filename)",
"filename"_a);
m.def("is_art",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ART::is_art),
"Check if the given raw data is an ``ART``",
"raw"_a);
m.def("art_version",
static_cast<LIEF::ART::art_version_t (*)(const std::string&)>(&LIEF::ART::version),
"Return the ART version of the given file",
"filename"_a);
m.def("art_version",
static_cast<LIEF::ART::art_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::ART::version),
"Return the ART version of the raw data",
"raw"_a);
#endif
}
<commit_msg>Fix typo<commit_after>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 "LIEF/PE/utils.hpp"
#include "LIEF/MachO/utils.hpp"
#include "LIEF/ELF/utils.hpp"
#include "LIEF/OAT.hpp"
#include "LIEF/DEX.hpp"
#include "LIEF/VDEX.hpp"
#include "LIEF/ART.hpp"
#include "pyLIEF.hpp"
void init_utils_functions(py::module& m) {
m.def("shell",
[] (void) {
auto&& InteractiveShellEmbed = py::module::import("IPython").attr("terminal").attr("embed").attr("InteractiveShellEmbed");
auto&& ipshell = InteractiveShellEmbed("banner1"_a = "Dropping into IPython", "exit_msg"_a = "Leaving Interpreter, back to program.");
return ipshell();
},
"Drop into an IPython Interpreter");
m.def("demangle", [] (const std::string& name) -> py::object {
#if defined(__unix__)
int status;
char* demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
if (status == 0) {
std::string realname = demangled_name;
free(demangled_name);
return py::str(realname);
} else {
return py::none();
}
#else
return py::none();
#endif
});
m.def("breakp",
[] (void) {
py::object set_trace = py::module::import("pdb").attr("set_trace");
return set_trace();
},
"Trigger 'pdb.set_trace()'");
#if defined(LIEF_PE_SUPPORT)
m.def("is_pe",
static_cast<bool (*)(const std::string&)>(&LIEF::PE::is_pe),
"Check if the given file is a ``PE`` (from filename)",
"filename"_a);
m.def("is_pe",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::PE::is_pe),
"Check if the given raw data is a ``PE``",
"raw"_a);
#endif
#if defined(LIEF_ELF_SUPPORT)
m.def("is_elf",
static_cast<bool (*)(const std::string&)>(&LIEF::ELF::is_elf),
"Check if the given file is an ``ELF``",
"filename"_a);
m.def("is_elf",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ELF::is_elf),
"Check if the given raw data is an ``ELF``",
"raw"_a);
#endif
#if defined(LIEF_MACHO_SUPPORT)
m.def("is_macho",
static_cast<bool (*)(const std::string&)>(&LIEF::MachO::is_macho),
"Check if the given file is a ``MachO`` (from filename)",
"filename"_a);
m.def("is_macho",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::MachO::is_macho),
"Check if the given raw data is a ``MachO``",
"raw"_a);
#endif
#if defined(LIEF_OAT_SUPPORT)
m.def("is_oat",
static_cast<bool (*)(const std::string&)>(&LIEF::OAT::is_oat),
"Check if the given file is an ``OAT`` (from filename)",
"filename"_a);
m.def("is_oat",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::is_oat),
"Check if the given raw data is an ``OAT``",
"raw"_a);
m.def("is_oat",
static_cast<bool (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::is_oat),
"Check if the given " RST_CLASS_REF(lief.ELF.Binary) " is an ``OAT``",
"elf"_a);
m.def("oat_version",
static_cast<LIEF::OAT::oat_version_t (*)(const std::string&)>(&LIEF::OAT::version),
"Return the OAT version of the given file",
"filename"_a);
m.def("oat_version",
static_cast<LIEF::OAT::oat_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::version),
"Return the OAT version of the raw data",
"raw"_a);
m.def("oat_version",
static_cast<LIEF::OAT::oat_version_t (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::version),
"Return the OAT version of the given " RST_CLASS_REF(lief.ELF.Binary) "",
"elf"_a);
#endif
#if defined(LIEF_DEX_SUPPORT)
m.def("is_dex",
static_cast<bool (*)(const std::string&)>(&LIEF::DEX::is_dex),
"Check if the given file is a ``DEX`` (from filename)",
"filename"_a);
m.def("is_dex",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::is_dex),
"Check if the given raw data is a ``DEX``",
"raw"_a);
m.def("dex_version",
static_cast<LIEF::DEX::dex_version_t (*)(const std::string&)>(&LIEF::DEX::version),
"Return the OAT version of the given file",
"filename"_a);
m.def("dex_version",
static_cast<LIEF::DEX::dex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::version),
"Return the DEX version of the raw data",
"raw"_a);
#endif
#if defined(LIEF_VDEX_SUPPORT)
m.def("is_vdex",
static_cast<bool (*)(const std::string&)>(&LIEF::VDEX::is_vdex),
"Check if the given file is a ``VDEX`` (from filename)",
"filename"_a);
m.def("is_vdex",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::is_vdex),
"Check if the given raw data is a ``VDEX``",
"raw"_a);
m.def("vdex_version",
static_cast<LIEF::VDEX::vdex_version_t (*)(const std::string&)>(&LIEF::VDEX::version),
"Return the VDEX version of the given file",
"filename"_a);
m.def("vdex_version",
static_cast<LIEF::VDEX::vdex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::version),
"Return the VDEX version of the raw data",
"raw"_a);
#endif
#if defined(LIEF_ART_SUPPORT)
m.def("is_art",
static_cast<bool (*)(const std::string&)>(&LIEF::ART::is_art),
"Check if the given file is an ``ART`` (from filename)",
"filename"_a);
m.def("is_art",
static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ART::is_art),
"Check if the given raw data is an ``ART``",
"raw"_a);
m.def("art_version",
static_cast<LIEF::ART::art_version_t (*)(const std::string&)>(&LIEF::ART::version),
"Return the ART version of the given file",
"filename"_a);
m.def("art_version",
static_cast<LIEF::ART::art_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::ART::version),
"Return the ART version of the raw data",
"raw"_a);
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 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/autofill/risk/fingerprint.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "base/port.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/testing_pref_service.h"
#include "chrome/browser/autofill/risk/proto/fingerprint.pb.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebScreenInfo.h"
#include "ui/gfx/rect.h"
namespace autofill {
namespace risk {
const int64 kGaiaId = GG_INT64_C(99194853094755497);
const char kCharset[] = "UTF-8";
const char kAcceptLanguages[] = "en-US,en";
const int kScreenColorDepth = 53;
class AutofillRiskFingerprintTest : public InProcessBrowserTest {
public:
AutofillRiskFingerprintTest()
: kWindowBounds(2, 3, 5, 7),
kContentBounds(11, 13, 17, 37),
kScreenBounds(0, 0, 101, 71),
kAvailableScreenBounds(0, 11, 101, 60),
kUnavailableScreenBounds(0, 0, 101, 11),
message_loop_(MessageLoop::TYPE_UI) {}
void GetFingerprintTestCallback(scoped_ptr<Fingerprint> fingerprint) {
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Callback called.";
// Verify that all fields Chrome can fill have been filled.
ASSERT_TRUE(fingerprint->has_machine_characteristics());
const Fingerprint_MachineCharacteristics& machine =
fingerprint->machine_characteristics();
ASSERT_TRUE(machine.has_operating_system_build());
ASSERT_TRUE(machine.has_browser_install_time_hours());
ASSERT_GT(machine.font_size(), 0);
ASSERT_GT(machine.plugin_size(), 0);
ASSERT_TRUE(machine.has_utc_offset_ms());
ASSERT_TRUE(machine.has_browser_language());
ASSERT_GT(machine.requested_language_size(), 0);
ASSERT_TRUE(machine.has_charset());
ASSERT_TRUE(machine.has_screen_count());
ASSERT_TRUE(machine.has_screen_size());
ASSERT_TRUE(machine.screen_size().has_width());
ASSERT_TRUE(machine.screen_size().has_height());
ASSERT_TRUE(machine.has_screen_color_depth());
ASSERT_TRUE(machine.has_unavailable_screen_size());
ASSERT_TRUE(machine.unavailable_screen_size().has_width());
ASSERT_TRUE(machine.unavailable_screen_size().has_height());
ASSERT_TRUE(machine.has_user_agent());
ASSERT_TRUE(machine.has_cpu());
ASSERT_TRUE(machine.cpu().has_vendor_name());
ASSERT_TRUE(machine.cpu().has_brand());
ASSERT_TRUE(machine.has_ram());
ASSERT_TRUE(machine.has_graphics_card());
ASSERT_TRUE(machine.graphics_card().has_vendor_id());
ASSERT_TRUE(machine.graphics_card().has_device_id());
ASSERT_TRUE(machine.has_browser_build());
ASSERT_TRUE(fingerprint->has_transient_state());
const Fingerprint_TransientState& transient_state =
fingerprint->transient_state();
ASSERT_TRUE(transient_state.has_inner_window_size());
ASSERT_TRUE(transient_state.has_outer_window_size());
ASSERT_TRUE(transient_state.inner_window_size().has_width());
ASSERT_TRUE(transient_state.inner_window_size().has_height());
ASSERT_TRUE(transient_state.outer_window_size().has_width());
ASSERT_TRUE(transient_state.outer_window_size().has_height());
ASSERT_TRUE(fingerprint->has_metadata());
ASSERT_TRUE(fingerprint->metadata().has_timestamp_ms());
ASSERT_TRUE(fingerprint->metadata().has_gaia_id());
ASSERT_TRUE(fingerprint->metadata().has_fingerprinter_version());
// Some values have exact known (mocked out) values:
ASSERT_EQ(2, machine.requested_language_size());
EXPECT_EQ("en-US", machine.requested_language(0));
EXPECT_EQ("en", machine.requested_language(1));
EXPECT_EQ(kCharset, machine.charset());
EXPECT_EQ(kScreenColorDepth, machine.screen_color_depth());
EXPECT_EQ(kUnavailableScreenBounds.width(),
machine.unavailable_screen_size().width());
EXPECT_EQ(kUnavailableScreenBounds.height(),
machine.unavailable_screen_size().height());
EXPECT_EQ(kContentBounds.width(),
transient_state.inner_window_size().width());
EXPECT_EQ(kContentBounds.height(),
transient_state.inner_window_size().height());
EXPECT_EQ(kWindowBounds.width(),
transient_state.outer_window_size().width());
EXPECT_EQ(kWindowBounds.height(),
transient_state.outer_window_size().height());
EXPECT_EQ(kGaiaId, fingerprint->metadata().gaia_id());
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Stopping the message loop.";
message_loop_.Quit();
}
protected:
const gfx::Rect kWindowBounds;
const gfx::Rect kContentBounds;
const gfx::Rect kScreenBounds;
const gfx::Rect kAvailableScreenBounds;
const gfx::Rect kUnavailableScreenBounds;
MessageLoop message_loop_;
};
// Test that getting a fingerprint works on some basic level.
IN_PROC_BROWSER_TEST_F(AutofillRiskFingerprintTest, GetFingerprint) {
TestingPrefServiceSimple prefs;
prefs.registry()->RegisterStringPref(prefs::kDefaultCharset, kCharset);
prefs.registry()->RegisterStringPref(prefs::kAcceptLanguages,
kAcceptLanguages);
WebKit::WebScreenInfo screen_info;
screen_info.depth = kScreenColorDepth;
screen_info.rect = WebKit::WebRect(kScreenBounds);
screen_info.availableRect = WebKit::WebRect(kAvailableScreenBounds);
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Loading fingerprint.";
internal::GetFingerprintInternal(
kGaiaId, kWindowBounds, kContentBounds, screen_info, prefs,
base::Bind(&AutofillRiskFingerprintTest::GetFingerprintTestCallback,
base::Unretained(this)));
// Wait for the callback to be called.
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Waiting for the callback to be called.";
message_loop_.Run();
}
} // namespace risk
} // namespace autofill
<commit_msg>Disable AutofillRiskFingerprintTest.GetFingerprint on Windows<commit_after>// Copyright (c) 2012 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/autofill/risk/fingerprint.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "base/port.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/testing_pref_service.h"
#include "chrome/browser/autofill/risk/proto/fingerprint.pb.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebScreenInfo.h"
#include "ui/gfx/rect.h"
namespace autofill {
namespace risk {
const int64 kGaiaId = GG_INT64_C(99194853094755497);
const char kCharset[] = "UTF-8";
const char kAcceptLanguages[] = "en-US,en";
const int kScreenColorDepth = 53;
class AutofillRiskFingerprintTest : public InProcessBrowserTest {
public:
AutofillRiskFingerprintTest()
: kWindowBounds(2, 3, 5, 7),
kContentBounds(11, 13, 17, 37),
kScreenBounds(0, 0, 101, 71),
kAvailableScreenBounds(0, 11, 101, 60),
kUnavailableScreenBounds(0, 0, 101, 11),
message_loop_(MessageLoop::TYPE_UI) {}
void GetFingerprintTestCallback(scoped_ptr<Fingerprint> fingerprint) {
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Callback called.";
// Verify that all fields Chrome can fill have been filled.
ASSERT_TRUE(fingerprint->has_machine_characteristics());
const Fingerprint_MachineCharacteristics& machine =
fingerprint->machine_characteristics();
ASSERT_TRUE(machine.has_operating_system_build());
ASSERT_TRUE(machine.has_browser_install_time_hours());
ASSERT_GT(machine.font_size(), 0);
ASSERT_GT(machine.plugin_size(), 0);
ASSERT_TRUE(machine.has_utc_offset_ms());
ASSERT_TRUE(machine.has_browser_language());
ASSERT_GT(machine.requested_language_size(), 0);
ASSERT_TRUE(machine.has_charset());
ASSERT_TRUE(machine.has_screen_count());
ASSERT_TRUE(machine.has_screen_size());
ASSERT_TRUE(machine.screen_size().has_width());
ASSERT_TRUE(machine.screen_size().has_height());
ASSERT_TRUE(machine.has_screen_color_depth());
ASSERT_TRUE(machine.has_unavailable_screen_size());
ASSERT_TRUE(machine.unavailable_screen_size().has_width());
ASSERT_TRUE(machine.unavailable_screen_size().has_height());
ASSERT_TRUE(machine.has_user_agent());
ASSERT_TRUE(machine.has_cpu());
ASSERT_TRUE(machine.cpu().has_vendor_name());
ASSERT_TRUE(machine.cpu().has_brand());
ASSERT_TRUE(machine.has_ram());
ASSERT_TRUE(machine.has_graphics_card());
ASSERT_TRUE(machine.graphics_card().has_vendor_id());
ASSERT_TRUE(machine.graphics_card().has_device_id());
ASSERT_TRUE(machine.has_browser_build());
ASSERT_TRUE(fingerprint->has_transient_state());
const Fingerprint_TransientState& transient_state =
fingerprint->transient_state();
ASSERT_TRUE(transient_state.has_inner_window_size());
ASSERT_TRUE(transient_state.has_outer_window_size());
ASSERT_TRUE(transient_state.inner_window_size().has_width());
ASSERT_TRUE(transient_state.inner_window_size().has_height());
ASSERT_TRUE(transient_state.outer_window_size().has_width());
ASSERT_TRUE(transient_state.outer_window_size().has_height());
ASSERT_TRUE(fingerprint->has_metadata());
ASSERT_TRUE(fingerprint->metadata().has_timestamp_ms());
ASSERT_TRUE(fingerprint->metadata().has_gaia_id());
ASSERT_TRUE(fingerprint->metadata().has_fingerprinter_version());
// Some values have exact known (mocked out) values:
ASSERT_EQ(2, machine.requested_language_size());
EXPECT_EQ("en-US", machine.requested_language(0));
EXPECT_EQ("en", machine.requested_language(1));
EXPECT_EQ(kCharset, machine.charset());
EXPECT_EQ(kScreenColorDepth, machine.screen_color_depth());
EXPECT_EQ(kUnavailableScreenBounds.width(),
machine.unavailable_screen_size().width());
EXPECT_EQ(kUnavailableScreenBounds.height(),
machine.unavailable_screen_size().height());
EXPECT_EQ(kContentBounds.width(),
transient_state.inner_window_size().width());
EXPECT_EQ(kContentBounds.height(),
transient_state.inner_window_size().height());
EXPECT_EQ(kWindowBounds.width(),
transient_state.outer_window_size().width());
EXPECT_EQ(kWindowBounds.height(),
transient_state.outer_window_size().height());
EXPECT_EQ(kGaiaId, fingerprint->metadata().gaia_id());
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Stopping the message loop.";
message_loop_.Quit();
}
protected:
const gfx::Rect kWindowBounds;
const gfx::Rect kContentBounds;
const gfx::Rect kScreenBounds;
const gfx::Rect kAvailableScreenBounds;
const gfx::Rect kUnavailableScreenBounds;
MessageLoop message_loop_;
};
// This test is flaky on Windows. See http://crbug.com/178356.
#if defined(OS_WIN)
#define MAYBE_GetFingerprint DISABLE_GetFingerprint
#else
#define MAYBE_GetFingerprint GetFingerprint
#endif
// Test that getting a fingerprint works on some basic level.
IN_PROC_BROWSER_TEST_F(AutofillRiskFingerprintTest, MAYBE_GetFingerprint) {
TestingPrefServiceSimple prefs;
prefs.registry()->RegisterStringPref(prefs::kDefaultCharset, kCharset);
prefs.registry()->RegisterStringPref(prefs::kAcceptLanguages,
kAcceptLanguages);
WebKit::WebScreenInfo screen_info;
screen_info.depth = kScreenColorDepth;
screen_info.rect = WebKit::WebRect(kScreenBounds);
screen_info.availableRect = WebKit::WebRect(kAvailableScreenBounds);
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Loading fingerprint.";
internal::GetFingerprintInternal(
kGaiaId, kWindowBounds, kContentBounds, screen_info, prefs,
base::Bind(&AutofillRiskFingerprintTest::GetFingerprintTestCallback,
base::Unretained(this)));
// Wait for the callback to be called.
// TODO(isherman): Investigating http://crbug.com/174296
LOG(WARNING) << "Waiting for the callback to be called.";
message_loop_.Run();
}
} // namespace risk
} // namespace autofill
<|endoftext|> |
<commit_before>#ifndef CK_CONFIG_AMD_HPP
#define CK_CONFIG_AMD_HPP
#include "hip/hip_runtime.h"
#include "hip/hip_fp16.h"
#include "bfloat16_dev.hpp"
// index type: unsigned or signed
#define CK_UNSIGNED_INDEX_TYPE 0
// device backend
#define CK_DEVICE_BACKEND_AMD 1
// AMD inline asm
#ifndef CK_USE_AMD_INLINE_ASM
#define CK_USE_AMD_INLINE_ASM 0
#endif
#ifndef CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM
#define CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM 0
#endif
// AMD buffer addressing
#ifndef CK_USE_AMD_BUFFER_ADDRESSING
#define CK_USE_AMD_BUFFER_ADDRESSING 1
#endif
#ifndef CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC
#define CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC 1
#endif
// AMD XDLOPS
#ifndef CK_USE_AMD_XDLOPS
#define CK_USE_AMD_XDLOPS 1
#endif
#ifndef CK_USE_AMD_XDLOPS_INLINE_ASM
#define CK_USE_AMD_XDLOPS_INLINE_ASM 1
#endif
// experimental implementation
#define CK_EXPERIMENTAL_BLOCKWISE_GEMM_USE_PIPELINE 1
#define CK_EXPERIMENTAL_TENSOR_COORDINATE_USE_CALCULATE_OFFSET_DIFF 0
#define CK_EXPERIMENTAL_THREADWISE_COPY_V4R2_USE_OPTIMIZED_ADDRESS_CACLULATION 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_BLOCKWISE_GENERIC_SLICE_COPY_V1 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V1R2 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V2R1 0
// workaround
#define CK_WORKAROUND_SWDEV_202749 1
namespace ck {
enum AddressSpace
{
generic,
global
};
#if CK_UNSIGNED_INDEX_TYPE
using index_t = uint32_t;
#else
using index_t = int32_t;
#endif
// int32x4_t use by buffer_load and buffer_store llvm intrinsic
typedef int32_t int32x4_t __attribute__((ext_vector_type(4)));
} // namespace ck
#endif
<commit_msg>Avoid xdlops header files on non-xdlops GPUs (#2161)<commit_after>#ifndef CK_CONFIG_AMD_HPP
#define CK_CONFIG_AMD_HPP
#include "hip/hip_runtime.h"
#include "hip/hip_fp16.h"
#include "bfloat16_dev.hpp"
// index type: unsigned or signed
#define CK_UNSIGNED_INDEX_TYPE 0
// device backend
#define CK_DEVICE_BACKEND_AMD 1
// AMD inline asm
#ifndef CK_USE_AMD_INLINE_ASM
#define CK_USE_AMD_INLINE_ASM 1
#endif
#ifndef CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM
#define CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM 1
#endif
// AMD buffer addressing
#ifndef CK_USE_AMD_BUFFER_ADDRESSING
#define CK_USE_AMD_BUFFER_ADDRESSING 1
#endif
#ifndef CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC
#define CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC 1
#endif
// AMD XDLOPS
#ifndef CK_USE_AMD_XDLOPS
#define CK_USE_AMD_XDLOPS 0
#endif
#ifndef CK_USE_AMD_XDLOPS_INLINE_ASM
#define CK_USE_AMD_XDLOPS_INLINE_ASM 0
#endif
// experimental implementation
#define CK_EXPERIMENTAL_BLOCKWISE_GEMM_USE_PIPELINE 1
#define CK_EXPERIMENTAL_TENSOR_COORDINATE_USE_CALCULATE_OFFSET_DIFF 0
#define CK_EXPERIMENTAL_THREADWISE_COPY_V4R2_USE_OPTIMIZED_ADDRESS_CACLULATION 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_BLOCKWISE_GENERIC_SLICE_COPY_V1 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V1R2 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V2R1 0
// workaround
#define CK_WORKAROUND_SWDEV_202749 1
namespace ck {
enum AddressSpace
{
generic,
global
};
#if CK_UNSIGNED_INDEX_TYPE
using index_t = uint32_t;
#else
using index_t = int32_t;
#endif
// int32x4_t use by buffer_load and buffer_store llvm intrinsic
typedef int32_t int32x4_t __attribute__((ext_vector_type(4)));
} // namespace ck
#endif
<|endoftext|> |
<commit_before>#include "AntGoalTestApp.hpp"
#include "../sim/worldobject/AntHome.hpp"
#include "../sim/nav/Node.hpp"
#include "../sim/agent/testagent/AntGoalTester.hpp"
#include "../sim/agent/testagent/AntEatAntTest.hpp"
#include "../sim/agent/testagent/AntExploreAntTest.hpp"
#include "../sim/agent/testagent/AntFindFoodAntTest.hpp"
#include "../sim/agent/testagent/AntForageAntTest.hpp"
#include "../sim/agent/testagent/AntGoHomeAntTest.hpp"
#include "../sim/agent/testagent/AntMoveToNodeAntTest.hpp"
#include "../sim/agent/testagent/AntFollowPathAntTest.hpp"
#include "../util/make_unique.hpp"
#include "../sim/knowledge/GenericPercept.hpp"
#include <iostream>
#include <vector>
// Christopher D. Canfield
// November 2013
// AntGoalTestApp.cpp
using namespace std;
using namespace cdc;
void createNavGraph1(vector<Node>& navGraph);
std::vector<unique_ptr<AntGoalTester>> getTestAnts(GuiEventManager& manager, AntHome& home, NavGraphHelper& navGraphHelper,
Node& startNode, Node& nearTarget, Node& farTarget);
AntGoalTestApp::AntGoalTestApp() :
viewManager(eventManager, 1000, 1000, 800, 800, 200, 800),
ticks(0)
{
}
AntGoalTestApp::~AntGoalTestApp()
{
}
void AntGoalTestApp::setup()
{
createNavGraph1(navGraph);
foodPile = new AntFoodPile(100, navGraph[11]);
navGraphHelper = NavGraphHelper(navGraph);
antHome = new AntHome(navGraph[10], navGraph, world);
goalTestAnts = getTestAnts(eventManager, *antHome, navGraphHelper, navGraph[0], navGraph[1], navGraph.back());
window = std::unique_ptr<sf::RenderWindow>(new sf::RenderWindow(sf::VideoMode(800, 800), "GUI Tests"));
window->setFramerateLimit(60);
viewManager.setWindow(*window);
viewManager.getSimView().setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f));
}
bool AntGoalTestApp::run()
{
if (ant != nullptr && ant->isGoalFinished() && goalTestAnts.empty())
{
return false;
}
if (ant == nullptr || ant->isGoalFinished())
{
ant = move(goalTestAnts.back());
goalTestAnts.pop_back();
cout << "----------------------------------------" << endl;
cout << "Running ant test: " << (typeid(*ant.get()).name()) << endl;
cout << "----------------------------------------" << endl;
}
sf::Event event;
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window->close();
return false;
}
else
{
eventManager.update(event, *window);
}
}
GenericPercept percept;
ant->update(ticks, percept);
++ticks;
window->clear(sf::Color::Green);
for (auto& node : navGraph)
{
window->draw(node);
}
window->draw(*ant);
window->draw(*foodPile);
window->display();
return true;
}
void AntGoalTestApp::teardown()
{
}
std::vector<unique_ptr<AntGoalTester>> getTestAnts(GuiEventManager& manager, AntHome& home, NavGraphHelper& navGraphHelper,
Node& startNode, Node& nearTarget, Node& farTarget)
{
cout << "Ant goal tester type: " << endl;
cout << " 1: AntEat" << endl;
cout << " 2: AntExplore" << endl;
cout << " 3: AntFindFood" << endl;
cout << " 4: AntForage" << endl;
cout << " 5: AntGoHome" << endl;
cout << " 6: AntMoveToNode" << endl;
cout << " 7: AntFollowPath" << endl;
cout << " 8: Run all tests" << endl;
cout << "Type: ";
int goalType;
cin >> goalType;
std::vector<unique_ptr<AntGoalTester>> goals;
switch (goalType)
{
case 1:
goals.push_back(make_unique<AntEatAntTest>(manager, home, navGraphHelper, startNode));
break;
case 2:
goals.push_back(make_unique<AntExploreAntTest>(manager, home, navGraphHelper, startNode));
break;
case 3:
goals.push_back(make_unique<AntFindFoodAntTest>(manager, home, navGraphHelper, startNode));
break;
case 4:
goals.push_back(make_unique<AntForageAntTest>(manager, home, navGraphHelper, startNode));
break;
case 5:
goals.push_back(make_unique<AntGoHomeAntTest>(manager, home, navGraphHelper, startNode));
break;
case 6:
goals.push_back(make_unique<AntMoveToNodeAntTest>(manager, home, navGraphHelper, startNode, nearTarget));
break;
case 7:
goals.push_back(make_unique<AntFollowPathAntTest>(manager, home, navGraphHelper, startNode, farTarget));
break;
case 8:
goals.push_back(make_unique<AntEatAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntExploreAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntFindFoodAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntForageAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntGoHomeAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntMoveToNodeAntTest>(manager, home, navGraphHelper, startNode, nearTarget));
goals.push_back(make_unique<AntFollowPathAntTest>(manager, home, navGraphHelper, startNode, farTarget));
break;
default:
throw runtime_error("Invalid goal selection");
}
return goals;
}
void createNavGraph1(vector<Node>& navGraph)
{
navGraph.reserve(12);
navGraph.push_back(Node(GridLocation(0, 0), 50, 50)); // 0
navGraph.push_back(Node(GridLocation(0, 1), 150, 50)); // 1
navGraph.push_back(Node(GridLocation(0, 2), 250, 50)); // 2
navGraph.push_back(Node(GridLocation(0, 3), 350, 50)); // 3
navGraph.push_back(Node(GridLocation(1, 0), 50, 150)); // 4
navGraph.push_back(Node(GridLocation(1, 1), 150, 150)); // 5
navGraph.push_back(Node(GridLocation(1, 2), 250, 150)); // 6
navGraph.push_back(Node(GridLocation(1, 3), 350, 150)); // 7
navGraph.push_back(Node(GridLocation(2, 0), 50, 250)); // 8
navGraph.push_back(Node(GridLocation(2, 1), 150, 250)); // 9
navGraph.push_back(Node(GridLocation(2, 2), 250, 250)); // 10
navGraph.push_back(Node(GridLocation(2, 3), 350, 250)); // 11
auto edge_00_01 = make_shared<Edge>(navGraph[0], navGraph[1], 1);
auto edge_00_10 = make_shared<Edge>(navGraph[0], navGraph[4], 1);
navGraph[0].addEdge(edge_00_01).addEdge(edge_00_10);
auto edge_01_02 = make_shared<Edge>(navGraph[1], navGraph[2], 1);
auto edge_01_11 = make_shared<Edge>(navGraph[1], navGraph[5], 1);
navGraph[1].addEdge(edge_01_02).addEdge(edge_01_11);
auto edge_02_03 = make_shared<Edge>(navGraph[2], navGraph[3], 1);
auto edge_02_12 = make_shared<Edge>(navGraph[2], navGraph[6], 1);
navGraph[2].addEdge(edge_02_03).addEdge(edge_02_12);
auto edge_03_13 = make_shared<Edge>(navGraph[3], navGraph[7], 1);
navGraph[3].addEdge(edge_03_13);
auto edge_10_11 = make_shared<Edge>(navGraph[4], navGraph[5], 1);
auto edge_10_20 = make_shared<Edge>(navGraph[4], navGraph[8], 1);
navGraph[4].addEdge(edge_10_11).addEdge(edge_10_20);
auto edge_11_12 = make_shared<Edge>(navGraph[5], navGraph[6], 1);
auto edge_11_21 = make_shared<Edge>(navGraph[5], navGraph[9], 1);
navGraph[5].addEdge(edge_11_12).addEdge(edge_11_21);
auto edge_12_13 = make_shared<Edge>(navGraph[6], navGraph[7], 1);
auto edge_12_22 = make_shared<Edge>(navGraph[6], navGraph[10], 1);
navGraph[6].addEdge(edge_12_13).addEdge(edge_12_22);
auto edge_13_23 = make_shared<Edge>(navGraph[7], navGraph[11], 1);
navGraph[7].addEdge(edge_13_23);
auto edge_20_21 = make_shared<Edge>(navGraph[8], navGraph[9], 1);
navGraph[8].addEdge(edge_20_21);
auto edge_21_22 = make_shared<Edge>(navGraph[9], navGraph[10], 1);
navGraph[9].addEdge(edge_21_22);
auto edge_22_23 = make_shared<Edge>(navGraph[10], navGraph[11], 1);
navGraph[10].addEdge(edge_22_23);
}<commit_msg>Updated AntGoalTestApp<commit_after>#include "AntGoalTestApp.hpp"
#include "../sim/worldobject/AntHome.hpp"
#include "../sim/nav/Node.hpp"
#include "../sim/agent/testagent/AntGoalTester.hpp"
#include "../sim/agent/testagent/AntEatAntTest.hpp"
#include "../sim/agent/testagent/AntExploreAntTest.hpp"
#include "../sim/agent/testagent/AntFindFoodAntTest.hpp"
#include "../sim/agent/testagent/AntForageAntTest.hpp"
#include "../sim/agent/testagent/AntGoHomeAntTest.hpp"
#include "../sim/agent/testagent/AntMoveToNodeAntTest.hpp"
#include "../sim/agent/testagent/AntFollowPathAntTest.hpp"
#include "../util/make_unique.hpp"
#include "../sim/knowledge/GenericPercept.hpp"
#include <iostream>
#include <vector>
// Christopher D. Canfield
// November 2013
// AntGoalTestApp.cpp
using namespace std;
using namespace cdc;
void createNavGraph1(vector<Node>& navGraph);
std::vector<unique_ptr<AntGoalTester>> getTestAnts(GuiEventManager& manager, AntHome& home, NavGraphHelper& navGraphHelper,
Node& startNode, Node& nearTarget, Node& farTarget);
AntGoalTestApp::AntGoalTestApp() :
viewManager(eventManager, 1000, 1000, 800, 800, 200, 800),
ticks(0)
{
}
AntGoalTestApp::~AntGoalTestApp()
{
}
void AntGoalTestApp::setup()
{
createNavGraph1(navGraph);
foodPile = new AntFoodPile(100, navGraph[11]);
navGraphHelper = NavGraphHelper(navGraph);
antHome = new AntHome(navGraph[10], navGraph, world);
goalTestAnts = getTestAnts(eventManager, *antHome, navGraphHelper, navGraph[0], navGraph[1], navGraph.back());
window = std::unique_ptr<sf::RenderWindow>(new sf::RenderWindow(sf::VideoMode(800, 800), "GUI Tests"));
window->setFramerateLimit(60);
viewManager.setWindow(*window);
viewManager.getSimView().setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f));
}
bool AntGoalTestApp::run()
{
if (ant != nullptr && ant->isGoalFinished() && goalTestAnts.empty())
{
return false;
}
if (ant == nullptr || ant->isGoalFinished())
{
ant = move(goalTestAnts.back());
goalTestAnts.pop_back();
cout << "----------------------------------------" << endl;
cout << "Running ant test: " << (typeid(*ant.get()).name()) << endl;
cout << "----------------------------------------" << endl;
}
sf::Event event;
while (window->pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window->close();
return false;
}
else
{
eventManager.update(event, *window);
}
}
GenericPercept percept;
ant->update(ticks, percept);
++ticks;
window->clear(sf::Color::Green);
for (auto& node : navGraph)
{
window->draw(node);
}
for (auto& node : navGraph)
{
for (auto& edge : node.getEdgeList())
{
edge->drawPheromone(*window, sf::RenderStates::Default);
}
}
window->draw(*ant);
window->draw(*foodPile);
window->display();
return true;
}
void AntGoalTestApp::teardown()
{
}
std::vector<unique_ptr<AntGoalTester>> getTestAnts(GuiEventManager& manager, AntHome& home, NavGraphHelper& navGraphHelper,
Node& startNode, Node& nearTarget, Node& farTarget)
{
cout << "Ant goal tester type: " << endl;
cout << " 1: AntEat" << endl;
cout << " 2: AntExplore" << endl;
cout << " 3: AntFindFood" << endl;
cout << " 4: AntForage" << endl;
cout << " 5: AntGoHome" << endl;
cout << " 6: AntMoveToNode" << endl;
cout << " 7: AntFollowPath" << endl;
cout << " 8: Run all tests" << endl;
cout << "Type: ";
int goalType;
cin >> goalType;
std::vector<unique_ptr<AntGoalTester>> goals;
switch (goalType)
{
case 1:
goals.push_back(make_unique<AntEatAntTest>(manager, home, navGraphHelper, startNode));
break;
case 2:
goals.push_back(make_unique<AntExploreAntTest>(manager, home, navGraphHelper, startNode));
break;
case 3:
goals.push_back(make_unique<AntFindFoodAntTest>(manager, home, navGraphHelper, startNode));
break;
case 4:
goals.push_back(make_unique<AntForageAntTest>(manager, home, navGraphHelper, startNode));
break;
case 5:
goals.push_back(make_unique<AntGoHomeAntTest>(manager, home, navGraphHelper, startNode));
break;
case 6:
goals.push_back(make_unique<AntMoveToNodeAntTest>(manager, home, navGraphHelper, startNode, nearTarget));
break;
case 7:
goals.push_back(make_unique<AntFollowPathAntTest>(manager, home, navGraphHelper, startNode, farTarget));
break;
case 8:
goals.push_back(make_unique<AntEatAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntExploreAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntFindFoodAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntForageAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntGoHomeAntTest>(manager, home, navGraphHelper, startNode));
goals.push_back(make_unique<AntMoveToNodeAntTest>(manager, home, navGraphHelper, startNode, nearTarget));
goals.push_back(make_unique<AntFollowPathAntTest>(manager, home, navGraphHelper, startNode, farTarget));
break;
default:
throw runtime_error("Invalid goal selection");
}
return goals;
}
void createNavGraph1(vector<Node>& navGraph)
{
navGraph.reserve(12);
navGraph.push_back(Node(GridLocation(0, 0), 50, 50)); // 0
navGraph.push_back(Node(GridLocation(0, 1), 150, 50)); // 1
navGraph.push_back(Node(GridLocation(0, 2), 250, 50)); // 2
navGraph.push_back(Node(GridLocation(0, 3), 350, 50)); // 3
navGraph.push_back(Node(GridLocation(1, 0), 50, 150)); // 4
navGraph.push_back(Node(GridLocation(1, 1), 150, 150)); // 5
navGraph.push_back(Node(GridLocation(1, 2), 250, 150)); // 6
navGraph.push_back(Node(GridLocation(1, 3), 350, 150)); // 7
navGraph.push_back(Node(GridLocation(2, 0), 50, 250)); // 8
navGraph.push_back(Node(GridLocation(2, 1), 150, 250)); // 9
navGraph.push_back(Node(GridLocation(2, 2), 250, 250)); // 10
navGraph.push_back(Node(GridLocation(2, 3), 350, 250)); // 11
auto edge_00_01 = make_shared<Edge>(navGraph[0], navGraph[1], 1);
auto edge_00_10 = make_shared<Edge>(navGraph[0], navGraph[4], 1);
navGraph[0].addEdge(edge_00_01).addEdge(edge_00_10);
auto edge_01_02 = make_shared<Edge>(navGraph[1], navGraph[2], 1);
auto edge_01_11 = make_shared<Edge>(navGraph[1], navGraph[5], 1);
navGraph[1].addEdge(edge_01_02).addEdge(edge_01_11);
auto edge_02_03 = make_shared<Edge>(navGraph[2], navGraph[3], 1);
auto edge_02_12 = make_shared<Edge>(navGraph[2], navGraph[6], 1);
navGraph[2].addEdge(edge_02_03).addEdge(edge_02_12);
auto edge_03_13 = make_shared<Edge>(navGraph[3], navGraph[7], 1);
navGraph[3].addEdge(edge_03_13);
auto edge_10_11 = make_shared<Edge>(navGraph[4], navGraph[5], 1);
auto edge_10_20 = make_shared<Edge>(navGraph[4], navGraph[8], 1);
navGraph[4].addEdge(edge_10_11).addEdge(edge_10_20);
auto edge_11_12 = make_shared<Edge>(navGraph[5], navGraph[6], 1);
auto edge_11_21 = make_shared<Edge>(navGraph[5], navGraph[9], 1);
navGraph[5].addEdge(edge_11_12).addEdge(edge_11_21);
auto edge_12_13 = make_shared<Edge>(navGraph[6], navGraph[7], 1);
auto edge_12_22 = make_shared<Edge>(navGraph[6], navGraph[10], 1);
navGraph[6].addEdge(edge_12_13).addEdge(edge_12_22);
auto edge_13_23 = make_shared<Edge>(navGraph[7], navGraph[11], 1);
navGraph[7].addEdge(edge_13_23);
auto edge_20_21 = make_shared<Edge>(navGraph[8], navGraph[9], 1);
navGraph[8].addEdge(edge_20_21);
auto edge_21_22 = make_shared<Edge>(navGraph[9], navGraph[10], 1);
navGraph[9].addEdge(edge_21_22);
auto edge_22_23 = make_shared<Edge>(navGraph[10], navGraph[11], 1);
navGraph[10].addEdge(edge_22_23);
}<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "AbstractTransportFactory.h"
#include <memory>
#include <string>
#include <activemq/wireformat/WireFormat.h>
#include <activemq/wireformat/WireFormatRegistry.h>
#include <activemq/util/URISupport.h>
#include <activemq/transport/correlator/ResponseCorrelator.h>
#include <activemq/transport/logging/LoggingTransport.h>
using namespace std;
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::transport::correlator;
using namespace activemq::transport::logging;
using namespace activemq::wireformat;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::net;
using namespace decaf::util;
////////////////////////////////////////////////////////////////////////////////
Pointer<Transport> AbstractTransportFactory::create( const decaf::net::URI& location )
throw ( exceptions::ActiveMQException ) {
try{
Properties properties =
activemq::util::URISupport::parseQuery( location.getQuery() );
Pointer<WireFormat> wireFormat = this->createWireFormat( properties );
// Create the initial Transport, then wrap it in the normal Filters
Pointer<Transport> transport( doCreateComposite( location, wireFormat, properties ) );
// Create the Transport for response correlator
transport.reset( new ResponseCorrelator( transport ) );
// If command tracing was enabled, wrap the transport with a logging transport.
if( properties.getProperty( "transport.commandTracingEnabled", "false" ) == "true" ) {
// Create the Transport for response correlator
transport.reset( new LoggingTransport( transport ) );
}
// If there is a negotiator need then we create and wrap here.
if( wireFormat->hasNegotiator() ) {
transport = wireFormat->createNegotiator( transport );
}
return transport;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
Pointer<Transport> AbstractTransportFactory::createComposite( const decaf::net::URI& location )
throw ( exceptions::ActiveMQException ) {
try{
Properties properties =
activemq::util::URISupport::parseQuery( location.getQuery() );
Pointer<WireFormat> wireFormat = this->createWireFormat( properties );
// Create the initial Transport, then wrap it in the normal Filters
Pointer<Transport> transport( doCreateComposite( location, wireFormat, properties ) );
return transport;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
Pointer<WireFormat> AbstractTransportFactory::createWireFormat(
const decaf::util::Properties& properties )
throw( decaf::lang::exceptions::NoSuchElementException ) {
try{
std::string wireFormat = properties.getProperty( "wireFormat", "openwire" );
WireFormatFactory* factory =
WireFormatRegistry::getInstance().findFactory( wireFormat );
return Pointer<WireFormat>( factory->createWireFormat( properties ) );
}
AMQ_CATCH_RETHROW( NoSuchElementException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, NoSuchElementException )
AMQ_CATCHALL_THROW( NoSuchElementException )
}
<commit_msg>small cleanup<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "AbstractTransportFactory.h"
#include <memory>
#include <string>
#include <activemq/wireformat/WireFormat.h>
#include <activemq/wireformat/WireFormatRegistry.h>
#include <activemq/util/URISupport.h>
#include <activemq/transport/correlator/ResponseCorrelator.h>
#include <activemq/transport/logging/LoggingTransport.h>
using namespace std;
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::transport::correlator;
using namespace activemq::transport::logging;
using namespace activemq::wireformat;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::net;
using namespace decaf::util;
////////////////////////////////////////////////////////////////////////////////
Pointer<Transport> AbstractTransportFactory::create( const decaf::net::URI& location )
throw ( exceptions::ActiveMQException ) {
try{
Properties properties =
activemq::util::URISupport::parseQuery( location.getQuery() );
Pointer<WireFormat> wireFormat = this->createWireFormat( properties );
// Create the initial Transport, then wrap it in the normal Filters
Pointer<Transport> transport( doCreateComposite( location, wireFormat, properties ) );
// Create the Transport for response correlator
transport.reset( new ResponseCorrelator( transport ) );
// If command tracing was enabled, wrap the transport with a logging transport.
if( properties.getProperty( "transport.commandTracingEnabled", "false" ) == "true" ) {
// Create the Transport for response correlator
transport.reset( new LoggingTransport( transport ) );
}
// If there is a negotiator need then we create and wrap here.
if( wireFormat->hasNegotiator() ) {
transport = wireFormat->createNegotiator( transport );
}
return transport;
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
Pointer<Transport> AbstractTransportFactory::createComposite( const decaf::net::URI& location )
throw ( exceptions::ActiveMQException ) {
try{
Properties properties =
activemq::util::URISupport::parseQuery( location.getQuery() );
Pointer<WireFormat> wireFormat = this->createWireFormat( properties );
// Create the initial Transport, then wrap it in the normal Filters
return doCreateComposite( location, wireFormat, properties );
}
AMQ_CATCH_RETHROW( ActiveMQException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, ActiveMQException )
AMQ_CATCHALL_THROW( ActiveMQException )
}
////////////////////////////////////////////////////////////////////////////////
Pointer<WireFormat> AbstractTransportFactory::createWireFormat(
const decaf::util::Properties& properties )
throw( decaf::lang::exceptions::NoSuchElementException ) {
try{
std::string wireFormat = properties.getProperty( "wireFormat", "openwire" );
WireFormatFactory* factory =
WireFormatRegistry::getInstance().findFactory( wireFormat );
return factory->createWireFormat( properties );
}
AMQ_CATCH_RETHROW( NoSuchElementException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, NoSuchElementException )
AMQ_CATCHALL_THROW( NoSuchElementException )
}
<|endoftext|> |
<commit_before>#include "chromecast.hpp"
#include "cast_channel.pb.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <syslog.h>
ChromeCast::ChromeCast(const std::string& ip)
: m_ip(ip)
{
if (!connect())
throw std::runtime_error("could not connect");
}
ChromeCast::~ChromeCast()
{
disconnect();
}
void ChromeCast::setMediaStatusCallback(std::function<void(const std::string&,
const std::string&, const std::string&)> func)
{
m_mediaStatusCallback = func;
}
unsigned int ChromeCast::_request_id()
{
unsigned int request_id;
m_mutex.lock();
request_id = m_request_id++;
m_mutex.unlock();
return request_id;
}
bool ChromeCast::connect()
{
m_s = socket(PF_INET, SOCK_STREAM, 0);
if (m_s == -1)
return false;
struct sockaddr_in inaddr;
memset(&inaddr, 0, sizeof inaddr);
inaddr.sin_family = AF_INET;
inaddr.sin_port = htons(8009);
inaddr.sin_addr.s_addr = inet_addr(m_ip.c_str());
if (::connect(m_s, (const struct sockaddr *)&inaddr,
sizeof inaddr) != 0) {
close(m_s);
return false;
}
SSL_CTX* x = SSL_CTX_new(TLSv1_client_method());
m_ssls = SSL_new(x);
SSL_set_fd(m_ssls, m_s);
SSL_set_mode(m_ssls, SSL_get_mode(m_ssls) | SSL_MODE_AUTO_RETRY);
SSL_set_connect_state(m_ssls);
if (SSL_connect(m_ssls) != 1) {
SSL_free(m_ssls);
m_ssls = NULL;
close(m_s);
return false;
}
m_tread = std::thread(&ChromeCast::_read, this);
m_init = false;
return true;
}
bool ChromeCast::init()
{
static std::mutex m_init_mutex;
std::lock_guard<std::mutex> lock(m_init_mutex);
if (m_init)
return true;
if (!m_ssls)
if (!connect())
return false;
m_destination_id = "receiver-0";
m_session_id = "";
Json::Value response;
{
Json::Value msg;
msg["type"] = "CONNECT";
msg["origin"] = Json::Value(Json::objectValue);
send("urn:x-cast:com.google.cast.tp.connection", msg);
}
{
Json::Value msg;
msg["type"] = "GET_STATUS";
msg["requestId"] = _request_id();
response = send("urn:x-cast:com.google.cast.receiver", msg);
bool isRunning = false;
if (response.isMember("status") &&
response["status"].isMember("applications") &&
response["status"]["applications"].isValidIndex(0u)) {
Json::Value& application = response["status"]["applications"][0u];
if (application["appId"].asString() == "CC1AD845")
isRunning = true;
}
if (!isRunning)
{
Json::Value msg;
msg["type"] = "LAUNCH";
msg["requestId"] = _request_id();
msg["appId"] = "CC1AD845";
response = send("urn:x-cast:com.google.cast.receiver", msg);
}
}
if (response.isMember("status") &&
response["status"].isMember("applications") &&
response["status"]["applications"].isValidIndex(0u))
{
Json::Value& application = response["status"]["applications"][0u];
m_destination_id = application["transportId"].asString();
m_session_id = application["sessionId"].asString();
}
{
Json::Value msg;
msg["type"] = "CONNECT";
msg["origin"] = Json::Value(Json::objectValue);
send("urn:x-cast:com.google.cast.tp.connection", msg);
}
m_init = true;
return true;
}
void ChromeCast::disconnect()
{
m_tread.join();
if (m_s != -1)
close(m_s);
if (m_ssls)
SSL_free(m_ssls);
m_s = -1;
m_ssls = NULL;
m_init = false;
}
Json::Value ChromeCast::send(const std::string& namespace_, const Json::Value& payload)
{
Json::FastWriter fw;
fw.omitEndingLineFeed();
extensions::core_api::cast_channel::CastMessage msg;
msg.set_payload_type(msg.STRING);
msg.set_protocol_version(msg.CASTV2_1_0);
msg.set_namespace_(namespace_);
msg.set_source_id(m_source_id);
msg.set_destination_id(m_destination_id);
msg.set_payload_utf8(fw.write(payload));
std::string data, foo;
char pktlen[4];
unsigned int len = htonl(msg.ByteSize());
memcpy(&pktlen, &len, sizeof len);
foo.append(pktlen, sizeof pktlen);
msg.SerializeToString(&data);
foo += data;
std::condition_variable f;
bool wait = false;
unsigned int requestId;
if (payload.isMember("requestId"))
{
requestId = payload["requestId"].asUInt();
m_mutex.lock();
m_wait[requestId] = std::make_pair(&f, std::string());
wait = true;
m_mutex.unlock();
}
syslog(LOG_DEBUG, "%s -> %s (%s): %s",
msg.source_id().c_str(),
msg.destination_id().c_str(),
msg.namespace_().c_str(),
msg.payload_utf8().c_str()
);
int w;
m_ssl_mutex.lock();
if (m_ssls) {
w = SSL_write(m_ssls, foo.c_str(), foo.size());
if (w == -1) {
syslog(LOG_DEBUG, "SSL_write eror");
disconnect();
}
} else
w = -1;
m_ssl_mutex.unlock();
if (wait && w == -1)
{
m_mutex.lock();
m_wait.erase(requestId);
m_mutex.unlock();
wait = false;
}
Json::Value ret;
if (wait) {
std::unique_lock<std::mutex> wl(m_mutex);
f.wait(wl);
ret = m_wait[requestId].second;
m_wait.erase(requestId);
m_mutex.unlock();
}
return ret;
}
void ChromeCast::_read()
{
while (true)
{
char pktlen[4];
int r;
for (r = 0; r < sizeof pktlen; ++r)
if (SSL_read(m_ssls, pktlen + r, 1) < 1)
break;
if (r != sizeof pktlen) {
syslog(LOG_ERR, "SSL_read error");
m_mutex.lock();
for (auto& item : m_wait) {
item.second.second = Json::Value();
item.second.first->notify_all();
}
m_mutex.unlock();
return;
}
unsigned int len;
memcpy(&len, pktlen, sizeof len);
len = ntohl(len);
std::string buf;
while (buf.size() < len) {
char b[2048];
int r = SSL_read(m_ssls, b, sizeof b);
if (r < 1)
break;
buf.append(b, r);
}
if (buf.size() != len) {
syslog(LOG_ERR, "SSL_read error");
m_mutex.lock();
for (auto& item : m_wait) {
item.second.second = Json::Value();
item.second.first->notify_all();
}
m_mutex.unlock();
return;
}
extensions::core_api::cast_channel::CastMessage msg;
msg.ParseFromString(buf);
syslog(LOG_DEBUG, "%s -> %s (%s): %s",
msg.source_id().c_str(),
msg.destination_id().c_str(),
msg.namespace_().c_str(),
msg.payload_utf8().c_str()
);
Json::Value response;
Json::Reader reader;
if (!reader.parse(msg.payload_utf8(), response, false))
continue;
if (msg.namespace_() == "urn:x-cast:com.google.cast.tp.heartbeat")
{
Json::FastWriter fw;
fw.omitEndingLineFeed();
extensions::core_api::cast_channel::CastMessage reply(msg);
Json::Value msg;
msg["type"] = "PONG";
reply.set_payload_utf8(fw.write(msg));
std::string data;
reply.SerializeToString(&data);
unsigned int len = htonl(data.size());
SSL_write(m_ssls, &len, sizeof len);
SSL_write(m_ssls, data.c_str(), data.size());
continue;
}
if (msg.namespace_() == "urn:x-cast:com.google.cast.tp.connection")
{
if (response["type"].asString() == "CLOSE")
{
m_mutex.lock();
m_init = false;
for (auto& item : m_wait) {
item.second.second = Json::Value();
item.second.first->notify_all();
}
m_mutex.unlock();
}
}
if (msg.namespace_() == "urn:x-cast:com.google.cast.media")
{
if (response["type"].asString() == "MEDIA_STATUS")
{
if (response.isMember("status") &&
response["status"].isValidIndex(0u))
{
Json::Value& status = response["status"][0u];
m_media_session_id = status["mediaSessionId"].asUInt();
}
}
}
if (response.isMember("requestId"))
{
m_mutex.lock();
auto waitIter = m_wait.find(response["requestId"].asUInt());
if (waitIter != m_wait.end())
{
waitIter->second.second = response;
waitIter->second.first->notify_all();
}
m_mutex.unlock();
}
if (msg.namespace_() == "urn:x-cast:com.google.cast.media")
{
if (response["type"].asString() == "MEDIA_STATUS")
{
if (response.isMember("status") &&
response["status"].isValidIndex(0u))
{
std::string uuid = m_uuid;
Json::Value& status = response["status"][0u];
m_player_state = status["playerState"].asString();
if (status["playerState"] == "IDLE")
m_uuid = "";
if (status["playerState"] == "BUFFERING")
uuid = m_uuid = status["media"]["customData"]["uuid"].asString();
if (m_mediaStatusCallback)
m_mediaStatusCallback(status["playerState"].asString(),
status["idleReason"].asString(),
uuid);
}
}
}
}
}
const std::string& ChromeCast::getUUID() const
{
return m_uuid;
}
const std::string& ChromeCast::getPlayerState() const
{
return m_player_state;
}
std::string ChromeCast::getSocketName() const
{
struct sockaddr_in addr;
socklen_t len = sizeof(struct sockaddr);
getsockname(m_s, (struct sockaddr*)&addr, &len);
return inet_ntoa(addr.sin_addr);
}
bool isPlayerState(const Json::Value& response, const std::string& playerState)
{
if (response.isMember("type") && response["type"].asString() == "MEDIA_STATUS")
{
if (response.isMember("status") &&
response["status"].isValidIndex(0u))
{
const Json::Value& status = response["status"][0u];
if (status.isMember("playerState") && status["playerState"].asString() == playerState)
return true;
}
}
return false;
}
bool ChromeCast::load(const std::string& url, const std::string& title, const std::string& uuid)
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "LOAD";
msg["requestId"] = _request_id();
msg["sessionId"] = m_session_id;
msg["media"]["contentId"] = url;
msg["media"]["streamType"] = "buffered";
msg["media"]["contentType"] = "video/x-matroska";
msg["media"]["customData"]["uuid"] = uuid;
msg["media"]["metadata"]["title"] = title;
msg["autoplay"] = true;
msg["currentTime"] = 0;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "BUFFERING") || isPlayerState(response, "PLAYING");
}
bool ChromeCast::pause()
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "PAUSE";
msg["requestId"] = _request_id();
msg["mediaSessionId"] = m_media_session_id;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "PAUSED");
}
bool ChromeCast::play()
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "PLAY";
msg["requestId"] = _request_id();
msg["mediaSessionId"] = m_media_session_id;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "BUFFERING") || isPlayerState(response, "PLAYING");
}
bool ChromeCast::stop()
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "STOP";
msg["requestId"] = _request_id();
msg["mediaSessionId"] = m_media_session_id;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "IDLE");
}
<commit_msg>spelling<commit_after>#include "chromecast.hpp"
#include "cast_channel.pb.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <syslog.h>
ChromeCast::ChromeCast(const std::string& ip)
: m_ip(ip)
{
if (!connect())
throw std::runtime_error("could not connect");
}
ChromeCast::~ChromeCast()
{
disconnect();
}
void ChromeCast::setMediaStatusCallback(std::function<void(const std::string&,
const std::string&, const std::string&)> func)
{
m_mediaStatusCallback = func;
}
unsigned int ChromeCast::_request_id()
{
unsigned int request_id;
m_mutex.lock();
request_id = m_request_id++;
m_mutex.unlock();
return request_id;
}
bool ChromeCast::connect()
{
m_s = socket(PF_INET, SOCK_STREAM, 0);
if (m_s == -1)
return false;
struct sockaddr_in inaddr;
memset(&inaddr, 0, sizeof inaddr);
inaddr.sin_family = AF_INET;
inaddr.sin_port = htons(8009);
inaddr.sin_addr.s_addr = inet_addr(m_ip.c_str());
if (::connect(m_s, (const struct sockaddr *)&inaddr,
sizeof inaddr) != 0) {
close(m_s);
return false;
}
SSL_CTX* x = SSL_CTX_new(TLSv1_client_method());
m_ssls = SSL_new(x);
SSL_set_fd(m_ssls, m_s);
SSL_set_mode(m_ssls, SSL_get_mode(m_ssls) | SSL_MODE_AUTO_RETRY);
SSL_set_connect_state(m_ssls);
if (SSL_connect(m_ssls) != 1) {
SSL_free(m_ssls);
m_ssls = NULL;
close(m_s);
return false;
}
m_tread = std::thread(&ChromeCast::_read, this);
m_init = false;
return true;
}
bool ChromeCast::init()
{
static std::mutex m_init_mutex;
std::lock_guard<std::mutex> lock(m_init_mutex);
if (m_init)
return true;
if (!m_ssls)
if (!connect())
return false;
m_destination_id = "receiver-0";
m_session_id = "";
Json::Value response;
{
Json::Value msg;
msg["type"] = "CONNECT";
msg["origin"] = Json::Value(Json::objectValue);
send("urn:x-cast:com.google.cast.tp.connection", msg);
if (!m_ssls) return false;
}
{
Json::Value msg;
msg["type"] = "GET_STATUS";
msg["requestId"] = _request_id();
response = send("urn:x-cast:com.google.cast.receiver", msg);
bool isRunning = false;
if (response.isMember("status") &&
response["status"].isMember("applications") &&
response["status"]["applications"].isValidIndex(0u)) {
Json::Value& application = response["status"]["applications"][0u];
if (application["appId"].asString() == "CC1AD845")
isRunning = true;
}
if (!isRunning)
{
Json::Value msg;
msg["type"] = "LAUNCH";
msg["requestId"] = _request_id();
msg["appId"] = "CC1AD845";
response = send("urn:x-cast:com.google.cast.receiver", msg);
}
}
if (response.isMember("status") &&
response["status"].isMember("applications") &&
response["status"]["applications"].isValidIndex(0u))
{
Json::Value& application = response["status"]["applications"][0u];
m_destination_id = application["transportId"].asString();
m_session_id = application["sessionId"].asString();
}
{
Json::Value msg;
msg["type"] = "CONNECT";
msg["origin"] = Json::Value(Json::objectValue);
send("urn:x-cast:com.google.cast.tp.connection", msg);
}
m_init = true;
return true;
}
void ChromeCast::disconnect()
{
m_tread.join();
if (m_s != -1)
close(m_s);
if (m_ssls)
SSL_free(m_ssls);
m_s = -1;
m_ssls = NULL;
m_init = false;
}
Json::Value ChromeCast::send(const std::string& namespace_, const Json::Value& payload)
{
Json::FastWriter fw;
fw.omitEndingLineFeed();
extensions::core_api::cast_channel::CastMessage msg;
msg.set_payload_type(msg.STRING);
msg.set_protocol_version(msg.CASTV2_1_0);
msg.set_namespace_(namespace_);
msg.set_source_id(m_source_id);
msg.set_destination_id(m_destination_id);
msg.set_payload_utf8(fw.write(payload));
std::string data, foo;
char pktlen[4];
unsigned int len = htonl(msg.ByteSize());
memcpy(&pktlen, &len, sizeof len);
foo.append(pktlen, sizeof pktlen);
msg.SerializeToString(&data);
foo += data;
std::condition_variable f;
bool wait = false;
unsigned int requestId;
if (payload.isMember("requestId"))
{
requestId = payload["requestId"].asUInt();
m_mutex.lock();
m_wait[requestId] = std::make_pair(&f, std::string());
wait = true;
m_mutex.unlock();
}
syslog(LOG_DEBUG, "%s -> %s (%s): %s",
msg.source_id().c_str(),
msg.destination_id().c_str(),
msg.namespace_().c_str(),
msg.payload_utf8().c_str()
);
int w;
m_ssl_mutex.lock();
if (m_ssls) {
w = SSL_write(m_ssls, foo.c_str(), foo.size());
if (w == -1) {
syslog(LOG_DEBUG, "SSL_write reror");
disconnect();
}
} else
w = -1;
m_ssl_mutex.unlock();
if (wait && w == -1)
{
m_mutex.lock();
m_wait.erase(requestId);
m_mutex.unlock();
wait = false;
}
Json::Value ret;
if (wait) {
std::unique_lock<std::mutex> wl(m_mutex);
f.wait(wl);
ret = m_wait[requestId].second;
m_wait.erase(requestId);
m_mutex.unlock();
}
return ret;
}
void ChromeCast::_read()
{
while (true)
{
char pktlen[4];
int r;
for (r = 0; r < sizeof pktlen; ++r)
if (SSL_read(m_ssls, pktlen + r, 1) < 1)
break;
if (r != sizeof pktlen) {
syslog(LOG_ERR, "SSL_read error");
m_mutex.lock();
for (auto& item : m_wait) {
item.second.second = Json::Value();
item.second.first->notify_all();
}
m_mutex.unlock();
return;
}
unsigned int len;
memcpy(&len, pktlen, sizeof len);
len = ntohl(len);
std::string buf;
while (buf.size() < len) {
char b[2048];
int r = SSL_read(m_ssls, b, sizeof b);
if (r < 1)
break;
buf.append(b, r);
}
if (buf.size() != len) {
syslog(LOG_ERR, "SSL_read error");
m_mutex.lock();
for (auto& item : m_wait) {
item.second.second = Json::Value();
item.second.first->notify_all();
}
m_mutex.unlock();
return;
}
extensions::core_api::cast_channel::CastMessage msg;
msg.ParseFromString(buf);
syslog(LOG_DEBUG, "%s -> %s (%s): %s",
msg.source_id().c_str(),
msg.destination_id().c_str(),
msg.namespace_().c_str(),
msg.payload_utf8().c_str()
);
Json::Value response;
Json::Reader reader;
if (!reader.parse(msg.payload_utf8(), response, false))
continue;
if (msg.namespace_() == "urn:x-cast:com.google.cast.tp.heartbeat")
{
Json::FastWriter fw;
fw.omitEndingLineFeed();
extensions::core_api::cast_channel::CastMessage reply(msg);
Json::Value msg;
msg["type"] = "PONG";
reply.set_payload_utf8(fw.write(msg));
std::string data;
reply.SerializeToString(&data);
unsigned int len = htonl(data.size());
SSL_write(m_ssls, &len, sizeof len);
SSL_write(m_ssls, data.c_str(), data.size());
continue;
}
if (msg.namespace_() == "urn:x-cast:com.google.cast.tp.connection")
{
if (response["type"].asString() == "CLOSE")
{
m_mutex.lock();
m_init = false;
for (auto& item : m_wait) {
item.second.second = Json::Value();
item.second.first->notify_all();
}
m_mutex.unlock();
}
}
if (msg.namespace_() == "urn:x-cast:com.google.cast.media")
{
if (response["type"].asString() == "MEDIA_STATUS")
{
if (response.isMember("status") &&
response["status"].isValidIndex(0u))
{
Json::Value& status = response["status"][0u];
m_media_session_id = status["mediaSessionId"].asUInt();
}
}
}
if (response.isMember("requestId"))
{
m_mutex.lock();
auto waitIter = m_wait.find(response["requestId"].asUInt());
if (waitIter != m_wait.end())
{
waitIter->second.second = response;
waitIter->second.first->notify_all();
}
m_mutex.unlock();
}
if (msg.namespace_() == "urn:x-cast:com.google.cast.media")
{
if (response["type"].asString() == "MEDIA_STATUS")
{
if (response.isMember("status") &&
response["status"].isValidIndex(0u))
{
std::string uuid = m_uuid;
Json::Value& status = response["status"][0u];
m_player_state = status["playerState"].asString();
if (status["playerState"] == "IDLE")
m_uuid = "";
if (status["playerState"] == "BUFFERING")
uuid = m_uuid = status["media"]["customData"]["uuid"].asString();
if (m_mediaStatusCallback)
m_mediaStatusCallback(status["playerState"].asString(),
status["idleReason"].asString(),
uuid);
}
}
}
}
}
const std::string& ChromeCast::getUUID() const
{
return m_uuid;
}
const std::string& ChromeCast::getPlayerState() const
{
return m_player_state;
}
std::string ChromeCast::getSocketName() const
{
struct sockaddr_in addr;
socklen_t len = sizeof(struct sockaddr);
getsockname(m_s, (struct sockaddr*)&addr, &len);
return inet_ntoa(addr.sin_addr);
}
bool isPlayerState(const Json::Value& response, const std::string& playerState)
{
if (response.isMember("type") && response["type"].asString() == "MEDIA_STATUS")
{
if (response.isMember("status") &&
response["status"].isValidIndex(0u))
{
const Json::Value& status = response["status"][0u];
if (status.isMember("playerState") && status["playerState"].asString() == playerState)
return true;
}
}
return false;
}
bool ChromeCast::load(const std::string& url, const std::string& title, const std::string& uuid)
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "LOAD";
msg["requestId"] = _request_id();
msg["sessionId"] = m_session_id;
msg["media"]["contentId"] = url;
msg["media"]["streamType"] = "buffered";
msg["media"]["contentType"] = "video/x-matroska";
msg["media"]["customData"]["uuid"] = uuid;
msg["media"]["metadata"]["title"] = title;
msg["autoplay"] = true;
msg["currentTime"] = 0;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "BUFFERING") || isPlayerState(response, "PLAYING");
}
bool ChromeCast::pause()
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "PAUSE";
msg["requestId"] = _request_id();
msg["mediaSessionId"] = m_media_session_id;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "PAUSED");
}
bool ChromeCast::play()
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "PLAY";
msg["requestId"] = _request_id();
msg["mediaSessionId"] = m_media_session_id;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "BUFFERING") || isPlayerState(response, "PLAYING");
}
bool ChromeCast::stop()
{
if (!m_init && !init())
return false;
Json::Value msg, response;
msg["type"] = "STOP";
msg["requestId"] = _request_id();
msg["mediaSessionId"] = m_media_session_id;
response = send("urn:x-cast:com.google.cast.media", msg);
return isPlayerState(response, "IDLE");
}
<|endoftext|> |
<commit_before>/*
* IPAddress6.cpp
*
* Copyright (C) 2006 - 2008 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
* Copyright (C) 2008 by Christoph Mller. Alle Rechte vorbehalten.
*/
#include "vislib/IPAddress6.h"
#include <cstdlib>
#include "vislib/assert.h"
#include "vislib/DNS.h"
#include "vislib/IllegalStateException.h"
#include "vislib/OutOfRangeException.h"
#include "vislib/SocketException.h"
#include "vislib/Trace.h"
/*
* vislib::net::IPAddress6::Create
*/
vislib::net::IPAddress6 vislib::net::IPAddress6::Create(
const char *hostNameOrAddress) {
IPAddress6 retval;
DNS::GetHostAddress(retval, hostNameOrAddress);
return retval;
}
/*
* vislib::net::IPAddress6::Create
*/
vislib::net::IPAddress6 vislib::net::IPAddress6::Create(
const wchar_t *hostNameOrAddress) {
IPAddress6 retval;
DNS::GetHostAddress(retval, hostNameOrAddress);
return retval;
}
/*
* vislib::net::IPAddress6::ALL_NODES_ON_LINK
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ALL_NODES_ON_LINK(
#ifdef _WIN32
::in6addr_allnodesonlink);
#else /* _WIN32 */
"ff02::1");
#endif /* _WIN32 */
/*
* vislib::net::IPAddress6::ALL_ROUTERS_ON_LINK
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ALL_ROUTERS_ON_LINK(
#ifdef _WIN32
::in6addr_allroutersonlink);
#else /* _WIN32 */
"ff02::2");
#endif /* _WIN32 */
/*
* vislib::net::IPAddress6::ALL_NODES_ON_NODE
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ALL_NODES_ON_NODE(
#ifdef _WIN32
::in6addr_allnodesonnode);
#else /* _WIN32 */
"ff01::1");
#endif /* _WIN32 */
/*
* vislib::net::IPAddress6::ANY
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ANY(::in6addr_any);
/*
* vislib::net::IPAddress6::LOCALHOST
*/
const vislib::net::IPAddress6& vislib::net::IPAddress6::LOCALHOST
= vislib::net::IPAddress6::LOOPBACK;
/*
* vislib::net::IPAddress6::LOOPBACK
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::LOOPBACK(
::in6addr_loopback);
/*
* vislib::net::IPAddress6::UNSPECIFIED
*/
const vislib::net::IPAddress6& vislib::net::IPAddress6::UNSPECIFIED
= vislib::net::IPAddress6::ANY;
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(void) {
*this = ::in6addr_loopback;
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const struct in6_addr& address) {
*this = address;
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(
const BYTE b1, const BYTE b2, const BYTE b3, const BYTE b4,
const BYTE b5, const BYTE b6, const BYTE b7, const BYTE b8,
const BYTE b9, const BYTE b10, const BYTE b11, const BYTE b12,
const BYTE b13, const BYTE b14, const BYTE b15, const BYTE b16) {
#define VLIPADDR5_INITBYTE(n) this->address.s6_addr[n - 1] = b##n
VLIPADDR5_INITBYTE(1);
VLIPADDR5_INITBYTE(2);
VLIPADDR5_INITBYTE(3);
VLIPADDR5_INITBYTE(4);
VLIPADDR5_INITBYTE(5);
VLIPADDR5_INITBYTE(6);
VLIPADDR5_INITBYTE(7);
VLIPADDR5_INITBYTE(8);
VLIPADDR5_INITBYTE(9);
VLIPADDR5_INITBYTE(10);
VLIPADDR5_INITBYTE(11);
VLIPADDR5_INITBYTE(12);
VLIPADDR5_INITBYTE(13);
VLIPADDR5_INITBYTE(14);
VLIPADDR5_INITBYTE(15);
VLIPADDR5_INITBYTE(16);
#undef VLIPADDR5_INITBYTE
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const IPAddress& address) {
this->MapV4Address(address);
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const struct in_addr& address) {
this->MapV4Address(address);
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const IPAddress6& rhs) {
*this = rhs;
}
/*
* vislib::net::IPAddress6::~IPAddress6
*/
vislib::net::IPAddress6::~IPAddress6(void) {
}
/*
* vislib::net::IPAddress6::GetPrefix
*/
vislib::net::IPAddress6
vislib::net::IPAddress6::GetPrefix(const ULONG prefixLength) const {
IPAddress6 retval;
int cntBytes = sizeof(retval.address.s6_addr);
int cntPrefix = prefixLength > static_cast<ULONG>(8 * cntBytes)
? cntBytes : static_cast<int>(prefixLength);
div_t cntCopy = ::div(cntPrefix, 8);
/* Zero out everything. */
::ZeroMemory(retval.address.s6_addr, cntBytes);
/* Copy complete bytes. */
::memcpy(retval.address.s6_addr, this->address.s6_addr, cntCopy.quot);
/* Copy fraction of incomplete byte if necessary. */
if (cntCopy.rem > 0) {
retval.address.s6_addr[cntCopy.quot]
= this->address.s6_addr[cntCopy.quot] << (8 - cntCopy.rem);
}
return retval;
}
/*
* vislib::net::IPAddress6::MapV4Address
*/
void vislib::net::IPAddress6::MapV4Address(const struct in_addr& address) {
/* Zero out first 80 bits. */
for (int i = 0; i < 10; i++) {
this->address.s6_addr[i] = 0;
}
/* Bits 80 to 95 must be all 1. */
for (int i = 10; i < 12; i++) {
this->address.s6_addr[i] = 0xff;
}
/* Embed IPv4 in the last 32 bits. */
ASSERT(sizeof(in_addr) == 4);
::memcpy(this->address.s6_addr + 12, &address, sizeof(in_addr));
ASSERT(this->IsV4Mapped());
}
/*
* vislib::net::IPAddress6::ToStringA
*/
vislib::StringA vislib::net::IPAddress6::ToStringA(void) const {
struct sockaddr_in6 addr; // Dummy socket address used for lookup.
char buffer[NI_MAXHOST]; // Receives the stringised address.
int err = 0; // OS operation return value.
::ZeroMemory(&addr, sizeof(addr));
addr.sin6_family = AF_INET6;
::memcpy(&addr.sin6_addr, &this->address, sizeof(struct in6_addr));
if ((err = ::getnameinfo(reinterpret_cast<struct sockaddr *>(&addr),
sizeof(struct sockaddr_in6), buffer, sizeof(buffer), NULL, 0,
NI_NUMERICHOST)) != 0) {
VLTRACE(Trace::LEVEL_VL_ERROR, "::getnameinfo failed in "
"IPAddress6::ToStringA(): %s\n",
#ifdef _WIN32
::gai_strerrorA(err)
#else /* _WIN32 */
::gai_strerror(err)
#endif /* _WIN32 */
);
buffer[0] = 0;
}
return StringA(buffer);
}
/*
* vislib::net::IPAddress6::UnmapV4Address
*/
vislib::net::IPAddress vislib::net::IPAddress6::UnmapV4Address(void) const {
if (this->IsV4Mapped()) {
return IPAddress(*reinterpret_cast<const in_addr *>(
this->address.s6_addr + 12));
} else {
throw IllegalStateException("The IPv6 address is not a mapped IPv4 "
"address.", __FILE__, __LINE__);
}
}
/*
* vislib::net::IPAddress6::operator []
*/
BYTE vislib::net::IPAddress6::operator [](const int i) const {
if ((i > 0) && (i < static_cast<int>(sizeof(this->address)))) {
return reinterpret_cast<const BYTE *>(&this->address)[i];
} else {
throw OutOfRangeException(i, 0, sizeof(this->address), __FILE__,
__LINE__);
}
}
/*
* vislib::net::IPAddress6::operator =
*/
vislib::net::IPAddress6& vislib::net::IPAddress6::operator =(
const struct in6_addr& rhs) {
if (&this->address != &rhs) {
::memcpy(&this->address, &rhs, sizeof(struct in6_addr));
}
return *this;
}
/*
* vislib::net::IPAddress6::operator =
*/
vislib::net::IPAddress6& vislib::net::IPAddress6::operator =(
const IPAddress& rhs) {
this->MapV4Address(rhs);
return *this;
}
/*
* vislib::net::IPAddress6::operator ==
*/
bool vislib::net::IPAddress6::operator ==(const struct in6_addr& rhs) const {
#ifndef _WIN32
#define IN6_ADDR_EQUAL IN6_ARE_ADDR_EQUAL
#endif /* !_WIN32 */
return (IN6_ADDR_EQUAL(&this->address, &rhs) != 0);
}
/*
* vislib::net::IPAddress6::IPAddress
*/
vislib::net::IPAddress6::operator vislib::net::IPAddress(void) const {
if (this->IsV4Compatible()) {
return IPAddress(*reinterpret_cast<const in_addr *>(
this->address.s6_addr + 12));
} else {
return this->UnmapV4Address();
}
}
<commit_msg>Linux hotfix<commit_after>/*
* IPAddress6.cpp
*
* Copyright (C) 2006 - 2008 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
* Copyright (C) 2008 by Christoph Mller. Alle Rechte vorbehalten.
*/
#include "vislib/IPAddress6.h"
#include <cstdlib>
#include "vislib/assert.h"
#include "vislib/DNS.h"
#include "vislib/IllegalStateException.h"
#include "vislib/OutOfRangeException.h"
#include "vislib/SocketException.h"
#include "vislib/Trace.h"
/*
* vislib::net::IPAddress6::Create
*/
vislib::net::IPAddress6 vislib::net::IPAddress6::Create(
const char *hostNameOrAddress) {
IPAddress6 retval;
DNS::GetHostAddress(retval, hostNameOrAddress);
return retval;
}
/*
* vislib::net::IPAddress6::Create
*/
vislib::net::IPAddress6 vislib::net::IPAddress6::Create(
const wchar_t *hostNameOrAddress) {
IPAddress6 retval;
DNS::GetHostAddress(retval, hostNameOrAddress);
return retval;
}
/*
* vislib::net::IPAddress6::ALL_NODES_ON_LINK
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ALL_NODES_ON_LINK
#ifdef _WIN32
(::in6addr_allnodesonlink);
#else /* _WIN32 */
= vislib::net::IPAddress6::Create("ff02::1");
#endif /* _WIN32 */
/*
* vislib::net::IPAddress6::ALL_ROUTERS_ON_LINK
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ALL_ROUTERS_ON_LINK
#ifdef _WIN32
(::in6addr_allroutersonlink);
#else /* _WIN32 */
= vislib::net::IPAddress6::Create("ff02::2");
#endif /* _WIN32 */
/*
* vislib::net::IPAddress6::ALL_NODES_ON_NODE
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ALL_NODES_ON_NODE
#ifdef _WIN32
(::in6addr_allnodesonnode);
#else /* _WIN32 */
= vislib::net::IPAddress6::Create("ff01::1");
#endif /* _WIN32 */
/*
* vislib::net::IPAddress6::ANY
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::ANY(::in6addr_any);
/*
* vislib::net::IPAddress6::LOCALHOST
*/
const vislib::net::IPAddress6& vislib::net::IPAddress6::LOCALHOST
= vislib::net::IPAddress6::LOOPBACK;
/*
* vislib::net::IPAddress6::LOOPBACK
*/
const vislib::net::IPAddress6 vislib::net::IPAddress6::LOOPBACK(
::in6addr_loopback);
/*
* vislib::net::IPAddress6::UNSPECIFIED
*/
const vislib::net::IPAddress6& vislib::net::IPAddress6::UNSPECIFIED
= vislib::net::IPAddress6::ANY;
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(void) {
*this = ::in6addr_loopback;
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const struct in6_addr& address) {
*this = address;
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(
const BYTE b1, const BYTE b2, const BYTE b3, const BYTE b4,
const BYTE b5, const BYTE b6, const BYTE b7, const BYTE b8,
const BYTE b9, const BYTE b10, const BYTE b11, const BYTE b12,
const BYTE b13, const BYTE b14, const BYTE b15, const BYTE b16) {
#define VLIPADDR5_INITBYTE(n) this->address.s6_addr[n - 1] = b##n
VLIPADDR5_INITBYTE(1);
VLIPADDR5_INITBYTE(2);
VLIPADDR5_INITBYTE(3);
VLIPADDR5_INITBYTE(4);
VLIPADDR5_INITBYTE(5);
VLIPADDR5_INITBYTE(6);
VLIPADDR5_INITBYTE(7);
VLIPADDR5_INITBYTE(8);
VLIPADDR5_INITBYTE(9);
VLIPADDR5_INITBYTE(10);
VLIPADDR5_INITBYTE(11);
VLIPADDR5_INITBYTE(12);
VLIPADDR5_INITBYTE(13);
VLIPADDR5_INITBYTE(14);
VLIPADDR5_INITBYTE(15);
VLIPADDR5_INITBYTE(16);
#undef VLIPADDR5_INITBYTE
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const IPAddress& address) {
this->MapV4Address(address);
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const struct in_addr& address) {
this->MapV4Address(address);
}
/*
* vislib::net::IPAddress6::IPAddress6
*/
vislib::net::IPAddress6::IPAddress6(const IPAddress6& rhs) {
*this = rhs;
}
/*
* vislib::net::IPAddress6::~IPAddress6
*/
vislib::net::IPAddress6::~IPAddress6(void) {
}
/*
* vislib::net::IPAddress6::GetPrefix
*/
vislib::net::IPAddress6
vislib::net::IPAddress6::GetPrefix(const ULONG prefixLength) const {
IPAddress6 retval;
int cntBytes = sizeof(retval.address.s6_addr);
int cntPrefix = prefixLength > static_cast<ULONG>(8 * cntBytes)
? cntBytes : static_cast<int>(prefixLength);
div_t cntCopy = ::div(cntPrefix, 8);
/* Zero out everything. */
::ZeroMemory(retval.address.s6_addr, cntBytes);
/* Copy complete bytes. */
::memcpy(retval.address.s6_addr, this->address.s6_addr, cntCopy.quot);
/* Copy fraction of incomplete byte if necessary. */
if (cntCopy.rem > 0) {
retval.address.s6_addr[cntCopy.quot]
= this->address.s6_addr[cntCopy.quot] << (8 - cntCopy.rem);
}
return retval;
}
/*
* vislib::net::IPAddress6::MapV4Address
*/
void vislib::net::IPAddress6::MapV4Address(const struct in_addr& address) {
/* Zero out first 80 bits. */
for (int i = 0; i < 10; i++) {
this->address.s6_addr[i] = 0;
}
/* Bits 80 to 95 must be all 1. */
for (int i = 10; i < 12; i++) {
this->address.s6_addr[i] = 0xff;
}
/* Embed IPv4 in the last 32 bits. */
ASSERT(sizeof(in_addr) == 4);
::memcpy(this->address.s6_addr + 12, &address, sizeof(in_addr));
ASSERT(this->IsV4Mapped());
}
/*
* vislib::net::IPAddress6::ToStringA
*/
vislib::StringA vislib::net::IPAddress6::ToStringA(void) const {
struct sockaddr_in6 addr; // Dummy socket address used for lookup.
char buffer[NI_MAXHOST]; // Receives the stringised address.
int err = 0; // OS operation return value.
::ZeroMemory(&addr, sizeof(addr));
addr.sin6_family = AF_INET6;
::memcpy(&addr.sin6_addr, &this->address, sizeof(struct in6_addr));
if ((err = ::getnameinfo(reinterpret_cast<struct sockaddr *>(&addr),
sizeof(struct sockaddr_in6), buffer, sizeof(buffer), NULL, 0,
NI_NUMERICHOST)) != 0) {
VLTRACE(Trace::LEVEL_VL_ERROR, "::getnameinfo failed in "
"IPAddress6::ToStringA(): %s\n",
#ifdef _WIN32
::gai_strerrorA(err)
#else /* _WIN32 */
::gai_strerror(err)
#endif /* _WIN32 */
);
buffer[0] = 0;
}
return StringA(buffer);
}
/*
* vislib::net::IPAddress6::UnmapV4Address
*/
vislib::net::IPAddress vislib::net::IPAddress6::UnmapV4Address(void) const {
if (this->IsV4Mapped()) {
return IPAddress(*reinterpret_cast<const in_addr *>(
this->address.s6_addr + 12));
} else {
throw IllegalStateException("The IPv6 address is not a mapped IPv4 "
"address.", __FILE__, __LINE__);
}
}
/*
* vislib::net::IPAddress6::operator []
*/
BYTE vislib::net::IPAddress6::operator [](const int i) const {
if ((i > 0) && (i < static_cast<int>(sizeof(this->address)))) {
return reinterpret_cast<const BYTE *>(&this->address)[i];
} else {
throw OutOfRangeException(i, 0, sizeof(this->address), __FILE__,
__LINE__);
}
}
/*
* vislib::net::IPAddress6::operator =
*/
vislib::net::IPAddress6& vislib::net::IPAddress6::operator =(
const struct in6_addr& rhs) {
if (&this->address != &rhs) {
::memcpy(&this->address, &rhs, sizeof(struct in6_addr));
}
return *this;
}
/*
* vislib::net::IPAddress6::operator =
*/
vislib::net::IPAddress6& vislib::net::IPAddress6::operator =(
const IPAddress& rhs) {
this->MapV4Address(rhs);
return *this;
}
/*
* vislib::net::IPAddress6::operator ==
*/
bool vislib::net::IPAddress6::operator ==(const struct in6_addr& rhs) const {
#ifndef _WIN32
#define IN6_ADDR_EQUAL IN6_ARE_ADDR_EQUAL
#endif /* !_WIN32 */
return (IN6_ADDR_EQUAL(&this->address, &rhs) != 0);
}
/*
* vislib::net::IPAddress6::IPAddress
*/
vislib::net::IPAddress6::operator vislib::net::IPAddress(void) const {
if (this->IsV4Compatible()) {
return IPAddress(*reinterpret_cast<const in_addr *>(
this->address.s6_addr + 12));
} else {
return this->UnmapV4Address();
}
}
<|endoftext|> |
<commit_before>/*! @file cell.cpp
@brief Implementation of Cell class
*/
#include "cell.hpp"
#include <wtl/iostr.hpp>
#include <wtl/random.hpp>
#include <type_traits>
namespace tumopp {
static_assert(std::is_nothrow_copy_constructible<Cell>{}, "");
static_assert(std::is_nothrow_move_constructible<Cell>{}, "");
Cell::param_type Cell::PARAM_;
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace {
class GammaFactory {
public:
GammaFactory(double k) noexcept: shape_(k) {}
std::gamma_distribution<double> operator()(double mu) {
const double theta = std::max(mu / shape_, 0.0);
return std::gamma_distribution<double>(shape_, theta);
}
void param(double k) {shape_ = k;}
private:
double shape_;
};
template <class URBG>
inline bool bernoulli(double p, URBG& engine) {
// consume less URBG when p is set to 0 or 1.
return p >= 1.0 || (p > 0.0 && wtl::generate_canonical(engine) < p);
}
class bernoulli_distribution {
public:
bernoulli_distribution(double p) noexcept: p_(p) {}
template <class URBG>
bool operator()(URBG& engine) const {
return p_ >= 1.0 || (p_ > 0.0 && wtl::generate_canonical(engine) < p_);
}
void param(double p) {p_ = p;}
private:
double p_;
};
GammaFactory GAMMA_FACTORY(Cell::param().GAMMA_SHAPE);
bernoulli_distribution BERN_SYMMETRIC(Cell::param().PROB_SYMMETRIC_DIVISION);
bernoulli_distribution BERN_MUT_BIRTH(Cell::param().RATE_BIRTH);
bernoulli_distribution BERN_MUT_DEATH(Cell::param().RATE_DEATH);
bernoulli_distribution BERN_MUT_ALPHA(Cell::param().RATE_ALPHA);
bernoulli_distribution BERN_MUT_MIGRA(Cell::param().RATE_MIGRA);
std::normal_distribution<double> GAUSS_BIRTH(Cell::param().MEAN_BIRTH, Cell::param().SD_BIRTH);
std::normal_distribution<double> GAUSS_DEATH(Cell::param().MEAN_DEATH, Cell::param().SD_DEATH);
std::normal_distribution<double> GAUSS_ALPHA(Cell::param().MEAN_ALPHA, Cell::param().SD_ALPHA);
std::normal_distribution<double> GAUSS_MIGRA(Cell::param().MEAN_MIGRA, Cell::param().SD_MIGRA);
}// namespace
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
void Cell::param(const param_type& p) {
PARAM_ = p;
GAMMA_FACTORY.param(PARAM_.GAMMA_SHAPE);
BERN_SYMMETRIC.param(PARAM_.PROB_SYMMETRIC_DIVISION);
BERN_MUT_BIRTH.param(PARAM_.RATE_BIRTH);
BERN_MUT_DEATH.param(PARAM_.RATE_DEATH);
BERN_MUT_ALPHA.param(PARAM_.RATE_ALPHA);
BERN_MUT_MIGRA.param(PARAM_.RATE_MIGRA);
GAUSS_BIRTH.param(decltype(GAUSS_BIRTH)::param_type(PARAM_.MEAN_BIRTH, PARAM_.SD_BIRTH));
GAUSS_DEATH.param(decltype(GAUSS_DEATH)::param_type(PARAM_.MEAN_DEATH, PARAM_.SD_DEATH));
GAUSS_ALPHA.param(decltype(GAUSS_ALPHA)::param_type(PARAM_.MEAN_ALPHA, PARAM_.SD_ALPHA));
GAUSS_MIGRA.param(decltype(GAUSS_MIGRA)::param_type(PARAM_.MEAN_MIGRA, PARAM_.SD_MIGRA));
}
void Cell::differentiate(urbg_t& engine) {
if (is_differentiated()) return;
if (BERN_SYMMETRIC(engine)) return;
proliferation_capacity_ = static_cast<int8_t>(PARAM_.MAX_PROLIFERATION_CAPACITY);
}
std::string Cell::mutate(urbg_t& engine) {
auto oss = wtl::make_oss();
if (BERN_MUT_BIRTH(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_BIRTH(engine);
oss << id_ << "\tbeta\t" << s << "\n";
event_rates_->birth_rate *= (s += 1.0);
}
if (BERN_MUT_DEATH(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_DEATH(engine);
oss << id_ << "\tdelta\t" << s << "\n";
event_rates_->death_rate *= (s += 1.0);
}
if (BERN_MUT_ALPHA(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_ALPHA(engine);
oss << id_ << "\talpha\t" << s << "\n";
event_rates_->death_prob *= (s += 1.0);
}
if (BERN_MUT_MIGRA(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_MIGRA(engine);
oss << id_ << "\trho\t" << s << "\n";
event_rates_->migra_rate *= (s += 1.0);
}
return oss.str();
}
std::string Cell::force_mutate(urbg_t& engine) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
const double s_birth = GAUSS_BIRTH(engine);
const double s_death = GAUSS_DEATH(engine);
const double s_alpha = GAUSS_ALPHA(engine);
const double s_migra = GAUSS_MIGRA(engine);
event_rates_->birth_rate *= (1.0 + s_birth);
event_rates_->death_rate *= (1.0 + s_death);
event_rates_->death_prob *= (1.0 + s_alpha);
event_rates_->migra_rate *= (1.0 + s_migra);
auto oss = wtl::make_oss();
oss << id_ << "\tbeta\t" << s_birth << "\n"
<< id_ << "\tdelta\t" << s_death << "\n"
<< id_ << "\talpha\t" << s_alpha << "\n"
<< id_ << "\trho\t" << s_migra << "\n";
return oss.str();
}
double Cell::delta_time(urbg_t& engine, const double now, const double positional_value, const bool surrounded) {
double t_birth = std::numeric_limits<double>::infinity();
double t_death = std::numeric_limits<double>::infinity();
double t_migra = std::numeric_limits<double>::infinity();
if (proliferation_capacity_ != 0) {
double mu = 1.0;
mu /= birth_rate();
mu /= positional_value;
if (!surrounded) mu -= (now - time_of_birth_);
t_birth = GAMMA_FACTORY(mu)(engine);
}
if (death_rate() > 0.0) {
std::exponential_distribution<double> exponential(death_rate());
t_death = exponential(engine);
}
if (migra_rate() > 0.0) {
std::exponential_distribution<double> exponential(migra_rate());
t_migra = exponential(engine);
}
if (t_birth < t_death && t_birth < t_migra) {
next_event_ = bernoulli(death_prob(), engine)
? Event::death : Event::birth;
return t_birth;
} else if (t_death < t_migra) {
next_event_ = Event::death;
return t_death;
} else {
next_event_ = Event::migration;
return t_migra;
}
}
void Cell::set_cycle_dependent_death(urbg_t& engine, const double p) {
//TODO: reduce redundant copy for susceptible cells
event_rates_ = std::make_shared<EventRates>(*event_rates_);
event_rates_->death_prob = p;
next_event_ = bernoulli(p, engine) ? Event::death : Event::birth;
}
std::string Cell::header() {
std::ostringstream oss;
oss << "x\ty\tz\t"
<< "id\tancestor\t"
<< "birth\tdeath\t"
<< "omega";
return oss.str();
}
std::ostream& Cell::write(std::ostream& ost) const {
return ost
<< coord_[0] << "\t" << coord_[1] << "\t" << coord_[2] << "\t"
<< id_ << "\t"
<< (ancestor_ ? ancestor_->id_ : 0u) << "\t"
<< time_of_birth_ << "\t" << time_of_death_ << "\t"
<< static_cast<int>(proliferation_capacity_);
}
std::ostream& Cell::traceback(std::ostream& ost, std::unordered_set<unsigned>* done) const {
write(ost) << "\n";
if (ancestor_ && done->insert(ancestor_->id_).second) {
ancestor_->traceback(ost, done);
}
return ost;
}
//! Stream operator for debug print
std::ostream& operator<< (std::ostream& ost, const Cell& x) {
return x.write(ost);
}
} // namespace tumopp
<commit_msg>:art: Output only mutations with s>0 from force_mutate()<commit_after>/*! @file cell.cpp
@brief Implementation of Cell class
*/
#include "cell.hpp"
#include <wtl/iostr.hpp>
#include <wtl/random.hpp>
#include <type_traits>
namespace tumopp {
static_assert(std::is_nothrow_copy_constructible<Cell>{}, "");
static_assert(std::is_nothrow_move_constructible<Cell>{}, "");
Cell::param_type Cell::PARAM_;
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace {
class GammaFactory {
public:
GammaFactory(double k) noexcept: shape_(k) {}
std::gamma_distribution<double> operator()(double mu) {
const double theta = std::max(mu / shape_, 0.0);
return std::gamma_distribution<double>(shape_, theta);
}
void param(double k) {shape_ = k;}
private:
double shape_;
};
template <class URBG>
inline bool bernoulli(double p, URBG& engine) {
// consume less URBG when p is set to 0 or 1.
return p >= 1.0 || (p > 0.0 && wtl::generate_canonical(engine) < p);
}
class bernoulli_distribution {
public:
bernoulli_distribution(double p) noexcept: p_(p) {}
template <class URBG>
bool operator()(URBG& engine) const {
return p_ >= 1.0 || (p_ > 0.0 && wtl::generate_canonical(engine) < p_);
}
void param(double p) {p_ = p;}
private:
double p_;
};
GammaFactory GAMMA_FACTORY(Cell::param().GAMMA_SHAPE);
bernoulli_distribution BERN_SYMMETRIC(Cell::param().PROB_SYMMETRIC_DIVISION);
bernoulli_distribution BERN_MUT_BIRTH(Cell::param().RATE_BIRTH);
bernoulli_distribution BERN_MUT_DEATH(Cell::param().RATE_DEATH);
bernoulli_distribution BERN_MUT_ALPHA(Cell::param().RATE_ALPHA);
bernoulli_distribution BERN_MUT_MIGRA(Cell::param().RATE_MIGRA);
std::normal_distribution<double> GAUSS_BIRTH(Cell::param().MEAN_BIRTH, Cell::param().SD_BIRTH);
std::normal_distribution<double> GAUSS_DEATH(Cell::param().MEAN_DEATH, Cell::param().SD_DEATH);
std::normal_distribution<double> GAUSS_ALPHA(Cell::param().MEAN_ALPHA, Cell::param().SD_ALPHA);
std::normal_distribution<double> GAUSS_MIGRA(Cell::param().MEAN_MIGRA, Cell::param().SD_MIGRA);
}// namespace
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
void Cell::param(const param_type& p) {
PARAM_ = p;
GAMMA_FACTORY.param(PARAM_.GAMMA_SHAPE);
BERN_SYMMETRIC.param(PARAM_.PROB_SYMMETRIC_DIVISION);
BERN_MUT_BIRTH.param(PARAM_.RATE_BIRTH);
BERN_MUT_DEATH.param(PARAM_.RATE_DEATH);
BERN_MUT_ALPHA.param(PARAM_.RATE_ALPHA);
BERN_MUT_MIGRA.param(PARAM_.RATE_MIGRA);
GAUSS_BIRTH.param(decltype(GAUSS_BIRTH)::param_type(PARAM_.MEAN_BIRTH, PARAM_.SD_BIRTH));
GAUSS_DEATH.param(decltype(GAUSS_DEATH)::param_type(PARAM_.MEAN_DEATH, PARAM_.SD_DEATH));
GAUSS_ALPHA.param(decltype(GAUSS_ALPHA)::param_type(PARAM_.MEAN_ALPHA, PARAM_.SD_ALPHA));
GAUSS_MIGRA.param(decltype(GAUSS_MIGRA)::param_type(PARAM_.MEAN_MIGRA, PARAM_.SD_MIGRA));
}
void Cell::differentiate(urbg_t& engine) {
if (is_differentiated()) return;
if (BERN_SYMMETRIC(engine)) return;
proliferation_capacity_ = static_cast<int8_t>(PARAM_.MAX_PROLIFERATION_CAPACITY);
}
std::string Cell::mutate(urbg_t& engine) {
auto oss = wtl::make_oss();
if (BERN_MUT_BIRTH(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_BIRTH(engine);
oss << id_ << "\tbeta\t" << s << "\n";
event_rates_->birth_rate *= (s += 1.0);
}
if (BERN_MUT_DEATH(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_DEATH(engine);
oss << id_ << "\tdelta\t" << s << "\n";
event_rates_->death_rate *= (s += 1.0);
}
if (BERN_MUT_ALPHA(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_ALPHA(engine);
oss << id_ << "\talpha\t" << s << "\n";
event_rates_->death_prob *= (s += 1.0);
}
if (BERN_MUT_MIGRA(engine)) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
double s = GAUSS_MIGRA(engine);
oss << id_ << "\trho\t" << s << "\n";
event_rates_->migra_rate *= (s += 1.0);
}
return oss.str();
}
std::string Cell::force_mutate(urbg_t& engine) {
event_rates_ = std::make_shared<EventRates>(*event_rates_);
const double s_birth = GAUSS_BIRTH(engine);
const double s_death = GAUSS_DEATH(engine);
const double s_alpha = GAUSS_ALPHA(engine);
const double s_migra = GAUSS_MIGRA(engine);
event_rates_->birth_rate *= (1.0 + s_birth);
event_rates_->death_rate *= (1.0 + s_death);
event_rates_->death_prob *= (1.0 + s_alpha);
event_rates_->migra_rate *= (1.0 + s_migra);
auto oss = wtl::make_oss();
if (s_birth != 0.0) {oss << id_ << "\tbeta\t" << s_birth << "\n";}
if (s_death != 0.0) {oss << id_ << "\tdelta\t" << s_death << "\n";}
if (s_alpha != 0.0) {oss << id_ << "\talpha\t" << s_alpha << "\n";}
if (s_migra != 0.0) {oss << id_ << "\trho\t" << s_migra << "\n";}
return oss.str();
}
double Cell::delta_time(urbg_t& engine, const double now, const double positional_value, const bool surrounded) {
double t_birth = std::numeric_limits<double>::infinity();
double t_death = std::numeric_limits<double>::infinity();
double t_migra = std::numeric_limits<double>::infinity();
if (proliferation_capacity_ != 0) {
double mu = 1.0;
mu /= birth_rate();
mu /= positional_value;
if (!surrounded) mu -= (now - time_of_birth_);
t_birth = GAMMA_FACTORY(mu)(engine);
}
if (death_rate() > 0.0) {
std::exponential_distribution<double> exponential(death_rate());
t_death = exponential(engine);
}
if (migra_rate() > 0.0) {
std::exponential_distribution<double> exponential(migra_rate());
t_migra = exponential(engine);
}
if (t_birth < t_death && t_birth < t_migra) {
next_event_ = bernoulli(death_prob(), engine)
? Event::death : Event::birth;
return t_birth;
} else if (t_death < t_migra) {
next_event_ = Event::death;
return t_death;
} else {
next_event_ = Event::migration;
return t_migra;
}
}
void Cell::set_cycle_dependent_death(urbg_t& engine, const double p) {
//TODO: reduce redundant copy for susceptible cells
event_rates_ = std::make_shared<EventRates>(*event_rates_);
event_rates_->death_prob = p;
next_event_ = bernoulli(p, engine) ? Event::death : Event::birth;
}
std::string Cell::header() {
std::ostringstream oss;
oss << "x\ty\tz\t"
<< "id\tancestor\t"
<< "birth\tdeath\t"
<< "omega";
return oss.str();
}
std::ostream& Cell::write(std::ostream& ost) const {
return ost
<< coord_[0] << "\t" << coord_[1] << "\t" << coord_[2] << "\t"
<< id_ << "\t"
<< (ancestor_ ? ancestor_->id_ : 0u) << "\t"
<< time_of_birth_ << "\t" << time_of_death_ << "\t"
<< static_cast<int>(proliferation_capacity_);
}
std::ostream& Cell::traceback(std::ostream& ost, std::unordered_set<unsigned>* done) const {
write(ost) << "\n";
if (ancestor_ && done->insert(ancestor_->id_).second) {
ancestor_->traceback(ost, done);
}
return ost;
}
//! Stream operator for debug print
std::ostream& operator<< (std::ostream& ost, const Cell& x) {
return x.write(ost);
}
} // namespace tumopp
<|endoftext|> |
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_common_subgraph/algorithms.hh>
#include <max_clique/algorithms.hh>
#include <graph/degree_sort.hh>
#include <graph/min_width_sort.hh>
#include <boost/program_options.hpp>
#include <iostream>
#include <iomanip>
#include <exception>
#include <algorithm>
#include <random>
#include <thread>
#include <cstdlib>
using namespace parasols;
namespace po = boost::program_options;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
auto algorithms = {
MaxCliqueAlgorithm{ cco_max_clique<CCOPermutations::None, CCOInference::None> }
};
void table(int size1, int size2, int samples)
{
using namespace std::placeholders;
for (int p1 = 0 ; p1 <= 100 ; p1 += 1) {
for (int p2 = 0 ; p2 <= 100 ; p2 += 1) {
std::cout << p1 / 100.0 << " " << p2 / 100.0;
for (auto & algorithm : algorithms) {
double size_total = 0.0, nodes_total = 0.0, best_nodes_total = 0.0, first = 0.0, second = 0.0;
for (int sample = 0 ; sample < samples ; ++sample) {
std::mt19937 rnd1, rnd2;
rnd1.seed(1234 + sample + (p1 * 2 * samples));
rnd2.seed(24681012 + sample + samples + (p2 * 2 * samples));
Graph graph1(size1, false), graph2(size2, false);
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (int e = 0 ; e < size1 ; ++e)
for (int f = e + 1 ; f < size1 ; ++f)
if (dist(rnd1) <= (double(p1) / 100.0))
graph1.add_edge(e, f);
for (int e = 0 ; e < size2 ; ++e)
for (int f = e + 1 ; f < size2 ; ++f)
if (dist(rnd2) <= (double(p2) / 100.0))
graph2.add_edge(e, f);
MaxCommonSubgraphParams params;
params.max_clique_algorithm = algorithm;
params.order_function = std::bind(none_sort, _1, _2, false);
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.start_time = steady_clock::now();
auto result1 = clique_max_common_subgraph(std::make_pair(graph1, graph2), params);
size_total += result1.size;
nodes_total += result1.nodes;
params.start_time = steady_clock::now();
auto result2 = clique_max_common_subgraph(std::make_pair(graph2, graph1), params);
if (result1.size != result2.size)
throw 0; /* oops... */
if (result1.nodes < result2.nodes) {
best_nodes_total += result1.nodes;
first += 1.0;
}
else if (result1.nodes == result2.nodes) {
best_nodes_total += result1.nodes;
first += 0.5;
second += 0.5;
}
else {
best_nodes_total += result2.nodes;
second += 1.0;
}
}
std::cout << " " << (size_total / samples) << " " <<
(nodes_total / samples) << " " << (best_nodes_total /
samples) << " " << first << " " << second;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
;
po::options_description all_options{ "All options" };
all_options.add(display_options);
all_options.add_options()
("size1", po::value<int>(), "Size of first graph")
("size2", po::value<int>(), "Size of second graph")
("samples", po::value<int>(), "Sample size")
;
po::positional_options_description positional_options;
positional_options
.add("size1", 1)
.add("size2", 1)
.add("samples", 1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] size1 size2 samples" << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No values specified? Show a message and exit. */
if (! options_vars.count("size1") || ! options_vars.count("size2") || ! options_vars.count("samples")) {
std::cout << "Usage: " << argv[0] << " [options] size1 size2 samples" << std::endl;
return EXIT_FAILURE;
}
int size1 = options_vars["size1"].as<int>();
int size2 = options_vars["size2"].as<int>();
int samples = options_vars["samples"].as<int>();
table(size1, size2, samples);
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>Order as a parameter<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <max_common_subgraph/algorithms.hh>
#include <max_clique/algorithms.hh>
#include <graph/orders.hh>
#include <boost/program_options.hpp>
#include <iostream>
#include <iomanip>
#include <exception>
#include <algorithm>
#include <random>
#include <thread>
#include <cstdlib>
using namespace parasols;
namespace po = boost::program_options;
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
auto algorithms = {
MaxCliqueAlgorithm{ cco_max_clique<CCOPermutations::None, CCOInference::None> }
};
void table(int size1, int size2, int samples, const MaxCliqueOrderFunction & order_function)
{
using namespace std::placeholders;
for (int p1 = 0 ; p1 <= 100 ; p1 += 1) {
for (int p2 = 0 ; p2 <= 100 ; p2 += 1) {
std::cout << p1 / 100.0 << " " << p2 / 100.0;
for (auto & algorithm : algorithms) {
double size_total = 0.0, nodes_total = 0.0, best_nodes_total = 0.0, first = 0.0, second = 0.0;
for (int sample = 0 ; sample < samples ; ++sample) {
std::mt19937 rnd1, rnd2;
rnd1.seed(1234 + sample + (p1 * 2 * samples));
rnd2.seed(24681012 + sample + samples + (p2 * 2 * samples));
Graph graph1(size1, false), graph2(size2, false);
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (int e = 0 ; e < size1 ; ++e)
for (int f = e + 1 ; f < size1 ; ++f)
if (dist(rnd1) <= (double(p1) / 100.0))
graph1.add_edge(e, f);
for (int e = 0 ; e < size2 ; ++e)
for (int f = e + 1 ; f < size2 ; ++f)
if (dist(rnd2) <= (double(p2) / 100.0))
graph2.add_edge(e, f);
MaxCommonSubgraphParams params;
params.max_clique_algorithm = algorithm;
params.order_function = order_function;
std::atomic<bool> abort;
abort.store(false);
params.abort = &abort;
params.start_time = steady_clock::now();
auto result1 = clique_max_common_subgraph(std::make_pair(graph1, graph2), params);
size_total += result1.size;
nodes_total += result1.nodes;
params.start_time = steady_clock::now();
auto result2 = clique_max_common_subgraph(std::make_pair(graph2, graph1), params);
if (result1.size != result2.size)
throw 0; /* oops... */
if (result1.nodes < result2.nodes) {
best_nodes_total += result1.nodes;
first += 1.0;
}
else if (result1.nodes == result2.nodes) {
best_nodes_total += result1.nodes;
first += 0.5;
second += 0.5;
}
else {
best_nodes_total += result2.nodes;
second += 1.0;
}
}
std::cout << " " << (size_total / samples) << " " <<
(nodes_total / samples) << " " << (best_nodes_total /
samples) << " " << first << " " << second;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
auto main(int argc, char * argv[]) -> int
{
try {
po::options_description display_options{ "Program options" };
display_options.add_options()
("help", "Display help information")
;
po::options_description all_options{ "All options" };
all_options.add(display_options);
all_options.add_options()
("size1", po::value<int>(), "Size of first graph")
("size2", po::value<int>(), "Size of second graph")
("samples", po::value<int>(), "Sample size")
("order", "Specify the initial vertex order")
;
po::positional_options_description positional_options;
positional_options
.add("size1", 1)
.add("size2", 1)
.add("samples", 1)
.add("order", 1)
;
po::variables_map options_vars;
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(positional_options)
.run(), options_vars);
po::notify(options_vars);
/* --help? Show a message, and exit. */
if (options_vars.count("help")) {
std::cout << "Usage: " << argv[0] << " [options] size1 size2 samples order" << std::endl;
std::cout << std::endl;
std::cout << display_options << std::endl;
return EXIT_SUCCESS;
}
/* No values specified? Show a message and exit. */
if (! options_vars.count("size1") || ! options_vars.count("size2") || ! options_vars.count("samples")
|| ! options_vars.count("order")) {
std::cout << "Usage: " << argv[0] << " [options] size1 size2 samples order" << std::endl;
return EXIT_FAILURE;
}
int size1 = options_vars["size1"].as<int>();
int size2 = options_vars["size2"].as<int>();
int samples = options_vars["samples"].as<int>();
/* Turn an order string name into a runnable function. */
MaxCliqueOrderFunction order_function;
for (auto order = orders.begin() ; order != orders.end() ; ++order)
if (std::get<0>(*order) == options_vars["order"].as<std::string>()) {
order_function = std::get<1>(*order);
break;
}
/* Unknown algorithm? Show a message and exit. */
if (! order_function) {
std::cerr << "Unknown order " << options_vars["order"].as<std::string>() << ", choose from:";
for (auto a : orders)
std::cerr << " " << std::get<0>(a);
std::cerr << std::endl;
return EXIT_FAILURE;
}
table(size1, size2, samples, order_function);
return EXIT_SUCCESS;
}
catch (const po::error & e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "Try " << argv[0] << " --help" << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright 2015-2017 MICRORISC s.r.o.
* Copyright 2017 IQRF Tech s.r.o.
*
* 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 "DpaTransfer.h"
#include "DpaTransaction.h"
#include "unexpected_packet_type.h"
#include "unexpected_command.h"
#include "unexpected_peripheral.h"
#include "IqrfLogging.h"
DpaTransfer::DpaTransfer()
: m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),
m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(kStd), m_dpaTransaction(nullptr)
{
}
DpaTransfer::DpaTransfer(DpaTransaction* dpaTransaction, IqrfRfCommunicationMode comMode)
: m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),
m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(comMode), m_dpaTransaction(dpaTransaction)
{
}
DpaTransfer::~DpaTransfer()
{
delete m_sentMessage;
delete m_responseMessage;
}
void DpaTransfer::ProcessSentMessage(const DpaMessage& sentMessage)
{
TRC_ENTER("");
if (m_status != kCreated)
{
throw std::logic_error("Sent message already set.");
}
// current request status is set as sent
if (sentMessage.NodeAddress() == COORDINATOR_ADDRESS) {
SetStatus(kSentCoordinator);
}
else {
SetStatus(kSent);
}
// message itself is destroyed after being sent
delete m_sentMessage;
// creating object to hold new request
m_sentMessage = new DpaMessage(sentMessage);
// setting default timeout, no estimation yet
SetTimingForCurrentTransfer();
TRC_LEAVE("");
}
bool DpaTransfer::ProcessReceivedMessage(const DpaMessage& receivedMessage)
{
TRC_ENTER("");
// direction
auto messageDirection = receivedMessage.MessageDirection();
// is transfer in progress?
if (!IsInProgressStatus(m_status)) {
// no
TRC_INF("No transfer started, space for async message processing." << PAR(m_status));
return false;
}
// yes
else {
// no request is expected
if (messageDirection != DpaMessage::kResponse && messageDirection != DpaMessage::kConfirmation)
throw unexpected_packet_type("Response is expected.");
// same as sent request
if (receivedMessage.PeripheralType() != m_sentMessage->PeripheralType()) {
throw unexpected_peripheral("Different peripheral type than in sent message.");
}
// same as sent request
if ((receivedMessage.PeripheralCommand() & ~0x80) != m_sentMessage->PeripheralCommand()) {
throw unexpected_command("Different peripheral command than in sent message.");
}
}
if (messageDirection == DpaMessage::kConfirmation) {
if (m_dpaTransaction) {
m_dpaTransaction->processConfirmationMessage(receivedMessage);
}
{
// change in transfer status
std::lock_guard<std::mutex> lck(m_statusMutex);
ProcessConfirmationMessage(receivedMessage);
}
TRC_INF("Confirmation processed.");
}
else {
if (m_dpaTransaction) {
m_dpaTransaction->processResponseMessage(receivedMessage);
}
{
// change in transfer status
std::lock_guard<std::mutex> lck(m_statusMutex);
ProcessResponseMessage(receivedMessage);
}
TRC_INF("Response processed.");
}
TRC_LEAVE("");
return true;
}
void DpaTransfer::ProcessConfirmationMessage(const DpaMessage& confirmationMessage)
{
if (confirmationMessage.NodeAddress() == DpaMessage::kBroadCastAddress) {
m_status = kConfirmationBroadcast;
}
else {
m_status = kConfirmation;
}
// setting timeout based on the confirmation
SetTimingForCurrentTransfer(EstimatedTimeout(confirmationMessage));
}
void DpaTransfer::ProcessResponseMessage(const DpaMessage& responseMessage)
{
// if there is a request to coordinator then after receiving response it is allowed to send another
if (m_status == kSentCoordinator) {
// done, next request gets ready
m_status = kProcessed;
}
else {
// only if there is not infinite timeout
if (m_expectedDurationMs != 0) {
m_status = kReceivedResponse;
// adjust timing before allowing next request
SetTimingForCurrentTransfer(EstimatedTimeout(responseMessage));
}
// infinite timeout
else {
// done, next request gets ready
m_status = kProcessed;
}
}
delete m_responseMessage;
m_responseMessage = new DpaMessage(responseMessage);
}
int32_t DpaTransfer::EstimatedTimeout(const DpaMessage& receivedMessage)
{
// direction
auto direction = receivedMessage.MessageDirection();
// double check
if (direction != DpaMessage::kConfirmation && direction != DpaMessage::kResponse) {
throw std::invalid_argument("Parameter is not a received message type.");
}
// confirmation
if (direction == DpaMessage::kConfirmation) {
auto iFace = receivedMessage.DpaPacket().DpaResponsePacket_t.DpaMessage.IFaceConfirmation;
// save for later use with response
m_hops = iFace.Hops;
m_timeslotLength = iFace.TimeSlotLength;
m_hopsResponse = iFace.HopsResponse;
// lp
if (m_currentCommunicationMode == kLp) {
return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse);
}
// std
return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse);
}
// response
if (direction == DpaMessage::kResponse) {
// lp
if (m_currentCommunicationMode == kLp) {
return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse,
receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));
}
// std
return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse,
receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));
}
}
int32_t DpaTransfer::EstimateStdTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)
{
TRC_ENTER("");
int32_t responseTimeSlotLengthMs;
auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;
// estimation from confirmation
if (responseDataLength == -1) {
if (timeslotReq == 20) {
responseTimeSlotLengthMs = 200;
}
else {
// worst case
responseTimeSlotLengthMs = 60;
}
}
// correction of the estimation from response
else {
TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength));
if (responseDataLength >= 0 && responseDataLength < 16)
{
responseTimeSlotLengthMs = 40;
}
else if (responseDataLength >= 16 && responseDataLength <= 39)
{
responseTimeSlotLengthMs = 50;
}
else if (responseDataLength > 39)
{
responseTimeSlotLengthMs = 60;
}
TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs));
}
estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;
TRC_DBG("Estimated STD timeout: " << PAR(estimatedTimeoutMs));
TRC_LEAVE("");
return estimatedTimeoutMs;
}
int32_t DpaTransfer::EstimateLpTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)
{
TRC_ENTER("");
int32_t responseTimeSlotLengthMs;
auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;
// estimation from confirmation
if (responseDataLength == -1) {
if (timeslotReq == 20) {
responseTimeSlotLengthMs = 200;
}
else {
// worst case
responseTimeSlotLengthMs = 110;
}
}
// correction of the estimation from response
else {
TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength));
if (responseDataLength >= 0 && responseDataLength < 11)
{
responseTimeSlotLengthMs = 80;
}
else if (responseDataLength >= 11 && responseDataLength <= 33)
{
responseTimeSlotLengthMs = 90;
}
else if (responseDataLength >= 34 && responseDataLength <= 56)
{
responseTimeSlotLengthMs = 100;
}
else if (responseDataLength > 56)
{
responseTimeSlotLengthMs = 110;
}
TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs));
}
estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;
TRC_DBG("Estimated LP timeout: " << PAR(estimatedTimeoutMs));
TRC_LEAVE("");
return estimatedTimeoutMs;
}
void DpaTransfer::SetTimingForCurrentTransfer(int32_t estimatedTimeMs)
{
TRC_ENTER("");
// waiting forever
if (m_timeoutMs == 0) {
m_expectedDurationMs = m_timeoutMs;
TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs));
return;
}
// adjust time to wait before allowing next request to go the iqrf network
if (m_status == kReceivedResponse) {
//adjust new timing based on length of PData in response
m_expectedDurationMs = estimatedTimeMs;
TRC_DBG("New expected duration to wait :" << PAR(m_expectedDurationMs));
return;
}
// estimation done
if (estimatedTimeMs >= 0) {
// either default timeout is 400 or user sets lower time than estimated
if (m_timeoutMs < estimatedTimeMs) {
// in both cases use estimation from confirmation
m_timeoutMs = estimatedTimeMs;
}
// set new duration
// there is also case when user sets higher than estimation then user choice is set
m_expectedDurationMs = m_timeoutMs;
TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs));
}
// start time when dpa request is sent and rerun again when confirmation is received
m_startTime = std::chrono::system_clock::now();
TRC_INF("Transfer status: started");
TRC_LEAVE("");
}
DpaTransfer::DpaTransferStatus DpaTransfer::ProcessStatus() {
TRC_ENTER("");
std::lock_guard<std::mutex> lck(m_statusMutex);
// changes m_status, does not care about remains
// todo: refactor and rename - two functions
CheckTimeout();
TRC_LEAVE("");
return m_status;
}
int32_t DpaTransfer::CheckTimeout()
{
int32_t remains(0);
if (m_status == kCreated) {
TRC_INF("Transfer status: created");
return remains;
}
if (m_status == kAborted) {
TRC_INF("Transfer status: aborted");
return remains;
}
bool timingFinished(false);
// infinite (0) is out of this statement
if (m_expectedDurationMs > 0) {
// passed time from sent request
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_startTime);
remains = m_expectedDurationMs - duration.count();
TRC_DBG("Time to wait: " << PAR(remains));
// already over?
timingFinished = remains < 0;
}
// not yet set and yes time is over
// processed or timeouted can be set only after finished timing
if (m_status != kProcessed && m_status != kTimeout) {
if (timingFinished) {
// and we have received confirmation for broadcast or response
if (m_status == kConfirmationBroadcast || m_status == kReceivedResponse) {
SetStatus(kProcessed);
TRC_INF("Transfer status: processed");
}
else {
SetStatus(kTimeout);
TRC_INF("Transfer status: timeout");
}
}
}
// time to wait
return remains;
}
bool DpaTransfer::IsInProgress() {
return IsInProgressStatus(ProcessStatus());
}
bool DpaTransfer::IsInProgress(int32_t& expectedDuration) {
std::lock_guard<std::mutex> lck(m_statusMutex);
expectedDuration = CheckTimeout();
return IsInProgressStatus(m_status);
}
bool DpaTransfer::IsInProgressStatus(DpaTransferStatus status)
{
switch (status)
{
case kSent:
case kSentCoordinator:
case kConfirmation:
case kConfirmationBroadcast:
case kReceivedResponse:
return true;
// kCreated, kProcessed, kTimeout, kAbort, kError
default:
return false;
}
}
void DpaTransfer::Abort() {
std::lock_guard<std::mutex> lck(m_statusMutex);
m_status = kAborted;
}
void DpaTransfer::SetStatus(DpaTransfer::DpaTransferStatus status)
{
m_status = status;
}
<commit_msg>Improve locking of m_statusMutex<commit_after>/**
* Copyright 2015-2017 MICRORISC s.r.o.
* Copyright 2017 IQRF Tech s.r.o.
*
* 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 "DpaTransfer.h"
#include "DpaTransaction.h"
#include "unexpected_packet_type.h"
#include "unexpected_command.h"
#include "unexpected_peripheral.h"
#include "IqrfLogging.h"
DpaTransfer::DpaTransfer()
: m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),
m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(kStd), m_dpaTransaction(nullptr)
{
}
DpaTransfer::DpaTransfer(DpaTransaction* dpaTransaction, IqrfRfCommunicationMode comMode)
: m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),
m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(comMode), m_dpaTransaction(dpaTransaction)
{
}
DpaTransfer::~DpaTransfer()
{
delete m_sentMessage;
delete m_responseMessage;
}
void DpaTransfer::ProcessSentMessage(const DpaMessage& sentMessage)
{
TRC_ENTER("");
if (m_status != kCreated)
{
throw std::logic_error("Sent message already set.");
}
// current request status is set as sent
if (sentMessage.NodeAddress() == COORDINATOR_ADDRESS) {
SetStatus(kSentCoordinator);
}
else {
SetStatus(kSent);
}
// message itself is destroyed after being sent
delete m_sentMessage;
// creating object to hold new request
m_sentMessage = new DpaMessage(sentMessage);
// setting default timeout, no estimation yet
SetTimingForCurrentTransfer();
TRC_LEAVE("");
}
bool DpaTransfer::ProcessReceivedMessage(const DpaMessage& receivedMessage)
{
TRC_ENTER("");
// direction
auto messageDirection = receivedMessage.MessageDirection();
// is transfer in progress?
if (!IsInProgressStatus(m_status)) {
// no
TRC_INF("No transfer started, space for async message processing." << PAR(m_status));
return false;
}
// yes
else {
// no request is expected
if (messageDirection != DpaMessage::kResponse && messageDirection != DpaMessage::kConfirmation)
throw unexpected_packet_type("Response is expected.");
// same as sent request
if (receivedMessage.PeripheralType() != m_sentMessage->PeripheralType()) {
throw unexpected_peripheral("Different peripheral type than in sent message.");
}
// same as sent request
if ((receivedMessage.PeripheralCommand() & ~0x80) != m_sentMessage->PeripheralCommand()) {
throw unexpected_command("Different peripheral command than in sent message.");
}
}
if (messageDirection == DpaMessage::kConfirmation) {
if (m_dpaTransaction) {
m_dpaTransaction->processConfirmationMessage(receivedMessage);
}
{
// change in transfer status
std::lock_guard<std::mutex> lck(m_statusMutex);
ProcessConfirmationMessage(receivedMessage);
}
TRC_INF("Confirmation processed.");
}
else {
if (m_dpaTransaction) {
m_dpaTransaction->processResponseMessage(receivedMessage);
}
{
// change in transfer status
std::lock_guard<std::mutex> lck(m_statusMutex);
ProcessResponseMessage(receivedMessage);
}
TRC_INF("Response processed.");
}
TRC_LEAVE("");
return true;
}
void DpaTransfer::ProcessConfirmationMessage(const DpaMessage& confirmationMessage)
{
if (confirmationMessage.NodeAddress() == DpaMessage::kBroadCastAddress) {
m_status = kConfirmationBroadcast;
}
else {
m_status = kConfirmation;
}
// setting timeout based on the confirmation
SetTimingForCurrentTransfer(EstimatedTimeout(confirmationMessage));
}
void DpaTransfer::ProcessResponseMessage(const DpaMessage& responseMessage)
{
// if there is a request to coordinator then after receiving response it is allowed to send another
if (m_status == kSentCoordinator) {
// done, next request gets ready
m_status = kProcessed;
}
else {
// only if there is not infinite timeout
if (m_expectedDurationMs != 0) {
m_status = kReceivedResponse;
// adjust timing before allowing next request
SetTimingForCurrentTransfer(EstimatedTimeout(responseMessage));
}
// infinite timeout
else {
// done, next request gets ready
m_status = kProcessed;
}
}
delete m_responseMessage;
m_responseMessage = new DpaMessage(responseMessage);
}
int32_t DpaTransfer::EstimatedTimeout(const DpaMessage& receivedMessage)
{
// direction
auto direction = receivedMessage.MessageDirection();
// double check
if (direction != DpaMessage::kConfirmation && direction != DpaMessage::kResponse) {
throw std::invalid_argument("Parameter is not a received message type.");
}
// confirmation
if (direction == DpaMessage::kConfirmation) {
auto iFace = receivedMessage.DpaPacket().DpaResponsePacket_t.DpaMessage.IFaceConfirmation;
// save for later use with response
m_hops = iFace.Hops;
m_timeslotLength = iFace.TimeSlotLength;
m_hopsResponse = iFace.HopsResponse;
// lp
if (m_currentCommunicationMode == kLp) {
return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse);
}
// std
return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse);
}
// response
if (direction == DpaMessage::kResponse) {
// lp
if (m_currentCommunicationMode == kLp) {
return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse,
receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));
}
// std
return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse,
receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));
}
}
int32_t DpaTransfer::EstimateStdTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)
{
TRC_ENTER("");
int32_t responseTimeSlotLengthMs;
auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;
// estimation from confirmation
if (responseDataLength == -1) {
if (timeslotReq == 20) {
responseTimeSlotLengthMs = 200;
}
else {
// worst case
responseTimeSlotLengthMs = 60;
}
}
// correction of the estimation from response
else {
TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength));
if (responseDataLength >= 0 && responseDataLength < 16)
{
responseTimeSlotLengthMs = 40;
}
else if (responseDataLength >= 16 && responseDataLength <= 39)
{
responseTimeSlotLengthMs = 50;
}
else if (responseDataLength > 39)
{
responseTimeSlotLengthMs = 60;
}
TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs));
}
estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;
TRC_DBG("Estimated STD timeout: " << PAR(estimatedTimeoutMs));
TRC_LEAVE("");
return estimatedTimeoutMs;
}
int32_t DpaTransfer::EstimateLpTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)
{
TRC_ENTER("");
int32_t responseTimeSlotLengthMs;
auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;
// estimation from confirmation
if (responseDataLength == -1) {
if (timeslotReq == 20) {
responseTimeSlotLengthMs = 200;
}
else {
// worst case
responseTimeSlotLengthMs = 110;
}
}
// correction of the estimation from response
else {
TRC_DBG("PData length of the received response: " << PAR((int)responseDataLength));
if (responseDataLength >= 0 && responseDataLength < 11)
{
responseTimeSlotLengthMs = 80;
}
else if (responseDataLength >= 11 && responseDataLength <= 33)
{
responseTimeSlotLengthMs = 90;
}
else if (responseDataLength >= 34 && responseDataLength <= 56)
{
responseTimeSlotLengthMs = 100;
}
else if (responseDataLength > 56)
{
responseTimeSlotLengthMs = 110;
}
TRC_DBG("Correction of the response timeout: " << PAR(responseTimeSlotLengthMs));
}
estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;
TRC_DBG("Estimated LP timeout: " << PAR(estimatedTimeoutMs));
TRC_LEAVE("");
return estimatedTimeoutMs;
}
void DpaTransfer::SetTimingForCurrentTransfer(int32_t estimatedTimeMs)
{
TRC_ENTER("");
// waiting forever
if (m_timeoutMs == 0) {
m_expectedDurationMs = m_timeoutMs;
TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs));
return;
}
// adjust time to wait before allowing next request to go the iqrf network
if (m_status == kReceivedResponse) {
//adjust new timing based on length of PData in response
m_expectedDurationMs = estimatedTimeMs;
TRC_DBG("New expected duration to wait :" << PAR(m_expectedDurationMs));
return;
}
// estimation done
if (estimatedTimeMs >= 0) {
// either default timeout is 400 or user sets lower time than estimated
if (m_timeoutMs < estimatedTimeMs) {
// in both cases use estimation from confirmation
m_timeoutMs = estimatedTimeMs;
}
// set new duration
// there is also case when user sets higher than estimation then user choice is set
m_expectedDurationMs = m_timeoutMs;
TRC_DBG("Expected duration to wait :" << PAR(m_expectedDurationMs));
}
// start time when dpa request is sent and rerun again when confirmation is received
m_startTime = std::chrono::system_clock::now();
TRC_INF("Transfer status: started");
TRC_LEAVE("");
}
DpaTransfer::DpaTransferStatus DpaTransfer::ProcessStatus() {
TRC_ENTER("");
{
std::lock_guard<std::mutex> lck(m_statusMutex);
// changes m_status, does not care about remains
// todo: refactor and rename - two functions
CheckTimeout();
}
TRC_LEAVE("");
return m_status;
}
int32_t DpaTransfer::CheckTimeout()
{
int32_t remains(0);
if (m_status == kCreated) {
TRC_INF("Transfer status: created");
return remains;
}
if (m_status == kAborted) {
TRC_INF("Transfer status: aborted");
return remains;
}
bool timingFinished(false);
// infinite (0) is out of this statement
if (m_expectedDurationMs > 0) {
// passed time from sent request
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_startTime);
remains = m_expectedDurationMs - duration.count();
TRC_DBG("Time to wait: " << PAR(remains));
// already over?
timingFinished = remains < 0;
}
// not yet set and yes time is over
// processed or timeouted can be set only after finished timing
if (m_status != kProcessed && m_status != kTimeout) {
if (timingFinished) {
// and we have received confirmation for broadcast or response
if (m_status == kConfirmationBroadcast || m_status == kReceivedResponse) {
SetStatus(kProcessed);
TRC_INF("Transfer status: processed");
}
else {
SetStatus(kTimeout);
TRC_INF("Transfer status: timeout");
}
}
}
// time to wait
return remains;
}
bool DpaTransfer::IsInProgress() {
return IsInProgressStatus(ProcessStatus());
}
bool DpaTransfer::IsInProgress(int32_t& expectedDuration) {
{
std::lock_guard<std::mutex> lck(m_statusMutex);
expectedDuration = CheckTimeout();
}
return IsInProgressStatus(m_status);
}
bool DpaTransfer::IsInProgressStatus(DpaTransferStatus status)
{
switch (status)
{
case kSent:
case kSentCoordinator:
case kConfirmation:
case kConfirmationBroadcast:
case kReceivedResponse:
return true;
// kCreated, kProcessed, kTimeout, kAbort, kError
default:
return false;
}
}
void DpaTransfer::Abort() {
std::lock_guard<std::mutex> lck(m_statusMutex);
m_status = kAborted;
}
void DpaTransfer::SetStatus(DpaTransfer::DpaTransferStatus status)
{
m_status = status;
}
<|endoftext|> |
<commit_before>//
// main.cpp
// Euchre
//
// Created by Dillon Hammond on 9/12/14.
// Copyright (c) 2014 Learning. All rights reserved.
//
#define GLEW_STATIC
#include "GL/glew.h"
#include <SDL2/SDL.h>
#include "SOIL.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include <iostream>
#include <fstream>
#include <vector>
GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) {
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream;
VertexShaderStream.open(vertex_file_path);
if(VertexShaderStream.is_open()) {
std::string Line = "";
while(getline(VertexShaderStream, Line)) {
VertexShaderCode += "\n" + Line;
}
VertexShaderStream.close();
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream;
FragmentShaderStream.open(fragment_file_path);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line)) {
FragmentShaderCode += "\n" + Line;
}
FragmentShaderStream.close();
}
GLint Result;
// Compile Vertex Shader
const char* VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_FALSE) {
std::cout << "NOOOV" << std::endl;
std::cout << VertexSourcePointer << std::endl;
}
// Compile Fragment Shader
const char* FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_FALSE) {
std::cout << "NOOOF" << std::endl;
std::cout << FragmentSourcePointer << std::endl;
}
// Link the program
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
SDL_Window* createWindow(const char* title, int x, int y, int w, int h, Uint32 flags) {
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_Window *window = SDL_CreateWindow(title, x, y, w, h, flags);
return window;
}
void LoadTextures(std::vector<GLuint> textures, const char* filename, const char* texName, GLuint shaderProgram, int texNum) {
int width, height;
unsigned char* image;
glActiveTexture(GL_TEXTURE0 + texNum);
glBindTexture(GL_TEXTURE_2D, textures.at(texNum));
image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
glUniform1i(glGetUniformLocation(shaderProgram, "backGround"), texNum);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
std::vector<float> LoadData(const char* file_path) {
// Read Vertices in from a file
std::vector<float> vertices;
std::string fileCode;
std::ifstream fileStream;
fileStream.open(file_path);
if(fileStream.is_open()) {
std::string Line;
while(getline(fileStream, Line, ',')) {
fileCode = Line;
float numRead = std::stof(fileCode);
vertices.push_back(numRead);
}
fileStream.close();
}
return vertices;
}
int main() {
SDL_Window* window = createWindow("Euchre", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(window);
// Initialize GLEW
glewExperimental = GL_TRUE;
glewInit();
// Create Vertex Array Object
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Create a Position Buffer Object and copy the vertex data to it
GLuint positionBuffer;
glGenBuffers(1, &positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
std::vector<float> bgPosition = LoadData("./Resources/bgPosition.txt");
glBufferData(GL_ARRAY_BUFFER, bgPosition.size() * sizeof(float), &bgPosition.at(0), GL_STATIC_DRAW);
// Create a Color Buffer Object and copy the vertex data to it
GLuint colorBuffer;
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
std::vector<float> bgColor = LoadData("./Resources/bgColor.txt");
glBufferData(GL_ARRAY_BUFFER, bgColor.size() * sizeof(float), &bgColor.at(0), GL_STATIC_DRAW);
// Create a Texture Buffer Object and copy the vertex data to it
GLuint textureBuffer;
glGenBuffers(1, &textureBuffer);
glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
std::vector<float> bgTexture = LoadData("./Resources/bgTexture.txt");
glBufferData(GL_ARRAY_BUFFER, bgTexture.size() * sizeof(float), &bgTexture.at(0), GL_STATIC_DRAW);
// Create an element array
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
// Describes which set of points is drawn at each time
std::vector<float> drawOrders = LoadData("./Resources/drawOrder.txt");
std::vector<GLuint> drawOrder(drawOrders.begin(), drawOrders.end()); // If drawOrder is not a GLuint (if it is a float) then the code does not work (nothing renders)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, drawOrder.size() * sizeof(float), &drawOrder.at(0), GL_STATIC_DRAW);
GLuint shaderProgram = LoadShaders("./Resources/vertexShader.txt", "./Resources/fragmentShader.txt");
glUseProgram(shaderProgram);
// Specify the layout of the vertex data
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
// Specify the color attributes
GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
glEnableVertexAttribArray(colAttrib);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);
// Specifiy the texture usage
GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
glEnableVertexAttribArray(texAttrib);
glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
std::vector<GLuint> textures(1,0);
glGenTextures(1, &textures.at(0));
LoadTextures(textures, "./Resources/Background.png", "backGround", shaderProgram, 0);
SDL_Event windowEvent;
while (true) {
if (SDL_PollEvent(&windowEvent)) {
if (windowEvent.type == SDL_QUIT) {
break;
}
}
// Clear the screen to black
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Draw a rectangle from the 2 triangles using 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
SDL_GL_SwapWindow(window);
}
glDeleteTextures(static_cast<GLsizei>(textures.size()), &textures.at(0)); // Casted to remove warning about precision loss (this doesn't matter)
glDeleteProgram(shaderProgram);
glDeleteBuffers(1, &ebo);
glDeleteBuffers(1, &positionBuffer);
glDeleteVertexArrays(1, &vao);
SDL_GL_DeleteContext(context);
return 0;
}<commit_msg>LoadData is now a template, any vector type is ok<commit_after>//
// main.cpp
// Euchre
//
// Created by Dillon Hammond on 9/12/14.
// Copyright (c) 2014 Learning. All rights reserved.
//
#define GLEW_STATIC
#include "GL/glew.h"
#include <SDL2/SDL.h>
#include "SOIL.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include <iostream>
#include <fstream>
#include <vector>
GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) {
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream;
VertexShaderStream.open(vertex_file_path);
if(VertexShaderStream.is_open()) {
std::string Line = "";
while(getline(VertexShaderStream, Line)) {
VertexShaderCode += "\n" + Line;
}
VertexShaderStream.close();
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream;
FragmentShaderStream.open(fragment_file_path);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line)) {
FragmentShaderCode += "\n" + Line;
}
FragmentShaderStream.close();
}
GLint Result;
// Compile Vertex Shader
const char* VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_FALSE) {
std::cout << "NOOOV" << std::endl;
std::cout << VertexSourcePointer << std::endl;
}
// Compile Fragment Shader
const char* FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_FALSE) {
std::cout << "NOOOF" << std::endl;
std::cout << FragmentSourcePointer << std::endl;
}
// Link the program
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
SDL_Window* createWindow(const char* title, int x, int y, int w, int h, Uint32 flags) {
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_Window *window = SDL_CreateWindow(title, x, y, w, h, flags);
return window;
}
void LoadTextures(std::vector<GLuint> textures, const char* filename, const char* texName, GLuint shaderProgram, int texNum) {
int width, height;
unsigned char* image;
glActiveTexture(GL_TEXTURE0 + texNum);
glBindTexture(GL_TEXTURE_2D, textures.at(texNum));
image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
glUniform1i(glGetUniformLocation(shaderProgram, "backGround"), texNum);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
template<class T>
std::vector<T> LoadData(const char* file_path) {
// Read Vertices in from a file
std::vector<T> vertices;
std::string fileCode;
std::ifstream fileStream;
fileStream.open(file_path);
if(fileStream.is_open()) {
std::string Line;
while(getline(fileStream, Line, ',')) {
fileCode = Line;
float numRead = std::stof(fileCode);
vertices.push_back(numRead);
}
fileStream.close();
}
return vertices;
}
int main() {
SDL_Window* window = createWindow("Euchre", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(window);
// Initialize GLEW
glewExperimental = GL_TRUE;
glewInit();
// Create Vertex Array Object
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Create a Position Buffer Object and copy the vertex data to it
GLuint positionBuffer;
glGenBuffers(1, &positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
std::vector<float> bgPosition = LoadData<float>("./Resources/bgPosition.txt");
glBufferData(GL_ARRAY_BUFFER, bgPosition.size() * sizeof(float), &bgPosition.at(0), GL_STATIC_DRAW);
// Create a Color Buffer Object and copy the vertex data to it
GLuint colorBuffer;
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
std::vector<float> bgColor = LoadData<float>("./Resources/bgColor.txt");
glBufferData(GL_ARRAY_BUFFER, bgColor.size() * sizeof(float), &bgColor.at(0), GL_STATIC_DRAW);
// Create a Texture Buffer Object and copy the vertex data to it
GLuint textureBuffer;
glGenBuffers(1, &textureBuffer);
glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
std::vector<float> bgTexture = LoadData<float>("./Resources/bgTexture.txt");
glBufferData(GL_ARRAY_BUFFER, bgTexture.size() * sizeof(float), &bgTexture.at(0), GL_STATIC_DRAW);
// Create an element array
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
// Describes which set of points is drawn at each time
std::vector<GLuint> drawOrder = LoadData<GLuint>("./Resources/drawOrder.txt");
glBufferData(GL_ELEMENT_ARRAY_BUFFER, drawOrder.size() * sizeof(float), &drawOrder.at(0), GL_STATIC_DRAW);
GLuint shaderProgram = LoadShaders("./Resources/vertexShader.txt", "./Resources/fragmentShader.txt");
glUseProgram(shaderProgram);
// Specify the layout of the vertex data
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
// Specify the color attributes
GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
glEnableVertexAttribArray(colAttrib);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);
// Specifiy the texture usage
GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
glEnableVertexAttribArray(texAttrib);
glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
std::vector<GLuint> textures(1,0);
glGenTextures(1, &textures.at(0));
LoadTextures(textures, "./Resources/Background.png", "backGround", shaderProgram, 0);
SDL_Event windowEvent;
while (true) {
if (SDL_PollEvent(&windowEvent)) {
if (windowEvent.type == SDL_QUIT) {
break;
}
}
// Clear the screen to black
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Draw a rectangle from the 2 triangles using 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
SDL_GL_SwapWindow(window);
}
glDeleteTextures(static_cast<GLsizei>(textures.size()), &textures.at(0)); // Casted to remove warning about precision loss (this doesn't matter)
glDeleteProgram(shaderProgram);
glDeleteBuffers(1, &ebo);
glDeleteBuffers(1, &positionBuffer);
glDeleteVertexArrays(1, &vao);
SDL_GL_DeleteContext(context);
return 0;
}<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// clog - colorized log tail
//
// Copyright 2010-2012, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>
#include <time.h>
#include <Rule.h>
#include <cmake.h>
////////////////////////////////////////////////////////////////////////////////
// - Read rc file
// - Strip comments
// - Parse rules
//
// Note that it is an error to not have an rc file.
bool loadRules (const std::string& file, std::vector <Rule>& rules)
{
std::ifstream rc (file.c_str ());
if (rc.good ())
{
std::string::size_type comment;
std::string line;
while (getline (rc, line)) // Strips \n
{
// Remove comments.
if ((comment = line.find ('#')) != std::string::npos)
line = line.substr (0, comment);
// Process each non-trivial line as a rule.
if (line.length () > 1)
{
try
{
rules.push_back (Rule (line));
}
catch (int)
{
// Deliberately ignored - error handling.
}
}
}
rc.close ();
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Applies all the rules in all the sections specified.
// Note that processing does not stop after the first rule match - it keeps
// going.
void applyRules (
std::vector <Rule>& rules,
std::vector <std::string>& sections,
std::string& line)
{
std::vector <std::string>::const_iterator section;
for (section = sections.begin (); section != sections.end (); ++section)
{
std::vector <Rule>::iterator rule;
for (rule = rules.begin (); rule != rules.end (); ++rule)
{
// Modify line accordingly.
rule->apply (*section, line);
}
}
}
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
int status = 0;
try
{
// Locate $HOME.
struct passwd* pw = getpwuid (getuid ());
if (!pw)
throw std::string ("Could not read home directory from the passwd file.");
// Assume ~/.clogrc
std::string rcFile = pw->pw_dir;
rcFile += "/.clogrc";
// Process arguments.
std::vector <std::string> sections;
bool prepend_date = false;
bool prepend_time = false;
for (int i = 1; i < argc; ++i)
{
if (!strcmp (argv[i], "-h") ||
!strcmp (argv[i], "--help"))
{
std::cout << "\n"
<< "Usage: clog [-h|--help] [-v|--version] [-d|--date] [-t|--time] "
<< " [-f|--file <rc>] [ <section> ... ]\n"
<< "\n";
return status;
}
else if (!strcmp (argv[i], "-v") ||
!strcmp (argv[i], "--version"))
{
std::cout << "\n"
<< PACKAGE_STRING
<< " built for "
#if defined (DARWIN)
<< "darwin"
#elif defined (SOLARIS)
<< "solaris"
#elif defined (CYGWIN)
<< "cygwin"
#elif defined (OPENBSD)
<< "openbsd"
#elif defined (HAIKU)
<< "haiku"
#elif defined (FREEBSD)
<< "freebsd"
#elif defined (LINUX)
<< "linux"
#else
<< "unknown"
#endif
<< "\n"
<< "Copyright (C) 2010-2012 Göteborg Bit Factory\n"
<< "\n"
<< "Clog may be copied only under the terms of the MIT "
"license, which may be found in the source kit.\n"
<< "\n"
<< "Documentation for clog can be found using 'man clog' "
"or at http://tasktools.org/projects/clog.html\n"
<< "\n";
return status;
}
else if (!strcmp (argv[i], "-d") ||
!strcmp (argv[i], "--date"))
{
prepend_date = true;
}
else if (!strcmp (argv[i], "-t") ||
!strcmp (argv[i], "--time"))
{
prepend_time = true;
}
else if (argc > i + 1 &&
(!strcmp (argv[i], "-f") ||
!strcmp (argv[i], "--file")))
{
rcFile = argv[++i];
}
else
{
sections.push_back (argv[i]);
}
}
// Use a default section if one was not specified.
if (sections.size () == 0)
sections.push_back ("default");
// Read rc file.
std::vector <Rule> rules;
if (loadRules (rcFile, rules))
{
// Main loop: read line, apply rules, write line.
std::string line;
while (getline (std::cin, line)) // Strips \n
{
applyRules (rules, sections, line);
if (line.length ())
{
if (prepend_date || prepend_time)
{
time_t current;
time (¤t);
struct tm* t = localtime (¤t);
if (prepend_date)
std::cout << t->tm_year + 1900 << '-'
<< std::setw (2) << std::setfill ('0') << t->tm_mon + 1 << '-'
<< std::setw (2) << std::setfill ('0') << t->tm_mday << ' ';
if (prepend_time)
std::cout << std::setw (2) << std::setfill ('0') << t->tm_hour << ':'
<< std::setw (2) << std::setfill ('0') << t->tm_min << ':'
<< std::setw (2) << std::setfill ('0') << t->tm_sec << ' ';
}
std::cout << line << std::endl;
}
}
}
else
{
std::cout << "Cannot open " << rcFile << "\n"
<< "See 'man clog' for details, and a sample file.\n";
status = -1;
}
}
catch (std::string& error)
{
std::cout << error << "\n";
return -1;
}
catch (...)
{
std::cout << "Unknown error\n";
return -2;
}
return status;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Portability<commit_after>////////////////////////////////////////////////////////////////////////////////
// clog - colorized log tail
//
// Copyright 2010-2012, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <time.h>
#include <Rule.h>
#include <cmake.h>
////////////////////////////////////////////////////////////////////////////////
// - Read rc file
// - Strip comments
// - Parse rules
//
// Note that it is an error to not have an rc file.
bool loadRules (const std::string& file, std::vector <Rule>& rules)
{
std::ifstream rc (file.c_str ());
if (rc.good ())
{
std::string::size_type comment;
std::string line;
while (getline (rc, line)) // Strips \n
{
// Remove comments.
if ((comment = line.find ('#')) != std::string::npos)
line = line.substr (0, comment);
// Process each non-trivial line as a rule.
if (line.length () > 1)
{
try
{
rules.push_back (Rule (line));
}
catch (int)
{
// Deliberately ignored - error handling.
}
}
}
rc.close ();
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Applies all the rules in all the sections specified.
// Note that processing does not stop after the first rule match - it keeps
// going.
void applyRules (
std::vector <Rule>& rules,
std::vector <std::string>& sections,
std::string& line)
{
std::vector <std::string>::const_iterator section;
for (section = sections.begin (); section != sections.end (); ++section)
{
std::vector <Rule>::iterator rule;
for (rule = rules.begin (); rule != rules.end (); ++rule)
{
// Modify line accordingly.
rule->apply (*section, line);
}
}
}
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
int status = 0;
try
{
// Locate $HOME.
struct passwd* pw = getpwuid (getuid ());
if (!pw)
throw std::string ("Could not read home directory from the passwd file.");
// Assume ~/.clogrc
std::string rcFile = pw->pw_dir;
rcFile += "/.clogrc";
// Process arguments.
std::vector <std::string> sections;
bool prepend_date = false;
bool prepend_time = false;
for (int i = 1; i < argc; ++i)
{
if (!strcmp (argv[i], "-h") ||
!strcmp (argv[i], "--help"))
{
std::cout << "\n"
<< "Usage: clog [-h|--help] [-v|--version] [-d|--date] [-t|--time] "
<< " [-f|--file <rc>] [ <section> ... ]\n"
<< "\n";
return status;
}
else if (!strcmp (argv[i], "-v") ||
!strcmp (argv[i], "--version"))
{
std::cout << "\n"
<< PACKAGE_STRING
<< " built for "
#if defined (DARWIN)
<< "darwin"
#elif defined (SOLARIS)
<< "solaris"
#elif defined (CYGWIN)
<< "cygwin"
#elif defined (OPENBSD)
<< "openbsd"
#elif defined (HAIKU)
<< "haiku"
#elif defined (FREEBSD)
<< "freebsd"
#elif defined (LINUX)
<< "linux"
#else
<< "unknown"
#endif
<< "\n"
<< "Copyright (C) 2010-2012 Göteborg Bit Factory\n"
<< "\n"
<< "Clog may be copied only under the terms of the MIT "
"license, which may be found in the source kit.\n"
<< "\n"
<< "Documentation for clog can be found using 'man clog' "
"or at http://tasktools.org/projects/clog.html\n"
<< "\n";
return status;
}
else if (!strcmp (argv[i], "-d") ||
!strcmp (argv[i], "--date"))
{
prepend_date = true;
}
else if (!strcmp (argv[i], "-t") ||
!strcmp (argv[i], "--time"))
{
prepend_time = true;
}
else if (argc > i + 1 &&
(!strcmp (argv[i], "-f") ||
!strcmp (argv[i], "--file")))
{
rcFile = argv[++i];
}
else
{
sections.push_back (argv[i]);
}
}
// Use a default section if one was not specified.
if (sections.size () == 0)
sections.push_back ("default");
// Read rc file.
std::vector <Rule> rules;
if (loadRules (rcFile, rules))
{
// Main loop: read line, apply rules, write line.
std::string line;
while (getline (std::cin, line)) // Strips \n
{
applyRules (rules, sections, line);
if (line.length ())
{
if (prepend_date || prepend_time)
{
time_t current;
time (¤t);
struct tm* t = localtime (¤t);
if (prepend_date)
std::cout << t->tm_year + 1900 << '-'
<< std::setw (2) << std::setfill ('0') << t->tm_mon + 1 << '-'
<< std::setw (2) << std::setfill ('0') << t->tm_mday << ' ';
if (prepend_time)
std::cout << std::setw (2) << std::setfill ('0') << t->tm_hour << ':'
<< std::setw (2) << std::setfill ('0') << t->tm_min << ':'
<< std::setw (2) << std::setfill ('0') << t->tm_sec << ' ';
}
std::cout << line << std::endl;
}
}
}
else
{
std::cout << "Cannot open " << rcFile << "\n"
<< "See 'man clog' for details, and a sample file.\n";
status = -1;
}
}
catch (std::string& error)
{
std::cout << error << "\n";
return -1;
}
catch (...)
{
std::cout << "Unknown error\n";
return -2;
}
return status;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file brw_wm_channel_expressions.cpp
*
* Breaks vector operations down into operations on each component.
*
* The 965 fragment shader receives 8 or 16 pixels at a time, so each
* channel of a vector is laid out as 1 or 2 8-float registers. Each
* ALU operation operates on one of those channel registers. As a
* result, there is no value to the 965 fragment shader in tracking
* "vector" expressions in the sense of GLSL fragment shaders, when
* doing a channel at a time may help in constant folding, algebraic
* simplification, and reducing the liveness of channel registers.
*
* The exception to the desire to break everything down to floats is
* texturing. The texture sampler returns a writemasked masked
* 4/8-register sequence containing the texture values. We don't want
* to dispatch to the sampler separately for each channel we need, so
* we do retain the vector types in that case.
*/
extern "C" {
#include "main/core.h"
#include "brw_wm.h"
}
#include "glsl/ir.h"
#include "glsl/ir_expression_flattening.h"
#include "glsl/glsl_types.h"
class ir_channel_expressions_visitor : public ir_hierarchical_visitor {
public:
ir_channel_expressions_visitor()
{
this->progress = false;
this->mem_ctx = NULL;
}
ir_visitor_status visit_leave(ir_assignment *);
ir_rvalue *get_element(ir_variable *var, unsigned int element);
void assign(ir_assignment *ir, int elem, ir_rvalue *val);
bool progress;
void *mem_ctx;
};
static bool
channel_expressions_predicate(ir_instruction *ir)
{
ir_expression *expr = ir->as_expression();
unsigned int i;
if (!expr)
return false;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector())
return true;
}
return false;
}
bool
brw_do_channel_expressions(exec_list *instructions)
{
ir_channel_expressions_visitor v;
/* Pull out any matrix expression to a separate assignment to a
* temp. This will make our handling of the breakdown to
* operations on the matrix's vector components much easier.
*/
do_expression_flattening(instructions, channel_expressions_predicate);
visit_list_elements(&v, instructions);
return v.progress;
}
ir_rvalue *
ir_channel_expressions_visitor::get_element(ir_variable *var, unsigned int elem)
{
ir_dereference *deref;
if (var->type->is_scalar())
return new(mem_ctx) ir_dereference_variable(var);
assert(elem < var->type->components());
deref = new(mem_ctx) ir_dereference_variable(var);
return new(mem_ctx) ir_swizzle(deref, elem, 0, 0, 0, 1);
}
void
ir_channel_expressions_visitor::assign(ir_assignment *ir, int elem, ir_rvalue *val)
{
ir_dereference *lhs = ir->lhs->clone(mem_ctx, NULL);
ir_assignment *assign;
/* This assign-of-expression should have been generated by the
* expression flattening visitor (since we never short circit to
* not flatten, even for plain assignments of variables), so the
* writemask is always full.
*/
assert(ir->write_mask == (1 << ir->lhs->type->components()) - 1);
assign = new(mem_ctx) ir_assignment(lhs, val, NULL, (1 << elem));
ir->insert_before(assign);
}
ir_visitor_status
ir_channel_expressions_visitor::visit_leave(ir_assignment *ir)
{
ir_expression *expr = ir->rhs->as_expression();
bool found_vector = false;
unsigned int i, vector_elements = 1;
ir_variable *op_var[3];
if (!expr)
return visit_continue;
if (!this->mem_ctx)
this->mem_ctx = ralloc_parent(ir);
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector()) {
found_vector = true;
vector_elements = expr->operands[i]->type->vector_elements;
break;
}
}
if (!found_vector)
return visit_continue;
/* Store the expression operands in temps so we can use them
* multiple times.
*/
for (i = 0; i < expr->get_num_operands(); i++) {
ir_assignment *assign;
ir_dereference *deref;
assert(!expr->operands[i]->type->is_matrix());
op_var[i] = new(mem_ctx) ir_variable(expr->operands[i]->type,
"channel_expressions",
ir_var_temporary);
ir->insert_before(op_var[i]);
deref = new(mem_ctx) ir_dereference_variable(op_var[i]);
assign = new(mem_ctx) ir_assignment(deref,
expr->operands[i],
NULL);
ir->insert_before(assign);
}
const glsl_type *element_type = glsl_type::get_instance(ir->lhs->type->base_type,
1, 1);
/* OK, time to break down this vector operation. */
switch (expr->operation) {
case ir_unop_bit_not:
case ir_unop_logic_not:
case ir_unop_neg:
case ir_unop_abs:
case ir_unop_sign:
case ir_unop_rcp:
case ir_unop_rsq:
case ir_unop_sqrt:
case ir_unop_exp:
case ir_unop_log:
case ir_unop_exp2:
case ir_unop_log2:
case ir_unop_bitcast_i2f:
case ir_unop_bitcast_f2i:
case ir_unop_bitcast_f2u:
case ir_unop_bitcast_u2f:
case ir_unop_i2u:
case ir_unop_u2i:
case ir_unop_f2i:
case ir_unop_f2u:
case ir_unop_i2f:
case ir_unop_f2b:
case ir_unop_b2f:
case ir_unop_i2b:
case ir_unop_b2i:
case ir_unop_u2f:
case ir_unop_trunc:
case ir_unop_ceil:
case ir_unop_floor:
case ir_unop_fract:
case ir_unop_round_even:
case ir_unop_sin:
case ir_unop_cos:
case ir_unop_sin_reduced:
case ir_unop_cos_reduced:
case ir_unop_dFdx:
case ir_unop_dFdy:
case ir_unop_bitfield_reverse:
case ir_unop_bit_count:
case ir_unop_find_msb:
case ir_unop_find_lsb:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
NULL));
}
break;
case ir_binop_add:
case ir_binop_sub:
case ir_binop_mul:
case ir_binop_imul_high:
case ir_binop_div:
case ir_binop_carry:
case ir_binop_borrow:
case ir_binop_mod:
case ir_binop_min:
case ir_binop_max:
case ir_binop_pow:
case ir_binop_lshift:
case ir_binop_rshift:
case ir_binop_bit_and:
case ir_binop_bit_xor:
case ir_binop_bit_or:
case ir_binop_less:
case ir_binop_greater:
case ir_binop_lequal:
case ir_binop_gequal:
case ir_binop_equal:
case ir_binop_nequal:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1));
}
break;
case ir_unop_any: {
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], 0),
get_element(op_var[0], 1));
for (i = 2; i < vector_elements; i++) {
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], i),
temp);
}
assign(ir, 0, temp);
break;
}
case ir_binop_dot: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(ir_binop_add,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_binop_logic_and:
case ir_binop_logic_xor:
case ir_binop_logic_or:
ir->fprint(stderr);
fprintf(stderr, "\n");
unreachable("not reached: expression operates on scalars only");
case ir_binop_all_equal:
case ir_binop_any_nequal: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
ir_expression_operation join;
if (expr->operation == ir_binop_all_equal)
join = ir_binop_logic_and;
else
join = ir_binop_logic_or;
temp = new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(join,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_unop_noise:
unreachable("noise should have been broken down to function call");
case ir_binop_bfm: {
/* Does not need to be scalarized, since its result will be identical
* for all channels.
*/
ir_rvalue *op0 = get_element(op_var[0], 0);
ir_rvalue *op1 = get_element(op_var[1], 0);
assign(ir, 0, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1));
break;
}
case ir_binop_ubo_load:
unreachable("not yet supported");
case ir_triop_fma:
case ir_triop_lrp:
case ir_triop_csel:
case ir_triop_bitfield_extract:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_rvalue *op2 = get_element(op_var[2], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1,
op2));
}
break;
case ir_triop_bfi: {
/* Only a single BFM is needed for multiple BFIs. */
ir_rvalue *op0 = get_element(op_var[0], 0);
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op1 = get_element(op_var[1], i);
ir_rvalue *op2 = get_element(op_var[2], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0->clone(mem_ctx, NULL),
op1,
op2));
}
break;
}
case ir_unop_pack_snorm_2x16:
case ir_unop_pack_snorm_4x8:
case ir_unop_pack_unorm_2x16:
case ir_unop_pack_unorm_4x8:
case ir_unop_pack_half_2x16:
case ir_unop_unpack_snorm_2x16:
case ir_unop_unpack_snorm_4x8:
case ir_unop_unpack_unorm_2x16:
case ir_unop_unpack_unorm_4x8:
case ir_unop_unpack_half_2x16:
case ir_binop_ldexp:
case ir_binop_vector_extract:
case ir_triop_vector_insert:
case ir_quadop_bitfield_insert:
case ir_quadop_vector:
unreachable("should have been lowered");
case ir_unop_unpack_half_2x16_split_x:
case ir_unop_unpack_half_2x16_split_y:
case ir_binop_pack_half_2x16_split:
unreachable("not reached: expression operates on scalars only");
}
ir->remove();
this->progress = true;
return visit_continue;
}
<commit_msg>i965/fs: Skip channel expressions splitting for interpolation<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file brw_wm_channel_expressions.cpp
*
* Breaks vector operations down into operations on each component.
*
* The 965 fragment shader receives 8 or 16 pixels at a time, so each
* channel of a vector is laid out as 1 or 2 8-float registers. Each
* ALU operation operates on one of those channel registers. As a
* result, there is no value to the 965 fragment shader in tracking
* "vector" expressions in the sense of GLSL fragment shaders, when
* doing a channel at a time may help in constant folding, algebraic
* simplification, and reducing the liveness of channel registers.
*
* The exception to the desire to break everything down to floats is
* texturing. The texture sampler returns a writemasked masked
* 4/8-register sequence containing the texture values. We don't want
* to dispatch to the sampler separately for each channel we need, so
* we do retain the vector types in that case.
*/
extern "C" {
#include "main/core.h"
#include "brw_wm.h"
}
#include "glsl/ir.h"
#include "glsl/ir_expression_flattening.h"
#include "glsl/glsl_types.h"
class ir_channel_expressions_visitor : public ir_hierarchical_visitor {
public:
ir_channel_expressions_visitor()
{
this->progress = false;
this->mem_ctx = NULL;
}
ir_visitor_status visit_leave(ir_assignment *);
ir_rvalue *get_element(ir_variable *var, unsigned int element);
void assign(ir_assignment *ir, int elem, ir_rvalue *val);
bool progress;
void *mem_ctx;
};
static bool
channel_expressions_predicate(ir_instruction *ir)
{
ir_expression *expr = ir->as_expression();
unsigned int i;
if (!expr)
return false;
switch (expr->operation) {
/* these opcodes need to act on the whole vector,
* just like texturing.
*/
case ir_unop_interpolate_at_centroid:
case ir_binop_interpolate_at_offset:
case ir_binop_interpolate_at_sample:
return false;
default:
break;
}
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector())
return true;
}
return false;
}
bool
brw_do_channel_expressions(exec_list *instructions)
{
ir_channel_expressions_visitor v;
/* Pull out any matrix expression to a separate assignment to a
* temp. This will make our handling of the breakdown to
* operations on the matrix's vector components much easier.
*/
do_expression_flattening(instructions, channel_expressions_predicate);
visit_list_elements(&v, instructions);
return v.progress;
}
ir_rvalue *
ir_channel_expressions_visitor::get_element(ir_variable *var, unsigned int elem)
{
ir_dereference *deref;
if (var->type->is_scalar())
return new(mem_ctx) ir_dereference_variable(var);
assert(elem < var->type->components());
deref = new(mem_ctx) ir_dereference_variable(var);
return new(mem_ctx) ir_swizzle(deref, elem, 0, 0, 0, 1);
}
void
ir_channel_expressions_visitor::assign(ir_assignment *ir, int elem, ir_rvalue *val)
{
ir_dereference *lhs = ir->lhs->clone(mem_ctx, NULL);
ir_assignment *assign;
/* This assign-of-expression should have been generated by the
* expression flattening visitor (since we never short circit to
* not flatten, even for plain assignments of variables), so the
* writemask is always full.
*/
assert(ir->write_mask == (1 << ir->lhs->type->components()) - 1);
assign = new(mem_ctx) ir_assignment(lhs, val, NULL, (1 << elem));
ir->insert_before(assign);
}
ir_visitor_status
ir_channel_expressions_visitor::visit_leave(ir_assignment *ir)
{
ir_expression *expr = ir->rhs->as_expression();
bool found_vector = false;
unsigned int i, vector_elements = 1;
ir_variable *op_var[3];
if (!expr)
return visit_continue;
if (!this->mem_ctx)
this->mem_ctx = ralloc_parent(ir);
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_vector()) {
found_vector = true;
vector_elements = expr->operands[i]->type->vector_elements;
break;
}
}
if (!found_vector)
return visit_continue;
switch (expr->operation) {
case ir_unop_interpolate_at_centroid:
case ir_binop_interpolate_at_offset:
case ir_binop_interpolate_at_sample:
return visit_continue;
default:
break;
}
/* Store the expression operands in temps so we can use them
* multiple times.
*/
for (i = 0; i < expr->get_num_operands(); i++) {
ir_assignment *assign;
ir_dereference *deref;
assert(!expr->operands[i]->type->is_matrix());
op_var[i] = new(mem_ctx) ir_variable(expr->operands[i]->type,
"channel_expressions",
ir_var_temporary);
ir->insert_before(op_var[i]);
deref = new(mem_ctx) ir_dereference_variable(op_var[i]);
assign = new(mem_ctx) ir_assignment(deref,
expr->operands[i],
NULL);
ir->insert_before(assign);
}
const glsl_type *element_type = glsl_type::get_instance(ir->lhs->type->base_type,
1, 1);
/* OK, time to break down this vector operation. */
switch (expr->operation) {
case ir_unop_bit_not:
case ir_unop_logic_not:
case ir_unop_neg:
case ir_unop_abs:
case ir_unop_sign:
case ir_unop_rcp:
case ir_unop_rsq:
case ir_unop_sqrt:
case ir_unop_exp:
case ir_unop_log:
case ir_unop_exp2:
case ir_unop_log2:
case ir_unop_bitcast_i2f:
case ir_unop_bitcast_f2i:
case ir_unop_bitcast_f2u:
case ir_unop_bitcast_u2f:
case ir_unop_i2u:
case ir_unop_u2i:
case ir_unop_f2i:
case ir_unop_f2u:
case ir_unop_i2f:
case ir_unop_f2b:
case ir_unop_b2f:
case ir_unop_i2b:
case ir_unop_b2i:
case ir_unop_u2f:
case ir_unop_trunc:
case ir_unop_ceil:
case ir_unop_floor:
case ir_unop_fract:
case ir_unop_round_even:
case ir_unop_sin:
case ir_unop_cos:
case ir_unop_sin_reduced:
case ir_unop_cos_reduced:
case ir_unop_dFdx:
case ir_unop_dFdy:
case ir_unop_bitfield_reverse:
case ir_unop_bit_count:
case ir_unop_find_msb:
case ir_unop_find_lsb:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
NULL));
}
break;
case ir_binop_add:
case ir_binop_sub:
case ir_binop_mul:
case ir_binop_imul_high:
case ir_binop_div:
case ir_binop_carry:
case ir_binop_borrow:
case ir_binop_mod:
case ir_binop_min:
case ir_binop_max:
case ir_binop_pow:
case ir_binop_lshift:
case ir_binop_rshift:
case ir_binop_bit_and:
case ir_binop_bit_xor:
case ir_binop_bit_or:
case ir_binop_less:
case ir_binop_greater:
case ir_binop_lequal:
case ir_binop_gequal:
case ir_binop_equal:
case ir_binop_nequal:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1));
}
break;
case ir_unop_any: {
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], 0),
get_element(op_var[0], 1));
for (i = 2; i < vector_elements; i++) {
temp = new(mem_ctx) ir_expression(ir_binop_logic_or,
element_type,
get_element(op_var[0], i),
temp);
}
assign(ir, 0, temp);
break;
}
case ir_binop_dot: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
temp = new(mem_ctx) ir_expression(ir_binop_mul,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(ir_binop_add,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_binop_logic_and:
case ir_binop_logic_xor:
case ir_binop_logic_or:
ir->fprint(stderr);
fprintf(stderr, "\n");
unreachable("not reached: expression operates on scalars only");
case ir_binop_all_equal:
case ir_binop_any_nequal: {
ir_expression *last = NULL;
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_expression *temp;
ir_expression_operation join;
if (expr->operation == ir_binop_all_equal)
join = ir_binop_logic_and;
else
join = ir_binop_logic_or;
temp = new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1);
if (last) {
last = new(mem_ctx) ir_expression(join,
element_type,
temp,
last);
} else {
last = temp;
}
}
assign(ir, 0, last);
break;
}
case ir_unop_noise:
unreachable("noise should have been broken down to function call");
case ir_binop_bfm: {
/* Does not need to be scalarized, since its result will be identical
* for all channels.
*/
ir_rvalue *op0 = get_element(op_var[0], 0);
ir_rvalue *op1 = get_element(op_var[1], 0);
assign(ir, 0, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1));
break;
}
case ir_binop_ubo_load:
unreachable("not yet supported");
case ir_triop_fma:
case ir_triop_lrp:
case ir_triop_csel:
case ir_triop_bitfield_extract:
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op0 = get_element(op_var[0], i);
ir_rvalue *op1 = get_element(op_var[1], i);
ir_rvalue *op2 = get_element(op_var[2], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0,
op1,
op2));
}
break;
case ir_triop_bfi: {
/* Only a single BFM is needed for multiple BFIs. */
ir_rvalue *op0 = get_element(op_var[0], 0);
for (i = 0; i < vector_elements; i++) {
ir_rvalue *op1 = get_element(op_var[1], i);
ir_rvalue *op2 = get_element(op_var[2], i);
assign(ir, i, new(mem_ctx) ir_expression(expr->operation,
element_type,
op0->clone(mem_ctx, NULL),
op1,
op2));
}
break;
}
case ir_unop_pack_snorm_2x16:
case ir_unop_pack_snorm_4x8:
case ir_unop_pack_unorm_2x16:
case ir_unop_pack_unorm_4x8:
case ir_unop_pack_half_2x16:
case ir_unop_unpack_snorm_2x16:
case ir_unop_unpack_snorm_4x8:
case ir_unop_unpack_unorm_2x16:
case ir_unop_unpack_unorm_4x8:
case ir_unop_unpack_half_2x16:
case ir_binop_ldexp:
case ir_binop_vector_extract:
case ir_triop_vector_insert:
case ir_quadop_bitfield_insert:
case ir_quadop_vector:
unreachable("should have been lowered");
case ir_unop_unpack_half_2x16_split_x:
case ir_unop_unpack_half_2x16_split_y:
case ir_binop_pack_half_2x16_split:
case ir_unop_interpolate_at_centroid:
case ir_binop_interpolate_at_offset:
case ir_binop_interpolate_at_sample:
unreachable("not reached: expression operates on scalars only");
}
ir->remove();
this->progress = true;
return visit_continue;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ChainablePropertySetInfo.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-09-08 15:48:49 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COMPHELPER_CHAINABLEPROPERTYSETINFO_HXX_
#include <comphelper/ChainablePropertySetInfo.hxx>
#endif
#ifndef _COMPHELPER_TYPEGENERATION_HXX_
#include <comphelper/TypeGeneration.hxx>
#endif
using ::rtl::OUString;
using ::comphelper::PropertyInfo;
using ::comphelper::GenerateCppuType;
using ::comphelper::ChainablePropertySetInfo;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Type;
using ::com::sun::star::uno::XWeak;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::beans::Property;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::beans::UnknownPropertyException;
ChainablePropertySetInfo::ChainablePropertySetInfo()
throw()
{
}
ChainablePropertySetInfo::ChainablePropertySetInfo( PropertyInfo* pMap )
throw()
{
add ( pMap );
}
ChainablePropertySetInfo::~ChainablePropertySetInfo()
throw()
{
}
//XInterface
Any SAL_CALL ChainablePropertySetInfo::queryInterface( const Type& rType )
throw(RuntimeException)
{
return ::cppu::queryInterface ( rType ,
// OWeakObject interfaces
reinterpret_cast< XInterface* > ( this ) ,
static_cast < XWeak* > ( this ) ,
// my own interfaces
static_cast < XPropertySetInfo* > ( this ) );
}
void SAL_CALL ChainablePropertySetInfo::acquire( )
throw()
{
OWeakObject::acquire();
}
void SAL_CALL ChainablePropertySetInfo::release( )
throw()
{
OWeakObject::release();
}
void ChainablePropertySetInfo::add( PropertyInfo* pMap, sal_Int32 nCount )
throw()
{
// nCount < 0 => add all
// nCount == 0 => add nothing
// nCount > 0 => add at most nCount entries
if( maProperties.getLength() )
maProperties.realloc( 0 );
while( pMap->mpName && ( ( nCount < 0) || ( nCount-- > 0 ) ) )
{
OUString aName( pMap->mpName, pMap->mnNameLen, RTL_TEXTENCODING_ASCII_US );
#ifndef PRODUCT
PropertyInfoHash::iterator aIter = maMap.find( aName );
if( aIter != maMap.end() )
OSL_ENSURE( sal_False, "Warning: PropertyInfo added twice, possible error!");
#endif
maMap[aName] = pMap++;
}
}
void ChainablePropertySetInfo::remove( const rtl::OUString& aName )
throw()
{
maMap.erase ( aName );
if ( maProperties.getLength() )
maProperties.realloc( 0 );
}
Sequence< ::Property > SAL_CALL ChainablePropertySetInfo::getProperties()
throw(::com::sun::star::uno::RuntimeException)
{
sal_Int32 nSize = maMap.size();
if( maProperties.getLength() != nSize )
{
maProperties.realloc ( nSize );
Property* pProperties = maProperties.getArray();
PropertyInfoHash::iterator aIter = maMap.begin();
const PropertyInfoHash::iterator aEnd = maMap.end();
for ( ; aIter != aEnd; ++aIter, ++pProperties)
{
PropertyInfo* pInfo = (*aIter).second;
pProperties->Name = OUString( pInfo->mpName, pInfo->mnNameLen, RTL_TEXTENCODING_ASCII_US );
pProperties->Handle = pInfo->mnHandle;
const Type* pType;
GenerateCppuType ( pInfo->meCppuType, pType);
pProperties->Type = *pType;
pProperties->Attributes = pInfo->mnAttributes;
}
}
return maProperties;
}
Property SAL_CALL ChainablePropertySetInfo::getPropertyByName( const ::rtl::OUString& rName )
throw(::UnknownPropertyException, ::com::sun::star::uno::RuntimeException)
{
PropertyInfoHash::iterator aIter = maMap.find( rName );
if ( maMap.end() == aIter )
throw UnknownPropertyException();
PropertyInfo *pInfo = (*aIter).second;
Property aProperty;
aProperty.Name = OUString( pInfo->mpName, pInfo->mnNameLen, RTL_TEXTENCODING_ASCII_US );
aProperty.Handle = pInfo->mnHandle;
const Type* pType = &aProperty.Type;
GenerateCppuType ( pInfo->meCppuType, pType );
aProperty.Type = *pType;
aProperty.Attributes = pInfo->mnAttributes;
return aProperty;
}
sal_Bool SAL_CALL ChainablePropertySetInfo::hasPropertyByName( const ::rtl::OUString& rName )
throw(::com::sun::star::uno::RuntimeException)
{
return static_cast < sal_Bool > ( maMap.find ( rName ) != maMap.end() );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.118); FILE MERGED 2005/09/05 15:24:07 rt 1.4.118.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChainablePropertySetInfo.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:55:38 $
*
* 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 _COMPHELPER_CHAINABLEPROPERTYSETINFO_HXX_
#include <comphelper/ChainablePropertySetInfo.hxx>
#endif
#ifndef _COMPHELPER_TYPEGENERATION_HXX_
#include <comphelper/TypeGeneration.hxx>
#endif
using ::rtl::OUString;
using ::comphelper::PropertyInfo;
using ::comphelper::GenerateCppuType;
using ::comphelper::ChainablePropertySetInfo;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Type;
using ::com::sun::star::uno::XWeak;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::beans::Property;
using ::com::sun::star::beans::XPropertySetInfo;
using ::com::sun::star::beans::UnknownPropertyException;
ChainablePropertySetInfo::ChainablePropertySetInfo()
throw()
{
}
ChainablePropertySetInfo::ChainablePropertySetInfo( PropertyInfo* pMap )
throw()
{
add ( pMap );
}
ChainablePropertySetInfo::~ChainablePropertySetInfo()
throw()
{
}
//XInterface
Any SAL_CALL ChainablePropertySetInfo::queryInterface( const Type& rType )
throw(RuntimeException)
{
return ::cppu::queryInterface ( rType ,
// OWeakObject interfaces
reinterpret_cast< XInterface* > ( this ) ,
static_cast < XWeak* > ( this ) ,
// my own interfaces
static_cast < XPropertySetInfo* > ( this ) );
}
void SAL_CALL ChainablePropertySetInfo::acquire( )
throw()
{
OWeakObject::acquire();
}
void SAL_CALL ChainablePropertySetInfo::release( )
throw()
{
OWeakObject::release();
}
void ChainablePropertySetInfo::add( PropertyInfo* pMap, sal_Int32 nCount )
throw()
{
// nCount < 0 => add all
// nCount == 0 => add nothing
// nCount > 0 => add at most nCount entries
if( maProperties.getLength() )
maProperties.realloc( 0 );
while( pMap->mpName && ( ( nCount < 0) || ( nCount-- > 0 ) ) )
{
OUString aName( pMap->mpName, pMap->mnNameLen, RTL_TEXTENCODING_ASCII_US );
#ifndef PRODUCT
PropertyInfoHash::iterator aIter = maMap.find( aName );
if( aIter != maMap.end() )
OSL_ENSURE( sal_False, "Warning: PropertyInfo added twice, possible error!");
#endif
maMap[aName] = pMap++;
}
}
void ChainablePropertySetInfo::remove( const rtl::OUString& aName )
throw()
{
maMap.erase ( aName );
if ( maProperties.getLength() )
maProperties.realloc( 0 );
}
Sequence< ::Property > SAL_CALL ChainablePropertySetInfo::getProperties()
throw(::com::sun::star::uno::RuntimeException)
{
sal_Int32 nSize = maMap.size();
if( maProperties.getLength() != nSize )
{
maProperties.realloc ( nSize );
Property* pProperties = maProperties.getArray();
PropertyInfoHash::iterator aIter = maMap.begin();
const PropertyInfoHash::iterator aEnd = maMap.end();
for ( ; aIter != aEnd; ++aIter, ++pProperties)
{
PropertyInfo* pInfo = (*aIter).second;
pProperties->Name = OUString( pInfo->mpName, pInfo->mnNameLen, RTL_TEXTENCODING_ASCII_US );
pProperties->Handle = pInfo->mnHandle;
const Type* pType;
GenerateCppuType ( pInfo->meCppuType, pType);
pProperties->Type = *pType;
pProperties->Attributes = pInfo->mnAttributes;
}
}
return maProperties;
}
Property SAL_CALL ChainablePropertySetInfo::getPropertyByName( const ::rtl::OUString& rName )
throw(::UnknownPropertyException, ::com::sun::star::uno::RuntimeException)
{
PropertyInfoHash::iterator aIter = maMap.find( rName );
if ( maMap.end() == aIter )
throw UnknownPropertyException();
PropertyInfo *pInfo = (*aIter).second;
Property aProperty;
aProperty.Name = OUString( pInfo->mpName, pInfo->mnNameLen, RTL_TEXTENCODING_ASCII_US );
aProperty.Handle = pInfo->mnHandle;
const Type* pType = &aProperty.Type;
GenerateCppuType ( pInfo->meCppuType, pType );
aProperty.Type = *pType;
aProperty.Attributes = pInfo->mnAttributes;
return aProperty;
}
sal_Bool SAL_CALL ChainablePropertySetInfo::hasPropertyByName( const ::rtl::OUString& rName )
throw(::com::sun::star::uno::RuntimeException)
{
return static_cast < sal_Bool > ( maMap.find ( rName ) != maMap.end() );
}
<|endoftext|> |
<commit_before>// @(#)root/proofplayer:$Id$
// Author: Long Tran-Thanh 22/07/07
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPacketizerUnit //
// //
// This packetizer generates packets of generic units, representing the //
// number of times an operation cycle has to be repeated by the worker //
// node, e.g. the number of Monte carlo events to be generated. //
// Packets sizes are generated taking into account the performance of //
// worker nodes, based on the time needed to process previous packets. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPacketizerUnit.h"
#include "Riostream.h"
#include "TDSet.h"
#include "TError.h"
#include "TEventList.h"
#include "TMap.h"
#include "TMessage.h"
#include "TMonitor.h"
#include "TNtupleD.h"
#include "TObject.h"
#include "TParameter.h"
#include "TPerfStats.h"
#include "TProofDebug.h"
#include "TProof.h"
#include "TProofPlayer.h"
#include "TProofServ.h"
#include "TSlave.h"
#include "TSocket.h"
#include "TStopwatch.h"
#include "TTimer.h"
#include "TUrl.h"
#include "TClass.h"
#include "TMath.h"
#include "TObjString.h"
using namespace TMath;
//
// The following utility class manage the state of the
// work to be performed and the slaves involved in the process.
//
// The list of TSlaveStat(s) keep track of the work (being) done
// by each slave
//
//------------------------------------------------------------------------------
class TPacketizerUnit::TSlaveStat : public TVirtualPacketizer::TVirtualSlaveStat {
friend class TPacketizerUnit;
private:
Long64_t fLastProcessed; // number of processed entries of the last packet
Double_t fSpeed; // estimated current average speed of the processing slave
Double_t fTimeInstant; // stores the time instant when the current packet started
TNtupleD *fCircNtp; // Keeps circular info for speed calculations
Long_t fCircLvl; // Circularity level
public:
TSlaveStat(TSlave *sl, TList *input);
~TSlaveStat();
void GetCurrentTime();
const char *GetName() const { return fSlave->GetName(); }
void UpdatePerformance(Double_t time);
TProofProgressStatus *AddProcessed(TProofProgressStatus *st);
};
//______________________________________________________________________________
TPacketizerUnit::TSlaveStat::TSlaveStat(TSlave *slave, TList *input)
: fLastProcessed(0),
fSpeed(0), fTimeInstant(0), fCircLvl(5)
{
// Main constructor
// Initialize the circularity ntple for speed calculations
fCircNtp = new TNtupleD("Speed Circ Ntp", "Circular process info","tm:ev");
TProof::GetParameter(input, "PROOF_TPacketizerUnitCircularity", fCircLvl);
fCircLvl = (fCircLvl > 0) ? fCircLvl : 5;
fCircNtp->SetCircular(fCircLvl);
fSlave = slave;
fStatus = new TProofProgressStatus();
}
//______________________________________________________________________________
TPacketizerUnit::TSlaveStat::~TSlaveStat()
{
// Destructor
SafeDelete(fCircNtp);
}
//______________________________________________________________________________
void TPacketizerUnit::TSlaveStat::UpdatePerformance(Double_t time)
{
// Update the circular ntple
Double_t ttot = time;
Double_t *ar = fCircNtp->GetArgs();
Int_t ne = fCircNtp->GetEntries();
if (ne <= 0) {
// First call: just fill one ref entry and return
fCircNtp->Fill(0., 0);
fSpeed = 0.;
return;
}
// Fill the entry
fCircNtp->GetEntry(ne-1);
ttot = ar[0] + time;
fCircNtp->Fill(ttot, GetEntriesProcessed());
// Calculate the speed
fCircNtp->GetEntry(0);
Double_t dtime = (ttot > ar[0]) ? ttot - ar[0] : ne+1 ;
Long64_t nevts = GetEntriesProcessed() - (Long64_t)ar[1];
fSpeed = nevts / dtime;
PDB(kPacketizer,2)
Info("UpdatePerformance", "time:%f, dtime:%f, nevts:%lld, speed: %f",
time, dtime, nevts, fSpeed);
}
//______________________________________________________________________________
TProofProgressStatus *TPacketizerUnit::TSlaveStat::AddProcessed(TProofProgressStatus *st)
{
// Update the status info to the 'st'.
// return the difference (*st - *fStatus)
if (st) {
TProofProgressStatus *diff = new TProofProgressStatus(*st - *fStatus);
*fStatus += *diff;
return diff;
} else {
Error("AddProcessed", "status arg undefined");
return 0;
}
}
//------------------------------------------------------------------------------
ClassImp(TPacketizerUnit)
//______________________________________________________________________________
TPacketizerUnit::TPacketizerUnit(TList *slaves, Long64_t num, TList *input,
TProofProgressStatus *st)
: TVirtualPacketizer(input, st)
{
// Constructor
PDB(kPacketizer,1) Info("TPacketizerUnit", "enter (num %lld)", num);
// Init pointer members
fSlaveStats = 0;
fPackets = 0;
fTimeLimit = 1;
TProof::GetParameter(input, "PROOF_PacketizerTimeLimit", fTimeLimit);
PDB(kPacketizer,1)
Info("TPacketizerUnit", "time limit is %lf", fTimeLimit);
fProcessing = 0;
fAssigned = 0;
fStopwatch = new TStopwatch();
fPackets = new TList;
fPackets->SetOwner();
fSlaveStats = new TMap;
fSlaveStats->SetOwner(kFALSE);
TSlave *slave;
TIter si(slaves);
while ((slave = (TSlave*) si.Next()))
fSlaveStats->Add(slave, new TSlaveStat(slave, input));
fTotalEntries = num;
fStopwatch->Start();
PDB(kPacketizer,1) Info("TPacketizerUnit", "return");
}
//______________________________________________________________________________
TPacketizerUnit::~TPacketizerUnit()
{
// Destructor.
if (fSlaveStats)
fSlaveStats->DeleteValues();
SafeDelete(fSlaveStats);
SafeDelete(fPackets);
SafeDelete(fStopwatch);
}
//______________________________________________________________________________
Double_t TPacketizerUnit::GetCurrentTime()
{
// Get current time
Double_t retValue = fStopwatch->RealTime();
fStopwatch->Continue();
return retValue;
}
//______________________________________________________________________________
TDSetElement *TPacketizerUnit::GetNextPacket(TSlave *sl, TMessage *r)
{
// Get next packet
if (!fValid)
return 0;
// Find slave
TSlaveStat *slstat = (TSlaveStat*) fSlaveStats->GetValue(sl);
R__ASSERT(slstat != 0);
// Update stats & free old element
Double_t latency, proctime, proccpu;
Long64_t bytesRead = -1;
Long64_t totalEntries = -1; // used only to read an old message type
Long64_t totev = 0;
Long64_t numev = -1;
TProofProgressStatus *status = 0;
if (!gProofServ || gProofServ->GetProtocol() > 18) {
(*r) >> latency;
(*r) >> status;
// Calculate the progress made in the last packet
TProofProgressStatus *progress = 0;
if (status) {
// upadte the worker status
numev = status->GetEntries() - slstat->GetEntriesProcessed();
progress = slstat->AddProcessed(status);
if (progress) {
// (*fProgressStatus) += *progress;
proctime = progress->GetProcTime();
proccpu = progress->GetCPUTime();
totev = status->GetEntries(); // for backward compatibility
bytesRead = progress->GetBytesRead();
delete progress;
}
delete status;
} else
Error("GetNextPacket", "no status came in the kPROOF_GETPACKET message");
} else {
(*r) >> latency >> proctime >> proccpu;
// only read new info if available
if (r->BufferSize() > r->Length()) (*r) >> bytesRead;
if (r->BufferSize() > r->Length()) (*r) >> totalEntries;
if (r->BufferSize() > r->Length()) (*r) >> totev;
numev = totev - slstat->GetEntriesProcessed();
slstat->GetProgressStatus()->IncEntries(numev);
}
fProgressStatus->IncEntries(numev);
PDB(kPacketizer,2)
Info("GetNextPacket","worker-%s: fAssigned %lld\t", sl->GetOrdinal(), fAssigned);
fProcessing = 0;
PDB(kPacketizer,2)
Info("GetNextPacket","worker-%s (%s): %lld %7.3lf %7.3lf %7.3lf %lld",
sl->GetOrdinal(), sl->GetName(),
numev, latency, proctime, proccpu, bytesRead);
if (gPerfStats != 0) {
gPerfStats->PacketEvent(sl->GetOrdinal(), sl->GetName(), "", numev,
latency, proctime, proccpu, bytesRead);
}
if (fAssigned == fTotalEntries) {
// Send last timer message
HandleTimer(0);
SafeDelete(fProgress);
}
if (fStop) {
// Send last timer message
HandleTimer(0);
return 0;
}
Long64_t num;
// Get the current time
Double_t cTime = GetCurrentTime();
if (slstat->fCircNtp->GetEntries() <= 0) {
// The calibration phase
PDB(kPacketizer,2) Info("GetNextPacket"," calibration: "
"total entries %lld, workers %d",
fTotalEntries, fSlaveStats->GetSize());
Long64_t avg = fTotalEntries/(fSlaveStats->GetSize());
num = (avg > 5) ? 5 : avg;
// Create a reference entry
slstat->UpdatePerformance(0.);
} else {
// Schedule tasks for workers based on the currently estimated processing speeds
// Update performances
// slstat->fStatus was updated before;
slstat->UpdatePerformance(proctime);
TMapIter *iter = (TMapIter *)fSlaveStats->MakeIterator();
TSlave * tmpSlave;
TSlaveStat * tmpStat;
Double_t sumSpeed = 0;
Double_t sumBusy = 0;
// The basic idea is to estimate the optimal finishing time for the process, assuming
// that the currently measured processing speeds of the slaves remain the same in the future.
// The optTime can be calculated as follows.
// Let s_i be the speed of worker i. We assume that worker i will be busy in the
// next b_i time instant. Therefore we have the following equation:
// SUM((optTime-b_i)*s_i) = (remaining_entries),
// Hence optTime can be calculated easily:
// optTime = ((remaining_entries) + SUM(b_i*s_i))/SUM(s_i)
while ((tmpSlave = (TSlave *)iter->Next())) {
tmpStat = (TSlaveStat *)fSlaveStats->GetValue(tmpSlave);
// If the slave doesn't response for a long time, its service rate will be considered as 0
if ((cTime - tmpStat->fTimeInstant) > 4*fTimeLimit)
tmpStat->fSpeed = 0;
PDB(kPacketizer,2)
Info("GetNextPacket",
"worker-%s: speed %lf", tmpSlave->GetOrdinal(), tmpStat->fSpeed);
if (tmpStat->fSpeed > 0) {
// Calculating the SUM(s_i)
sumSpeed += tmpStat->fSpeed;
// There is nothing to do if slave_i is not calibrated or slave i is the current slave
if ((tmpStat->fTimeInstant) && (cTime - tmpStat->fTimeInstant > 0)) {
// Calculating the SUM(b_i*s_i)
// s_i = tmpStat->fSpeed
// b_i = tmpStat->fTimeInstant + tmpStat->fLastProcessed/s_i - cTime)
// b_i*s_i = (tmpStat->fTimeInstant - cTime)*s_i + tmpStat->fLastProcessed
Double_t busyspeed =
((tmpStat->fTimeInstant - cTime)*tmpStat->fSpeed + tmpStat->fLastProcessed);
if (busyspeed > 0)
sumBusy += busyspeed;
}
}
}
PDB(kPacketizer,2)
Info("GetNextPacket", "worker-%s: sum speed: %lf, sum busy: %f",
sl->GetOrdinal(), sumSpeed, sumBusy);
// firstly the slave will try to get all of the remaining entries
if (slstat->fSpeed > 0 &&
(fTotalEntries - fAssigned)/(slstat->fSpeed) < fTimeLimit) {
num = (fTotalEntries - fAssigned);
} else {
if (slstat->fSpeed > 0) {
// calculating the optTime
Double_t optTime = (fTotalEntries - fAssigned + sumBusy)/sumSpeed;
// if optTime is greater than the official time limit, then the slave gets a number
// of entries that still fit into the time limit, otherwise it uses the optTime as
// a time limit
num = (optTime > fTimeLimit) ? Nint(fTimeLimit*(slstat->fSpeed))
: Nint(optTime*(slstat->fSpeed));
PDB(kPacketizer,2)
Info("GetNextPacket", "opTime %lf num %lld speed %lf", optTime, num, slstat->fSpeed);
} else {
Long64_t avg = fTotalEntries/(fSlaveStats->GetSize());
num = (avg > 5) ? 5 : avg;
}
}
}
// Minimum packet size
num = (num > 1) ? num : 1;
fProcessing = (num < (fTotalEntries - fAssigned)) ? num
: (fTotalEntries - fAssigned);
// Set the informations of the current slave
slstat->fLastProcessed = fProcessing;
// Set the start time of the current packet
slstat->fTimeInstant = cTime;
PDB(kPacketizer,2)
Info("GetNextPacket", "worker-%s: num %lld, processing %lld, remaining %lld",sl->GetOrdinal(),
num, fProcessing, (fTotalEntries - fAssigned - fProcessing));
TDSetElement *elem = new TDSetElement("", "", "", 0, fProcessing);
elem->SetBit(TDSetElement::kEmpty);
// Update the total counter
fAssigned += slstat->fLastProcessed;
return elem;
}
<commit_msg><commit_after>// @(#)root/proofplayer:$Id$
// Author: Long Tran-Thanh 22/07/07
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPacketizerUnit //
// //
// This packetizer generates packets of generic units, representing the //
// number of times an operation cycle has to be repeated by the worker //
// node, e.g. the number of Monte carlo events to be generated. //
// Packets sizes are generated taking into account the performance of //
// worker nodes, based on the time needed to process previous packets. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPacketizerUnit.h"
#include "Riostream.h"
#include "TDSet.h"
#include "TError.h"
#include "TEventList.h"
#include "TMap.h"
#include "TMessage.h"
#include "TMonitor.h"
#include "TNtupleD.h"
#include "TObject.h"
#include "TParameter.h"
#include "TPerfStats.h"
#include "TProofDebug.h"
#include "TProof.h"
#include "TProofPlayer.h"
#include "TProofServ.h"
#include "TSlave.h"
#include "TSocket.h"
#include "TStopwatch.h"
#include "TTimer.h"
#include "TUrl.h"
#include "TClass.h"
#include "TMath.h"
#include "TObjString.h"
using namespace TMath;
//
// The following utility class manage the state of the
// work to be performed and the slaves involved in the process.
//
// The list of TSlaveStat(s) keep track of the work (being) done
// by each slave
//
//------------------------------------------------------------------------------
class TPacketizerUnit::TSlaveStat : public TVirtualPacketizer::TVirtualSlaveStat {
friend class TPacketizerUnit;
private:
Long64_t fLastProcessed; // number of processed entries of the last packet
Double_t fSpeed; // estimated current average speed of the processing slave
Double_t fTimeInstant; // stores the time instant when the current packet started
TNtupleD *fCircNtp; // Keeps circular info for speed calculations
Long_t fCircLvl; // Circularity level
public:
TSlaveStat(TSlave *sl, TList *input);
~TSlaveStat();
void GetCurrentTime();
const char *GetName() const { return fSlave->GetName(); }
void UpdatePerformance(Double_t time);
TProofProgressStatus *AddProcessed(TProofProgressStatus *st);
};
//______________________________________________________________________________
TPacketizerUnit::TSlaveStat::TSlaveStat(TSlave *slave, TList *input)
: fLastProcessed(0),
fSpeed(0), fTimeInstant(0), fCircLvl(5)
{
// Main constructor
// Initialize the circularity ntple for speed calculations
fCircNtp = new TNtupleD("Speed Circ Ntp", "Circular process info","tm:ev");
TProof::GetParameter(input, "PROOF_TPacketizerUnitCircularity", fCircLvl);
fCircLvl = (fCircLvl > 0) ? fCircLvl : 5;
fCircNtp->SetCircular(fCircLvl);
fSlave = slave;
fStatus = new TProofProgressStatus();
}
//______________________________________________________________________________
TPacketizerUnit::TSlaveStat::~TSlaveStat()
{
// Destructor
SafeDelete(fCircNtp);
}
//______________________________________________________________________________
void TPacketizerUnit::TSlaveStat::UpdatePerformance(Double_t time)
{
// Update the circular ntple
Double_t ttot = time;
Double_t *ar = fCircNtp->GetArgs();
Int_t ne = fCircNtp->GetEntries();
if (ne <= 0) {
// First call: just fill one ref entry and return
fCircNtp->Fill(0., 0);
fSpeed = 0.;
return;
}
// Fill the entry
fCircNtp->GetEntry(ne-1);
ttot = ar[0] + time;
fCircNtp->Fill(ttot, GetEntriesProcessed());
// Calculate the speed
fCircNtp->GetEntry(0);
Double_t dtime = (ttot > ar[0]) ? ttot - ar[0] : ne+1 ;
Long64_t nevts = GetEntriesProcessed() - (Long64_t)ar[1];
fSpeed = nevts / dtime;
PDB(kPacketizer,2)
Info("UpdatePerformance", "time:%f, dtime:%f, nevts:%lld, speed: %f",
time, dtime, nevts, fSpeed);
}
//______________________________________________________________________________
TProofProgressStatus *TPacketizerUnit::TSlaveStat::AddProcessed(TProofProgressStatus *st)
{
// Update the status info to the 'st'.
// return the difference (*st - *fStatus)
if (st) {
TProofProgressStatus *diff = new TProofProgressStatus(*st - *fStatus);
*fStatus += *diff;
return diff;
} else {
Error("AddProcessed", "status arg undefined");
return 0;
}
}
//------------------------------------------------------------------------------
ClassImp(TPacketizerUnit)
//______________________________________________________________________________
TPacketizerUnit::TPacketizerUnit(TList *slaves, Long64_t num, TList *input,
TProofProgressStatus *st)
: TVirtualPacketizer(input, st)
{
// Constructor
PDB(kPacketizer,1) Info("TPacketizerUnit", "enter (num %lld)", num);
// Init pointer members
fSlaveStats = 0;
fPackets = 0;
fTimeLimit = 1;
TProof::GetParameter(input, "PROOF_PacketizerTimeLimit", fTimeLimit);
PDB(kPacketizer,1)
Info("TPacketizerUnit", "time limit is %lf", fTimeLimit);
fProcessing = 0;
fAssigned = 0;
fStopwatch = new TStopwatch();
fPackets = new TList;
fPackets->SetOwner();
fSlaveStats = new TMap;
fSlaveStats->SetOwner(kFALSE);
TSlave *slave;
TIter si(slaves);
while ((slave = (TSlave*) si.Next()))
fSlaveStats->Add(slave, new TSlaveStat(slave, input));
fTotalEntries = num;
fStopwatch->Start();
PDB(kPacketizer,1) Info("TPacketizerUnit", "return");
}
//______________________________________________________________________________
TPacketizerUnit::~TPacketizerUnit()
{
// Destructor.
if (fSlaveStats)
fSlaveStats->DeleteValues();
SafeDelete(fSlaveStats);
SafeDelete(fPackets);
SafeDelete(fStopwatch);
}
//______________________________________________________________________________
Double_t TPacketizerUnit::GetCurrentTime()
{
// Get current time
Double_t retValue = fStopwatch->RealTime();
fStopwatch->Continue();
return retValue;
}
//______________________________________________________________________________
TDSetElement *TPacketizerUnit::GetNextPacket(TSlave *sl, TMessage *r)
{
// Get next packet
if (!fValid)
return 0;
// Find slave
TSlaveStat *slstat = (TSlaveStat*) fSlaveStats->GetValue(sl);
R__ASSERT(slstat != 0);
PDB(kPacketizer,2)
Info("GetNextPacket","worker-%s: fAssigned %lld\t", sl->GetOrdinal(), fAssigned);
// Update stats & free old element
Double_t latency, proctime, proccpu;
Long64_t bytesRead = -1;
Long64_t totalEntries = -1; // used only to read an old message type
Long64_t totev = 0;
Long64_t numev = -1;
TProofProgressStatus *status = 0;
if (!gProofServ || gProofServ->GetProtocol() > 18) {
(*r) >> latency;
(*r) >> status;
// Calculate the progress made in the last packet
TProofProgressStatus *progress = 0;
if (status) {
// upadte the worker status
numev = status->GetEntries() - slstat->GetEntriesProcessed();
progress = slstat->AddProcessed(status);
if (progress) {
// (*fProgressStatus) += *progress;
proctime = progress->GetProcTime();
proccpu = progress->GetCPUTime();
totev = status->GetEntries(); // for backward compatibility
bytesRead = progress->GetBytesRead();
delete progress;
}
delete status;
} else
Error("GetNextPacket", "no status came in the kPROOF_GETPACKET message");
} else {
(*r) >> latency >> proctime >> proccpu;
// only read new info if available
if (r->BufferSize() > r->Length()) (*r) >> bytesRead;
if (r->BufferSize() > r->Length()) (*r) >> totalEntries;
if (r->BufferSize() > r->Length()) (*r) >> totev;
numev = totev - slstat->GetEntriesProcessed();
slstat->GetProgressStatus()->IncEntries(numev);
}
fProgressStatus->IncEntries(numev);
fProcessing = 0;
PDB(kPacketizer,2)
Info("GetNextPacket","worker-%s (%s): %lld %7.3lf %7.3lf %7.3lf %lld",
sl->GetOrdinal(), sl->GetName(),
numev, latency, proctime, proccpu, bytesRead);
if (gPerfStats != 0) {
gPerfStats->PacketEvent(sl->GetOrdinal(), sl->GetName(), "", numev,
latency, proctime, proccpu, bytesRead);
}
if (fAssigned == fTotalEntries) {
// Send last timer message
HandleTimer(0);
return 0;
}
if (fStop) {
// Send last timer message
HandleTimer(0);
return 0;
}
Long64_t num;
// Get the current time
Double_t cTime = GetCurrentTime();
if (slstat->fCircNtp->GetEntries() <= 0) {
// The calibration phase
PDB(kPacketizer,2) Info("GetNextPacket"," calibration: "
"total entries %lld, workers %d",
fTotalEntries, fSlaveStats->GetSize());
Long64_t avg = fTotalEntries/(fSlaveStats->GetSize());
num = (avg > 5) ? 5 : avg;
// Create a reference entry
slstat->UpdatePerformance(0.);
} else {
// Schedule tasks for workers based on the currently estimated processing speeds
// Update performances
// slstat->fStatus was updated before;
slstat->UpdatePerformance(proctime);
TMapIter *iter = (TMapIter *)fSlaveStats->MakeIterator();
TSlave * tmpSlave;
TSlaveStat * tmpStat;
Double_t sumSpeed = 0;
Double_t sumBusy = 0;
// The basic idea is to estimate the optimal finishing time for the process, assuming
// that the currently measured processing speeds of the slaves remain the same in the future.
// The optTime can be calculated as follows.
// Let s_i be the speed of worker i. We assume that worker i will be busy in the
// next b_i time instant. Therefore we have the following equation:
// SUM((optTime-b_i)*s_i) = (remaining_entries),
// Hence optTime can be calculated easily:
// optTime = ((remaining_entries) + SUM(b_i*s_i))/SUM(s_i)
while ((tmpSlave = (TSlave *)iter->Next())) {
tmpStat = (TSlaveStat *)fSlaveStats->GetValue(tmpSlave);
// If the slave doesn't response for a long time, its service rate will be considered as 0
if ((cTime - tmpStat->fTimeInstant) > 4*fTimeLimit)
tmpStat->fSpeed = 0;
PDB(kPacketizer,2)
Info("GetNextPacket",
"worker-%s: speed %lf", tmpSlave->GetOrdinal(), tmpStat->fSpeed);
if (tmpStat->fSpeed > 0) {
// Calculating the SUM(s_i)
sumSpeed += tmpStat->fSpeed;
// There is nothing to do if slave_i is not calibrated or slave i is the current slave
if ((tmpStat->fTimeInstant) && (cTime - tmpStat->fTimeInstant > 0)) {
// Calculating the SUM(b_i*s_i)
// s_i = tmpStat->fSpeed
// b_i = tmpStat->fTimeInstant + tmpStat->fLastProcessed/s_i - cTime)
// b_i*s_i = (tmpStat->fTimeInstant - cTime)*s_i + tmpStat->fLastProcessed
Double_t busyspeed =
((tmpStat->fTimeInstant - cTime)*tmpStat->fSpeed + tmpStat->fLastProcessed);
if (busyspeed > 0)
sumBusy += busyspeed;
}
}
}
PDB(kPacketizer,2)
Info("GetNextPacket", "worker-%s: sum speed: %lf, sum busy: %f",
sl->GetOrdinal(), sumSpeed, sumBusy);
// firstly the slave will try to get all of the remaining entries
if (slstat->fSpeed > 0 &&
(fTotalEntries - fAssigned)/(slstat->fSpeed) < fTimeLimit) {
num = (fTotalEntries - fAssigned);
} else {
if (slstat->fSpeed > 0) {
// calculating the optTime
Double_t optTime = (fTotalEntries - fAssigned + sumBusy)/sumSpeed;
// if optTime is greater than the official time limit, then the slave gets a number
// of entries that still fit into the time limit, otherwise it uses the optTime as
// a time limit
num = (optTime > fTimeLimit) ? Nint(fTimeLimit*(slstat->fSpeed))
: Nint(optTime*(slstat->fSpeed));
PDB(kPacketizer,2)
Info("GetNextPacket", "opTime %lf num %lld speed %lf", optTime, num, slstat->fSpeed);
} else {
Long64_t avg = fTotalEntries/(fSlaveStats->GetSize());
num = (avg > 5) ? 5 : avg;
}
}
}
// Minimum packet size
num = (num > 1) ? num : 1;
fProcessing = (num < (fTotalEntries - fAssigned)) ? num
: (fTotalEntries - fAssigned);
// Set the informations of the current slave
slstat->fLastProcessed = fProcessing;
// Set the start time of the current packet
slstat->fTimeInstant = cTime;
PDB(kPacketizer,2)
Info("GetNextPacket", "worker-%s: num %lld, processing %lld, remaining %lld",sl->GetOrdinal(),
num, fProcessing, (fTotalEntries - fAssigned - fProcessing));
TDSetElement *elem = new TDSetElement("", "", "", 0, fProcessing);
elem->SetBit(TDSetElement::kEmpty);
// Update the total counter
fAssigned += slstat->fLastProcessed;
return elem;
}
<|endoftext|> |
<commit_before>//Author: Julian Yi
//Date Created: 7 August 2017
//File Description: c++ code for the king.
//Fun Fact: Simon Kim is now Simon King
#include <iostream>
#include <string>
#include "king.h"
King::King(coord pos) : Pieces()
{
type = PieceType::King;
position = pos;
}
coordList King::calculateMoves(coord boundary, const squareGrid& square) const
{
coordList validMoves;
// Create a vector of coords representing the moves of a king.
// The king can move diagonally and orthogonally.
coordList moves = {
// Diagonal unit vectors.
{ 1, 1 },{ 1, -1 },{ -1, 1 },{ -1, -1 },
// Orthogonal unit vectors.
{ 0, 1 },{ 0, -1 },{ 1, 0 },{ -1, 0 },
};
for (auto& move : moves)
{
coord newPos = position + move;
validMoves.push_back(newPos);
newPos = newPos + move;
}
return validMoves;
}
<commit_msg>Removed uneeded line.<commit_after>//Author: Julian Yi
//Date Created: 7 August 2017
//File Description: c++ code for the king.
//Fun Fact: Simon Kim is now Simon King
#include <iostream>
#include <string>
#include "king.h"
King::King(coord pos) : Pieces()
{
type = PieceType::King;
position = pos;
}
coordList King::calculateMoves(coord boundary, const squareGrid& square) const
{
coordList validMoves;
// Create a vector of coords representing the moves of a king.
// The king can move diagonally and orthogonally.
coordList moves = {
// Diagonal unit vectors.
{ 1, 1 },{ 1, -1 },{ -1, 1 },{ -1, -1 },
// Orthogonal unit vectors.
{ 0, 1 },{ 0, -1 },{ 1, 0 },{ -1, 0 },
};
for (auto& move : moves)
{
coord newPos = position + move;
validMoves.push_back(newPos);
}
return validMoves;
}
<|endoftext|> |
<commit_before>#include <sys/socket.h>
#include "utils.h"
#include "cJSON.h"
#include "client_http.h"
//
// Xapian http client
//
HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)
{
parser.data = this;
http_parser_init(&parser, HTTP_REQUEST);
LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, ++total_clients);
}
HttpClient::~HttpClient()
{
total_clients--;
}
void HttpClient::on_read(const char *buf, ssize_t received)
{
size_t parsed = http_parser_execute(&parser, &settings, buf, received);
if (parsed == received) {
if (parser.state == 1 || parser.state == 18) { // dead or message_complete
try {
// LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
// LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
// LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());
std::string content;
cJSON *json = cJSON_Parse(body.c_str());
cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;
cJSON *root = cJSON_CreateObject();
cJSON *response = cJSON_CreateObject();
cJSON_AddItemToObject(root, "response", response);
if (text) {
cJSON_AddStringToObject(response, "status", "OK");
cJSON_AddStringToObject(response, "query", text->valuestring);
cJSON_AddStringToObject(response, "title", "The title");
cJSON_AddNumberToObject(response, "items", 7);
const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
cJSON *results = cJSON_CreateArray();
cJSON_AddItemToObject(response, "results", results);
for (int i = 0; i < 7; i++) {
cJSON *result = cJSON_CreateObject();
cJSON_AddNumberToObject(result, "id", i);
cJSON_AddStringToObject(result, "name", strings[i]);
cJSON_AddItemToArray(results, result);
}
} else {
LOG_HTTP_PROTO("Error before: [%s]\n", cJSON_GetErrorPtr());
cJSON_AddStringToObject(response, "status", "ERROR");
cJSON_AddStringToObject(response, "message", cJSON_GetErrorPtr());
}
cJSON_Delete(json);
char *out = cJSON_Print(root);
content = out;
cJSON_Delete(root);
free(out);
char tmp[20];
std::string http_response;
http_response += "HTTP/";
sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
http_response += tmp;
http_response += " 200 OK\r\n";
http_response += "Content-Type: application/json\r\n";
http_response += "Content-Length: ";
sprintf(tmp, "%ld", content.size());
http_response += tmp;
http_response += "\r\n";
write(http_response + "\r\n" + content);
if (parser.state == 1) close();
} catch (...) {
LOG_ERR(this, "ERROR!\n");
}
}
} else {
enum http_errno err = HTTP_PARSER_ERRNO(&parser);
const char *desc = http_errno_description(err);
const char *msg = err != HPE_OK ? desc : "incomplete request";
LOG_HTTP_PROTO(this, msg);
// Handle error. Just close the connection.
destroy();
}
}
//
// HTTP parser callbacks.
//
const http_parser_settings HttpClient::settings = {
.on_message_begin = HttpClient::on_info,
.on_url = HttpClient::on_data,
.on_status = HttpClient::on_data,
.on_header_field = HttpClient::on_data,
.on_header_value = HttpClient::on_data,
.on_headers_complete = HttpClient::on_info,
.on_body = HttpClient::on_data,
.on_message_complete = HttpClient::on_info
};
int HttpClient::on_info(http_parser* p) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);
switch (p->state) {
case 18: // message_complete
break;
case 19: // message_begin
self->path.clear();
self->body.clear();
break;
}
return 0;
}
int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());
switch (p->state) {
case 32: // path
self->path = std::string(at, length);
break;
case 62: // data
self->body = std::string(at, length);
break;
}
return 0;
}
<commit_msg>Unformatted json returned<commit_after>#include <sys/socket.h>
#include "utils.h"
#include "cJSON.h"
#include "client_http.h"
//
// Xapian http client
//
HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)
{
parser.data = this;
http_parser_init(&parser, HTTP_REQUEST);
LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, ++total_clients);
}
HttpClient::~HttpClient()
{
total_clients--;
}
void HttpClient::on_read(const char *buf, ssize_t received)
{
size_t parsed = http_parser_execute(&parser, &settings, buf, received);
if (parsed == received) {
if (parser.state == 1 || parser.state == 18) { // dead or message_complete
try {
// LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
// LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
// LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());
std::string content;
cJSON *json = cJSON_Parse(body.c_str());
cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;
cJSON *root = cJSON_CreateObject();
cJSON *response = cJSON_CreateObject();
cJSON_AddItemToObject(root, "response", response);
if (text) {
cJSON_AddStringToObject(response, "status", "OK");
cJSON_AddStringToObject(response, "query", text->valuestring);
cJSON_AddStringToObject(response, "title", "The title");
cJSON_AddNumberToObject(response, "items", 7);
const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
cJSON *results = cJSON_CreateArray();
cJSON_AddItemToObject(response, "results", results);
for (int i = 0; i < 7; i++) {
cJSON *result = cJSON_CreateObject();
cJSON_AddNumberToObject(result, "id", i);
cJSON_AddStringToObject(result, "name", strings[i]);
cJSON_AddItemToArray(results, result);
}
} else {
LOG_HTTP_PROTO("Error before: [%s]\n", cJSON_GetErrorPtr());
cJSON_AddStringToObject(response, "status", "ERROR");
cJSON_AddStringToObject(response, "message", cJSON_GetErrorPtr());
}
cJSON_Delete(json);
bool pretty = false;
char *out;
if (pretty) {
out = cJSON_Print(root);
} else {
out = cJSON_PrintUnformatted(root);
}
content = out;
cJSON_Delete(root);
free(out);
char tmp[20];
std::string http_response;
http_response += "HTTP/";
sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
http_response += tmp;
http_response += " 200 OK\r\n";
http_response += "Content-Type: application/json\r\n";
http_response += "Content-Length: ";
sprintf(tmp, "%ld", content.size());
http_response += tmp;
http_response += "\r\n";
write(http_response + "\r\n" + content);
if (parser.state == 1) close();
} catch (...) {
LOG_ERR(this, "ERROR!\n");
}
}
} else {
enum http_errno err = HTTP_PARSER_ERRNO(&parser);
const char *desc = http_errno_description(err);
const char *msg = err != HPE_OK ? desc : "incomplete request";
LOG_HTTP_PROTO(this, msg);
// Handle error. Just close the connection.
destroy();
}
}
//
// HTTP parser callbacks.
//
const http_parser_settings HttpClient::settings = {
.on_message_begin = HttpClient::on_info,
.on_url = HttpClient::on_data,
.on_status = HttpClient::on_data,
.on_header_field = HttpClient::on_data,
.on_header_value = HttpClient::on_data,
.on_headers_complete = HttpClient::on_info,
.on_body = HttpClient::on_data,
.on_message_complete = HttpClient::on_info
};
int HttpClient::on_info(http_parser* p) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);
switch (p->state) {
case 18: // message_complete
break;
case 19: // message_begin
self->path.clear();
self->body.clear();
break;
}
return 0;
}
int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
HttpClient *self = static_cast<HttpClient *>(p->data);
LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());
switch (p->state) {
case 32: // path
self->path = std::string(at, length);
break;
case 62: // data
self->body = std::string(at, length);
break;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* deck.cpp
*
* Created on: Mar 13, 2016
* Author: Tumblr
*/
#include <iostream>
#include "deck.h"
#include "stdlib.h"
using namespace std;
Deck::Deck()
:count{0} {
// TODO Auto-generated constructor stuff
well_formed();
}
Deck::~Deck() {
// TODO Auto-generated destructor stuff
}
Deck::Deck(const Deck &clone)
:count{clone.count} {
// TODO cloning stuff here
// passes clone's data to here
well_formed();
}
Deck* Deck::operator=(const Deck* clone) {
// do set equals operations here
// set this equal to the clone
return this;
}
Deck& Deck::operator=(const Deck &clone) {
// do set equals operations here
// set this equal to the clone
return *this;
}
// removes the top card of the deck and returns it
// shifting all the cards up one
Card* Deck::draw_card() {
well_formed();
if(count == 0) return nullptr;
Card* ret = deck[0];
for(unsigned int i = 1; i < count; i++)
deck[i-1] = deck[i];
well_formed();
return ret;
}
// removes the top num cards from the deck and returns
// a "Deck" as the drawn cards. shifts all
// the cards up num
Deck Deck::draw_cards(int num) {
Deck ret;
if(!well_formed()) return ret;
// draws a card from our deck to add
// to the return deck;
for(int i = 0; i < num; i++)
ret.add_card(draw_card());
well_formed();
return ret;
}
// randomizes the order of the deck
void Deck::shuffle() {
if(!well_formed()) return;
// Traverses through the array swapping each index with a random other index
for(unsigned int i = 0; i < count; i++) {
unsigned int r = rand() % count;
Card* temp;
temp = deck[i];
deck[i] = deck[r];
deck[r] = temp;
}
well_formed();
}
// adds a card to the deck and then shuffles the deck
bool Deck::add_card(Card* card) {
return well_formed();
// no room to add the card
if(count == 20) return print_err("No more room to add a card.");
// adds the card and increments count
card[count++] = *card;
cout << card->to_string() << " has been added." << endl;
shuffle();
well_formed();
}
// adds a card at the specified index. i.e 0 for the top
bool Deck::add_card(Card* card, unsigned int index) {
return well_formed();
// index can not be larger than count
if(index >= count - 1) return print_err("Index is out of bounds.");
// no room to add the card
if(count == 20) return false;
// moves all the cards after index down one
for(unsigned int i = count - 1; i > index; i--) {
deck[i + 1] = deck[i];
}
// puts the deck in at index and increments count
deck[index] = card;
count++;
well_formed();
return true;
}
unsigned int Deck::size() {
return count;
}
// checks the integrity of the deck and returns false with an error message
// if something is wrong. Returns true otherwise.
// Rules:
// A Deck may not be larger than 20 cards
// A deck may not have any nullptr between 0 and count
bool Deck::well_formed() {
// may not be larger than 60 cards
if(count > deck.size()) return print_err("Count is larger than 20");
for(unsigned int i = 0; i < count; i++) {
// checks to make sure count is not larger than the size of the deck
if(deck[i] == nullptr) return print_err("Count is larger than size of deck");
int cardCount = 1;
for(unsigned int j = i + 1; j < count; j++) {
// adding it here checks the integrity of the array on our first pass
if(deck[i] == nullptr) return print_err("Count is larger than size of deck");
Card c1 = *deck[i];
Card c2 = *deck[j];
if(c1.get_name() == c2.get_name()) cardCount++;
// you may not have more than 4 of any card in a deck
//if(cardCount > 2) return print_err("You may not have more than 2 of any card");
}
}
// if the integrity of this data structure is held, returns true
return true;
}
// prints the error message passed and returns false
bool Deck::print_err(string err) {
cout << err << endl;
return false;
}
string Deck::to_string() {
string ret = "TESTING";
for(unsigned int i = 0; i < count; i++) {
ret += deck[i]->to_string();
ret += "TESTING";
}
return ret;
}
<commit_msg>solved issue with cards not getting added<commit_after>/*
* deck.cpp
*
* Created on: Mar 13, 2016
* Author: Tumblr
*/
#include <iostream>
#include "deck.h"
#include "stdlib.h"
using namespace std;
Deck::Deck()
:count{0} {
// TODO Auto-generated constructor stuff
well_formed();
}
Deck::~Deck() {
// TODO Auto-generated destructor stuff
}
Deck::Deck(const Deck &clone)
:count{clone.count} {
// TODO cloning stuff here
// passes clone's data to here
well_formed();
}
Deck* Deck::operator=(const Deck* clone) {
// do set equals operations here
// set this equal to the clone
return this;
}
Deck& Deck::operator=(const Deck &clone) {
// do set equals operations here
// set this equal to the clone
return *this;
}
// removes the top card of the deck and returns it
// shifting all the cards up one
Card* Deck::draw_card() {
well_formed();
if(count == 0) return nullptr;
Card* ret = deck[0];
for(unsigned int i = 1; i < count; i++)
deck[i-1] = deck[i];
well_formed();
return ret;
}
// removes the top num cards from the deck and returns
// a "Deck" as the drawn cards. shifts all
// the cards up num
Deck Deck::draw_cards(int num) {
Deck ret;
if(!well_formed()) return ret;
// draws a card from our deck to add
// to the return deck;
for(int i = 0; i < num; i++)
ret.add_card(draw_card());
well_formed();
return ret;
}
// randomizes the order of the deck
void Deck::shuffle() {
if(!well_formed()) return;
// Traverses through the array swapping each index with a random other index
for(unsigned int i = 0; i < count; i++) {
unsigned int r = rand() % count;
Card* temp;
temp = deck[i];
deck[i] = deck[r];
deck[r] = temp;
}
well_formed();
}
// adds a card to the deck and then shuffles the deck
bool Deck::add_card(Card* card) {
if(!well_formed()) return false;
// no room to add the card
if(count == 20) return print_err("No more room to add a card.");
// adds the card and increments count
card[count++] = *card;
cout << card->to_string() << " has been added." << endl;
shuffle();
return well_formed();
}
// adds a card at the specified index. i.e 0 for the top
bool Deck::add_card(Card* card, unsigned int index) {
if(!well_formed()) return false;
// index can not be larger than count
if(index >= count - 1) return print_err("Index is out of bounds.");
// no room to add the card
if(count == 20) return false;
// moves all the cards after index down one
for(unsigned int i = count - 1; i > index; i--) {
deck[i + 1] = deck[i];
}
// puts the deck in at index and increments count
deck[index] = card;
count++;
well_formed();
return true;
}
unsigned int Deck::size() {
return count;
}
// checks the integrity of the deck and returns false with an error message
// if something is wrong. Returns true otherwise.
// Rules:
// A Deck may not be larger than 20 cards
// A deck may not have any nullptr between 0 and count
bool Deck::well_formed() {
// may not be larger than 60 cards
if(count > deck.size()) return print_err("Count is larger than 20");
for(unsigned int i = 0; i < count; i++) {
// checks to make sure count is not larger than the size of the deck
if(deck[i] == nullptr) return print_err("Count is larger than size of deck");
int cardCount = 1;
for(unsigned int j = i + 1; j < count; j++) {
// adding it here checks the integrity of the array on our first pass
if(deck[i] == nullptr) return print_err("Count is larger than size of deck");
Card c1 = *deck[i];
Card c2 = *deck[j];
if(c1.get_name() == c2.get_name()) cardCount++;
// you may not have more than 2 of any card in a deck
//if(cardCount > 2) return print_err("You may not have more than 2 of any card");
}
}
// if the integrity of this data structure is held, returns true
return true;
}
// prints the error message passed and returns false
bool Deck::print_err(string err) {
cout << err << endl;
return false;
}
string Deck::to_string() {
string ret;
for(unsigned int i = 0; i < count; i++) {
ret += deck[i]->to_string();
}
return ret;
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
}
<commit_msg>delte mainwindow cpp<commit_after><|endoftext|> |
<commit_before>#include "engine/dukmathbindings.h"
#include <string>
#include <core/sol.h>
#include "core/vec2.h"
#include "core/sol.h"
namespace euphoria::engine
{
template <typename T>
void
bind_vec2(Sol* sol, const std::string& name)
{
using V = core::vec2<T>;
sol->lua.new_usertype<V>
(
name,
sol::constructors<V(T, T)>(),
"x", &V::x,
"y", &V::y
);
}
void
bind_math(Sol* duk)
{
bind_vec2<float>(duk, "vec2f");
// bind_vec2<int>(duk, "vec2i");
}
}
<commit_msg>removed more lua/sol warnings<commit_after>#include "engine/dukmathbindings.h"
#include <string>
#include "core/cint.h"
#include "core/vec2.h"
#include "core/sol.h"
namespace euphoria::engine
{
template <typename T>
void
bind_vec2(Sol* sol, const std::string& name)
{
using V = core::vec2<T>;
sol::usertype<V> t = sol->lua.new_usertype<V>
(
name,
sol::constructors<V(T, T)>()
);
t["x"] = sol::property
(
[](const V& v) -> double
{
return core::c_float_to_double(v.x);
},
[](V& v, double x)
{
v.x = core::c_double_to_float(x);
}
);
t["y"] = sol::property
(
[](const V& v) -> double
{
return core::c_float_to_double(v.y);
},
[](V& v, double y)
{
v.y = core::c_double_to_float(y);
}
);
}
void
bind_math(Sol* duk)
{
bind_vec2<float>(duk, "vec2f");
// bind_vec2<int>(duk, "vec2i");
}
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <string.h>
#include <stdlib.h>
#ifdef _WIN32
# include <io.h>
# include <fcntl.h>
# include <wchar.h>
#endif
#include "magic.h"
using namespace node;
using namespace v8;
struct Baton {
uv_work_t request;
NanCallback* callback;
char* data;
uint32_t dataLen;
bool dataIsPath;
// libmagic info
const char* path;
int flags;
bool error;
bool free_error;
char* error_message;
const char* result;
};
static Persistent<FunctionTemplate> constructor;
static const char* fallbackPath;
class Magic : public ObjectWrap {
public:
const char* mpath;
int mflags;
Magic(const char* path, int flags) {
if (path != NULL) {
/* Windows blows up trying to look up the path '(null)' returned by
magic_getpath() */
if (strncmp(path, "(null)", 6) == 0)
path = NULL;
}
mpath = (path == NULL ? strdup(fallbackPath) : path);
mflags = flags;
}
~Magic() {
if (mpath != NULL) {
free((void*)mpath);
mpath = NULL;
}
}
static NAN_METHOD(New) {
NanScope();
#ifndef _WIN32
int mflags = MAGIC_SYMLINK;
#else
int mflags = MAGIC_NONE;
#endif
char* path = NULL;
bool use_bundled = true;
if (!args.IsConstructCall())
return NanThrowTypeError("Use `new` to create instances of this object.");
if (args.Length() > 1) {
if (args[1]->IsInt32())
mflags = args[1]->Int32Value();
else
return NanThrowTypeError("Second argument must be an integer");
}
if (args.Length() > 0) {
if (args[0]->IsString()) {
use_bundled = false;
String::Utf8Value str(args[0]->ToString());
path = strdup((const char*)(*str));
} else if (args[0]->IsInt32())
mflags = args[0]->Int32Value();
else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) {
use_bundled = false;
path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/));
} else
return NanThrowTypeError("First argument must be a string or integer");
}
Magic* obj = new Magic((use_bundled ? NULL : path), mflags);
obj->Wrap(args.This());
obj->Ref();
NanReturnValue(args.This());
}
static NAN_METHOD(DetectFile) {
NanScope();
Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());
if (!args[0]->IsString())
return NanThrowTypeError("First argument must be a string");
if (!args[1]->IsFunction())
return NanThrowTypeError("Second argument must be a callback function");
Local<Function> callback = Local<Function>::Cast(args[1]);
String::Utf8Value str(args[0]->ToString());
Baton* baton = new Baton();
baton->error = false;
baton->free_error = true;
baton->error_message = NULL;
baton->request.data = baton;
baton->callback = new NanCallback(callback);
baton->data = strdup((const char*)*str);
baton->dataIsPath = true;
baton->path = obj->mpath;
baton->flags = obj->mflags;
baton->result = NULL;
int status = uv_queue_work(uv_default_loop(),
&baton->request,
Magic::DetectWork,
(uv_after_work_cb)Magic::DetectAfter);
assert(status == 0);
NanReturnUndefined();
}
static NAN_METHOD(Detect) {
NanScope();
Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());
if (args.Length() < 2)
return NanThrowTypeError("Expecting 2 arguments");
if (!Buffer::HasInstance(args[0]))
return NanThrowTypeError("First argument must be a Buffer");
if (!args[1]->IsFunction())
return NanThrowTypeError("Second argument must be a callback function");
Local<Function> callback = Local<Function>::Cast(args[1]);
#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 10
Local<Object> buffer_obj = args[0]->ToObject();
#else
Local<Value> buffer_obj = args[0];
#endif
Baton* baton = new Baton();
baton->error = false;
baton->free_error = true;
baton->error_message = NULL;
baton->request.data = baton;
baton->callback = new NanCallback(callback);
baton->data = Buffer::Data(buffer_obj);
baton->dataLen = Buffer::Length(buffer_obj);
baton->dataIsPath = false;
baton->path = obj->mpath;
baton->flags = obj->mflags;
baton->result = NULL;
int status = uv_queue_work(uv_default_loop(),
&baton->request,
Magic::DetectWork,
(uv_after_work_cb)Magic::DetectAfter);
assert(status == 0);
NanReturnUndefined();
}
static void DetectWork(uv_work_t* req) {
Baton* baton = static_cast<Baton*>(req->data);
const char* result;
struct magic_set *magic = magic_open(baton->flags
| MAGIC_NO_CHECK_COMPRESS
| MAGIC_ERROR);
if (magic == NULL) {
#if NODE_MODULE_VERSION <= 0x000B
baton->error_message = strdup(uv_strerror(
uv_last_error(uv_default_loop())));
#else
# ifdef _MSC_VER
baton->error_message = strdup(uv_strerror(GetLastError()));
# else
baton->error_message = strdup(uv_strerror(errno));
# endif
#endif
} else if (magic_load(magic, baton->path) == -1
&& magic_load(magic, fallbackPath) == -1) {
baton->error_message = strdup(magic_error(magic));
magic_close(magic);
magic = NULL;
}
if (magic == NULL) {
if (baton->error_message)
baton->error = true;
return;
}
if (baton->dataIsPath) {
#ifdef _WIN32
// open the file manually to help cope with potential unicode characters
// in filename
const char* ofn = baton->data;
int flags = O_RDONLY|O_BINARY;
int fd = -1;
int wLen;
wLen = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, NULL, 0);
if (wLen > 0) {
wchar_t* wfn = (wchar_t*)malloc(wLen * sizeof(wchar_t));
if (wfn) {
int wret = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, wfn, wLen);
if (wret != 0)
fd = _wopen(wfn, flags);
free(wfn);
wfn = NULL;
}
}
if (fd == -1) {
baton->error = true;
baton->free_error = false;
baton->error_message = "Error while opening file";
magic_close(magic);
return;
}
result = magic_descriptor(magic, fd);
_close(fd);
#else
result = magic_file(magic, baton->data);
#endif
} else
result = magic_buffer(magic, (const void*)baton->data, baton->dataLen);
if (result == NULL) {
const char* error = magic_error(magic);
if (error) {
baton->error = true;
baton->error_message = strdup(error);
}
} else
baton->result = strdup(result);
magic_close(magic);
}
static void DetectAfter(uv_work_t* req) {
NanScope();
Baton* baton = static_cast<Baton*>(req->data);
if (baton->error) {
Local<Value> err = NanError(baton->error_message);
if (baton->free_error)
free(baton->error_message);
Local<Value> argv[1] = { err };
baton->callback->Call(1, argv);
} else {
Local<Value> argv[2] = {
NanNull(),
Local<Value>(baton->result
? NanNew<String>(baton->result)
: NanNew<String>())
};
if (baton->result)
free((void*)baton->result);
baton->callback->Call(2, argv);
}
if (baton->dataIsPath)
free(baton->data);
delete baton->callback;
delete baton;
}
static NAN_METHOD(SetFallback) {
NanScope();
if (fallbackPath)
free((void*)fallbackPath);
if (args.Length() > 0 && args[0]->IsString()
&& args[0]->ToString()->Length() > 0) {
String::Utf8Value str(args[0]->ToString());
fallbackPath = strdup((const char*)(*str));
} else
fallbackPath = NULL;
NanReturnUndefined();
}
static void Initialize(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);
NanAssignPersistent(constructor, tpl);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(NanNew<String>("Magic"));
NODE_SET_PROTOTYPE_METHOD(tpl, "detectFile", DetectFile);
NODE_SET_PROTOTYPE_METHOD(tpl, "detect", Detect);
target->Set(NanNew<String>("setFallback"),
NanNew<FunctionTemplate>(SetFallback)->GetFunction());
target->Set(NanNew<String>("Magic"), tpl->GetFunction());
}
};
extern "C" {
void init(Handle<Object> target) {
NanScope();
Magic::Initialize(target);
}
NODE_MODULE(magic, init);
}
<commit_msg>src: fix errno in node v0.11+<commit_after>#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <string.h>
#include <stdlib.h>
#ifdef _WIN32
# include <io.h>
# include <fcntl.h>
# include <wchar.h>
#endif
#include "magic.h"
using namespace node;
using namespace v8;
struct Baton {
uv_work_t request;
NanCallback* callback;
char* data;
uint32_t dataLen;
bool dataIsPath;
// libmagic info
const char* path;
int flags;
bool error;
bool free_error;
char* error_message;
const char* result;
};
static Persistent<FunctionTemplate> constructor;
static const char* fallbackPath;
class Magic : public ObjectWrap {
public:
const char* mpath;
int mflags;
Magic(const char* path, int flags) {
if (path != NULL) {
/* Windows blows up trying to look up the path '(null)' returned by
magic_getpath() */
if (strncmp(path, "(null)", 6) == 0)
path = NULL;
}
mpath = (path == NULL ? strdup(fallbackPath) : path);
mflags = flags;
}
~Magic() {
if (mpath != NULL) {
free((void*)mpath);
mpath = NULL;
}
}
static NAN_METHOD(New) {
NanScope();
#ifndef _WIN32
int mflags = MAGIC_SYMLINK;
#else
int mflags = MAGIC_NONE;
#endif
char* path = NULL;
bool use_bundled = true;
if (!args.IsConstructCall())
return NanThrowTypeError("Use `new` to create instances of this object.");
if (args.Length() > 1) {
if (args[1]->IsInt32())
mflags = args[1]->Int32Value();
else
return NanThrowTypeError("Second argument must be an integer");
}
if (args.Length() > 0) {
if (args[0]->IsString()) {
use_bundled = false;
String::Utf8Value str(args[0]->ToString());
path = strdup((const char*)(*str));
} else if (args[0]->IsInt32())
mflags = args[0]->Int32Value();
else if (args[0]->IsBoolean() && !args[0]->BooleanValue()) {
use_bundled = false;
path = strdup(magic_getpath(NULL, 0/*FILE_LOAD*/));
} else
return NanThrowTypeError("First argument must be a string or integer");
}
Magic* obj = new Magic((use_bundled ? NULL : path), mflags);
obj->Wrap(args.This());
obj->Ref();
NanReturnValue(args.This());
}
static NAN_METHOD(DetectFile) {
NanScope();
Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());
if (!args[0]->IsString())
return NanThrowTypeError("First argument must be a string");
if (!args[1]->IsFunction())
return NanThrowTypeError("Second argument must be a callback function");
Local<Function> callback = Local<Function>::Cast(args[1]);
String::Utf8Value str(args[0]->ToString());
Baton* baton = new Baton();
baton->error = false;
baton->free_error = true;
baton->error_message = NULL;
baton->request.data = baton;
baton->callback = new NanCallback(callback);
baton->data = strdup((const char*)*str);
baton->dataIsPath = true;
baton->path = obj->mpath;
baton->flags = obj->mflags;
baton->result = NULL;
int status = uv_queue_work(uv_default_loop(),
&baton->request,
Magic::DetectWork,
(uv_after_work_cb)Magic::DetectAfter);
assert(status == 0);
NanReturnUndefined();
}
static NAN_METHOD(Detect) {
NanScope();
Magic* obj = ObjectWrap::Unwrap<Magic>(args.This());
if (args.Length() < 2)
return NanThrowTypeError("Expecting 2 arguments");
if (!Buffer::HasInstance(args[0]))
return NanThrowTypeError("First argument must be a Buffer");
if (!args[1]->IsFunction())
return NanThrowTypeError("Second argument must be a callback function");
Local<Function> callback = Local<Function>::Cast(args[1]);
#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 10
Local<Object> buffer_obj = args[0]->ToObject();
#else
Local<Value> buffer_obj = args[0];
#endif
Baton* baton = new Baton();
baton->error = false;
baton->free_error = true;
baton->error_message = NULL;
baton->request.data = baton;
baton->callback = new NanCallback(callback);
baton->data = Buffer::Data(buffer_obj);
baton->dataLen = Buffer::Length(buffer_obj);
baton->dataIsPath = false;
baton->path = obj->mpath;
baton->flags = obj->mflags;
baton->result = NULL;
int status = uv_queue_work(uv_default_loop(),
&baton->request,
Magic::DetectWork,
(uv_after_work_cb)Magic::DetectAfter);
assert(status == 0);
NanReturnUndefined();
}
static void DetectWork(uv_work_t* req) {
Baton* baton = static_cast<Baton*>(req->data);
const char* result;
struct magic_set *magic = magic_open(baton->flags
| MAGIC_NO_CHECK_COMPRESS
| MAGIC_ERROR);
if (magic == NULL) {
#if NODE_MODULE_VERSION <= 0x000B
baton->error_message = strdup(uv_strerror(
uv_last_error(uv_default_loop())));
#else
# ifdef _MSC_VER
baton->error_message = strdup(uv_strerror(GetLastError()));
# else
baton->error_message = strdup(uv_strerror(-errno));
# endif
#endif
} else if (magic_load(magic, baton->path) == -1
&& magic_load(magic, fallbackPath) == -1) {
baton->error_message = strdup(magic_error(magic));
magic_close(magic);
magic = NULL;
}
if (magic == NULL) {
if (baton->error_message)
baton->error = true;
return;
}
if (baton->dataIsPath) {
#ifdef _WIN32
// open the file manually to help cope with potential unicode characters
// in filename
const char* ofn = baton->data;
int flags = O_RDONLY|O_BINARY;
int fd = -1;
int wLen;
wLen = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, NULL, 0);
if (wLen > 0) {
wchar_t* wfn = (wchar_t*)malloc(wLen * sizeof(wchar_t));
if (wfn) {
int wret = MultiByteToWideChar(CP_UTF8, 0, ofn, -1, wfn, wLen);
if (wret != 0)
fd = _wopen(wfn, flags);
free(wfn);
wfn = NULL;
}
}
if (fd == -1) {
baton->error = true;
baton->free_error = false;
baton->error_message = "Error while opening file";
magic_close(magic);
return;
}
result = magic_descriptor(magic, fd);
_close(fd);
#else
result = magic_file(magic, baton->data);
#endif
} else
result = magic_buffer(magic, (const void*)baton->data, baton->dataLen);
if (result == NULL) {
const char* error = magic_error(magic);
if (error) {
baton->error = true;
baton->error_message = strdup(error);
}
} else
baton->result = strdup(result);
magic_close(magic);
}
static void DetectAfter(uv_work_t* req) {
NanScope();
Baton* baton = static_cast<Baton*>(req->data);
if (baton->error) {
Local<Value> err = NanError(baton->error_message);
if (baton->free_error)
free(baton->error_message);
Local<Value> argv[1] = { err };
baton->callback->Call(1, argv);
} else {
Local<Value> argv[2] = {
NanNull(),
Local<Value>(baton->result
? NanNew<String>(baton->result)
: NanNew<String>())
};
if (baton->result)
free((void*)baton->result);
baton->callback->Call(2, argv);
}
if (baton->dataIsPath)
free(baton->data);
delete baton->callback;
delete baton;
}
static NAN_METHOD(SetFallback) {
NanScope();
if (fallbackPath)
free((void*)fallbackPath);
if (args.Length() > 0 && args[0]->IsString()
&& args[0]->ToString()->Length() > 0) {
String::Utf8Value str(args[0]->ToString());
fallbackPath = strdup((const char*)(*str));
} else
fallbackPath = NULL;
NanReturnUndefined();
}
static void Initialize(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);
NanAssignPersistent(constructor, tpl);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(NanNew<String>("Magic"));
NODE_SET_PROTOTYPE_METHOD(tpl, "detectFile", DetectFile);
NODE_SET_PROTOTYPE_METHOD(tpl, "detect", Detect);
target->Set(NanNew<String>("setFallback"),
NanNew<FunctionTemplate>(SetFallback)->GetFunction());
target->Set(NanNew<String>("Magic"), tpl->GetFunction());
}
};
extern "C" {
void init(Handle<Object> target) {
NanScope();
Magic::Initialize(target);
}
NODE_MODULE(magic, init);
}
<|endoftext|> |
<commit_before>#include "merger.hpp"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <string>
// program version
const auto version = "0.2alpha";
void merge( boost::program_options::variables_map const& vm )
{
std::ifstream left, right;
// we need to check for failbit in case that opening failed...
left.exceptions( std::ifstream::failbit | std::ifstream::badbit );
right.exceptions( std::ifstream::failbit | std::ifstream::badbit );
left.open( vm["left"].as<std::string>() );
right.open( vm["right"].as<std::string>() );
// ... but failbit is set in some EOF conditions by getline,
// so disable its checking after file is open
left.exceptions( std::ifstream::badbit );
right.exceptions( std::ifstream::badbit );
merger::Merger m{
vm["separator"].as<char>(),
vm.count( "ignore-quotes" ) > 0,
vm.count( "date" ) > 0,
vm.count( "drop-empty" ) > 0,
vm["header"].as<std::size_t>()
};
if (vm.count( "out" )) {
// optional output file specified - using it as output
std::ofstream out;
out.exceptions( std::ofstream::failbit | std::ofstream::badbit );
out.open( vm["out"].as<std::string>() );
out.exceptions( std::ofstream::badbit );
m.merge( left, right, out );
} else {
// no output specified - using standart output
m.merge( left, right, std::cout );
}
}
int main( int argc, char* argv[] )
{
// executable name
auto name = boost::filesystem::path{ argv[0] }.filename().string();
try {
// parse parameters
namespace po = boost::program_options;
po::options_description desc{ "Allowed options" };
desc.add_options()
("help,h", "print this help message")
("version,v", "print program version")
("ignore-quotes,q", "no special treatment for quoted text")
("date,d", "compare by date/time")
("drop-empty,D", "discard lines without match in all sources")
("separator,s", po::value<char>()->default_value( ',' ), "set separator")
("header,H", po::value<std::size_t>()->default_value( 0 ), "size of the header (left header will also be copied to the output)")
;
po::options_description hidden{ "Hidden options" };
hidden.add_options()
("left", po::value<std::string>(), "left file")
("right", po::value<std::string>(), "right file")
("out", po::value<std::string>(), "output file")
;
po::options_description cmdline;
cmdline.add( desc ).add( hidden );
po::positional_options_description p;
p.add( "left", 1 ).add( "right", 1 ).add( "out", 1 );
po::variables_map vm;
po::store( po::command_line_parser{ argc, argv }.options( cmdline ).positional( p ).run(), vm );
po::notify( vm );
// check parameters
if (vm.count( "help" )) {
std::cout << "Usage:\n " << name << " [OPTIONS] LEFT-FILE RIGHT-FILE [OUTPUT]\n\n"
<< desc << std::endl;
return 0;
}
if (vm.count( "version" )) {
std::cout << name << " version: " << version << std::endl;
return 0;
}
if (!vm.count( "left" ) || !vm.count( "right" )) {
std::cerr << name << ": at least 2 files have to be provided" << std::endl;
return 1;
}
// the actual program
merge( vm );
} catch (std::ios_base::failure const& e) {
// I/O error occured - terminating
// TODO: more informative message
std::cerr << name << ": file I/O error: " << e.what() << std::endl;
return 1;
} catch (std::exception const& e) {
// some other error occured
std::cerr << name << ": " << e.what() << std::endl;
return 1;
}
}
<commit_msg>Version bump to 0.2<commit_after>#include "merger.hpp"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <string>
// program version
const auto version = "0.2";
void merge( boost::program_options::variables_map const& vm )
{
std::ifstream left, right;
// we need to check for failbit in case that opening failed...
left.exceptions( std::ifstream::failbit | std::ifstream::badbit );
right.exceptions( std::ifstream::failbit | std::ifstream::badbit );
left.open( vm["left"].as<std::string>() );
right.open( vm["right"].as<std::string>() );
// ... but failbit is set in some EOF conditions by getline,
// so disable its checking after file is open
left.exceptions( std::ifstream::badbit );
right.exceptions( std::ifstream::badbit );
merger::Merger m{
vm["separator"].as<char>(),
vm.count( "ignore-quotes" ) > 0,
vm.count( "date" ) > 0,
vm.count( "drop-empty" ) > 0,
vm["header"].as<std::size_t>()
};
if (vm.count( "out" )) {
// optional output file specified - using it as output
std::ofstream out;
out.exceptions( std::ofstream::failbit | std::ofstream::badbit );
out.open( vm["out"].as<std::string>() );
out.exceptions( std::ofstream::badbit );
m.merge( left, right, out );
} else {
// no output specified - using standart output
m.merge( left, right, std::cout );
}
}
int main( int argc, char* argv[] )
{
// executable name
auto name = boost::filesystem::path{ argv[0] }.filename().string();
try {
// parse parameters
namespace po = boost::program_options;
po::options_description desc{ "Allowed options" };
desc.add_options()
("help,h", "print this help message")
("version,v", "print program version")
("ignore-quotes,q", "no special treatment for quoted text")
("date,d", "compare by date/time")
("drop-empty,D", "discard lines without match in all sources")
("separator,s", po::value<char>()->default_value( ',' ), "set separator")
("header,H", po::value<std::size_t>()->default_value( 0 ), "size of the header (left header will also be copied to the output)")
;
po::options_description hidden{ "Hidden options" };
hidden.add_options()
("left", po::value<std::string>(), "left file")
("right", po::value<std::string>(), "right file")
("out", po::value<std::string>(), "output file")
;
po::options_description cmdline;
cmdline.add( desc ).add( hidden );
po::positional_options_description p;
p.add( "left", 1 ).add( "right", 1 ).add( "out", 1 );
po::variables_map vm;
po::store( po::command_line_parser{ argc, argv }.options( cmdline ).positional( p ).run(), vm );
po::notify( vm );
// check parameters
if (vm.count( "help" )) {
std::cout << "Usage:\n " << name << " [OPTIONS] LEFT-FILE RIGHT-FILE [OUTPUT]\n\n"
<< desc << std::endl;
return 0;
}
if (vm.count( "version" )) {
std::cout << name << " version: " << version << std::endl;
return 0;
}
if (!vm.count( "left" ) || !vm.count( "right" )) {
std::cerr << name << ": at least 2 files have to be provided" << std::endl;
return 1;
}
// the actual program
merge( vm );
} catch (std::ios_base::failure const& e) {
// I/O error occured - terminating
// TODO: more informative message
std::cerr << name << ": file I/O error: " << e.what() << std::endl;
return 1;
} catch (std::exception const& e) {
// some other error occured
std::cerr << name << ": " << e.what() << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Karsten Heinze <[email protected]>
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <libtecla.h>
#include "types.hpp"
#include "sesame/Instance.hpp"
#include "sesame/commands/InstanceTask.hpp"
#include "sesame/utils/string.hpp"
#include "sesame/utils/completion.hpp"
#include "sesame/utils/Parser.hpp"
#include "sesame/utils/ParseResult.hpp"
#include "sesame/utils/TeclaReader.hpp"
using sesame::commands::InstanceTask;
String buildPrompt( std::shared_ptr<sesame::Instance>& instance );
String usage( const char* command );
int main( int argc, char** argv)
{
// Set locale!
sesame::utils::setLocale();
// Start.
std::shared_ptr<sesame::Instance> instance;
// File passed?
if ( argc > 2 )
{
std::cout << usage( argv[ 0 ] ) << std::endl;
return 1;
}
else if ( argc == 2 )
{
try
{
InstanceTask task( InstanceTask::OPEN, argv[ 1 ] );
task.run( instance );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;;
return 1;
}
}
sesame::utils::TeclaReader reader( 1024, 2048 );
reader.addCompletion( cpl_complete_sesame, static_cast<void*>( &instance ) );
sesame::utils::Parser parser;
sesame::utils::ParseResult parseResult;
String normalized;
do
{
// Build prompt.
String prompt( buildPrompt( instance ) );
// Read line.
try
{
normalized = reader.readLine( prompt );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;
break;
}
if ( normalized == "\n" )
{
continue;
}
else if ( normalized.find( "edit-mode " ) == 0 )
{
if ( normalized == "edit-mode vi\n" )
{
if ( ! reader.setEditMode( "vi" ) )
{
std::cerr << "ERROR: failed to set edit-mode" << std::endl;
}
}
else if ( normalized == "edit-mode emacs\n" )
{
if ( ! reader.setEditMode( "emacs" ) )
{
std::cerr << "ERROR: failed to set edit-mode" << std::endl;
}
}
else
{
std::cerr << "ERROR: edit-mode not supported" << std::endl;
}
}
else if ( normalized == "clear\n" )
{
if ( ! reader.clear() )
{
std::cerr << "ERROR: failed to clear terminal" << std::endl;
}
}
else if ( normalized == "quit\n" )
{
try
{
InstanceTask task( InstanceTask::CLOSE );
task.run( instance );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;;
}
// Quit only if instance was closed!
if ( ! instance )
{
break;
}
}
else
{
parseResult = parser.parse( normalized );
if ( parseResult.isValid() )
{
if ( ! parseResult.getCommandToken().empty() )
{
//std::cout << parseResult << std::endl;
if ( parseResult.getCommand() != nullptr )
{
try
{
parseResult.getCommand()->run( instance );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;
}
}
}
}
else
{
std::cerr << parseResult << std::endl;
}
}
}
while ( true );
return 0;
}
String buildPrompt( std::shared_ptr<sesame::Instance>& instance )
{
String prompt( "sesame> " );
if ( instance )
{
StringStream s;
s << "sesame #" << std::hex << std::setw( 8 ) << std::setfill( '0' ) << instance->getId() << "> ";
prompt = s.str();
}
return prompt;
}
String usage( const char* command )
{
StringStream s;
s << "usage: " << command << " [FILE]";
return s.str();
}
<commit_msg>run close cmd only if instance is open<commit_after>// Copyright (c) 2015, Karsten Heinze <[email protected]>
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <libtecla.h>
#include "types.hpp"
#include "sesame/Instance.hpp"
#include "sesame/commands/InstanceTask.hpp"
#include "sesame/utils/string.hpp"
#include "sesame/utils/completion.hpp"
#include "sesame/utils/Parser.hpp"
#include "sesame/utils/ParseResult.hpp"
#include "sesame/utils/TeclaReader.hpp"
using sesame::commands::InstanceTask;
String buildPrompt( std::shared_ptr<sesame::Instance>& instance );
String usage( const char* command );
int main( int argc, char** argv)
{
// Set locale!
sesame::utils::setLocale();
// Start.
std::shared_ptr<sesame::Instance> instance;
// File passed?
if ( argc > 2 )
{
std::cout << usage( argv[ 0 ] ) << std::endl;
return 1;
}
else if ( argc == 2 )
{
try
{
InstanceTask task( InstanceTask::OPEN, argv[ 1 ] );
task.run( instance );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;;
return 1;
}
}
sesame::utils::TeclaReader reader( 1024, 2048 );
reader.addCompletion( cpl_complete_sesame, static_cast<void*>( &instance ) );
sesame::utils::Parser parser;
sesame::utils::ParseResult parseResult;
String normalized;
do
{
// Build prompt.
String prompt( buildPrompt( instance ) );
// Read line.
try
{
normalized = reader.readLine( prompt );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;
break;
}
if ( normalized == "\n" )
{
continue;
}
else if ( normalized.find( "edit-mode " ) == 0 )
{
if ( normalized == "edit-mode vi\n" )
{
if ( ! reader.setEditMode( "vi" ) )
{
std::cerr << "ERROR: failed to set edit-mode" << std::endl;
}
}
else if ( normalized == "edit-mode emacs\n" )
{
if ( ! reader.setEditMode( "emacs" ) )
{
std::cerr << "ERROR: failed to set edit-mode" << std::endl;
}
}
else
{
std::cerr << "ERROR: edit-mode not supported" << std::endl;
}
}
else if ( normalized == "clear\n" )
{
if ( ! reader.clear() )
{
std::cerr << "ERROR: failed to clear terminal" << std::endl;
}
}
else if ( normalized == "quit\n" )
{
if ( instance )
{
try
{
InstanceTask task( InstanceTask::CLOSE );
task.run( instance );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;;
}
}
// Quit only if no instance is open!
if ( ! instance )
{
break;
}
}
else
{
parseResult = parser.parse( normalized );
if ( parseResult.isValid() )
{
if ( ! parseResult.getCommandToken().empty() )
{
//std::cout << parseResult << std::endl;
if ( parseResult.getCommand() != nullptr )
{
try
{
parseResult.getCommand()->run( instance );
}
catch ( std::runtime_error& e )
{
std::cerr << "ERROR: " << e.what() << std::endl;
}
}
}
}
else
{
std::cerr << parseResult << std::endl;
}
}
}
while ( true );
return 0;
}
String buildPrompt( std::shared_ptr<sesame::Instance>& instance )
{
String prompt( "sesame> " );
if ( instance )
{
StringStream s;
s << "sesame #" << std::hex << std::setw( 8 ) << std::setfill( '0' ) << instance->getId() << "> ";
prompt = s.str();
}
return prompt;
}
String usage( const char* command )
{
StringStream s;
s << "usage: " << command << " [FILE]";
return s.str();
}
<|endoftext|> |
<commit_before>/* -*- coding: utf-8 -*-
* Copyright (c) 2010, Tim Kleinschmit. This file is
* licensed under the General Public License version 3 or later.
* See the COPYRIGHT file.
*/
#include <QtGui/QApplication>
#include <QtCore/QTranslator>
#include <QtCore/QLibraryInfo>
#include "const.h"
#include "mainwindow.h"
#include "iconloader.h"
int main(int argc, char *argv[])
{
// Settings stuff
QCoreApplication::setApplicationName ( APP_NAME );
QCoreApplication::setApplicationVersion ( APP_VERSION );
QCoreApplication::setOrganizationDomain ( APP_URL );
QCoreApplication::setOrganizationName ( APP_NAME);
// verify the user if not run as root
#ifdef Q_OS_UNIX
if ( geteuid () == 0 ) {
qWarning ()<< APP_NAME + QObject::tr ( " is not supposed to be run as root" );
exit(0);
}
#endif
// initiliaze the resource datas
Q_INIT_RESOURCE( data );
// only one session of simba
QApplication a( argc, argv );
// check tray exist
if ( !QSystemTrayIcon::isSystemTrayAvailable ())
qWarning ()<< QObject::tr ( "I couldn't detect any system tray on this system." );
// install qt translator
QTranslator qtTranslator;
qtTranslator.load( "qt_" + QLocale::system ().name (), QLibraryInfo::location ( QLibraryInfo::TranslationsPath ));
a.installTranslator( &qtTranslator );
// Icons
IconLoader::Init ();
// delivery the cli argument
MainWindow w( QCoreApplication::arguments ());
w.show ();
return a.exec ();
}
<commit_msg>Fix geteuid compile error<commit_after>/* -*- coding: utf-8 -*-
* Copyright (c) 2010, Tim Kleinschmit. This file is
* licensed under the General Public License version 3 or later.
* See the COPYRIGHT file.
*/
#include <QtGui/QApplication>
#include <QtCore/QTranslator>
#include <QtCore/QLibraryInfo>
#include "const.h"
#include "mainwindow.h"
#include "iconloader.h"
#include <unistd.h>
int main(int argc, char *argv[])
{
// Settings stuff
QCoreApplication::setApplicationName ( APP_NAME );
QCoreApplication::setApplicationVersion ( APP_VERSION );
QCoreApplication::setOrganizationDomain ( APP_URL );
QCoreApplication::setOrganizationName ( APP_NAME);
// verify the user if not run as root
#ifdef Q_OS_UNIX
if ( geteuid () == 0 ) {
qWarning ()<< APP_NAME + QObject::tr ( " is not supposed to be run as root" );
exit(0);
}
#endif
// initiliaze the resource datas
Q_INIT_RESOURCE( data );
// only one session of simba
QApplication a( argc, argv );
// check tray exist
if ( !QSystemTrayIcon::isSystemTrayAvailable ())
qWarning ()<< QObject::tr ( "I couldn't detect any system tray on this system." );
// install qt translator
QTranslator qtTranslator;
qtTranslator.load( "qt_" + QLocale::system ().name (), QLibraryInfo::location ( QLibraryInfo::TranslationsPath ));
a.installTranslator( &qtTranslator );
// Icons
IconLoader::Init ();
// delivery the cli argument
MainWindow w( QCoreApplication::arguments ());
w.show ();
return a.exec ();
}
<|endoftext|> |
<commit_before>#include "SequenceVectorizer.h"
#include "Opts.h"
#include "ContaminationDetection.h"
#include "Logger.h"
#include "TarjansAlgorithm.h"
#include "BarnesHutSNEAdapter.h"
#include "KrakenAdapter.h"
#include "RnammerAdapter.h"
#include "ResultIO.h"
#include "IOUtil.h"
#include "MLUtil.h"
#include "HierarchicalClustering.h"
#include "TaxonomyAnnotation.h"
#include <boost/filesystem.hpp>
#include <string>
#include <fstream>
#include <streambuf>
#include <future>
#include <map>
#include <Eigen/Dense>
#include "MatrixUtil.h"
int main(int argc, char *argv[])
{
std::string banner = "";
// build program arguments
try
{
Opts::initializeOnce(argc, argv);
std::ifstream ifs(Opts::sharePath() + "/banner.txt");
banner = std::string((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
}
catch(const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
// show help
if (Opts::needsHelp())
{
std::cout << banner << std::endl;
std::cout << Opts::helpDesc() << std::endl;
return EXIT_SUCCESS;
}
// configure logger
switch (Opts::logLevel())
{
case -1: Logger::getInstance().setLevel(Off); break;
case 0: Logger::getInstance().setLevel(Error); break;
case 1: Logger::getInstance().setLevel(Info); break;
case 2: Logger::getInstance().setLevel(Verbose); break;
case 3: Logger::getInstance().setLevel(Debug); break;
default: throw std::runtime_error("Loglevel undefined!");
}
// check for input files
if (Opts::inputFASTAs().empty())
{
ELOG << "No input FASTA file(s) given (--input-fasta,-i)." << std::endl;
return EXIT_FAILURE;
}
// setup Kraken
KrakenAdapter krk;
bool krakenExists = krk.krakenExists();
if (!krakenExists)
{
ELOG << "Kraken not found! It will be disabled.\n- Please make sure that the folders containing the 'kraken' and 'kraken-translate' executables is in your $PATH.\n- Please make sure to supply a database using the --kraken-db switch." << std::endl;
}
// setup Rnammer
bool rmrExists = RnammerAdapter::rnammerExists();
if (!rmrExists)
{
ELOG << "Rnammer not found! It will be disabled.\n- Please make sure that the folders containing the 'rnammer' executable is in your $PATH." << std::endl;
}
// create output / export directory
boost::filesystem::path exportPath (Opts::outputDir());
boost::system::error_code returnedError;
boost::filesystem::create_directories(exportPath, returnedError);
if (returnedError)
{
ELOG << "Could not create output/export directory, aborting." << std::endl;
return EXIT_FAILURE;
}
// copy result assets
try
{
IOUtil::copyDir(boost::filesystem::path(Opts::sharePath() + "/assets"), Opts::outputDir(), true);
} catch(const boost::filesystem::filesystem_error & e)
{
ELOG << e.what() << std::endl;
return EXIT_FAILURE;
}
// remove old data.js file if necessary
std::string dataFile = Opts::outputDir() + "/data.js";
if (boost::filesystem::exists(boost::filesystem::path(dataFile)))
{
std::remove(dataFile.c_str());
}
// process files
ResultIO rio(Opts::outputDir(), krakenExists);
unsigned idCnt = 1;
for (const auto & fasta : Opts::inputFASTAs())
{
if (!boost::filesystem::is_regular_file(boost::filesystem::path(fasta)))
{
ELOG << "File '" << fasta << "' does not exist or is not a regular file! Skipping..." << std::endl;
continue;
}
ILOG << "Processing file: " << fasta << std::endl;
ResultContainer result;
result.id = idCnt++;
result.fasta = fasta;
try
{
// run kraken
if (krakenExists)
{
ILOG << "Running Kraken..." << std::endl;
try
{
result.kraken = krk.runKraken(fasta);
} catch(const std::exception & e)
{
ELOG << e.what() << std::endl;
ELOG << "Kraken will be disabled." << std::endl;
krakenExists = false;
}
}
// gather information about input fasta
ILOG << "Gathering fasta information..." << std::endl;
result.stats = SequenceUtil::calculateStats(fasta, Opts::minContigLength());
// convert sequences into vectorial data
ILOG << "Vectorizing contigs..." << std::endl;
SequenceVectorizer sv(fasta);
auto svr = sv.vectorize();
result.seqVectorization = svr;
// run Rnammer
if (rmrExists)
{
ILOG << "Running Rnammer..." << std::endl;
try
{
result._16S = RnammerAdapter::find16S(fasta, svr);
} catch(const std::exception & e)
{
ELOG << e.what() << std::endl;
ELOG << "16S highlighting will be disabled." << std::endl;
rmrExists = false;
}
}
// contamination screening
ILOG << "Detecting contamination..." << std::endl;
std::vector<ContaminationDetectionResult> bootstraps = ContaminationDetection::analyzeBootstraps(svr);
ContaminationDetectionResult oneshot = bootstraps.at(0);
bootstraps.erase(bootstraps.begin());
result.contaminationAnalysis = ContaminationDetection::summarizeBootstraps(bootstraps);
result.dataSne = oneshot.dataSne;
result.dataPca = oneshot.dataPca;
// data clustering for decontamination
ILOG << "Clustering..." << std::endl;
result.clusterings = Decontamination::findLikelyClusterings(result.dataSne, result.dataPca, svr);
// annotate taxonomy if exists
if (result.contaminationAnalysis.state != "clean" && Opts::taxonomyFile() != "")
{
if(result.contaminationAnalysis.confidenceCC > result.contaminationAnalysis.confidenceDip)
{
unsigned optK = result.clusterings.numClustCC;
VLOG << "Optimal clustering = cc with k = " << optK << std::endl;
result.clusterings.mostLikelyClusteringName = "cc";
result.clusterings.mostLikelyClustering = & (result.clusterings.clustsCC[0]);
} else
{
unsigned optK = result.clusterings.numClustSne;
VLOG << "Optimal clustering = validity_sne with k = " << optK << std::endl;
result.clusterings.mostLikelyClusteringName = "validity_sne";
result.clusterings.mostLikelyClustering = & (result.clusterings.clustsSne[optK-1]);
}
if (!boost::filesystem::is_regular_file(boost::filesystem::path(Opts::taxonomyFile())))
{
ELOG << "Taxonomy file '" << Opts::taxonomyFile() << "' does not exist or is not a regular file! Ignoring..." << std::endl;
} else
{
ILOG << "Annotating taxonomy from file..." << std::endl;
TaxonomyAnnotation::annotateFromFile(result, Opts::taxonomyFile());
ILOG << "Annotating unknown taxonomies..." << std::endl;
TaxonomyAnnotation::annotateUnknown(result);
}
}
// write output files
ILOG << "Writing result..." << std::endl;
rio.processResult(result);
} catch(const std::exception & e)
{
ELOG << "An error occurred processing this file: " << e.what() << std::endl;
}
}
return EXIT_SUCCESS;
}
<commit_msg>tabs to spaces main.cpp<commit_after>#include "SequenceVectorizer.h"
#include "Opts.h"
#include "ContaminationDetection.h"
#include "Logger.h"
#include "TarjansAlgorithm.h"
#include "BarnesHutSNEAdapter.h"
#include "KrakenAdapter.h"
#include "RnammerAdapter.h"
#include "ResultIO.h"
#include "IOUtil.h"
#include "MLUtil.h"
#include "HierarchicalClustering.h"
#include "TaxonomyAnnotation.h"
#include <boost/filesystem.hpp>
#include <string>
#include <fstream>
#include <streambuf>
#include <future>
#include <map>
#include <Eigen/Dense>
#include "MatrixUtil.h"
int main(int argc, char *argv[])
{
std::string banner = "";
// build program arguments
try
{
Opts::initializeOnce(argc, argv);
std::ifstream ifs(Opts::sharePath() + "/banner.txt");
banner = std::string((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
}
catch(const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
// show help
if (Opts::needsHelp())
{
std::cout << banner << std::endl;
std::cout << Opts::helpDesc() << std::endl;
return EXIT_SUCCESS;
}
// configure logger
switch (Opts::logLevel())
{
case -1: Logger::getInstance().setLevel(Off); break;
case 0: Logger::getInstance().setLevel(Error); break;
case 1: Logger::getInstance().setLevel(Info); break;
case 2: Logger::getInstance().setLevel(Verbose); break;
case 3: Logger::getInstance().setLevel(Debug); break;
default: throw std::runtime_error("Loglevel undefined!");
}
// check for input files
if (Opts::inputFASTAs().empty())
{
ELOG << "No input FASTA file(s) given (--input-fasta,-i)." << std::endl;
return EXIT_FAILURE;
}
// setup Kraken
KrakenAdapter krk;
bool krakenExists = krk.krakenExists();
if (!krakenExists)
{
ELOG << "Kraken not found! It will be disabled.\n- Please make sure that the folders containing the 'kraken' and 'kraken-translate' executables is in your $PATH.\n- Please make sure to supply a database using the --kraken-db switch." << std::endl;
}
// setup Rnammer
bool rmrExists = RnammerAdapter::rnammerExists();
if (!rmrExists)
{
ELOG << "Rnammer not found! It will be disabled.\n- Please make sure that the folders containing the 'rnammer' executable is in your $PATH." << std::endl;
}
// create output / export directory
boost::filesystem::path exportPath (Opts::outputDir());
boost::system::error_code returnedError;
boost::filesystem::create_directories(exportPath, returnedError);
if (returnedError)
{
ELOG << "Could not create output/export directory, aborting." << std::endl;
return EXIT_FAILURE;
}
// copy result assets
try
{
IOUtil::copyDir(boost::filesystem::path(Opts::sharePath() + "/assets"), Opts::outputDir(), true);
} catch(const boost::filesystem::filesystem_error & e)
{
ELOG << e.what() << std::endl;
return EXIT_FAILURE;
}
// remove old data.js file if necessary
std::string dataFile = Opts::outputDir() + "/data.js";
if (boost::filesystem::exists(boost::filesystem::path(dataFile)))
{
std::remove(dataFile.c_str());
}
// process files
ResultIO rio(Opts::outputDir(), krakenExists);
unsigned idCnt = 1;
for (const auto & fasta : Opts::inputFASTAs())
{
if (!boost::filesystem::is_regular_file(boost::filesystem::path(fasta)))
{
ELOG << "File '" << fasta << "' does not exist or is not a regular file! Skipping..." << std::endl;
continue;
}
ILOG << "Processing file: " << fasta << std::endl;
ResultContainer result;
result.id = idCnt++;
result.fasta = fasta;
try
{
// run kraken
if (krakenExists)
{
ILOG << "Running Kraken..." << std::endl;
try
{
result.kraken = krk.runKraken(fasta);
} catch(const std::exception & e)
{
ELOG << e.what() << std::endl;
ELOG << "Kraken will be disabled." << std::endl;
krakenExists = false;
}
}
// gather information about input fasta
ILOG << "Gathering fasta information..." << std::endl;
result.stats = SequenceUtil::calculateStats(fasta, Opts::minContigLength());
// convert sequences into vectorial data
ILOG << "Vectorizing contigs..." << std::endl;
SequenceVectorizer sv(fasta);
auto svr = sv.vectorize();
result.seqVectorization = svr;
// run Rnammer
if (rmrExists)
{
ILOG << "Running Rnammer..." << std::endl;
try
{
result._16S = RnammerAdapter::find16S(fasta, svr);
} catch(const std::exception & e)
{
ELOG << e.what() << std::endl;
ELOG << "16S highlighting will be disabled." << std::endl;
rmrExists = false;
}
}
// contamination screening
ILOG << "Detecting contamination..." << std::endl;
std::vector<ContaminationDetectionResult> bootstraps = ContaminationDetection::analyzeBootstraps(svr);
ContaminationDetectionResult oneshot = bootstraps.at(0);
bootstraps.erase(bootstraps.begin());
result.contaminationAnalysis = ContaminationDetection::summarizeBootstraps(bootstraps);
result.dataSne = oneshot.dataSne;
result.dataPca = oneshot.dataPca;
// data clustering for decontamination
ILOG << "Clustering..." << std::endl;
result.clusterings = Decontamination::findLikelyClusterings(result.dataSne, result.dataPca, svr);
// annotate taxonomy if exists
if (result.contaminationAnalysis.state != "clean" && Opts::taxonomyFile() != "")
{
if(result.contaminationAnalysis.confidenceCC > result.contaminationAnalysis.confidenceDip)
{
unsigned optK = result.clusterings.numClustCC;
VLOG << "Optimal clustering = cc with k = " << optK << std::endl;
result.clusterings.mostLikelyClusteringName = "cc";
result.clusterings.mostLikelyClustering = & (result.clusterings.clustsCC[0]);
} else
{
unsigned optK = result.clusterings.numClustSne;
VLOG << "Optimal clustering = validity_sne with k = " << optK << std::endl;
result.clusterings.mostLikelyClusteringName = "validity_sne";
result.clusterings.mostLikelyClustering = & (result.clusterings.clustsSne[optK-1]);
}
if (!boost::filesystem::is_regular_file(boost::filesystem::path(Opts::taxonomyFile())))
{
ELOG << "Taxonomy file '" << Opts::taxonomyFile() << "' does not exist or is not a regular file! Ignoring..." << std::endl;
} else
{
ILOG << "Annotating taxonomy from file..." << std::endl;
TaxonomyAnnotation::annotateFromFile(result, Opts::taxonomyFile());
ILOG << "Annotating unknown taxonomies..." << std::endl;
TaxonomyAnnotation::annotateUnknown(result);
}
}
// write output files
ILOG << "Writing result..." << std::endl;
rio.processResult(result);
} catch(const std::exception & e)
{
ELOG << "An error occurred processing this file: " << e.what() << std::endl;
}
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <stdint.h>
#include <iostream>
#include "demo.pb.h"
#include "netmessages.pb.h"
#include "bitstream.h"
#include "debug.h"
#include "demo.h"
#include "entity.h"
#include "state.h"
#include "death_recording_visitor.h"
#define INSTANCE_BASELINE_TABLE "instancebaseline"
#define KEY_HISTORY_SIZE 32
#define MAX_EDICTS 0x800
#define MAX_KEY_SIZE 0x400
#define MAX_VALUE_SIZE 0x4000
enum UpdateFlag {
UF_LeavePVS = 1,
UF_Delete = 2,
UF_EnterPVS = 4,
};
State *state = 0;
Visitor *visitor = new DeathRecordingVisitor();
uint32_t read_var_int(const char *data, size_t length, size_t *offset) {
uint32_t b;
int count = 0;
uint32_t result = 0;
do {
XASSERT(count != 5, "Corrupt data.");
XASSERT(*offset <= length, "Premature end of stream.");
b = data[(*offset)++];
result |= (b & 0x7F) << (7 * count);
++count;
} while (b & 0x80);
return result;
}
void dump_SVC_SendTable(const CSVCMsg_SendTable &table) {
XASSERT(state, "SVC_SendTable but no state created.");
SendTable &converted = state->create_send_table(table.net_table_name(), table.needs_decoder());
size_t prop_count = table.props_size();
for (size_t i = 0; i < prop_count; ++i) {
const CSVCMsg_SendTable_sendprop_t &prop = table.props(i);
SendProp c(
static_cast<SP_Types>(prop.type()),
prop.var_name(),
prop.flags(),
prop.priority(),
prop.dt_name(),
prop.num_elements(),
prop.low_value(),
prop.high_value(),
prop.num_bits());
converted.props.add(c);
}
}
void dump_DEM_SendTables(const CDemoSendTables &tables) {
const char *data = tables.data().c_str();
size_t offset = 0;
size_t length = tables.data().length();
while (offset < length) {
uint32_t command = read_var_int(data, length, &offset);
uint32_t size = read_var_int(data, length, &offset);
XASSERT(offset + size <= length, "Reading data outside of table.");
XASSERT(command == svc_SendTable, "Command %u in DEM_SendTables.", command);
CSVCMsg_SendTable send_table;
send_table.ParseFromArray(&(data[offset]), size);
dump_SVC_SendTable(send_table);
offset += size;
}
}
const StringTableEntry &get_baseline_for(int class_i) {
XASSERT(state, "No state created.");
StringTable &instance_baseline = state->get_string_table(INSTANCE_BASELINE_TABLE);
char buf[32];
sprintf(buf, "%d", class_i);
return instance_baseline.get(buf);
}
uint32_t read_entity_header(uint32_t *base, Bitstream &stream) {
uint32_t value = stream.get_bits(6);
if (value & 0x30) {
uint32_t a = (value >> 4) & 3;
uint32_t b = (a == 3) ? 16 : 0;
value = stream.get_bits(4 * a + b) << 4 | (value & 0xF);
}
*base += value + 1;
unsigned int update_flags = 0;
if (!stream.get_bits(1)) {
if (stream.get_bits(1)) {
update_flags |= UF_EnterPVS;
}
} else {
update_flags |= UF_LeavePVS;
if (stream.get_bits(1)) {
update_flags |= UF_Delete;
}
}
return update_flags;
}
void read_entity_enter_pvs(uint32_t entity_id, Bitstream &stream) {
uint32_t class_i = stream.get_bits(state->class_bits);
uint32_t serial = stream.get_bits(10);
XASSERT(entity_id < MAX_EDICTS, "Entity %ld exceeds max edicts.", entity_id);
const Class &clazz = state->get_class(class_i);
const FlatSendTable &flat_send_table = state->flat_send_tables[clazz.dt_name];
Entity &entity = state->entities[entity_id];
if (entity.id != -1) {
visitor->visit_entity_deleted(entity);
}
entity = Entity(entity_id, clazz, flat_send_table);
const StringTableEntry &baseline = get_baseline_for(class_i);
Bitstream baseline_stream(baseline.value);
entity.update(baseline_stream);
entity.update(stream);
visitor->visit_entity_created(entity);
}
void read_entity_update(uint32_t entity_id, Bitstream &stream) {
XASSERT(entity_id < MAX_ENTITIES, "Entity id too big");
Entity &entity = state->entities[entity_id];
XASSERT(entity.id != -1, "Entity %d is not set up.", entity_id);
entity.update(stream);
visitor->visit_entity_updated(entity);
}
void dump_SVC_PacketEntities(const CSVCMsg_PacketEntities &entities) {
// Seem to get the first packet twice.
static bool first = true;
if (first) {
first = false;
return;
}
Bitstream stream(entities.entity_data());
uint32_t entity_id = -1;
size_t found = 0;
uint32_t update_type;
while (found < entities.updated_entries()) {
update_type = read_entity_header(&entity_id, stream);
if (update_type & UF_EnterPVS) {
read_entity_enter_pvs(entity_id, stream);
} else if (update_type & UF_LeavePVS) {
XASSERT(entities.is_delta(), "Leave PVS on full update");
if (update_type & UF_Delete) {
visitor->visit_entity_deleted(state->entities[entity_id]);
state->entities[entity_id].id = -1;
}
} else {
read_entity_update(entity_id, stream);
}
++found;
}
if (entities.is_delta()) {
while (stream.get_bits(1)) {
entity_id = stream.get_bits(11);
visitor->visit_entity_deleted(state->entities[entity_id]);
state->entities[entity_id].id = -1;
}
}
}
void dump_SVC_ServerInfo(const CSVCMsg_ServerInfo &info) {
XASSERT(!state, "Already seen SVC_ServerInfo.");
state = new State(info.max_classes());
}
void dump_DEM_ClassInfo(const CDemoClassInfo &info) {
XASSERT(state, "DEM_ClassInfo but no state.");
for (size_t i = 0; i < info.classes_size(); ++i) {
const CDemoClassInfo_class_t &clazz = info.classes(i);
state->create_class(clazz.class_id(), clazz.table_name(), clazz.network_name());
}
for (auto iter = state->send_tables.begin(); iter != state->send_tables.end(); ++iter) {
SendTable &table = *iter;
for (size_t i = 0; i < table.props.size(); ++i) {
SendProp &prop = table.props[i];
prop.in_table = &table;
if (prop.type == SP_Array) {
XASSERT(i > 0, "Array prop %s is at index zero.", prop.var_name.c_str());
prop.array_prop = &(table.props[i - 1]);
}
}
}
state->compile_send_tables();
}
void read_string_table_key(uint32_t first_bit, Bitstream &stream, char *buf,
size_t buf_length, std::vector<std::string> &key_history) {
if (first_bit && stream.get_bits(1)) {
XERROR("Not sure how to read this key");
} else {
uint32_t is_substring = stream.get_bits(1);
if (is_substring) {
uint32_t from_index = stream.get_bits(5);
uint32_t from_length = stream.get_bits(5);
key_history[from_index].copy(buf, from_length, 0);
stream.read_string(buf + from_length, buf_length - from_length);
} else {
stream.read_string(buf, buf_length);
}
}
}
void update_string_table(StringTable &table, size_t num_entries, const std::string &data) {
// These do something with precaches. This isn't a client so I'm assuming this
// is irrelevant.
if (table.flags & 2) {
return;
}
Bitstream stream(data);
uint32_t first_bit = stream.get_bits(1);
std::vector<std::string> key_history;
uint32_t entry_id = -1;
size_t entries_read = 0;
while (entries_read < num_entries) {
if (!stream.get_bits(1)) {
entry_id = stream.get_bits(table.entry_bits);
} else {
entry_id += 1;
}
XASSERT(entry_id < table.max_entries, "Entry id too large");
char key_buffer[MAX_KEY_SIZE];
char *key = 0;
if (stream.get_bits(1)) {
read_string_table_key(first_bit, stream, key_buffer, MAX_KEY_SIZE, key_history);
key = key_buffer;
// So technically we should only store the first 32 characters but I'm lazy.
if (key_history.size() == KEY_HISTORY_SIZE) {
key_history.erase(key_history.begin());
}
key_history.push_back(key);
}
char value_buffer[MAX_VALUE_SIZE];
char *value = 0;
size_t bit_length = 0;
size_t length = 0;
if (stream.get_bits(1)) {
if (table.flags & ST_FixedLength) {
length = table.user_data_size;
bit_length = table.user_data_size_bits;
} else {
length = stream.get_bits(14);
bit_length = 8 * length;
}
XASSERT(length < MAX_VALUE_SIZE, "Message too long.");
stream.read_bits(value_buffer, bit_length);
}
if (entry_id < table.count()) {
StringTableEntry &item = table.get(entry_id);
if (key) {
XASSERT(item.key == key, "Entry's keys don't match.");
}
if (value) {
item.value = std::string(value, length);
}
} else {
XASSERT(key, "Creating a new string table entry but no key specified.");
table.put(key, std::string(value_buffer, length));
}
++entries_read;
}
}
void handle_SVC_CreateStringTable(const CSVCMsg_CreateStringTable &table) {
XASSERT(state, "SVC_CreateStringTable but no state.");
StringTable &converted = state->create_string_table(table.name(),
(size_t) table.max_entries(), table.flags(), table.user_data_fixed_size(),
table.user_data_size(), table.user_data_size_bits());
update_string_table(converted, table.num_entries(), table.string_data());
}
void handle_SVC_UpdateStringTable(const CSVCMsg_UpdateStringTable &update) {
XASSERT(state, "SVC_UpdateStringTable but no state.");
StringTable &table = state->get_string_table(update.table_id());
update_string_table(table, update.num_changed_entries(), update.string_data());
}
void clear_entities() {
for (size_t i = 0; i < MAX_ENTITIES; ++i) {
Entity &entity = state->entities[i];
if (entity.id != -1) {
visitor->visit_entity_deleted(entity);
entity.id = -1;
}
}
}
void dump_DEM_Packet(const CDemoPacket &packet) {
const char *data = packet.data().c_str();
size_t offset = 0;
size_t length = packet.data().length();
while (offset < length) {
uint32_t command = read_var_int(data, length, &offset);
uint32_t size = read_var_int(data, length, &offset);
XASSERT(offset + size <= length, "Reading data outside of packet.");
if (command == svc_ServerInfo) {
CSVCMsg_ServerInfo info;
info.ParseFromArray(&(data[offset]), size);
dump_SVC_ServerInfo(info);
} else if (command == svc_PacketEntities) {
CSVCMsg_PacketEntities entities;
entities.ParseFromArray(&(data[offset]), size);
dump_SVC_PacketEntities(entities);
} else if (command == svc_CreateStringTable) {
CSVCMsg_CreateStringTable table;
table.ParseFromArray(&(data[offset]), size);
handle_SVC_CreateStringTable(table);
} else if (command == svc_UpdateStringTable) {
CSVCMsg_UpdateStringTable table;
table.ParseFromArray(&(data[offset]), size);
handle_SVC_UpdateStringTable(table);
}
offset += size;
}
}
void dump(const char *file) {
Demo demo(file);
for (int frame = 0; !demo.eof(); ++frame) {
int tick = 0;
size_t size;
bool compressed;
size_t uncompressed_size;
EDemoCommands command = demo.get_message_type(&tick, &compressed);
demo.read_message(compressed, &size, &uncompressed_size);
visitor->visit_tick(tick);
if (command == DEM_ClassInfo) {
CDemoClassInfo info;
info.ParseFromArray(demo.expose_buffer(), uncompressed_size);
dump_DEM_ClassInfo(info);
} else if (command == DEM_SendTables) {
CDemoSendTables tables;
tables.ParseFromArray(demo.expose_buffer(), uncompressed_size);
dump_DEM_SendTables(tables);
} else if (command == DEM_FullPacket) {
CDemoFullPacket packet;
packet.ParseFromArray(demo.expose_buffer(), uncompressed_size);
clear_entities();
dump_DEM_Packet(packet.packet());
} else if (command == DEM_Packet || command == DEM_SignonPacket) {
CDemoPacket packet;
packet.ParseFromArray(demo.expose_buffer(), uncompressed_size);
dump_DEM_Packet(packet);
}
}
}
int main(int argc, char **argv) {
if (argc <= 1) {
printf("Usage: %s something.dem\n", argv[0]);
exit(1);
} else {
dump(argv[1]);
}
return 0;
}
<commit_msg>Removed full packets, fixed bug #4.<commit_after>#include <stdint.h>
#include <iostream>
#include "demo.pb.h"
#include "netmessages.pb.h"
#include "bitstream.h"
#include "debug.h"
#include "demo.h"
#include "entity.h"
#include "state.h"
#include "death_recording_visitor.h"
#define INSTANCE_BASELINE_TABLE "instancebaseline"
#define KEY_HISTORY_SIZE 32
#define MAX_EDICTS 0x800
#define MAX_KEY_SIZE 0x400
#define MAX_VALUE_SIZE 0x4000
enum UpdateFlag {
UF_LeavePVS = 1,
UF_Delete = 2,
UF_EnterPVS = 4,
};
State *state = 0;
Visitor *visitor = new DeathRecordingVisitor();
uint32_t read_var_int(const char *data, size_t length, size_t *offset) {
uint32_t b;
int count = 0;
uint32_t result = 0;
do {
XASSERT(count != 5, "Corrupt data.");
XASSERT(*offset <= length, "Premature end of stream.");
b = data[(*offset)++];
result |= (b & 0x7F) << (7 * count);
++count;
} while (b & 0x80);
return result;
}
void dump_SVC_SendTable(const CSVCMsg_SendTable &table) {
XASSERT(state, "SVC_SendTable but no state created.");
SendTable &converted = state->create_send_table(table.net_table_name(), table.needs_decoder());
size_t prop_count = table.props_size();
for (size_t i = 0; i < prop_count; ++i) {
const CSVCMsg_SendTable_sendprop_t &prop = table.props(i);
SendProp c(
static_cast<SP_Types>(prop.type()),
prop.var_name(),
prop.flags(),
prop.priority(),
prop.dt_name(),
prop.num_elements(),
prop.low_value(),
prop.high_value(),
prop.num_bits());
converted.props.add(c);
}
}
void dump_DEM_SendTables(const CDemoSendTables &tables) {
const char *data = tables.data().c_str();
size_t offset = 0;
size_t length = tables.data().length();
while (offset < length) {
uint32_t command = read_var_int(data, length, &offset);
uint32_t size = read_var_int(data, length, &offset);
XASSERT(offset + size <= length, "Reading data outside of table.");
XASSERT(command == svc_SendTable, "Command %u in DEM_SendTables.", command);
CSVCMsg_SendTable send_table;
send_table.ParseFromArray(&(data[offset]), size);
dump_SVC_SendTable(send_table);
offset += size;
}
}
const StringTableEntry &get_baseline_for(int class_i) {
XASSERT(state, "No state created.");
StringTable &instance_baseline = state->get_string_table(INSTANCE_BASELINE_TABLE);
char buf[32];
sprintf(buf, "%d", class_i);
return instance_baseline.get(buf);
}
uint32_t read_entity_header(uint32_t *base, Bitstream &stream) {
uint32_t value = stream.get_bits(6);
if (value & 0x30) {
uint32_t a = (value >> 4) & 3;
uint32_t b = (a == 3) ? 16 : 0;
value = stream.get_bits(4 * a + b) << 4 | (value & 0xF);
}
*base += value + 1;
unsigned int update_flags = 0;
if (!stream.get_bits(1)) {
if (stream.get_bits(1)) {
update_flags |= UF_EnterPVS;
}
} else {
update_flags |= UF_LeavePVS;
if (stream.get_bits(1)) {
update_flags |= UF_Delete;
}
}
return update_flags;
}
void read_entity_enter_pvs(uint32_t entity_id, Bitstream &stream) {
uint32_t class_i = stream.get_bits(state->class_bits);
uint32_t serial = stream.get_bits(10);
XASSERT(entity_id < MAX_EDICTS, "Entity %ld exceeds max edicts.", entity_id);
const Class &clazz = state->get_class(class_i);
const FlatSendTable &flat_send_table = state->flat_send_tables[clazz.dt_name];
Entity &entity = state->entities[entity_id];
if (entity.id != -1) {
visitor->visit_entity_deleted(entity);
}
entity = Entity(entity_id, clazz, flat_send_table);
const StringTableEntry &baseline = get_baseline_for(class_i);
Bitstream baseline_stream(baseline.value);
entity.update(baseline_stream);
entity.update(stream);
visitor->visit_entity_created(entity);
}
void read_entity_update(uint32_t entity_id, Bitstream &stream) {
XASSERT(entity_id < MAX_ENTITIES, "Entity id too big");
Entity &entity = state->entities[entity_id];
XASSERT(entity.id != -1, "Entity %d is not set up.", entity_id);
entity.update(stream);
visitor->visit_entity_updated(entity);
}
void dump_SVC_PacketEntities(const CSVCMsg_PacketEntities &entities) {
Bitstream stream(entities.entity_data());
uint32_t entity_id = -1;
size_t found = 0;
uint32_t update_type;
while (found < entities.updated_entries()) {
update_type = read_entity_header(&entity_id, stream);
if (update_type & UF_EnterPVS) {
read_entity_enter_pvs(entity_id, stream);
} else if (update_type & UF_LeavePVS) {
XASSERT(entities.is_delta(), "Leave PVS on full update");
if (update_type & UF_Delete) {
visitor->visit_entity_deleted(state->entities[entity_id]);
state->entities[entity_id].id = -1;
}
} else {
read_entity_update(entity_id, stream);
}
++found;
}
if (entities.is_delta()) {
while (stream.get_bits(1)) {
entity_id = stream.get_bits(11);
visitor->visit_entity_deleted(state->entities[entity_id]);
state->entities[entity_id].id = -1;
}
}
}
void dump_SVC_ServerInfo(const CSVCMsg_ServerInfo &info) {
XASSERT(!state, "Already seen SVC_ServerInfo.");
state = new State(info.max_classes());
}
void dump_DEM_ClassInfo(const CDemoClassInfo &info) {
XASSERT(state, "DEM_ClassInfo but no state.");
for (size_t i = 0; i < info.classes_size(); ++i) {
const CDemoClassInfo_class_t &clazz = info.classes(i);
state->create_class(clazz.class_id(), clazz.table_name(), clazz.network_name());
}
for (auto iter = state->send_tables.begin(); iter != state->send_tables.end(); ++iter) {
SendTable &table = *iter;
for (size_t i = 0; i < table.props.size(); ++i) {
SendProp &prop = table.props[i];
prop.in_table = &table;
if (prop.type == SP_Array) {
XASSERT(i > 0, "Array prop %s is at index zero.", prop.var_name.c_str());
prop.array_prop = &(table.props[i - 1]);
}
}
}
state->compile_send_tables();
}
void read_string_table_key(uint32_t first_bit, Bitstream &stream, char *buf,
size_t buf_length, std::vector<std::string> &key_history) {
if (first_bit && stream.get_bits(1)) {
XERROR("Not sure how to read this key");
} else {
uint32_t is_substring = stream.get_bits(1);
if (is_substring) {
uint32_t from_index = stream.get_bits(5);
uint32_t from_length = stream.get_bits(5);
key_history[from_index].copy(buf, from_length, 0);
stream.read_string(buf + from_length, buf_length - from_length);
} else {
stream.read_string(buf, buf_length);
}
}
}
void update_string_table(StringTable &table, size_t num_entries, const std::string &data) {
// These do something with precaches. This isn't a client so I'm assuming this
// is irrelevant.
if (table.flags & 2) {
return;
}
Bitstream stream(data);
uint32_t first_bit = stream.get_bits(1);
std::vector<std::string> key_history;
uint32_t entry_id = -1;
size_t entries_read = 0;
while (entries_read < num_entries) {
if (!stream.get_bits(1)) {
entry_id = stream.get_bits(table.entry_bits);
} else {
entry_id += 1;
}
XASSERT(entry_id < table.max_entries, "Entry id too large");
char key_buffer[MAX_KEY_SIZE];
char *key = 0;
if (stream.get_bits(1)) {
read_string_table_key(first_bit, stream, key_buffer, MAX_KEY_SIZE, key_history);
key = key_buffer;
// So technically we should only store the first 32 characters but I'm lazy.
if (key_history.size() == KEY_HISTORY_SIZE) {
key_history.erase(key_history.begin());
}
key_history.push_back(key);
}
char value_buffer[MAX_VALUE_SIZE];
char *value = 0;
size_t bit_length = 0;
size_t length = 0;
if (stream.get_bits(1)) {
if (table.flags & ST_FixedLength) {
length = table.user_data_size;
bit_length = table.user_data_size_bits;
} else {
length = stream.get_bits(14);
bit_length = 8 * length;
}
XASSERT(length < MAX_VALUE_SIZE, "Message too long.");
stream.read_bits(value_buffer, bit_length);
}
if (entry_id < table.count()) {
StringTableEntry &item = table.get(entry_id);
if (key) {
XASSERT(item.key == key, "Entry's keys don't match.");
}
if (value) {
item.value = std::string(value, length);
}
} else {
XASSERT(key, "Creating a new string table entry but no key specified.");
table.put(key, std::string(value_buffer, length));
}
++entries_read;
}
}
void handle_SVC_CreateStringTable(const CSVCMsg_CreateStringTable &table) {
XASSERT(state, "SVC_CreateStringTable but no state.");
StringTable &converted = state->create_string_table(table.name(),
(size_t) table.max_entries(), table.flags(), table.user_data_fixed_size(),
table.user_data_size(), table.user_data_size_bits());
update_string_table(converted, table.num_entries(), table.string_data());
}
void handle_SVC_UpdateStringTable(const CSVCMsg_UpdateStringTable &update) {
XASSERT(state, "SVC_UpdateStringTable but no state.");
StringTable &table = state->get_string_table(update.table_id());
update_string_table(table, update.num_changed_entries(), update.string_data());
}
void clear_entities() {
for (size_t i = 0; i < MAX_ENTITIES; ++i) {
Entity &entity = state->entities[i];
if (entity.id != -1) {
visitor->visit_entity_deleted(entity);
entity.id = -1;
}
}
}
void dump_DEM_Packet(const CDemoPacket &packet) {
const char *data = packet.data().c_str();
size_t offset = 0;
size_t length = packet.data().length();
while (offset < length) {
uint32_t command = read_var_int(data, length, &offset);
uint32_t size = read_var_int(data, length, &offset);
XASSERT(offset + size <= length, "Reading data outside of packet.");
if (command == svc_ServerInfo) {
CSVCMsg_ServerInfo info;
info.ParseFromArray(&(data[offset]), size);
dump_SVC_ServerInfo(info);
} else if (command == svc_PacketEntities) {
CSVCMsg_PacketEntities entities;
entities.ParseFromArray(&(data[offset]), size);
dump_SVC_PacketEntities(entities);
} else if (command == svc_CreateStringTable) {
CSVCMsg_CreateStringTable table;
table.ParseFromArray(&(data[offset]), size);
handle_SVC_CreateStringTable(table);
} else if (command == svc_UpdateStringTable) {
CSVCMsg_UpdateStringTable table;
table.ParseFromArray(&(data[offset]), size);
handle_SVC_UpdateStringTable(table);
}
offset += size;
}
}
void dump(const char *file) {
Demo demo(file);
for (int frame = 0; !demo.eof(); ++frame) {
int tick = 0;
size_t size;
bool compressed;
size_t uncompressed_size;
EDemoCommands command = demo.get_message_type(&tick, &compressed);
demo.read_message(compressed, &size, &uncompressed_size);
visitor->visit_tick(tick);
if (command == DEM_ClassInfo) {
CDemoClassInfo info;
info.ParseFromArray(demo.expose_buffer(), uncompressed_size);
dump_DEM_ClassInfo(info);
} else if (command == DEM_SendTables) {
CDemoSendTables tables;
tables.ParseFromArray(demo.expose_buffer(), uncompressed_size);
dump_DEM_SendTables(tables);
} else if (command == DEM_Packet || command == DEM_SignonPacket) {
CDemoPacket packet;
packet.ParseFromArray(demo.expose_buffer(), uncompressed_size);
dump_DEM_Packet(packet);
}
}
}
int main(int argc, char **argv) {
if (argc <= 1) {
printf("Usage: %s something.dem\n", argv[0]);
exit(1);
} else {
dump(argv[1]);
}
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you 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.
*******************************************************************************/
//==============================================================================
// Main
//==============================================================================
#include "checkforupdateswindow.h"
#include "cliutils.h"
#include "guiutils.h"
#include "mainwindow.h"
#include "settings.h"
#include "splashscreenwindow.h"
//==============================================================================
#include <QDir>
#include <QLocale>
#include <QProcess>
#include <QSettings>
#include <QVariant>
#ifdef Q_OS_WIN
#include <QWebSettings>
#endif
//==============================================================================
#include <QtSingleApplication>
//==============================================================================
int main(int pArgC, char *pArgV[])
{
// Initialise Qt's message pattern
OpenCOR::initQtMessagePattern();
// Determine whether we should try the CLI version of OpenCOR:
// - Windows: we never try the CLI version of OpenCOR. We go straight for
// its GUI version.
// - Linux: we always try the CLI version of OpenCOR and then go for its
// GUI version, if needed.
// - OS X: we try the CLI version of OpenCOR unless the user double clicks
// on the OpenCOR bundle or opens it from the command line by
// entering something like:
// open OpenCOR.app
// in which case we go for its GUI version.
// Note #1: on Windows, we have two binaries (.com and .exe that are for the
// CLI and GUI versions of OpenCOR, respectively). This means that
// when a console window is open, to enter something like:
// C:\>OpenCOR
// will effectively call OpenCOR.com. From there, should there be
// no argument that requires CLI treatment, then the GUI version of
// OpenCOR will be run. This is, unfortunately, the only way to
// have OpenCOR to behave as both a CLI and a GUI application on
// Windows, hence the [OpenCOR]/windows/main.cpp file, which is
// used to generate the CLI version of OpenCOR...
// Note #2: on OS X, if we were to try to open the OpenCOR bundle from the
// command line, then we would get an error message similar to:
// LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app.
// Fortunately, when double clicking on the OpenCOR bundle or
// opening it from the command line, a special argument in the form
// of -psn_0_1234567 is passed to OpenCOR, so we can use that to
// determine whether we need to force OpenCOR to be run in GUI mode
// or whether we first try the CLI version of OpenCOR, and then its
// GUI version, if needed...
#if defined(Q_OS_WIN)
bool tryCliVersion = false;
#elif defined(Q_OS_LINUX)
bool tryCliVersion = true;
#elif defined(Q_OS_MAC)
bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5);
#else
#error Unsupported platform
#endif
// Run the CLI version of OpenCOR, if possible/needed
if (tryCliVersion) {
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create and initialise the CLI version of OpenCOR
QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV);
OpenCOR::initApplication(cliApp);
// Try to run the CLI version of OpenCOR
int res;
bool runCliApplication = OpenCOR::cliApplication(cliApp, &res);
OpenCOR::removeGlobalSettings();
delete cliApp;
if (runCliApplication) {
// OpenCOR was run as a CLI application, so leave
return res;
}
// Note: at this stage, we tried the CLI version of OpenCOR, but in the
// end we need to go for its GUI version, so start over but with
// the GUI version of OpenCOR this time...
}
// Make sure that we always use indirect rendering on Linux
// Note: indeed, depending on which plugins are selected, OpenCOR may need
// LLVM. If that's the case, and in case the user's video card uses a
// driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there
// may be a conflict between the version of LLVM used by OpenCOR and
// the one used by the video card. One way to address this issue is by
// using indirect rendering...
#ifdef Q_OS_LINUX
qputenv("LIBGL_ALWAYS_INDIRECT", "1");
#endif
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create the GUI version of OpenCOR
SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(),
pArgC, pArgV);
// Send a message (containing the arguments that were passed to this
// instance of OpenCOR minus the first one since it corresponds to the full
// path to our executable, which we are not interested in) to our 'official'
// instance of OpenCOR, should there be one. If there is none, then just
// carry on as normal, otherwise exit since we want only one instance of
// OpenCOR at any given time
QStringList appArguments = guiApp->arguments();
appArguments.removeFirst();
QString arguments = appArguments.join("|");
if (guiApp->isRunning()) {
guiApp->sendMessage(arguments);
delete guiApp;
return 0;
}
// Initialise the GUI version of OpenCOR
QString appDate = QString();
OpenCOR::initApplication(guiApp, &appDate);
// Check whether we want to check for new versions at startup and, if so,
// whether a new version of OpenCOR is available
QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication);
#ifndef QT_DEBUG
settings.beginGroup("CheckForUpdatesWindow");
bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool();
bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool();
settings.endGroup();
if (checkForUpdatesAtStartup) {
OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate);
checkForUpdatesEngine->check();
if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion())
|| (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) {
// Retrieve the language to be used to show the check for updates
// window
QString locale = OpenCOR::locale();
QLocale::setDefault(QLocale(locale));
QTranslator qtTranslator;
QTranslator appTranslator;
qtTranslator.load(":qt_"+locale);
qApp->installTranslator(&qtTranslator);
appTranslator.load(":app_"+locale);
qApp->installTranslator(&appTranslator);
// Show the check for updates window
// Note: checkForUpdatesEngine gets deleted by
// checkForUpdatesWindow...
OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine);
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.loadSettings(&settings);
settings.endGroup();
checkForUpdatesWindow.exec();
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.saveSettings(&settings);
settings.endGroup();
} else {
delete checkForUpdatesEngine;
}
}
#endif
// Create and show our splash screen, if we are not in debug mode
#ifndef QT_DEBUG
OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow();
splashScreen->show();
#endif
// Create our main window
OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate);
// Keep track of our main window (required by QtSingleApplication so that it
// can do what it's supposed to be doing)
guiApp->setActivationWindow(win);
// Handle our arguments
win->handleArguments(arguments);
// Show our main window
win->show();
// By default, we can and should execute our application
bool canExecuteAplication = true;
// Close and delete our splash screen once our main window is visible, if we
// are not in debug mode
#ifndef QT_DEBUG
splashScreen->closeAndDeleteAfter(win);
// Make sure that our main window is in the foreground, unless the user
// decided to close our main window while we were showing our splash screen
// Note: indeed, on Linux, to show our splash screen may result in our main
// window being shown in the background...
if (!win->shuttingDown())
win->showSelf();
else
canExecuteAplication = false;
#endif
// Execute our application, if possible
int res;
if (canExecuteAplication)
res = guiApp->exec();
else
res = 0;
// Keep track of our application file and directory paths (in case we need
// to restart OpenCOR)
QString appFilePath = guiApp->applicationFilePath();
QString appDirPath = guiApp->applicationDirPath();
// Delete our main window
delete win;
// We use QtWebKit, and QWebPage in particular, which results in some leak
// messages being generated on Windows when leaving OpenCOR. This is because
// an object cache is shared between all QWebPage instances. So to destroy a
// QWebPage instance doesn't clear the cache, hence the leak messages.
// However, those messages are 'only' warnings, so we can safely live with
// them. Still, it doesn't look 'good', so we clear the memory caches, thus
// avoiding those leak messages...
// Note: the below must absolutely be done after calling guiApp->exec() and
// before deleting guiApp...
#ifdef Q_OS_WIN
QWebSettings::clearMemoryCaches();
#endif
// Remove the global settings that were created and used during this session
OpenCOR::removeGlobalSettings();
// Delete our application
delete guiApp;
// We are done with the execution of our application, so now the question is
// whether we need to restart
// Note: we do this here rather than 'within' the GUI because once we have
// launched a new instance of OpenCOR, we want this instance of
// OpenCOR to finish as soon as possible, which will be the case here
// since all that remains to be done is to return the result of the
// execution of our application...
if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) {
// We want to restart, so the question is whether we want a normal
// restart or a clean one
if (res == OpenCOR::CleanRestart) {
// We want a clean restart, so clear all the user settings (indeed,
// this will ensure that the various windows are, for instance,
// properly reset with regards to their dimensions)
settings.clear();
}
// Restart OpenCOR, but without providing any of the arguments that were
// originally passed to us since we want to reset everything
QProcess::startDetached(appFilePath, QStringList(), appDirPath);
}
// We are done running the GUI version of OpenCOR, so leave
return res;
}
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you 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.
*******************************************************************************/
//==============================================================================
// Main
//==============================================================================
#include "checkforupdateswindow.h"
#include "cliutils.h"
#include "guiutils.h"
#include "mainwindow.h"
#include "settings.h"
#include "splashscreenwindow.h"
//==============================================================================
#include <QDir>
#include <QLocale>
#include <QProcess>
#include <QSettings>
#include <QVariant>
#ifdef Q_OS_WIN
#include <QWebSettings>
#endif
//==============================================================================
#include <QtSingleApplication>
//==============================================================================
int main(int pArgC, char *pArgV[])
{
// Initialise Qt's message pattern
OpenCOR::initQtMessagePattern();
// Determine whether we should try the CLI version of OpenCOR:
// - Windows: we never try the CLI version of OpenCOR. We go straight for
// its GUI version.
// - Linux: we always try the CLI version of OpenCOR and then go for its
// GUI version, if needed.
// - OS X: we try the CLI version of OpenCOR unless the user double clicks
// on the OpenCOR bundle or opens it from the command line by
// entering something like:
// open OpenCOR.app
// in which case we go for its GUI version.
// Note #1: on Windows, we have two binaries (.com and .exe that are for the
// CLI and GUI versions of OpenCOR, respectively). This means that
// when a console window is open, to enter something like:
// C:\>OpenCOR
// will effectively call OpenCOR.com. From there, should there be
// no argument that requires CLI treatment, then the GUI version of
// OpenCOR will be run. This is, unfortunately, the only way to
// have OpenCOR to behave as both a CLI and a GUI application on
// Windows, hence the [OpenCOR]/windows/main.cpp file, which is
// used to generate the CLI version of OpenCOR...
// Note #2: on OS X, if we were to try to open the OpenCOR bundle from the
// command line, then we would get an error message similar to:
// LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app.
// Fortunately, when double clicking on the OpenCOR bundle or
// opening it from the command line, a special argument in the form
// of -psn_0_1234567 is passed to OpenCOR, so we can use that to
// determine whether we need to force OpenCOR to be run in GUI mode
// or whether we first try the CLI version of OpenCOR, and then its
// GUI version, if needed...
#if defined(Q_OS_WIN)
bool tryCliVersion = false;
#elif defined(Q_OS_LINUX)
bool tryCliVersion = true;
#elif defined(Q_OS_MAC)
bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5);
#else
#error Unsupported platform
#endif
// Run the CLI version of OpenCOR, if possible/needed
if (tryCliVersion) {
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create and initialise the CLI version of OpenCOR
QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV);
OpenCOR::initApplication(cliApp);
// Try to run the CLI version of OpenCOR
int res;
bool runCliApplication = OpenCOR::cliApplication(cliApp, &res);
OpenCOR::removeGlobalSettings();
delete cliApp;
if (runCliApplication) {
// OpenCOR was run as a CLI application, so leave
return res;
}
// Note: at this stage, we tried the CLI version of OpenCOR, but in the
// end we need to go for its GUI version, so start over but with
// the GUI version of OpenCOR this time...
}
// Make sure that we always use indirect rendering on Linux
// Note: indeed, depending on which plugins are selected, OpenCOR may need
// LLVM. If that's the case, and in case the user's video card uses a
// driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there
// may be a conflict between the version of LLVM used by OpenCOR and
// the one used by the video card. One way to address this issue is by
// using indirect rendering...
#ifdef Q_OS_LINUX
qputenv("LIBGL_ALWAYS_INDIRECT", "1");
#endif
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create the GUI version of OpenCOR
SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(),
pArgC, pArgV);
// Send a message (containing the arguments that were passed to this
// instance of OpenCOR minus the first one since it corresponds to the full
// path to our executable, which we are not interested in) to our 'official'
// instance of OpenCOR, should there be one. If there is none, then just
// carry on as normal, otherwise exit since we want only one instance of
// OpenCOR at any given time
QStringList appArguments = guiApp->arguments();
appArguments.removeFirst();
QString arguments = appArguments.join("|");
if (guiApp->isRunning()) {
guiApp->sendMessage(arguments);
delete guiApp;
return 0;
}
// Initialise the GUI version of OpenCOR
QString appDate = QString();
OpenCOR::initApplication(guiApp, &appDate);
// Check whether we want to check for new versions at startup and, if so,
// whether a new version of OpenCOR is available
QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication);
#ifndef QT_DEBUG
settings.beginGroup("CheckForUpdatesWindow");
bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool();
bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool();
settings.endGroup();
if (checkForUpdatesAtStartup) {
OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate);
checkForUpdatesEngine->check();
if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion())
|| (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) {
// Retrieve the language to be used to show the check for updates
// window
QString locale = OpenCOR::locale();
QLocale::setDefault(QLocale(locale));
QTranslator qtTranslator;
QTranslator appTranslator;
qtTranslator.load(":qt_"+locale);
guiApp->installTranslator(&qtTranslator);
appTranslator.load(":app_"+locale);
guiApp->installTranslator(&appTranslator);
// Show the check for updates window
// Note: checkForUpdatesEngine gets deleted by
// checkForUpdatesWindow...
OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine);
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.loadSettings(&settings);
settings.endGroup();
checkForUpdatesWindow.exec();
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.saveSettings(&settings);
settings.endGroup();
} else {
delete checkForUpdatesEngine;
}
}
#endif
// Create and show our splash screen, if we are not in debug mode
#ifndef QT_DEBUG
OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow();
splashScreen->show();
#endif
// Create our main window
OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate);
// Keep track of our main window (required by QtSingleApplication so that it
// can do what it's supposed to be doing)
guiApp->setActivationWindow(win);
// Handle our arguments
win->handleArguments(arguments);
// Show our main window
win->show();
// By default, we can and should execute our application
bool canExecuteAplication = true;
// Close and delete our splash screen once our main window is visible, if we
// are not in debug mode
#ifndef QT_DEBUG
splashScreen->closeAndDeleteAfter(win);
// Make sure that our main window is in the foreground, unless the user
// decided to close our main window while we were showing our splash screen
// Note: indeed, on Linux, to show our splash screen may result in our main
// window being shown in the background...
if (!win->shuttingDown())
win->showSelf();
else
canExecuteAplication = false;
#endif
// Execute our application, if possible
int res;
if (canExecuteAplication)
res = guiApp->exec();
else
res = 0;
// Keep track of our application file and directory paths (in case we need
// to restart OpenCOR)
QString appFilePath = guiApp->applicationFilePath();
QString appDirPath = guiApp->applicationDirPath();
// Delete our main window
delete win;
// We use QtWebKit, and QWebPage in particular, which results in some leak
// messages being generated on Windows when leaving OpenCOR. This is because
// an object cache is shared between all QWebPage instances. So to destroy a
// QWebPage instance doesn't clear the cache, hence the leak messages.
// However, those messages are 'only' warnings, so we can safely live with
// them. Still, it doesn't look 'good', so we clear the memory caches, thus
// avoiding those leak messages...
// Note: the below must absolutely be done after calling guiApp->exec() and
// before deleting guiApp...
#ifdef Q_OS_WIN
QWebSettings::clearMemoryCaches();
#endif
// Remove the global settings that were created and used during this session
OpenCOR::removeGlobalSettings();
// Delete our application
delete guiApp;
// We are done with the execution of our application, so now the question is
// whether we need to restart
// Note: we do this here rather than 'within' the GUI because once we have
// launched a new instance of OpenCOR, we want this instance of
// OpenCOR to finish as soon as possible, which will be the case here
// since all that remains to be done is to return the result of the
// execution of our application...
if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) {
// We want to restart, so the question is whether we want a normal
// restart or a clean one
if (res == OpenCOR::CleanRestart) {
// We want a clean restart, so clear all the user settings (indeed,
// this will ensure that the various windows are, for instance,
// properly reset with regards to their dimensions)
settings.clear();
}
// Restart OpenCOR, but without providing any of the arguments that were
// originally passed to us since we want to reset everything
QProcess::startDetached(appFilePath, QStringList(), appDirPath);
}
// We are done running the GUI version of OpenCOR, so leave
return res;
}
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include "RobustFeatureMatching.hpp"
#include <iostream>
cv::Mat stichImages (cv::Mat imgInput1, std::vector<cv::Point2f> &inlierPoints1, cv::Mat imgInput2, std::vector<cv::Point2f> &inlierPoints2)
{
cv::Mat H = cv::findHomography(cv::Mat(inlierPoints2),
cv::Mat(inlierPoints1),
cv::FM_RANSAC,
1.0);
// Use the Homography Matrix to warp the images
std::cout << "Homo: " << H << std::endl;
cv::Mat result, warpImage2;
cv::warpPerspective(imgInput2, warpImage2, H, cv::Size(imgInput2.cols * 2, imgInput2.rows * 2), cv::INTER_CUBIC);
// cv::imwrite("warp.jpg", warpImage2);
cv::Mat finalHomo(cv::Size(imgInput2.cols * 2 + imgInput1.cols, imgInput2.rows * 2), imgInput2.type());
// cv::imwrite("finalHomo.jpg", finalHomo);
cv::Mat roi1(finalHomo, cv::Rect(0, 0, imgInput1.cols, imgInput1.rows));
cv::Mat roi2(finalHomo, cv::Rect(0, 0, warpImage2.cols, warpImage2.rows));
// cv::imwrite("roi1.jpg", roi1);
// cv::imwrite("roi2.jpg", roi2);
warpImage2.copyTo(roi2);
// cv::imwrite("roi2.jpg", roi2);
imgInput1.copyTo(roi1);
// cv::imwrite("roi1.jpg", roi1);
// cv::imwrite("finalHomo.jpg", finalHomo);
int colInx = 0;
for (size_t i(0); i < warpImage2.cols; i++)
{
cv::Scalar res = cv::sum(warpImage2.col(i));
if (res[0] == 0)
{
colInx = i;
break;
}
}
std::cout << "Col Inx: " << colInx << std::endl;
int rowInx = 0;
for (size_t i(0); i < warpImage2.rows; i++)
{
cv::Scalar res = cv::sum(warpImage2.row(i));
if (res[0] == 0)
{
rowInx = i;
break;
}
}
std::cout << "Row Inx: " << rowInx << std::endl;
cv::Mat cropImage(warpImage2, cv::Rect(0 , 0, colInx, rowInx));
return cropImage;
/// crop over the finalHomo
// int colInx = 0;
// for (size_t i(0); i < finalHomo.cols; i++)
// {
// cv::Scalar res = cv::sum(finalHomo.col(i));
// if (res[0] == 0)
// {
// colInx = i;
// break;
// }
// }
// std::cout << "Col Inx: " << colInx << std::endl;
// int rowInx = 0;
// for (size_t i(0); i < finalHomo.rows; i++)
// {
// cv::Scalar res = cv::sum(finalHomo.row(i));
// if (res[0] == 0)
// {
// rowInx = i;
// break;
// }
// }
// std::cout << "Row Inx: " << rowInx << std::endl;
// cv::Mat cropImage(finalHomo, cv::Rect(0 , 0, colInx, rowInx));
// return cropImage;
}
int main(int argc, char *argv[])
{
cv::Mat imgInput1 = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
cv::Mat imgInput2 = cv::imread(argv[2], cv::IMREAD_GRAYSCALE);
std::vector <cv::Point2f> inlierPoints1;
std::vector <cv::Point2f> inlierPoints2;
cv::Mat fundamental;
RobustFeatureMatching matcher(0.8, 1.0, 0.99, 6);
std::vector <cv::DMatch> finalMatches = matcher.run(imgInput1, imgInput2);
std::cout << "Size Matched Points: " << finalMatches.size() << std::endl;
std::pair < std::vector <cv::KeyPoint>, std::vector <cv::KeyPoint> > keyPoints = matcher.getKeyPoints();
cv::Mat matchImage;
cv::drawMatches(imgInput1, keyPoints.first, imgInput2, keyPoints.second, finalMatches, matchImage);
cv::imwrite(argv[3], matchImage);
std::pair < std::vector <cv::Point2f>, std::vector <cv::Point2f> > inlierPoints = matcher.getInlierPoints();
cv::Mat cropImage = stichImages (imgInput1, inlierPoints.first, imgInput2, inlierPoints.second);
cv::imwrite(argv[4], cropImage);
finalMatches = matcher.run(imgInput1, cropImage);
std::cout << "Size Matched Points: " << finalMatches.size() << std::endl;
keyPoints = matcher.getKeyPoints();
cv::drawMatches(imgInput1, keyPoints.first, cropImage, keyPoints.second, finalMatches, matchImage);
cv::imwrite(argv[5], matchImage);
// cv::imshow("Image Matches", matchImage);
// cv::waitKey(0);
return 0;
}<commit_msg>Run feature matching for wrap image and first image<commit_after>#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include "RobustFeatureMatching.hpp"
#include <iostream>
cv::Mat stichImages (cv::Mat imgInput1, std::vector<cv::Point2f> &inlierPoints1, cv::Mat imgInput2, std::vector<cv::Point2f> &inlierPoints2)
{
cv::Mat H = cv::findHomography(cv::Mat(inlierPoints2),
cv::Mat(inlierPoints1),
cv::FM_RANSAC,
1.0);
// Use the Homography Matrix to warp the images
std::cout << "Homo: " << H << std::endl;
cv::Mat result, warpImage2;
cv::warpPerspective(imgInput2, warpImage2, H, cv::Size(imgInput2.cols * 2, imgInput2.rows * 2), cv::INTER_CUBIC);
// cv::imwrite("warp.jpg", warpImage2);
cv::Mat finalHomo(cv::Size(imgInput2.cols * 2 + imgInput1.cols, imgInput2.rows * 2), imgInput2.type());
// cv::imwrite("finalHomo.jpg", finalHomo);
cv::Mat roi1(finalHomo, cv::Rect(0, 0, imgInput1.cols, imgInput1.rows));
cv::Mat roi2(finalHomo, cv::Rect(0, 0, warpImage2.cols, warpImage2.rows));
// cv::imwrite("roi1.jpg", roi1);
// cv::imwrite("roi2.jpg", roi2);
warpImage2.copyTo(roi2);
// cv::imwrite("roi2.jpg", roi2);
imgInput1.copyTo(roi1);
// cv::imwrite("roi1.jpg", roi1);
// cv::imwrite("finalHomo.jpg", finalHomo);
int colInx = 0;
for (size_t i(0); i < warpImage2.cols; i++)
{
cv::Scalar res = cv::sum(warpImage2.col(i));
if (res[0] == 0)
{
colInx = i;
break;
}
}
std::cout << "Col Inx: " << colInx << std::endl;
int rowInx = 0;
for (size_t i(0); i < warpImage2.rows; i++)
{
cv::Scalar res = cv::sum(warpImage2.row(i));
if (res[0] == 0)
{
rowInx = i;
break;
}
}
std::cout << "Row Inx: " << rowInx << std::endl;
cv::Mat cropImage(warpImage2, cv::Rect(0 , 0, colInx, rowInx));
return cropImage;
/// crop over the finalHomo
// int colInx = 0;
// for (size_t i(0); i < finalHomo.cols; i++)
// {
// cv::Scalar res = cv::sum(finalHomo.col(i));
// if (res[0] == 0)
// {
// colInx = i;
// break;
// }
// }
// std::cout << "Col Inx: " << colInx << std::endl;
// int rowInx = 0;
// for (size_t i(0); i < finalHomo.rows; i++)
// {
// cv::Scalar res = cv::sum(finalHomo.row(i));
// if (res[0] == 0)
// {
// rowInx = i;
// break;
// }
// }
// std::cout << "Row Inx: " << rowInx << std::endl;
// cv::Mat cropImage(finalHomo, cv::Rect(0 , 0, colInx, rowInx));
// return cropImage;
}
int main(int argc, char *argv[])
{
cv::Mat imgInput1 = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
cv::Mat imgInput2 = cv::imread(argv[2], cv::IMREAD_GRAYSCALE);
std::vector <cv::Point2f> inlierPoints1;
std::vector <cv::Point2f> inlierPoints2;
cv::Mat fundamental;
RobustFeatureMatching matcher(0.8, 1.0, 0.99, 6);
std::vector <cv::DMatch> finalMatches = matcher.run(imgInput1, imgInput2);
std::cout << "Size Matched Points: " << finalMatches.size() << std::endl;
std::pair < std::vector <cv::KeyPoint>, std::vector <cv::KeyPoint> > keyPoints = matcher.getKeyPoints();
cv::Mat matchImage;
cv::drawMatches(imgInput1, keyPoints.first, imgInput2, keyPoints.second, finalMatches, matchImage);
cv::imwrite(argv[3], matchImage);
std::pair < std::vector <cv::Point2f>, std::vector <cv::Point2f> > inlierPoints = matcher.getInlierPoints();
cv::Mat cropImage = stichImages (imgInput1, inlierPoints.first, imgInput2, inlierPoints.second);
cv::imwrite(argv[4], cropImage);
RobustFeatureMatching matcher2(0.8, 1.0, 0.99, 6);
finalMatches = matcher2.run(imgInput1, cropImage);
std::cout << "Size Matched Points: " << finalMatches.size() << std::endl;
keyPoints = matcher2.getKeyPoints();
cv::drawMatches(imgInput1, keyPoints.first, cropImage, keyPoints.second, finalMatches, matchImage);
cv::imwrite(argv[5], matchImage);
// cv::imshow("Image Matches", matchImage);
// cv::waitKey(0);
return 0;
}<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
// swap integers
void swap(int &a, int &b){
int t = b;
b = a;
a = t;
}
int bigger(int a, int b){
return a>b?a:b;
}
int main()
{
cout << "hello world/n";
return 0;
}
<commit_msg>added swap test case<commit_after>#include <iostream>
using namespace std;
// swap integers
void swap(int &a, int &b){
int t = b;
b = a;
a = t;
}
int bigger(int a, int b){
return a>b?a:b;
}
int main()
{
cout << swap(1,2);
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read galaxies
Gals G;
if(F.Ascii){
G=read_galaxies_ascii(F);}
else{
G = read_galaxies(F);
}
F.Ngal = G.size();
printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
std::vector<int> count;
count=count_galaxies(G);
for(int i=0;i<8;i++){printf (" %d \n",count[i]);}
// make MTL
MTL M=make_MTL(G,F);
for(int i=0;i<M.priority_list.size();++i){
printf(" priority %d",M.priority_list[i]);
}
printf(" \n");
assign_priority_class(M);
//find available SS and SF galaxies on each petal
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
count_class[M[i].priority_class]+=1;
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
printf(" number of MTL galaxies %d\n",M.size());
printf("Read fiber center positions and compute related things\n");
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
printf("spectrometer has to be identified from 0 to F.Npetal-1\n");
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
printf("get neighbors of each fiber;\n");
//for each spectrometer, get list of fibers
printf("Read plates in order they are to be observed\n ");
Plates P_original = read_plate_centers(F);
F.Nplate=P_original.size();
printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n");
Plates P;
P.resize(F.Nplate);
List permut = random_permut(F.Nplate);
for (int jj=0; jj<F.Nplate; jj++){
P[jj]=P_original[permut[jj]];
}
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf("before assignment\n");
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
simple_assign(M,P,pp,F,A);
diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Want to have even distribution of unused fibers
// so we can put in sky fibers and standard stars
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
for (int i=0; i<1; i++) { // more iterations will improve performance slightly
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
}
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
// Still not updated, so all QSO targets have multiple observations etc
// Apply and update the plan --------------------------------------
init_time_at(time,"# Begin real time assignment",t);
for (int jj=0; jj<F.Nplate; jj++) {
int j = A.next_plate;
//assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
//assign_unused(j,M,P,pp,F,A);
//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies
//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");
A.next_plate++;
// Redistribute and improve on various occasions add more times if desired
if ( j==2000 || j==4000) {
printf(" j == %d \n",j);
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
diagnostic(M,G,F,A);
}
}
print_time(time,"# ... took :");
// Results -------------------------------------------------------
if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output
display_results("doc/figs/",M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>print j at 2000,4000, remove assign_unused<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read galaxies
Gals G;
if(F.Ascii){
G=read_galaxies_ascii(F);}
else{
G = read_galaxies(F);
}
F.Ngal = G.size();
printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
std::vector<int> count;
count=count_galaxies(G);
for(int i=0;i<8;i++){printf (" %d \n",count[i]);}
// make MTL
MTL M=make_MTL(G,F);
for(int i=0;i<M.priority_list.size();++i){
printf(" priority %d",M.priority_list[i]);
}
printf(" \n");
assign_priority_class(M);
//find available SS and SF galaxies on each petal
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
count_class[M[i].priority_class]+=1;
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
printf(" number of MTL galaxies %d\n",M.size());
printf("Read fiber center positions and compute related things\n");
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
printf("spectrometer has to be identified from 0 to F.Npetal-1\n");
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
printf("get neighbors of each fiber;\n");
//for each spectrometer, get list of fibers
printf("Read plates in order they are to be observed\n ");
Plates P_original = read_plate_centers(F);
F.Nplate=P_original.size();
printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n");
Plates P;
P.resize(F.Nplate);
List permut = random_permut(F.Nplate);
for (int jj=0; jj<F.Nplate; jj++){
P[jj]=P_original[permut[jj]];
}
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
// For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..]
collect_galaxies_for_all(M,T,P,pp,F);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf("before assignment\n");
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
simple_assign(M,P,pp,F,A);
diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Want to have even distribution of unused fibers
// so we can put in sky fibers and standard stars
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
for (int i=0; i<1; i++) { // more iterations will improve performance slightly
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
}
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
// Still not updated, so all QSO targets have multiple observations etc
// Apply and update the plan --------------------------------------
init_time_at(time,"# Begin real time assignment",t);
for (int jj=0; jj<F.Nplate; jj++) {
int j = A.next_plate;
printf(" j == %d \n",j);
//assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
//assign_unused(j,M,P,pp,F,A);
//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies
//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");
A.next_plate++;
// Redistribute and improve on various occasions add more times if desired
if ( j==2000 || j==4000) {
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
diagnostic(M,G,F,A);
}
}
print_time(time,"# ... took :");
// Results -------------------------------------------------------
if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output
display_results("doc/figs/",M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|> |
<commit_before>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
/**
* This is the global main of amos-ss16-proj5.
*
* It takes a video (hdf5 or mp4), extracts it, executes object detection and scenario analysation.
* Every time a specific scenario is detected, the communication is performed.
*/
//std
#include <iostream>
#include <sstream>
#include <vector>
//local
#include "StreamDecoder/hdf5_frame_selector.h"
#include "StreamDecoder/frame_selector_factory.h"
#include "StreamDecoder/image_view.h"
#include "ProcessControl/controller.h"
//#include "ProcessControl/multithreadedcontroller.h"
#include "CarCommunication/protoagent.h"
using namespace std;
static bool
str_to_uint16(const char *str, uint16_t *res)
{
char *end;
errno = 0;
intmax_t val = strtoimax(str, &end, 10);
if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0')
return false;
*res = (uint16_t) val;
return true;
}
int main(int argc, const char* argv[]) {
std::cout << "AMOS Project 2016 - Group 5 @ University of Erlangen-Nuremberg \n"
" \n"
" _____ \n"
" | ____| \n"
" __ _ _ __ ___ | |__ ___ ___ \n"
" / _` | '_ ` _ \\|___ \\ / _ \\/ __| \n"
"| (_| | | | | | |___) | (_) \\__ \\ \n"
" \\__,_|_| |_| |_|____/ \\___/|___/ \n"
" \n" << std::endl;
if (argc > 4 || argc == 1){
cerr << "Usage1: " << " FULL_PATH_TO_VIDEO_FILE (IMAGE_INDEX)\n";
cerr << "Usage2: " << " PORT (SERVERIP FULL_PATH_TO_VIDEO_FILE)" << endl;
return -1;
}
if(argc == 2){
uint16_t port;
if(str_to_uint16(argv[1],&port))
{
cout << "Server port: " << port << endl;
ProtoAgent protoagent(port);
}
else
{
cerr << "Analysing video in file " << argv[1] << endl;
Controller controller;
controller.AnalyseVideo(argv[1]);
}
}
if(argc == 3){
/*FrameSelectorFactory frame_selector_factory(argv[1]);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
// read one image
unsigned int index = 0;
stringstream string_index(argv[2]);
string_index >> index;
Image * result_image = pipeline->ReadImage(index);
ImageView image_viewer;
image_viewer.ShowImage(result_image, 0);*/
}
if(argc == 4){
uint16_t port;
if(str_to_uint16(argv[1],&port))
{
//MultithreadedController controller(argv[3],port,argv[2]);
Controller controller;
controller.InitilalizeCarConnection(port,argv[2]);
controller.AnalyseVideo(argv[3]);
}
else
{
cerr << "Could not read port" << endl;
}
}
return 0;
}
<commit_msg>removed handling of arg==3 as it is no loonger used - in main<commit_after>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
/**
* This is the global main of amos-ss16-proj5.
*
* It takes a video (hdf5 or mp4), extracts it, executes object detection and scenario analysation.
* Every time a specific scenario is detected, the communication is performed.
*/
//std
#include <iostream>
#include <sstream>
#include <vector>
//local
#include "StreamDecoder/hdf5_frame_selector.h"
#include "StreamDecoder/frame_selector_factory.h"
#include "StreamDecoder/image_view.h"
#include "ProcessControl/controller.h"
//#include "ProcessControl/multithreadedcontroller.h"
#include "CarCommunication/protoagent.h"
using namespace std;
static bool
str_to_uint16(const char *str, uint16_t *res)
{
char *end;
errno = 0;
intmax_t val = strtoimax(str, &end, 10);
if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0')
return false;
*res = (uint16_t) val;
return true;
}
int main(int argc, const char* argv[]) {
std::cout << "AMOS Project 2016 - Group 5 @ University of Erlangen-Nuremberg \n"
" \n"
" _____ \n"
" | ____| \n"
" __ _ _ __ ___ | |__ ___ ___ \n"
" / _` | '_ ` _ \\|___ \\ / _ \\/ __| \n"
"| (_| | | | | | |___) | (_) \\__ \\ \n"
" \\__,_|_| |_| |_|____/ \\___/|___/ \n"
" \n" << std::endl;
if (argc > 4 || argc == 1 || argc == 3){
cerr << "Usage1: " << " FULL_PATH_TO_VIDEO_FILE (IMAGE_INDEX)\n";
cerr << "Usage2: " << " PORT (SERVERIP FULL_PATH_TO_VIDEO_FILE)" << endl;
return -1;
}
if(argc == 2){
uint16_t port;
if(str_to_uint16(argv[1],&port))
{
cout << "Server port: " << port << endl;
ProtoAgent protoagent(port);
}
else
{
cerr << "Analysing video in file " << argv[1] << endl;
Controller controller;
controller.AnalyseVideo(argv[1]);
}
}
if(argc == 4){
uint16_t port;
if(str_to_uint16(argv[1],&port))
{
//MultithreadedController controller(argv[3],port,argv[2]);
Controller controller;
controller.InitilalizeCarConnection(port,argv[2]);
controller.AnalyseVideo(argv[3]);
}
else
{
cerr << "Could not read port" << endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <irrlicht.h>
#include <string>
#include <ctime>
#include <vector>
#include <boost/filesystem.hpp>
#include "globs.h"
#include "map.h"
#ifdef _IRR_WINDOWS_
#pragma comment(lib, "Irrlicht.lib")
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#include <windows.h>
#define Pass(ms) Sleep(ms)
#else
#include <unistd.h>
#define Pass(ms) usleep(ms*1000)
#endif
#define FPS 68.0
using namespace irr;
using core::vector3df;
using video::SColor;
using core::rect;
EventReceiver receiver;
ConfigFile UserConfig;
video::IVideoDriver* driver;
scene::ISceneManager* smgr;
// I couldn't resist, alright? :D
void bork(std::string msg) {
#ifndef BE_POLITE
printf("SHIT! %s!\n", msg.c_str());
#else
printf("%s, aborting.\n", msg.c_str());
#endif
exit(-1);
}
IrrlichtDevice *setupDevice(EventReceiver &receiver, ConfigFile *UserConfig) {
SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
if (IrrlichtDevice::isDriverSupported(video::EDT_OPENGL)) {
params.DriverType = video::EDT_OPENGL;
}
else if (IrrlichtDevice::isDriverSupported(video::EDT_DIRECT3D9)) {
params.DriverType = video::EDT_DIRECT3D9;
}
else if (IrrlichtDevice::isDriverSupported(video::EDT_DIRECT3D8)) {
params.DriverType = video::EDT_DIRECT3D8;
}
else {
printf("No suitable video driver found.\n");
return NULL;
}
params.WindowSize = core::dimension2d<u32>(UserConfig->read<int>("display.width", 800), UserConfig->read<int>("display.height", 600));
params.Bits = 32;
params.Fullscreen = UserConfig->read<bool>("display.fullscreen", false);
params.Stencilbuffer = false;
params.Doublebuffer = true;
params.Vsync = true;
params.EventReceiver = &receiver;
return createDeviceEx(params);
}
struct controls {
EKEY_CODE cam_up;
EKEY_CODE cam_down;
EKEY_CODE cam_left;
EKEY_CODE cam_right;
EKEY_CODE cam_raise;
EKEY_CODE cam_lower;
};
std::string get_userdata_path() {
#ifdef __unix
string result ( getenv("HOME") );
result += "/.IrrRR/"; // TODO: Is this ok?
#else // __unix
#ifdef __WIN32__
string result ( getenv("APPDATA") );
result += "\\IrrRR\\";
#endif // __WIN32__
#endif // __unix
return result;
}
int main() {
try {
UserConfig = ConfigFile(get_userdata_path() + "user.cfg");
}
catch (ConfigFile::file_not_found) {
printf("No user config file found, creating...\n");
boost::filesystem::create_directories(get_userdata_path());
FILE *f;
f = fopen((get_userdata_path() + "user.cfg").c_str(), "w");
if (f == NULL) {
printf("Could not create user config file. Aborting. Please check that the path to the user config file is available: %s", (get_userdata_path() + "user.cfg").c_str());
exit(-1);
}
fclose(f);
UserConfig = ConfigFile(get_userdata_path() + "user.cfg");
}
IrrlichtDevice *device = setupDevice(receiver, &UserConfig);
if (!device) {
printf("Could not create device.\n");
}
device->setWindowCaption(L"IrrRR");
driver = device->getVideoDriver();
smgr = device->getSceneManager();
env = device->getGUIEnvironment();
scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();
/* Set up GUI */
gui::IGUISkin* skin = env->getSkin();
setup_GUI();
/* Load controls */
controls userControls;
userControls.cam_up = (EKEY_CODE) UserConfig.read<int>("keys.camera_up", KEY_KEY_W);
userControls.cam_down = (EKEY_CODE) UserConfig.read<int>("keys.camera_down", KEY_KEY_S);
userControls.cam_left = (EKEY_CODE) UserConfig.read<int>("keys.camera_left", KEY_KEY_A);
userControls.cam_right = (EKEY_CODE) UserConfig.read<int>("keys.camera_right", KEY_KEY_D);
userControls.cam_raise = (EKEY_CODE) UserConfig.read<int>("keys.camera_raise", KEY_KEY_Q);
userControls.cam_lower = (EKEY_CODE) UserConfig.read<int>("keys.camera_lower", KEY_KEY_E);
/* Set up camera */
scene::ICameraSceneNode *cam = smgr->addCameraSceneNode(0, vector3df(0, 10, -2), vector3df(0, 0, 0));
// scene::ICameraSceneNode *blehcam = smgr->addCameraSceneNode(0, vector3df(0, 50, -2), vector3df(0, 0, 0));
cam->setPosition(core::vector3df(-5,18,0));
cam->setTarget(core::vector3df(0,0,0));
cam->setFarValue(42000.0f);
vector3df camMove(0, 0, 0);
vector3df camPos = cam->getPosition();
vector3df camTarget = cam->getTarget();
/* Map */
FILE *mapfile;
mapfile = fopen("data/maps/test.map", "rb");
if (mapfile == NULL) {
bork("Could not open test map");
}
Map *map = new Map;
map->load(mapfile);
fclose(mapfile);
/* Set up lighting */
/* std::vector<scene::ILightSceneNode*> lights;
#define asdf 3
#define asdfg asdf/2
for (int i = 0; i<8; i++) {
vector3df pos (
(float)((i & 1) != 0)*asdf-asdfg,
(float)((i & 2) != 0)*asdf-asdfg,
(float)((i & 4) != 0)*asdf-asdfg
);
lights.push_back(smgr->addLightSceneNode(cam, pos));
}*/
smgr->setAmbientLight(SColor(0x000000));
scene::ILightSceneNode *light = smgr->addLightSceneNode(cam);
/* Set up skybox */
const io::path skyboxFilename ("data/textures/skybox/top.png");
video::ITexture *sb_tex = driver->getTexture(skyboxFilename);
smgr->addSkyBoxSceneNode(sb_tex, sb_tex, sb_tex, sb_tex, sb_tex, sb_tex);
/* T-Minus ten! */
ITimer* timer = device->getTimer();
timer->setTime(0);
unsigned int now = 0;
unsigned int lastUpdate = 0;
int frame = 0;
vector3df mousething;
scene::IMesh *arrowMesh = smgr->addArrowMesh("ITSANARROW", 0xFFFFFF, 0xFF0000);
scene::IMeshSceneNode *mouseNode = smgr->addMeshSceneNode(arrowMesh, 0);
// scene::IMeshSceneNode *camPoint = smgr->addMeshSceneNode(arrowMesh, cam);
mouseNode->setRotation(vector3df(0, 0, 180));
// camPoint->setRotation(vector3df(0,0,180));
core::line3df ray;
scene::ISceneNode *dummyNode;
core::triangle3df dummyTri;
/* We have liftoff! */
while (device->run()) {
now = timer->getTime();
if (now >= lastUpdate + 1000.0/FPS) {
frame++;
lastUpdate = now;
driver->beginScene(true, true, SColor(255, 0, 0, 0));
smgr->drawAll();
env->drawAll();
driver->draw3DLine(cam->getAbsolutePosition(), vector3df(0,0,0), 0x0000ff);
driver->draw3DLine(cam->getAbsolutePosition(), ray.start, 0xff0000);
driver->draw3DLine(ray.end, vector3df(0,0,0), 0x00ff00);
driver->endScene();
camMove.set(0, 0, 0);
if (receiver.IsKeyPressed(userControls.cam_up)) {
camMove.X = 0.1;
}
if (receiver.IsKeyPressed(userControls.cam_down)) {
camMove.X = -0.1;
}
if (receiver.IsKeyPressed(userControls.cam_left)) {
camMove.Z = 0.1;
}
if (receiver.IsKeyPressed(userControls.cam_right)) {
camMove.Z = -0.1;
}
if (receiver.IsKeyPressed(userControls.cam_raise)) {
camMove.Y = 0.1;
}
if (receiver.IsKeyPressed(userControls.cam_lower)) {
camMove.Y = -0.1;
}
camPos = cam->getPosition();
camTarget = cam->getTarget();
camPos += camMove;
camMove.Y = 0;
camTarget += camMove;
cam->setPosition(camPos);
cam->setTarget(camTarget);
ray = collMan->getRayFromScreenCoordinates(receiver.MousePosition, cam);
ray.start = cam->getAbsolutePosition();
if (collMan->getSceneNodeAndCollisionPointFromRay(ray, mousething, dummyTri)) {
mouseNode->setPosition(mousething);
}
if(receiver.IsKeyPressed(KEY_ESCAPE)) break;
if(frame % 100 == 0) printf("%i FPS\n", driver->getFPS());
}
else {
Pass(10);
}
}
device->drop();
return 0;
}
<commit_msg>Totally messed up the lighting :)<commit_after>#include <irrlicht.h>
#include <string>
#include <ctime>
#include <vector>
#include <boost/filesystem.hpp>
#include "globs.h"
#include "map.h"
#ifdef _IRR_WINDOWS_
#pragma comment(lib, "Irrlicht.lib")
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#include <windows.h>
#define Pass(ms) Sleep(ms)
#else
#include <unistd.h>
#define Pass(ms) usleep(ms*1000)
#endif
#define FPS 68.0
using namespace irr;
using core::vector3df;
using video::SColor;
using core::rect;
EventReceiver receiver;
ConfigFile UserConfig;
video::IVideoDriver* driver;
scene::ISceneManager* smgr;
// I couldn't resist, alright? :D
void bork(std::string msg) {
#ifndef BE_POLITE
printf("SHIT! %s!\n", msg.c_str());
#else
printf("%s, aborting.\n", msg.c_str());
#endif
exit(-1);
}
IrrlichtDevice *setupDevice(EventReceiver &receiver, ConfigFile *UserConfig) {
SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
if (IrrlichtDevice::isDriverSupported(video::EDT_OPENGL)) {
params.DriverType = video::EDT_OPENGL;
}
else if (IrrlichtDevice::isDriverSupported(video::EDT_DIRECT3D9)) {
params.DriverType = video::EDT_DIRECT3D9;
}
else if (IrrlichtDevice::isDriverSupported(video::EDT_DIRECT3D8)) {
params.DriverType = video::EDT_DIRECT3D8;
}
else {
printf("No suitable video driver found.\n");
return NULL;
}
params.WindowSize = core::dimension2d<u32>(UserConfig->read<int>("display.width", 800), UserConfig->read<int>("display.height", 600));
params.Bits = 32;
params.Fullscreen = UserConfig->read<bool>("display.fullscreen", false);
params.Stencilbuffer = false;
params.Doublebuffer = true;
params.Vsync = true;
params.EventReceiver = &receiver;
return createDeviceEx(params);
}
struct controls {
EKEY_CODE cam_up;
EKEY_CODE cam_down;
EKEY_CODE cam_left;
EKEY_CODE cam_right;
EKEY_CODE cam_raise;
EKEY_CODE cam_lower;
};
std::string get_userdata_path() {
#ifdef __unix
string result ( getenv("HOME") );
result += "/.IrrRR/"; // TODO: Is this ok?
#else // __unix
#ifdef __WIN32__
string result ( getenv("APPDATA") );
result += "\\IrrRR\\";
#endif // __WIN32__
#endif // __unix
return result;
}
int main() {
try {
UserConfig = ConfigFile(get_userdata_path() + "user.cfg");
}
catch (ConfigFile::file_not_found) {
printf("No user config file found, creating...\n");
boost::filesystem::create_directories(get_userdata_path());
FILE *f;
f = fopen((get_userdata_path() + "user.cfg").c_str(), "w");
if (f == NULL) {
printf("Could not create user config file. Aborting. Please check that the path to the user config file is available: %s", (get_userdata_path() + "user.cfg").c_str());
exit(-1);
}
fclose(f);
UserConfig = ConfigFile(get_userdata_path() + "user.cfg");
}
IrrlichtDevice *device = setupDevice(receiver, &UserConfig);
if (!device) {
printf("Could not create device.\n");
}
device->setWindowCaption(L"IrrRR");
driver = device->getVideoDriver();
smgr = device->getSceneManager();
env = device->getGUIEnvironment();
scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();
/* Set up GUI */
gui::IGUISkin* skin = env->getSkin();
setup_GUI();
/* Load controls */
controls userControls;
userControls.cam_up = (EKEY_CODE) UserConfig.read<int>("keys.camera_up", KEY_KEY_W);
userControls.cam_down = (EKEY_CODE) UserConfig.read<int>("keys.camera_down", KEY_KEY_S);
userControls.cam_left = (EKEY_CODE) UserConfig.read<int>("keys.camera_left", KEY_KEY_A);
userControls.cam_right = (EKEY_CODE) UserConfig.read<int>("keys.camera_right", KEY_KEY_D);
userControls.cam_raise = (EKEY_CODE) UserConfig.read<int>("keys.camera_raise", KEY_KEY_Q);
userControls.cam_lower = (EKEY_CODE) UserConfig.read<int>("keys.camera_lower", KEY_KEY_E);
/* Set up camera */
scene::ICameraSceneNode *cam = smgr->addCameraSceneNode(0, vector3df(0, 10, -2), vector3df(0, 0, 0));
// scene::ICameraSceneNode *blehcam = smgr->addCameraSceneNode(0, vector3df(0, 50, -2), vector3df(0, 0, 0));
cam->setPosition(core::vector3df(-5,18,0));
cam->setTarget(core::vector3df(0,0,0));
cam->setFarValue(42000.0f);
vector3df camMove(0, 0, 0);
vector3df camPos = cam->getPosition();
vector3df camTarget = cam->getTarget();
/* Map */
FILE *mapfile;
mapfile = fopen("data/maps/test.map", "rb");
if (mapfile == NULL) {
bork("Could not open test map");
}
Map *map = new Map;
map->load(mapfile);
fclose(mapfile);
/* Set up lighting */
smgr->setAmbientLight(SColor(0x000000));
scene::ILightSceneNode *groundLight = smgr->addLightSceneNode(0, vector3df(0,0,0), SColor(0xffffff), 10.0f);
scene::ILightSceneNode *raisedLight = smgr->addLightSceneNode(groundLight, vector3df(0,5,0), SColor(0xffffff), 10.0f);
/* Set up skybox */
const io::path skyboxFilename ("data/textures/skybox/top.png");
video::ITexture *sb_tex = driver->getTexture(skyboxFilename);
//smgr->addSkyBoxSceneNode(sb_tex, sb_tex, sb_tex, sb_tex, sb_tex, sb_tex); XXX REACTIVATE
/* T-Minus ten! */
ITimer* timer = device->getTimer();
timer->setTime(0);
unsigned int now = 0;
unsigned int lastUpdate = 0;
int frame = 0;
vector3df mousething;
scene::IMesh *arrowMesh = smgr->addArrowMesh("ITSANARROW", 0xFFFFFF, 0xFF0000);
scene::IMeshSceneNode *mouseNode = smgr->addMeshSceneNode(arrowMesh, 0);
// scene::IMeshSceneNode *camPoint = smgr->addMeshSceneNode(arrowMesh, cam);
mouseNode->setRotation(vector3df(0, 0, 180));
// camPoint->setRotation(vector3df(0,0,180));
core::line3df ray;
scene::ISceneNode *dummyNode;
core::triangle3df dummyTri;
/* We have liftoff! */
while (device->run()) {
now = timer->getTime();
if (now >= lastUpdate + 1000.0/FPS) {
frame++;
lastUpdate = now;
driver->beginScene(true, true, SColor(255, 255, 0, 255));
driver->draw3DLine(ray.end, vector3df(0,0,0), 0x00ff00);
driver->draw3DLine(cam->getAbsolutePosition(), vector3df(0,0,0), 0x0000ff);
driver->draw3DLine(cam->getAbsolutePosition(), ray.start, 0xff0000);
smgr->drawAll();
env->drawAll();
driver->endScene();
camMove.set(0, 0, 0);
if (receiver.IsKeyPressed(userControls.cam_up)) {
camMove.X = 0.1;
}
if (receiver.IsKeyPressed(userControls.cam_down)) {
camMove.X = -0.1;
}
if (receiver.IsKeyPressed(userControls.cam_left)) {
camMove.Z = 0.1;
}
if (receiver.IsKeyPressed(userControls.cam_right)) {
camMove.Z = -0.1;
}
if (receiver.IsKeyPressed(userControls.cam_raise)) {
camMove.Y = 0.1;
}
if (receiver.IsKeyPressed(userControls.cam_lower)) {
camMove.Y = -0.1;
}
camPos = cam->getPosition();
camTarget = cam->getTarget();
camPos += camMove;
camMove.Y = 0;
camTarget += camMove;
cam->setPosition(camPos);
cam->setTarget(camTarget);
groundLight->setPosition(camTarget);
ray = collMan->getRayFromScreenCoordinates(receiver.MousePosition, cam);
ray.start = cam->getAbsolutePosition();
if (collMan->getSceneNodeAndCollisionPointFromRay(ray, mousething, dummyTri)) {
mouseNode->setPosition(mousething);
}
if(receiver.IsKeyPressed(KEY_ESCAPE)) break;
if(frame % 100 == 0) printf("%i FPS\n", driver->getFPS());
}
else {
Pass(10);
}
}
device->drop();
return 0;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) Sjors Gielen, 2010
* See LICENSE for license.
*/
#include "dazeus.h"
#include "dazeusglobal.h"
#include <libircclient.h>
int main(int argc, char *argv[])
{
fprintf(stderr, "DaZeus version: %s", DAZEUS_VERSION_STR);
unsigned int high, low;
irc_get_version(&high, &low);
fprintf(stdout, "IRC library version: %d.%02d\n", high, low);
// TODO parse command-line options
DaZeus d( "./dazeus.conf" );
// find and initialise plugins
d.initPlugins();
// connect to servers marked as "autoconnect"
d.autoConnect();
// start the event loop
d.run();
return 0;
}
<commit_msg>Fix startup output<commit_after>/**
* Copyright (c) Sjors Gielen, 2010
* See LICENSE for license.
*/
#include "dazeus.h"
#include "dazeusglobal.h"
#include <libircclient.h>
int main(int argc, char *argv[])
{
fprintf(stderr, "DaZeus version: %s\n", DAZEUS_VERSION_STR);
unsigned int high, low;
irc_get_version(&high, &low);
fprintf(stdout, "IRC library version: %d.%02d\n", high, low);
// TODO parse command-line options
DaZeus d( "./dazeus.conf" );
// find and initialise plugins
d.initPlugins();
// connect to servers marked as "autoconnect"
d.autoConnect();
// start the event loop
d.run();
return 0;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <stdexcept>
class Models_BasicDistributions_InvWishart : public ::testing::Test {
protected:
virtual void SetUp() {
FILE *in;
if(!(in = popen("make path_separator --no-print-directory", "r")))
throw std::runtime_error("\"make path_separator\" has failed.");
path_separator += fgetc(in);
pclose(in);
model.append("models").append(path_separator);
model.append("basic_distributions").append(path_separator);
model.append("inv_wishart");
output1 = model + "1.csv";
output2 = model + "2.csv";
}
std::string path_separator;
std::string model;
std::string output1;
std::string output2;
};
TEST_F(Models_BasicDistributions_InvWishart,RunModel) {
std::string command;
command = model;
command += " --samples=";
command += output1;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
command = model;
command += " --samples=";
command += output2;
EXPECT_EQ(0, system(command.c_str()))
<< "Can not execute command: " << command << std::endl;
}
<commit_msg>test-models: updated test/models/basic_distributions/inv_wishart<commit_after>#include <gtest/gtest.h>
#include <test/models/model_test_fixture.hpp>
class Models_BasicDistributions_InvWishart :
public ::testing::Model_Test_Fixture<Models_BasicDistributions_InvWishart,
false> {
protected:
virtual void SetUp() {
}
public:
static std::vector<std::string> get_model_path() {
std::vector<std::string> model_path;
model_path.push_back("models");
model_path.push_back("basic_distributions");
model_path.push_back("inv_wishart");
return model_path;
}
};
TEST_F(Models_BasicDistributions_InvWishart,RunModel) {
run_model();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 John Sullivan
// Copyright (c) 2013 Other contributers as noted in the CONTRIBUTERS file
//
// This file is part of Irish Light Show
//
// 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 "graphics/primitives/ColorRGB.hpp"
#include "graphics/primitives/RGBSurface.hpp"
#include "graphics/files/ImageFile.hpp"
#include "common/SDLException.hpp"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <vector>
#include <cstdlib>
typedef uint32_t color_t;
// Other options at http://stackoverflow.com/a/596243/1989056
unsigned get_luminence(graphics::ColorRGB const & color) {
return static_cast<unsigned>(
0.299 * color.red +
0.587 * color.green +
0.114 * color.blue);
}
// Blends b atop a. Returns b if lumincence of b is greater than a, unless b's
// luminence is greater than cap, in which case a is returned.
void light_blend_surfaces(graphics::RGBSurface const & a,
graphics::RGBSurface const & b, graphics::RGBSurface & out,
unsigned cap) {
unsigned width = std::min(a.width(), b.width());
unsigned height = std::min(a.height(), b.height());
if (width > out.width() || height > out.height()) {
throw std::invalid_argument("out must not be smaller than a or b");
}
for (unsigned x = 0; x < width; ++x) {
for (unsigned y = 0; y < height; ++y) {
graphics::ColorRGB * chosen_color;
graphics::ColorRGB a_color = a.get_pixel(x, y);
graphics::ColorRGB b_color = b.get_pixel(x, y);
unsigned b_lumincence = get_luminence(b_color);
if (b_lumincence > cap) {
chosen_color = &a_color;
} else {
unsigned a_lumincence = get_luminence(a_color);
chosen_color =
b_lumincence > a_lumincence ? &b_color : &a_color;
}
out.set_pixel(x, y, *chosen_color);
}
}
}
int main(int argc, char * argv[]) {
if (argc < 3) {
std::cout << "usage: " << argv[0] << " image0 image1 ..." << std::endl;
return 1;
}
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Failed to initialize SDL_video." << std::endl;
return 1;
}
// Open all the image files and load them into memory
std::vector<graphics::ImageFile> files;
unsigned max_width = 0, max_height = 0;
for (int i = 1; i < argc; ++i) {
files.emplace_back(argv[i]);
max_width = std::max(max_width,
files[files.size() - 1].surface().width());
max_height = std::max(max_height,
files[files.size() - 1].surface().height());
}
// Create an off-screen buffer we'll draw to
graphics::RGBSurface buffer(max_width, max_height);
// Blend the images from left to right
light_blend_surfaces(files.at(0).surface(), files.at(1).surface(), buffer,
255);
for (size_t i = 2; i < files.size(); ++i) {
light_blend_surfaces(buffer, files.at(i).surface(), buffer, 255);
}
// Get a window up
SDL_Window * win = SDL_CreateWindow(
"Irish Light Show", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
max_width, max_height, SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cerr << "Failed to create window. " << SDL_GetError() << std::endl;
return 1;
}
SDL_Surface * screen = SDL_GetWindowSurface(win);
SDL_BlitSurface(buffer.sdl_surface(), nullptr, screen, nullptr);
SDL_UpdateWindowSurface(win);
SDL_Delay(2000);
SDL_DestroyWindow(win);
IMG_Quit();
SDL_Quit();
return 0;
}
<commit_msg>Functionally it's all working. Bed time.<commit_after>// Copyright (c) 2013 John Sullivan
// Copyright (c) 2013 Other contributers as noted in the CONTRIBUTERS file
//
// This file is part of Irish Light Show
//
// 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 "graphics/primitives/ColorRGB.hpp"
#include "graphics/primitives/RGBSurface.hpp"
#include "graphics/files/ImageFile.hpp"
#include "common/SDLException.hpp"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <vector>
#include <cstdlib>
typedef uint32_t color_t;
// Other options at http://stackoverflow.com/a/596243/1989056
unsigned get_luminence(graphics::ColorRGB const & color) {
return static_cast<unsigned>(
0.299 * color.red +
0.587 * color.green +
0.114 * color.blue);
}
// Blends b atop a. Returns b if lumincence of b is greater than a, unless b's
// luminence is greater than cap, in which case a is returned.
void light_blend_surfaces(graphics::RGBSurface const & a,
graphics::RGBSurface const & b, graphics::RGBSurface & out,
unsigned cap) {
unsigned width = std::min(a.width(), b.width());
unsigned height = std::min(a.height(), b.height());
if (width > out.width() || height > out.height()) {
throw std::invalid_argument("out must not be smaller than a or b");
}
for (unsigned x = 0; x < width; ++x) {
for (unsigned y = 0; y < height; ++y) {
graphics::ColorRGB * chosen_color;
graphics::ColorRGB a_color = a.get_pixel(x, y);
graphics::ColorRGB b_color = b.get_pixel(x, y);
unsigned b_lumincence = get_luminence(b_color);
if (b_lumincence > cap) {
chosen_color = &a_color;
} else {
unsigned a_lumincence = get_luminence(a_color);
chosen_color =
b_lumincence > a_lumincence ? &b_color : &a_color;
}
out.set_pixel(x, y, *chosen_color);
}
}
}
int main(int argc, char * argv[]) {
if (argc < 3) {
std::cout << "usage: " << argv[0] << " image0 image1 ..." << std::endl;
return 1;
}
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Failed to initialize SDL_video." << std::endl;
return 1;
}
// Open all the image files and load them into memory
std::vector<graphics::ImageFile> files;
unsigned max_width = 0, max_height = 0;
for (int i = 1; i < argc; ++i) {
files.emplace_back(argv[i]);
max_width = std::max(max_width,
files[files.size() - 1].surface().width());
max_height = std::max(max_height,
files[files.size() - 1].surface().height());
}
// Create an off-screen buffer we'll draw to
graphics::RGBSurface buffer(max_width, max_height);
// Get a window up
SDL_Window * win = SDL_CreateWindow(
"Irish Light Show", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
max_width, max_height, SDL_WINDOW_SHOWN);
if (win == nullptr){
std::cerr << "Failed to create window. " << SDL_GetError() << std::endl;
return 1;
}
SDL_Surface * screen = SDL_GetWindowSurface(win);
unsigned const LIGHTNESS_CAP_MAX = 255;
unsigned const LIGHTNESS_CAP_MIN = 0;
unsigned const LIGHTNESS_CAP_BIG_STEP = 30;
unsigned lightness_cap = LIGHTNESS_CAP_MAX;
bool refresh_screen = false;
SDL_Event event;
while (SDL_WaitEvent(&event) == 1)
{
switch(event.type)
{
case SDL_KEYDOWN:
refresh_screen = true;
if (event.key.keysym.sym == SDLK_UP &&
lightness_cap < LIGHTNESS_CAP_MAX) {
++lightness_cap;
} else if (event.key.keysym.sym == SDLK_DOWN &&
lightness_cap > LIGHTNESS_CAP_MIN) {
--lightness_cap;
} else if (event.key.keysym.sym == SDLK_PAGEUP) {
lightness_cap = std::min(
lightness_cap + LIGHTNESS_CAP_BIG_STEP,
LIGHTNESS_CAP_MAX);
} else if (event.key.keysym.sym == SDLK_PAGEDOWN) {
if (LIGHTNESS_CAP_MIN + LIGHTNESS_CAP_BIG_STEP >
lightness_cap) {
lightness_cap = 0;
} else {
lightness_cap -= LIGHTNESS_CAP_BIG_STEP;
}
} else {
refresh_screen = false;
}
break;
case SDL_QUIT:
goto cleanup;
break;
}
if (refresh_screen) {
std::cout << "cap: " << lightness_cap << std::endl;
// Blend the images from left to right
light_blend_surfaces(files.at(0).surface(), files.at(1).surface(),
buffer, lightness_cap);
for (size_t i = 2; i < files.size(); ++i) {
light_blend_surfaces(buffer, files.at(i).surface(), buffer,
lightness_cap);
}
SDL_BlitSurface(buffer.sdl_surface(), nullptr, screen, nullptr);
SDL_UpdateWindowSurface(win);
refresh_screen = false;
}
}
cleanup:
IMG_Quit();
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
*/
#include <pkt/flow_proto.h>
#include "ksync_flow_index_manager.h"
#include "flowtable_ksync.h"
#include "ksync_init.h"
//////////////////////////////////////////////////////////////////////////////
// KSyncFlowIndexEntry routines
//////////////////////////////////////////////////////////////////////////////
KSyncFlowIndexEntry::KSyncFlowIndexEntry() :
state_(INIT), index_(FlowEntry::kInvalidFlowHandle), ksync_entry_(NULL),
index_owner_(NULL), evict_count_(0), delete_in_progress_(false) {
}
KSyncFlowIndexEntry::~KSyncFlowIndexEntry() {
assert(index_owner_.get() == NULL);
assert(ksync_entry_ == NULL);
}
bool KSyncFlowIndexEntry::IsEvicted() const {
return (state_ == INDEX_EVICT || state_ == INDEX_CHANGE);
}
void KSyncFlowIndexEntry::Reset() {
index_ = FlowEntry::kInvalidFlowHandle;
state_ = INIT;
ksync_entry_ = NULL;
delete_in_progress_ = false;
}
//////////////////////////////////////////////////////////////////////////////
// KSyncFlowIndexManager routines
//////////////////////////////////////////////////////////////////////////////
KSyncFlowIndexManager::KSyncFlowIndexManager(KSync *ksync) :
ksync_(ksync), proto_(NULL), count_(0), index_list_() {
}
KSyncFlowIndexManager::~KSyncFlowIndexManager() {
}
void KSyncFlowIndexManager::InitDone(uint32_t count) {
proto_ = ksync_->agent()->pkt()->get_flow_proto();
count_ = count;
index_list_.resize(count);
}
//////////////////////////////////////////////////////////////////////////////
// KSyncFlowIndexManager APIs
//////////////////////////////////////////////////////////////////////////////
void KSyncFlowIndexManager::RetryIndexAcquireRequest(FlowEntry *flow,
uint32_t flow_handle) {
if (flow == NULL)
return;
proto_->RetryIndexAcquireRequest(flow, flow_handle);
}
void KSyncFlowIndexManager::ReleaseRequest(FlowEntry *flow) {
Release(flow);
}
// Handle add of a flow
void KSyncFlowIndexManager::Add(FlowEntry *flow) {
FlowTableKSyncObject *object = GetKSyncObject(flow);
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED) {
UpdateFlowHandle(flow);
return;
}
// If flow already has a KSync entry, it means old flow was evicted.
// Delete the old KSync entry. Once the KSync entry is freed, we will
// get callback to "Release". New KSync entry will be allocated from
// "Release" method
if (index_entry->ksync_entry()) {
EvictFlow(flow);
return;
}
FlowEntryPtr old_flow = SafeAcquireIndex(flow);
if (old_flow.get() != NULL) {
// If index cannot be acquired, put flow into wait list of old_flow
// (flow holding the index)
EvictFlow(old_flow.get(), flow);
return;
}
assert(index_entry->ksync_entry_ == NULL);
if (index_entry->index_ == FlowEntry::kInvalidFlowHandle &&
flow->flow_handle() == FlowEntry::kInvalidFlowHandle) {
index_entry->state_ = KSyncFlowIndexEntry::INDEX_UNASSIGNED;
} else {
index_entry->state_ = KSyncFlowIndexEntry::INDEX_SET;
}
FlowTableKSyncEntry key(object, flow, flow->flow_handle());
index_entry->ksync_entry_ =
(static_cast<FlowTableKSyncEntry *>(object->Create(&key, true)));
// Add called for deleted flow. This happens when Reverse flow is
// deleted before getting ACK from vrouter.
// Create and delete KSync Entry
if (flow->deleted()) {
Delete(flow);
}
}
void KSyncFlowIndexManager::Change(FlowEntry *flow) {
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (flow->deleted() ||
(index_entry->state_ != KSyncFlowIndexEntry::INDEX_SET)) {
return;
}
// If index not yet assigned for flow, the flow will be written when later
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED) {
return;
}
FlowTableKSyncObject *object = GetKSyncObject(flow);
object->Change(index_entry->ksync_entry_);
}
bool KSyncFlowIndexManager::Delete(FlowEntry *flow) {
FlowTableKSyncObject *object = GetKSyncObject(flow);
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->delete_in_progress_) {
return false;
}
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED)
return false;
if (index_entry->ksync_entry_ == NULL) {
assert(index_entry->index_ == FlowEntry::kInvalidFlowHandle);
return false;
}
index_entry->delete_in_progress_ = true;
// Hold reference to ksync-entry till this function call is over
KSyncEntry::KSyncEntryPtr ksync_ptr = index_entry->ksync_entry_;
object->Delete(index_entry->ksync_entry_);
return true;
}
// Flow was written with -1 as index and vrouter allocated an index.
void KSyncFlowIndexManager::UpdateFlowHandle(FlowEntry *flow) {
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->index_ == flow->flow_handle())
return;
// Ensure that flow is not evicted
// A flow with index -1 will always have a flow with HOLD state as reverse
// flow. VRouter does not evict flows in HOLD state. As a result, we dont
// expect the flow to be evicted.
assert(index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED);
assert(index_entry->index_ == FlowEntry::kInvalidFlowHandle);
assert(index_entry->ksync_entry());
FlowEntryPtr old_flow = SafeAcquireIndex(flow);
if (old_flow.get() != NULL) {
// If index cannot be acquired, put flow into wait list of old_flow
// (flow holding the index)
EvictFlow(old_flow.get(), flow);
return;
}
flow->ksync_index_entry()->state_ = KSyncFlowIndexEntry::INDEX_SET;
FlowTableKSyncObject *object = GetKSyncObject(flow);
object->UpdateFlowHandle(index_entry->ksync_entry_, index_entry->index_);
// If flow is deleted in the meanwhile, delete the flow entry
if (flow->deleted()) {
Delete(flow);
}
}
void KSyncFlowIndexManager::Release(FlowEntry *flow) {
FlowEntryPtr wait_flow = ReleaseIndex(flow);
// Make a copy of values needed for subsequent processing before reset
KSyncFlowIndexEntry::State state = flow->ksync_index_entry()->state_;
FlowEntryPtr owner_entry = flow->ksync_index_entry()->index_owner_;
uint32_t evict_index = flow->ksync_index_entry()->index_;
// Reset the old index entry
flow->ksync_index_entry()->Reset();
switch (state) {
// Entry has index set and no further transitions necessary
case KSyncFlowIndexEntry::INDEX_SET:
break;
// Entry deleted when waiting for index.
// Invoke Add() again so that the HOLD entry entry is deleted from VRouter
case KSyncFlowIndexEntry::INDEX_WAIT: {
RemoveWaitList(owner_entry.get(), flow);
Add(flow);
break;
}
// Index changed for flow and old index freed. Try acquring new index
case KSyncFlowIndexEntry::INDEX_CHANGE: {
RetryIndexAcquireRequest(wait_flow.get(), evict_index);
Add(flow);
break;
}
// Flow evicted. Now activate entry waiting for on the index
case KSyncFlowIndexEntry::INDEX_EVICT: {
RetryIndexAcquireRequest(wait_flow.get(), evict_index);
break;
}
default:
assert(0);
}
return;
}
// Release the index and return flow in wait list
FlowEntryPtr KSyncFlowIndexManager::ReleaseIndex(FlowEntry *flow) {
FlowEntryPtr wait_flow = NULL;
uint32_t index = flow->ksync_index_entry()->index_;
if (index == FlowEntry::kInvalidFlowHandle) {
return wait_flow;
}
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
assert(index_list_[index].owner_.get() == flow);
// Release the index_list_ entry
index_list_[index].owner_ = NULL;
wait_flow.swap(index_list_[index].wait_entry_);
return wait_flow;
}
FlowEntryPtr KSyncFlowIndexManager::FindByIndex(uint32_t idx) {
tbb::mutex::scoped_lock lock(index_list_[idx].mutex_);
if (index_list_[idx].owner_.get() != NULL)
return index_list_[idx].owner_;
return FlowEntryPtr(NULL);
}
FlowEntryPtr KSyncFlowIndexManager::AcquireIndex(FlowEntry *flow) {
FlowEntryPtr ret(NULL);
// Sanity checks for a new flow
assert(flow->ksync_index_entry()->index_ == FlowEntry::kInvalidFlowHandle);
// Ignore entries with invalid index
uint32_t index = flow->flow_handle();
if (index == FlowEntry::kInvalidFlowHandle) {
return ret;
}
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
if (index_list_[index].owner_.get() != NULL)
return index_list_[index].owner_;
flow->ksync_index_entry()->index_ = index;
index_list_[index].owner_ = flow;
return ret;
}
FlowEntryPtr KSyncFlowIndexManager::SafeAcquireIndex(FlowEntry *flow) {
if (flow->ksync_index_entry()->ksync_entry_ != NULL) {
assert(flow->ksync_index_entry()->index_ ==
FlowEntry::kInvalidFlowHandle);
}
return AcquireIndex(flow);
}
void KSyncFlowIndexManager::AddWaitList(FlowEntry *old_flow, FlowEntry *flow) {
uint32_t index = old_flow->ksync_index_entry()->index_;
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
assert((index_list_[index].wait_entry_.get() == NULL) ||
(index_list_[index].wait_entry_.get() == flow));
index_list_[index].wait_entry_ = flow;
}
void KSyncFlowIndexManager::RemoveWaitList(FlowEntry *old_flow,
FlowEntry *flow) {
uint32_t index = old_flow->ksync_index_entry()->index_;
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
assert(index_list_[index].wait_entry_.get() == flow);
index_list_[index].wait_entry_ = NULL;
}
void KSyncFlowIndexManager::EvictFlow(FlowEntry *flow) {
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
index_entry->evict_count_++;
index_entry->state_ = KSyncFlowIndexEntry::INDEX_CHANGE;
Delete(flow);
}
void KSyncFlowIndexManager::EvictFlow(FlowEntry *old_flow, FlowEntry *flow) {
old_flow->ksync_index_entry()->evict_count_++;
old_flow->ksync_index_entry()->state_ = KSyncFlowIndexEntry::INDEX_EVICT;
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED) {
assert(index_entry->index_ == FlowEntry::kInvalidFlowHandle);
} else {
flow->ksync_index_entry()->state_ = KSyncFlowIndexEntry::INDEX_WAIT;
}
AddWaitList(old_flow, flow);
proto_->EvictFlowRequest(old_flow, flow->flow_handle());
}
FlowTableKSyncObject *KSyncFlowIndexManager::GetKSyncObject(FlowEntry *flow) {
return flow->flow_table()->ksync_object();
}
<commit_msg>Flows not deleted resulting in vrf del pending.<commit_after>/*
* Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
*/
#include <pkt/flow_proto.h>
#include "ksync_flow_index_manager.h"
#include "flowtable_ksync.h"
#include "ksync_init.h"
//////////////////////////////////////////////////////////////////////////////
// KSyncFlowIndexEntry routines
//////////////////////////////////////////////////////////////////////////////
KSyncFlowIndexEntry::KSyncFlowIndexEntry() :
state_(INIT), index_(FlowEntry::kInvalidFlowHandle), ksync_entry_(NULL),
index_owner_(NULL), evict_count_(0), delete_in_progress_(false) {
}
KSyncFlowIndexEntry::~KSyncFlowIndexEntry() {
assert(index_owner_.get() == NULL);
assert(ksync_entry_ == NULL);
}
bool KSyncFlowIndexEntry::IsEvicted() const {
return (state_ == INDEX_EVICT || state_ == INDEX_CHANGE);
}
void KSyncFlowIndexEntry::Reset() {
index_ = FlowEntry::kInvalidFlowHandle;
state_ = INIT;
ksync_entry_ = NULL;
delete_in_progress_ = false;
}
//////////////////////////////////////////////////////////////////////////////
// KSyncFlowIndexManager routines
//////////////////////////////////////////////////////////////////////////////
KSyncFlowIndexManager::KSyncFlowIndexManager(KSync *ksync) :
ksync_(ksync), proto_(NULL), count_(0), index_list_() {
}
KSyncFlowIndexManager::~KSyncFlowIndexManager() {
}
void KSyncFlowIndexManager::InitDone(uint32_t count) {
proto_ = ksync_->agent()->pkt()->get_flow_proto();
count_ = count;
index_list_.resize(count);
}
//////////////////////////////////////////////////////////////////////////////
// KSyncFlowIndexManager APIs
//////////////////////////////////////////////////////////////////////////////
void KSyncFlowIndexManager::RetryIndexAcquireRequest(FlowEntry *flow,
uint32_t flow_handle) {
if (flow == NULL)
return;
proto_->RetryIndexAcquireRequest(flow, flow_handle);
}
void KSyncFlowIndexManager::ReleaseRequest(FlowEntry *flow) {
Release(flow);
}
// Handle add of a flow
void KSyncFlowIndexManager::Add(FlowEntry *flow) {
FlowTableKSyncObject *object = GetKSyncObject(flow);
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED) {
UpdateFlowHandle(flow);
return;
}
// If flow already has a KSync entry, it means old flow was evicted.
// Delete the old KSync entry. Once the KSync entry is freed, we will
// get callback to "Release". New KSync entry will be allocated from
// "Release" method
if (index_entry->ksync_entry()) {
EvictFlow(flow);
return;
}
FlowEntryPtr old_flow = SafeAcquireIndex(flow);
if (old_flow.get() != NULL) {
// If index cannot be acquired, put flow into wait list of old_flow
// (flow holding the index)
EvictFlow(old_flow.get(), flow);
return;
}
assert(index_entry->ksync_entry_ == NULL);
if (index_entry->index_ == FlowEntry::kInvalidFlowHandle &&
flow->flow_handle() == FlowEntry::kInvalidFlowHandle) {
index_entry->state_ = KSyncFlowIndexEntry::INDEX_UNASSIGNED;
} else {
index_entry->state_ = KSyncFlowIndexEntry::INDEX_SET;
}
FlowTableKSyncEntry key(object, flow, flow->flow_handle());
index_entry->ksync_entry_ =
(static_cast<FlowTableKSyncEntry *>(object->Create(&key, true)));
// Add called for deleted flow. This happens when Reverse flow is
// deleted before getting ACK from vrouter.
// Create and delete KSync Entry
if (flow->deleted()) {
Delete(flow);
}
}
void KSyncFlowIndexManager::Change(FlowEntry *flow) {
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (flow->deleted() ||
(index_entry->state_ != KSyncFlowIndexEntry::INDEX_SET)) {
return;
}
// If index not yet assigned for flow, the flow will be written when later
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED) {
return;
}
FlowTableKSyncObject *object = GetKSyncObject(flow);
object->Change(index_entry->ksync_entry_);
}
bool KSyncFlowIndexManager::Delete(FlowEntry *flow) {
FlowTableKSyncObject *object = GetKSyncObject(flow);
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->delete_in_progress_) {
return false;
}
bool force_delete = false;
//Flow index allocation had failed from kernel, so dont wait for
//index allocation and delete flow. Note: Because of failed index allocation
//flow was marked as short flow with reason SHORT_FAILED_VROUTER_INSTALL
force_delete |= (flow->is_flags_set(FlowEntry::ShortFlow) &&
(flow->short_flow_reason() ==
((uint16_t) FlowEntry::SHORT_FAILED_VROUTER_INSTALL)));
if (!force_delete) {
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED)
return false;
if (index_entry->ksync_entry_ == NULL) {
assert(index_entry->index_ == FlowEntry::kInvalidFlowHandle);
return false;
}
}
index_entry->delete_in_progress_ = true;
// Hold reference to ksync-entry till this function call is over
KSyncEntry::KSyncEntryPtr ksync_ptr = index_entry->ksync_entry_;
object->Delete(index_entry->ksync_entry_);
return true;
}
// Flow was written with -1 as index and vrouter allocated an index.
void KSyncFlowIndexManager::UpdateFlowHandle(FlowEntry *flow) {
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->index_ == flow->flow_handle())
return;
// Ensure that flow is not evicted
// A flow with index -1 will always have a flow with HOLD state as reverse
// flow. VRouter does not evict flows in HOLD state. As a result, we dont
// expect the flow to be evicted.
assert(index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED);
assert(index_entry->index_ == FlowEntry::kInvalidFlowHandle);
assert(index_entry->ksync_entry());
FlowEntryPtr old_flow = SafeAcquireIndex(flow);
if (old_flow.get() != NULL) {
// If index cannot be acquired, put flow into wait list of old_flow
// (flow holding the index)
EvictFlow(old_flow.get(), flow);
return;
}
flow->ksync_index_entry()->state_ = KSyncFlowIndexEntry::INDEX_SET;
FlowTableKSyncObject *object = GetKSyncObject(flow);
object->UpdateFlowHandle(index_entry->ksync_entry_, index_entry->index_);
// If flow is deleted in the meanwhile, delete the flow entry
if (flow->deleted()) {
Delete(flow);
}
}
void KSyncFlowIndexManager::Release(FlowEntry *flow) {
FlowEntryPtr wait_flow = ReleaseIndex(flow);
// Make a copy of values needed for subsequent processing before reset
KSyncFlowIndexEntry::State state = flow->ksync_index_entry()->state_;
FlowEntryPtr owner_entry = flow->ksync_index_entry()->index_owner_;
uint32_t evict_index = flow->ksync_index_entry()->index_;
// Reset the old index entry
flow->ksync_index_entry()->Reset();
switch (state) {
// Entry has index set and no further transitions necessary
case KSyncFlowIndexEntry::INDEX_SET:
break;
// Entry deleted when waiting for index.
// Invoke Add() again so that the HOLD entry entry is deleted from VRouter
case KSyncFlowIndexEntry::INDEX_WAIT: {
RemoveWaitList(owner_entry.get(), flow);
Add(flow);
break;
}
// Index changed for flow and old index freed. Try acquring new index
case KSyncFlowIndexEntry::INDEX_CHANGE: {
RetryIndexAcquireRequest(wait_flow.get(), evict_index);
Add(flow);
break;
}
// Flow evicted. Now activate entry waiting for on the index
case KSyncFlowIndexEntry::INDEX_EVICT: {
RetryIndexAcquireRequest(wait_flow.get(), evict_index);
break;
}
default:
assert(0);
}
return;
}
// Release the index and return flow in wait list
FlowEntryPtr KSyncFlowIndexManager::ReleaseIndex(FlowEntry *flow) {
FlowEntryPtr wait_flow = NULL;
uint32_t index = flow->ksync_index_entry()->index_;
if (index == FlowEntry::kInvalidFlowHandle) {
return wait_flow;
}
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
assert(index_list_[index].owner_.get() == flow);
// Release the index_list_ entry
index_list_[index].owner_ = NULL;
wait_flow.swap(index_list_[index].wait_entry_);
return wait_flow;
}
FlowEntryPtr KSyncFlowIndexManager::FindByIndex(uint32_t idx) {
tbb::mutex::scoped_lock lock(index_list_[idx].mutex_);
if (index_list_[idx].owner_.get() != NULL)
return index_list_[idx].owner_;
return FlowEntryPtr(NULL);
}
FlowEntryPtr KSyncFlowIndexManager::AcquireIndex(FlowEntry *flow) {
FlowEntryPtr ret(NULL);
// Sanity checks for a new flow
assert(flow->ksync_index_entry()->index_ == FlowEntry::kInvalidFlowHandle);
// Ignore entries with invalid index
uint32_t index = flow->flow_handle();
if (index == FlowEntry::kInvalidFlowHandle) {
return ret;
}
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
if (index_list_[index].owner_.get() != NULL)
return index_list_[index].owner_;
flow->ksync_index_entry()->index_ = index;
index_list_[index].owner_ = flow;
return ret;
}
FlowEntryPtr KSyncFlowIndexManager::SafeAcquireIndex(FlowEntry *flow) {
if (flow->ksync_index_entry()->ksync_entry_ != NULL) {
assert(flow->ksync_index_entry()->index_ ==
FlowEntry::kInvalidFlowHandle);
}
return AcquireIndex(flow);
}
void KSyncFlowIndexManager::AddWaitList(FlowEntry *old_flow, FlowEntry *flow) {
uint32_t index = old_flow->ksync_index_entry()->index_;
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
assert((index_list_[index].wait_entry_.get() == NULL) ||
(index_list_[index].wait_entry_.get() == flow));
index_list_[index].wait_entry_ = flow;
}
void KSyncFlowIndexManager::RemoveWaitList(FlowEntry *old_flow,
FlowEntry *flow) {
uint32_t index = old_flow->ksync_index_entry()->index_;
tbb::mutex::scoped_lock lock(index_list_[index].mutex_);
assert(index_list_[index].wait_entry_.get() == flow);
index_list_[index].wait_entry_ = NULL;
}
void KSyncFlowIndexManager::EvictFlow(FlowEntry *flow) {
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
index_entry->evict_count_++;
index_entry->state_ = KSyncFlowIndexEntry::INDEX_CHANGE;
Delete(flow);
}
void KSyncFlowIndexManager::EvictFlow(FlowEntry *old_flow, FlowEntry *flow) {
old_flow->ksync_index_entry()->evict_count_++;
old_flow->ksync_index_entry()->state_ = KSyncFlowIndexEntry::INDEX_EVICT;
KSyncFlowIndexEntry *index_entry = flow->ksync_index_entry();
if (index_entry->state_ == KSyncFlowIndexEntry::INDEX_UNASSIGNED) {
assert(index_entry->index_ == FlowEntry::kInvalidFlowHandle);
} else {
flow->ksync_index_entry()->state_ = KSyncFlowIndexEntry::INDEX_WAIT;
}
AddWaitList(old_flow, flow);
proto_->EvictFlowRequest(old_flow, flow->flow_handle());
}
FlowTableKSyncObject *KSyncFlowIndexManager::GetKSyncObject(FlowEntry *flow) {
return flow->flow_table()->ksync_object();
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>
#include "functions.h"
int main(int argc, char** argv)
{
// print welcome message and prompt
printf("Welcome to rshell!\n");
bool ext = false;
while (!ext)
{
// holds a single command and its arguments
Command cmd;
// holds multiple commands
std::vector<Command> cmds;
// hold a raw line of input
std::string line;
// print prompt and get a line of text (done in condition)
printf("$ ");
getline(std::cin, line);
// look for comments
if (line.find("#") != std::string::npos)
{
// remove them if necessary (they're useless)
line = line.substr(0, line.find("#"));
}
// remove leading whitespace
while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
{
line = line.substr(1, line.size() - 1);
}
// adding this makes parsing easier
line += "; ";
if (std::cin.fail())
{
printf("\nGoodbye!\n");
exit(0);
}
int mode = GETWORD;
unsigned begin = 0;
// prepare cmd
cmd.connector = NONE;
// syntax error flag
bool se = false;
// starts with a connector? I don't think so
if (line.size() > 0 && isConn(line[0]) && line[0] != ';')
{
se = true;
}
// handle the input
for(unsigned i = 0; i < line.size() && !se; ++i)
{
bool con = isConn(line[i]);
bool space = isspace(line[i]);
// if we're getting a word and there's a whitespace or connector here
if (mode == GETWORD && (space || con))
{
// chunk the last term and throw it into the vector
char* c = stocstr(line.substr(begin, i - begin));
if (strlen(c) > 0)
{
cmd.args.push_back(c);
}
else
{
// only happens when nothing is entered. breaks so nothing more happens
break;
}
if (space)
{
mode = TRIMSPACE;
}
else // it's a connector
{
handleCon(cmds, cmd, line, mode, begin, i, se);
}
}
else if (mode == TRIMSPACE && (!space || con))
{
if (con && cmd.args.empty())
{
if (line[i] != ';')
{
se = true;
}
}
else if (con)
{
handleCon(cmds, cmd, line, mode, begin, i, se);
}
else
{
mode = GETWORD;
begin = i;
}
}
else if (mode == HANDLESEMI && line[i] != ';')
{
if (isConn(line[i]))
{
se = true;
}
else if (isspace(line[i]))
{
mode = TRIMSPACE;
}
else // it's a word
{
mode = GETWORD;
begin = i;
}
}
}
// if the last command has a continuation connector, syntax error
if (cmds.size() > 0 && (cmds[cmds.size() - 1].connector == AND
|| cmds[cmds.size() - 1].connector == OR))
{
se = true;
}
// if there was a syntax error
if (se)
{
printf("Syntax error\n");
continue;
}
// now to execute all the commands
for(unsigned i = 0; i < cmds.size(); ++i)
{
int exitStatus = 0;
char* arg = cmds[i].args[0];
if (strcmp(arg, "exit") == 0)
{
ext = true;
break;
}
char** argv = new char*[cmds[i].args.size()];
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
argv[j] = cmds[i].args[j];
}
// arg and argv are now prepared
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
exit(1);
}
else if (pid == 0) // child process
{
if (execvp(arg, argv) == -1)
{
// if there's a return value, there was a problem
// -1 indicates a problem, specifically
perror("execvp");
exit(1);
}
}
else // parent process
{
if (waitpid(pid, &exitStatus, 0) == -1)
{
perror("waitpid");
exit(1);
}
}
if (!exitStatus) // all is good (0)
{
while (i < cmds.size() && cmds[i].connector == OR)
{
++i;
}
}
else // last command failed
{
while (i < cmds.size() && cmds[i].connector == AND)
{
++i;
}
}
}
/* debugging code
for(unsigned i = 0; i < cmds.size(); ++i)
{
printf("Command %u:\n", i);
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
printf("\t\"%s\"\n", cmds[i].args[j]);
}
switch(cmds[i].connector)
{
case AND:
printf("\t&&\n");
break;
case OR:
printf("\t||\n");
break;
case SEMI:
printf("\t;\n");
break;
case NONE:
printf("\tNo connector\n");
break;
default:
printf("\tERROR: no valid connector specified\n");
}
}
*/
// deallocate allocated memory
for(unsigned i = 0; i < cmds.size(); ++i)
{
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
delete[] cmds[i].args[j];
}
}
}
return 0;
}
<commit_msg>added goodbye message<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>
#include "functions.h"
int main(int argc, char** argv)
{
// print welcome message and prompt
printf("Welcome to rshell!\n");
bool ext = false;
while (!ext)
{
// holds a single command and its arguments
Command cmd;
// holds multiple commands
std::vector<Command> cmds;
// hold a raw line of input
std::string line;
// print prompt and get a line of text (done in condition)
printf("$ ");
getline(std::cin, line);
// look for comments
if (line.find("#") != std::string::npos)
{
// remove them if necessary (they're useless)
line = line.substr(0, line.find("#"));
}
// remove leading whitespace
while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
{
line = line.substr(1, line.size() - 1);
}
// adding this makes parsing easier
line += "; ";
if (std::cin.fail())
{
printf("\nGoodbye!\n");
exit(0);
}
int mode = GETWORD;
unsigned begin = 0;
// prepare cmd
cmd.connector = NONE;
// syntax error flag
bool se = false;
// starts with a connector? I don't think so
if (line.size() > 0 && isConn(line[0]) && line[0] != ';')
{
se = true;
}
// handle the input
for(unsigned i = 0; i < line.size() && !se; ++i)
{
bool con = isConn(line[i]);
bool space = isspace(line[i]);
// if we're getting a word and there's a whitespace or connector here
if (mode == GETWORD && (space || con))
{
// chunk the last term and throw it into the vector
char* c = stocstr(line.substr(begin, i - begin));
if (strlen(c) > 0)
{
cmd.args.push_back(c);
}
else
{
// only happens when nothing is entered. breaks so nothing more happens
break;
}
if (space)
{
mode = TRIMSPACE;
}
else // it's a connector
{
handleCon(cmds, cmd, line, mode, begin, i, se);
}
}
else if (mode == TRIMSPACE && (!space || con))
{
if (con && cmd.args.empty())
{
if (line[i] != ';')
{
se = true;
}
}
else if (con)
{
handleCon(cmds, cmd, line, mode, begin, i, se);
}
else
{
mode = GETWORD;
begin = i;
}
}
else if (mode == HANDLESEMI && line[i] != ';')
{
if (isConn(line[i]))
{
se = true;
}
else if (isspace(line[i]))
{
mode = TRIMSPACE;
}
else // it's a word
{
mode = GETWORD;
begin = i;
}
}
}
// if the last command has a continuation connector, syntax error
if (cmds.size() > 0 && (cmds[cmds.size() - 1].connector == AND
|| cmds[cmds.size() - 1].connector == OR))
{
se = true;
}
// if there was a syntax error
if (se)
{
printf("Syntax error\n");
continue;
}
// now to execute all the commands
for(unsigned i = 0; i < cmds.size(); ++i)
{
int exitStatus = 0;
char* arg = cmds[i].args[0];
if (strcmp(arg, "exit") == 0)
{
ext = true;
break;
}
char** argv = new char*[cmds[i].args.size()];
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
argv[j] = cmds[i].args[j];
}
// arg and argv are now prepared
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
exit(1);
}
else if (pid == 0) // child process
{
if (execvp(arg, argv) == -1)
{
// if there's a return value, there was a problem
// -1 indicates a problem, specifically
perror("execvp");
exit(1);
}
}
else // parent process
{
if (waitpid(pid, &exitStatus, 0) == -1)
{
perror("waitpid");
exit(1);
}
}
if (!exitStatus) // all is good (0)
{
while (i < cmds.size() && cmds[i].connector == OR)
{
++i;
}
}
else // last command failed
{
while (i < cmds.size() && cmds[i].connector == AND)
{
++i;
}
}
}
/* debugging code
for(unsigned i = 0; i < cmds.size(); ++i)
{
printf("Command %u:\n", i);
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
printf("\t\"%s\"\n", cmds[i].args[j]);
}
switch(cmds[i].connector)
{
case AND:
printf("\t&&\n");
break;
case OR:
printf("\t||\n");
break;
case SEMI:
printf("\t;\n");
break;
case NONE:
printf("\tNo connector\n");
break;
default:
printf("\tERROR: no valid connector specified\n");
}
}
*/
// deallocate allocated memory
for(unsigned i = 0; i < cmds.size(); ++i)
{
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
delete[] cmds[i].args[j];
}
}
}
printf("Goodbye!\n");
return 0;
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/15/2019, 9:15:16 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return mint(0) - *this; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
int N;
ll A[100010];
void solve()
{
int ind = 0;
for (auto i = 0; i < N; i++)
{
if (A[i] > 0)
{
ind = i;
break;
}
}
ll ans = 0;
for (auto i = 0; i < N; i++)
{
ans += abs(A[i]);
}
cout << ans << endl;
ll now = A[0];
for (auto i = ind; i < N - 1; i++)
{
cout << now << " " << A[i] << endl;
now -= A[i];
}
ll now2 = A[N - 1];
for (auto i = 1; i < ind; i++)
{
cout << now2 << " " << A[i] << endl;
now2 -= A[i];
}
cout << now2 << " " << now << endl;
assert(now2 - now == ans);
}
void solve_plus()
{
ll ans = -A[0];
for (auto i = 1; i < N; i++)
{
ans += abs(A[i]);
}
cout << ans << endl;
ll now = A[0];
for (auto i = 1; i < N - 1; i++)
{
cout << now << " " << A[i] << endl;
now -= A[i];
}
cout << A[N - 1] << " " << now << endl;
assert(A[N - 1] - now == ans);
}
void solve_minus()
{
ll ans = A[N - 1];
for (auto i = 0; i < N - 1; i++)
{
ans += abs(A[i]);
}
cout << ans << endl;
ll now = A[N - 1];
for (auto i = 0; i < N - 1; i++)
{
cout << now << " " << A[i] << endl;
now -= A[i];
}
assert(now == ans);
}
int main()
{
// init();
cin >> N;
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
sort(A, A + N);
if (A[0] > 0)
{
solve_plus();
}
else if (A[N - 1] < 0)
{
solve_minus();
}
else
{
solve();
}
}<commit_msg>submit C.cpp to 'C - Successive Subtraction' (diverta2019-2) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/15/2019, 9:15:16 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return mint(0) - *this; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
int N;
ll A[100010];
void solve()
{
int ind = 0;
for (auto i = 0; i < N; i++)
{
if (A[i] > 0)
{
ind = i;
break;
}
}
ll ans = 0;
for (auto i = 0; i < N; i++)
{
ans += abs(A[i]);
}
cout << ans << endl;
ll now = A[0];
for (auto i = ind; i < N - 1; i++)
{
cout << now << " " << A[i] << endl;
now -= A[i];
}
ll now2 = A[N - 1];
for (auto i = 1; i < ind; i++)
{
cout << now2 << " " << A[i] << endl;
now2 -= A[i];
}
cout << now2 << " " << now << endl;
assert(now2 - now == ans);
}
void solve_plus()
{
ll ans = -A[0];
for (auto i = 1; i < N; i++)
{
ans += abs(A[i]);
}
cout << ans << endl;
ll now = A[0];
for (auto i = 1; i < N - 1; i++)
{
cout << now << " " << A[i] << endl;
now -= A[i];
}
cout << A[N - 1] << " " << now << endl;
assert(A[N - 1] - now == ans);
}
void solve_minus()
{
ll ans = A[N - 1];
for (auto i = 0; i < N - 1; i++)
{
ans += abs(A[i]);
}
cout << ans << endl;
ll now = A[N - 1];
for (auto i = 0; i < N - 1; i++)
{
cout << now << " " << A[i] << endl;
now -= A[i];
}
assert(now == ans);
}
int main()
{
// init();
cin >> N;
for (auto i = 0; i < N; i++)
{
cin >> A[i];
}
sort(A, A + N);
if (A[0] >= 0)
{
solve_plus();
}
else if (A[N - 1] <= 0)
{
solve_minus();
}
else
{
solve();
}
}<|endoftext|> |
<commit_before>// Given an integer n, count the total number of digit 1 appearing in all
// non-negative integers less than or equal to n.
// For example:
// Given n = 13,
// Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12,
// 13.
class Solution {
public:
int countDigitOne(int n) {
if (n < 0)
return 0;
int cnt = 0;
for (int i = 1; i <= n; i *= 10) {
// at each loop, add contribution of this digit
// e.g. for 1124
// 1st loop, we add 1 + 1 * (n/10) (0001, 0011, 0021...1111)
// 2nd loop, we add 10 + 10 * (n/100) (010-019, 110-119...1010-1019)
// 3rd loop, we add 25 + 100 (100-199) for 100 digit contribution
// 4th loop, we add 125 for 1000 digit contribution
int digit = (n / i) % 10;
if (digit == 1)
cnt += n % i + 1;
else if (digit > 1)
cnt += i;
cnt += i * (n / i / 10);
if (INT_MAX / i < 10)
break;
}
return cnt;
}
};<commit_msg>new version<commit_after>// Given an integer n, count the total number of digit 1 appearing in all
// non-negative integers less than or equal to n.
// For example:
// Given n = 13,
// Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12,
// 13.
class Solution {
public:
int countDigitOne(int n) {
if (n < 0)
return 0;
int cnt = 0;
for (int i = 1; i <= n; i *= 10) {
// at each loop, add contribution of this digit
// e.g. for 1124
// 1st loop, we add 1 + 1 * (n/10) (0001, 0011, 0021...1111)
// 2nd loop, we add 10 + 10 * (n/100) (010-019, 110-119...1010-1019)
// 3rd loop, we add 25 + 100 (100-199) for 100 digit contribution
// 4th loop, we add 125 for 1000 digit contribution
int digit = (n / i) % 10;
if (digit == 1)
cnt += n % i + 1;
else if (digit > 1)
cnt += i;
cnt += i * (n / i / 10);
if (INT_MAX / i < 10)
break;
}
return cnt;
}
};<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <ROOT/TVec.hxx>
#include <vector>
#include <sstream>
template <typename T, typename V>
void CheckEqual(const T &a, const V &b, std::string_view msg = "")
{
const auto asize = a.size();
const auto bsize = b.size();
EXPECT_EQ(asize, bsize);
for (unsigned int i = 0; i < asize; ++i) {
EXPECT_EQ(a[i], b[i]) << msg;
}
}
TEST(VecOps, DefaultCtor)
{
ROOT::Experimental::VecOps::TVec<int> v;
EXPECT_EQ(v.size(), 0u);
}
TEST(VecOps, InitListCtor)
{
ROOT::Experimental::VecOps::TVec<int> v{1, 2, 3};
EXPECT_EQ(v.size(), 3u);
EXPECT_EQ(v[0], 1);
EXPECT_EQ(v[1], 2);
EXPECT_EQ(v[2], 3);
}
TEST(VecOps, CopyCtor)
{
ROOT::Experimental::VecOps::TVec<int> v1{1, 2, 3};
ROOT::Experimental::VecOps::TVec<int> v2(v1);
EXPECT_EQ(v1.size(), 3u);
EXPECT_EQ(v2.size(), 3u);
EXPECT_EQ(v2[0], 1);
EXPECT_EQ(v2[1], 2);
EXPECT_EQ(v2[2], 3);
}
TEST(VecOps, MoveCtor)
{
ROOT::Experimental::VecOps::TVec<int> v1{1, 2, 3};
ROOT::Experimental::VecOps::TVec<int> v2(std::move(v1));
EXPECT_EQ(v1.size(), 0u);
EXPECT_EQ(v2.size(), 3u);
}
TEST(VecOps, MathScalar)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
TVec<double> v(ref);
int scalar = 3;
auto plus = v + scalar;
auto minus = v - scalar;
auto mult = v * scalar;
auto div = v / scalar;
CheckEqual(plus, ref + scalar);
CheckEqual(minus, ref - scalar);
CheckEqual(mult, ref * scalar);
CheckEqual(div, ref / scalar);
// The same with views
ROOT::Experimental::VecOps::TVec<double> w(ref.data(), ref.size());
plus = w + scalar;
minus = w - scalar;
mult = w * scalar;
div = w / scalar;
CheckEqual(plus, ref + scalar);
CheckEqual(minus, ref - scalar);
CheckEqual(mult, ref * scalar);
CheckEqual(div, ref / scalar);
}
TEST(VecOps, MathScalarInPlace)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
const TVec<double> v(ref);
int scalar = 3;
auto plus = v;
plus += scalar;
auto minus = v;
minus -= scalar;
auto mult = v;
mult *= scalar;
auto div = v;
div /= scalar;
CheckEqual(plus, ref + scalar);
CheckEqual(minus, ref - scalar);
CheckEqual(mult, ref * scalar);
CheckEqual(div, ref / scalar);
}
TEST(VecOps, MathVector)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
TVec<double> vec{3, 4, 5};
TVec<double> v(ref);
auto plus = v + vec;
auto minus = v - vec;
auto mult = v * vec;
auto div = v / vec;
CheckEqual(plus, ref + vec);
CheckEqual(minus, ref - vec);
CheckEqual(mult, ref * vec);
CheckEqual(div, ref / vec);
// The same with 1 view
ROOT::Experimental::VecOps::TVec<double> w(ref.data(), ref.size());
plus = w + vec;
minus = w - vec;
mult = w * vec;
div = w / vec;
CheckEqual(plus, ref + vec);
CheckEqual(minus, ref - vec);
CheckEqual(mult, ref * vec);
CheckEqual(div, ref / vec);
// The same with 2 views
ROOT::Experimental::VecOps::TVec<double> w2(ref.data(), ref.size());
plus = w + w2;
minus = w - w2;
mult = w * w2;
div = w / w2;
CheckEqual(plus, ref + w2);
CheckEqual(minus, ref - w2);
CheckEqual(mult, ref * w2);
CheckEqual(div, ref / w2);
}
TEST(VecOps, MathVectorInPlace)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
TVec<double> vec{3, 4, 5};
TVec<double> v(ref);
auto plus = v;
plus += vec;
auto minus = v;
minus -= vec;
auto mult = v;
mult *= vec;
auto div = v;
div /= vec;
CheckEqual(plus, ref + vec);
CheckEqual(minus, ref - vec);
CheckEqual(mult, ref * vec);
CheckEqual(div, ref / vec);
}
TEST(VecOps, Filter)
{
using namespace ROOT::Experimental::VecOps;
TVec<int> v{0, 1, 2, 3, 4, 5};
const std::vector<int> vEvenRef{0, 2, 4};
const std::vector<int> vOddRef{1, 3, 5};
auto vEven = v[v % 2 == 0];
auto vOdd = v[v % 2 == 1];
CheckEqual(vEven, vEvenRef, "Even check");
CheckEqual(vOdd, vOddRef, "Odd check");
// now with the helper function
vEven = Filter(v, [](int i) { return 0 == i % 2; });
vOdd = Filter(v, [](int i) { return 1 == i % 2; });
CheckEqual(vEven, vEvenRef, "Even check");
CheckEqual(vOdd, vOddRef, "Odd check");
}
template <typename T, typename V>
std::string PrintTVec(ROOT::Experimental::VecOps::TVec<T> v, V w)
{
using namespace ROOT::Experimental::VecOps;
std::stringstream ss;
ss << v << " " << w << std::endl;
ss << v + w << std::endl;
ss << v - w << std::endl;
ss << v * w << std::endl;
ss << v / w << std::endl;
ss << (v > w) << std::endl;
ss << (v >= w) << std::endl;
ss << (v == w) << std::endl;
ss << (v <= w) << std::endl;
ss << (v < w) << std::endl;
return ss.str();
}
TEST(VecOps, PrintOps)
{
using namespace ROOT::Experimental::VecOps;
TVec<int> ref{1, 2, 3};
TVec<int> v(ref);
auto ref0 = R"ref0({ 1, 2, 3 } 2
{ 3, 4, 5 }
{ -1, 0, 1 }
{ 2, 4, 6 }
{ 0.5, 1, 1.5 }
{ 0, 0, 1 }
{ 0, 1, 1 }
{ 0, 1, 0 }
{ 1, 1, 0 }
{ 1, 0, 0 }
)ref0";
auto t0 = PrintTVec(v, 2.);
EXPECT_STREQ(t0.c_str(), ref0);
auto ref1 = R"ref1({ 1, 2, 3 } { 3, 4, 5 }
{ 4, 6, 8 }
{ -2, -2, -2 }
{ 3, 8, 15 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 1, 1, 1 }
{ 1, 1, 1 }
)ref1";
auto t1 = PrintTVec(v, ref + 2);
EXPECT_STREQ(t1.c_str(), ref1);
ROOT::Experimental::VecOps::TVec<int> w(ref.data(), ref.size());
auto ref2 = R"ref2({ 1, 2, 3 } 2
{ 3, 4, 5 }
{ -1, 0, 1 }
{ 2, 4, 6 }
{ 0.5, 1, 1.5 }
{ 0, 0, 1 }
{ 0, 1, 1 }
{ 0, 1, 0 }
{ 1, 1, 0 }
{ 1, 0, 0 }
)ref2";
auto t2 = PrintTVec(v, 2.);
EXPECT_STREQ(t2.c_str(), ref2);
auto ref3 = R"ref3({ 1, 2, 3 } { 3, 4, 5 }
{ 4, 6, 8 }
{ -2, -2, -2 }
{ 3, 8, 15 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 1, 1, 1 }
{ 1, 1, 1 }
)ref3";
auto t3 = PrintTVec(v, ref + 2);
EXPECT_STREQ(t3.c_str(), ref3);
}
TEST(VecOps, MathFuncs)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> v{1, 2, 3};
CheckEqual(sqrt(v), Map(v, [](double x) { return std::sqrt(x); }), " error checking math function sqrt");
CheckEqual(log(v), Map(v, [](double x) { return std::log(x); }), " error checking math function log");
CheckEqual(sin(v), Map(v, [](double x) { return std::sin(x); }), " error checking math function sin");
CheckEqual(cos(v), Map(v, [](double x) { return std::cos(x); }), " error checking math function cos");
CheckEqual(tan(v), Map(v, [](double x) { return std::tan(x); }), " error checking math function tan");
CheckEqual(atan(v), Map(v, [](double x) { return std::atan(x); }), " error checking math function atan");
CheckEqual(sinh(v), Map(v, [](double x) { return std::sinh(x); }), " error checking math function sinh");
CheckEqual(cosh(v), Map(v, [](double x) { return std::cosh(x); }), " error checking math function cosh");
CheckEqual(tanh(v), Map(v, [](double x) { return std::tanh(x); }), " error checking math function tanh");
CheckEqual(asinh(v), Map(v, [](double x) { return std::asinh(x); }), " error checking math function asinh");
CheckEqual(acosh(v), Map(v, [](double x) { return std::acosh(x); }), " error checking math function acosh");
v /= 10.;
CheckEqual(asin(v), Map(v, [](double x) { return std::asin(x); }), " error checking math function asin");
CheckEqual(acos(v), Map(v, [](double x) { return std::acos(x); }), " error checking math function acos");
CheckEqual(atanh(v), Map(v, [](double x) { return std::atanh(x); }), " error checking math function atanh");
}
TEST(VecOps, PhysicsSelections)
{
// We emulate 8 muons
ROOT::Experimental::VecOps::TVec<short> mu_charge{1, 1, -1, -1, -1, 1, 1, -1};
ROOT::Experimental::VecOps::TVec<float> mu_pt{56, 45, 32, 24, 12, 8, 7, 6.2};
ROOT::Experimental::VecOps::TVec<float> mu_eta{3.1, -.2, -1.1, 1, 4.1, 1.6, 2.4, -.5};
// Pick the pt of the muons with a pt greater than 10, an eta between -2 and 2 and a negative charge
// or the ones with a pt > 20, outside the eta range -2:2 and with positive charge
auto goodMuons_pt = mu_pt[(mu_pt > 10.f && abs(mu_eta) <= 2.f && mu_charge == -1) ||
(mu_pt > 15.f && abs(mu_eta) > 2.f && mu_charge == 1)];
ROOT::Experimental::VecOps::TVec<float> goodMuons_pt_ref = {56, 32, 24};
CheckEqual(goodMuons_pt, goodMuons_pt_ref, "Muons quality cut");
}
<commit_msg>[VecOps] Fix vector initialisation on windows<commit_after>#include <gtest/gtest.h>
#include <ROOT/TVec.hxx>
#include <vector>
#include <sstream>
template <typename T, typename V>
void CheckEqual(const T &a, const V &b, std::string_view msg = "")
{
const auto asize = a.size();
const auto bsize = b.size();
EXPECT_EQ(asize, bsize);
for (unsigned int i = 0; i < asize; ++i) {
EXPECT_EQ(a[i], b[i]) << msg;
}
}
TEST(VecOps, DefaultCtor)
{
ROOT::Experimental::VecOps::TVec<int> v;
EXPECT_EQ(v.size(), 0u);
}
TEST(VecOps, InitListCtor)
{
ROOT::Experimental::VecOps::TVec<int> v{1, 2, 3};
EXPECT_EQ(v.size(), 3u);
EXPECT_EQ(v[0], 1);
EXPECT_EQ(v[1], 2);
EXPECT_EQ(v[2], 3);
}
TEST(VecOps, CopyCtor)
{
ROOT::Experimental::VecOps::TVec<int> v1{1, 2, 3};
ROOT::Experimental::VecOps::TVec<int> v2(v1);
EXPECT_EQ(v1.size(), 3u);
EXPECT_EQ(v2.size(), 3u);
EXPECT_EQ(v2[0], 1);
EXPECT_EQ(v2[1], 2);
EXPECT_EQ(v2[2], 3);
}
TEST(VecOps, MoveCtor)
{
ROOT::Experimental::VecOps::TVec<int> v1{1, 2, 3};
ROOT::Experimental::VecOps::TVec<int> v2(std::move(v1));
EXPECT_EQ(v1.size(), 0u);
EXPECT_EQ(v2.size(), 3u);
}
TEST(VecOps, MathScalar)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
TVec<double> v(ref);
int scalar = 3;
auto plus = v + scalar;
auto minus = v - scalar;
auto mult = v * scalar;
auto div = v / scalar;
CheckEqual(plus, ref + scalar);
CheckEqual(minus, ref - scalar);
CheckEqual(mult, ref * scalar);
CheckEqual(div, ref / scalar);
// The same with views
ROOT::Experimental::VecOps::TVec<double> w(ref.data(), ref.size());
plus = w + scalar;
minus = w - scalar;
mult = w * scalar;
div = w / scalar;
CheckEqual(plus, ref + scalar);
CheckEqual(minus, ref - scalar);
CheckEqual(mult, ref * scalar);
CheckEqual(div, ref / scalar);
}
TEST(VecOps, MathScalarInPlace)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
const TVec<double> v(ref);
int scalar = 3;
auto plus = v;
plus += scalar;
auto minus = v;
minus -= scalar;
auto mult = v;
mult *= scalar;
auto div = v;
div /= scalar;
CheckEqual(plus, ref + scalar);
CheckEqual(minus, ref - scalar);
CheckEqual(mult, ref * scalar);
CheckEqual(div, ref / scalar);
}
TEST(VecOps, MathVector)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
TVec<double> vec{3, 4, 5};
TVec<double> v(ref);
auto plus = v + vec;
auto minus = v - vec;
auto mult = v * vec;
auto div = v / vec;
CheckEqual(plus, ref + vec);
CheckEqual(minus, ref - vec);
CheckEqual(mult, ref * vec);
CheckEqual(div, ref / vec);
// The same with 1 view
ROOT::Experimental::VecOps::TVec<double> w(ref.data(), ref.size());
plus = w + vec;
minus = w - vec;
mult = w * vec;
div = w / vec;
CheckEqual(plus, ref + vec);
CheckEqual(minus, ref - vec);
CheckEqual(mult, ref * vec);
CheckEqual(div, ref / vec);
// The same with 2 views
ROOT::Experimental::VecOps::TVec<double> w2(ref.data(), ref.size());
plus = w + w2;
minus = w - w2;
mult = w * w2;
div = w / w2;
CheckEqual(plus, ref + w2);
CheckEqual(minus, ref - w2);
CheckEqual(mult, ref * w2);
CheckEqual(div, ref / w2);
}
TEST(VecOps, MathVectorInPlace)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> ref{1, 2, 3};
TVec<double> vec{3, 4, 5};
TVec<double> v(ref);
auto plus = v;
plus += vec;
auto minus = v;
minus -= vec;
auto mult = v;
mult *= vec;
auto div = v;
div /= vec;
CheckEqual(plus, ref + vec);
CheckEqual(minus, ref - vec);
CheckEqual(mult, ref * vec);
CheckEqual(div, ref / vec);
}
TEST(VecOps, Filter)
{
using namespace ROOT::Experimental::VecOps;
TVec<int> v{0, 1, 2, 3, 4, 5};
const std::vector<int> vEvenRef{0, 2, 4};
const std::vector<int> vOddRef{1, 3, 5};
auto vEven = v[v % 2 == 0];
auto vOdd = v[v % 2 == 1];
CheckEqual(vEven, vEvenRef, "Even check");
CheckEqual(vOdd, vOddRef, "Odd check");
// now with the helper function
vEven = Filter(v, [](int i) { return 0 == i % 2; });
vOdd = Filter(v, [](int i) { return 1 == i % 2; });
CheckEqual(vEven, vEvenRef, "Even check");
CheckEqual(vOdd, vOddRef, "Odd check");
}
template <typename T, typename V>
std::string PrintTVec(ROOT::Experimental::VecOps::TVec<T> v, V w)
{
using namespace ROOT::Experimental::VecOps;
std::stringstream ss;
ss << v << " " << w << std::endl;
ss << v + w << std::endl;
ss << v - w << std::endl;
ss << v * w << std::endl;
ss << v / w << std::endl;
ss << (v > w) << std::endl;
ss << (v >= w) << std::endl;
ss << (v == w) << std::endl;
ss << (v <= w) << std::endl;
ss << (v < w) << std::endl;
return ss.str();
}
TEST(VecOps, PrintOps)
{
using namespace ROOT::Experimental::VecOps;
TVec<int> ref{1, 2, 3};
TVec<int> v(ref);
auto ref0 = R"ref0({ 1, 2, 3 } 2
{ 3, 4, 5 }
{ -1, 0, 1 }
{ 2, 4, 6 }
{ 0.5, 1, 1.5 }
{ 0, 0, 1 }
{ 0, 1, 1 }
{ 0, 1, 0 }
{ 1, 1, 0 }
{ 1, 0, 0 }
)ref0";
auto t0 = PrintTVec(v, 2.);
EXPECT_STREQ(t0.c_str(), ref0);
auto ref1 = R"ref1({ 1, 2, 3 } { 3, 4, 5 }
{ 4, 6, 8 }
{ -2, -2, -2 }
{ 3, 8, 15 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 1, 1, 1 }
{ 1, 1, 1 }
)ref1";
auto t1 = PrintTVec(v, ref + 2);
EXPECT_STREQ(t1.c_str(), ref1);
ROOT::Experimental::VecOps::TVec<int> w(ref.data(), ref.size());
auto ref2 = R"ref2({ 1, 2, 3 } 2
{ 3, 4, 5 }
{ -1, 0, 1 }
{ 2, 4, 6 }
{ 0.5, 1, 1.5 }
{ 0, 0, 1 }
{ 0, 1, 1 }
{ 0, 1, 0 }
{ 1, 1, 0 }
{ 1, 0, 0 }
)ref2";
auto t2 = PrintTVec(v, 2.);
EXPECT_STREQ(t2.c_str(), ref2);
auto ref3 = R"ref3({ 1, 2, 3 } { 3, 4, 5 }
{ 4, 6, 8 }
{ -2, -2, -2 }
{ 3, 8, 15 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 0, 0, 0 }
{ 1, 1, 1 }
{ 1, 1, 1 }
)ref3";
auto t3 = PrintTVec(v, ref + 2);
EXPECT_STREQ(t3.c_str(), ref3);
}
TEST(VecOps, MathFuncs)
{
using namespace ROOT::Experimental::VecOps;
TVec<double> v{1, 2, 3};
CheckEqual(sqrt(v), Map(v, [](double x) { return std::sqrt(x); }), " error checking math function sqrt");
CheckEqual(log(v), Map(v, [](double x) { return std::log(x); }), " error checking math function log");
CheckEqual(sin(v), Map(v, [](double x) { return std::sin(x); }), " error checking math function sin");
CheckEqual(cos(v), Map(v, [](double x) { return std::cos(x); }), " error checking math function cos");
CheckEqual(tan(v), Map(v, [](double x) { return std::tan(x); }), " error checking math function tan");
CheckEqual(atan(v), Map(v, [](double x) { return std::atan(x); }), " error checking math function atan");
CheckEqual(sinh(v), Map(v, [](double x) { return std::sinh(x); }), " error checking math function sinh");
CheckEqual(cosh(v), Map(v, [](double x) { return std::cosh(x); }), " error checking math function cosh");
CheckEqual(tanh(v), Map(v, [](double x) { return std::tanh(x); }), " error checking math function tanh");
CheckEqual(asinh(v), Map(v, [](double x) { return std::asinh(x); }), " error checking math function asinh");
CheckEqual(acosh(v), Map(v, [](double x) { return std::acosh(x); }), " error checking math function acosh");
v /= 10.;
CheckEqual(asin(v), Map(v, [](double x) { return std::asin(x); }), " error checking math function asin");
CheckEqual(acos(v), Map(v, [](double x) { return std::acos(x); }), " error checking math function acos");
CheckEqual(atanh(v), Map(v, [](double x) { return std::atanh(x); }), " error checking math function atanh");
}
TEST(VecOps, PhysicsSelections)
{
// We emulate 8 muons
ROOT::Experimental::VecOps::TVec<short> mu_charge{1, 1, -1, -1, -1, 1, 1, -1};
ROOT::Experimental::VecOps::TVec<float> mu_pt{56.f, 45.f, 32.f, 24.f, 12.f, 8.f, 7.f, 6.2f};
ROOT::Experimental::VecOps::TVec<float> mu_eta{3.1f, -.2f, -1.1f, 1.f, 4.1f, 1.6f, 2.4f, -.5f};
// Pick the pt of the muons with a pt greater than 10, an eta between -2 and 2 and a negative charge
// or the ones with a pt > 20, outside the eta range -2:2 and with positive charge
auto goodMuons_pt = mu_pt[(mu_pt > 10.f && abs(mu_eta) <= 2.f && mu_charge == -1) ||
(mu_pt > 15.f && abs(mu_eta) > 2.f && mu_charge == 1)];
ROOT::Experimental::VecOps::TVec<float> goodMuons_pt_ref = {56.f, 32.f, 24.f};
CheckEqual(goodMuons_pt, goodMuons_pt_ref, "Muons quality cut");
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "entry.h"
#include "journal.h"
#include "format.h"
#include "session.h"
#include "report.h"
namespace ledger {
entry_base_t::entry_base_t(const entry_base_t& e)
: item_t(), journal(NULL)
{
TRACE_CTOR(entry_base_t, "copy");
#if 0
xacts.insert(xacts.end(), e.xacts.begin(), e.xacts.end());
#endif
}
entry_base_t::~entry_base_t()
{
TRACE_DTOR(entry_base_t);
foreach (xact_t * xact, xacts) {
// If the transaction is a temporary, it will be destructed when the
// temporary is. If it's from a binary cache, we can safely destruct it
// but its memory will be deallocated with the cache.
if (! xact->has_flags(ITEM_TEMP)) {
if (! xact->has_flags(ITEM_IN_CACHE))
checked_delete(xact);
else
xact->~xact_t();
}
}
}
item_t::state_t entry_base_t::state() const
{
bool first = true;
state_t result = UNCLEARED;
foreach (xact_t * xact, xacts) {
if ((result == UNCLEARED && xact->_state != UNCLEARED) ||
(result == PENDING && xact->_state == CLEARED))
result = xact->_state;
}
return result;
}
void entry_base_t::add_xact(xact_t * xact)
{
xacts.push_back(xact);
}
bool entry_base_t::remove_xact(xact_t * xact)
{
xacts.remove(xact);
return true;
}
bool entry_base_t::finalize()
{
// Scan through and compute the total balance for the entry. This is used
// for auto-calculating the value of entries with no cost, and the per-unit
// price of unpriced commodities.
// (let ((balance 0)
// null-xact)
value_t balance;
xact_t * null_xact = NULL;
foreach (xact_t * xact, xacts) {
if (xact->must_balance()) {
amount_t& p(xact->cost ? *xact->cost : xact->amount);
DEBUG("entry.finalize", "xact must balance = " << p);
if (! p.is_null()) {
if (p.keep_precision()) {
amount_t temp(p);
// If the amount was a cost, it very likely has the "keep_precision"
// flag set, meaning commodity display precision is ignored when
// displaying the amount. We never want this set for the balance,
// so we must clear the flag in a temporary to avoid it propagating
// into the balance.
temp.set_keep_precision(false);
add_or_set_value(balance, temp);
} else {
add_or_set_value(balance, p);
}
} else {
if (null_xact)
throw_(std::logic_error,
"Only one xact with null amount allowed per entry");
else
null_xact = xact;
}
}
}
assert(balance.valid());
DEBUG("entry.finalize", "initial balance = " << balance);
// If there is only one xact, balance against the default account if
// one has been set.
if (journal && journal->basket && xacts.size() == 1 && ! balance.is_null()) {
// jww (2008-07-24): Need to make the rest of the code aware of what to do
// when it sees a generated xact.
null_xact = new xact_t(journal->basket, ITEM_GENERATED);
null_xact->_state = (*xacts.begin())->_state;
add_xact(null_xact);
}
if (null_xact != NULL) {
// If one xact has no value at all, its value will become the
// inverse of the rest. If multiple commodities are involved, multiple
// xacts are generated to balance them all.
if (balance.is_balance()) {
bool first = true;
const balance_t& bal(balance.as_balance());
foreach (const balance_t::amounts_map::value_type& pair, bal.amounts) {
if (first) {
null_xact->amount = pair.second.negate();
first = false;
} else {
add_xact(new xact_t(null_xact->account, pair.second.negate(),
ITEM_GENERATED));
}
}
}
else if (balance.is_amount()) {
null_xact->amount = balance.as_amount().negate();
null_xact->add_flags(XACT_CALCULATED);
}
else if (! balance.is_null() && ! balance.is_realzero()) {
throw_(balance_error, "Entry does not balance");
}
balance = NULL_VALUE;
}
else if (balance.is_balance() &&
balance.as_balance().amounts.size() == 2) {
// When an entry involves two different commodities (regardless of how
// many xacts there are) determine the conversion ratio by dividing
// the total value of one commodity by the total value of the other. This
// establishes the per-unit cost for this xact for both
// commodities.
const balance_t& bal(balance.as_balance());
balance_t::amounts_map::const_iterator a = bal.amounts.begin();
const amount_t& x((*a++).second);
const amount_t& y((*a++).second);
if (! y.is_realzero()) {
amount_t per_unit_cost = (x / y).abs();
commodity_t& comm(x.commodity());
foreach (xact_t * xact, xacts) {
const amount_t& amt(xact->amount);
if (! (xact->cost || ! xact->must_balance() ||
amt.commodity() == comm)) {
balance -= amt;
xact->cost = per_unit_cost * amt;
balance += *xact->cost;
}
}
}
DEBUG("entry.finalize", "resolved balance = " << balance);
}
// Now that the xact list has its final form, calculate the balance
// once more in terms of total cost, accounting for any possible gain/loss
// amounts.
foreach (xact_t * xact, xacts) {
if (xact->cost) {
if (xact->amount.commodity() == xact->cost->commodity())
throw_(balance_error, "Transaction's cost must be of a different commodity");
commodity_t::cost_breakdown_t breakdown =
commodity_t::exchange(xact->amount, *xact->cost);
if (xact->amount.is_annotated())
add_or_set_value(balance, breakdown.basis_cost - breakdown.final_cost);
else
xact->amount = breakdown.amount;
}
}
DEBUG("entry.finalize", "final balance = " << balance);
if (! balance.is_null() && ! balance.is_zero()) {
#if 0
add_error_context(entry_context(*this));
#endif
add_error_context("Unbalanced remainder is: ");
add_error_context(value_context(balance.unrounded()));
throw_(balance_error, "Entry does not balance");
}
// Add the final calculated totals each to their related account
if (dynamic_cast<entry_t *>(this)) {
bool all_null = true;
foreach (xact_t * xact, xacts) {
if (! xact->amount.is_null()) {
all_null = false;
// jww (2008-08-09): For now, this feature only works for
// non-specific commodities.
add_or_set_value(xact->account->xdata().value, xact->amount);
DEBUG("entry.finalize.totals",
"Total for " << xact->account->fullname() << " + "
<< xact->amount.strip_annotations() << ": "
<< xact->account->xdata().value.strip_annotations());
}
}
if (all_null)
return false; // ignore this entry completely
}
return true;
}
entry_t::entry_t(const entry_t& e)
: entry_base_t(e), code(e.code), payee(e.payee)
{
TRACE_CTOR(entry_t, "copy");
#if 0
foreach (xact_t * xact, xacts)
xact->entry = this;
#endif
}
void entry_t::add_xact(xact_t * xact)
{
xact->entry = this;
entry_base_t::add_xact(xact);
}
namespace {
value_t get_code(entry_t& entry) {
if (entry.code)
return string_value(*entry.code);
else
return string_value(empty_string);
}
value_t get_payee(entry_t& entry) {
return string_value(entry.payee);
}
template <value_t (*Func)(entry_t&)>
value_t get_wrapper(call_scope_t& scope) {
return (*Func)(find_scope<entry_t>(scope));
}
}
expr_t::ptr_op_t entry_t::lookup(const string& name)
{
switch (name[0]) {
case 'c':
if (name == "code")
return WRAP_FUNCTOR(get_wrapper<&get_code>);
break;
case 'p':
if (name[1] == '\0' || name == "payee")
return WRAP_FUNCTOR(get_wrapper<&get_payee>);
break;
}
return item_t::lookup(name);
}
bool entry_t::valid() const
{
if (! _date || ! journal) {
DEBUG("ledger.validate", "entry_t: ! _date || ! journal");
return false;
}
foreach (xact_t * xact, xacts)
if (xact->entry != this || ! xact->valid()) {
DEBUG("ledger.validate", "entry_t: xact not valid");
return false;
}
return true;
}
#if 0
void entry_context::describe(std::ostream& out) const throw()
{
if (! desc.empty())
out << desc << std::endl;
print_entry(out, entry, " ");
}
#endif
void auto_entry_t::extend_entry(entry_base_t& entry, bool post)
{
xacts_list initial_xacts(entry.xacts.begin(),
entry.xacts.end());
foreach (xact_t * initial_xact, initial_xacts) {
if (predicate(*initial_xact)) {
foreach (xact_t * xact, xacts) {
amount_t amt;
assert(xact->amount);
if (! xact->amount.commodity()) {
if (! post)
continue;
assert(initial_xact->amount);
amt = initial_xact->amount * xact->amount;
} else {
if (post)
continue;
amt = xact->amount;
}
IF_DEBUG("entry.extend") {
DEBUG("entry.extend",
"Initial xact on line " << initial_xact->beg_line << ": "
<< "amount " << initial_xact->amount << " (precision "
<< initial_xact->amount.precision() << ")");
if (initial_xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
DEBUG("entry.extend",
"Transaction on line " << xact->beg_line << ": "
<< "amount " << xact->amount << ", amt " << amt
<< " (precision " << xact->amount.precision()
<< " != " << amt.precision() << ")");
if (xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
if (amt.keep_precision())
DEBUG("entry.extend", " amt precision is kept");
}
account_t * account = xact->account;
string fullname = account->fullname();
assert(! fullname.empty());
if (fullname == "$account" || fullname == "@account")
account = initial_xact->account;
// Copy over details so that the resulting xact is a mirror of
// the automated entry's one.
xact_t * new_xact = new xact_t(account, amt);
new_xact->copy_details(*xact);
new_xact->add_flags(XACT_AUTO);
entry.add_xact(new_xact);
}
}
}
}
void extend_entry_base(journal_t * journal, entry_base_t& base, bool post)
{
foreach (auto_entry_t * entry, journal->auto_entries)
entry->extend_entry(base, post);
}
} // namespace ledger
<commit_msg>Fixed some entry balancing problems relating to the new rational code.<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "entry.h"
#include "journal.h"
#include "format.h"
#include "session.h"
#include "report.h"
namespace ledger {
entry_base_t::entry_base_t(const entry_base_t& e)
: item_t(), journal(NULL)
{
TRACE_CTOR(entry_base_t, "copy");
#if 0
xacts.insert(xacts.end(), e.xacts.begin(), e.xacts.end());
#endif
}
entry_base_t::~entry_base_t()
{
TRACE_DTOR(entry_base_t);
foreach (xact_t * xact, xacts) {
// If the transaction is a temporary, it will be destructed when the
// temporary is. If it's from a binary cache, we can safely destruct it
// but its memory will be deallocated with the cache.
if (! xact->has_flags(ITEM_TEMP)) {
if (! xact->has_flags(ITEM_IN_CACHE))
checked_delete(xact);
else
xact->~xact_t();
}
}
}
item_t::state_t entry_base_t::state() const
{
bool first = true;
state_t result = UNCLEARED;
foreach (xact_t * xact, xacts) {
if ((result == UNCLEARED && xact->_state != UNCLEARED) ||
(result == PENDING && xact->_state == CLEARED))
result = xact->_state;
}
return result;
}
void entry_base_t::add_xact(xact_t * xact)
{
xacts.push_back(xact);
}
bool entry_base_t::remove_xact(xact_t * xact)
{
xacts.remove(xact);
return true;
}
bool entry_base_t::finalize()
{
// Scan through and compute the total balance for the entry. This is used
// for auto-calculating the value of entries with no cost, and the per-unit
// price of unpriced commodities.
// (let ((balance 0)
// null-xact)
value_t balance;
xact_t * null_xact = NULL;
foreach (xact_t * xact, xacts) {
if (xact->must_balance()) {
amount_t& p(xact->cost ? *xact->cost : xact->amount);
DEBUG("entry.finalize", "xact must balance = " << p);
if (! p.is_null()) {
if (p.keep_precision()) {
// If the amount was a cost, it very likely has the "keep_precision"
// flag set, meaning commodity display precision is ignored when
// displaying the amount. We never want this set for the balance,
// so we must clear the flag in a temporary to avoid it propagating
// into the balance.
add_or_set_value(balance, p.rounded());
} else {
add_or_set_value(balance, p);
}
} else {
if (null_xact)
throw_(std::logic_error,
"Only one xact with null amount allowed per entry");
else
null_xact = xact;
}
}
}
assert(balance.valid());
DEBUG("entry.finalize", "initial balance = " << balance);
// If there is only one xact, balance against the default account if
// one has been set.
if (journal && journal->basket && xacts.size() == 1 && ! balance.is_null()) {
// jww (2008-07-24): Need to make the rest of the code aware of what to do
// when it sees a generated xact.
null_xact = new xact_t(journal->basket, ITEM_GENERATED);
null_xact->_state = (*xacts.begin())->_state;
add_xact(null_xact);
}
if (null_xact != NULL) {
// If one xact has no value at all, its value will become the
// inverse of the rest. If multiple commodities are involved, multiple
// xacts are generated to balance them all.
if (balance.is_balance()) {
bool first = true;
const balance_t& bal(balance.as_balance());
foreach (const balance_t::amounts_map::value_type& pair, bal.amounts) {
if (first) {
null_xact->amount = pair.second.negate();
first = false;
} else {
add_xact(new xact_t(null_xact->account, pair.second.negate(),
ITEM_GENERATED));
}
}
}
else if (balance.is_amount()) {
null_xact->amount = balance.as_amount().negate();
null_xact->add_flags(XACT_CALCULATED);
}
else if (! balance.is_null() && ! balance.is_realzero()) {
throw_(balance_error, "Entry does not balance");
}
balance = NULL_VALUE;
}
else if (balance.is_balance() &&
balance.as_balance().amounts.size() == 2) {
// When an entry involves two different commodities (regardless of how
// many xacts there are) determine the conversion ratio by dividing
// the total value of one commodity by the total value of the other. This
// establishes the per-unit cost for this xact for both
// commodities.
const balance_t& bal(balance.as_balance());
balance_t::amounts_map::const_iterator a = bal.amounts.begin();
const amount_t& x((*a++).second);
const amount_t& y((*a++).second);
if (! y.is_realzero()) {
amount_t per_unit_cost = (x / y).abs();
commodity_t& comm(x.commodity());
foreach (xact_t * xact, xacts) {
const amount_t& amt(xact->amount);
if (! (xact->cost || ! xact->must_balance() ||
amt.commodity() == comm)) {
balance -= amt;
xact->cost = per_unit_cost * amt;
balance += *xact->cost;
}
}
}
DEBUG("entry.finalize", "resolved balance = " << balance);
}
// Now that the xact list has its final form, calculate the balance
// once more in terms of total cost, accounting for any possible gain/loss
// amounts.
foreach (xact_t * xact, xacts) {
if (xact->cost) {
if (xact->amount.commodity() == xact->cost->commodity())
throw_(balance_error, "Transaction's cost must be of a different commodity");
commodity_t::cost_breakdown_t breakdown =
commodity_t::exchange(xact->amount, *xact->cost);
if (xact->amount.is_annotated())
add_or_set_value(balance, (breakdown.basis_cost -
breakdown.final_cost).rounded());
else
xact->amount = breakdown.amount;
}
}
DEBUG("entry.finalize", "final balance = " << balance);
if (! balance.is_null() && ! balance.is_zero()) {
#if 0
add_error_context(entry_context(*this));
#endif
add_error_context("Unbalanced remainder is: ");
add_error_context(value_context(balance));
throw_(balance_error, "Entry does not balance");
}
// Add the final calculated totals each to their related account
if (dynamic_cast<entry_t *>(this)) {
bool all_null = true;
foreach (xact_t * xact, xacts) {
if (! xact->amount.is_null()) {
all_null = false;
// jww (2008-08-09): For now, this feature only works for
// non-specific commodities.
add_or_set_value(xact->account->xdata().value, xact->amount);
DEBUG("entry.finalize.totals",
"Total for " << xact->account->fullname() << " + "
<< xact->amount.strip_annotations() << ": "
<< xact->account->xdata().value.strip_annotations());
}
}
if (all_null)
return false; // ignore this entry completely
}
return true;
}
entry_t::entry_t(const entry_t& e)
: entry_base_t(e), code(e.code), payee(e.payee)
{
TRACE_CTOR(entry_t, "copy");
#if 0
foreach (xact_t * xact, xacts)
xact->entry = this;
#endif
}
void entry_t::add_xact(xact_t * xact)
{
xact->entry = this;
entry_base_t::add_xact(xact);
}
namespace {
value_t get_code(entry_t& entry) {
if (entry.code)
return string_value(*entry.code);
else
return string_value(empty_string);
}
value_t get_payee(entry_t& entry) {
return string_value(entry.payee);
}
template <value_t (*Func)(entry_t&)>
value_t get_wrapper(call_scope_t& scope) {
return (*Func)(find_scope<entry_t>(scope));
}
}
expr_t::ptr_op_t entry_t::lookup(const string& name)
{
switch (name[0]) {
case 'c':
if (name == "code")
return WRAP_FUNCTOR(get_wrapper<&get_code>);
break;
case 'p':
if (name[1] == '\0' || name == "payee")
return WRAP_FUNCTOR(get_wrapper<&get_payee>);
break;
}
return item_t::lookup(name);
}
bool entry_t::valid() const
{
if (! _date || ! journal) {
DEBUG("ledger.validate", "entry_t: ! _date || ! journal");
return false;
}
foreach (xact_t * xact, xacts)
if (xact->entry != this || ! xact->valid()) {
DEBUG("ledger.validate", "entry_t: xact not valid");
return false;
}
return true;
}
#if 0
void entry_context::describe(std::ostream& out) const throw()
{
if (! desc.empty())
out << desc << std::endl;
print_entry(out, entry, " ");
}
#endif
void auto_entry_t::extend_entry(entry_base_t& entry, bool post)
{
xacts_list initial_xacts(entry.xacts.begin(),
entry.xacts.end());
foreach (xact_t * initial_xact, initial_xacts) {
if (predicate(*initial_xact)) {
foreach (xact_t * xact, xacts) {
amount_t amt;
assert(xact->amount);
if (! xact->amount.commodity()) {
if (! post)
continue;
assert(initial_xact->amount);
amt = initial_xact->amount * xact->amount;
} else {
if (post)
continue;
amt = xact->amount;
}
IF_DEBUG("entry.extend") {
DEBUG("entry.extend",
"Initial xact on line " << initial_xact->beg_line << ": "
<< "amount " << initial_xact->amount << " (precision "
<< initial_xact->amount.precision() << ")");
if (initial_xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
DEBUG("entry.extend",
"Transaction on line " << xact->beg_line << ": "
<< "amount " << xact->amount << ", amt " << amt
<< " (precision " << xact->amount.precision()
<< " != " << amt.precision() << ")");
if (xact->amount.keep_precision())
DEBUG("entry.extend", " precision is kept");
if (amt.keep_precision())
DEBUG("entry.extend", " amt precision is kept");
}
account_t * account = xact->account;
string fullname = account->fullname();
assert(! fullname.empty());
if (fullname == "$account" || fullname == "@account")
account = initial_xact->account;
// Copy over details so that the resulting xact is a mirror of
// the automated entry's one.
xact_t * new_xact = new xact_t(account, amt);
new_xact->copy_details(*xact);
new_xact->add_flags(XACT_AUTO);
entry.add_xact(new_xact);
}
}
}
}
void extend_entry_base(journal_t * journal, entry_base_t& base, bool post)
{
foreach (auto_entry_t * entry, journal->auto_entries)
entry->extend_entry(base, post);
}
} // namespace ledger
<|endoftext|> |
<commit_before>#include "Optimiser.h"
#include "Hildreth.h"
using namespace Moses;
using namespace std;
namespace Mira {
void MiraOptimiser::updateWeights(ScoreComponentCollection& currWeights,
const vector< vector<ScoreComponentCollection> >& featureValues,
const vector< vector<float> >& losses,
const ScoreComponentCollection& oracleFeatureValues) {
if (m_hildreth) {
size_t numberOfViolatedConstraints = 0;
vector< ScoreComponentCollection> featureValueDiffs;
vector< float> lossMarginDistances;
for (size_t i = 0; i < featureValues.size(); ++i) {
for (size_t j = 0; j < featureValues[i].size(); ++j) {
// check if optimisation criterion is violated for one hypothesis and the oracle
// h(e*) >= h(e_ij) + loss(e_ij)
// h(e*) - h(e_ij) >= loss(e_ij)
float modelScoreDiff = featureValues[i][j].InnerProduct(currWeights);
if (modelScoreDiff < losses[i][j]) {
cerr << "Constraint violated: " << modelScoreDiff << " < " << losses[i][j] << endl;
++numberOfViolatedConstraints;
}
else {
cerr << "Constraint satisfied: " << modelScoreDiff << " >= " << losses[i][j] << endl;
}
// Objective: 1/2 * ||w' - w||^2 + C * SUM_1_m[ max_1_n (l_ij - Delta_h_ij.w')]
// To add a constraint for the optimiser for each sentence i and hypothesis j, we need:
// 1. vector Delta_h_ij of the feature value differences (oracle - hypothesis)
// 2. loss_ij - difference in model scores (Delta_h_ij.w') (oracle - hypothesis)
ScoreComponentCollection featureValueDiff = oracleFeatureValues;
featureValueDiff.MinusEquals(featureValues[i][j]);
featureValueDiffs.push_back(featureValueDiff);
float lossMarginDistance = losses[i][j] - modelScoreDiff;
lossMarginDistances.push_back(lossMarginDistance);
// TODO: should we only pass violated constraints to the optimiser?
}
}
if (numberOfViolatedConstraints > 0) {
// run optimisation
cerr << "Number of violated constraints: " << numberOfViolatedConstraints << endl;
// TODO: slack
// compute deltas for all given constraints
vector< float> deltas = Hildreth::optimise(featureValueDiffs, lossMarginDistances);
// Update the weight vector according to the deltas and the feature value differences
// * w' = w' + delta * Dh_ij ---> w' = w' + delta * (h(e*) - h(e_ij))
for (size_t k = 0; k < featureValueDiffs.size(); ++k) {
// scale feature value differences with delta
featureValueDiffs[k].MultiplyEquals(deltas[k]);
// apply update to weight vector
currWeights.PlusEquals(featureValueDiffs[k]);
}
}
else {
cout << "No constraint violated for this batch" << endl;
}
}
else {
// SMO:
for (size_t i = 0; i < featureValues.size(); ++i) {
// initialise alphas for each source (alpha for oracle translation = C, all other alphas = 0)
vector< float> alphas(featureValues[i].size());
for (size_t j = 0; j < featureValues[i].size(); ++j) {
if (j == m_n) { // TODO: use oracle index
// oracle
alphas[j] = m_c;
//std::cout << "alpha " << j << ": " << alphas[j] << endl;
}
else {
alphas[j] = 0;
//std::cout << "alpha " << j << ": " << alphas[j] << endl;
}
}
// consider all pairs of hypotheses
size_t pairs = 0;
for (size_t j = 0; j < featureValues[i].size(); ++j) {
for (size_t k = 0; k < featureValues[i].size(); ++k) {
if (j <= k) {
++pairs;
// Compute delta:
cout << "\nComparing pair" << j << "," << k << endl;
ScoreComponentCollection featureValueDiffs;
float delta = computeDelta(currWeights, featureValues[i], j, k, losses[i], alphas, featureValueDiffs);
// update weight vector:
if (delta != 0) {
update(currWeights, featureValueDiffs, delta);
}
}
}
}
cout << "number of pairs: " << pairs << endl;
}
}
}
/*
* Compute delta for weight update.
* As part of this compute feature value differences
* Dh_ij - Dh_ij' ---> h(e_ij') - h(e_ij)) --> h(hope) - h(fear)
* which are used in the delta term and in the weight update term.
*/
float MiraOptimiser::computeDelta(ScoreComponentCollection& currWeights,
const vector< ScoreComponentCollection>& featureValues,
const size_t indexHope,
const size_t indexFear,
const vector< float>& losses,
vector< float>& alphas,
ScoreComponentCollection& featureValueDiffs) {
const ScoreComponentCollection featureValuesHope = featureValues[indexHope]; // hypothesis j'
const ScoreComponentCollection featureValuesFear = featureValues[indexFear]; // hypothesis j
// compute delta
float delta = 0.0;
float diffOfModelScores = 0.0; // (Dh_ij - Dh_ij') * w' ---> (h(e_ij') - h(e_ij))) * w' (inner product)
float squaredNorm = 0.0; // ||Dh_ij - Dh_ij'||^2 ---> sum over squares of elements of h(e_ij') - h(e_ij)
featureValueDiffs = featureValuesHope;
featureValueDiffs.MinusEquals(featureValuesFear);
cout << "feature value diffs: " << featureValueDiffs << endl;
squaredNorm = featureValueDiffs.InnerProduct(featureValueDiffs);
diffOfModelScores = featureValueDiffs.InnerProduct(currWeights);
if (squaredNorm == 0.0) {
delta = 0.0;
}
else {
// loss difference used to compute delta: (l_ij - l_ij') ---> B(e_ij') - B(e_ij)
// TODO: simplify and use BLEU scores of hypotheses directly?
float lossDiff = losses[indexFear] - losses[indexHope];
delta = (lossDiff - diffOfModelScores) / squaredNorm;
cout << "delta: " << delta << endl;
cout << "loss diff - model diff: " << lossDiff << " - " << diffOfModelScores << endl;
// clipping
// fear translation: e_ij --> alpha_ij = alpha_ij + delta
// hope translation: e_ij' --> alpha_ij' = alpha_ij' - delta
// clipping interval: [-alpha_ij, alpha_ij']
// clip delta
cout << "Interval [" << (-1 * alphas[indexFear]) << "," << alphas[indexHope] << "]" << endl;
if (delta > alphas[indexHope]) {
//cout << "clipping " << delta << " to " << alphas[indexHope] << endl;
delta = alphas[indexHope];
}
else if (delta < (-1 * alphas[indexFear])) {
//cout << "clipping " << delta << " to " << (-1 * alphas[indexFear]) << endl;
delta = (-1 * alphas[indexFear]);
}
// update alphas
alphas[indexHope] -= delta;
alphas[indexFear] += delta;
//cout << "alpha[" << indexHope << "] = " << alphas[indexHope] << endl;
//cout << "alpha[" << indexFear << "] = " << alphas[indexFear] << endl;
}
return delta;
}
/*
* Update the weight vector according to delta and the feature value difference
* w' = w' + delta * (Dh_ij - Dh_ij') ---> w' = w' + delta * (h(e_ij') - h(e_ij)))
*/
void MiraOptimiser::update(ScoreComponentCollection& currWeights, ScoreComponentCollection& featureValueDiffs, const float delta) {
featureValueDiffs.MultiplyEquals(delta);
currWeights.PlusEquals(featureValueDiffs);
}
}
<commit_msg>fix hildreth<commit_after>#include "Optimiser.h"
#include "Hildreth.h"
using namespace Moses;
using namespace std;
namespace Mira {
void MiraOptimiser::updateWeights(ScoreComponentCollection& currWeights,
const vector< vector<ScoreComponentCollection> >& featureValues,
const vector< vector<float> >& losses,
const ScoreComponentCollection& oracleFeatureValues) {
if (m_hildreth) {
size_t numberOfViolatedConstraints = 0;
vector< ScoreComponentCollection> featureValueDiffs;
vector< float> lossMarginDistances;
for (size_t i = 0; i < featureValues.size(); ++i) {
for (size_t j = 0; j < featureValues[i].size(); ++j) {
// check if optimisation criterion is violated for one hypothesis and the oracle
// h(e*) >= h(e_ij) + loss(e_ij)
// h(e*) - h(e_ij) >= loss(e_ij)
ScoreComponentCollection featureValueDiff = oracleFeatureValues;
featureValueDiff.MinusEquals(featureValues[i][j]);
float modelScoreDiff = featureValueDiff.InnerProduct(currWeights);
if (modelScoreDiff < losses[i][j]) {
cerr << "Constraint violated: " << modelScoreDiff << " (modelScoreDiff) < " << losses[i][j] << " (loss)" << endl;
++numberOfViolatedConstraints;
}
else {
cerr << "Constraint satisfied: " << modelScoreDiff << " (modelScoreDiff) >= " << losses[i][j] << " (loss)" << endl;
}
// Objective: 1/2 * ||w' - w||^2 + C * SUM_1_m[ max_1_n (l_ij - Delta_h_ij.w')]
// To add a constraint for the optimiser for each sentence i and hypothesis j, we need:
// 1. vector Delta_h_ij of the feature value differences (oracle - hypothesis)
// 2. loss_ij - difference in model scores (Delta_h_ij.w') (oracle - hypothesis)
featureValueDiffs.push_back(featureValueDiff);
float lossMarginDistance = losses[i][j] - modelScoreDiff;
lossMarginDistances.push_back(lossMarginDistance);
}
}
if (numberOfViolatedConstraints > 0) {
// run optimisation
cerr << "Number of violated constraints: " << numberOfViolatedConstraints << endl;
// TODO: slack? margin scale factor?
// compute deltas for all given constraints
vector< float> deltas = Hildreth::optimise(featureValueDiffs, lossMarginDistances);
// Update the weight vector according to the deltas and the feature value differences
// * w' = w' + delta * Dh_ij ---> w' = w' + delta * (h(e*) - h(e_ij))
for (size_t k = 0; k < featureValueDiffs.size(); ++k) {
// scale feature value differences with delta
featureValueDiffs[k].MultiplyEquals(deltas[k]);
// apply update to weight vector
currWeights.PlusEquals(featureValueDiffs[k]);
}
}
else {
cout << "No constraint violated for this batch" << endl;
}
}
else {
// SMO:
for (size_t i = 0; i < featureValues.size(); ++i) {
// initialise alphas for each source (alpha for oracle translation = C, all other alphas = 0)
vector< float> alphas(featureValues[i].size());
for (size_t j = 0; j < featureValues[i].size(); ++j) {
if (j == m_n) { // TODO: use oracle index
// oracle
alphas[j] = m_c;
//std::cout << "alpha " << j << ": " << alphas[j] << endl;
}
else {
alphas[j] = 0;
//std::cout << "alpha " << j << ": " << alphas[j] << endl;
}
}
// consider all pairs of hypotheses
size_t pairs = 0;
for (size_t j = 0; j < featureValues[i].size(); ++j) {
for (size_t k = 0; k < featureValues[i].size(); ++k) {
if (j <= k) {
++pairs;
// Compute delta:
cout << "\nComparing pair" << j << "," << k << endl;
ScoreComponentCollection featureValueDiffs;
float delta = computeDelta(currWeights, featureValues[i], j, k, losses[i], alphas, featureValueDiffs);
// update weight vector:
if (delta != 0) {
update(currWeights, featureValueDiffs, delta);
}
}
}
}
cout << "number of pairs: " << pairs << endl;
}
}
}
/*
* Compute delta for weight update.
* As part of this compute feature value differences
* Dh_ij - Dh_ij' ---> h(e_ij') - h(e_ij)) --> h(hope) - h(fear)
* which are used in the delta term and in the weight update term.
*/
float MiraOptimiser::computeDelta(ScoreComponentCollection& currWeights,
const vector< ScoreComponentCollection>& featureValues,
const size_t indexHope,
const size_t indexFear,
const vector< float>& losses,
vector< float>& alphas,
ScoreComponentCollection& featureValueDiffs) {
const ScoreComponentCollection featureValuesHope = featureValues[indexHope]; // hypothesis j'
const ScoreComponentCollection featureValuesFear = featureValues[indexFear]; // hypothesis j
// compute delta
float delta = 0.0;
float diffOfModelScores = 0.0; // (Dh_ij - Dh_ij') * w' ---> (h(e_ij') - h(e_ij))) * w' (inner product)
float squaredNorm = 0.0; // ||Dh_ij - Dh_ij'||^2 ---> sum over squares of elements of h(e_ij') - h(e_ij)
featureValueDiffs = featureValuesHope;
featureValueDiffs.MinusEquals(featureValuesFear);
cout << "feature value diffs: " << featureValueDiffs << endl;
squaredNorm = featureValueDiffs.InnerProduct(featureValueDiffs);
diffOfModelScores = featureValueDiffs.InnerProduct(currWeights);
if (squaredNorm == 0.0) {
delta = 0.0;
}
else {
// loss difference used to compute delta: (l_ij - l_ij') ---> B(e_ij') - B(e_ij)
// TODO: simplify and use BLEU scores of hypotheses directly?
float lossDiff = losses[indexFear] - losses[indexHope];
delta = (lossDiff - diffOfModelScores) / squaredNorm;
cout << "delta: " << delta << endl;
cout << "loss diff - model diff: " << lossDiff << " - " << diffOfModelScores << endl;
// clipping
// fear translation: e_ij --> alpha_ij = alpha_ij + delta
// hope translation: e_ij' --> alpha_ij' = alpha_ij' - delta
// clipping interval: [-alpha_ij, alpha_ij']
// clip delta
cout << "Interval [" << (-1 * alphas[indexFear]) << "," << alphas[indexHope] << "]" << endl;
if (delta > alphas[indexHope]) {
//cout << "clipping " << delta << " to " << alphas[indexHope] << endl;
delta = alphas[indexHope];
}
else if (delta < (-1 * alphas[indexFear])) {
//cout << "clipping " << delta << " to " << (-1 * alphas[indexFear]) << endl;
delta = (-1 * alphas[indexFear]);
}
// update alphas
alphas[indexHope] -= delta;
alphas[indexFear] += delta;
//cout << "alpha[" << indexHope << "] = " << alphas[indexHope] << endl;
//cout << "alpha[" << indexFear << "] = " << alphas[indexFear] << endl;
}
return delta;
}
/*
* Update the weight vector according to delta and the feature value difference
* w' = w' + delta * (Dh_ij - Dh_ij') ---> w' = w' + delta * (h(e_ij') - h(e_ij)))
*/
void MiraOptimiser::update(ScoreComponentCollection& currWeights, ScoreComponentCollection& featureValueDiffs, const float delta) {
featureValueDiffs.MultiplyEquals(delta);
currWeights.PlusEquals(featureValueDiffs);
}
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include <map>
#include <stdlib.h> /* srand, rand */
#include "misc.h"
#include "collision.h"
#include "feat.h"
// Features ------------------------------------------------------------------
Feat::Feat() {
Count = 0;
Categories = 0;
MinDec = -90.0;
MaxDec = 90.0;
MinRa = 0.0;
MaxRa = 360.0;
}
int Feat::id(str s) const {
for (int i=0; i<Categories; i++) if (kind[i]==s) return i;
std::cout << "ERROR in Feat id(), string not found in kind" << std::endl;
return -1;
}
void Feat::init_ids() {
for (int i=0; i<Categories; i++) ids[kind[i]] = i;
}
void Feat::init_ids_types() {
for (int i=0; i<Categories; i++) ids_types[kind[i]] = i;
}
List Feat::init_ids_list(str l[], int size) const {
List L;
L.resize(size);
for (int i=0; i<size; i++) L[i] = ids.at(l[i]);
return L;
}
void Feat::init_types() {
for (int i=0; i<type.size(); i++) if (!isfound(type[i],types)) types.push_back(type[i]);
}
void Feat::init_no_ss_sf() {
//str noA[] = {"LRG","FakeLRG","ELG","QSOLy-a","QSOTracer","FakeQSO"};
for(int i=0;i<kind.size()-2;++i)no_ss_sf.push_back(i);
//no_ss_sf = init_ids_list(noA,6);
}
void Feat::init_ss_sf() {
str A[] = {"SS","SF"};
ss_sf = init_ids_list(A,2);
}
bool Feat::iftype(int kind, str type) const {
return ids_types.at(type)==type[kind];
}
void Feat::readInputFile(const char file[]) {
const int Mc = 512; // Max chars per line
char delimiter = ' ';
std::ifstream fIn;
fIn.open(file); // open a file
if (!fIn.good()) myexit(1); // Not found
while (!fIn.eof()) {
char buf[Mc];
fIn.getline(buf,Mc);
int n = 0; // a for-loop index
Slist tok = s2vec(buf,delimiter);
if (2<=tok.size()) {
if (tok[0]=="galFile") galFile = tok[1];
if (tok[0]=="tileFile") tileFile= tok[1];
if (tok[0]=="fibFile") fibFile= tok[1];
if (tok[0]=="surveyFile") surveyFile= tok[1];
if (tok[0]=="outDir") outDir= tok[1];
if (tok[0]=="PrintAscii") PrintAscii= s2b(tok[1]);
if (tok[0]=="PrintFits") PrintFits= s2b(tok[1]);
if (tok[0]=="MTLfile") MTLfile=tok[1];
if (tok[0]=="Targfile") Targfile=tok[1];
if (tok[0]=="SStarsfile")SStarsfile=tok[1];
if (tok[0]=="SkyFfile") SkyFfile=tok[1];
if (tok[0]=="Secretfile") Secretfile=tok[1];
if (tok[0]=="diagnose") diagnose=s2b(tok[1]);
if (tok[0]=="kind") {
Categories = tok.size()-1;
for (int i=0; i<Categories; i++) kind.push_back(tok[i+1]);
init_ids();
init_ss_sf();
init_no_ss_sf();
}
if (tok[0]=="type") {
Categories = tok.size()-1;
for (int i=0; i<Categories; i++) type.push_back(tok[i+1]);
init_types();
init_ids_types();
}
if (tok[0]=="prio") for (int i=0; i<Categories; i++){prio.push_back(s2i(tok[i+1]));}
if (tok[0]=="priopost") for (int i=0; i<Categories; i++) priopost.push_back(s2i(tok[i+1]));
if (tok[0]=="goal") for (int i=0; i<Categories; i++) goal.push_back(s2i(tok[i+1]));
if (tok[0]=="goalpost") for (int i=0; i<Categories; i++) goalpost.push_back(s2i(tok[i+1]));
if (tok[0]=="lastpass") for(int i=0; i<Categories;i++)lastpass.push_back(s2i(tok[i+1]));
if (tok[0]=="SS") for(int i=0; i<Categories;i++)SS.push_back(s2i(tok[i+1]));
if (tok[0]=="SF") for(int i=0; i<Categories;i++)SF.push_back(s2i(tok[i+1]));
if (tok[0]=="pass_intervals"){
int n_intervals=tok.size()-1;
for (int i=0;i<n_intervals;++i) pass_intervals.push_back(s2i(tok[i+1]));
}
if (tok[0]=="InterPlate") InterPlate = s2i(tok[1]);
if (tok[0]=="Randomize") Randomize = s2b(tok[1]);
if (tok[0]=="Pacman") Pacman = s2b(tok[1]);
if (tok[0]=="Npass") Npass = s2i(tok[1]);
if (tok[0]=="MaxSS") MaxSS = s2i(tok[1]);
if (tok[0]=="MaxSF") MaxSF = s2i(tok[1]);
if (tok[0]=="PlateRadius") PlateRadius = s2d(tok[1]);
if (tok[0]=="Analysis") Analysis = s2i(tok[1]);
if (tok[0]=="InfDens") InfDens = s2b(tok[1]);
if (tok[0]=="TotalArea") TotalArea = s2d(tok[1]);
if (tok[0]=="invFibArea") invFibArea = s2d(tok[1]);
if (tok[0]=="moduloGal") moduloGal = s2i(tok[1]);
if (tok[0]=="moduloFiber") moduloFiber = s2i(tok[1]);
if (tok[0]=="Collision") Collision = s2b(tok[1]);
if (tok[0]=="Exact") Exact = s2b(tok[1]);
if (tok[0]=="AvCollide") AvCollide = s2d(tok[1]);
if (tok[0]=="Collide") Collide = s2d(tok[1]);
if (tok[0]=="NoCollide") NoCollide = s2d(tok[1]);
if (tok[0]=="PatrolRad") PatrolRad = s2d(tok[1]);
if (tok[0]=="NeighborRad") NeighborRad = s2d(tok[1]);
if (tok[0]=="PlotObsTime") PlotObsTime = s2b(tok[1]);
if (tok[0]=="PlotHistLya") PlotHistLya = s2b(tok[1]);
if (tok[0]=="PlotDistLya") PlotDistLya = s2b(tok[1]);
if (tok[0]=="PlotFreeFibHist") PlotFreeFibHist = s2b(tok[1]);
if (tok[0]=="PlotFreeFibTime") PlotFreeFibTime = s2b(tok[1]);
if (tok[0]=="PlotSeenDens") PlotSeenDens = s2b(tok[1]);
if (tok[0]=="Verif") Verif = s2b(tok[1]);
if (tok[0]=="Ascii") Ascii = s2b(tok[1]);
if (tok[0]=="PrintGalObs") PrintGalObs = s2i(tok[1]);
if (tok[0]=="BrightTime") BrightTime = s2b(tok[1]);
if (tok[0]=="MaxDec") MaxDec = s2d(tok[1]);
if (tok[0]=="MinDec") MinDec = s2d(tok[1]);
if (tok[0]=="MaxRa") MaxRa = s2d(tok[1]);
if (tok[0]=="MinRa") MinRa = s2d(tok[1]);
}
}
fIn.close();
}
<commit_msg>remove prio and priopost<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include <map>
#include <stdlib.h> /* srand, rand */
#include "misc.h"
#include "collision.h"
#include "feat.h"
// Features ------------------------------------------------------------------
Feat::Feat() {
Count = 0;
Categories = 0;
MinDec = -90.0;
MaxDec = 90.0;
MinRa = 0.0;
MaxRa = 360.0;
}
int Feat::id(str s) const {
for (int i=0; i<Categories; i++) if (kind[i]==s) return i;
std::cout << "ERROR in Feat id(), string not found in kind" << std::endl;
return -1;
}
void Feat::init_ids() {
for (int i=0; i<Categories; i++) ids[kind[i]] = i;
}
void Feat::init_ids_types() {
for (int i=0; i<Categories; i++) ids_types[kind[i]] = i;
}
List Feat::init_ids_list(str l[], int size) const {
List L;
L.resize(size);
for (int i=0; i<size; i++) L[i] = ids.at(l[i]);
return L;
}
void Feat::init_types() {
for (int i=0; i<type.size(); i++) if (!isfound(type[i],types)) types.push_back(type[i]);
}
void Feat::init_no_ss_sf() {
//str noA[] = {"LRG","FakeLRG","ELG","QSOLy-a","QSOTracer","FakeQSO"};
for(int i=0;i<kind.size()-2;++i)no_ss_sf.push_back(i);
//no_ss_sf = init_ids_list(noA,6);
}
void Feat::init_ss_sf() {
str A[] = {"SS","SF"};
ss_sf = init_ids_list(A,2);
}
bool Feat::iftype(int kind, str type) const {
return ids_types.at(type)==type[kind];
}
void Feat::readInputFile(const char file[]) {
const int Mc = 512; // Max chars per line
char delimiter = ' ';
std::ifstream fIn;
fIn.open(file); // open a file
if (!fIn.good()) myexit(1); // Not found
while (!fIn.eof()) {
char buf[Mc];
fIn.getline(buf,Mc);
int n = 0; // a for-loop index
Slist tok = s2vec(buf,delimiter);
if (2<=tok.size()) {
if (tok[0]=="galFile") galFile = tok[1];
if (tok[0]=="tileFile") tileFile= tok[1];
if (tok[0]=="fibFile") fibFile= tok[1];
if (tok[0]=="surveyFile") surveyFile= tok[1];
if (tok[0]=="outDir") outDir= tok[1];
if (tok[0]=="PrintAscii") PrintAscii= s2b(tok[1]);
if (tok[0]=="PrintFits") PrintFits= s2b(tok[1]);
if (tok[0]=="MTLfile") MTLfile=tok[1];
if (tok[0]=="Targfile") Targfile=tok[1];
if (tok[0]=="SStarsfile")SStarsfile=tok[1];
if (tok[0]=="SkyFfile") SkyFfile=tok[1];
if (tok[0]=="Secretfile") Secretfile=tok[1];
if (tok[0]=="diagnose") diagnose=s2b(tok[1]);
if (tok[0]=="kind") {
Categories = tok.size()-1;
for (int i=0; i<Categories; i++) kind.push_back(tok[i+1]);
init_ids();
init_ss_sf();
init_no_ss_sf();
}
if (tok[0]=="type") {
Categories = tok.size()-1;
for (int i=0; i<Categories; i++) type.push_back(tok[i+1]);
init_types();
init_ids_types();
}
//if (tok[0]=="prio") for (int i=0; i<Categories; i++){prio.push_back(s2i(tok[i+1]));}
//if (tok[0]=="priopost") for (int i=0; i<Categories; i++) priopost.push_back(s2i(tok[i+1]));
if (tok[0]=="goal") for (int i=0; i<Categories; i++) goal.push_back(s2i(tok[i+1]));
if (tok[0]=="goalpost") for (int i=0; i<Categories; i++) goalpost.push_back(s2i(tok[i+1]));
if (tok[0]=="lastpass") for(int i=0; i<Categories;i++)lastpass.push_back(s2i(tok[i+1]));
if (tok[0]=="SS") for(int i=0; i<Categories;i++)SS.push_back(s2i(tok[i+1]));
if (tok[0]=="SF") for(int i=0; i<Categories;i++)SF.push_back(s2i(tok[i+1]));
if (tok[0]=="pass_intervals"){
int n_intervals=tok.size()-1;
for (int i=0;i<n_intervals;++i) pass_intervals.push_back(s2i(tok[i+1]));
}
if (tok[0]=="InterPlate") InterPlate = s2i(tok[1]);
if (tok[0]=="Randomize") Randomize = s2b(tok[1]);
if (tok[0]=="Pacman") Pacman = s2b(tok[1]);
if (tok[0]=="Npass") Npass = s2i(tok[1]);
if (tok[0]=="MaxSS") MaxSS = s2i(tok[1]);
if (tok[0]=="MaxSF") MaxSF = s2i(tok[1]);
if (tok[0]=="PlateRadius") PlateRadius = s2d(tok[1]);
if (tok[0]=="Analysis") Analysis = s2i(tok[1]);
if (tok[0]=="InfDens") InfDens = s2b(tok[1]);
if (tok[0]=="TotalArea") TotalArea = s2d(tok[1]);
if (tok[0]=="invFibArea") invFibArea = s2d(tok[1]);
if (tok[0]=="moduloGal") moduloGal = s2i(tok[1]);
if (tok[0]=="moduloFiber") moduloFiber = s2i(tok[1]);
if (tok[0]=="Collision") Collision = s2b(tok[1]);
if (tok[0]=="Exact") Exact = s2b(tok[1]);
if (tok[0]=="AvCollide") AvCollide = s2d(tok[1]);
if (tok[0]=="Collide") Collide = s2d(tok[1]);
if (tok[0]=="NoCollide") NoCollide = s2d(tok[1]);
if (tok[0]=="PatrolRad") PatrolRad = s2d(tok[1]);
if (tok[0]=="NeighborRad") NeighborRad = s2d(tok[1]);
if (tok[0]=="PlotObsTime") PlotObsTime = s2b(tok[1]);
if (tok[0]=="PlotHistLya") PlotHistLya = s2b(tok[1]);
if (tok[0]=="PlotDistLya") PlotDistLya = s2b(tok[1]);
if (tok[0]=="PlotFreeFibHist") PlotFreeFibHist = s2b(tok[1]);
if (tok[0]=="PlotFreeFibTime") PlotFreeFibTime = s2b(tok[1]);
if (tok[0]=="PlotSeenDens") PlotSeenDens = s2b(tok[1]);
if (tok[0]=="Verif") Verif = s2b(tok[1]);
if (tok[0]=="Ascii") Ascii = s2b(tok[1]);
if (tok[0]=="PrintGalObs") PrintGalObs = s2i(tok[1]);
if (tok[0]=="BrightTime") BrightTime = s2b(tok[1]);
if (tok[0]=="MaxDec") MaxDec = s2d(tok[1]);
if (tok[0]=="MinDec") MinDec = s2d(tok[1]);
if (tok[0]=="MaxRa") MaxRa = s2d(tok[1]);
if (tok[0]=="MinRa") MinRa = s2d(tok[1]);
}
}
fIn.close();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: type_misc.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 23:37:51 $
*
* 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 _BRIDGES_CPP_UNO_TYPE_MISC_HXX_
#define _BRIDGES_CPP_UNO_TYPE_MISC_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _TYPELIB_TYPEDESCRIPTION_H_
#include <typelib/typedescription.h>
#endif
/** Determines whether given type might relate or relates to an interface,
i.e. values of this type are interface or may contain interface(s).<br>
@param pTypeDescr type description of type
@return true if type might relate to an interface, false otherwise
*/
inline bool cppu_relatesToInterface( typelib_TypeDescription * pTypeDescr ) SAL_THROW( () )
{
switch (pTypeDescr->eTypeClass)
{
// case typelib_TypeClass_TYPEDEF:
case typelib_TypeClass_SEQUENCE:
{
switch (((typelib_IndirectTypeDescription *)pTypeDescr)->pType->eTypeClass)
{
case typelib_TypeClass_INTERFACE:
case typelib_TypeClass_UNION: // might relate to interface
case typelib_TypeClass_ANY: // might relate to interface
return true;
case typelib_TypeClass_SEQUENCE:
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
typelib_TypeDescription * pTD = 0;
TYPELIB_DANGER_GET( &pTD, ((typelib_IndirectTypeDescription *)pTypeDescr)->pType );
bool bRel = cppu_relatesToInterface( pTD );
TYPELIB_DANGER_RELEASE( pTD );
return bRel;
}
default:
return false;
}
}
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
// ...optimized... to avoid getDescription() calls!
typelib_CompoundTypeDescription * pComp = (typelib_CompoundTypeDescription *)pTypeDescr;
typelib_TypeDescriptionReference ** pTypes = pComp->ppTypeRefs;
for ( sal_Int32 nPos = pComp->nMembers; nPos--; )
{
switch (pTypes[nPos]->eTypeClass)
{
case typelib_TypeClass_INTERFACE:
case typelib_TypeClass_UNION: // might relate to interface
case typelib_TypeClass_ANY: // might relate to interface
return true;
// case typelib_TypeClass_TYPEDEF:
case typelib_TypeClass_SEQUENCE:
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
typelib_TypeDescription * pTD = 0;
TYPELIB_DANGER_GET( &pTD, pTypes[nPos] );
bool bRel = cppu_relatesToInterface( pTD );
TYPELIB_DANGER_RELEASE( pTD );
if (bRel)
return true;
}
default:
break;
}
}
if (pComp->pBaseTypeDescription)
return cppu_relatesToInterface( (typelib_TypeDescription *)pComp->pBaseTypeDescription );
return false;
}
case typelib_TypeClass_UNION: // might relate to interface
case typelib_TypeClass_ANY: // might relate to interface
case typelib_TypeClass_INTERFACE:
return true;
default:
return false;
}
}
/** Determines whether given type is a cpp simple type, e.g. int, enum.<br>
@param eTypeClass type class of type
@return true if type is a cpp simple type, false otherwise
*/
inline bool cppu_isSimpleType( typelib_TypeClass eTypeClass ) SAL_THROW( () )
{
return (eTypeClass <= typelib_TypeClass_ENUM &&
eTypeClass != typelib_TypeClass_STRING &&
eTypeClass != typelib_TypeClass_ANY &&
eTypeClass != typelib_TypeClass_TYPE);
}
/** Determines whether given type is a cpp simple type, e.g. int, enum.<br>
@param pTypeDescr type description of type
@return true if type is a cpp simple type, false otherwise
*/
inline bool cppu_isSimpleType( typelib_TypeDescription * pTypeDescr ) SAL_THROW( () )
{
return cppu_isSimpleType( pTypeDescr->eTypeClass );
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.122); FILE MERGED 2008/04/01 15:02:32 thb 1.5.122.2: #i85898# Stripping all external header guards 2008/03/28 16:29:51 rt 1.5.122.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: type_misc.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BRIDGES_CPP_UNO_TYPE_MISC_HXX_
#define _BRIDGES_CPP_UNO_TYPE_MISC_HXX_
#include <sal/types.h>
#include <typelib/typedescription.h>
/** Determines whether given type might relate or relates to an interface,
i.e. values of this type are interface or may contain interface(s).<br>
@param pTypeDescr type description of type
@return true if type might relate to an interface, false otherwise
*/
inline bool cppu_relatesToInterface( typelib_TypeDescription * pTypeDescr ) SAL_THROW( () )
{
switch (pTypeDescr->eTypeClass)
{
// case typelib_TypeClass_TYPEDEF:
case typelib_TypeClass_SEQUENCE:
{
switch (((typelib_IndirectTypeDescription *)pTypeDescr)->pType->eTypeClass)
{
case typelib_TypeClass_INTERFACE:
case typelib_TypeClass_UNION: // might relate to interface
case typelib_TypeClass_ANY: // might relate to interface
return true;
case typelib_TypeClass_SEQUENCE:
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
typelib_TypeDescription * pTD = 0;
TYPELIB_DANGER_GET( &pTD, ((typelib_IndirectTypeDescription *)pTypeDescr)->pType );
bool bRel = cppu_relatesToInterface( pTD );
TYPELIB_DANGER_RELEASE( pTD );
return bRel;
}
default:
return false;
}
}
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
// ...optimized... to avoid getDescription() calls!
typelib_CompoundTypeDescription * pComp = (typelib_CompoundTypeDescription *)pTypeDescr;
typelib_TypeDescriptionReference ** pTypes = pComp->ppTypeRefs;
for ( sal_Int32 nPos = pComp->nMembers; nPos--; )
{
switch (pTypes[nPos]->eTypeClass)
{
case typelib_TypeClass_INTERFACE:
case typelib_TypeClass_UNION: // might relate to interface
case typelib_TypeClass_ANY: // might relate to interface
return true;
// case typelib_TypeClass_TYPEDEF:
case typelib_TypeClass_SEQUENCE:
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_EXCEPTION:
{
typelib_TypeDescription * pTD = 0;
TYPELIB_DANGER_GET( &pTD, pTypes[nPos] );
bool bRel = cppu_relatesToInterface( pTD );
TYPELIB_DANGER_RELEASE( pTD );
if (bRel)
return true;
}
default:
break;
}
}
if (pComp->pBaseTypeDescription)
return cppu_relatesToInterface( (typelib_TypeDescription *)pComp->pBaseTypeDescription );
return false;
}
case typelib_TypeClass_UNION: // might relate to interface
case typelib_TypeClass_ANY: // might relate to interface
case typelib_TypeClass_INTERFACE:
return true;
default:
return false;
}
}
/** Determines whether given type is a cpp simple type, e.g. int, enum.<br>
@param eTypeClass type class of type
@return true if type is a cpp simple type, false otherwise
*/
inline bool cppu_isSimpleType( typelib_TypeClass eTypeClass ) SAL_THROW( () )
{
return (eTypeClass <= typelib_TypeClass_ENUM &&
eTypeClass != typelib_TypeClass_STRING &&
eTypeClass != typelib_TypeClass_ANY &&
eTypeClass != typelib_TypeClass_TYPE);
}
/** Determines whether given type is a cpp simple type, e.g. int, enum.<br>
@param pTypeDescr type description of type
@return true if type is a cpp simple type, false otherwise
*/
inline bool cppu_isSimpleType( typelib_TypeDescription * pTypeDescr ) SAL_THROW( () )
{
return cppu_isSimpleType( pTypeDescr->eTypeClass );
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: urp_marshal.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2008-02-04 13:44:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _URP_MARSHAL_HXX_
#define _URP_MARSHAL_HXX_
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RTL_BYTESEQ_HXX_
#include <rtl/byteseq.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_TYPE_HXX_
#include <com/sun/star/uno/Type.hxx>
#endif
#ifndef _URP_BRIDGEIMPL_HXX_
#include "urp_bridgeimpl.hxx"
#endif
#ifndef _URP_MARSHAL_DECL_HXX_
#include "urp_marshal_decl.hxx"
#endif
#include <string.h>
struct remote_Interface;
namespace bridges_urp
{
// methods for accessing marshaling buffer
inline void Marshal::finish( sal_Int32 nMessageCount )
{
sal_Int32 nSize = getSize() - 2*sizeof( sal_Int32 );
// save the state
sal_Int8 *pos = m_pos;
m_pos = m_base;
packInt32( &nSize );
packInt32( &nMessageCount );
// reset the state
m_pos = pos;
}
inline void Marshal::restart()
{
m_pos = m_base + 2*sizeof( sal_Int32 );
}
inline sal_Int8 *Marshal::getBuffer()
{
return m_base;
}
inline sal_Bool Marshal::empty() const
{
return ( m_pos - m_base ) == 2*sizeof( sal_Int32 );
}
inline sal_Int32 Marshal::getSize()
{
return ((sal_Int32) (m_pos - m_base));
}
inline void Marshal::ensureAdditionalMem( sal_Int32 nMemToAdd )
{
sal_Int32 nDiff = m_pos - m_base;
if( nDiff + nMemToAdd > m_nBufferSize )
{
m_nBufferSize = m_nBufferSize * 2 > nDiff + nMemToAdd ?
m_nBufferSize* 2 :
nDiff + nMemToAdd;
m_base = ( sal_Int8 * ) rtl_reallocateMemory( m_base , m_nBufferSize );
m_pos = m_base + nDiff;
}
}
// marshaling methods
inline void Marshal::packInt8( void *pSource )
{
ensureAdditionalMem( 1 );
*m_pos = *((sal_Int8*) pSource );
m_pos++;
}
inline void Marshal::packInt16( void *pSource )
{
ensureAdditionalMem( 2 );
if( isSystemLittleEndian() )
{
m_pos[0] = ((unsigned char *)pSource)[1];
m_pos[1] = ((unsigned char *)pSource)[0];
}
else
{
m_pos[1] = ((unsigned char *)pSource)[1];
m_pos[0] = ((unsigned char *)pSource)[0];
}
m_pos +=2;
}
inline void Marshal::packByteSequence( sal_Int8 *pData , sal_Int32 nLength )
{
packCompressedSize( nLength );
ensureAdditionalMem( nLength );
memcpy( m_pos , pData , nLength );
m_pos += nLength;
}
inline void Marshal::packString( void *pSource )
{
rtl_uString *p = *( rtl_uString ** ) pSource;
// to be optimized !
// static buffer in marshal
::rtl::OString o = ::rtl::OUStringToOString( p , RTL_TEXTENCODING_UTF8 );
sal_Int32 nLength = o.pData->length;
packCompressedSize( nLength );
ensureAdditionalMem( nLength );
memcpy( m_pos , o.pData->buffer , nLength );
m_pos += nLength;
}
inline sal_Bool Marshal::packAny( void *pSource )
{
sal_Bool bSuccess = sal_True;
uno_Any *pAny = (uno_Any * ) pSource;
// pack the type
packType( &( pAny->pType ) );
// pack the value
typelib_TypeDescription *pType = 0;
TYPELIB_DANGER_GET( &pType, pAny->pType );
if( pType )
{
pack( pAny->pData , pType );
TYPELIB_DANGER_RELEASE( pType );
}
else
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("couldn't get typedescription for type " ) );
buf.append( pAny->pType->pTypeName );
m_pBridgeImpl->addError( buf.makeStringAndClear() );
bSuccess = sal_False;
}
return bSuccess;
}
inline void Marshal::packInt32( void *pSource )
{
ensureAdditionalMem( 4 );
if( isSystemLittleEndian() )
{
m_pos[0] = ((unsigned char *)pSource)[3];
m_pos[1] = ((unsigned char *)pSource)[2];
m_pos[2] = ((unsigned char *)pSource)[1];
m_pos[3] = ((unsigned char *)pSource)[0];
}
else {
m_pos[3] = ((unsigned char *)pSource)[3];
m_pos[2] = ((unsigned char *)pSource)[2];
m_pos[1] = ((unsigned char *)pSource)[1];
m_pos[0] = ((unsigned char *)pSource)[0];
}
m_pos +=4;
}
inline void Marshal::packCompressedSize( sal_Int32 nSize )
{
ensureAdditionalMem( 5 );
if( nSize < 0xff )
{
*((sal_uInt8*)m_pos) = (sal_uInt8) nSize;
m_pos ++;
}
else
{
*((sal_uInt8*)m_pos) = 0xff;
m_pos ++;
packInt32( &nSize );
}
}
inline sal_Bool Marshal::pack( void *pSource , typelib_TypeDescription *pType )
{
sal_Bool bSuccess = sal_True;
switch( pType->eTypeClass )
{
case typelib_TypeClass_BYTE:
{
packInt8( pSource );
break;
}
case typelib_TypeClass_BOOLEAN:
{
ensureAdditionalMem( 1 );
*m_pos = ( *((sal_Bool*) pSource ) ) ? 1 : 0;
m_pos++;
break;
}
case typelib_TypeClass_CHAR:
case typelib_TypeClass_SHORT:
case typelib_TypeClass_UNSIGNED_SHORT:
{
packInt16( pSource );
break;
}
case typelib_TypeClass_ENUM:
case typelib_TypeClass_LONG:
case typelib_TypeClass_UNSIGNED_LONG:
case typelib_TypeClass_FLOAT:
{
packInt32( pSource );
break;
}
case typelib_TypeClass_DOUBLE:
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
{
ensureAdditionalMem( 8 );
if( isSystemLittleEndian() )
{
m_pos[0] = ((unsigned char *)pSource)[7];
m_pos[1] = ((unsigned char *)pSource)[6];
m_pos[2] = ((unsigned char *)pSource)[5];
m_pos[3] = ((unsigned char *)pSource)[4];
m_pos[4] = ((unsigned char *)pSource)[3];
m_pos[5] = ((unsigned char *)pSource)[2];
m_pos[6] = ((unsigned char *)pSource)[1];
m_pos[7] = ((unsigned char *)pSource)[0];
}
else
{
m_pos[7] = ((unsigned char *)pSource)[7];
m_pos[6] = ((unsigned char *)pSource)[6];
m_pos[5] = ((unsigned char *)pSource)[5];
m_pos[4] = ((unsigned char *)pSource)[4];
m_pos[3] = ((unsigned char *)pSource)[3];
m_pos[2] = ((unsigned char *)pSource)[2];
m_pos[1] = ((unsigned char *)pSource)[1];
m_pos[0] = ((unsigned char *)pSource)[0];
}
m_pos += 8;
break;
}
case typelib_TypeClass_STRING:
{
packString( pSource );
break;
}
case typelib_TypeClass_TYPE:
{
packType( pSource );
break;
}
case typelib_TypeClass_ANY:
{
bSuccess = packAny( pSource );
break;
}
case typelib_TypeClass_TYPEDEF:
{
bSuccess = sal_False;
m_pBridgeImpl->addError( "can't handle typedef typedescriptions" );
break;
}
case typelib_TypeClass_INTERFACE:
{
remote_Interface *pRemoteI = *( remote_Interface ** )pSource;
::rtl::OUString sOid;
sal_uInt16 nIndex = 0xffff;
if( pRemoteI )
{
m_callback( pRemoteI , &(sOid.pData) );
nIndex = m_pBridgeImpl->m_oidCacheOut.seek( sOid );
if( 0xffff == nIndex )
{
nIndex = m_pBridgeImpl->m_oidCacheOut.put( sOid );
}
else
{
// cached !
sOid = ::rtl::OUString();
}
}
packString( &sOid );
packInt16( &nIndex );
break;
}
case typelib_TypeClass_VOID:
{
// do nothing
break;
}
case typelib_TypeClass_EXCEPTION:
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_SEQUENCE:
{
bSuccess = packRecursive( pSource, pType );
break;
}
default:
{
bSuccess = sal_False;
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "can't handle values with typeclass " ) );
buf.append( (sal_Int32 ) pType->eTypeClass , 10 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " (" ) );
buf.append( pType->pTypeName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( ")" ) );
m_pBridgeImpl->addError( buf.makeStringAndClear() );
break;
}
}
return bSuccess;
}
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.14); FILE MERGED 2008/04/01 15:02:36 thb 1.8.14.3: #i85898# Stripping all external header guards 2008/04/01 10:49:07 thb 1.8.14.2: #i85898# Stripping all external header guards 2008/03/28 16:30:59 rt 1.8.14.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: urp_marshal.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _URP_MARSHAL_HXX_
#define _URP_MARSHAL_HXX_
#include <rtl/ustrbuf.hxx>
#include <rtl/byteseq.hxx>
#include <com/sun/star/uno/Type.hxx>
#include "urp_bridgeimpl.hxx"
#include "urp_marshal_decl.hxx"
#include <string.h>
struct remote_Interface;
namespace bridges_urp
{
// methods for accessing marshaling buffer
inline void Marshal::finish( sal_Int32 nMessageCount )
{
sal_Int32 nSize = getSize() - 2*sizeof( sal_Int32 );
// save the state
sal_Int8 *pos = m_pos;
m_pos = m_base;
packInt32( &nSize );
packInt32( &nMessageCount );
// reset the state
m_pos = pos;
}
inline void Marshal::restart()
{
m_pos = m_base + 2*sizeof( sal_Int32 );
}
inline sal_Int8 *Marshal::getBuffer()
{
return m_base;
}
inline sal_Bool Marshal::empty() const
{
return ( m_pos - m_base ) == 2*sizeof( sal_Int32 );
}
inline sal_Int32 Marshal::getSize()
{
return ((sal_Int32) (m_pos - m_base));
}
inline void Marshal::ensureAdditionalMem( sal_Int32 nMemToAdd )
{
sal_Int32 nDiff = m_pos - m_base;
if( nDiff + nMemToAdd > m_nBufferSize )
{
m_nBufferSize = m_nBufferSize * 2 > nDiff + nMemToAdd ?
m_nBufferSize* 2 :
nDiff + nMemToAdd;
m_base = ( sal_Int8 * ) rtl_reallocateMemory( m_base , m_nBufferSize );
m_pos = m_base + nDiff;
}
}
// marshaling methods
inline void Marshal::packInt8( void *pSource )
{
ensureAdditionalMem( 1 );
*m_pos = *((sal_Int8*) pSource );
m_pos++;
}
inline void Marshal::packInt16( void *pSource )
{
ensureAdditionalMem( 2 );
if( isSystemLittleEndian() )
{
m_pos[0] = ((unsigned char *)pSource)[1];
m_pos[1] = ((unsigned char *)pSource)[0];
}
else
{
m_pos[1] = ((unsigned char *)pSource)[1];
m_pos[0] = ((unsigned char *)pSource)[0];
}
m_pos +=2;
}
inline void Marshal::packByteSequence( sal_Int8 *pData , sal_Int32 nLength )
{
packCompressedSize( nLength );
ensureAdditionalMem( nLength );
memcpy( m_pos , pData , nLength );
m_pos += nLength;
}
inline void Marshal::packString( void *pSource )
{
rtl_uString *p = *( rtl_uString ** ) pSource;
// to be optimized !
// static buffer in marshal
::rtl::OString o = ::rtl::OUStringToOString( p , RTL_TEXTENCODING_UTF8 );
sal_Int32 nLength = o.pData->length;
packCompressedSize( nLength );
ensureAdditionalMem( nLength );
memcpy( m_pos , o.pData->buffer , nLength );
m_pos += nLength;
}
inline sal_Bool Marshal::packAny( void *pSource )
{
sal_Bool bSuccess = sal_True;
uno_Any *pAny = (uno_Any * ) pSource;
// pack the type
packType( &( pAny->pType ) );
// pack the value
typelib_TypeDescription *pType = 0;
TYPELIB_DANGER_GET( &pType, pAny->pType );
if( pType )
{
pack( pAny->pData , pType );
TYPELIB_DANGER_RELEASE( pType );
}
else
{
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("couldn't get typedescription for type " ) );
buf.append( pAny->pType->pTypeName );
m_pBridgeImpl->addError( buf.makeStringAndClear() );
bSuccess = sal_False;
}
return bSuccess;
}
inline void Marshal::packInt32( void *pSource )
{
ensureAdditionalMem( 4 );
if( isSystemLittleEndian() )
{
m_pos[0] = ((unsigned char *)pSource)[3];
m_pos[1] = ((unsigned char *)pSource)[2];
m_pos[2] = ((unsigned char *)pSource)[1];
m_pos[3] = ((unsigned char *)pSource)[0];
}
else {
m_pos[3] = ((unsigned char *)pSource)[3];
m_pos[2] = ((unsigned char *)pSource)[2];
m_pos[1] = ((unsigned char *)pSource)[1];
m_pos[0] = ((unsigned char *)pSource)[0];
}
m_pos +=4;
}
inline void Marshal::packCompressedSize( sal_Int32 nSize )
{
ensureAdditionalMem( 5 );
if( nSize < 0xff )
{
*((sal_uInt8*)m_pos) = (sal_uInt8) nSize;
m_pos ++;
}
else
{
*((sal_uInt8*)m_pos) = 0xff;
m_pos ++;
packInt32( &nSize );
}
}
inline sal_Bool Marshal::pack( void *pSource , typelib_TypeDescription *pType )
{
sal_Bool bSuccess = sal_True;
switch( pType->eTypeClass )
{
case typelib_TypeClass_BYTE:
{
packInt8( pSource );
break;
}
case typelib_TypeClass_BOOLEAN:
{
ensureAdditionalMem( 1 );
*m_pos = ( *((sal_Bool*) pSource ) ) ? 1 : 0;
m_pos++;
break;
}
case typelib_TypeClass_CHAR:
case typelib_TypeClass_SHORT:
case typelib_TypeClass_UNSIGNED_SHORT:
{
packInt16( pSource );
break;
}
case typelib_TypeClass_ENUM:
case typelib_TypeClass_LONG:
case typelib_TypeClass_UNSIGNED_LONG:
case typelib_TypeClass_FLOAT:
{
packInt32( pSource );
break;
}
case typelib_TypeClass_DOUBLE:
case typelib_TypeClass_HYPER:
case typelib_TypeClass_UNSIGNED_HYPER:
{
ensureAdditionalMem( 8 );
if( isSystemLittleEndian() )
{
m_pos[0] = ((unsigned char *)pSource)[7];
m_pos[1] = ((unsigned char *)pSource)[6];
m_pos[2] = ((unsigned char *)pSource)[5];
m_pos[3] = ((unsigned char *)pSource)[4];
m_pos[4] = ((unsigned char *)pSource)[3];
m_pos[5] = ((unsigned char *)pSource)[2];
m_pos[6] = ((unsigned char *)pSource)[1];
m_pos[7] = ((unsigned char *)pSource)[0];
}
else
{
m_pos[7] = ((unsigned char *)pSource)[7];
m_pos[6] = ((unsigned char *)pSource)[6];
m_pos[5] = ((unsigned char *)pSource)[5];
m_pos[4] = ((unsigned char *)pSource)[4];
m_pos[3] = ((unsigned char *)pSource)[3];
m_pos[2] = ((unsigned char *)pSource)[2];
m_pos[1] = ((unsigned char *)pSource)[1];
m_pos[0] = ((unsigned char *)pSource)[0];
}
m_pos += 8;
break;
}
case typelib_TypeClass_STRING:
{
packString( pSource );
break;
}
case typelib_TypeClass_TYPE:
{
packType( pSource );
break;
}
case typelib_TypeClass_ANY:
{
bSuccess = packAny( pSource );
break;
}
case typelib_TypeClass_TYPEDEF:
{
bSuccess = sal_False;
m_pBridgeImpl->addError( "can't handle typedef typedescriptions" );
break;
}
case typelib_TypeClass_INTERFACE:
{
remote_Interface *pRemoteI = *( remote_Interface ** )pSource;
::rtl::OUString sOid;
sal_uInt16 nIndex = 0xffff;
if( pRemoteI )
{
m_callback( pRemoteI , &(sOid.pData) );
nIndex = m_pBridgeImpl->m_oidCacheOut.seek( sOid );
if( 0xffff == nIndex )
{
nIndex = m_pBridgeImpl->m_oidCacheOut.put( sOid );
}
else
{
// cached !
sOid = ::rtl::OUString();
}
}
packString( &sOid );
packInt16( &nIndex );
break;
}
case typelib_TypeClass_VOID:
{
// do nothing
break;
}
case typelib_TypeClass_EXCEPTION:
case typelib_TypeClass_STRUCT:
case typelib_TypeClass_SEQUENCE:
{
bSuccess = packRecursive( pSource, pType );
break;
}
default:
{
bSuccess = sal_False;
rtl::OUStringBuffer buf( 128 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "can't handle values with typeclass " ) );
buf.append( (sal_Int32 ) pType->eTypeClass , 10 );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " (" ) );
buf.append( pType->pTypeName );
buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( ")" ) );
m_pBridgeImpl->addError( buf.makeStringAndClear() );
break;
}
}
return bSuccess;
}
}
#endif
<|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 <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
typedef int mode_t;
#else
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
namespace fs = boost::filesystem;
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
// if (m == (mode_in | mode_out)) return O_RDWR | O_BINARY;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
assert(false);
return 0;
}
}
namespace libtorrent
{
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
void open(fs::path const& path, int mode)
{
close();
m_fd = ::open(
path.native_file_string().c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< strerror(errno);
throw file_error(msg.str());
}
m_open_mode = mode;
}
void close()
{
if (m_fd == -1) return;
std::stringstream str;
str << "fd: " << m_fd << "\n";
::close(m_fd);
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
assert(m_open_mode == mode_in);
assert(m_fd != -1);
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
assert(m_open_mode == mode_out);
assert(m_fd != -1);
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
void seek(size_type offset, int m)
{
assert(m_open_mode);
assert(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
throw file_error(msg.str());
}
}
size_type tell()
{
assert(m_open_mode);
assert(m_fd != -1);
#ifdef WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(boost::filesystem::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
void file::open(boost::filesystem::path const& p, file::open_mode m)
{
m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
void file::seek(size_type pos, file::seek_mode m)
{
m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>*** empty log message ***<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 <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#else
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
namespace fs = boost::filesystem;
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
// if (m == (mode_in | mode_out)) return O_RDWR | O_BINARY;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
assert(false);
return 0;
}
}
namespace libtorrent
{
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
void open(fs::path const& path, int mode)
{
close();
m_fd = ::open(
path.native_file_string().c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< strerror(errno);
throw file_error(msg.str());
}
m_open_mode = mode;
}
void close()
{
if (m_fd == -1) return;
std::stringstream str;
str << "fd: " << m_fd << "\n";
::close(m_fd);
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
assert(m_open_mode == mode_in);
assert(m_fd != -1);
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
assert(m_open_mode == mode_out);
assert(m_fd != -1);
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
void seek(size_type offset, int m)
{
assert(m_open_mode);
assert(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
throw file_error(msg.str());
}
}
size_type tell()
{
assert(m_open_mode);
assert(m_fd != -1);
#ifdef WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(boost::filesystem::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
void file::open(boost::filesystem::path const& p, file::open_mode m)
{
m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
void file::seek(size_type pos, file::seek_mode m)
{
m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/atom_javascript_dialog_manager.h"
#include "base/utf_string_conversions.h"
namespace atom {
void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
const string16& message_text,
bool is_reload,
const DialogClosedCallback& callback) {
bool prevent_reload = !message_text.empty() ||
message_text == ASCIIToUTF16("false");
callback.Run(!prevent_reload, message_text);
}
} // namespace atom
<commit_msg>Revert ":lipstick: for the beforeunload handler."<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/atom_javascript_dialog_manager.h"
#include "base/utf_string_conversions.h"
namespace atom {
void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
const string16& message_text,
bool is_reload,
const DialogClosedCallback& callback) {
bool prevent_reload = message_text.empty() ||
message_text == ASCIIToUTF16("false");
callback.Run(!prevent_reload, message_text);
}
} // namespace atom
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <queue>
#include <sys/stat.h>
//getlogin() and gethostname().
#include <unistd.h>
//perror.
#include <stdio.h>
//fork,wait and execvp.
#include <sys/types.h>
#include <sys/wait.h>
//boost!
#include "boost/algorithm/string.hpp"
#include "boost/tokenizer.hpp"
#include "boost/foreach.hpp"
//that one class.
#include "Command.h"
using namespace std;
using namespace boost;
//execute command.
void execute(const vector<string> & s);
//replaces char in string.
void replace_char(string &s, char o, char r);
//takes a string and returns vector of parsed string.
vector<string> parseInput(string s);
//display vector.
template<typename unit>
void display_vector(vector<unit> v);
//helper function that finds amount of character.
int find_char_amount(const string s,char c);
//removes comment from input.
void remove_comment(string &s);
//removes char in string.
void remove_char(string &s, char c);
//checks if string passed in contains a flag
bool isFlag(string f);
//creates command types from vector of strings.
vector<Command> create_commands(const vector<string> &v);
int main()
{
//grab the login.
char* login = getlogin();
//start a flag.
bool login_check = true;
if((!login) != 0)
{
//check flag.
login_check = false;
//output error.
perror("Error: could not retrieve login name");
}
//hold c-string for host name.
char host[150];
//start another flag.
bool host_check = true;
//gets hostname while checking if it actually grabbed it.
if(gethostname(host,sizeof(host)) != 0)
{
//check flag.
host_check = false;
//output error.
perror("Error: could not rerieve host name.");
}
//warn user of upcoming trouble.
if(login_check == false || host_check == false)
cout << "Unable to display login and/or host information." << endl;
//string to hold user input.
string input;
while(true)
{
//output login@hostname.
if(login_check && host_check)
cout << login << '@' << host << ' ';
//bash money.
cout << "$ ";
//placeholder to tell its the program.
cout << " (program) ";
//geting input as a string.
getline(cin,input);
//remove extra white space.
trim(input);
//remove comments.
remove_comment(input);
//trim again just in case.
trim(input);
//testing parse.
cout << "Testing parse" << endl;
display_vector(parseInput(input));
//execute command.
execute(parseInput(input));
}
cout << "End of program" << endl;
return 0;
}
void execute(const vector<string> &s)
{
//check to see if user wants to quit and its the only command.
if(s.size() == 1)
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == "exit")
exit(0);
//c-string to hold command.
char* args[2048];
//place, remove comments and convert commands.
for(unsigned int i = 0; i < s.size(); ++i)
{
string temp = s.at(i);
remove_char(temp,'\"');
args[i] = (char*)temp.c_str();
}
args[s.size()] = NULL;
//creates fork process.
pid_t pid = fork();
if(pid == -1)
{
//fork didn't work.
perror("fork");
}
if(pid ==0)
{
if(execvp(args[0], args) == -1)
{
//execute didn't work.
perror("execvp");
//break out of shadow realm.
exit(1);
}
}
if(pid > 0)
{
//wait for child to die.
if(wait(0) == -1)
{
//didnt wait.
perror("wait");
}
}
return;
}
vector<string> parseInput(string s)
{
//replace spaces.
replace_char(s,' ','*');
//make temp vector to hold parsed strings.
vector<string> temp;
//create boost magic function.
char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens);
//create boost magic holder thingy.
tokenizer< char_separator<char> > cm(s,sep);
//for each loop to grab each peice and push it into a vector.
for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it)
if(*it != "")
{
//fix string.
string temp_string = *it;
replace_char(temp_string,'*',' ');
temp.push_back(temp_string);
}
//return that vector.
return temp;
}
void replace_char(string &s, char o, char r)
{
//different use for the function.
if(o == '\"')
{
//nothing to replace.
if(s.find(o) == string::npos)
return;
//replace.
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == o)
s.at(i) = r;
return;
}
//no quotes.
if(s.find("\"") == string::npos)
return;
else if(s.find(o) == string::npos)
return;
//vector to hold quote positions.
vector<int> pos;
//place positions of char into vector.
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == '\"')
pos.push_back(i);
//count position.
unsigned int count = 0;
//replace.
while(count < pos.size())
{
for(int i = pos.at(count); i < pos.at(count+1); ++i)
if(s.at(i) == o)
s.at(i) = r;
count++;
count++;
}
return;
}
template<typename unit>
void display_vector(vector<unit> v)
{
for(unsigned int i = 0; i < v.size(); ++i)
cout << i+1 << ": " << v.at(i) << endl;
return;
}
void remove_comment(string &s)
{
//just add a " to the end to avoid errors.
if(find_char_amount(s,'\"') % 2 != 0)
s += '\"';
//delete everything!
if(s.find("#") == 0)
{
s = "";
return;
}
//return if no comments.
if(s.find("#") == string::npos)
{
return;
}
//if no comments then deletes everything from hash forward.
if(s.find("\"") == string::npos && s.find("#") != string::npos)
{
s = s.substr(0,s.find("#"));
return;
}
//if comment before quote then delete.
if(s.find("\"") > s.find("#"))
{
s = s.substr(0,s.find("#"));
return;
}
//advanced situations.
//get a vector to hold positions of quotes and hash.
vector<int> quotePos;
vector<int> hashPos;
//grab pos.
for(unsigned int i = 0; i < s.size(); ++i)
{
if(s.at(i) == '\"')
quotePos.push_back(i);
else if(s.at(i) == '#')
hashPos.push_back(i);
}
//no comments or hash for some reason.
if(hashPos.size() == 0 || quotePos.size() == 0)
return;
//just in case.
if(quotePos.size() % 2 != 0)
quotePos.push_back(0);
//overall check;
vector<bool> check;
//start it up.
for(unsigned int i = 0; i < hashPos.size(); ++i)
check.push_back(true);
//check if hash is in quotes.
for(unsigned int i = 0; i < hashPos.size(); ++i )
for(unsigned int j = 0; j < quotePos.size(); j+=2 )
{
if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1))
{
check.at(i) = true;
break;
}
else
check.at(i) = false;
}
//check bool vector to delete string.
for(unsigned int i = 0; i < check.size(); ++i)
if(!check.at(i))
{
s = s.substr(0,hashPos.at(i));
return;
}
//if comment at end then kill it.
if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1))
s = s.substr(0,hashPos.at(hashPos.size()-1));
return;
}
int find_char_amount(const string s, char c)
{
if(s.find(c) == string::npos)
return 0;
int count = 0;
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == c)
count++;
return count;
}
void remove_char(string &s, char c)
{
//if not there then just return.
if(s.find(c) == string::npos)
return;
//start empty.
string temp = "";
//add everything thats not what we dont want.
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) != c)
temp += s.at(i);
//transfer to s.
s = temp;
return;
}
bool isFlag(string f)
{ //default list of possible flags
string flags = "-e -d -f";
//see if string is one of the flags
if (flags.find(f) != string::npos)
return true;
return false;
}
/*
bool test(vector<string> &commands, vector<char*> &command_v)
{
//defaults to "-e"
string flag = "-e";
struct stat s_thing;
//put everything into a queue for ease of use
queue<string> coms;
for (unsigned int i = 0; i < commands.size(); i++)
{
coms.push_back(commands.at(i));
}
//was a bracket used for the test command?
bool bracketUsed = false;
//set if a bracket was used
if(coms.front() == "[";
bracketUsed = true;
//remove the first part of the command regardless of whether it's "test" or "["
coms.pop();
if (isTestFlag(coms.front()))
{
flag = coms.front();
//now we have the flag for the test
coms.pop()
}
//if there's another flag attempt then it's broken
if (coms.front().at(0) == "-")
{
cout << "ERROR: incorrect flags" << endl;
//keep deleting from queue till the next command
while (!is_connector(coms.front()))
{
coms.pop();
}
return true;
}
// if the first part of the path is a "/" remove it (that way it can't mess up)
if(coms.front().at(0) == "/")
commands.front().substr(1, commands.front().size() - 1);
//make a new c_string to hold the file path
char *filePath = new char[coms.front.size()];
//copy it on over from the command vector
strcpy(filePath, coms.front().c_str());
command_v.push_back(filePath);
//moving along
coms.pop();
//Did we use a bracket instead of "test"? If so get rid of the last bracket
if(bracketUsed)
{
coms.pop();
}
//valuse for using the stat thingy
int current_stat;
//get the status of the command
current_stat = stat(command_v.front(), &s_thing);
//Did it fail?
if(current_stat < 0)
{
//Yup it did
perror("ERROR: Coudn't get the stat");
return true;
}
//No it didn't so lets try out with "-e"
if (flag == "-e")
{
return false;
}
//Try it out with "-f"
if(flag == "-f")
{
if(S_ISREG(s_thing.st_mode))
{
return false
} else
{
return true
}
}
//Try it out with "-d"
if (flag == "-d")
{
if (S_ISDIR(s_thing.st_mode))
{
return false;
} else
{
return true
}
}
//Obviously something went wrong if you got here
return true
}*/
vector<Command> create_commands(const vector<string> &v)
{
vector<Command> commandVector;
Command temp;
return commandVector;
}
<commit_msg>added the is_connector function<commit_after>#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <queue>
#include <sys/stat.h>
//getlogin() and gethostname().
#include <unistd.h>
//perror.
#include <stdio.h>
//fork,wait and execvp.
#include <sys/types.h>
#include <sys/wait.h>
//boost!
#include "boost/algorithm/string.hpp"
#include "boost/tokenizer.hpp"
#include "boost/foreach.hpp"
//that one class.
#include "Command.h"
using namespace std;
using namespace boost;
//execute command.
void execute(const vector<string> & s);
//replaces char in string.
void replace_char(string &s, char o, char r);
//takes a string and returns vector of parsed string.
vector<string> parseInput(string s);
//display vector.
template<typename unit>
void display_vector(vector<unit> v);
//helper function that finds amount of character.
int find_char_amount(const string s,char c);
//removes comment from input.
void remove_comment(string &s);
//removes char in string.
void remove_char(string &s, char c);
//checks if string passed in contains a flag
bool isFlag(string f);
//creates command types from vector of strings.
vector<Command> create_commands(const vector<string> &v);
int main()
{
//grab the login.
char* login = getlogin();
//start a flag.
bool login_check = true;
if((!login) != 0)
{
//check flag.
login_check = false;
//output error.
perror("Error: could not retrieve login name");
}
//hold c-string for host name.
char host[150];
//start another flag.
bool host_check = true;
//gets hostname while checking if it actually grabbed it.
if(gethostname(host,sizeof(host)) != 0)
{
//check flag.
host_check = false;
//output error.
perror("Error: could not rerieve host name.");
}
//warn user of upcoming trouble.
if(login_check == false || host_check == false)
cout << "Unable to display login and/or host information." << endl;
//string to hold user input.
string input;
while(true)
{
//output login@hostname.
if(login_check && host_check)
cout << login << '@' << host << ' ';
//bash money.
cout << "$ ";
//placeholder to tell its the program.
cout << " (program) ";
//geting input as a string.
getline(cin,input);
//remove extra white space.
trim(input);
//remove comments.
remove_comment(input);
//trim again just in case.
trim(input);
//testing parse.
cout << "Testing parse" << endl;
display_vector(parseInput(input));
//execute command.
execute(parseInput(input));
}
cout << "End of program" << endl;
return 0;
}
void execute(const vector<string> &s)
{
//check to see if user wants to quit and its the only command.
if(s.size() == 1)
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == "exit")
exit(0);
//c-string to hold command.
char* args[2048];
//place, remove comments and convert commands.
for(unsigned int i = 0; i < s.size(); ++i)
{
string temp = s.at(i);
remove_char(temp,'\"');
args[i] = (char*)temp.c_str();
}
args[s.size()] = NULL;
//creates fork process.
pid_t pid = fork();
if(pid == -1)
{
//fork didn't work.
perror("fork");
}
if(pid ==0)
{
if(execvp(args[0], args) == -1)
{
//execute didn't work.
perror("execvp");
//break out of shadow realm.
exit(1);
}
}
if(pid > 0)
{
//wait for child to die.
if(wait(0) == -1)
{
//didnt wait.
perror("wait");
}
}
return;
}
vector<string> parseInput(string s)
{
//replace spaces.
replace_char(s,' ','*');
//make temp vector to hold parsed strings.
vector<string> temp;
//create boost magic function.
char_separator<char> sep(" ;||&&(){}", ";||&&()[]",keep_empty_tokens);
//create boost magic holder thingy.
tokenizer< char_separator<char> > cm(s,sep);
//for each loop to grab each peice and push it into a vector.
for(tokenizer< char_separator<char> >::iterator it = cm.begin(); it != cm.end(); ++it)
if(*it != "")
{
//fix string.
string temp_string = *it;
replace_char(temp_string,'*',' ');
temp.push_back(temp_string);
}
//return that vector.
return temp;
}
void replace_char(string &s, char o, char r)
{
//different use for the function.
if(o == '\"')
{
//nothing to replace.
if(s.find(o) == string::npos)
return;
//replace.
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == o)
s.at(i) = r;
return;
}
//no quotes.
if(s.find("\"") == string::npos)
return;
else if(s.find(o) == string::npos)
return;
//vector to hold quote positions.
vector<int> pos;
//place positions of char into vector.
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == '\"')
pos.push_back(i);
//count position.
unsigned int count = 0;
//replace.
while(count < pos.size())
{
for(int i = pos.at(count); i < pos.at(count+1); ++i)
if(s.at(i) == o)
s.at(i) = r;
count++;
count++;
}
return;
}
template<typename unit>
void display_vector(vector<unit> v)
{
for(unsigned int i = 0; i < v.size(); ++i)
cout << i+1 << ": " << v.at(i) << endl;
return;
}
void remove_comment(string &s)
{
//just add a " to the end to avoid errors.
if(find_char_amount(s,'\"') % 2 != 0)
s += '\"';
//delete everything!
if(s.find("#") == 0)
{
s = "";
return;
}
//return if no comments.
if(s.find("#") == string::npos)
{
return;
}
//if no comments then deletes everything from hash forward.
if(s.find("\"") == string::npos && s.find("#") != string::npos)
{
s = s.substr(0,s.find("#"));
return;
}
//if comment before quote then delete.
if(s.find("\"") > s.find("#"))
{
s = s.substr(0,s.find("#"));
return;
}
//advanced situations.
//get a vector to hold positions of quotes and hash.
vector<int> quotePos;
vector<int> hashPos;
//grab pos.
for(unsigned int i = 0; i < s.size(); ++i)
{
if(s.at(i) == '\"')
quotePos.push_back(i);
else if(s.at(i) == '#')
hashPos.push_back(i);
}
//no comments or hash for some reason.
if(hashPos.size() == 0 || quotePos.size() == 0)
return;
//just in case.
if(quotePos.size() % 2 != 0)
quotePos.push_back(0);
//overall check;
vector<bool> check;
//start it up.
for(unsigned int i = 0; i < hashPos.size(); ++i)
check.push_back(true);
//check if hash is in quotes.
for(unsigned int i = 0; i < hashPos.size(); ++i )
for(unsigned int j = 0; j < quotePos.size(); j+=2 )
{
if(hashPos.at(i) > quotePos.at(j) && hashPos.at(i) < quotePos.at(j+1))
{
check.at(i) = true;
break;
}
else
check.at(i) = false;
}
//check bool vector to delete string.
for(unsigned int i = 0; i < check.size(); ++i)
if(!check.at(i))
{
s = s.substr(0,hashPos.at(i));
return;
}
//if comment at end then kill it.
if(hashPos.at(hashPos.size()-1) > quotePos.at(quotePos.size()-1))
s = s.substr(0,hashPos.at(hashPos.size()-1));
return;
}
int find_char_amount(const string s, char c)
{
if(s.find(c) == string::npos)
return 0;
int count = 0;
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) == c)
count++;
return count;
}
void remove_char(string &s, char c)
{
//if not there then just return.
if(s.find(c) == string::npos)
return;
//start empty.
string temp = "";
//add everything thats not what we dont want.
for(unsigned int i = 0; i < s.size(); ++i)
if(s.at(i) != c)
temp += s.at(i);
//transfer to s.
s = temp;
return;
}
int is_connector(string s)
{
if(s == ";")
return 1;
if(s == "&&")
return 2;
if(s == "||")
return 3;
return -1;
}
bool isFlag(string f)
{ //default list of possible flags
string flags = "-e -d -f";
//see if string is one of the flags
if (flags.find(f) != string::npos)
return true;
return false;
}
/*
bool test(vector<string> &commands, vector<char*> &command_v)
{
//defaults to "-e"
string flag = "-e";
struct stat s_thing;
//put everything into a queue for ease of use
queue<string> coms;
for (unsigned int i = 0; i < commands.size(); i++)
{
coms.push_back(commands.at(i));
}
//was a bracket used for the test command?
bool bracketUsed = false;
//set if a bracket was used
if(coms.front() == "[";
bracketUsed = true;
//remove the first part of the command regardless of whether it's "test" or "["
coms.pop();
if (isTestFlag(coms.front()))
{
flag = coms.front();
//now we have the flag for the test
coms.pop()
}
//if there's another flag attempt then it's broken
if (coms.front().at(0) == "-")
{
cout << "ERROR: incorrect flags" << endl;
//keep deleting from queue till the next command
while (!is_connector(coms.front()))
{
coms.pop();
}
return true;
}
// if the first part of the path is a "/" remove it (that way it can't mess up)
if(coms.front().at(0) == "/")
commands.front().substr(1, commands.front().size() - 1);
//make a new c_string to hold the file path
char *filePath = new char[coms.front.size()];
//copy it on over from the command vector
strcpy(filePath, coms.front().c_str());
command_v.push_back(filePath);
//moving along
coms.pop();
//Did we use a bracket instead of "test"? If so get rid of the last bracket
if(bracketUsed)
{
coms.pop();
}
//valuse for using the stat thingy
int current_stat;
//get the status of the command
current_stat = stat(command_v.front(), &s_thing);
//Did it fail?
if(current_stat < 0)
{
//Yup it did
perror("ERROR: Coudn't get the stat");
return true;
}
//No it didn't so lets try out with "-e"
if (flag == "-e")
{
return false;
}
//Try it out with "-f"
if(flag == "-f")
{
if(S_ISREG(s_thing.st_mode))
{
return false
} else
{
return true
}
}
//Try it out with "-d"
if (flag == "-d")
{
if (S_ISDIR(s_thing.st_mode))
{
return false;
} else
{
return true
}
}
//Obviously something went wrong if you got here
return true
}*/
vector<Command> create_commands(const vector<string> &v)
{
vector<Command> commandVector;
Command temp;
return commandVector;
}
<|endoftext|> |
<commit_before>#include "encoder_app.h"
#include "encoding_task.h"
#include "riff_wave.h"
int main(int argc, char *argv[])
{
// GMp3Enc::RiffWave w;
// w.readWave("./temple_of_love-sisters_of_mercy.wav");
// if (!w.isValid()) {
// return -1;
// }
// GMp3Enc::EncodingTask *t = GMp3Enc::EncodingTask::create(
// w, "./1.mp3", 0);
// t->encode();
GMp3Enc::EncoderApp app(argc, argv);
return app.exec();
}
<commit_msg>Removed not needed comments<commit_after>#include "encoder_app.h"
#include "encoding_task.h"
#include "riff_wave.h"
int main(int argc, char *argv[])
{
GMp3Enc::EncoderApp app(argc, argv);
return app.exec();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "Constants.h"
#include "Path.h"
#include "AbstractView.h"
#include "ResourceManager.h"
#include "HIManager.h"
#include "Logs.h"
using namespace std;
int main(int argc, char *argv[]) {
log_init();
LOG(info) << "Superteacher is starting";
LOG(debug) << "SRC Directory: " << _SRC_DIR;
LOG(debug) << "Install Prefix: " << _INSTALL_PREFIX;
LOG(info) << "Opening window";
LOG(debug) << "Window size: " << SCREEN_X_PXSIZE << "x" << SCREEN_Y_PXSIZE;
ResourceManager resource = {};
auto config = resource.get_json("conf.json");
auto style = sf::Style::Default;
if((bool)(*config)["video"]["fullscreen"]){
style = sf::Style::Fullscreen;
}
sf::RenderWindow window(
sf::VideoMode(SCREEN_X_PXSIZE, SCREEN_Y_PXSIZE),
"SuperTeacher",
style
);
window.setFramerateLimit(50);
HIManager user_input = {&window};
user_input.HIEvent_sig.connect([&window](HIEvent event)->void{
switch(event) {
case HIEvent::CLOSE:
window.close();
break;
default:
break;
}
});
auto level = resource.get_json("levels/level.json");
auto font = resource.get_font(FONT_INDIE_FLOWER);
auto song = resource.get_music(SONG_1);
sf::Text text("Hello SuperTeacher", *font, 50);
text.move(25,25);
const std::string bg = (*level)["background"];
auto bg_texture = resource.get_texture("graphics/backgrounds/" + bg + ".png");
bg_texture->setRepeated(true);
sf::Sprite bg_sprite;
bg_sprite.setTexture(*bg_texture);
bg_sprite.setTextureRect(sf::IntRect(0,0,1920,1080));
auto cloud_texture = resource.get_texture("graphics/tests/Items/cloud3.png");
sf::Sprite cloud_sprite;
cloud_sprite.setTexture(*cloud_texture);
cloud_sprite.move(200,200);
sf::Sprite cloud2_sprite;
cloud2_sprite.setTexture(*cloud_texture);
cloud2_sprite.move(400,175);
std::string gr_name = (*level)["ground"]["name"];
auto ground_texture = resource.get_texture("graphics/grounds/" + gr_name + "/top.png");
ground_texture->setRepeated(true);
sf::Sprite ground_sprite;
ground_sprite.setTexture(*ground_texture);
ground_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE));
ground_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] )));
auto ground_fill_texture = resource.get_texture("graphics/grounds/" + gr_name + "/fill.png");
ground_fill_texture->setRepeated(true);
sf::Sprite ground_fill_sprite;
ground_fill_sprite.setTexture(*ground_fill_texture);
ground_fill_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE*(SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] ) - 1));
ground_fill_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] - 1 )));
auto superteacher_texture = resource.get_texture("graphics/characters/superteacher.png");
sf::Sprite superteacher;
superteacher.setTexture(*superteacher_texture);
superteacher.move(0,720 - ( BLOCK_PXSIZE * ((SCREEN_Y_BLOCKS) - (int)(*level)["ground"]["level"] )));
user_input.HIEvent_sig.connect([&superteacher](HIEvent event)->void{
switch(event) {
case HIEvent::GO_LEFT:
superteacher.move(-10,0);
break;
case HIEvent::GO_RIGHT:
superteacher.move(10,0);
break;
case HIEvent::GO_UP:
superteacher.move(0, -10);
break;
case HIEvent::GO_DOWN:
superteacher.move(0, 10);
break;
default:
break;
}
});
song->play();
while(window.isOpen()){
user_input.process();
window.clear(sf::Color::White);
// Dessin
window.draw(bg_sprite);
window.draw(ground_sprite);
window.draw(ground_fill_sprite);
window.draw(cloud_sprite);
window.draw(cloud2_sprite);
window.draw(text);
window.draw(superteacher);
window.display();
}
LOG(info) << "Good bye, end of main process";
return 0;
}
<commit_msg>Speed adjustment<commit_after>#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "Constants.h"
#include "Path.h"
#include "AbstractView.h"
#include "ResourceManager.h"
#include "HIManager.h"
#include "Logs.h"
using namespace std;
int main(int argc, char *argv[]) {
log_init();
LOG(info) << "Superteacher is starting";
LOG(debug) << "SRC Directory: " << _SRC_DIR;
LOG(debug) << "Install Prefix: " << _INSTALL_PREFIX;
LOG(info) << "Opening window";
LOG(debug) << "Window size: " << SCREEN_X_PXSIZE << "x" << SCREEN_Y_PXSIZE;
ResourceManager resource = {};
auto config = resource.get_json("conf.json");
auto style = sf::Style::Default;
if((bool)(*config)["video"]["fullscreen"]){
style = sf::Style::Fullscreen;
}
sf::RenderWindow window(
sf::VideoMode(SCREEN_X_PXSIZE, SCREEN_Y_PXSIZE),
"SuperTeacher",
style
);
window.setFramerateLimit(50);
HIManager user_input = {&window};
user_input.HIEvent_sig.connect([&window](HIEvent event)->void{
switch(event) {
case HIEvent::CLOSE:
window.close();
break;
default:
break;
}
});
auto level = resource.get_json("levels/level.json");
auto font = resource.get_font(FONT_INDIE_FLOWER);
auto song = resource.get_music(SONG_1);
sf::Text text("Hello SuperTeacher", *font, 50);
text.move(25,25);
const std::string bg = (*level)["background"];
auto bg_texture = resource.get_texture("graphics/backgrounds/" + bg + ".png");
bg_texture->setRepeated(true);
sf::Sprite bg_sprite;
bg_sprite.setTexture(*bg_texture);
bg_sprite.setTextureRect(sf::IntRect(0,0,1920,1080));
auto cloud_texture = resource.get_texture("graphics/tests/Items/cloud3.png");
sf::Sprite cloud_sprite;
cloud_sprite.setTexture(*cloud_texture);
cloud_sprite.move(200,200);
sf::Sprite cloud2_sprite;
cloud2_sprite.setTexture(*cloud_texture);
cloud2_sprite.move(400,175);
std::string gr_name = (*level)["ground"]["name"];
auto ground_texture = resource.get_texture("graphics/grounds/" + gr_name + "/top.png");
ground_texture->setRepeated(true);
sf::Sprite ground_sprite;
ground_sprite.setTexture(*ground_texture);
ground_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE));
ground_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] )));
auto ground_fill_texture = resource.get_texture("graphics/grounds/" + gr_name + "/fill.png");
ground_fill_texture->setRepeated(true);
sf::Sprite ground_fill_sprite;
ground_fill_sprite.setTexture(*ground_fill_texture);
ground_fill_sprite.setTextureRect(sf::IntRect(0, 0, SCREEN_X_PXSIZE, BLOCK_PXSIZE*(SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] ) - 1));
ground_fill_sprite.move(0,SCREEN_Y_PXSIZE - (BLOCK_PXSIZE * (SCREEN_Y_BLOCKS - (int)(*level)["ground"]["level"] - 1 )));
auto superteacher_texture = resource.get_texture("graphics/characters/superteacher.png");
sf::Sprite superteacher;
superteacher.setTexture(*superteacher_texture);
superteacher.move(0,720 - ( BLOCK_PXSIZE * ((SCREEN_Y_BLOCKS) - (int)(*level)["ground"]["level"] )));
user_input.HIEvent_sig.connect([&superteacher](HIEvent event)->void{
switch(event) {
case HIEvent::GO_LEFT:
superteacher.move(-5,0);
break;
case HIEvent::GO_RIGHT:
superteacher.move(5,0);
break;
case HIEvent::GO_UP:
superteacher.move(0, -5);
break;
case HIEvent::GO_DOWN:
superteacher.move(0, 5);
break;
default:
break;
}
});
song->play();
while(window.isOpen()){
user_input.process();
window.clear(sf::Color::White);
// Dessin
window.draw(bg_sprite);
window.draw(ground_sprite);
window.draw(ground_fill_sprite);
window.draw(cloud_sprite);
window.draw(cloud2_sprite);
window.draw(text);
window.draw(superteacher);
window.display();
}
LOG(info) << "Good bye, end of main process";
return 0;
}
<|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 "libtorrent/pch.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
bool open(fs::path const& path, int mode)
{
close();
#if defined(_WIN32) && defined(UNICODE)
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
m_fd = ::_open(
#else
m_fd = ::open(
#endif
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode)
#ifdef _WIN32
, S_IREAD | S_IWRITE);
#else
, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
m_open_mode = mode;
return true;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
bool set_size(size_type s)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
std::stringstream msg;
msg << "ftruncate failed: '" << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
return true;
#endif
}
size_type seek(size_type offset, int m = 1)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << std::strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return -1;
}
return ret;
}
size_type tell()
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
std::string const& error() const
{
if (!m_error) m_error.reset(new std::string);
return *m_error;
}
int m_fd;
int m_open_mode;
mutable boost::scoped_ptr<std::string> m_error;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
bool file::open(fs::path const& p, file::open_mode m)
{
return m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
bool file::set_size(size_type s)
{
return m_impl->set_size(s);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
std::string const& file::error() const
{
return m_impl->error();
}
}
<commit_msg>removed hard coded file permission bits<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/pch.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
bool open(fs::path const& path, int mode)
{
close();
#if defined _WIN32 && defined UNICODE
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode));
#elif defined _WIN32
m_fd = ::_open(
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode));
#else
m_fd = ::open(
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode));
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
m_open_mode = mode;
return true;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
bool set_size(size_type s)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
std::stringstream msg;
msg << "ftruncate failed: '" << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
return true;
#endif
}
size_type seek(size_type offset, int m = 1)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << std::strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return -1;
}
return ret;
}
size_type tell()
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
std::string const& error() const
{
if (!m_error) m_error.reset(new std::string);
return *m_error;
}
int m_fd;
int m_open_mode;
mutable boost::scoped_ptr<std::string> m_error;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
bool file::open(fs::path const& p, file::open_mode m)
{
return m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
bool file::set_size(size_type s)
{
return m_impl->set_size(s);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
std::string const& file::error() const
{
return m_impl->error();
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "model.hpp"
#include "scanner.hpp"
#include "tokenizer.hpp"
int main()
{
model::Stack stack, stack2;
stack.push(new model::Integer(1));
stack.push(new model::Integer(2));
stack2.push(new model::Integer(3));
stack2.push(new model::Integer(4));
// スタックの内容確認
std::cout << "stack: " << stack.to_string() << std::endl;
std::cout << "stack2: " << stack2.to_string() << std::endl;
//////////////////
// オーバーライドの確認
model::Integer a(321);
model::Integer b(123);
std::cout << "321 + 123 = " << a.add(&b)->cast<model::Integer>()->get_data() << std::endl;
// スタックの結合確認
std::cout << "[ " << stack.to_string() << "] + [ " << stack2.to_string() << "] = ";
stack += stack2;
std::cout << stack.to_string() << std::endl;
// 関数実行確認
model::Instruction inst = model::Instruction::INST_PLUS;
inst.applicate(stack);
std::cout << "3 + 4 = " << stack.back()->cast<model::Integer>()->get_data() << std::endl;
// スタックの内容確認
/*
stack.pop();
stack.pop();
int i;
for (i = 0; i < 100; i++) {
stack.push(new model::Integer(i));
}
std::cout << "stack: " << stack.to_string() << std::endl;
for (i = 0; i < 100; i++) {
std::cout << ((model::Integer*)(stack.pop()))->data << std::endl;
}
*/
// stack1
// std::cout << stack.at(-1) << std::endl;
//
// Lexer testing
lexer::Tokenizer tokenizer("3 4");
model::Stack stack3 = tokenizer.tokenize().to_stack();
std::cout << "stack3: " << stack3.to_string() << std::endl;
// applicate check
lexer::Tokenizer tokenizer2("1 2 3 4 5 6 7 8 9 10");
model::Stack stack4 = tokenizer2.tokenize().to_stack();
std::cout << "stack4: " << stack4.to_string() << std::endl;
while (stack4.size() > 1) {
model::Instruction(model::Instruction::INST_PLUS).applicate(stack4);
}
std::cout << "stack4: " << stack4.to_string() << std::endl;
// String Tokenize Test
lexer::Tokenizer tokenizer3("1 2 3 + 4 \"string data example\" 12 34");
std::cout << "string data: " << tokenizer3.tokenize().to_stack().to_string() << std::endl;
// REPL
std::string input;
model::Stack stack5;
lexer::TokenVector tokvec;
while (true) {
std::cout << std::endl << "Input> ";
std::getline(std::cin, input);
lexer::Tokenizer* p_tokenizer = new lexer::Tokenizer(input);
tokvec = p_tokenizer->tokenize();
for (auto& tok : tokvec) {
if (tok.type == tokentype::T_INST_PLUS
|| tok.type == tokentype::T_INST_MINUS
|| tok.type == tokentype::T_INST_MULTIPLICATION
|| tok.type == tokentype::T_INST_DIVISION
) {
if (stack5.size() > 1) {
tok.to_element()->cast<model::Instruction>()->applicate(stack5);
} else {
std::cout << "Cannot Applicate Instruction" << std::endl;
}
} else if (tok.type == tokentype::T_INTEGER
|| tok.type == tokentype::T_FLOAT
|| tok.type == tokentype::T_STRING
|| tok.type == tokentype::T_NIL
) {
stack5.push(tok.to_element());
} else {
std::cout << "Unknown TokenType" << std::endl;
}
}
delete p_tokenizer;
std::cout << "Data Stack: " << stack5.to_string() << std::endl;
}
return 0;
}
<commit_msg>comment out test code<commit_after>#include <iostream>
#include "model.hpp"
#include "scanner.hpp"
#include "tokenizer.hpp"
int main()
{
/*
model::Stack stack, stack2;
stack.push(new model::Integer(1));
stack.push(new model::Integer(2));
stack2.push(new model::Integer(3));
stack2.push(new model::Integer(4));
// スタックの内容確認
std::cout << "stack: " << stack.to_string() << std::endl;
std::cout << "stack2: " << stack2.to_string() << std::endl;
//////////////////
// オーバーライドの確認
model::Integer a(321);
model::Integer b(123);
std::cout << "321 + 123 = " << a.add(&b)->cast<model::Integer>()->get_data() << std::endl;
// スタックの結合確認
std::cout << "[ " << stack.to_string() << "] + [ " << stack2.to_string() << "] = ";
stack += stack2;
std::cout << stack.to_string() << std::endl;
// 関数実行確認
model::Instruction inst = model::Instruction::INST_PLUS;
inst.applicate(stack);
std::cout << "3 + 4 = " << stack.back()->cast<model::Integer>()->get_data() << std::endl;
*/
// スタックの内容確認
/*
stack.pop();
stack.pop();
int i;
for (i = 0; i < 100; i++) {
stack.push(new model::Integer(i));
}
std::cout << "stack: " << stack.to_string() << std::endl;
for (i = 0; i < 100; i++) {
std::cout << ((model::Integer*)(stack.pop()))->data << std::endl;
}
*/
/*
// stack1
// std::cout << stack.at(-1) << std::endl;
//
// Lexer testing
lexer::Tokenizer tokenizer("3 4");
model::Stack stack3 = tokenizer.tokenize().to_stack();
std::cout << "stack3: " << stack3.to_string() << std::endl;
// applicate check
lexer::Tokenizer tokenizer2("1 2 3 4 5 6 7 8 9 10");
model::Stack stack4 = tokenizer2.tokenize().to_stack();
std::cout << "stack4: " << stack4.to_string() << std::endl;
while (stack4.size() > 1) {
model::Instruction(model::Instruction::INST_PLUS).applicate(stack4);
}
std::cout << "stack4: " << stack4.to_string() << std::endl;
// String Tokenize Test
lexer::Tokenizer tokenizer3("1 2 3 + 4 \"string data example\" 12 34");
std::cout << "string data: " << tokenizer3.tokenize().to_stack().to_string() << std::endl;
*/
// REPL
std::string input;
model::Stack stack5;
lexer::TokenVector tokvec;
while (true) {
std::cout << "Input> ";
std::getline(std::cin, input);
lexer::Tokenizer* p_tokenizer = new lexer::Tokenizer(input);
tokvec = p_tokenizer->tokenize();
for (auto& tok : tokvec) {
if (tok.type == tokentype::T_INST_PLUS
|| tok.type == tokentype::T_INST_MINUS
|| tok.type == tokentype::T_INST_MULTIPLICATION
|| tok.type == tokentype::T_INST_DIVISION
) {
if (stack5.size() > 1) {
tok.to_element()->cast<model::Instruction>()->applicate(stack5);
} else {
std::cout << "Cannot Applicate Instruction" << std::endl;
}
} else if (tok.type == tokentype::T_INTEGER
|| tok.type == tokentype::T_FLOAT
|| tok.type == tokentype::T_STRING
|| tok.type == tokentype::T_NIL
) {
stack5.push(tok.to_element());
} else {
std::cout << "Unknown TokenType" << std::endl;
}
}
delete p_tokenizer;
std::cout << "Data Stack: " << stack5.to_string() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
using namespace std;
//Global Variable vectors
vector<int> connect_Pos; //holds the positions of possible connectors in prompt
vector<int> kinds_of_connect; //holds what kind of connector are in prompt
void possible_connector(string prompt,int size)
{
for(int x = 0; x < size; x++)
{
if(prompt.at(x) == ';')
{
connect_Pos.push_back(x);
kinds_of_connect.push_back(0);
}
else if(prompt[x] == '|' && (x + 1 < size && prompt[x + 1] == '|'))
{
connect_Pos.push_back(x);
kinds_of_connect.push_back(1);
kinds_of_connect.push_back(1);
x++;
}
else if(prompt[x] == '&' && (x + 1 < size && prompt[x + 1] == '&'))
{
connect_Pos.push_back(x);
kinds_of_connect.push_back(2);
kinds_of_connect.push_back(2);
x++;
}
else
{
kinds_of_connect.push_back(-1);
}
}
}
int main(int argc, char **argv)
{
char prompt_holder[50000];
cout << "$ ";
string converter; //converts all bits of string into one piece
string to_be_tokenized;
getline(cin, to_be_tokenized);
for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
{
prompt_holder[x] = to_be_tokenized.at(x);
}
prompt_holder[to_be_tokenized.size()] = '\0';
possible_connector(to_be_tokenized ,to_be_tokenized.size());
int i = fork();
if(i == 0)
{
if(-1 == execvp(prompt_holder, argv))
{
perror("execvp");
}
}
else
{
cout << "hello world" << endl;
}
for(int x = 0; x < connect_Pos.size() ; x++)
{
cout << "Connect_pos: " << connect_Pos.at(x) << endl;
}
for(int x = 0; x < kinds_of_connect.size() ; x++)
{
cout << "kinds of connect: " << kinds_of_connect.at(x) << endl;
}
}
/* || && ;
succeeds ||
notsucceed &&
ls -a
[ls] [-a]
exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/
<commit_msg>calling it a night, still having trouble with parsing through string, almost there though<commit_after>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
using namespace std;
//Global Variable vectors
vector<int> connect_Pos; //holds the positions of possible connectors in prompt
vector<int> kinds_of_connect; //holds what kind of connector are in prompt
void possible_connector(string prompt,int size)
{
for(int x = 0; x < size; x++)
{
if(prompt.at(x) == ';')
{
connect_Pos.push_back(x);
kinds_of_connect.push_back(0);
}
else if(prompt[x] == '|' && (x + 1 < size && prompt[x + 1] == '|'))
{
connect_Pos.push_back(x);
kinds_of_connect.push_back(1);
kinds_of_connect.push_back(1);
x++;
}
else if(prompt[x] == '&' && (x + 1 < size && prompt[x + 1] == '&'))
{
connect_Pos.push_back(x);
kinds_of_connect.push_back(2);
kinds_of_connect.push_back(2);
x++;
}
else
{
kinds_of_connect.push_back(-1);
}
}
}
int main(int argc, char **argv)
{
vector <string> Vctr_of_commands;
char prompt_holder[50000];//orginal array to hold prompt
char *token;//used to break up using string tokenizer
cout << "$ ";
string converter; //converts all bits of string into one piece
string to_be_tokenized;
getline(cin, to_be_tokenized);
for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
{
prompt_holder[x] = to_be_tokenized.at(x);
}
prompt_holder[to_be_tokenized.size()] = '\0';
possible_connector(to_be_tokenized ,to_be_tokenized.size());
token = (prompt_holder);
cout << "output what is suppose to be tokenized" << endl;
while(token != NULL)
{
cout << token << endl;
char foo[10000] = {*token};
string s(foo);
cout << "output strings: " << s << endl;
Vctr_of_commands.push_back(s);
cout<< "What is suppose to output: " << Vctr_of_commands[0] << endl;
token = strtok(NULL, "|;&");
}
string finished_tok = strtok(prompt_holder, " &|;");
int i = fork();
if(i == 0)
{
if(-1 == execvp(prompt_holder, argv))
{
perror("execvp");
}
}
else
{
cout << "hello world" << endl;
}
for(unsigned int x = 0; x < connect_Pos.size() ; x++)
{
cout << "Connect_pos: " << connect_Pos.at(x) << endl;
}
for(unsigned int x = 0; x < kinds_of_connect.size() ; x++)
{
cout << "kinds of connect: " << kinds_of_connect.at(x) << endl;
}
}
/* || && ;
succeeds ||
notsucceed &&
ls -a
[ls] [-a]
exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/
<|endoftext|> |
<commit_before>/*The MIT License (MIT)
JSPlay Copyright (c) 2015 Jens Malmborg
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 <script/script-engine.h>
#include <audio/audio-manager.h>
#include <gl/glew.h>
#include <glfw/glfw3.h>
#include <memory>
int main(int argc, char *argv[]) {
if (!glfwInit()) {
//
}
std::unique_ptr<AudioManager> audio;
try {
audio = std::unique_ptr<AudioManager>(new AudioManager(nullptr));
}
catch (std::exception& error) {
//
}
ScriptEngine::current().Run(argv[1], argc, argv);
glfwTerminate();
return 0;
}<commit_msg>Fix for running without arguments.<commit_after>/*The MIT License (MIT)
JSPlay Copyright (c) 2015 Jens Malmborg
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 <script/script-engine.h>
#include <audio/audio-manager.h>
#include <gl/glew.h>
#include <glfw/glfw3.h>
#include <memory>
#include <iostream>
int main(int argc, char *argv[]) {
if (argc == 1) {
std::cout << "Script argument is missing" << std::endl;
return 0;
}
if (!glfwInit()) {
//
}
std::unique_ptr<AudioManager> audio;
try {
audio = std::unique_ptr<AudioManager>(new AudioManager(nullptr));
}
catch (std::exception& error) {
//
}
ScriptEngine::current().Run(argv[1], argc, argv);
glfwTerminate();
return 0;
}<|endoftext|> |
<commit_before>/*
This file is part of qNotesManager.
qNotesManager 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.
qNotesManager 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 qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include <stdio.h>
#include <stdlib.h>
#include "mainwindow.h"
#include <QTextCodec>
#include "application.h"
using namespace qNotesManager;
void myMessageOutput(QtMsgType type, const char *msg);
bool errorOutput;
int main(int argc, char** argv) {
QString helpScreenText = QString().append("Usage: \n").append(APPNAME).append(
" [-v] [-h] [options] [file]\n"
"-v, --version Print version and exit.\n"
"-h, --help Print this screen\n"
"Options:\n"
"-s, --silent Do not send data to stderr\n"
"-fo FILE, --file-output FILE Send debug output to file FILE\n\n"
"file File to open\n");
errorOutput = true;
QApplication app(argc, argv);
app.setQuitOnLastWindowClosed(false);
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QStringList arguments = QCoreApplication::arguments();
if (arguments.count() > 1) {
arguments.removeAt(0);
if (arguments.count() == 1) {
QString arg = arguments.at(0);
if (arg == "-v" || arg == "--version") {
fprintf(stdout, "%s version: %s\n", APPNAME, VERSION); // FIXME: add actual version
return 0;
} else if (arg == "-h" || arg == "--help") {
fprintf(stdout, qPrintable(helpScreenText));
return 0;
}
if (arguments.contains("-no") || arguments.contains("--no-output")) {
errorOutput = false;
}
}
}
qInstallMsgHandler(myMessageOutput);
Application::I()->Settings.Load();
MainWindow w;
QObject::connect(&app, SIGNAL(aboutToQuit()), &w, SLOT(sl_QApplication_AboutToQuit()));
if (Application::I()->Settings.ShowWindowOnStart) {
w.show();
} else {
w.hide();
}
if (Application::I()->Settings.OpenLastDocumentOnStart &&
!Application::I()->Settings.LastDocumentName.isEmpty()) {
w.OpenDocument(Application::I()->Settings.LastDocumentName);
}
return app.exec();
}
void myMessageOutput(QtMsgType type, const char *msg) {
if (!errorOutput) {
if (type == QtFatalMsg) {
abort();
}
return;
}
switch (type) {
case QtDebugMsg:
#ifdef DEBUG
fprintf(stderr, "Debug: %s\n", msg);
#endif
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg);
abort();
}
}
<commit_msg>Last opened file existence check added<commit_after>/*
This file is part of qNotesManager.
qNotesManager 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.
qNotesManager 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 qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include <QTextCodec>
#include <QFileInfo>
#include <stdio.h>
#include <stdlib.h>
#include "mainwindow.h"
#include "application.h"
using namespace qNotesManager;
void myMessageOutput(QtMsgType type, const char *msg);
bool errorOutput;
int main(int argc, char** argv) {
QString helpScreenText = QString().append("Usage: \n").append(APPNAME).append(
" [-v] [-h] [options] [file]\n"
"-v, --version Print version and exit.\n"
"-h, --help Print this screen\n"
"Options:\n"
"-s, --silent Do not send data to stderr\n"
"-fo FILE, --file-output FILE Send debug output to file FILE\n\n"
"file File to open\n");
errorOutput = true;
QApplication app(argc, argv);
app.setQuitOnLastWindowClosed(false);
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QStringList arguments = QCoreApplication::arguments();
if (arguments.count() > 1) {
arguments.removeAt(0);
if (arguments.count() == 1) {
QString arg = arguments.at(0);
if (arg == "-v" || arg == "--version") {
fprintf(stdout, "%s version: %s\n", APPNAME, VERSION); // FIXME: add actual version
return 0;
} else if (arg == "-h" || arg == "--help") {
fprintf(stdout, qPrintable(helpScreenText));
return 0;
}
if (arguments.contains("-no") || arguments.contains("--no-output")) {
errorOutput = false;
}
}
}
qInstallMsgHandler(myMessageOutput);
Application::I()->Settings.Load();
MainWindow w;
QObject::connect(&app, SIGNAL(aboutToQuit()), &w, SLOT(sl_QApplication_AboutToQuit()));
if (Application::I()->Settings.ShowWindowOnStart) {
w.show();
} else {
w.hide();
}
if (Application::I()->Settings.OpenLastDocumentOnStart &&
!Application::I()->Settings.LastDocumentName.isEmpty() &&
QFileInfo(Application::I()->Settings.LastDocumentName).exists()) {
w.OpenDocument(Application::I()->Settings.LastDocumentName);
}
return app.exec();
}
void myMessageOutput(QtMsgType type, const char *msg) {
if (!errorOutput) {
if (type == QtFatalMsg) {
abort();
}
return;
}
switch (type) {
case QtDebugMsg:
#ifdef DEBUG
fprintf(stderr, "Debug: %s\n", msg);
#endif
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg);
abort();
}
}
<|endoftext|> |
<commit_before>#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/heap/priority_queue.hpp>
#include <boost/graph/graphviz.hpp>
#include <gameai/point2.hpp>
#include <gameai/astar_vertex.hpp>
struct vertex_pos_t { typedef boost::vertex_property_tag kind; };
struct edge_label_t { typedef boost::edge_property_tag kind; };
typedef boost::property<vertex_pos_t, gameai::point2<int>> vertex_pos_p;
typedef boost::property<boost::vertex_name_t, unsigned int, vertex_pos_p> vertex_p;
typedef boost::property<boost::edge_weight_t, unsigned int> edge_p;
typedef boost::no_property graph_p;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_p, edge_p, graph_p> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t;
typedef gameai::astar_vertex<vertex_t> astar_vertex_t;
template<typename T> class inverse_comparator {
public:
bool operator()(const T &lhs, const T &rhs) const {
return lhs > rhs;
}
};
int main(int argc, char **argv) {
std::ifstream in("assets/graph.dot");
graph_t g;
boost::dynamic_properties dp(boost::ignore_other_properties);
dp.property("node_id", boost::get(boost::vertex_name, g));
dp.property("pos", boost::get(vertex_pos_t(), g));
dp.property("label", boost::get(boost::edge_weight, g));
boost::read_graphviz(in, g, dp);
boost::unordered_map<int, vertex_t> vertex_map;
BGL_FORALL_VERTICES(v, g, graph_t) {
vertex_map.emplace(boost::get(boost::vertex_name, g, v), v);
}
/* a heap-based priority queue is used to retrive the lowest-cost open node in O(1)
* hash-based sets are used to lookup nodes in O(1)
*/
boost::heap::priority_queue<astar_vertex_t, boost::heap::compare<inverse_comparator<astar_vertex_t>>> open_heap;
boost::unordered_set<astar_vertex_t> open_set;
boost::unordered_set<astar_vertex_t> closed_set;
astar_vertex_t v{0, 0, 1, vertex_map.at(1)};
open_heap.emplace(v);
open_set.emplace(v);
while(!open_heap.empty()) {
auto current = open_heap.top();
open_heap.pop();
open_set.erase(current);
std::cout << boost::get(boost::vertex_name, g, current.vertex) << std::endl;
BOOST_FOREACH(auto edge, boost::out_edges(current.vertex, g)) {
auto target = boost::target(edge, g);
auto n = boost::get(boost::vertex_name, g, target);
if(n == 61) {
/* contrary to popular belief, goto is perfectly safe in C++
* in fact, it conforms to C++ scope and object lifetime
* so this is a perfectly valid optimization
*/
goto end;
}
auto dist_to_here = gameai::distance_squared(boost::get(vertex_pos_t(), g, current.vertex),
boost::get(vertex_pos_t(), g, target));
auto dist_to_end = gameai::distance_squared(boost::get(vertex_pos_t(), g, target),
boost::get(vertex_pos_t(), g, vertex_map.at(61)));
astar_vertex_t next{current.base_cost + dist_to_here, dist_to_end, n, target};
}
closed_set.emplace(current);
}
end:
return 0;
}
<commit_msg>main: finish implementing A*<commit_after>#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/heap/priority_queue.hpp>
#include <boost/graph/graphviz.hpp>
#include <gameai/point2.hpp>
#include <gameai/astar_vertex.hpp>
struct vertex_pos_t { typedef boost::vertex_property_tag kind; };
struct edge_label_t { typedef boost::edge_property_tag kind; };
typedef boost::property<vertex_pos_t, gameai::point2<int>> vertex_pos_p;
typedef boost::property<boost::vertex_name_t, unsigned int, vertex_pos_p> vertex_p;
typedef boost::property<boost::edge_weight_t, unsigned int> edge_p;
typedef boost::no_property graph_p;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_p, edge_p, graph_p> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t;
typedef gameai::astar_vertex<vertex_t> astar_vertex_t;
template<typename T> class inverse_comparator {
public:
bool operator()(const T &lhs, const T &rhs) const {
return lhs > rhs;
}
};
int main(int argc, char **argv) {
std::ifstream in("assets/graph.dot");
graph_t g;
boost::dynamic_properties dp(boost::ignore_other_properties);
dp.property("node_id", boost::get(boost::vertex_name, g));
dp.property("pos", boost::get(vertex_pos_t(), g));
dp.property("label", boost::get(boost::edge_weight, g));
boost::read_graphviz(in, g, dp);
boost::unordered_map<int, vertex_t> vertex_map;
BGL_FORALL_VERTICES(v, g, graph_t) {
vertex_map.emplace(boost::get(boost::vertex_name, g, v), v);
}
/* a heap-based priority queue is used to retrive the lowest-cost open node in O(1)
* hash-based sets are used to lookup nodes in O(1)
*/
boost::heap::priority_queue<astar_vertex_t, boost::heap::compare<inverse_comparator<astar_vertex_t>>> open_heap;
boost::unordered_set<astar_vertex_t> open_set;
boost::unordered_set<astar_vertex_t> closed_set;
astar_vertex_t v{0, 0, 1, vertex_map.at(1)};
open_heap.emplace(v);
open_set.emplace(v);
while(!open_heap.empty()) {
auto current = open_heap.top();
open_heap.pop();
open_set.erase(current);
std::cout << boost::get(boost::vertex_name, g, current.vertex) << std::endl;
BOOST_FOREACH(auto edge, boost::out_edges(current.vertex, g)) {
auto target = boost::target(edge, g);
auto n = boost::get(boost::vertex_name, g, target);
if(n == 61) {
/* contrary to popular belief, goto is perfectly safe in C++
* in fact, it conforms to C++ scope and object lifetime
* so this is a perfectly valid optimization
*/
goto end;
}
auto w = boost::get(boost::edge_weight, g, edge);
auto dist_to_end = gameai::distance_squared(boost::get(vertex_pos_t(), g, target),
boost::get(vertex_pos_t(), g, vertex_map.at(61)));
astar_vertex_t next{current.base_cost + w, dist_to_end, n, target};
auto open_find = open_set.find(next);
if(open_find != open_set.end() && open_find->total_cost() < next.total_cost()) { continue; }
auto closed_find = closed_set.find(next);
if(closed_find != closed_set.end() && closed_find->total_cost() < next.total_cost()) { continue; }
open_heap.emplace(next);
open_set.emplace(next);
}
closed_set.emplace(current);
}
end:
std::cout << 61 << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>
#include "Emulator.hpp"
void printHelpMessage() {
std::cout
<< "A NES emulator. Takes .nes files.\n\n"
<< "Usage: turbones [options] <path-to-rom-file>\n\n"
<< "Options:\n"
<< "\t-h --help\n"
<< "\t\tPrint this help text and exit."
<< std::endl;
}
void handleArguments(const int& argc, char* argv[], Emulator& emulator) {
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-h"
|| arg == "--help") {
printHelpMessage();
exit(EXIT_SUCCESS);
}
else if (i == argc - 1) {
emulator.rom_path = arg;
}
else {
std::cerr << "Unrecognized argument: " << arg << std::endl; }
}
}
int main(const int argc, char* argv[]) {
Emulator emulator;
handleArguments(argc, argv, emulator);
try {
emulator.run();
}
catch (const std::runtime_error& e) {
std::cerr << "\nFailed to run (" << e.what() << "). Shutting down." << std::endl;
// The pause here is to make sure the error can be read.
std::cout << "Press Enter to exit . . . ";
// Waits until Enter ('\n') is pressed. It turns out to be simpler
// to write this portably, if we wait for Enter, rather than "any key".
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return EXIT_FAILURE;
}
}<commit_msg>Extricate failure shutdown code into separate function<commit_after>#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>
#include "Emulator.hpp"
void printHelpMessage() {
std::cout
<< "A NES emulator. Takes .nes files.\n\n"
<< "Usage: turbones [options] <path-to-rom-file>\n\n"
<< "Options:\n"
<< "\t-h --help\n"
<< "\t\tPrint this help text and exit."
<< std::endl;
}
void handleArguments(const int& argc, char* argv[], Emulator& emulator) {
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-h"
|| arg == "--help") {
printHelpMessage();
exit(EXIT_SUCCESS);
}
else if (i == argc - 1) {
emulator.rom_path = arg;
}
else {
std::cerr << "Unrecognized argument: " << arg << std::endl; }
}
}
// Prints failure message, and then waits until Enter ('\n') is pressed,
// so there's time for the message to be read, in case the console closes itself immediately afterwards.
// It turns out to be simpler to write this portably, if we wait for Enter, rather than "any key".
void printFailureAndWait(const std::runtime_error& e) {
std::cerr
<< "\nFailed to run (" << e.what() << "). Shutting down.\n"
<< "Press Enter to exit . . . " << std::flush;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Wait for enter key.
}
int main(const int argc, char* argv[]) {
Emulator emulator;
handleArguments(argc, argv, emulator);
try {
emulator.run(); }
catch (const std::runtime_error& e) {
printFailureAndWait(e);
return EXIT_FAILURE;
}
}<|endoftext|> |
<commit_before>/**
* LED Strip host.
*
* Turns LEDs red (for now)
*/
#include "Arduino.h"
#include <FastLED.h>
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif
#define NUM_LEDS 300
#define DATA_PIN 6
CRGB leds[NUM_LEDS];
int count = 0;
void setup()
{
// Init fastled
FastLED.addLeds<WS2812, DATA_PIN, BGR>(leds, NUM_LEDS);
}
void loop()
{
int i;
for (i=0;i<=count;i++)
leds[i] = CRGB::Blue;
for (;i<NUM_LEDS;i++)
leds[i] = CRGB::White;
count++;
if (count >= NUM_LEDS)
count = 0;
FastLED.show();
// wait for a second
delay(100);
}
<commit_msg>Did something and worked.<commit_after>/**
* LED Strip host.
*
* Turns LEDs red (for now)
*/
#include "Arduino.h"
#include <FastLED.h>
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif
#define NUM_LEDS 300
#define DATA_PIN 6
CRGB leds[NUM_LEDS];
int count = 0;
void setup()
{
// Init fastled
pinMode(LED_BUILTIN, OUTPUT);
FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
for (int i=0;i<NUM_LEDS;i++)
leds[i] = CRGB::White;
FastLED.show();
}
void loop()
{
// turn the LED on (HIGH is the voltage level)
digitalWrite(LED_BUILTIN, HIGH);
int i = 0;
for (;i<count;i++)
leds[i] = CRGB::Blue;
for (;i<NUM_LEDS;i++)
leds[i] = CRGB::Green;
count = (count+1) % NUM_LEDS;
FastLED.show();
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>
#include <Espfc.h>
#include <Kalman.h>
#include <Madgwick.h>
#include <Mahony.h>
#include <printf.h>
#include <blackbox/blackbox.h>
#include <EspSoftSerial.h>
#include <EspGpio.h>
#include <EscDriver.h>
#include <EspWire.h>
#if defined(ESP32)
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <WiFi.h>
#if !CONFIG_FREERTOS_UNICORE
#define ESPFC_DUAL_CORE 1
#endif
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
Espfc::Espfc espfc;
#if defined(ESPFC_DUAL_CORE)
void otherTask(void *pvParameters)
{
while(true) espfc.updateOther();
}
#endif
void setup()
{
espfc.begin();
#if defined(ESPFC_DUAL_CORE)
xTaskCreatePinnedToCore(otherTask, "otherTask", 8192, NULL, 1, NULL, 0); // run on PRO(0) core, loopTask is on APP(1)
#endif
}
void loop()
{
espfc.update();
#if !defined(ESPFC_DUAL_CORE)
espfc.updateOther();
#endif
}<commit_msg>fixes #10 - esp32 disable core0 wdt<commit_after>#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>
#include <Espfc.h>
#include <Kalman.h>
#include <Madgwick.h>
#include <Mahony.h>
#include <printf.h>
#include <blackbox/blackbox.h>
#include <EspSoftSerial.h>
#include <EspGpio.h>
#include <EscDriver.h>
#include <EspWire.h>
#if defined(ESP32)
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
//#include "esp_task_wdt.h"
#include <WiFi.h>
#if !CONFIG_FREERTOS_UNICORE
#define ESPFC_DUAL_CORE 1
TaskHandle_t otherTaskHandle = NULL;
#endif
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
Espfc::Espfc espfc;
#if defined(ESPFC_DUAL_CORE)
void otherTask(void *pvParameters)
{
//esp_task_wdt_add(otherTaskHandle);
while(true)
{
//esp_task_wdt_reset();
espfc.updateOther();
}
}
#endif
void setup()
{
espfc.begin();
#if defined(ESPFC_DUAL_CORE)
disableCore0WDT();
xTaskCreatePinnedToCore(otherTask, "otherTask", 8192, NULL, 1, &otherTaskHandle, 0); // run on PRO(0) core, loopTask is on APP(1)
#endif
}
void loop()
{
espfc.update();
#if !defined(ESPFC_DUAL_CORE)
espfc.updateOther();
#endif
}<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include <memory>
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
// Print the whole module after each pass, which requires disabling
// multi-threading as well.
pm->getContext()->disableMultithreading();
pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
/*print_module_scope=*/true));
pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
} // namespace
namespace TFTPU {
namespace {
tensorflow::Status RunTPUBridge(
ModuleOp module, bool enable_logging,
llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
PassManager bridge(module.getContext());
::tensorflow::applyTensorflowAndCLOptions(bridge);
if (enable_logging || VLOG_IS_ON(1)) {
tensorflow::DumpMlirOpToFile("tpu_bridge_before", module);
if (VLOG_IS_ON(2)) EnableLogging(&bridge);
}
// Populate a passmanager with the list of passes that implement the bridge.
pipeline_builder(bridge);
// Add set of passes to lower back to graph (from tf_executor).
TF::AddGraphExportLoweringPasses(bridge);
// Run the bridge on the module, in case of failure, the `diag_handler`
// converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
if (enable_logging || VLOG_IS_ON(1))
tensorflow::DumpMlirOpToFile("tpu_bridge_after", module);
return diag_handler.ConsumeStatus();
}
} // namespace
void CreateTPUBridgePipeline(OpPassManager &pm) {
// The following ops must be preserved regardless of reachability. Ideally,
// all graphs should have control dependencies to enforce this but this is
// currently not the case (see b/177478741).
const llvm::SmallVector<std::string, 4> ops_to_preserve = {
"tf.TPUReplicateMetadata", "tf.TPUCompilationResult",
"tf.TPUReplicatedInput", "tf.TPUReplicatedOutput"};
pm.addNestedPass<FuncOp>(
tf_executor::CreateTFExecutorGraphPruningPass(ops_to_preserve));
// It is assumed at this stage there are no V1 control flow ops as Graph
// functionalization is ran before import. Ops can be lifted out of
// tf_executor dialect islands/graphs.
pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
// Run shape inference so that tf_executor/tf_device ops created later will
// likely to inherit more concrete types.
pm.addPass(TF::CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(CreateTPUReorderReplicateAndPartitionedInputsPass());
// Encode this in its own scope so that func_pm is not mistakenly used
// later on.
{
pm.addPass(CreateTPUClusterFormationPass());
OpPassManager &func_pm = pm.nest<FuncOp>();
// Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
// because DecomposeResourceOpsPass uses pattern rewriter which hoists
// changed constants out of tf_device.Launch.
func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
func_pm.addPass(CreateTPUHostComputationExpansionPass());
func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());
}
// Run another shape inference pass because resource decomposition might have
// created new partial types.
pm.addPass(TF::CreateTFShapeInferencePass());
// Note that the region-based control-flow produced here still contains
// function call ops which get inlined by the subsequent inliner pass.
pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());
pm.addPass(mlir::createInlinerPass());
pm.addPass(CreateTPUClusterCleanupAttributesPass());
pm.addPass(TFDevice::CreateResourceOpLiftingPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());
pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
pm.addPass(CreateTPUExtractOutsideCompilationPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateClusterConstantSinkingPass());
pm.addPass(TF::CreateResourceDeviceInferencePass());
pm.addPass(TFDevice::CreateClusterOutliningPass());
pm.addPass(CreateTPUDynamicPaddingMapperPass());
pm.addPass(CreateTPUResourceReadForWritePass());
pm.addPass(CreateTPUShardingIdentificationPass());
pm.addNestedPass<FuncOp>(CreateTPUResourceReadsWritesPartitioningPass());
pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
pm.addPass(CreateTPURewritePass());
pm.addPass(createSymbolDCEPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
pm.addNestedPass<FuncOp>(CreateTPUColocateCompositeResourceOps());
pm.addPass(CreateTPUVariableReformattingPass());
pm.addPass(TF::CreateTFRegionControlFlowToFunctional());
}
void CreateTPUBridgePipelineV1(OpPassManager &pm) {
pm.addPass(TF::CreateTFShapeInferencePass());
// For V1 compatibility, we process a module where the graph does not have
// feeds and fetched. We extract first the TPU computation in a submodule,
// where it'll be in a function with args and returned values, much more like
// a TF v2 module. We can then run the usual pipeline on this nested module.
// Afterward we inline back in the parent module and delete the nested one.
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
OpPassManager &nested_module = pm.nest<ModuleOp>();
CreateTPUBridgePipeline(nested_module);
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}
tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}
} // namespace TFTPU
namespace TF {
void AddGraphExportLoweringPasses(OpPassManager &pm) {
auto add_pass = [&](std::unique_ptr<Pass> pass) {
pm.addNestedPass<FuncOp>(std::move(pass));
pm.addPass(CreateBreakUpIslandsPass());
};
add_pass(CreateFunctionalToExecutorDialectConversionPass());
add_pass(TFDevice::CreateReplicateToIslandPass());
add_pass(TFDevice::CreateParallelExecuteToIslandsPass());
add_pass(TFDevice::CreateLaunchToDeviceAttributePass());
pm.addNestedPass<FuncOp>(TFTPU::CreateTPUDevicePropagationPass());
pm.addPass(createSymbolDCEPass());
pm.addPass(CreateVerifySuitableForExportPass());
}
tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
bool enable_logging,
bool enable_inliner) {
PassManager bridge(module.getContext());
if (enable_logging || VLOG_IS_ON(1)) {
tensorflow::DumpMlirOpToFile("standard_pipeline_before", module);
if (VLOG_IS_ON(2)) EnableLogging(&bridge);
}
StandardPipelineOptions pipeline_options;
pipeline_options.enable_inliner.setValue(enable_inliner);
CreateTFStandardPipeline(bridge, pipeline_options);
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
if (enable_logging || VLOG_IS_ON(1))
tensorflow::DumpMlirOpToFile("standard_pipeline_after", module);
return diag_handler.ConsumeStatus();
}
} // namespace TF
} // namespace mlir
<commit_msg>Enable pass to drop shape_invariant attribute from while ops in bridge and perform shape inference and canonicalization after it.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include <memory>
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
// Print the whole module after each pass, which requires disabling
// multi-threading as well.
pm->getContext()->disableMultithreading();
pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
/*print_module_scope=*/true));
pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
} // namespace
namespace TFTPU {
namespace {
tensorflow::Status RunTPUBridge(
ModuleOp module, bool enable_logging,
llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
PassManager bridge(module.getContext());
::tensorflow::applyTensorflowAndCLOptions(bridge);
if (enable_logging || VLOG_IS_ON(1)) {
tensorflow::DumpMlirOpToFile("tpu_bridge_before", module);
if (VLOG_IS_ON(2)) EnableLogging(&bridge);
}
// Populate a passmanager with the list of passes that implement the bridge.
pipeline_builder(bridge);
// Add set of passes to lower back to graph (from tf_executor).
TF::AddGraphExportLoweringPasses(bridge);
// Run the bridge on the module, in case of failure, the `diag_handler`
// converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
if (enable_logging || VLOG_IS_ON(1))
tensorflow::DumpMlirOpToFile("tpu_bridge_after", module);
return diag_handler.ConsumeStatus();
}
} // namespace
void CreateTPUBridgePipeline(OpPassManager &pm) {
// The following ops must be preserved regardless of reachability. Ideally,
// all graphs should have control dependencies to enforce this but this is
// currently not the case (see b/177478741).
const llvm::SmallVector<std::string, 4> ops_to_preserve = {
"tf.TPUReplicateMetadata", "tf.TPUCompilationResult",
"tf.TPUReplicatedInput", "tf.TPUReplicatedOutput"};
pm.addNestedPass<FuncOp>(
tf_executor::CreateTFExecutorGraphPruningPass(ops_to_preserve));
// It is assumed at this stage there are no V1 control flow ops as Graph
// functionalization is ran before import. Ops can be lifted out of
// tf_executor dialect islands/graphs.
pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
// Run shape inference so that tf_executor/tf_device ops created later will
// likely to inherit more concrete types.
pm.addPass(TF::CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(CreateTPUReorderReplicateAndPartitionedInputsPass());
// Encode this in its own scope so that func_pm is not mistakenly used
// later on.
{
pm.addPass(CreateTPUClusterFormationPass());
OpPassManager &func_pm = pm.nest<FuncOp>();
// Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
// because DecomposeResourceOpsPass uses pattern rewriter which hoists
// changed constants out of tf_device.Launch.
func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
func_pm.addPass(CreateTPUHostComputationExpansionPass());
func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());
}
// Note that the region-based control-flow produced here still contains
// function call ops which get inlined by the subsequent inliner pass.
pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());
pm.addPass(mlir::createInlinerPass());
pm.addNestedPass<FuncOp>(
TF::CreateDropWhileShapeInvariantInDeviceClusterPass());
// Run another shape inference pass because resource decomposition might have
// created new partial types. Also, after dropping `shape_invariant` attribute
// from While/WhileRegion ops within cluster would lead to more precise
// shapes.
pm.addPass(TF::CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(createCanonicalizerPass());
pm.addPass(CreateTPUClusterCleanupAttributesPass());
pm.addPass(TFDevice::CreateResourceOpLiftingPass());
pm.addNestedPass<FuncOp>(createCSEPass());
pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());
pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
pm.addPass(CreateTPUExtractOutsideCompilationPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateClusterConstantSinkingPass());
pm.addPass(TF::CreateResourceDeviceInferencePass());
pm.addPass(TFDevice::CreateClusterOutliningPass());
pm.addPass(CreateTPUDynamicPaddingMapperPass());
pm.addPass(CreateTPUResourceReadForWritePass());
pm.addPass(CreateTPUShardingIdentificationPass());
pm.addNestedPass<FuncOp>(CreateTPUResourceReadsWritesPartitioningPass());
pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
pm.addPass(CreateTPURewritePass());
pm.addPass(createSymbolDCEPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
pm.addNestedPass<FuncOp>(CreateTPUColocateCompositeResourceOps());
pm.addPass(CreateTPUVariableReformattingPass());
pm.addPass(TF::CreateTFRegionControlFlowToFunctional());
}
void CreateTPUBridgePipelineV1(OpPassManager &pm) {
pm.addPass(TF::CreateTFShapeInferencePass());
// For V1 compatibility, we process a module where the graph does not have
// feeds and fetched. We extract first the TPU computation in a submodule,
// where it'll be in a function with args and returned values, much more like
// a TF v2 module. We can then run the usual pipeline on this nested module.
// Afterward we inline back in the parent module and delete the nested one.
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
OpPassManager &nested_module = pm.nest<ModuleOp>();
CreateTPUBridgePipeline(nested_module);
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}
tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}
} // namespace TFTPU
namespace TF {
void AddGraphExportLoweringPasses(OpPassManager &pm) {
auto add_pass = [&](std::unique_ptr<Pass> pass) {
pm.addNestedPass<FuncOp>(std::move(pass));
pm.addPass(CreateBreakUpIslandsPass());
};
add_pass(CreateFunctionalToExecutorDialectConversionPass());
add_pass(TFDevice::CreateReplicateToIslandPass());
add_pass(TFDevice::CreateParallelExecuteToIslandsPass());
add_pass(TFDevice::CreateLaunchToDeviceAttributePass());
pm.addNestedPass<FuncOp>(TFTPU::CreateTPUDevicePropagationPass());
pm.addPass(createSymbolDCEPass());
pm.addPass(CreateVerifySuitableForExportPass());
}
tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
bool enable_logging,
bool enable_inliner) {
PassManager bridge(module.getContext());
if (enable_logging || VLOG_IS_ON(1)) {
tensorflow::DumpMlirOpToFile("standard_pipeline_before", module);
if (VLOG_IS_ON(2)) EnableLogging(&bridge);
}
StandardPipelineOptions pipeline_options;
pipeline_options.enable_inliner.setValue(enable_inliner);
CreateTFStandardPipeline(bridge, pipeline_options);
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
if (enable_logging || VLOG_IS_ON(1))
tensorflow::DumpMlirOpToFile("standard_pipeline_after", module);
return diag_handler.ConsumeStatus();
}
} // namespace TF
} // namespace mlir
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <DNSServer.h>
#include <Ticker.h>
#include "helpers.hpp"
#include "defaults.hpp"
#include "radio.hpp"
#include "Config.hpp"
#include "TrackingData.hpp"
#include "ConfigServer.hpp"
#define DNS_PORT 53
Ticker wifiBlinker;
Config* conf = new Config();
Radio rf(conf);
TrackingData data(conf, DEFAULT_BUFFER_SIZE);
ConfigServer cfgSrv(conf, 80);
WebSocketsServer webSocket(81);
DNSServer dnsServer;
IPAddress localIP(10, 10, 10, 1);
void setup () {
// Set up the EEPROM w/ a maximum size of 4096 bytes
EEPROM.begin(4096);
/// Set up the built-in LED and turn it on to let the user know the ESP is working
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
/// Open up the serial and TCP monitor
Terminal::begin(115200);
// Print some stats
Terminal::printf("CPU running at %dMHz, Cycle %d, Flash chip running at %d MHz, VCC is at %d\n", ESP.getCpuFreqMHz(), ESP.getCycleCount(), ESP.getFlashChipSpeed()/1000000, ESP.getVcc());
// If the pin is not pulled to ground read config or write the default one if its not
if (digitalRead(RESET_CONF_PIN)) {
conf->read(EEPROM_CONF_ADDR);
} else {
Terminal::println("Restoring factory settings...");
conf->write(EEPROM_CONF_ADDR);
}
// If the pin is pulled to ground then disable tracking
if (!digitalRead(DISABLE_TRACKING_PIN)) {
Terminal::println("Disabling tracking...");
conf->readFromString("{'active': false}");
conf->write(EEPROM_CONF_ADDR);
}
// Set the hostname
WiFi.hostname("FINDTracker");
// Setup the radios according to the configuration
rf.setup();
MDNS.begin("FINDTracker");
MDNS.addService("http", "tcp", 80);
// Setup the OTA server
OTA();
// Setup the websocket server
webSocket.begin();
// Setup the DNS server
dnsServer.setTTL(300);
dnsServer.setErrorReplyCode(DNSReplyCode::ServerFailure);
dnsServer.start(DNS_PORT, "findtracker", localIP);
}
void runServerHandlers() {
ArduinoOTA.handle();
cfgSrv.handle();
Terminal::handle();
webSocket.loop();
dnsServer.processNextRequest();
}
int lastWatchdog;
int sleepTimeMS;
int lastScan;
int lastUpdate;
bool connected;
bool active;
void loop() {
if (millis() - lastUpdate > 1500) {
connected = rf.connected();
active = conf->get<bool>("active");
lastUpdate = millis();
}
// Check for a WiFi connection and attempt to reestablish it if it died
if (
(active && !connected) ||
(!active && !connected && millis() - lastScan > 30000)
) {
digitalWrite(LED_PIN, LOW);
if (!rf.connect()) {
Terminal::print("Connection failed. ");
if (active) {
// Enter deep sleep in case the connection failed
sleepTimeMS = conf->get<int>("wifiReconnectionInterval");
blink(); blink(); blink();
Terminal::printf("Entering deep sleep mode for %dms ...\n", sleepTimeMS);
ESP.deepSleep(sleepTimeMS * 1000, WAKE_NO_RFCAL);
} else {
Terminal::println("");
wifiBlinker.attach(0.5, blinkSync);
}
} else {
wifiBlinker.detach();
digitalWrite(LED_PIN, HIGH);
}
lastScan = millis();
}
// TODO: The data.send() step takes way too long
if (active) {
/// Update the environment data (scan for networks)
if (data.update()) {
// Send the data to the FIND Server
String response = data.send();
/// Blink to indicate that we have sent our location
if (response != "") {
blink();
webSocket.broadcastTXT(response);
}
}
// Enter a very basic sleep mode and limit the amount of cycles to preserve power
// (Turn off the radio and wake it up periodically to answer beacon signals from router)
// TODO Only do this when nothing else is connected (low power mode setting maybe?)
// since it breaks all kind of things like websockets, HTTP etc.
WiFi.setSleepMode(WIFI_MODEM_SLEEP);
delay(500);
} else {
/// Let some background tasks run
delay(100);
yield();
}
/// Run all kinds of server handlers
runServerHandlers();
// Send a watchdog signal for all websocket clients
if (millis() - lastWatchdog > 5000) {
webSocket.broadcastTXT("watchdog");
lastWatchdog = millis();
}
}
<commit_msg>Removed startup delay<commit_after>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <DNSServer.h>
#include <Ticker.h>
#include "helpers.hpp"
#include "defaults.hpp"
#include "radio.hpp"
#include "Config.hpp"
#include "TrackingData.hpp"
#include "ConfigServer.hpp"
#define DNS_PORT 53
Ticker wifiBlinker;
Config* conf = new Config();
Radio rf(conf);
TrackingData data(conf, DEFAULT_BUFFER_SIZE);
ConfigServer cfgSrv(conf, 80);
WebSocketsServer webSocket(81);
DNSServer dnsServer;
IPAddress localIP(10, 10, 10, 1);
void setup () {
// Set up the EEPROM w/ a maximum size of 4096 bytes
EEPROM.begin(4096);
/// Set up the built-in LED and turn it on to let the user know the ESP is working
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
/// Open up the serial and TCP monitor
Terminal::begin(115200);
// Print some stats
Terminal::printf("CPU running at %dMHz, Cycle %d, Flash chip running at %d MHz, VCC is at %d\n", ESP.getCpuFreqMHz(), ESP.getCycleCount(), ESP.getFlashChipSpeed()/1000000, ESP.getVcc());
// If the pin is not pulled to ground read config or write the default one if its not
if (digitalRead(RESET_CONF_PIN)) {
conf->read(EEPROM_CONF_ADDR);
} else {
Terminal::println("Restoring factory settings...");
conf->write(EEPROM_CONF_ADDR);
}
// If the pin is pulled to ground then disable tracking
if (!digitalRead(DISABLE_TRACKING_PIN)) {
Terminal::println("Disabling tracking...");
conf->readFromString("{'active': false}");
conf->write(EEPROM_CONF_ADDR);
}
// Set the hostname
WiFi.hostname("FINDTracker");
// Setup the radios according to the configuration
rf.setup();
MDNS.begin("FINDTracker");
MDNS.addService("http", "tcp", 80);
// Setup the OTA server
OTA();
// Setup the websocket server
webSocket.begin();
// Setup the DNS server
dnsServer.setTTL(300);
dnsServer.setErrorReplyCode(DNSReplyCode::ServerFailure);
dnsServer.start(DNS_PORT, "findtracker", localIP);
}
void runServerHandlers() {
ArduinoOTA.handle();
cfgSrv.handle();
Terminal::handle();
webSocket.loop();
dnsServer.processNextRequest();
}
int lastWatchdog = -999999;
int sleepTimeMS;
int lastScan = -999999;
int lastUpdate = -999999;
bool connected;
bool active;
void loop() {
if (millis() - lastUpdate > 1500) {
connected = rf.connected();
active = conf->get<bool>("active");
lastUpdate = millis();
}
// Check for a WiFi connection and attempt to reestablish it if it died
if (
(active && !connected) ||
(!active && !connected && millis() - lastScan > 30000)
) {
digitalWrite(LED_PIN, LOW);
if (!rf.connect()) {
Terminal::print("Connection failed. ");
if (active) {
// Enter deep sleep in case the connection failed
sleepTimeMS = conf->get<int>("wifiReconnectionInterval");
blink(); blink(); blink();
Terminal::printf("Entering deep sleep mode for %dms ...\n", sleepTimeMS);
ESP.deepSleep(sleepTimeMS * 1000, WAKE_NO_RFCAL);
} else {
Terminal::println("");
wifiBlinker.attach(0.5, blinkSync);
}
} else {
wifiBlinker.detach();
digitalWrite(LED_PIN, HIGH);
}
lastScan = millis();
}
// TODO: The data.send() step takes way too long
if (active) {
/// Update the environment data (scan for networks)
if (data.update()) {
// Send the data to the FIND Server
String response = data.send();
/// Blink to indicate that we have sent our location
if (response != "") {
blink();
webSocket.broadcastTXT(response);
}
}
// Enter a very basic sleep mode and limit the amount of cycles to preserve power
// (Turn off the radio and wake it up periodically to answer beacon signals from router)
// TODO Only do this when nothing else is connected (low power mode setting maybe?)
// since it breaks all kind of things like websockets, HTTP etc.
WiFi.setSleepMode(WIFI_MODEM_SLEEP);
delay(500);
} else {
/// Let some background tasks run
delay(100);
yield();
}
/// Run all kinds of server handlers
runServerHandlers();
// Send a watchdog signal for all websocket clients
if (millis() - lastWatchdog > 5000) {
webSocket.broadcastTXT("watchdog");
lastWatchdog = millis();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>
#include <future>
#include "common/log.h"
#include "common/value_map.h"
#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/mesh_chunk.h"
#include "gfx/idriver_ui_adapter.h"
#include "gfx/support/load_wavefront.h"
#include "gfx/support/mesh_conversion.h"
#include "gfx/support/generate_aabb.h"
#include "gfx/support/write_data_to_mesh.h"
#include "gfx/support/texture_load.h"
#include "gfx/support/software_texture.h"
#include "gfx/support/unproject.h"
#include "gfx/support/render_normals.h"
#include "gfx/immediate_renderer.h"
#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"
#include "ui/pie_menu.h"
#include "strat/map.h"
#include "strat/wall.h"
#include "strat/water.h"
#include "strat/terrain.h"
#include "strat/player_state.h"
#include "procedural/terrain.h"
#include "glad/glad.h"
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "uv.h"
#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"
glm::vec4 project_point(glm::vec4 pt,
glm::mat4 const& model,
glm::mat4 const& view,
glm::mat4 const& proj) noexcept
{
pt = proj * view * model * pt;
pt /= pt.w;
return pt;
}
struct Glfw_User_Data
{
game::gfx::IDriver& driver;
game::gfx::Camera& camera;
game::ui::Element& root_hud;
game::ui::Mouse_State& mouse_state;
};
void mouse_button_callback(GLFWwindow* window, int glfw_button, int action,int)
{
using game::Vec; using game::ui::Mouse_State;
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& mouse_state = user_ptr.mouse_state;
bool down = (action == GLFW_PRESS);
using namespace game::ui;
Mouse_Button button;
switch(glfw_button)
{
case GLFW_MOUSE_BUTTON_LEFT:
{
button = Mouse_Button_Left;
break;
}
case GLFW_MOUSE_BUTTON_RIGHT:
{
button = Mouse_Button_Right;
break;
}
case GLFW_MOUSE_BUTTON_MIDDLE:
{
button = Mouse_Button_Middle;
break;
}
}
if(down) mouse_state.buttons |= button;
else mouse_state.buttons &= ~button;
}
void mouse_motion_callback(GLFWwindow* window, double x, double y)
{
using game::ui::Mouse_State;
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& mouse_state = user_ptr.mouse_state;
mouse_state.position.x = x;
mouse_state.position.y = y;
}
void scroll_callback(GLFWwindow* window, double, double deltay)
{
using game::ui::Mouse_State;
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& mouse_state = user_ptr.mouse_state;
mouse_state.scroll_delta = deltay;
}
void log_gl_limits(game::Log_Severity s) noexcept
{
GLint i = 0;
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}
void error_callback(int error, const char* description)
{
game::log_d("GLFW Error: % (Code = %)", description, error);
}
void resize_callback(GLFWwindow* window, int width, int height)
{
// Change OpenGL viewport
glViewport(0, 0, width, height);
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& idriver = user_ptr.driver;
// Inform the driver of this change
idriver.window_extents({width,height});
// Change the camera aspect ratio
user_ptr.camera.perspective.aspect = width / (float) height;
// Perhaps relayout the hud here?
user_ptr.root_hud.layout(game::Vec<int>{width, height});
}
int main(int argc, char** argv)
{
using namespace game;
set_log_level(Log_Severity::Debug);
uv_chdir("assets/");
// Initialize logger.
Scoped_Log_Init log_init_raii_lock{};
// Error callback
glfwSetErrorCallback(error_callback);
// Init glfw.
if(!glfwInit())
return EXIT_FAILURE;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
if(!window)
{
glfwTerminate();
return EXIT_FAILURE;
}
// Init context + load gl functions.
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Log glfw version.
log_i("Initialized GLFW %", glfwGetVersionString());
int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
// Log GL profile.
log_i("OpenGL core profile %.%.%", maj, min, rev);
// Set GLFW callbacks
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, mouse_motion_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetWindowSizeCallback(window, resize_callback);
// UI Controller
ui::Simple_Controller controller;
{
// Make an OpenGL driver.
// Don't rely on any window resolution. Query it again.
// After this, we'll query the driver for the real size.
int window_width, window_height;
glfwGetWindowSize(window, &window_width, &window_height);
gfx::gl::Driver driver{Vec<int>{window_width, window_height}};
// Load our default shader.
auto default_shader = driver.make_shader_repr();
default_shader->load_vertex_part("shader/basic/vs");
default_shader->load_fragment_part("shader/basic/fs");
default_shader->set_projection_name("proj");
default_shader->set_view_name("view");
default_shader->set_model_name("model");
default_shader->set_sampler_name("tex");
default_shader->set_diffuse_name("dif");
driver.use_shader(*default_shader);
default_shader->set_sampler(0);
// Load our textures.
auto grass_tex = driver.make_texture_repr();
load_png("tex/grass.png", *grass_tex);
// Load the image
Software_Texture terrain_image;
load_png("map/default.png", terrain_image);
// Convert it into a heightmap
Maybe_Owned<Mesh> terrain = driver.make_mesh_repr();
auto terrain_heightmap = strat::make_heightmap_from_image(terrain_image);
auto terrain_data =
make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01);
auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f));
gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain);
gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain));
gfx::format_mesh_buffers(*terrain);
terrain->set_primitive_type(Primitive_Type::Triangle);
// Map + structures.
Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr();
strat::Game_State game_state{&driver, gfx::make_isometric_camera(driver),
strat::Map{{1000, 1000}}}; // <-Map size for now
strat::Player_State player_state{game_state};
std::vector<Indexed_Mesh_Data> imd_vec;
auto structures = strat::load_structures("structure/structures.json",
ref_mo(structure_mesh),
driver, &imd_vec);
int fps = 0;
int time = glfwGetTime();
// Set up some pre-rendering state.
driver.clear_color_value(Color{0x55, 0x66, 0x77});
driver.clear_depth_value(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
// Load our ui
gfx::IDriver_UI_Adapter ui_adapter{driver};
ui::Freetype_Renderer freetype_font;
auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
auto hud = ui::load("ui/hud.json", ui_load_params);
hud->find_child_r("build_house")->on_step_mouse(
ui::On_Release_Handler{[&](auto const& ms)
{
player_state.switch_state<strat::Building_State>(structures[0]);
}});
hud->find_child_r("build_gvn_build")->on_step_mouse(
ui::On_Release_Handler{[&](auto const& ms)
{
player_state.switch_state<strat::Building_State>(structures[1]);
}});
hud->find_child_r("build_wall")->on_step_mouse(
ui::On_Release_Handler{[&](auto const& ms)
{
strat::Wall_Type type{1, structures[2].aabb().width};
player_state.switch_state<strat::Wall_Building_State>(type);
}});
hud->layout(driver.window_extents());
auto cur_mouse = ui::Mouse_State{};
// TODO: Put the camera somewhere else / Otherwise clean up the distinction
// and usage of Glfw_User_Data, Game_State and Player_State.
auto glfw_user_data = Glfw_User_Data{driver,game_state.cam, *hud, cur_mouse};
glfwSetWindowUserPointer(window, &glfw_user_data);
auto light_dir_pos = default_shader->get_location("light_dir");
gfx::Immediate_Renderer ir{driver};
std::size_t st_size = game_state.map.structures.size();
while(!glfwWindowShouldClose(window))
{
++fps;
// Reset the scroll delta
cur_mouse.scroll_delta = 0.0;
if(st_size != game_state.map.structures.size()) ir.reset();
// Update the mouse state.
glfwPollEvents();
// Clear the screen and render the terrain.
driver.clear();
use_camera(driver, game_state.cam);
default_shader->set_vec3(light_dir_pos, glm::vec3(0.0f, 1.0f, 0.0f));
driver.bind_texture(*grass_tex, 0);
default_shader->set_diffuse(colors::white);
default_shader->set_model(terrain_model);
// Render the terrain before we calculate the depth of the mouse position.
terrain->draw_elements(0, terrain_data.mesh.elements.size());
// These functions are bound to get the depth from the framebuffer. Make
// sure the depth value is only based on the terrain.
{
if(!controller.step(hud, cur_mouse))
{
player_state.step_mouse(cur_mouse);
}
// Handle zoom
gfx::apply_zoom(game_state.cam, cur_mouse.scroll_delta,
cur_mouse.position, driver);
}
// Render any structures.
// Maybe the mouse?
// We only want to be able to pan the terrain for now. That's why we need
// to do this before any structure rendering.
//auto mouse_world = gfx::unproject_screen(driver, game_state.cam,
//glm::mat4(1.0f),
//mouse_state.position);
//player_state.handle_mouse(Vec<float>{mouse_world.x, mouse_world.z});
//if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS &&
//player_state.type == strat::Player_State_Type::Nothing)
//{
//glfwSetWindowShouldClose(window, true);
//}
auto& pending_st = game_state.map.pending_structure;
if(pending_st)
{
render_structure_instance(driver, pending_st.value());
}
// Render all the other structures.
for(auto const& st : game_state.map.structures)
{
// TODO: Find/store correct y somehow?
render_structure_instance(driver, st);
if(st_size != game_state.map.structures.size())
{
if(&st.structure() == &structures[0])
{
gfx::render_normals(ir, imd_vec[0], st.model_matrix());
}
else if(&st.structure() == &structures[1])
{
gfx::render_normals(ir, imd_vec[1], st.model_matrix());
}
}
}
// Render walls
if(game_state.map.pending_wall)
{
// Render the structure at the pending wall point.
auto pos = game_state.map.pending_wall->pos;
glm::mat4 model = glm::translate(glm::mat4(1.0f),
glm::vec3(pos.x, 0.0f, pos.y));
render_structure(driver, structures[2], model);
}
for(auto const& wall : game_state.map.walls)
{
render_wall(driver, wall, structures[2]);
}
ir.render(game_state.cam);
{
ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
hud->render(ui_adapter);
}
glfwSwapBuffers(window);
if(int(glfwGetTime()) != time)
{
time = glfwGetTime();
log_d("fps: %", fps);
fps = 0;
}
flush_log();
st_size = game_state.map.structures.size();
}
}
glfwTerminate();
return 0;
}
<commit_msg>Stop rendering normals<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>
#include <future>
#include "common/log.h"
#include "common/value_map.h"
#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/mesh_chunk.h"
#include "gfx/idriver_ui_adapter.h"
#include "gfx/support/load_wavefront.h"
#include "gfx/support/mesh_conversion.h"
#include "gfx/support/generate_aabb.h"
#include "gfx/support/write_data_to_mesh.h"
#include "gfx/support/texture_load.h"
#include "gfx/support/software_texture.h"
#include "gfx/support/unproject.h"
#include "gfx/support/render_normals.h"
#include "gfx/immediate_renderer.h"
#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"
#include "ui/pie_menu.h"
#include "strat/map.h"
#include "strat/wall.h"
#include "strat/water.h"
#include "strat/terrain.h"
#include "strat/player_state.h"
#include "procedural/terrain.h"
#include "glad/glad.h"
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "uv.h"
#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"
glm::vec4 project_point(glm::vec4 pt,
glm::mat4 const& model,
glm::mat4 const& view,
glm::mat4 const& proj) noexcept
{
pt = proj * view * model * pt;
pt /= pt.w;
return pt;
}
struct Glfw_User_Data
{
game::gfx::IDriver& driver;
game::gfx::Camera& camera;
game::ui::Element& root_hud;
game::ui::Mouse_State& mouse_state;
};
void mouse_button_callback(GLFWwindow* window, int glfw_button, int action,int)
{
using game::Vec; using game::ui::Mouse_State;
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& mouse_state = user_ptr.mouse_state;
bool down = (action == GLFW_PRESS);
using namespace game::ui;
Mouse_Button button;
switch(glfw_button)
{
case GLFW_MOUSE_BUTTON_LEFT:
{
button = Mouse_Button_Left;
break;
}
case GLFW_MOUSE_BUTTON_RIGHT:
{
button = Mouse_Button_Right;
break;
}
case GLFW_MOUSE_BUTTON_MIDDLE:
{
button = Mouse_Button_Middle;
break;
}
}
if(down) mouse_state.buttons |= button;
else mouse_state.buttons &= ~button;
}
void mouse_motion_callback(GLFWwindow* window, double x, double y)
{
using game::ui::Mouse_State;
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& mouse_state = user_ptr.mouse_state;
mouse_state.position.x = x;
mouse_state.position.y = y;
}
void scroll_callback(GLFWwindow* window, double, double deltay)
{
using game::ui::Mouse_State;
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& mouse_state = user_ptr.mouse_state;
mouse_state.scroll_delta = deltay;
}
void log_gl_limits(game::Log_Severity s) noexcept
{
GLint i = 0;
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}
void error_callback(int error, const char* description)
{
game::log_d("GLFW Error: % (Code = %)", description, error);
}
void resize_callback(GLFWwindow* window, int width, int height)
{
// Change OpenGL viewport
glViewport(0, 0, width, height);
auto user_ptr = *(Glfw_User_Data*) glfwGetWindowUserPointer(window);
auto& idriver = user_ptr.driver;
// Inform the driver of this change
idriver.window_extents({width,height});
// Change the camera aspect ratio
user_ptr.camera.perspective.aspect = width / (float) height;
// Perhaps relayout the hud here?
user_ptr.root_hud.layout(game::Vec<int>{width, height});
}
int main(int argc, char** argv)
{
using namespace game;
set_log_level(Log_Severity::Debug);
uv_chdir("assets/");
// Initialize logger.
Scoped_Log_Init log_init_raii_lock{};
// Error callback
glfwSetErrorCallback(error_callback);
// Init glfw.
if(!glfwInit())
return EXIT_FAILURE;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
if(!window)
{
glfwTerminate();
return EXIT_FAILURE;
}
// Init context + load gl functions.
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Log glfw version.
log_i("Initialized GLFW %", glfwGetVersionString());
int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
// Log GL profile.
log_i("OpenGL core profile %.%.%", maj, min, rev);
// Set GLFW callbacks
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, mouse_motion_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetWindowSizeCallback(window, resize_callback);
// UI Controller
ui::Simple_Controller controller;
{
// Make an OpenGL driver.
// Don't rely on any window resolution. Query it again.
// After this, we'll query the driver for the real size.
int window_width, window_height;
glfwGetWindowSize(window, &window_width, &window_height);
gfx::gl::Driver driver{Vec<int>{window_width, window_height}};
// Load our default shader.
auto default_shader = driver.make_shader_repr();
default_shader->load_vertex_part("shader/basic/vs");
default_shader->load_fragment_part("shader/basic/fs");
default_shader->set_projection_name("proj");
default_shader->set_view_name("view");
default_shader->set_model_name("model");
default_shader->set_sampler_name("tex");
default_shader->set_diffuse_name("dif");
driver.use_shader(*default_shader);
default_shader->set_sampler(0);
// Load our textures.
auto grass_tex = driver.make_texture_repr();
load_png("tex/grass.png", *grass_tex);
// Load the image
Software_Texture terrain_image;
load_png("map/default.png", terrain_image);
// Convert it into a heightmap
Maybe_Owned<Mesh> terrain = driver.make_mesh_repr();
auto terrain_heightmap = strat::make_heightmap_from_image(terrain_image);
auto terrain_data =
make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01);
auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f));
gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain);
gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain));
gfx::format_mesh_buffers(*terrain);
terrain->set_primitive_type(Primitive_Type::Triangle);
// Map + structures.
Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr();
strat::Game_State game_state{&driver, gfx::make_isometric_camera(driver),
strat::Map{{1000, 1000}}}; // <-Map size for now
strat::Player_State player_state{game_state};
std::vector<Indexed_Mesh_Data> imd_vec;
auto structures = strat::load_structures("structure/structures.json",
ref_mo(structure_mesh),
driver, &imd_vec);
int fps = 0;
int time = glfwGetTime();
// Set up some pre-rendering state.
driver.clear_color_value(Color{0x55, 0x66, 0x77});
driver.clear_depth_value(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
// Load our ui
gfx::IDriver_UI_Adapter ui_adapter{driver};
ui::Freetype_Renderer freetype_font;
auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
auto hud = ui::load("ui/hud.json", ui_load_params);
hud->find_child_r("build_house")->on_step_mouse(
ui::On_Release_Handler{[&](auto const& ms)
{
player_state.switch_state<strat::Building_State>(structures[0]);
}});
hud->find_child_r("build_gvn_build")->on_step_mouse(
ui::On_Release_Handler{[&](auto const& ms)
{
player_state.switch_state<strat::Building_State>(structures[1]);
}});
hud->find_child_r("build_wall")->on_step_mouse(
ui::On_Release_Handler{[&](auto const& ms)
{
strat::Wall_Type type{1, structures[2].aabb().width};
player_state.switch_state<strat::Wall_Building_State>(type);
}});
hud->layout(driver.window_extents());
auto cur_mouse = ui::Mouse_State{};
// TODO: Put the camera somewhere else / Otherwise clean up the distinction
// and usage of Glfw_User_Data, Game_State and Player_State.
auto glfw_user_data = Glfw_User_Data{driver,game_state.cam, *hud, cur_mouse};
glfwSetWindowUserPointer(window, &glfw_user_data);
auto light_dir_pos = default_shader->get_location("light_dir");
gfx::Immediate_Renderer ir{driver};
std::size_t st_size = game_state.map.structures.size();
while(!glfwWindowShouldClose(window))
{
++fps;
// Reset the scroll delta
cur_mouse.scroll_delta = 0.0;
if(st_size != game_state.map.structures.size()) ir.reset();
// Update the mouse state.
glfwPollEvents();
// Clear the screen and render the terrain.
driver.clear();
use_camera(driver, game_state.cam);
default_shader->set_vec3(light_dir_pos, glm::vec3(0.0f, 1.0f, 0.0f));
driver.bind_texture(*grass_tex, 0);
default_shader->set_diffuse(colors::white);
default_shader->set_model(terrain_model);
// Render the terrain before we calculate the depth of the mouse position.
terrain->draw_elements(0, terrain_data.mesh.elements.size());
// These functions are bound to get the depth from the framebuffer. Make
// sure the depth value is only based on the terrain.
{
if(!controller.step(hud, cur_mouse))
{
player_state.step_mouse(cur_mouse);
}
// Handle zoom
gfx::apply_zoom(game_state.cam, cur_mouse.scroll_delta,
cur_mouse.position, driver);
}
// Render any structures.
// Maybe the mouse?
// We only want to be able to pan the terrain for now. That's why we need
// to do this before any structure rendering.
//auto mouse_world = gfx::unproject_screen(driver, game_state.cam,
//glm::mat4(1.0f),
//mouse_state.position);
//player_state.handle_mouse(Vec<float>{mouse_world.x, mouse_world.z});
//if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS &&
//player_state.type == strat::Player_State_Type::Nothing)
//{
//glfwSetWindowShouldClose(window, true);
//}
auto& pending_st = game_state.map.pending_structure;
if(pending_st)
{
render_structure_instance(driver, pending_st.value());
}
// Render all the other structures.
for(auto const& st : game_state.map.structures)
{
// TODO: Find/store correct y somehow?
render_structure_instance(driver, st);
}
// Render walls
if(game_state.map.pending_wall)
{
// Render the structure at the pending wall point.
auto pos = game_state.map.pending_wall->pos;
glm::mat4 model = glm::translate(glm::mat4(1.0f),
glm::vec3(pos.x, 0.0f, pos.y));
render_structure(driver, structures[2], model);
}
for(auto const& wall : game_state.map.walls)
{
render_wall(driver, wall, structures[2]);
}
ir.render(game_state.cam);
{
ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
hud->render(ui_adapter);
}
glfwSwapBuffers(window);
if(int(glfwGetTime()) != time)
{
time = glfwGetTime();
log_d("fps: %", fps);
fps = 0;
}
flush_log();
st_size = game_state.map.structures.size();
}
}
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>// This file was developed by Thomas Müller <[email protected]>.
// It is published under the BSD 3-Clause License within the LICENSE file.
#include <tev/ImageViewer.h>
#include <tev/Ipc.h>
#include <tev/SharedQueue.h>
#include <tev/ThreadPool.h>
#include <args.hxx>
#include <ImfThreading.h>
#include <iostream>
#include <thread>
using namespace args;
using namespace filesystem;
using namespace std;
TEV_NAMESPACE_BEGIN
int mainFunc(const vector<string>& arguments) {
ArgumentParser parser{
"Inspection tool for images with a high dynamic range.",
"",
};
HelpFlag helpFlag{
parser,
"help",
"Display this help menu",
{'h', "help"},
};
Flag newWindowFlag{
parser,
"new window",
"Opens a new window of tev, even if one exists already.",
{'n', "new"},
};
ValueFlag<float> exposureFlag{
parser,
"exposure",
"Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. "
"It can be controlled via the GUI, or by pressing E/Shift+E.",
{'e', "exposure"},
};
ValueFlag<string> filterFlag{
parser,
"filter",
"Filters visible images and layers according to a supplied string. "
"The string must have the format 'image:layer'. "
"Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.",
{'f', "filter"},
};
ValueFlag<bool> maximizeFlag{
parser,
"maximize",
"Whether to maximize the window on startup or not. "
"If no images were supplied via the command line, then the default is false. "
"Otherwise, the default is true.",
{"max", "maximize"},
};
ValueFlag<string> metricFlag{
parser,
"metric",
"The metric to use when comparing two images. "
R"(
The available metrics are:
E - Error
AE - Absolute Error
SE - Squared Error
RAE - Relative Absolute Error
RSE - Relative Squared Error
)"
"Default is E.",
{'m', "metric"},
};
ValueFlag<float> offsetFlag{
parser,
"offset",
"The offset is added to the image after exposure has been applied. "
"It can be controlled via the GUI, or by pressing O/Shift+O.",
{'o', "offset"},
};
ValueFlag<string> tonemapFlag{
parser,
"tonemap",
"The tonemapping algorithm to use. "
R"(
The available tonemaps are:
sRGB - sRGB
Gamma - Gamma curve (2.2)
FC - False Color
PN - Positive=Green, Negative=Red
)"
"Default is sRGB.",
{'t', "tonemap"},
};
PositionalList<string> imageFiles{
parser,
"images or channel selectors",
"The image files to be opened by the viewer. "
"If a filename starting with a ':' is encountered, "
"then this filename is not treated as an image file "
"but as a comma-separated channel selector. Until the next channel "
"selector is encountered only channels containing "
"elements from the current selector will be loaded. This is "
"especially useful for selectively loading a specific "
"part of a multi-part EXR file.",
};
// Parse command line arguments and react to parsing
// errors using exceptions.
try {
parser.ParseArgs(arguments);
} catch (args::Help) {
std::cout << parser;
return 0;
} catch (args::ParseError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -1;
} catch (args::ValidationError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -2;
}
auto ipc = make_shared<Ipc>();
// If we're not the primary instance and did not request to open a new window,
// simply send the to-be-opened images to the primary instance.
if (!ipc->isPrimaryInstance() && !newWindowFlag) {
string channelSelector;
for (auto imageFile : get(imageFiles)) {
if (!imageFile.empty() && imageFile[0] == ':') {
channelSelector = imageFile.substr(1);
continue;
}
try {
ipc->sendToPrimaryInstance(path{imageFile}.make_absolute().str() + ":" + channelSelector);
} catch (runtime_error e) {
cerr << "Invalid file '" << imageFile << "': " << e.what() << endl;
}
}
return 0;
}
Imf::setGlobalThreadCount(thread::hardware_concurrency());
cout << "Loading window..." << endl;
// Load images passed via command line in the background prior to
// creating our main application such that they are not stalled
// by the potentially slow initialization of opengl / glfw.
shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();
string channelSelector;
for (auto imageFile : get(imageFiles)) {
if (!imageFile.empty() && imageFile[0] == ':') {
channelSelector = imageFile.substr(1);
continue;
}
ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {
auto image = tryLoadImage(imageFile, channelSelector);
if (image) {
imagesToAdd->push({false, image});
}
});
}
// Init nanogui application
nanogui::init();
{
auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd, !imageFiles}};
app->drawAll();
app->setVisible(true);
// Do what the maximize flag tells us---if it exists---and
// maximize if we have images otherwise.
if (maximizeFlag ? get(maximizeFlag) : imageFiles) {
app->maximize();
}
// Apply parameter flags
if (exposureFlag) { app->setExposure(get(exposureFlag)); }
if (filterFlag) { app->setFilter(get(filterFlag)); }
if (metricFlag) { app->setMetric(toMetric(get(metricFlag))); }
if (offsetFlag) { app->setOffset(get(offsetFlag)); }
if (tonemapFlag) { app->setTonemap(toTonemap(get(tonemapFlag))); }
// Refresh only every 250ms if there are no user interactions.
// This makes an idling tev surprisingly energy-efficient. :)
nanogui::mainloop(250);
}
// On some linux distributions glfwTerminate() (which is called by
// nanogui::shutdown()) causes segfaults. Since we are done with our
// program here anyways, let's let the OS clean up after us.
//nanogui::shutdown();
// Let all threads gracefully terminate.
ThreadPool::shutdown();
return 0;
}
#ifdef _WIN32
vector<string> arguments(int argc, char*[]) {
vector<string> arguments;
LPWSTR* arglist = CommandLineToArgvW(GetCommandLineW(), &argc);
if (arglist == NULL) {
// tfm::format is not used due to a compiler issue in MSVC 2015 clashing with the "args" namespace.
throw runtime_error{string{"Could not obtain command line: "} + errorString(lastError())};
}
for (int i = 1; i < argc; ++i) {
wstring warg = arglist[i];
string arg;
if (!warg.empty()) {
int size = WideCharToMultiByte(CP_UTF8, 0, &warg[0], (int)warg.size(), NULL, 0, NULL, NULL);
arg.resize(size, 0);
WideCharToMultiByte(CP_UTF8, 0, &warg[0], (int)warg.size(), &arg[0], size, NULL, NULL);
}
arguments.emplace_back(arg);
}
LocalFree(arglist);
return arguments;
}
#else
vector<string> arguments(int argc, char* argv[]) {
vector<string> arguments;
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
// OSX sometimes (seemingly sporadically) passes the
// process serial number via a command line parameter.
// We would like to ignore this.
if (arg.find("-psn") == 0) {
continue;
}
arguments.emplace_back(arg);
}
return arguments;
}
#endif
TEV_NAMESPACE_END
int main(int argc, char* argv[]) {
try {
tev::mainFunc(tev::arguments(argc, argv));
} catch (const runtime_error& e) {
cerr << "Uncaught exception: " << e.what() << endl;
return 1;
}
}
<commit_msg>Remove unnecessary explicit args:: prefix<commit_after>// This file was developed by Thomas Müller <[email protected]>.
// It is published under the BSD 3-Clause License within the LICENSE file.
#include <tev/ImageViewer.h>
#include <tev/Ipc.h>
#include <tev/SharedQueue.h>
#include <tev/ThreadPool.h>
#include <args.hxx>
#include <ImfThreading.h>
#include <iostream>
#include <thread>
using namespace args;
using namespace filesystem;
using namespace std;
TEV_NAMESPACE_BEGIN
int mainFunc(const vector<string>& arguments) {
ArgumentParser parser{
"Inspection tool for images with a high dynamic range.",
"",
};
HelpFlag helpFlag{
parser,
"help",
"Display this help menu",
{'h', "help"},
};
Flag newWindowFlag{
parser,
"new window",
"Opens a new window of tev, even if one exists already.",
{'n', "new"},
};
ValueFlag<float> exposureFlag{
parser,
"exposure",
"Exposure scales the brightness of an image prior to tonemapping by 2^Exposure. "
"It can be controlled via the GUI, or by pressing E/Shift+E.",
{'e', "exposure"},
};
ValueFlag<string> filterFlag{
parser,
"filter",
"Filters visible images and layers according to a supplied string. "
"The string must have the format 'image:layer'. "
"Only images whose name contains 'image' and layers whose name contains 'layer' will be visible.",
{'f', "filter"},
};
ValueFlag<bool> maximizeFlag{
parser,
"maximize",
"Whether to maximize the window on startup or not. "
"If no images were supplied via the command line, then the default is false. "
"Otherwise, the default is true.",
{"max", "maximize"},
};
ValueFlag<string> metricFlag{
parser,
"metric",
"The metric to use when comparing two images. "
R"(
The available metrics are:
E - Error
AE - Absolute Error
SE - Squared Error
RAE - Relative Absolute Error
RSE - Relative Squared Error
)"
"Default is E.",
{'m', "metric"},
};
ValueFlag<float> offsetFlag{
parser,
"offset",
"The offset is added to the image after exposure has been applied. "
"It can be controlled via the GUI, or by pressing O/Shift+O.",
{'o', "offset"},
};
ValueFlag<string> tonemapFlag{
parser,
"tonemap",
"The tonemapping algorithm to use. "
R"(
The available tonemaps are:
sRGB - sRGB
Gamma - Gamma curve (2.2)
FC - False Color
PN - Positive=Green, Negative=Red
)"
"Default is sRGB.",
{'t', "tonemap"},
};
PositionalList<string> imageFiles{
parser,
"images or channel selectors",
"The image files to be opened by the viewer. "
"If a filename starting with a ':' is encountered, "
"then this filename is not treated as an image file "
"but as a comma-separated channel selector. Until the next channel "
"selector is encountered only channels containing "
"elements from the current selector will be loaded. This is "
"especially useful for selectively loading a specific "
"part of a multi-part EXR file.",
};
// Parse command line arguments and react to parsing
// errors using exceptions.
try {
parser.ParseArgs(arguments);
} catch (Help) {
std::cout << parser;
return 0;
} catch (ParseError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -1;
} catch (ValidationError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return -2;
}
auto ipc = make_shared<Ipc>();
// If we're not the primary instance and did not request to open a new window,
// simply send the to-be-opened images to the primary instance.
if (!ipc->isPrimaryInstance() && !newWindowFlag) {
string channelSelector;
for (auto imageFile : get(imageFiles)) {
if (!imageFile.empty() && imageFile[0] == ':') {
channelSelector = imageFile.substr(1);
continue;
}
try {
ipc->sendToPrimaryInstance(path{imageFile}.make_absolute().str() + ":" + channelSelector);
} catch (runtime_error e) {
cerr << "Invalid file '" << imageFile << "': " << e.what() << endl;
}
}
return 0;
}
Imf::setGlobalThreadCount(thread::hardware_concurrency());
cout << "Loading window..." << endl;
// Load images passed via command line in the background prior to
// creating our main application such that they are not stalled
// by the potentially slow initialization of opengl / glfw.
shared_ptr<SharedQueue<ImageAddition>> imagesToAdd = make_shared<SharedQueue<ImageAddition>>();
string channelSelector;
for (auto imageFile : get(imageFiles)) {
if (!imageFile.empty() && imageFile[0] == ':') {
channelSelector = imageFile.substr(1);
continue;
}
ThreadPool::singleWorker().enqueueTask([imageFile, channelSelector, &imagesToAdd] {
auto image = tryLoadImage(imageFile, channelSelector);
if (image) {
imagesToAdd->push({false, image});
}
});
}
// Init nanogui application
nanogui::init();
{
auto app = unique_ptr<ImageViewer>{new ImageViewer{ipc, imagesToAdd, !imageFiles}};
app->drawAll();
app->setVisible(true);
// Do what the maximize flag tells us---if it exists---and
// maximize if we have images otherwise.
if (maximizeFlag ? get(maximizeFlag) : imageFiles) {
app->maximize();
}
// Apply parameter flags
if (exposureFlag) { app->setExposure(get(exposureFlag)); }
if (filterFlag) { app->setFilter(get(filterFlag)); }
if (metricFlag) { app->setMetric(toMetric(get(metricFlag))); }
if (offsetFlag) { app->setOffset(get(offsetFlag)); }
if (tonemapFlag) { app->setTonemap(toTonemap(get(tonemapFlag))); }
// Refresh only every 250ms if there are no user interactions.
// This makes an idling tev surprisingly energy-efficient. :)
nanogui::mainloop(250);
}
// On some linux distributions glfwTerminate() (which is called by
// nanogui::shutdown()) causes segfaults. Since we are done with our
// program here anyways, let's let the OS clean up after us.
//nanogui::shutdown();
// Let all threads gracefully terminate.
ThreadPool::shutdown();
return 0;
}
#ifdef _WIN32
vector<string> arguments(int argc, char*[]) {
vector<string> arguments;
LPWSTR* arglist = CommandLineToArgvW(GetCommandLineW(), &argc);
if (arglist == NULL) {
// tfm::format is not used due to a compiler issue in MSVC 2015 clashing with the "args" namespace.
throw runtime_error{string{"Could not obtain command line: "} + errorString(lastError())};
}
for (int i = 1; i < argc; ++i) {
wstring warg = arglist[i];
string arg;
if (!warg.empty()) {
int size = WideCharToMultiByte(CP_UTF8, 0, &warg[0], (int)warg.size(), NULL, 0, NULL, NULL);
arg.resize(size, 0);
WideCharToMultiByte(CP_UTF8, 0, &warg[0], (int)warg.size(), &arg[0], size, NULL, NULL);
}
arguments.emplace_back(arg);
}
LocalFree(arglist);
return arguments;
}
#else
vector<string> arguments(int argc, char* argv[]) {
vector<string> arguments;
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
// OSX sometimes (seemingly sporadically) passes the
// process serial number via a command line parameter.
// We would like to ignore this.
if (arg.find("-psn") == 0) {
continue;
}
arguments.emplace_back(arg);
}
return arguments;
}
#endif
TEV_NAMESPACE_END
int main(int argc, char* argv[]) {
try {
tev::mainFunc(tev::arguments(argc, argv));
} catch (const runtime_error& e) {
cerr << "Uncaught exception: " << e.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <iostream>
#include <ios>
#include "hext/parser.h"
#include "hext/matcher.h"
#include "hext/print.h"
int main(int argc, char ** argv)
{
// todo: boost::program_options
if( argc < 3 )
{
std::cout << "Usage: " << argv[0]
<< " [rules.hext] [target.html]" << std::endl;
return EXIT_SUCCESS;
}
try
{
auto rules = hext::parser::parse_file(argv[1]);
hext::matcher m(argv[2]);
for(const auto& r : rules)
{
hext::print_rule(r);
std::unique_ptr<hext::match_tree> mt = m.match(&r);
assert(mt.get() != nullptr);
//hext::print_match_tree(mt.get());
mt->to_json(std::cout);
}
}
catch( std::ios_base::failure& e )
{
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>disable iostreams syncing with stdio<commit_after>#include <cstdlib>
#include <iostream>
#include <ios>
#include "hext/parser.h"
#include "hext/matcher.h"
#include "hext/print.h"
int main(int argc, char ** argv)
{
std::ios_base::sync_with_stdio(false);
// todo: boost::program_options
if( argc < 3 )
{
std::cout << "Usage: " << argv[0]
<< " [rules.hext] [target.html]" << std::endl;
return EXIT_SUCCESS;
}
try
{
auto rules = hext::parser::parse_file(argv[1]);
hext::matcher m(argv[2]);
for(const auto& r : rules)
{
hext::print_rule(r);
std::unique_ptr<hext::match_tree> mt = m.match(&r);
assert(mt.get() != nullptr);
//hext::print_match_tree(mt.get());
mt->to_json(std::cout);
}
}
catch( std::ios_base::failure& e )
{
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <loftili.h>
#include <server.h>
int main(int argc, char ** argv) {
if(argc > 1)
std::cout << LOFTILI_PKG_VERSION << std::endl;
else
return loftili::Server::run();
}
<commit_msg>updating includes in main.cpp to follow style<commit_after>#include "loftili.h"
#include "server.h"
int main(int argc, char ** argv) {
if(argc > 1)
std::cout << LOFTILI_PKG_VERSION << std::endl;
else
return loftili::Server::run();
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <chrono>
#include <thread>
using std::chrono::microseconds;
#if defined(__linux__)
#include <sys/prctl.h>
#endif
volatile int g_thread_2_continuing = 0;
void *
thread_1_func (void *input)
{
// Waiting to be released by the debugger.
while (!g_thread_2_continuing) // Another thread will change this value
{
std::this_thread::sleep_for(microseconds(1));
}
// Return
return NULL; // Set third breakpoint here
}
void *
thread_2_func (void *input)
{
// Waiting to be released by the debugger.
int child_thread_continue = 0;
while (!child_thread_continue) // The debugger will change this value
{
std::this_thread::sleep_for(microseconds(1)); // Set second breakpoint here
}
// Release thread 1
g_thread_2_continuing = 1;
// Return
return NULL;
}
int main(int argc, char const *argv[])
{
#if defined(__linux__)
// Immediately enable any ptracer so that we can allow the stub attach
// operation to succeed. Some Linux kernels are locked down so that
// only an ancestor process can be a ptracer of a process. This disables that
// restriction. Without it, attach-related stub tests will fail.
#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
int prctl_result;
// For now we execute on best effort basis. If this fails for
// some reason, so be it.
prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
(void) prctl_result;
#endif
#endif
// Create a new thread
std::thread thread_1(thread_1_func, nullptr);
// Waiting to be attached by the debugger.
int main_thread_continue = 0;
while (!main_thread_continue) // The debugger will change this value
{
std::this_thread::sleep_for(microseconds(1)); // Set first breakpoint here
}
// Create another new thread
std::thread thread_2(thread_2_func, nullptr);
// Wait for the threads to finish.
thread_1.join();
thread_2.join();
printf("Exiting now\n");
}
<commit_msg>Normalize line endings.<commit_after>#include <stdio.h>
#include <chrono>
#include <thread>
using std::chrono::microseconds;
#if defined(__linux__)
#include <sys/prctl.h>
#endif
volatile int g_thread_2_continuing = 0;
void *
thread_1_func (void *input)
{
// Waiting to be released by the debugger.
while (!g_thread_2_continuing) // Another thread will change this value
{
std::this_thread::sleep_for(microseconds(1));
}
// Return
return NULL; // Set third breakpoint here
}
void *
thread_2_func (void *input)
{
// Waiting to be released by the debugger.
int child_thread_continue = 0;
while (!child_thread_continue) // The debugger will change this value
{
std::this_thread::sleep_for(microseconds(1)); // Set second breakpoint here
}
// Release thread 1
g_thread_2_continuing = 1;
// Return
return NULL;
}
int main(int argc, char const *argv[])
{
#if defined(__linux__)
// Immediately enable any ptracer so that we can allow the stub attach
// operation to succeed. Some Linux kernels are locked down so that
// only an ancestor process can be a ptracer of a process. This disables that
// restriction. Without it, attach-related stub tests will fail.
#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
int prctl_result;
// For now we execute on best effort basis. If this fails for
// some reason, so be it.
prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
(void) prctl_result;
#endif
#endif
// Create a new thread
std::thread thread_1(thread_1_func, nullptr);
// Waiting to be attached by the debugger.
int main_thread_continue = 0;
while (!main_thread_continue) // The debugger will change this value
{
std::this_thread::sleep_for(microseconds(1)); // Set first breakpoint here
}
// Create another new thread
std::thread thread_2(thread_2_func, nullptr);
// Wait for the threads to finish.
thread_1.join();
thread_2.join();
printf("Exiting now\n");
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/// @file p9_query_cache_access_state.H
/// @brief Check the stop level for the EX caches and sets boolean scomable parameters
///
// *HWP HWP Owner: Christina Graves <[email protected]>
// *HWP Backup HWP Owner: Greg Still <[email protected]>
// *HWP FW Owner: Sangeetha T S <[email protected]>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: FSP:HS:SBE
///
///-----------------------------------------------------------------------------
#ifndef _p9_query_cache_access_state_H_
#define _p9_query_cache_access_state_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_pm.H>
#include <p9_quad_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_query_cache_access_state_FP_t) (
const fapi2::Target<fapi2::TARGET_TYPE_EQ>&,
bool&,
bool&,
bool&,
bool&);
extern "C"
{
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
/// @brief Check the stop level for the EX caches and sets boolean scomable parameters
///
/// @param[in] i_target EX target
///
/// @param[out] o_l2_is_scomable L2 cache has clocks running and is scomable
/// @param[out[ o_l2_is_scannable L2 cache is powered up and has valid latch state
/// @param[out] o_l3_is_scomable L3 cache has clocks running and is scomable
/// @param[out[ o_l2_is_scannable L3 cache is powered up and has valid latch state
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode
p9_query_cache_access_state(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
bool& o_l2_is_scomable,
bool& o_l2_is_scannable,
bool& o_l3_is_scomable,
bool& o_l3_is_scannable);
} // extern "C"
#endif // _p9_query_cache_access_state_H_
<commit_msg>Fix bug in cache query state procedure<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_cache_access_state.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/// @file p9_query_cache_access_state.H
/// @brief Check the stop level for the EX caches and sets boolean scomable parameters
///
// *HWP HWP Owner: Christina Graves <[email protected]>
// *HWP Backup HWP Owner: Greg Still <[email protected]>
// *HWP FW Owner: Sangeetha T S <[email protected]>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: FSP:HS:SBE
///
///-----------------------------------------------------------------------------
#ifndef _p9_query_cache_access_state_H_
#define _p9_query_cache_access_state_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_pm.H>
#include <p9_quad_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
#define MAX_L2_PER_QUAD 2 //shared by the core/ex
#define MAX_L3_PER_QUAD 2 //shared by the core/ex
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_query_cache_access_state_FP_t) (
const fapi2::Target<fapi2::TARGET_TYPE_EQ>&,
bool*,
bool*,
bool*,
bool*);
extern "C"
{
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
/// @brief Check the stop level for the EX caches and sets boolean scomable parameters
///
/// @param[in] i_target EX target
///
/// @param[out] o_l2_is_scomable[MAX_L2_PER_QUAD]
// L2 cache has clocks running and is scomable
/// @param[out[ o_l2_is_scannable[MAX_L2_PER_QUAD]
// L2 cache is powered up and has valid latch state
/// @param[out] o_l3_is_scomable L3 cache has clocks running and is scomable
/// @param[out[ o_l2_is_scannable L3 cache is powered up and has valid latch state
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode
p9_query_cache_access_state(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
bool o_l2_is_scomable[MAX_L2_PER_QUAD],
bool o_l2_is_scannable[MAX_L2_PER_QUAD],
bool o_l3_is_scomable[MAX_L3_PER_QUAD],
bool o_l3_is_scannable[MAX_L3_PER_QUAD]);
/// @brief Check the stop level for the EX caches and sets boolean scomable parameters
///
/// @param[in] i_target EX target
///
/// @param[out] o_l2_is_scomable[MAX_L2_PER_QUAD]
// L2 cache has clocks running and is scomable
/// @param[out] o_l3_is_scomable L3 cache has clocks running and is scomable
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
fapi2::ReturnCode
p9_query_cache_clock_state(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
bool o_l2_is_scomable[MAX_L2_PER_QUAD],
bool o_l3_is_scomable[MAX_L3_PER_QUAD]);
} // extern "C"
#endif // _p9_query_cache_access_state_H_
<|endoftext|> |
<commit_before>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkParameterFileParser_cxx
#define __itkParameterFileParser_cxx
#include "itkParameterFileParser.h"
#include <itksys/SystemTools.hxx>
#include <itksys/RegularExpression.hxx>
namespace itk
{
/**
* **************** Constructor ***************
*/
ParameterFileParser
::ParameterFileParser()
{
this->m_ParameterFileName = "";
this->m_ParameterMap.clear();
} // end Constructor()
/**
* **************** Destructor ***************
*/
ParameterFileParser
::~ParameterFileParser()
{
if ( this->m_ParameterFile.is_open() )
{
this->m_ParameterFile.close();
}
} // end Destructor()
/**
* **************** GetParameterMap ***************
*/
const ParameterFileParser::ParameterMapType &
ParameterFileParser
::GetParameterMap( void ) const
{
return this->m_ParameterMap;
} // end GetParameterMap()
/**
* **************** ReadParameterFile ***************
*/
void
ParameterFileParser
::ReadParameterFile( void )
{
/** Perform some basic checks. */
this->BasicFileChecking();
/** Open the parameter file for reading. */
if ( this->m_ParameterFile.is_open() )
{
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
}
this->m_ParameterFile.open( this->m_ParameterFileName.c_str(), std::fstream::in );
/** Check if it opened. */
if ( !this->m_ParameterFile.is_open() )
{
itkExceptionMacro( << "ERROR: could not open "
<< this->m_ParameterFileName
<< " for reading." );
}
/** Clear the map. */
this->m_ParameterMap.clear();
/** Loop over the parameter file, line by line. */
std::string lineIn = "";
std::string lineOut = "";
while ( this->m_ParameterFile.good() )
{
/** Extract a line. */
itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, lineIn );
/** Check this line. */
bool validLine = this->CheckLine( lineIn, lineOut );
if ( validLine )
{
/** Get the parameter name from this line and store it. */
this->GetParameterFromLine( lineIn, lineOut );
}
// Otherwise, we simply ignore this line
}
/** Close the parameter file. */
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
} // end ReadParameterFile()
/**
* **************** BasicFileChecking ***************
*/
void
ParameterFileParser
::BasicFileChecking( void ) const
{
/** Check if the file name is given. */
if ( this->m_ParameterFileName == "" )
{
itkExceptionMacro( << "ERROR: FileName has not been set." );
}
/** Basic error checking: existence. */
bool exists = itksys::SystemTools::FileExists(
this->m_ParameterFileName.c_str() );
if ( !exists )
{
itkExceptionMacro( << "ERROR: the file "
<< this->m_ParameterFileName
<< " does not exist." );
}
/** Basic error checking: file or directory. */
bool isDir = itksys::SystemTools::FileIsDirectory(
this->m_ParameterFileName.c_str() );
if ( isDir )
{
itkExceptionMacro( << "ERROR: the file "
<< this->m_ParameterFileName
<< " is a directory." );
}
/** Check the extension. */
std::string ext = itksys::SystemTools::GetFilenameLastExtension(
this->m_ParameterFileName );
if ( ext != ".txt" )
{
itkExceptionMacro( << "ERROR: the file "
<< this->m_ParameterFileName
<< " should be a text file (*.txt)." );
}
} // end BasicFileChecking()
/**
* **************** CheckLine ***************
*/
bool
ParameterFileParser
::CheckLine( const std::string & lineIn, std::string & lineOut ) const
{
/** Preprocessing of lineIn:
* 1) Replace tabs with spaces
* 2) Remove everything after comment sign //
* 3) Remove leading spaces
* 4) Remove trailing spaces
*/
lineOut = lineIn;
itksys::SystemTools::ReplaceString( lineOut, "\t", " " );
itksys::RegularExpression commentPart( "//" );
if ( commentPart.find( lineOut ) )
{
lineOut = lineOut.substr( 0, commentPart.start() );
}
itksys::RegularExpression leadingSpaces( "^[ ]*(.*)" );
leadingSpaces.find( lineOut );
lineOut = leadingSpaces.match( 1 );
itksys::RegularExpression trailingSpaces( "[ \t]+$" );
if ( trailingSpaces.find( lineOut ) )
{
lineOut = lineOut.substr( 0, trailingSpaces.start() );
}
/**
* Checks:
* 1. Empty line -> false
* 2. Comment (line starts with "//") -> false
* 3. Line is not between brackets (...) -> exception
* 4. Line contains less than two words -> exception
*
* Otherwise return true.
*/
/** 1. Check for non-empty lines. */
itksys::RegularExpression reNonEmptyLine( "[^ ]+" );
bool match1 = reNonEmptyLine.find( lineOut );
if ( !match1 )
{
return false;
}
/** 2. Check for comments. */
itksys::RegularExpression reComment( "^//" );
bool match2 = reComment.find( lineOut );
if ( match2 )
{
return false;
}
/** 3. Check if line is between brackets. */
if ( !itksys::SystemTools::StringStartsWith( lineOut.c_str(), "(" )
|| !itksys::SystemTools::StringEndsWith( lineOut.c_str(), ")" ) )
{
std::string hint = "Line is not between brackets: \"(...)\".";
this->ThrowException( lineIn, hint );
}
/** Remove brackets. */
lineOut = lineOut.substr( 1, lineOut.size() - 2 );
/** 4. Check: the line should contain at least two words. */
itksys::RegularExpression reTwoWords( "([ ]+)([^ ]+)" );
bool match4 = reTwoWords.find( lineOut );
if ( !match4 )
{
std::string hint = "Line does not contain a parameter name and value.";
this->ThrowException( lineIn, hint );
}
/** At this point we know its at least a line containing a parameter.
* However, this line can still be invalid, for example:
* (string &^%^*)
* This will be checked later.
*/
return true;
} // end CheckLine()
/**
* **************** GetParameterFromLine ***************
*/
void
ParameterFileParser
::GetParameterFromLine( const std::string & fullLine,
const std::string & line )
{
/** A line has a parameter name followed by one or more parameters.
* They are all separated by one or more spaces (all tabs have been
* removed previously) or by quotes in case of strings. So,
* 1) we split the line at the spaces or quotes
* 2) the first one is the parameter name
* 3) the other strings that are not a series of spaces, are parameter values
*/
/** 1) Split the line. */
std::vector<std::string> splittedLine;
this->SplitLine( fullLine, line, splittedLine );
/** 2) Get the parameter name. */
std::string parameterName = splittedLine[ 0 ];
itksys::SystemTools::ReplaceString( parameterName, " ", "" );
splittedLine.erase( splittedLine.begin() );
/** 3) Get the parameter values. */
std::vector< std::string > parameterValues;
for ( unsigned int i = 0; i < splittedLine.size(); ++i )
{
if ( splittedLine[ i ] != "" )
{
parameterValues.push_back( splittedLine[ i ] );
}
}
/** 4) Perform some checks on the parameter name. */
itksys::RegularExpression reInvalidCharacters1( "[.,:;!@#$%^&-+|<>?]" );
bool match = reInvalidCharacters1.find( parameterName );
if ( match )
{
std::string hint = "The parameter \""
+ parameterName
+ "\" contains invalid characters (.,:;!@#$%^&-+|<>?).";
this->ThrowException( fullLine, hint );
}
/** 5) Perform checks on the parameter values. */
itksys::RegularExpression reInvalidCharacters2( "[,;!@#$%^&|<>?]" );
for ( unsigned int i = 0; i < parameterValues.size(); ++i )
{
/** For all entries some characters are not allowed. */
if ( reInvalidCharacters2.find( parameterValues[ i ] ) )
{
std::string hint = "The parameter value \""
+ parameterValues[ i ]
+ "\" contains invalid characters (,;!@#$%^&|<>?).";
this->ThrowException( fullLine, hint );
}
}
/** 6) Insert this combination in the parameter map. */
this->m_ParameterMap.insert( make_pair( parameterName, parameterValues ) );
} // end GetParameterFromLine()
/**
* **************** SplitLine ***************
*/
void
ParameterFileParser
::SplitLine( const std::string & fullLine, const std::string & line,
std::vector<std::string> & splittedLine ) const
{
splittedLine.clear();
splittedLine.resize( 1 );
std::vector<itksys::String> splittedLine1;
/** Count the number of quotes in the line. If it is an odd value, the
* line contains an error; strings should start and end with a quote, so
* the total number of quotes is even.
*/
std::size_t numQuotes = itksys::SystemTools::CountChar( line.c_str(), '"' );
if ( numQuotes % 2 == 1 )
{
/** An invalid parameter line. */
std::string hint = "This line has an odd number of quotes (\").";
this->ThrowException( fullLine, hint );
}
/** Loop over the line. */
std::string::const_iterator it;
unsigned int index = 0;
numQuotes = 0;
for ( it = line.begin(); it < line.end(); it++ )
{
if ( *it == '"' )
{
/** Start a new element. */
splittedLine.push_back( "" );
index++;
numQuotes++;
}
else if ( *it == ' ' )
{
/** Only start a new element if it is not a quote, otherwise just add
* the space to the string.
*/
if ( numQuotes % 2 == 0 )
{
splittedLine.push_back( "" );
index++;
}
else
{
splittedLine[ index ].push_back( *it );
}
}
else
{
/** Add this character to the element. */
splittedLine[ index ].push_back( *it );
}
}
} // end SplitLine()
/**
* **************** ThrowException ***************
*/
void
ParameterFileParser
::ThrowException( const std::string & line, const std::string & hint ) const
{
/** Construct an error message. */
std::string errorMessage
= "ERROR: the following line in your parameter file is invalid: \n\""
+ line
+ "\"\n"
+ hint
+ "\nPlease correct you parameter file!";
/** Throw exception. */
itkExceptionMacro( << errorMessage.c_str() );
} // end ThrowException()
/**
* **************** ReturnParameterFileAsString ***************
*/
std::string
ParameterFileParser
::ReturnParameterFileAsString( void )
{
/** Perform some basic checks. */
this->BasicFileChecking();
/** Open the parameter file for reading. */
if ( this->m_ParameterFile.is_open() )
{
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
}
this->m_ParameterFile.open( this->m_ParameterFileName.c_str(), std::fstream::in );
/** Check if it opened. */
if ( !this->m_ParameterFile.is_open() )
{
itkExceptionMacro( << "ERROR: could not open "
<< this->m_ParameterFileName
<< " for reading." );
}
/** Loop over the parameter file, line by line. */
std::string line = "";
std::string output;
while ( this->m_ParameterFile.good() )
{
/** Extract a line. */
itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, line ); // \todo: returns bool
output += line + "\n";
}
/** Close the parameter file. */
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
/** Return the string. */
return output;
} // end ReturnParameterFileAsString()
} // end namespace itk
#endif // end __itkParameterFileParser_cxx
<commit_msg>MS:<commit_after>/*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkParameterFileParser_cxx
#define __itkParameterFileParser_cxx
#include "itkParameterFileParser.h"
#include <itksys/SystemTools.hxx>
#include <itksys/RegularExpression.hxx>
namespace itk
{
/**
* **************** Constructor ***************
*/
ParameterFileParser
::ParameterFileParser()
{
this->m_ParameterFileName = "";
this->m_ParameterMap.clear();
} // end Constructor()
/**
* **************** Destructor ***************
*/
ParameterFileParser
::~ParameterFileParser()
{
if ( this->m_ParameterFile.is_open() )
{
this->m_ParameterFile.close();
}
} // end Destructor()
/**
* **************** GetParameterMap ***************
*/
const ParameterFileParser::ParameterMapType &
ParameterFileParser
::GetParameterMap( void ) const
{
return this->m_ParameterMap;
} // end GetParameterMap()
/**
* **************** ReadParameterFile ***************
*/
void
ParameterFileParser
::ReadParameterFile( void )
{
/** Perform some basic checks. */
this->BasicFileChecking();
/** Open the parameter file for reading. */
if ( this->m_ParameterFile.is_open() )
{
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
}
this->m_ParameterFile.open( this->m_ParameterFileName.c_str(), std::fstream::in );
/** Check if it opened. */
if ( !this->m_ParameterFile.is_open() )
{
itkExceptionMacro( << "ERROR: could not open "
<< this->m_ParameterFileName
<< " for reading." );
}
/** Clear the map. */
this->m_ParameterMap.clear();
/** Loop over the parameter file, line by line. */
std::string lineIn = "";
std::string lineOut = "";
while ( this->m_ParameterFile.good() )
{
/** Extract a line. */
itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, lineIn );
/** Check this line. */
bool validLine = this->CheckLine( lineIn, lineOut );
if ( validLine )
{
/** Get the parameter name from this line and store it. */
this->GetParameterFromLine( lineIn, lineOut );
}
// Otherwise, we simply ignore this line
}
/** Close the parameter file. */
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
} // end ReadParameterFile()
/**
* **************** BasicFileChecking ***************
*/
void
ParameterFileParser
::BasicFileChecking( void ) const
{
/** Check if the file name is given. */
if ( this->m_ParameterFileName == "" )
{
itkExceptionMacro( << "ERROR: FileName has not been set." );
}
/** Basic error checking: existence. */
bool exists = itksys::SystemTools::FileExists(
this->m_ParameterFileName.c_str() );
if ( !exists )
{
itkExceptionMacro( << "ERROR: the file "
<< this->m_ParameterFileName
<< " does not exist." );
}
/** Basic error checking: file or directory. */
bool isDir = itksys::SystemTools::FileIsDirectory(
this->m_ParameterFileName.c_str() );
if ( isDir )
{
itkExceptionMacro( << "ERROR: the file "
<< this->m_ParameterFileName
<< " is a directory." );
}
/** Check the extension. */
std::string ext = itksys::SystemTools::GetFilenameLastExtension(
this->m_ParameterFileName );
if ( ext != ".txt" )
{
itkExceptionMacro( << "ERROR: the file "
<< this->m_ParameterFileName
<< " should be a text file (*.txt)." );
}
} // end BasicFileChecking()
/**
* **************** CheckLine ***************
*/
bool
ParameterFileParser
::CheckLine( const std::string & lineIn, std::string & lineOut ) const
{
/** Preprocessing of lineIn:
* 1) Replace tabs with spaces
* 2) Remove everything after comment sign //
* 3) Remove leading spaces
* 4) Remove trailing spaces
*/
lineOut = lineIn;
itksys::SystemTools::ReplaceString( lineOut, "\t", " " );
itksys::RegularExpression commentPart( "//" );
if ( commentPart.find( lineOut ) )
{
lineOut = lineOut.substr( 0, commentPart.start() );
}
itksys::RegularExpression leadingSpaces( "^[ ]*(.*)" );
leadingSpaces.find( lineOut );
lineOut = leadingSpaces.match( 1 );
itksys::RegularExpression trailingSpaces( "[ \t]+$" );
if ( trailingSpaces.find( lineOut ) )
{
lineOut = lineOut.substr( 0, trailingSpaces.start() );
}
/**
* Checks:
* 1. Empty line -> false
* 2. Comment (line starts with "//") -> false
* 3. Line is not between brackets (...) -> exception
* 4. Line contains less than two words -> exception
*
* Otherwise return true.
*/
/** 1. Check for non-empty lines. */
itksys::RegularExpression reNonEmptyLine( "[^ ]+" );
bool match1 = reNonEmptyLine.find( lineOut );
if ( !match1 )
{
return false;
}
/** 2. Check for comments. */
itksys::RegularExpression reComment( "^//" );
bool match2 = reComment.find( lineOut );
if ( match2 )
{
return false;
}
/** 3. Check if line is between brackets. */
if ( !itksys::SystemTools::StringStartsWith( lineOut.c_str(), "(" )
|| !itksys::SystemTools::StringEndsWith( lineOut.c_str(), ")" ) )
{
std::string hint = "Line is not between brackets: \"(...)\".";
this->ThrowException( lineIn, hint );
}
/** Remove brackets. */
lineOut = lineOut.substr( 1, lineOut.size() - 2 );
/** 4. Check: the line should contain at least two words. */
itksys::RegularExpression reTwoWords( "([ ]+)([^ ]+)" );
bool match4 = reTwoWords.find( lineOut );
if ( !match4 )
{
std::string hint = "Line does not contain a parameter name and value.";
this->ThrowException( lineIn, hint );
}
/** At this point we know its at least a line containing a parameter.
* However, this line can still be invalid, for example:
* (string &^%^*)
* This will be checked later.
*/
return true;
} // end CheckLine()
/**
* **************** GetParameterFromLine ***************
*/
void
ParameterFileParser
::GetParameterFromLine( const std::string & fullLine,
const std::string & line )
{
/** A line has a parameter name followed by one or more parameters.
* They are all separated by one or more spaces (all tabs have been
* removed previously) or by quotes in case of strings. So,
* 1) we split the line at the spaces or quotes
* 2) the first one is the parameter name
* 3) the other strings that are not a series of spaces, are parameter values
*/
/** 1) Split the line. */
std::vector<std::string> splittedLine;
this->SplitLine( fullLine, line, splittedLine );
/** 2) Get the parameter name. */
std::string parameterName = splittedLine[ 0 ];
itksys::SystemTools::ReplaceString( parameterName, " ", "" );
splittedLine.erase( splittedLine.begin() );
/** 3) Get the parameter values. */
std::vector< std::string > parameterValues;
for ( unsigned int i = 0; i < splittedLine.size(); ++i )
{
if ( splittedLine[ i ] != "" )
{
parameterValues.push_back( splittedLine[ i ] );
}
}
/** 4) Perform some checks on the parameter name. */
itksys::RegularExpression reInvalidCharacters1( "[.,:;!@#$%^&-+|<>?]" );
bool match = reInvalidCharacters1.find( parameterName );
if ( match )
{
std::string hint = "The parameter \""
+ parameterName
+ "\" contains invalid characters (.,:;!@#$%^&-+|<>?).";
this->ThrowException( fullLine, hint );
}
/** 5) Perform checks on the parameter values. */
itksys::RegularExpression reInvalidCharacters2( "[,;!@#$%^&|<>?]" );
for ( unsigned int i = 0; i < parameterValues.size(); ++i )
{
/** For all entries some characters are not allowed. */
if ( reInvalidCharacters2.find( parameterValues[ i ] ) )
{
std::string hint = "The parameter value \""
+ parameterValues[ i ]
+ "\" contains invalid characters (,;!@#$%^&|<>?).";
this->ThrowException( fullLine, hint );
}
}
/** 6) Insert this combination in the parameter map. */
if ( this->m_ParameterMap.count( parameterName ) )
{
std::string hint = "The parameter \""
+ parameterName
+ "\" is specified more than once.";
this->ThrowException( fullLine, hint );
}
else
{
this->m_ParameterMap.insert( make_pair( parameterName, parameterValues ) );
}
} // end GetParameterFromLine()
/**
* **************** SplitLine ***************
*/
void
ParameterFileParser
::SplitLine( const std::string & fullLine, const std::string & line,
std::vector<std::string> & splittedLine ) const
{
splittedLine.clear();
splittedLine.resize( 1 );
std::vector<itksys::String> splittedLine1;
/** Count the number of quotes in the line. If it is an odd value, the
* line contains an error; strings should start and end with a quote, so
* the total number of quotes is even.
*/
std::size_t numQuotes = itksys::SystemTools::CountChar( line.c_str(), '"' );
if ( numQuotes % 2 == 1 )
{
/** An invalid parameter line. */
std::string hint = "This line has an odd number of quotes (\").";
this->ThrowException( fullLine, hint );
}
/** Loop over the line. */
std::string::const_iterator it;
unsigned int index = 0;
numQuotes = 0;
for ( it = line.begin(); it < line.end(); it++ )
{
if ( *it == '"' )
{
/** Start a new element. */
splittedLine.push_back( "" );
index++;
numQuotes++;
}
else if ( *it == ' ' )
{
/** Only start a new element if it is not a quote, otherwise just add
* the space to the string.
*/
if ( numQuotes % 2 == 0 )
{
splittedLine.push_back( "" );
index++;
}
else
{
splittedLine[ index ].push_back( *it );
}
}
else
{
/** Add this character to the element. */
splittedLine[ index ].push_back( *it );
}
}
} // end SplitLine()
/**
* **************** ThrowException ***************
*/
void
ParameterFileParser
::ThrowException( const std::string & line, const std::string & hint ) const
{
/** Construct an error message. */
std::string errorMessage
= "ERROR: the following line in your parameter file is invalid: \n\""
+ line
+ "\"\n"
+ hint
+ "\nPlease correct you parameter file!";
/** Throw exception. */
itkExceptionMacro( << errorMessage.c_str() );
} // end ThrowException()
/**
* **************** ReturnParameterFileAsString ***************
*/
std::string
ParameterFileParser
::ReturnParameterFileAsString( void )
{
/** Perform some basic checks. */
this->BasicFileChecking();
/** Open the parameter file for reading. */
if ( this->m_ParameterFile.is_open() )
{
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
}
this->m_ParameterFile.open( this->m_ParameterFileName.c_str(), std::fstream::in );
/** Check if it opened. */
if ( !this->m_ParameterFile.is_open() )
{
itkExceptionMacro( << "ERROR: could not open "
<< this->m_ParameterFileName
<< " for reading." );
}
/** Loop over the parameter file, line by line. */
std::string line = "";
std::string output;
while ( this->m_ParameterFile.good() )
{
/** Extract a line. */
itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, line ); // \todo: returns bool
output += line + "\n";
}
/** Close the parameter file. */
this->m_ParameterFile.clear();
this->m_ParameterFile.close();
/** Return the string. */
return output;
} // end ReturnParameterFileAsString()
} // end namespace itk
#endif // end __itkParameterFileParser_cxx
<|endoftext|> |
<commit_before>#include "game.hpp"
#include "window.hpp"
#include "clock.hpp"
#include "events.hpp"
#include <iostream>
// "Game" specific data
namespace {
bool gIsRunning = false;
class GameEventEar : public EventEar {
public:
void onWindowClose()
{
Game::stop();
}
};
GameEventEar gEar;
}
void Game::run()
{
// Don't run it twice.
if (gIsRunning)
return;
// Initialize the basics
Window::open(800, 600);
Clock::setTime(0.0);
Events::addEar(&gEar);
// Run the game loop
gIsRunning = true;
Clock::Timer frameCapTimer;
while (gIsRunning)
{
// Poll for new events
Events::poll();
// Perform drawing, logic, etc...
// Cap the framerate at 60
Clock::sleepFor((1.0 / 60.0) - dt.get());
frameCapTimer.set(0.0);
}
// Close the basics
Events::removeEar(&gEar);
Window::close();
}
void Game::stop()
{
gIsRunning = false;
}
<commit_msg>Fix mistaken local variable name.<commit_after>#include "game.hpp"
#include "window.hpp"
#include "clock.hpp"
#include "events.hpp"
#include <iostream>
// "Game" specific data
namespace {
bool gIsRunning = false;
class GameEventEar : public EventEar {
public:
void onWindowClose()
{
Game::stop();
}
};
GameEventEar gEar;
}
void Game::run()
{
// Don't run it twice.
if (gIsRunning)
return;
// Initialize the basics
Window::open(800, 600);
Clock::setTime(0.0);
Events::addEar(&gEar);
// Run the game loop
gIsRunning = true;
Clock::Timer frameCapTimer;
while (gIsRunning)
{
// Poll for new events
Events::poll();
// Perform drawing, logic, etc...
// Cap the framerate at 60
Clock::sleepFor((1.0 / 60.0) - frameCapTimer.get());
frameCapTimer.set(0.0);
}
// Close the basics
Events::removeEar(&gEar);
Window::close();
}
void Game::stop()
{
gIsRunning = false;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>
#include "functions.h"
int main(int argc, char** argv)
{
// hold a raw line of input
std::string line;
// print welcome message and prompt
printf("Welcome to rshell!\n");
while (true)
{
// holds a single command and its arguments
Command cmd;
// holds multiple commands
std::vector<Command> cmds;
// print prompt and get a line of text (done in condition)
printf("$ ");
getline(std::cin, line);
// look for comments
if (line.find("#") != std::string::npos)
{
// remove them if necessary (they're useless)
line = line.substr(0, line.find("#"));
}
// remove leading whitespace
while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
{
line = line.substr(1, line.size() - 1);
}
// adding a space to the end makes parsing easier
line += ' ';
if (std::cin.fail())
{
printf("\nGoodbye!\n");
exit(0);
}
int mode = GETWORD;
unsigned begin = 0;
// temporary: show pre-processed input to know what's being dealt with
printf("You entered: \"%s\"\n", line.c_str());
// prepare cmd
cmd.connector = NONE;
// syntax error flag
bool se = false;
// starts with a connector? I don't think so
if (line.size() > 0 && isConn(line[0]))
{
se = true;
}
// handle the input
for(unsigned i = 0; i < line.size() && !se; ++i)
{
bool con = isConn(line[i]);
bool space = isspace(line[i]);
// if we're getting a word and there's a whitespace or connector here
if (mode == GETWORD && (space || con))
{
// chunk the last term and throw it into the vector
char* c = stocstr(line.substr(begin, i - begin));
if (strlen(c) > 0)
{
cmd.args.push_back(c);
}
else
{
printf("Oh no! Recieved a word with no length\n");
break;
}
if (space)
{
mode = TRIMSPACE;
}
else // it's a connector
{
handleCon(cmds, cmd, line, mode, i, se);
}
}
else if (mode == TRIMSPACE && (!space || con))
{
if (con && cmd.args.empty())
{
se = true;
}
else if (con)
{
handleCon(cmds, cmd, line, mode, i, se);
}
else
{
mode = GETWORD;
begin = i;
}
}
if (i + 1 == line.size() && !cmd.args.empty()) // parsing the last character
{
// if it has a continuation connector, and we're finished with parsing, syntax error
if (cmd.connector == AND || cmd.connector == OR)
{
se = true;
}
else
{
cmds.push_back(cmd);
}
}
}
// if the last command has a continuation connector, syntax error
if (cmds.size() > 0 && (cmds[cmds.size() - 1].connector == AND
|| cmds[cmds.size() - 1].connector == OR))
{
se = true;
}
// if there was a syntax error
if (se)
{
printf("Syntax error detected\n");
continue;
}
for(unsigned i = 0; i < cmds.size(); ++i)
{
printf("Command %u:\n", i);
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
printf("\t\"%s\"\n", cmds[i].args[j]);
}
switch(cmds[i].connector)
{
case AND:
printf("\t&&\n");
break;
case OR:
printf("\t||\n");
break;
case SEMI:
printf("\t;\n");
break;
case NONE:
printf("\tNo connector\n");
break;
default:
printf("\tERROR: no valid connector specified\n");
}
}
// deallocate allocated memory
for(unsigned i = 0; i < cmds.size(); ++i)
{
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
delete[] cmds[i].args[j];
}
}
}
return 0;
}
<commit_msg>changed messages to the user<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>
#include "functions.h"
int main(int argc, char** argv)
{
// hold a raw line of input
std::string line;
// print welcome message and prompt
printf("Welcome to rshell!\n");
while (true)
{
// holds a single command and its arguments
Command cmd;
// holds multiple commands
std::vector<Command> cmds;
// print prompt and get a line of text (done in condition)
printf("$ ");
getline(std::cin, line);
// look for comments
if (line.find("#") != std::string::npos)
{
// remove them if necessary (they're useless)
line = line.substr(0, line.find("#"));
}
// remove leading whitespace
while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
{
line = line.substr(1, line.size() - 1);
}
// adding a space to the end makes parsing easier
line += ' ';
if (std::cin.fail())
{
printf("\nGoodbye!\n");
exit(0);
}
int mode = GETWORD;
unsigned begin = 0;
// temporary: show pre-processed input to know what's being dealt with
printf("You entered: \"%s\"\n", line.c_str());
// prepare cmd
cmd.connector = NONE;
// syntax error flag
bool se = false;
// starts with a connector? I don't think so
if (line.size() > 0 && isConn(line[0]))
{
se = true;
}
// handle the input
for(unsigned i = 0; i < line.size() && !se; ++i)
{
bool con = isConn(line[i]);
bool space = isspace(line[i]);
// if we're getting a word and there's a whitespace or connector here
if (mode == GETWORD && (space || con))
{
// chunk the last term and throw it into the vector
char* c = stocstr(line.substr(begin, i - begin));
if (strlen(c) > 0)
{
cmd.args.push_back(c);
}
else
{
// only happens when nothing is entered. breaks so nothing more happens
break;
}
if (space)
{
mode = TRIMSPACE;
}
else // it's a connector
{
handleCon(cmds, cmd, line, mode, i, se);
}
}
else if (mode == TRIMSPACE && (!space || con))
{
if (con && cmd.args.empty())
{
se = true;
}
else if (con)
{
handleCon(cmds, cmd, line, mode, i, se);
}
else
{
mode = GETWORD;
begin = i;
}
}
if (i + 1 == line.size() && !cmd.args.empty()) // parsing the last character
{
// if it has a continuation connector, and we're finished with parsing, syntax error
if (cmd.connector == AND || cmd.connector == OR)
{
se = true;
}
else
{
cmds.push_back(cmd);
}
}
}
// if the last command has a continuation connector, syntax error
if (cmds.size() > 0 && (cmds[cmds.size() - 1].connector == AND
|| cmds[cmds.size() - 1].connector == OR))
{
se = true;
}
// if there was a syntax error
if (se)
{
printf("Syntax error\n");
continue;
}
for(unsigned i = 0; i < cmds.size(); ++i)
{
printf("Command %u:\n", i);
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
printf("\t\"%s\"\n", cmds[i].args[j]);
}
switch(cmds[i].connector)
{
case AND:
printf("\t&&\n");
break;
case OR:
printf("\t||\n");
break;
case SEMI:
printf("\t;\n");
break;
case NONE:
printf("\tNo connector\n");
break;
default:
printf("\tERROR: no valid connector specified\n");
}
}
// deallocate allocated memory
for(unsigned i = 0; i < cmds.size(); ++i)
{
for(unsigned j = 0; j < cmds[i].args.size(); ++j)
{
delete[] cmds[i].args[j];
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <limits.h>
#include <manyclaw/manyclaw.h>
#include "gtest/gtest.h"
::testing::AssertionResult ArraysMatch(const real *expected,
const real *actual, int size){
for (int i=0; i < size; ++i){
if (fabs(expected[i] - actual[i]) > 1e-8){
return ::testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
}
return ::testing::AssertionSuccess();
}
// Test the indexer methods
TEST(AdvectionStepper, base) {
int nx = 5, ny = 5;
int num_ghost = advection_rp_grid_params.num_ghost;
int num_eqns = advection_rp_grid_params.num_eqn;
int num_waves = advection_rp_grid_params.num_waves;
FieldIndexer fi(nx, ny, num_ghost, num_eqns);
EdgeFieldIndexer efi(nx, ny, num_ghost, num_eqns, num_waves);
real q[fi.size()];
real amdq[efi.size()], amdq_gold[efi.size()];
real apdq[efi.size()], apdq_gold[efi.size()];
real wave[efi.size()], wave_gold[efi.size()];
real speed[efi.size()], speed_gold[efi.size()];
for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx)
q[idx] = 0.0;
q[fi.idx(5, 5)] = 1.0;
for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx) {
wave_gold[idx] = 0.0;
speed_gold[idx] = 1.0;
amdq_gold[idx] = 0.0;
apdq_gold[idx] = 0.0;
}
wave_gold[efi.left_edge(5,5)] = 1.0;
speed_gold[efi.left_edge(5,5)] = 1.0;
amdq_gold[efi.left_edge(5,5)] = 0.0;
apdq_gold[efi.left_edge(5,5)] = 1.0;
wave_gold[efi.right_edge(5,5)] = -1.0;
speed_gold[efi.right_edge(5,5)] = 1.0;
amdq_gold[efi.right_edge(5,5)] = 0.0;
apdq_gold[efi.right_edge(5,5)] = -1.0;
wave_gold[efi.down_edge(5,5)] = 1.0;
speed_gold[efi.down_edge(5,5)] = 1.0;
amdq_gold[efi.down_edge(5,5)] = 0.0;
apdq_gold[efi.down_edge(5,5)] = 1.0;
wave_gold[efi.up_edge(5,5)] = -1.0;
speed_gold[efi.up_edge(5,5)] = 1.0;
amdq_gold[efi.up_edge(5,5)] = 0.0;
apdq_gold[efi.up_edge(5,5)] = -1.0;
advection_rp_step_serial_cellwise(q, NULL, nx, ny, amdq, apdq, wave, speed);
EXPECT_TRUE(ArraysMatch(wave_gold, wave, efi.size()));
EXPECT_TRUE(ArraysMatch(speed_gold, speed, efi.size()));
EXPECT_TRUE(ArraysMatch(amdq_gold, amdq, efi.size()));
EXPECT_TRUE(ArraysMatch(apdq_gold, apdq, efi.size()));
}
<commit_msg>Making prettier test<commit_after>#include <limits.h>
#include <manyclaw/manyclaw.h>
#include "gtest/gtest.h"
::testing::AssertionResult ArraysMatch(const real *expected,
const real *actual, int size){
std::vector<int> bad_loc;
for (int i=0; i < size; ++i){
if (std::fabs(expected[i] - actual[i]) > 1e-8){
bad_loc.push_back(i);
}
}
if (bad_loc.size() > 0) {
std::ostringstream fail;
fail << std::endl;
for(size_t i=0; i < bad_loc.size(); ++i){
int idx = bad_loc[i];
fail << std::scientific
<< " array[" << idx
<< "] (" << actual[idx] << ") != expected[" << idx
<< "] (" << expected[idx] << ")\n";
}
fail << " Num_wrong:" << bad_loc.size();
return ::testing::AssertionFailure() << fail.str();
}
return ::testing::AssertionSuccess();
}
// Test the indexer methods
TEST(AdvectionStepper, base) {
int nx = 5, ny = 5;
int num_ghost = advection_rp_grid_params.num_ghost;
int num_eqns = advection_rp_grid_params.num_eqn;
int num_waves = advection_rp_grid_params.num_waves;
FieldIndexer fi(nx, ny, num_ghost, num_eqns);
EdgeFieldIndexer efi(nx, ny, num_ghost, num_eqns, num_waves);
real q[fi.size()];
real amdq[efi.size()], amdq_gold[efi.size()];
real apdq[efi.size()], apdq_gold[efi.size()];
real wave[efi.size()], wave_gold[efi.size()];
real speed[efi.size()], speed_gold[efi.size()];
for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx)
q[idx] = 0.0;
q[fi.idx(5, 5)] = 1.0;
for(int idx=0; idx < fi.row_size() * fi.col_size(); ++idx) {
wave_gold[idx] = 0.0;
speed_gold[idx] = 1.0;
amdq_gold[idx] = 0.0;
apdq_gold[idx] = 0.0;
}
wave_gold[efi.left_edge(5,5)] = 1.0;
speed_gold[efi.left_edge(5,5)] = 1.0;
amdq_gold[efi.left_edge(5,5)] = 0.0;
apdq_gold[efi.left_edge(5,5)] = 1.0;
wave_gold[efi.right_edge(5,5)] = -1.0;
speed_gold[efi.right_edge(5,5)] = 1.0;
amdq_gold[efi.right_edge(5,5)] = 0.0;
apdq_gold[efi.right_edge(5,5)] = -1.0;
wave_gold[efi.down_edge(5,5)] = 1.0;
speed_gold[efi.down_edge(5,5)] = 1.0;
amdq_gold[efi.down_edge(5,5)] = 0.0;
apdq_gold[efi.down_edge(5,5)] = 1.0;
wave_gold[efi.up_edge(5,5)] = -1.0;
speed_gold[efi.up_edge(5,5)] = 1.0;
amdq_gold[efi.up_edge(5,5)] = 0.0;
apdq_gold[efi.up_edge(5,5)] = -1.0;
advection_rp_step_serial_cellwise(q, NULL, nx, ny, amdq, apdq, wave, speed);
EXPECT_TRUE(ArraysMatch(wave, wave_gold, efi.size()));
EXPECT_TRUE(ArraysMatch(speed, speed_gold, efi.size()));
EXPECT_TRUE(ArraysMatch(amdq, amdq_gold, efi.size()));
EXPECT_TRUE(ArraysMatch(apdq, apdq_gold, efi.size()));
}
<|endoftext|> |
<commit_before>#include "game.hpp"
#include <iostream>
#include "exception.hpp"
namespace Quoridor {
Game::Game(Board *board) : board_(board), player_list_()
{
}
Game::~Game()
{
}
void Game::main_loop()
{
while (true) {
for (auto *player: player_list_) {
make_move(player);
}
}
}
void Game::add_player(Player *player)
{
int board_side = board_->next_side();
player->set_board_side(board_side);
pos_t pos;
switch (board_side) {
case 0:
pos.first = 0;
pos.second = 4;
break;
case 1:
pos.first = 4;
pos.second = 0;
break;
case 2:
pos.first = 8;
pos.second = 4;
break;
case 3:
pos.first = 4;
pos.second = 8;
break;
default:
throw Exception();
}
player->set_pos(pos);
board_->add_occupied(pos);
player_list_.push_back(player);
}
void Game::make_move(Player *player)
{
int move;
while (true) {
std::cout << "make move ";
std::cin >> move;
if ((move >= 0) && (move <= 4)) {
break;
}
}
pos_t fin_pos;
move = (move + player->board_side()) % 4;
if (board_->make_move(move, player->pos(), &fin_pos) == 0) {
std::cout << player->name() << ": ("
<< player->pos().first << "," << player->pos().second << " => ("
<< fin_pos.first << "," << fin_pos.second << ")" << std::endl;
board_->rm_occupied(player->pos());
player->set_pos(fin_pos);
board_->add_occupied(fin_pos);
}
}
bool Game::is_win(const Player *player) const
{
return board_->is_at_opposite_side(player->board_side(), player->pos());
}
} /* namespace Quoridor */
<commit_msg>Check if player wins after each move.<commit_after>#include "game.hpp"
#include <iostream>
#include "exception.hpp"
namespace Quoridor {
Game::Game(Board *board) : board_(board), player_list_()
{
}
Game::~Game()
{
}
void Game::main_loop()
{
while (true) {
for (auto *player: player_list_) {
make_move(player);
if (is_win(player)) {
std::cout << player->name() << " win" << std::endl;
}
}
}
}
void Game::add_player(Player *player)
{
int board_side = board_->next_side();
player->set_board_side(board_side);
pos_t pos;
switch (board_side) {
case 0:
pos.first = 0;
pos.second = 4;
break;
case 1:
pos.first = 4;
pos.second = 0;
break;
case 2:
pos.first = 8;
pos.second = 4;
break;
case 3:
pos.first = 4;
pos.second = 8;
break;
default:
throw Exception();
}
player->set_pos(pos);
board_->add_occupied(pos);
player_list_.push_back(player);
}
void Game::make_move(Player *player)
{
int move;
while (true) {
std::cout << "make move ";
std::cin >> move;
if ((move >= 0) && (move <= 4)) {
break;
}
}
pos_t fin_pos;
move = (move + player->board_side()) % 4;
if (board_->make_move(move, player->pos(), &fin_pos) == 0) {
std::cout << player->name() << ": ("
<< player->pos().first << "," << player->pos().second << " => ("
<< fin_pos.first << "," << fin_pos.second << ")" << std::endl;
board_->rm_occupied(player->pos());
player->set_pos(fin_pos);
board_->add_occupied(fin_pos);
}
}
bool Game::is_win(const Player *player) const
{
return board_->is_at_opposite_side(player->board_side(), player->pos());
}
} /* namespace Quoridor */
<|endoftext|> |
<commit_before>#include <SDL/SDL.h>
#ifdef __APPLE__
#include <SDL_mixer/SDL_mixer.h>
#else
#include <SDL/SDL_mixer.h>
#endif
#include "main.h"
#include "game.h"
#include "map.h"
#include "hud.h"
#include "sprite.h"
extern int resetTimer;
extern SDL_Surface *screen;
Game::Game()
{
}
bool Game::hitTarget(Sprite *hero,Sprite *target,Map &map,Hud &hud)
{
float deltax,deltay;
float dist;
deltax=target->x-hero->x;
deltay=target->y-hero->y;
dist=deltax*deltax+deltay*deltay;
if(dist<32*32) {
hero->score++;
hud.animateScore(map.viewx,map.viewy,hero);
return true;
}
return false;
}
void Game::mapReset(Map &map)
{
// hero.reset(64,128);
// baddie.reset(64,128);
// i=(rand()%(map.getTilesAcross()-3))+2;
// j=(rand()%(map.getTilesDown()-2))+1;
// target.reset(32*i,32*j);
int x,j;
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
x=(rand()%(map.getTilesAcross()-3))+2;
j=(rand()%(map.getTilesDown()-2))+1;
Sprite *player=*p;
player->reset(32*x, 32*j);
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
x=(rand()%(map.getTilesAcross()-3))+2;
j=(rand()%(map.getTilesDown()-2))+1;
Sprite *item=*p;
item->reset(32*x, 32*j);
}
// map.calculateGradient(&target);
// resetTimer=3000;
// Mix_PauseMusic();
// map.updateView(&target);
}
void Game::newGame(Map &map)
{
//for (int i = 0; i < _playerList.size(); i++) {
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
Sprite *player=*p;
player->score = 0;
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
Sprite *item=*p;
item->score = 0;
}
mapReset(map);
playSound(S_START);
}
void Game::update(Map &map,Hud &hud)
{
map.updatePhysics();
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
Sprite *player=*p;
player->updatePhysics(&map);
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
Sprite *item=*p;
item->updatePhysics(&map);
}
//baddie.x=200;
// if(resetTimer>0) {
// resetTimer-=16;
// if(resetTimer<=0) {
// resetTimer=0;
// Mix_ResumeMusic();
// }
// } else {
// map.updateView(&hero); //, &baddie);
// }
// hud.update(&hero, &baddie);
// if( hitTarget(&hero,&target,map,hud) || hitTarget(&baddie,&target,map,hud)) {
// mapReset(map);
// playSound(S_MATCH);
// if(hud.leftScore>8 || hud.rightScore>8) gameMode=MODE_WINNER;
// }
}
SDL_Surface *titleImage=0;
SDL_Surface *menuImage=0;
void Game::draw(Map &map,Hud &hud)
{
#ifdef _PSP
oslStartDrawing(); //To be able to draw on the screen
#else
static SDL_Surface *bgImage=0;
//if(!bgImage) bgImage=IMG_Load("data/title.png");
//if(bgImage) SDL_BlitSurface(bgImage,0,screen,0);
//else
SDL_FillRect(screen,0,SDL_MapRGB(screen->format,240,240,128));
#endif
map.draw(); //Draw the images to the screen
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
Sprite *player=*p;
player->draw(map.viewx,map.viewy);
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
Sprite *item=*p;
item->draw(map.viewx,map.viewy);
}
hud.draw();
if( gameMode==MODE_TITLE) {
if(!titleImage) titleImage=IMG_Load("data/title.png");
if(titleImage) SDL_BlitSurface( titleImage, NULL, screen, NULL);
} else {
if(titleImage) SDL_FreeSurface( titleImage);
titleImage=0;
}
if( gameMode==MODE_MENU) {
if(!menuImage) menuImage=IMG_Load("data/menu.png");
if(menuImage) SDL_BlitSurface( menuImage, NULL, screen, NULL);
} else {
if(menuImage) SDL_FreeSurface( menuImage);
menuImage=0;
}
#ifdef _PSP
oslEndDrawing(); //Ends drawing mode
oslEndFrame();
oslSyncFrame(); //Synchronizes the screen
#else
SDL_Flip(screen);
static long before;
long now=SDL_GetTicks();
long delay=before+32-now;
if(delay>0 && delay<60) SDL_Delay(delay);
before=now;
#endif
}
void Game::handleUp(int key)
{
}
void Game::handleDown(int key)
{
}
void Game::addCharSprite(Sprite* spriteToAdd){
_playerList.push_back(spriteToAdd);
printf("Success\n");
}
void Game::addItemSprite(Sprite *spriteToAdd){
_itemList.push_back(spriteToAdd);
}
<commit_msg>New Background<commit_after>#include <SDL/SDL.h>
#ifdef __APPLE__
#include <SDL_mixer/SDL_mixer.h>
#else
#include <SDL/SDL_mixer.h>
#endif
#include "main.h"
#include "game.h"
#include "map.h"
#include "hud.h"
#include "sprite.h"
extern int resetTimer;
extern SDL_Surface *screen;
Game::Game()
{
}
bool Game::hitTarget(Sprite *hero,Sprite *target,Map &map,Hud &hud)
{
float deltax,deltay;
float dist;
deltax=target->x-hero->x;
deltay=target->y-hero->y;
dist=deltax*deltax+deltay*deltay;
if(dist<32*32) {
hero->score++;
hud.animateScore(map.viewx,map.viewy,hero);
return true;
}
return false;
}
void Game::mapReset(Map &map)
{
// hero.reset(64,128);
// baddie.reset(64,128);
// i=(rand()%(map.getTilesAcross()-3))+2;
// j=(rand()%(map.getTilesDown()-2))+1;
// target.reset(32*i,32*j);
int x,j;
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
x=(rand()%(map.getTilesAcross()-3))+2;
j=(rand()%(map.getTilesDown()-2))+1;
Sprite *player=*p;
player->reset(32*x, 32*j);
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
x=(rand()%(map.getTilesAcross()-3))+2;
j=(rand()%(map.getTilesDown()-2))+1;
Sprite *item=*p;
item->reset(32*x, 32*j);
}
// map.calculateGradient(&target);
// resetTimer=3000;
// Mix_PauseMusic();
// map.updateView(&target);
}
void Game::newGame(Map &map)
{
//for (int i = 0; i < _playerList.size(); i++) {
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
Sprite *player=*p;
player->score = 0;
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
Sprite *item=*p;
item->score = 0;
}
mapReset(map);
playSound(S_START);
}
void Game::update(Map &map,Hud &hud)
{
map.updatePhysics();
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
Sprite *player=*p;
player->updatePhysics(&map);
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
Sprite *item=*p;
item->updatePhysics(&map);
}
//baddie.x=200;
// if(resetTimer>0) {
// resetTimer-=16;
// if(resetTimer<=0) {
// resetTimer=0;
// Mix_ResumeMusic();
// }
// } else {
// map.updateView(&hero); //, &baddie);
// }
// hud.update(&hero, &baddie);
// if( hitTarget(&hero,&target,map,hud) || hitTarget(&baddie,&target,map,hud)) {
// mapReset(map);
// playSound(S_MATCH);
// if(hud.leftScore>8 || hud.rightScore>8) gameMode=MODE_WINNER;
// }
}
SDL_Surface *titleImage=0;
SDL_Surface *menuImage=0;
void Game::draw(Map &map,Hud &hud)
{
#ifdef _PSP
oslStartDrawing(); //To be able to draw on the screen
#else
static SDL_Surface *bgImage=0;
//if(!bgImage) bgImage=IMG_Load("data/title.png");
//if(bgImage) SDL_BlitSurface(bgImage,0,screen,0);
//else
SDL_FillRect(screen,0,SDL_MapRGB(screen->format,189, 237, 255));
#endif
map.draw(); //Draw the images to the screen
for( SpriteList::iterator p=_playerList.begin(); p!=_playerList.end(); p++) {
Sprite *player=*p;
player->draw(map.viewx,map.viewy);
}
for( SpriteList::iterator p=_itemList.begin(); p!=_itemList.end(); p++) {
Sprite *item=*p;
item->draw(map.viewx,map.viewy);
}
hud.draw();
if( gameMode==MODE_TITLE) {
if(!titleImage) titleImage=IMG_Load("data/title.png");
if(titleImage) SDL_BlitSurface( titleImage, NULL, screen, NULL);
} else {
if(titleImage) SDL_FreeSurface( titleImage);
titleImage=0;
}
if( gameMode==MODE_MENU) {
if(!menuImage) menuImage=IMG_Load("data/menu.png");
if(menuImage) SDL_BlitSurface( menuImage, NULL, screen, NULL);
} else {
if(menuImage) SDL_FreeSurface( menuImage);
menuImage=0;
}
#ifdef _PSP
oslEndDrawing(); //Ends drawing mode
oslEndFrame();
oslSyncFrame(); //Synchronizes the screen
#else
SDL_Flip(screen);
static long before;
long now=SDL_GetTicks();
long delay=before+32-now;
if(delay>0 && delay<60) SDL_Delay(delay);
before=now;
#endif
}
void Game::handleUp(int key)
{
}
void Game::handleDown(int key)
{
}
void Game::addCharSprite(Sprite* spriteToAdd){
_playerList.push_back(spriteToAdd);
printf("Success\n");
}
void Game::addItemSprite(Sprite *spriteToAdd){
_itemList.push_back(spriteToAdd);
}
<|endoftext|> |
<commit_before>#include <PlatformSpecification.h>
#include <Framebuffer.h>
#include <Perlin.h>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/random.hpp>
#include <fstream>
#include <string>
#define WIDTH 700
#define HEIGHT 500
#define SIZE WIDTH * HEIGHT
struct InputData
{
float Da;
float Db;
float f;
float k;
float delta;
};
struct SimData
{
float a_current[SIZE];
float b_current[SIZE];
float a_buffer[SIZE];
float b_buffer[SIZE];
};
std::string read_file(const char _filepath[])
{
std::string output;
std::ifstream file(_filepath);
if(file.is_open())
{
std::string line;
while(!file.eof())
{
std::getline(file, line);
output.append(line + "\n");
}
}
else
{
std::cout << "File could not be opened." << std::endl;
exit(EXIT_FAILURE);
}
file.close();
return output;
}
void opencl_error_check(const cl_int _error)
{
if(_error != CL_SUCCESS)
{
std::cout << "OpenCL error: " << _error << std::endl;
exit(EXIT_FAILURE);
}
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
InputData *input = static_cast<InputData*>(glfwGetWindowUserPointer(window));
if(action == GLFW_PRESS)
{
switch(key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_Q:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_A:
input->Da *= 1.25f;
std::cout << input->Da << std::endl;
break;
case GLFW_KEY_Z:
input->Da *= 0.8f;
std::cout << input->Da << std::endl;
break;
case GLFW_KEY_S:
input->Db *= 1.25f;
std::cout << input->Db << std::endl;
break;
case GLFW_KEY_X:
input->Db *= 0.8f;
std::cout << input->Db << std::endl;
break;
case GLFW_KEY_D:
input->f *= 1.25f;
std::cout << "f = " << input->f << std::endl;
break;
case GLFW_KEY_C:
input->f *= 0.8f;
std::cout << "f = " << input->f << std::endl;
break;
case GLFW_KEY_F:
input->k *= 1.25f;
std::cout << "k = " << input->k << std::endl;
break;
case GLFW_KEY_V:
input->k *= 0.8f;
std::cout << "k = " << input->k << std::endl;
break;
}
}
}
int mod(const int _a, const int _b)
{
int value = _a % _b;
if (value < 0)
value += _b;
return value;
}
float laplacian(const float* _array, const int _point, const int _width, const int _height)
{
int xpos = _point % _width;
int ypos = _point / _width;
int positive_x = mod(xpos + 1, _width);
int negative_x = mod(xpos - 1, _width);
int positive_y = mod(ypos + 1, _height) * _width;
int negative_y = mod(ypos - 1, _height) * _width;
int index[] = {
negative_x + positive_y, xpos + positive_y, positive_x + positive_y,
negative_x + ypos * _width, xpos + ypos * _width, positive_x + ypos * _width,
negative_x + negative_y, xpos + negative_y, positive_x + negative_y
};
float weight[] = {
0.05f, 0.2f, 0.05f,
0.2f, -1.f, 0.2f,
0.05f, 0.2f, 0.05f
};
float output = _array[index[0]] * weight[0] + _array[index[1]] * weight[1] + _array[index[2]] * weight[2]
+ _array[index[3]] * weight[3] + _array[index[4]] * weight[4] + _array[index[5]] * weight[5]
+ _array[index[6]] * weight[6] + _array[index[7]] * weight[7] + _array[index[8]] * weight[8];
return output;
}
int main(int argc, char const *argv[])
{
InputData input;
input.Da = 1.f;
input.Db = 0.5f;
input.f = 0.018f;
input.k = 0.051f;
input.delta = 0.8f;
Framebuffer *framebuffer = new Framebuffer();
GLFWwindow* window = framebuffer->init(WIDTH, HEIGHT, &input);
glfwSetKeyCallback(window, keyCallback);
Perlin perlin;
SimData *data = new SimData;
for(int i = 0; i < SIZE; ++i)
{
float xpos = i % WIDTH;
float ypos = i / WIDTH;
if(perlin.noise(xpos / 100, ypos / 100, 0) > 0.4f)
{
data->a_current[i] = 1.f;
data->b_current[i] = 1.f;
data->a_buffer[i] = 0.f;
data->b_buffer[i] = 0.f;
}
else
{
data->a_current[i] = 1.f;
data->b_current[i] = 0.f;
data->a_buffer[i] = 0.f;
data->b_buffer[i] = 0.f;
}
}
float *image = new float[SIZE*3];
for(int i = 0; i < SIZE; ++i)
{
image[i * 3 + 0] = data->a_current[i];
image[i * 3 + 1] = data->a_current[i];
image[i * 3 + 2] = data->a_current[i];
}
framebuffer->image(image, WIDTH, HEIGHT);
// OpenCL setup starts here
// Setup
cl_platform_id platform_id;
clGetPlatformIDs(1, &platform_id, NULL);
cl_uint device_count;
clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &device_count);
cl_device_id *device_ids = new cl_device_id[device_count];
clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, device_count, device_ids, NULL);
// Error code
cl_int error = CL_SUCCESS;
// Context creation
const cl_context_properties context_properties[] = {
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform_id),
0
};
cl_context context = clCreateContext(context_properties, device_count, device_ids, NULL, NULL, &error);
opencl_error_check(error);
// GLuint m_texture;
// glGenTextures(1, &m_texture);
// glBindTexture(GL_TEXTURE_2D, m_texture);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);
// Memory allocation
cl_mem cMem_a = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_current, &error);
opencl_error_check(error);
cl_mem cMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_current, &error);
opencl_error_check(error);
cl_mem bMem_a = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_buffer, &error);
opencl_error_check(error);
cl_mem bMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_buffer, &error);
opencl_error_check(error);
// cl_mem mem = clCreateFromGLTexture(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &error);
// opencl_error_check(error);
// Load source file
std::string file = read_file("kernals/image.cl");
const char* source[] = {file.c_str()};
// Build program
cl_program program = clCreateProgramWithSource(context, 1, source, NULL, &error);
opencl_error_check(error);
error = clBuildProgram(program, device_count, device_ids, NULL, NULL, NULL);
if(error != CL_SUCCESS)
{
char buffer[2048];
clGetProgramBuildInfo(program, device_ids[0], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, NULL);
std::cout << buffer << std::endl;
exit(EXIT_FAILURE);
}
// Resolution for kernal
const float width = WIDTH;
const float height = HEIGHT;
// Create kernel one
cl_kernel kernel_one = clCreateKernel(program, "square", &error);
opencl_error_check(error);
// Set argurments for kernel one
clSetKernelArg(kernel_one, 0, sizeof(cl_mem), &cMem_a);
clSetKernelArg(kernel_one, 1, sizeof(cl_mem), &cMem_b);
clSetKernelArg(kernel_one, 2, sizeof(cl_mem), &bMem_a);
clSetKernelArg(kernel_one, 3, sizeof(cl_mem), &bMem_b);
clSetKernelArg(kernel_one, 4, sizeof(InputData), &input);
clSetKernelArg(kernel_one, 5, sizeof(float), &width);
clSetKernelArg(kernel_one, 6, sizeof(float), &height);
// Create kernel two
cl_kernel kernel_two = clCreateKernel(program, "square", &error);
opencl_error_check(error);
// Set argurments for kernel two
clSetKernelArg(kernel_two, 0, sizeof(cl_mem), &bMem_a);
clSetKernelArg(kernel_two, 1, sizeof(cl_mem), &bMem_b);
clSetKernelArg(kernel_two, 2, sizeof(cl_mem), &cMem_a);
clSetKernelArg(kernel_two, 3, sizeof(cl_mem), &cMem_b);
clSetKernelArg(kernel_two, 4, sizeof(InputData), &input);
clSetKernelArg(kernel_two, 5, sizeof(float), &width);
clSetKernelArg(kernel_two, 6, sizeof(float), &height);
// Create queue
cl_command_queue queue = clCreateCommandQueue(context, device_ids[0], 0, &error);
opencl_error_check(error);
// OpenCL setup ends here
framebuffer->bind();
unsigned int iteration = 0;
boost::chrono::milliseconds iteration_delta(static_cast<int>((1000.f / 60.f) * input.delta));
while( !framebuffer->close() )
{
boost::chrono::high_resolution_clock::time_point timer_start = boost::chrono::high_resolution_clock::now();
// for(int i = 0; i < SIZE; ++i)
// {
// data->a_buffer[i] = data->a_current[i];
// data->b_buffer[i] = data->b_current[i];
// float reaction = data->a_buffer[i] * (data->b_buffer[i] * data->b_buffer[i]);
// data->a_current[i] = data->a_buffer[i] + (input.Da * laplacian(data->a_buffer, i, WIDTH, HEIGHT) - reaction + input.f * (1.f - data->a_buffer[i])) * input.delta;
// data->b_current[i] = data->b_buffer[i] + (input.Db * laplacian(data->b_buffer, i, WIDTH, HEIGHT) + reaction - (input.k + input.f) * data->b_buffer[i]) * input.delta;
// }
// Run queue
std::size_t size[] = {SIZE};
error = clEnqueueNDRangeKernel(queue, (iteration % 2) ? kernel_one : kernel_two, 1, 0, size, NULL, 0, NULL, NULL);
opencl_error_check(error);
// Get data from GPU
error = clEnqueueReadBuffer(queue, cMem_a, CL_TRUE, 0, sizeof(float) * SIZE, data->a_current, 0, NULL, NULL);
opencl_error_check(error);
for(int i = 0; i < SIZE; ++i)
{
float current = image[i * 3 + 0];
image[i * 3 + 0] = data->a_current[i];
image[i * 3 + 1] = data->a_current[i];
image[i * 3 + 2] = data->a_current[i];
}
framebuffer->image(image, WIDTH, HEIGHT);
framebuffer->draw();
std::string title = "Graphics Environment Iteration: " + std::to_string(++iteration);
framebuffer->title(title);
boost::chrono::high_resolution_clock::time_point timer_end = boost::chrono::high_resolution_clock::now();
boost::chrono::milliseconds iteration_time(boost::chrono::duration_cast<boost::chrono::milliseconds>(timer_end - timer_start).count());
if(iteration_time < iteration_delta)
{
boost::this_thread::sleep_for(iteration_delta - iteration_time);
}
}
// Cleanup
clReleaseCommandQueue(queue);
clReleaseMemObject(bMem_b);
clReleaseMemObject(bMem_a);
clReleaseMemObject(cMem_b);
clReleaseMemObject(cMem_a);
clReleaseKernel(kernel_two);
clReleaseKernel(kernel_one);
clReleaseProgram(program);
clReleaseContext(context);
delete[] device_ids;
delete data;
delete framebuffer;
delete[] image;
exit(EXIT_SUCCESS);
}<commit_msg>Removed code for CPU simulation<commit_after>#include <PlatformSpecification.h>
#include <Framebuffer.h>
#include <Perlin.h>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/random.hpp>
#include <fstream>
#include <string>
#define WIDTH 700
#define HEIGHT 500
#define SIZE WIDTH * HEIGHT
struct InputData
{
float Da;
float Db;
float f;
float k;
float delta;
};
struct SimData
{
float a_current[SIZE];
float b_current[SIZE];
float a_buffer[SIZE];
float b_buffer[SIZE];
};
std::string read_file(const char _filepath[])
{
std::string output;
std::ifstream file(_filepath);
if(file.is_open())
{
std::string line;
while(!file.eof())
{
std::getline(file, line);
output.append(line + "\n");
}
}
else
{
std::cout << "File could not be opened." << std::endl;
exit(EXIT_FAILURE);
}
file.close();
return output;
}
void opencl_error_check(const cl_int _error)
{
if(_error != CL_SUCCESS)
{
std::cout << "OpenCL error: " << _error << std::endl;
exit(EXIT_FAILURE);
}
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
InputData *input = static_cast<InputData*>(glfwGetWindowUserPointer(window));
if(action == GLFW_PRESS)
{
switch(key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_Q:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_A:
input->Da *= 1.25f;
std::cout << input->Da << std::endl;
break;
case GLFW_KEY_Z:
input->Da *= 0.8f;
std::cout << input->Da << std::endl;
break;
case GLFW_KEY_S:
input->Db *= 1.25f;
std::cout << input->Db << std::endl;
break;
case GLFW_KEY_X:
input->Db *= 0.8f;
std::cout << input->Db << std::endl;
break;
case GLFW_KEY_D:
input->f *= 1.25f;
std::cout << "f = " << input->f << std::endl;
break;
case GLFW_KEY_C:
input->f *= 0.8f;
std::cout << "f = " << input->f << std::endl;
break;
case GLFW_KEY_F:
input->k *= 1.25f;
std::cout << "k = " << input->k << std::endl;
break;
case GLFW_KEY_V:
input->k *= 0.8f;
std::cout << "k = " << input->k << std::endl;
break;
}
}
}
int main(int argc, char const *argv[])
{
InputData input;
input.Da = 1.f;
input.Db = 0.5f;
input.f = 0.018f;
input.k = 0.051f;
input.delta = 0.8f;
Framebuffer *framebuffer = new Framebuffer();
GLFWwindow* window = framebuffer->init(WIDTH, HEIGHT, &input);
glfwSetKeyCallback(window, keyCallback);
SimData *data = new SimData;
float *image = new float[SIZE*3];
Perlin perlin;
for(int i = 0; i < SIZE; ++i)
{
float xpos = i % WIDTH;
float ypos = i / WIDTH;
if(perlin.noise(xpos / 100, ypos / 100, 0) > 0.4f)
{
data->a_current[i] = 1.f;
data->b_current[i] = 1.f;
}
else
{
data->a_current[i] = 1.f;
data->b_current[i] = 0.f;
}
data->a_buffer[i] = 0.f;
data->b_buffer[i] = 0.f;
}
// OpenCL setup starts here
// Setup
cl_platform_id platform_id;
clGetPlatformIDs(1, &platform_id, NULL);
cl_uint device_count;
clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &device_count);
cl_device_id *device_ids = new cl_device_id[device_count];
clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, device_count, device_ids, NULL);
// Error code
cl_int error = CL_SUCCESS;
// Context creation
const cl_context_properties context_properties[] = {
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform_id),
0
};
cl_context context = clCreateContext(context_properties, device_count, device_ids, NULL, NULL, &error);
opencl_error_check(error);
// GLuint m_texture;
// glGenTextures(1, &m_texture);
// glBindTexture(GL_TEXTURE_2D, m_texture);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);
// Memory allocation
cl_mem cMem_a = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_current, &error);
opencl_error_check(error);
cl_mem cMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_current, &error);
opencl_error_check(error);
cl_mem bMem_a = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->a_buffer, &error);
opencl_error_check(error);
cl_mem bMem_b = clCreateBuffer(context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * SIZE, data->b_buffer, &error);
opencl_error_check(error);
// cl_mem mem = clCreateFromGLTexture(context, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &error);
// opencl_error_check(error);
// Load source file
std::string file = read_file("kernals/image.cl");
const char* source[] = {file.c_str()};
// Build program
cl_program program = clCreateProgramWithSource(context, 1, source, NULL, &error);
opencl_error_check(error);
error = clBuildProgram(program, device_count, device_ids, NULL, NULL, NULL);
if(error != CL_SUCCESS)
{
char buffer[1024];
clGetProgramBuildInfo(program, device_ids[0], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, NULL);
std::cout << buffer << std::endl;
exit(EXIT_FAILURE);
}
// Resolution for kernal
const float width = WIDTH;
const float height = HEIGHT;
// Create kernel one
cl_kernel kernel_one = clCreateKernel(program, "square", &error);
opencl_error_check(error);
// Set argurments for kernel one
clSetKernelArg(kernel_one, 0, sizeof(cl_mem), &cMem_a);
clSetKernelArg(kernel_one, 1, sizeof(cl_mem), &cMem_b);
clSetKernelArg(kernel_one, 2, sizeof(cl_mem), &bMem_a);
clSetKernelArg(kernel_one, 3, sizeof(cl_mem), &bMem_b);
clSetKernelArg(kernel_one, 4, sizeof(InputData), &input);
clSetKernelArg(kernel_one, 5, sizeof(float), &width);
clSetKernelArg(kernel_one, 6, sizeof(float), &height);
// Create kernel two
cl_kernel kernel_two = clCreateKernel(program, "square", &error);
opencl_error_check(error);
// Set argurments for kernel two
clSetKernelArg(kernel_two, 0, sizeof(cl_mem), &bMem_a);
clSetKernelArg(kernel_two, 1, sizeof(cl_mem), &bMem_b);
clSetKernelArg(kernel_two, 2, sizeof(cl_mem), &cMem_a);
clSetKernelArg(kernel_two, 3, sizeof(cl_mem), &cMem_b);
clSetKernelArg(kernel_two, 4, sizeof(InputData), &input);
clSetKernelArg(kernel_two, 5, sizeof(float), &width);
clSetKernelArg(kernel_two, 6, sizeof(float), &height);
// Create queue
cl_command_queue queue = clCreateCommandQueue(context, device_ids[0], 0, &error);
opencl_error_check(error);
// OpenCL setup ends here
framebuffer->bind();
unsigned int iteration = 0;
boost::chrono::milliseconds iteration_delta(static_cast<int>((1000.f / 60.f) * input.delta));
while( !framebuffer->close() )
{
boost::chrono::high_resolution_clock::time_point timer_start = boost::chrono::high_resolution_clock::now();
// Run queue
std::size_t size[] = {SIZE};
error = clEnqueueNDRangeKernel(queue, (iteration % 2) ? kernel_one : kernel_two, 1, 0, size, NULL, 0, NULL, NULL);
opencl_error_check(error);
// Get data from GPU
error = clEnqueueReadBuffer(queue, cMem_a, CL_TRUE, 0, sizeof(float) * SIZE, data->a_current, 0, NULL, NULL);
opencl_error_check(error);
for(int i = 0; i < SIZE; ++i)
{
float current = image[i * 3 + 0];
image[i * 3 + 0] = data->a_current[i];
image[i * 3 + 1] = data->a_current[i];
image[i * 3 + 2] = data->a_current[i];
}
framebuffer->image(image, WIDTH, HEIGHT);
framebuffer->draw();
std::string title = "Graphics Environment Iteration: " + std::to_string(++iteration);
framebuffer->title(title);
boost::chrono::high_resolution_clock::time_point timer_end = boost::chrono::high_resolution_clock::now();
boost::chrono::milliseconds iteration_time(boost::chrono::duration_cast<boost::chrono::milliseconds>(timer_end - timer_start).count());
if(iteration_time < iteration_delta)
{
boost::this_thread::sleep_for(iteration_delta - iteration_time);
}
}
// Cleanup
clReleaseCommandQueue(queue);
clReleaseMemObject(bMem_b);
clReleaseMemObject(bMem_a);
clReleaseMemObject(cMem_b);
clReleaseMemObject(cMem_a);
clReleaseKernel(kernel_two);
clReleaseKernel(kernel_one);
clReleaseProgram(program);
clReleaseContext(context);
delete[] device_ids;
delete data;
delete framebuffer;
delete[] image;
exit(EXIT_SUCCESS);
}<|endoftext|> |
<commit_before>#include "math/Vector.hpp"
#include "mill_pdb.hpp"
#include "mill_dcd.hpp"
#include "mill_ninfo.hpp"
#include <iostream>
template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo();
void print_help();
void print_man();
int main(int argc, char **argv)
{
print_logo<1, 0>();
if(argc < 3)
{
print_help();
return 1;
}
std::string mode(argv[1]);
if(mode == "pdb")
{
try
{
return mill::mode_pdb<mill::Vector<double, 3>>(argc-1, ++argv);
}
catch(std::exception& excpt)
{
std::cerr << "exception thrown: " << excpt.what() << std::endl;
return 1;
}
}
else if(mode == "ninfo")
{
try
{
return mill::mode_ninfo<mill::Vector<double, 3>>(argc-1, ++argv);
}
catch(std::exception& excpt)
{
std::cerr << "exception thrown: " << excpt.what() << std::endl;
return 1;
}
}
else if(mode == "dcd")
{
try
{
return mill::mode_dcd<mill::Vector<double, 3>>(argc-1, ++argv);
}
catch(std::exception& excpt)
{
std::cerr << "exception thrown: " << excpt.what() << std::endl;
return 1;
}
}
else if(mode == "help")
{
print_help();
return 1;
}
else
{
std::cerr << "unknown command: " << mode << std::endl;
print_help();
return 1;
}
}
template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo()
{
// not escaped
// std::cerr << " ____ __ __ __ __ _ _ _ " << std::endl;
// std::cerr << " / ___| ___ / _|/ _| ___ ___ | \ / |(_)| || | " << std::endl;
// std::cerr << "| | / _ \| |_| |_ / _ \/ _ \ | \/ || || || | " << std::endl;
// std::cerr << "| |___| (_) | _| _| __| __/ | |\/| || || || | " << std::endl;
// std::cerr << " \____|\___/|_| |_| \___|\___| |_| |_||_||_||_| " << std::endl;
std::cerr << " ___ __ __ __ __ _ _ _ " << std::endl;
std::cerr << " / __| ___ / _|/ _| ___ ___ | \\ / |(_)| || | " << std::endl;
std::cerr << "| | / _ \\| |_| |_ / _ \\/ _ \\ | \\/ || || || | " << std::endl;
std::cerr << "| |__| (_) | _| _| __| __/ | |\\/| || || || | " << std::endl;
std::cerr << " \\___|\\___/|_| |_| \\___|\\___| |_| |_||_||_||_| " << std::endl;
std::cerr << " version "
<< MAJOR_V << "." << MINOR_V << std::endl;
std::cerr << " Copyright 2016 Toru Niina " << std::endl;
std::cerr << std::endl;
std::cerr << std::endl;
return;
}
void print_help()
{
std::cerr << "Usage: mill [mode] [job]" << std::endl;
std::cerr << std::endl;
std::cerr << "command-line interface" << std::endl;
std::cerr << std::endl;
std::cerr << "list of modes" << std::endl;
std::cerr << "\t" << "pdb" << std::endl;
std::cerr << "\t" << "dcd" << std::endl;
std::cerr << "\t" << "ninfo" << std::endl;
std::cerr << std::endl;
std::cerr << "jobs" << std::endl;
std::cerr << "\t" << "seq" << std::endl;
std::cerr << "\t" << "join" << std::endl;
std::cerr << "\t" << "split" << std::endl;
std::cerr << "\t" << "make-movie" << std::endl;
// std::cerr << "\t" << JOB_SHOW << std::endl;
// std::cerr << "\t" << JOB_MUTATE << std::endl;
// std::cerr << "\t" << JOB_MAKE_CG << std::endl;
// std::cerr << "\t" << JOB_MAKE_NINFO << std::endl;
std::cerr << std::endl;
std::cerr << "some combination of mode and job is not defined." << std::endl;
std::cerr << "to see more information, run `mill --man`." << std::endl;
return;
}
void print_man()
{
std::cerr << "\t\t\t\t Coffee Mill" << std::endl;
std::cerr << "NAME" << std::endl;
std::cerr << "\tcoffee mill - command line tools for using cafemol" << std::endl;
std::cerr << std::endl;
std::cerr << "SYNOPSIS" << std::endl;
std::cerr << "\tmill [-h] {pdb | dcd | ninfo | dna}" << std::endl;
std::cerr << std::endl;
std::cerr << "DESCRIPTION" << std::endl;
std::cerr << "\tcoffee mill is the command line tool for handling cafemol files."
<< std::endl;
std::cerr << std::endl;
std::cerr << "\tpdb" << std::endl;
std::cerr << "\t\thandle pdb files. extract sequence, split for cafemol input, "
<< std::endl;
std::cerr << "\t\tmake cg file, make ninfo file, etc..." << std::endl;
std::cerr << std::endl;
std::cerr << "\tdna" << std::endl;
std::cerr << "\t\thandle dna sequence, mutate pdb file, etc..." << std::endl;
std::cerr << std::endl;
std::cerr << "\tdcd" << std::endl;
std::cerr << "\t\thandle dcd files. make movie file, calculate some values, "
<< std::endl;
std::cerr << "\t\tjoin some dcd files, etc..." << std::endl;
std::cerr << std::endl;
std::cerr << "\tninfo" << std::endl;
std::cerr << "\t\thandle ninfo files. split ninfo files, show structure as XYZ file,"
<< std::endl;
std::cerr << "\t\tetc..." << std::endl;
return;
}
<commit_msg>change include path<commit_after>#include <mill/math/Vector.hpp>
#include "mill_pdb.hpp"
#include "mill_dcd.hpp"
#include "mill_ninfo.hpp"
#include <iostream>
template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo();
void print_help();
void print_man();
int main(int argc, char **argv)
{
print_logo<1, 0>();
if(argc < 3)
{
print_help();
return 1;
}
std::string mode(argv[1]);
if(mode == "pdb")
{
try
{
return mill::mode_pdb<mill::Vector<double, 3>>(argc-1, ++argv);
}
catch(std::exception& excpt)
{
std::cerr << "exception thrown: " << excpt.what() << std::endl;
return 1;
}
}
else if(mode == "ninfo")
{
try
{
return mill::mode_ninfo<mill::Vector<double, 3>>(argc-1, ++argv);
}
catch(std::exception& excpt)
{
std::cerr << "exception thrown: " << excpt.what() << std::endl;
return 1;
}
}
else if(mode == "dcd")
{
try
{
return mill::mode_dcd<mill::Vector<double, 3>>(argc-1, ++argv);
}
catch(std::exception& excpt)
{
std::cerr << "exception thrown: " << excpt.what() << std::endl;
return 1;
}
}
else if(mode == "help")
{
print_help();
return 1;
}
else
{
std::cerr << "unknown command: " << mode << std::endl;
print_help();
return 1;
}
}
template<std::size_t MAJOR_V, std::size_t MINOR_V>
void print_logo()
{
// not escaped
// std::cerr << " ____ __ __ __ __ _ _ _ " << std::endl;
// std::cerr << " / ___| ___ / _|/ _| ___ ___ | \ / |(_)| || | " << std::endl;
// std::cerr << "| | / _ \| |_| |_ / _ \/ _ \ | \/ || || || | " << std::endl;
// std::cerr << "| |___| (_) | _| _| __| __/ | |\/| || || || | " << std::endl;
// std::cerr << " \____|\___/|_| |_| \___|\___| |_| |_||_||_||_| " << std::endl;
std::cerr << " ___ __ __ __ __ _ _ _ " << std::endl;
std::cerr << " / __| ___ / _|/ _| ___ ___ | \\ / |(_)| || | " << std::endl;
std::cerr << "| | / _ \\| |_| |_ / _ \\/ _ \\ | \\/ || || || | " << std::endl;
std::cerr << "| |__| (_) | _| _| __| __/ | |\\/| || || || | " << std::endl;
std::cerr << " \\___|\\___/|_| |_| \\___|\\___| |_| |_||_||_||_| " << std::endl;
std::cerr << " version "
<< MAJOR_V << "." << MINOR_V << std::endl;
std::cerr << " Copyright 2016 Toru Niina " << std::endl;
std::cerr << std::endl;
std::cerr << std::endl;
return;
}
void print_help()
{
std::cerr << "Usage: mill [mode] [job]" << std::endl;
std::cerr << std::endl;
std::cerr << "command-line interface" << std::endl;
std::cerr << std::endl;
std::cerr << "list of modes" << std::endl;
std::cerr << "\t" << "pdb" << std::endl;
std::cerr << "\t" << "dcd" << std::endl;
std::cerr << "\t" << "ninfo" << std::endl;
std::cerr << std::endl;
std::cerr << "jobs" << std::endl;
std::cerr << "\t" << "seq" << std::endl;
std::cerr << "\t" << "join" << std::endl;
std::cerr << "\t" << "split" << std::endl;
std::cerr << "\t" << "make-movie" << std::endl;
// std::cerr << "\t" << JOB_SHOW << std::endl;
// std::cerr << "\t" << JOB_MUTATE << std::endl;
// std::cerr << "\t" << JOB_MAKE_CG << std::endl;
// std::cerr << "\t" << JOB_MAKE_NINFO << std::endl;
std::cerr << std::endl;
std::cerr << "some combination of mode and job is not defined." << std::endl;
std::cerr << "to see more information, run `mill --man`." << std::endl;
return;
}
void print_man()
{
std::cerr << "\t\t\t\t Coffee Mill" << std::endl;
std::cerr << "NAME" << std::endl;
std::cerr << "\tcoffee mill - command line tools for using cafemol" << std::endl;
std::cerr << std::endl;
std::cerr << "SYNOPSIS" << std::endl;
std::cerr << "\tmill [-h] {pdb | dcd | ninfo | dna}" << std::endl;
std::cerr << std::endl;
std::cerr << "DESCRIPTION" << std::endl;
std::cerr << "\tcoffee mill is the command line tool for handling cafemol files."
<< std::endl;
std::cerr << std::endl;
std::cerr << "\tpdb" << std::endl;
std::cerr << "\t\thandle pdb files. extract sequence, split for cafemol input, "
<< std::endl;
std::cerr << "\t\tmake cg file, make ninfo file, etc..." << std::endl;
std::cerr << std::endl;
std::cerr << "\tdna" << std::endl;
std::cerr << "\t\thandle dna sequence, mutate pdb file, etc..." << std::endl;
std::cerr << std::endl;
std::cerr << "\tdcd" << std::endl;
std::cerr << "\t\thandle dcd files. make movie file, calculate some values, "
<< std::endl;
std::cerr << "\t\tjoin some dcd files, etc..." << std::endl;
std::cerr << std::endl;
std::cerr << "\tninfo" << std::endl;
std::cerr << "\t\thandle ninfo files. split ninfo files, show structure as XYZ file,"
<< std::endl;
std::cerr << "\t\tetc..." << std::endl;
return;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"
#include <unotools/localisationoptions.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/configitem.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <rtl/logfile.hxx>
#include "itemholder1.hxx"
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using namespace ::utl ;
using namespace ::rtl ;
using namespace ::osl ;
using namespace ::com::sun::star::uno ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define ROOTNODE_LOCALISATION OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/View/Localisation"))
#define DEFAULT_AUTOMNEMONIC sal_False
#define DEFAULT_DIALOGSCALE 0
#define PROPERTYNAME_AUTOMNEMONIC OUString(RTL_CONSTASCII_USTRINGPARAM("AutoMnemonic" ))
#define PROPERTYNAME_DIALOGSCALE OUString(RTL_CONSTASCII_USTRINGPARAM("DialogScale" ))
#define PROPERTYHANDLE_AUTOMNEMONIC 0
#define PROPERTYHANDLE_DIALOGSCALE 1
#define PROPERTYCOUNT 2
//_________________________________________________________________________________________________________________
// private declarations!
//_________________________________________________________________________________________________________________
class SvtLocalisationOptions_Impl : public ConfigItem
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtLocalisationOptions_Impl();
~SvtLocalisationOptions_Impl();
//---------------------------------------------------------------------------------------------------------
// overloaded methods of baseclass
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short called for notify of configmanager
@descr These method is called from the ConfigManager before application ends or from the
PropertyChangeListener if the sub tree broadcasts changes. You must update your
internal values.
@seealso baseclass ConfigItem
@param "seqPropertyNames" is the list of properties which should be updated.
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Notify( const Sequence< OUString >& seqPropertyNames );
/*-****************************************************************************************************//**
@short write changes to configuration
@descr These method writes the changed values into the sub tree
and should always called in our destructor to guarantee consistency of config data.
@seealso baseclass ConfigItem
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Commit();
//---------------------------------------------------------------------------------------------------------
// public interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short access method to get internal values
@descr These method give us a chance to regulate acces to ouer internal values.
It's not used in the moment - but it's possible for the feature!
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
sal_Bool IsAutoMnemonic ( ) const ;
void SetAutoMnemonic ( sal_Bool bState ) ;
sal_Int32 GetDialogScale ( ) const ;
void SetDialogScale ( sal_Int32 nScale ) ;
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return list of key names of ouer configuration management which represent oue module tree
@descr These methods return a static const list of key names. We need it to get needed values from our
configuration management.
@seealso -
@param -
@return A list of needed configuration keys is returned.
@onerror -
*//*-*****************************************************************************************************/
static Sequence< OUString > GetPropertyNames();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
sal_Bool m_bAutoMnemonic ;
sal_Int32 m_nDialogScale ;
};
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()
// Init baseclasses first
: ConfigItem ( ROOTNODE_LOCALISATION )
// Init member then.
, m_bAutoMnemonic ( DEFAULT_AUTOMNEMONIC )
, m_nDialogScale ( DEFAULT_DIALOGSCALE )
{
// Use our static list of configuration keys to get his values.
Sequence< OUString > seqNames = GetPropertyNames ( );
Sequence< Any > seqValues = GetProperties ( seqNames );
// Safe impossible cases.
// We need values from ALL configuration keys.
// Follow assignment use order of values in relation to our list of key names!
DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nI miss some values of configuration keys!\n" );
// Copy values from list in right order to ouer internal member.
sal_Int32 nPropertyCount = seqValues.getLength();
for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
// Safe impossible cases.
// Check any for valid value.
DBG_ASSERT( !(seqValues[nProperty].hasValue()==sal_False), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nInvalid property value detected!\n" );
switch( nProperty )
{
case PROPERTYHANDLE_AUTOMNEMONIC : {
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
seqValues[nProperty] >>= m_bAutoMnemonic;
}
break;
case PROPERTYHANDLE_DIALOGSCALE : {
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
seqValues[nProperty] >>= m_nDialogScale;
}
break;
}
}
// Enable notification mechanism of ouer baseclass.
// We need it to get information about changes outside these class on ouer used configuration keys!
EnableNotification( seqNames );
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::~SvtLocalisationOptions_Impl()
{
// We must save our current values .. if user forget it!
if( IsModified() == sal_True )
{
Commit();
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames )
{
// Use given list of updated properties to get his values from configuration directly!
Sequence< Any > seqValues = GetProperties( seqPropertyNames );
// Safe impossible cases.
// We need values from ALL notified configuration keys.
DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::Notify()\nI miss some values of configuration keys!\n" );
// Step over list of property names and get right value from coreesponding value list to set it on internal members!
sal_Int32 nCount = seqPropertyNames.getLength();
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
if( seqPropertyNames[nProperty] == PROPERTYNAME_AUTOMNEMONIC )
{
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
seqValues[nProperty] >>= m_bAutoMnemonic;
}
else
if( seqPropertyNames[nProperty] == PROPERTYNAME_DIALOGSCALE )
{
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
seqValues[nProperty] >>= m_nDialogScale;
}
#if OSL_DEBUG_LEVEL > 1
else DBG_ASSERT( sal_False, "SvtLocalisationOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" );
#endif
}
NotifyListeners(0);
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Commit()
{
// Get names of supported properties, create a list for values and copy current values to it.
Sequence< OUString > seqNames = GetPropertyNames ();
sal_Int32 nCount = seqNames.getLength();
Sequence< Any > seqValues ( nCount );
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
switch( nProperty )
{
case PROPERTYHANDLE_AUTOMNEMONIC : {
seqValues[nProperty] <<= m_bAutoMnemonic;
}
break;
case PROPERTYHANDLE_DIALOGSCALE : {
seqValues[nProperty] <<= m_nDialogScale;
}
break;
}
}
// Set properties in configuration.
PutProperties( seqNames, seqValues );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions_Impl::IsAutoMnemonic() const
{
return m_bAutoMnemonic;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetAutoMnemonic( sal_Bool bState )
{
m_bAutoMnemonic = bState;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions_Impl::GetDialogScale() const
{
return m_nDialogScale;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetDialogScale( sal_Int32 nScale )
{
m_nDialogScale = nScale;
SetModified();
}
Sequence< OUString > SvtLocalisationOptions_Impl::GetPropertyNames()
{
// Build static list of configuration key names.
const OUString aProperties[] =
{
PROPERTYNAME_AUTOMNEMONIC ,
PROPERTYNAME_DIALOGSCALE ,
};
// Initialize return sequence with these list ...
Sequence< OUString > seqPropertyNames(aProperties, PROPERTYCOUNT);
// ... and return it.
return seqPropertyNames;
}
//*****************************************************************************************************************
// initialize static member
// DON'T DO IT IN YOUR HEADER!
// see definition for further informations
//*****************************************************************************************************************
SvtLocalisationOptions_Impl* SvtLocalisationOptions::m_pDataContainer = NULL ;
sal_Int32 SvtLocalisationOptions::m_nRefCount = 0 ;
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtLocalisationOptions::SvtLocalisationOptions()
{
// Global access, must be guarded (multithreading!).
MutexGuard aGuard( GetOwnStaticMutex() );
// Increase ouer refcount ...
++m_nRefCount;
// ... and initialize ouer data container only if it not already exist!
if( m_pDataContainer == NULL )
{
RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtLocalisationOptions_Impl::ctor()");
m_pDataContainer = new SvtLocalisationOptions_Impl;
ItemHolder1::holdConfigItem(E_LOCALISATIONOPTIONS);
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtLocalisationOptions::~SvtLocalisationOptions()
{
// Global access, must be guarded (multithreading!)
MutexGuard aGuard( GetOwnStaticMutex() );
// Decrease ouer refcount.
--m_nRefCount;
// If last instance was deleted ...
// we must destroy ouer static data container!
if( m_nRefCount <= 0 )
{
delete m_pDataContainer;
m_pDataContainer = NULL;
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions::IsAutoMnemonic() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->IsAutoMnemonic();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetAutoMnemonic( sal_Bool bState )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetAutoMnemonic( bState );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions::GetDialogScale() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetDialogScale();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetDialogScale( sal_Int32 nScale )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetDialogScale( nScale );
}
namespace
{
class theLocalisationOptionsMutex : public rtl::Static<osl::Mutex, theLocalisationOptionsMutex>{};
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Mutex& SvtLocalisationOptions::GetOwnStaticMutex()
{
return theLocalisationOptionsMutex::get();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>handle missing values gracefully<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_unotools.hxx"
#include <unotools/localisationoptions.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/configitem.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <rtl/logfile.hxx>
#include "itemholder1.hxx"
//_________________________________________________________________________________________________________________
// namespaces
//_________________________________________________________________________________________________________________
using namespace ::utl ;
using namespace ::rtl ;
using namespace ::osl ;
using namespace ::com::sun::star::uno ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
#define ROOTNODE_LOCALISATION OUString(RTL_CONSTASCII_USTRINGPARAM("Office.Common/View/Localisation"))
#define DEFAULT_AUTOMNEMONIC sal_False
#define DEFAULT_DIALOGSCALE 0
#define PROPERTYNAME_AUTOMNEMONIC OUString(RTL_CONSTASCII_USTRINGPARAM("AutoMnemonic" ))
#define PROPERTYNAME_DIALOGSCALE OUString(RTL_CONSTASCII_USTRINGPARAM("DialogScale" ))
#define PROPERTYHANDLE_AUTOMNEMONIC 0
#define PROPERTYHANDLE_DIALOGSCALE 1
#define PROPERTYCOUNT 2
//_________________________________________________________________________________________________________________
// private declarations!
//_________________________________________________________________________________________________________________
class SvtLocalisationOptions_Impl : public ConfigItem
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
SvtLocalisationOptions_Impl();
~SvtLocalisationOptions_Impl();
//---------------------------------------------------------------------------------------------------------
// overloaded methods of baseclass
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short called for notify of configmanager
@descr These method is called from the ConfigManager before application ends or from the
PropertyChangeListener if the sub tree broadcasts changes. You must update your
internal values.
@seealso baseclass ConfigItem
@param "seqPropertyNames" is the list of properties which should be updated.
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Notify( const Sequence< OUString >& seqPropertyNames );
/*-****************************************************************************************************//**
@short write changes to configuration
@descr These method writes the changed values into the sub tree
and should always called in our destructor to guarantee consistency of config data.
@seealso baseclass ConfigItem
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
virtual void Commit();
//---------------------------------------------------------------------------------------------------------
// public interface
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short access method to get internal values
@descr These method give us a chance to regulate acces to ouer internal values.
It's not used in the moment - but it's possible for the feature!
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
sal_Bool IsAutoMnemonic ( ) const ;
void SetAutoMnemonic ( sal_Bool bState ) ;
sal_Int32 GetDialogScale ( ) const ;
void SetDialogScale ( sal_Int32 nScale ) ;
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return list of key names of ouer configuration management which represent oue module tree
@descr These methods return a static const list of key names. We need it to get needed values from our
configuration management.
@seealso -
@param -
@return A list of needed configuration keys is returned.
@onerror -
*//*-*****************************************************************************************************/
static Sequence< OUString > GetPropertyNames();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
sal_Bool m_bAutoMnemonic ;
sal_Int32 m_nDialogScale ;
};
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()
// Init baseclasses first
: ConfigItem ( ROOTNODE_LOCALISATION )
// Init member then.
, m_bAutoMnemonic ( DEFAULT_AUTOMNEMONIC )
, m_nDialogScale ( DEFAULT_DIALOGSCALE )
{
// Use our static list of configuration keys to get his values.
Sequence< OUString > seqNames = GetPropertyNames ( );
Sequence< Any > seqValues = GetProperties ( seqNames );
// Safe impossible cases.
// We need values from ALL configuration keys.
// Follow assignment use order of values in relation to our list of key names!
DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nI miss some values of configuration keys!\n" );
// Copy values from list in right order to our internal member.
sal_Int32 nPropertyCount = seqValues.getLength();
for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty )
{
if (!seqValues[nProperty].hasValue())
continue;
switch( nProperty )
{
case PROPERTYHANDLE_AUTOMNEMONIC : {
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
seqValues[nProperty] >>= m_bAutoMnemonic;
}
break;
case PROPERTYHANDLE_DIALOGSCALE : {
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
seqValues[nProperty] >>= m_nDialogScale;
}
break;
}
}
// Enable notification mechanism of ouer baseclass.
// We need it to get information about changes outside these class on ouer used configuration keys!
EnableNotification( seqNames );
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtLocalisationOptions_Impl::~SvtLocalisationOptions_Impl()
{
// We must save our current values .. if user forget it!
if( IsModified() == sal_True )
{
Commit();
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Notify( const Sequence< OUString >& seqPropertyNames )
{
// Use given list of updated properties to get his values from configuration directly!
Sequence< Any > seqValues = GetProperties( seqPropertyNames );
// Safe impossible cases.
// We need values from ALL notified configuration keys.
DBG_ASSERT( !(seqPropertyNames.getLength()!=seqValues.getLength()), "SvtLocalisationOptions_Impl::Notify()\nI miss some values of configuration keys!\n" );
// Step over list of property names and get right value from coreesponding value list to set it on internal members!
sal_Int32 nCount = seqPropertyNames.getLength();
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
if( seqPropertyNames[nProperty] == PROPERTYNAME_AUTOMNEMONIC )
{
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_BOOLEAN), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\AutoMnemonic\"?" );
seqValues[nProperty] >>= m_bAutoMnemonic;
}
else
if( seqPropertyNames[nProperty] == PROPERTYNAME_DIALOGSCALE )
{
DBG_ASSERT(!(seqValues[nProperty].getValueTypeClass()!=TypeClass_LONG), "SvtLocalisationOptions_Impl::SvtLocalisationOptions_Impl()\nWho has changed the value type of \"Office.Common\\View\\Localisation\\DialogScale\"?" );
seqValues[nProperty] >>= m_nDialogScale;
}
#if OSL_DEBUG_LEVEL > 1
else DBG_ASSERT( sal_False, "SvtLocalisationOptions_Impl::Notify()\nUnkown property detected ... I can't handle these!\n" );
#endif
}
NotifyListeners(0);
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::Commit()
{
// Get names of supported properties, create a list for values and copy current values to it.
Sequence< OUString > seqNames = GetPropertyNames ();
sal_Int32 nCount = seqNames.getLength();
Sequence< Any > seqValues ( nCount );
for( sal_Int32 nProperty=0; nProperty<nCount; ++nProperty )
{
switch( nProperty )
{
case PROPERTYHANDLE_AUTOMNEMONIC : {
seqValues[nProperty] <<= m_bAutoMnemonic;
}
break;
case PROPERTYHANDLE_DIALOGSCALE : {
seqValues[nProperty] <<= m_nDialogScale;
}
break;
}
}
// Set properties in configuration.
PutProperties( seqNames, seqValues );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions_Impl::IsAutoMnemonic() const
{
return m_bAutoMnemonic;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetAutoMnemonic( sal_Bool bState )
{
m_bAutoMnemonic = bState;
SetModified();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions_Impl::GetDialogScale() const
{
return m_nDialogScale;
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions_Impl::SetDialogScale( sal_Int32 nScale )
{
m_nDialogScale = nScale;
SetModified();
}
Sequence< OUString > SvtLocalisationOptions_Impl::GetPropertyNames()
{
// Build static list of configuration key names.
const OUString aProperties[] =
{
PROPERTYNAME_AUTOMNEMONIC ,
PROPERTYNAME_DIALOGSCALE ,
};
// Initialize return sequence with these list ...
Sequence< OUString > seqPropertyNames(aProperties, PROPERTYCOUNT);
// ... and return it.
return seqPropertyNames;
}
//*****************************************************************************************************************
// initialize static member
// DON'T DO IT IN YOUR HEADER!
// see definition for further informations
//*****************************************************************************************************************
SvtLocalisationOptions_Impl* SvtLocalisationOptions::m_pDataContainer = NULL ;
sal_Int32 SvtLocalisationOptions::m_nRefCount = 0 ;
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
SvtLocalisationOptions::SvtLocalisationOptions()
{
// Global access, must be guarded (multithreading!).
MutexGuard aGuard( GetOwnStaticMutex() );
// Increase ouer refcount ...
++m_nRefCount;
// ... and initialize ouer data container only if it not already exist!
if( m_pDataContainer == NULL )
{
RTL_LOGFILE_CONTEXT(aLog, "unotools ( ??? ) ::SvtLocalisationOptions_Impl::ctor()");
m_pDataContainer = new SvtLocalisationOptions_Impl;
ItemHolder1::holdConfigItem(E_LOCALISATIONOPTIONS);
}
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
SvtLocalisationOptions::~SvtLocalisationOptions()
{
// Global access, must be guarded (multithreading!)
MutexGuard aGuard( GetOwnStaticMutex() );
// Decrease ouer refcount.
--m_nRefCount;
// If last instance was deleted ...
// we must destroy ouer static data container!
if( m_nRefCount <= 0 )
{
delete m_pDataContainer;
m_pDataContainer = NULL;
}
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Bool SvtLocalisationOptions::IsAutoMnemonic() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->IsAutoMnemonic();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetAutoMnemonic( sal_Bool bState )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetAutoMnemonic( bState );
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
sal_Int32 SvtLocalisationOptions::GetDialogScale() const
{
MutexGuard aGuard( GetOwnStaticMutex() );
return m_pDataContainer->GetDialogScale();
}
//*****************************************************************************************************************
// public method
//*****************************************************************************************************************
void SvtLocalisationOptions::SetDialogScale( sal_Int32 nScale )
{
MutexGuard aGuard( GetOwnStaticMutex() );
m_pDataContainer->SetDialogScale( nScale );
}
namespace
{
class theLocalisationOptionsMutex : public rtl::Static<osl::Mutex, theLocalisationOptionsMutex>{};
}
//*****************************************************************************************************************
// private method
//*****************************************************************************************************************
Mutex& SvtLocalisationOptions::GetOwnStaticMutex()
{
return theLocalisationOptionsMutex::get();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <iostream>
#include "common.h"
#include "Overlap.h"
#include "params.h"
#include "ReadTrim.h"
#include "Graph.h"
#include "OverlapUtils.h"
#include "IO.h"
#include "GraphUtils.h"
#include "Unitig.h"
#include "UnitigUtils.h"
int main() {
Overlaps overlaps;
Params params( getDefaultParams());
std::cout << "1) Reading overlaps and reads" << std::endl;
loadPAF( overlaps, "../test-data/lambda_overlaps.paf", params );
std::cout << "2) Proposing read trims" << std::endl;
ReadTrims readTrims;
proposeReadTrims( readTrims, overlaps, params, false );
std::cout << "3) Trimming reads" << std::endl;
trimReads( overlaps, readTrims, params );
std::cout << "3) Filtering reads" << std::endl;
filterReads( overlaps, readTrims, params );
std::cout << "4) Proposing read trims" << std::endl;
ReadTrims readTrims2;
proposeReadTrims( readTrims2, overlaps, params, true );
std::cout << "5) Trimming reads" << std::endl;
trimReads( overlaps, readTrims2, params );
mergeTrims( readTrims, readTrims2 );
std::cout << "6) Chimering reads" << std::endl;
filterChimeric( overlaps, readTrims, params );
std::cout << "7) Filtering contained reads" << std::endl;
filterContained( overlaps, readTrims, params );
// logTrimmedOverlaps( overlaps, readTrims );
std::cout << "8) Generating graph" << std::endl;
Graph g;
generateGraph( g, overlaps, readTrims, params );
// logGraph(g);
std::cout << "9) Filtering transitive edges" << std::endl;
filterTransitiveEdges( g, 1000 );
// logGraph(g);
std::cout << "10) Removing asymetric edges" << std::endl;
removeAsymetricEdges( g );
std::cout << "11) Cutting tips" << std::endl;
cutTips( g, readTrims, params );
writeGraphToSIF( "../test-data/notips.sif", g );
std::cout << "12) Popping bubbles" << std::endl;
popBubbles( g, readTrims );
writeGraphToSIF( "../test-data/nobubles.sif", g );
// logGraph(g);
Unitigs unitigs;
std::cout << "13) Generating unitigs" << std::endl;
generateUnitigs( unitigs, g, readTrims );
assignSequencesToUnitigs( unitigs, readTrims, "../test-data/lambda_reads.fasta" );
logUnitigs( unitigs, readTrims );
// logGraph(g);
// std::cout << "Left with " << overlaps.size() << " trimmed overlaps" << std::endl;
//
// for (auto const &readTrim: readTrims) {
// std::cout << readTrim.first << " " << readTrim.second.toString() << std::endl;
// }
// writeOverlapsToSIF("mnebijemte.sif", overlaps);
return 0;
}
<commit_msg>easier dataset change<commit_after>#include <iostream>
#include "common.h"
#include "Overlap.h"
#include "params.h"
#include "ReadTrim.h"
#include "Graph.h"
#include "OverlapUtils.h"
#include "IO.h"
#include "GraphUtils.h"
#include "Unitig.h"
#include "UnitigUtils.h"
#define DATASET "ecoli"
int main() {
Overlaps overlaps;
Params params( getDefaultParams());
std::cout << "1) Reading overlaps and reads" << std::endl;
loadPAF( overlaps, "../test-data/" DATASET "_overlaps.paf", params );
std::cout << "2) Proposing read trims" << std::endl;
ReadTrims readTrims;
proposeReadTrims( readTrims, overlaps, params, false );
std::cout << "3) Trimming reads" << std::endl;
trimReads( overlaps, readTrims, params );
std::cout << "3) Filtering reads" << std::endl;
filterReads( overlaps, readTrims, params );
std::cout << "4) Proposing read trims" << std::endl;
ReadTrims readTrims2;
proposeReadTrims( readTrims2, overlaps, params, true );
std::cout << "5) Trimming reads" << std::endl;
trimReads( overlaps, readTrims2, params );
mergeTrims( readTrims, readTrims2 );
std::cout << "6) Chimering reads" << std::endl;
filterChimeric( overlaps, readTrims, params );
std::cout << "7) Filtering contained reads" << std::endl;
filterContained( overlaps, readTrims, params );
// logTrimmedOverlaps( overlaps, readTrims );
std::cout << "8) Generating graph" << std::endl;
Graph g;
generateGraph( g, overlaps, readTrims, params );
// logGraph(g);
std::cout << "9) Filtering transitive edges" << std::endl;
filterTransitiveEdges( g, 1000 );
// logGraph(g);
std::cout << "10) Removing asymetric edges" << std::endl;
removeAsymetricEdges( g );
std::cout << "11) Cutting tips" << std::endl;
cutTips( g, readTrims, params );
writeGraphToSIF( "../test-data/" DATASET "_notips.sif", g );
std::cout << "12) Popping bubbles" << std::endl;
popBubbles( g, readTrims );
writeGraphToSIF( "../test-data/" DATASET "_nobubles.sif", g );
// logGraph(g);
Unitigs unitigs;
std::cout << "13) Generating unitigs" << std::endl;
generateUnitigs( unitigs, g, readTrims );
assignSequencesToUnitigs( unitigs, readTrims, "../test-data/" DATASET "_reads.fasta" );
logUnitigs( unitigs, readTrims );
// logGraph(g);
// std::cout << "Left with " << overlaps.size() << " trimmed overlaps" << std::endl;
//
// for (auto const &readTrim: readTrims) {
// std::cout << readTrim.first << " " << readTrim.second.toString() << std::endl;
// }
// writeOverlapsToSIF("mnebijemte.sif", overlaps);
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iterator>
#include <sstream>
#include <cassert>
int main(int argc, char* argv[])
{
std::stringstream str;
str << "Cat";
std::istream_iterator<char> eos;
std::istream_iterator<char> i(str);
char a, b;
a = *i++;
b = *i++;
std::cout << a << b << std::endl;
return 0;
}
// vim: set ts=4 sw=4 :
<commit_msg>Removed some old testing code<commit_after>#include <iostream>
#include <cassert>
int main(int argc, char* argv[])
{
return 0;
}
// vim: set ts=4 sw=4 :
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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 "build/build_config.h"
#include "chrome/browser/back_forward_menu_model.h"
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "net/base/registry_controlled_domain.h"
const int BackForwardMenuModel::kMaxHistoryItems = 12;
const int BackForwardMenuModel::kMaxChapterStops = 5;
int BackForwardMenuModel::GetHistoryItemCount() const {
TabContents* contents = GetTabContents();
int items = 0;
if (model_type_ == FORWARD_MENU_DELEGATE) {
// Only count items from n+1 to end (if n is current entry)
items = contents->controller().entry_count() -
contents->controller().GetCurrentEntryIndex() - 1;
} else {
items = contents->controller().GetCurrentEntryIndex();
}
if (items > kMaxHistoryItems)
items = kMaxHistoryItems;
else if (items < 0)
items = 0;
return items;
}
int BackForwardMenuModel::GetChapterStopCount(int history_items) const {
TabContents* contents = GetTabContents();
int chapter_stops = 0;
int current_entry = contents->controller().GetCurrentEntryIndex();
if (history_items == kMaxHistoryItems) {
int chapter_id = current_entry;
if (model_type_ == FORWARD_MENU_DELEGATE) {
chapter_id += history_items;
} else {
chapter_id -= history_items;
}
do {
chapter_id = GetIndexOfNextChapterStop(chapter_id,
model_type_ == FORWARD_MENU_DELEGATE);
if (chapter_id != -1)
++chapter_stops;
} while (chapter_id != -1 && chapter_stops < kMaxChapterStops);
}
return chapter_stops;
}
int BackForwardMenuModel::GetTotalItemCount() const {
int items = GetHistoryItemCount();
if (items > 0) {
int chapter_stops = 0;
// Next, we count ChapterStops, if any.
if (items == kMaxHistoryItems)
chapter_stops = GetChapterStopCount(items);
if (chapter_stops)
items += chapter_stops + 1; // Chapter stops also need a separator.
// If the menu is not empty, add two positions in the end
// for a separator and a "Show Full History" item.
items += 2;
}
return items;
}
int BackForwardMenuModel::GetIndexOfNextChapterStop(int start_from,
bool forward) const {
TabContents* contents = GetTabContents();
NavigationController& controller = contents->controller();
int max_count = controller.entry_count();
if (start_from < 0 || start_from >= max_count)
return -1; // Out of bounds.
if (forward) {
if (start_from < max_count - 1) {
// We want to advance over the current chapter stop, so we add one.
// We don't need to do this when direction is backwards.
start_from++;
} else {
return -1;
}
}
NavigationEntry* start_entry = controller.GetEntryAtIndex(start_from);
const GURL& url = start_entry->url();
if (!forward) {
// When going backwards we return the first entry we find that has a
// different domain.
for (int i = start_from - 1; i >= 0; --i) {
if (!net::RegistryControlledDomainService::SameDomainOrHost(url,
controller.GetEntryAtIndex(i)->url()))
return i;
}
// We have reached the beginning without finding a chapter stop.
return -1;
} else {
// When going forwards we return the entry before the entry that has a
// different domain.
for (int i = start_from + 1; i < max_count; ++i) {
if (!net::RegistryControlledDomainService::SameDomainOrHost(url,
controller.GetEntryAtIndex(i)->url()))
return i - 1;
}
// Last entry is always considered a chapter stop.
return max_count - 1;
}
}
int BackForwardMenuModel::FindChapterStop(int offset,
bool forward,
int skip) const {
if (offset < 0 || skip < 0)
return -1;
if (!forward)
offset *= -1;
TabContents* contents = GetTabContents();
int entry = contents->controller().GetCurrentEntryIndex() + offset;
for (int i = 0; i < skip + 1; i++)
entry = GetIndexOfNextChapterStop(entry, forward);
return entry;
}
void BackForwardMenuModel::ExecuteCommandById(int menu_id) {
TabContents* contents = GetTabContents();
NavigationController& controller = contents->controller();
DCHECK(!IsSeparator(menu_id));
// Execute the command for the last item: "Show Full History".
if (menu_id == GetTotalItemCount()) {
UserMetrics::RecordComputedAction(BuildActionName(L"ShowFullHistory", -1),
controller.profile());
#if defined(OS_WIN)
browser_->ShowSingleDOMUITab(GURL(chrome::kChromeUIHistoryURL));
#else
NOTIMPLEMENTED();
#endif
return;
}
// Log whether it was a history or chapter click.
if (menu_id <= GetHistoryItemCount()) {
UserMetrics::RecordComputedAction(
BuildActionName(L"HistoryClick", menu_id), controller.profile());
} else {
UserMetrics::RecordComputedAction(
BuildActionName(L"ChapterClick", menu_id - GetHistoryItemCount() - 1),
controller.profile());
}
int index = MenuIdToNavEntryIndex(menu_id);
if (index >= 0 && index < controller.entry_count())
controller.GoToIndex(index);
}
bool BackForwardMenuModel::IsSeparator(int menu_id) const {
int history_items = GetHistoryItemCount();
// If the menu_id is higher than the number of history items + separator,
// we then consider if it is a chapter-stop entry.
if (menu_id > history_items + 1) {
// We either are in ChapterStop area, or at the end of the list (the "Show
// Full History" link).
int chapter_stops = GetChapterStopCount(history_items);
if (chapter_stops == 0)
return false; // We must have reached the "Show Full History" link.
// Otherwise, look to see if we have reached the separator for the
// chapter-stops. If not, this is a chapter stop.
return (menu_id == history_items + 1 +
chapter_stops + 1);
}
// Look to see if we have reached the separator for the history items.
return menu_id == history_items + 1;
}
std::wstring BackForwardMenuModel::GetItemLabel(int menu_id) const {
// Return label "Show Full History" for the last item of the menu.
if (menu_id == GetTotalItemCount())
return l10n_util::GetString(IDS_SHOWFULLHISTORY_LINK);
// Return an empty string for a separator.
if (IsSeparator(menu_id))
return L"";
NavigationEntry* entry = GetNavigationEntry(menu_id);
return UTF16ToWideHack(entry->GetTitleForDisplay(
&GetTabContents()->controller()));
}
const SkBitmap& BackForwardMenuModel::GetItemIcon(int menu_id) const {
DCHECK(ItemHasIcon(menu_id));
NavigationEntry* entry = GetNavigationEntry(menu_id);
return entry->favicon().bitmap();
}
bool BackForwardMenuModel::ItemHasIcon(int menu_id) const {
// Using "id" not "id - 1" because the last item "Show Full History"
// doesn't have an icon.
return menu_id < GetTotalItemCount() && !IsSeparator(menu_id);
}
bool BackForwardMenuModel::ItemHasCommand(int menu_id) const {
return menu_id - 1 < GetTotalItemCount() && !IsSeparator(menu_id);
}
std::wstring BackForwardMenuModel::GetShowFullHistoryLabel() const {
return l10n_util::GetString(IDS_SHOWFULLHISTORY_LINK);
}
TabContents* BackForwardMenuModel::GetTabContents() const {
// We use the test tab contents if the unit test has specified it.
return test_tab_contents_ ? test_tab_contents_ :
browser_->GetSelectedTabContents();
}
int BackForwardMenuModel::MenuIdToNavEntryIndex(int menu_id) const {
TabContents* contents = GetTabContents();
int history_items = GetHistoryItemCount();
DCHECK(menu_id > 0);
// Convert anything above the History items separator.
if (menu_id <= history_items) {
if (model_type_ == FORWARD_MENU_DELEGATE) {
// The |menu_id| is relative to our current position, so we need to add.
menu_id += contents->controller().GetCurrentEntryIndex();
} else {
// Back menu is reverse.
menu_id = contents->controller().GetCurrentEntryIndex() - menu_id;
}
return menu_id;
}
if (menu_id == history_items + 1)
return -1; // Don't translate the separator for history items.
if (menu_id >= history_items + 1 + GetChapterStopCount(history_items) + 1)
return -1; // This is beyond the last chapter stop so we abort.
// This menu item is a chapter stop located between the two separators.
menu_id = FindChapterStop(history_items,
model_type_ == FORWARD_MENU_DELEGATE,
menu_id - history_items - 1 - 1);
return menu_id;
}
NavigationEntry* BackForwardMenuModel::GetNavigationEntry(int menu_id) const {
int index = MenuIdToNavEntryIndex(menu_id);
return GetTabContents()->controller().GetEntryAtIndex(index);
}
std::wstring BackForwardMenuModel::BuildActionName(
const std::wstring& action, int index) const {
DCHECK(!action.empty());
DCHECK(index >= -1);
std::wstring metric_string;
if (model_type_ == FORWARD_MENU_DELEGATE)
metric_string += L"ForwardMenu_";
else
metric_string += L"BackMenu_";
metric_string += action;
if (index != -1)
metric_string += IntToWString(index);
return metric_string;
}
<commit_msg>Linux and Mac support chrome://history by now. Remove NOTIMPLEMENTED.<commit_after>// Copyright (c) 2006-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 "build/build_config.h"
#include "chrome/browser/back_forward_menu_model.h"
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "net/base/registry_controlled_domain.h"
const int BackForwardMenuModel::kMaxHistoryItems = 12;
const int BackForwardMenuModel::kMaxChapterStops = 5;
int BackForwardMenuModel::GetHistoryItemCount() const {
TabContents* contents = GetTabContents();
int items = 0;
if (model_type_ == FORWARD_MENU_DELEGATE) {
// Only count items from n+1 to end (if n is current entry)
items = contents->controller().entry_count() -
contents->controller().GetCurrentEntryIndex() - 1;
} else {
items = contents->controller().GetCurrentEntryIndex();
}
if (items > kMaxHistoryItems)
items = kMaxHistoryItems;
else if (items < 0)
items = 0;
return items;
}
int BackForwardMenuModel::GetChapterStopCount(int history_items) const {
TabContents* contents = GetTabContents();
int chapter_stops = 0;
int current_entry = contents->controller().GetCurrentEntryIndex();
if (history_items == kMaxHistoryItems) {
int chapter_id = current_entry;
if (model_type_ == FORWARD_MENU_DELEGATE) {
chapter_id += history_items;
} else {
chapter_id -= history_items;
}
do {
chapter_id = GetIndexOfNextChapterStop(chapter_id,
model_type_ == FORWARD_MENU_DELEGATE);
if (chapter_id != -1)
++chapter_stops;
} while (chapter_id != -1 && chapter_stops < kMaxChapterStops);
}
return chapter_stops;
}
int BackForwardMenuModel::GetTotalItemCount() const {
int items = GetHistoryItemCount();
if (items > 0) {
int chapter_stops = 0;
// Next, we count ChapterStops, if any.
if (items == kMaxHistoryItems)
chapter_stops = GetChapterStopCount(items);
if (chapter_stops)
items += chapter_stops + 1; // Chapter stops also need a separator.
// If the menu is not empty, add two positions in the end
// for a separator and a "Show Full History" item.
items += 2;
}
return items;
}
int BackForwardMenuModel::GetIndexOfNextChapterStop(int start_from,
bool forward) const {
TabContents* contents = GetTabContents();
NavigationController& controller = contents->controller();
int max_count = controller.entry_count();
if (start_from < 0 || start_from >= max_count)
return -1; // Out of bounds.
if (forward) {
if (start_from < max_count - 1) {
// We want to advance over the current chapter stop, so we add one.
// We don't need to do this when direction is backwards.
start_from++;
} else {
return -1;
}
}
NavigationEntry* start_entry = controller.GetEntryAtIndex(start_from);
const GURL& url = start_entry->url();
if (!forward) {
// When going backwards we return the first entry we find that has a
// different domain.
for (int i = start_from - 1; i >= 0; --i) {
if (!net::RegistryControlledDomainService::SameDomainOrHost(url,
controller.GetEntryAtIndex(i)->url()))
return i;
}
// We have reached the beginning without finding a chapter stop.
return -1;
} else {
// When going forwards we return the entry before the entry that has a
// different domain.
for (int i = start_from + 1; i < max_count; ++i) {
if (!net::RegistryControlledDomainService::SameDomainOrHost(url,
controller.GetEntryAtIndex(i)->url()))
return i - 1;
}
// Last entry is always considered a chapter stop.
return max_count - 1;
}
}
int BackForwardMenuModel::FindChapterStop(int offset,
bool forward,
int skip) const {
if (offset < 0 || skip < 0)
return -1;
if (!forward)
offset *= -1;
TabContents* contents = GetTabContents();
int entry = contents->controller().GetCurrentEntryIndex() + offset;
for (int i = 0; i < skip + 1; i++)
entry = GetIndexOfNextChapterStop(entry, forward);
return entry;
}
void BackForwardMenuModel::ExecuteCommandById(int menu_id) {
TabContents* contents = GetTabContents();
NavigationController& controller = contents->controller();
DCHECK(!IsSeparator(menu_id));
// Execute the command for the last item: "Show Full History".
if (menu_id == GetTotalItemCount()) {
UserMetrics::RecordComputedAction(BuildActionName(L"ShowFullHistory", -1),
controller.profile());
browser_->ShowSingleDOMUITab(GURL(chrome::kChromeUIHistoryURL));
return;
}
// Log whether it was a history or chapter click.
if (menu_id <= GetHistoryItemCount()) {
UserMetrics::RecordComputedAction(
BuildActionName(L"HistoryClick", menu_id), controller.profile());
} else {
UserMetrics::RecordComputedAction(
BuildActionName(L"ChapterClick", menu_id - GetHistoryItemCount() - 1),
controller.profile());
}
int index = MenuIdToNavEntryIndex(menu_id);
if (index >= 0 && index < controller.entry_count())
controller.GoToIndex(index);
}
bool BackForwardMenuModel::IsSeparator(int menu_id) const {
int history_items = GetHistoryItemCount();
// If the menu_id is higher than the number of history items + separator,
// we then consider if it is a chapter-stop entry.
if (menu_id > history_items + 1) {
// We either are in ChapterStop area, or at the end of the list (the "Show
// Full History" link).
int chapter_stops = GetChapterStopCount(history_items);
if (chapter_stops == 0)
return false; // We must have reached the "Show Full History" link.
// Otherwise, look to see if we have reached the separator for the
// chapter-stops. If not, this is a chapter stop.
return (menu_id == history_items + 1 +
chapter_stops + 1);
}
// Look to see if we have reached the separator for the history items.
return menu_id == history_items + 1;
}
std::wstring BackForwardMenuModel::GetItemLabel(int menu_id) const {
// Return label "Show Full History" for the last item of the menu.
if (menu_id == GetTotalItemCount())
return l10n_util::GetString(IDS_SHOWFULLHISTORY_LINK);
// Return an empty string for a separator.
if (IsSeparator(menu_id))
return L"";
NavigationEntry* entry = GetNavigationEntry(menu_id);
return UTF16ToWideHack(entry->GetTitleForDisplay(
&GetTabContents()->controller()));
}
const SkBitmap& BackForwardMenuModel::GetItemIcon(int menu_id) const {
DCHECK(ItemHasIcon(menu_id));
NavigationEntry* entry = GetNavigationEntry(menu_id);
return entry->favicon().bitmap();
}
bool BackForwardMenuModel::ItemHasIcon(int menu_id) const {
// Using "id" not "id - 1" because the last item "Show Full History"
// doesn't have an icon.
return menu_id < GetTotalItemCount() && !IsSeparator(menu_id);
}
bool BackForwardMenuModel::ItemHasCommand(int menu_id) const {
return menu_id - 1 < GetTotalItemCount() && !IsSeparator(menu_id);
}
std::wstring BackForwardMenuModel::GetShowFullHistoryLabel() const {
return l10n_util::GetString(IDS_SHOWFULLHISTORY_LINK);
}
TabContents* BackForwardMenuModel::GetTabContents() const {
// We use the test tab contents if the unit test has specified it.
return test_tab_contents_ ? test_tab_contents_ :
browser_->GetSelectedTabContents();
}
int BackForwardMenuModel::MenuIdToNavEntryIndex(int menu_id) const {
TabContents* contents = GetTabContents();
int history_items = GetHistoryItemCount();
DCHECK(menu_id > 0);
// Convert anything above the History items separator.
if (menu_id <= history_items) {
if (model_type_ == FORWARD_MENU_DELEGATE) {
// The |menu_id| is relative to our current position, so we need to add.
menu_id += contents->controller().GetCurrentEntryIndex();
} else {
// Back menu is reverse.
menu_id = contents->controller().GetCurrentEntryIndex() - menu_id;
}
return menu_id;
}
if (menu_id == history_items + 1)
return -1; // Don't translate the separator for history items.
if (menu_id >= history_items + 1 + GetChapterStopCount(history_items) + 1)
return -1; // This is beyond the last chapter stop so we abort.
// This menu item is a chapter stop located between the two separators.
menu_id = FindChapterStop(history_items,
model_type_ == FORWARD_MENU_DELEGATE,
menu_id - history_items - 1 - 1);
return menu_id;
}
NavigationEntry* BackForwardMenuModel::GetNavigationEntry(int menu_id) const {
int index = MenuIdToNavEntryIndex(menu_id);
return GetTabContents()->controller().GetEntryAtIndex(index);
}
std::wstring BackForwardMenuModel::BuildActionName(
const std::wstring& action, int index) const {
DCHECK(!action.empty());
DCHECK(index >= -1);
std::wstring metric_string;
if (model_type_ == FORWARD_MENU_DELEGATE)
metric_string += L"ForwardMenu_";
else
metric_string += L"BackMenu_";
metric_string += action;
if (index != -1)
metric_string += IntToWString(index);
return metric_string;
}
<|endoftext|> |
<commit_before><commit_msg>Clear yet another few stats when a new chrome version is installed<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QTextDocument>
#include <QTextLayout>
#include <QDebug>
#include <QAbstractTextDocumentLayout>
#include <QSyntaxHighlighter>
//TESTED_CLASS=
//TESTED_FILES=
//
class QTestDocumentLayout : public QAbstractTextDocumentLayout
{
Q_OBJECT
public:
inline QTestDocumentLayout(QTextDocument *doc)
: QAbstractTextDocumentLayout(doc), documentChangedCalled(false) {}
virtual void draw(QPainter *, const QAbstractTextDocumentLayout::PaintContext &) {}
virtual int hitTest(const QPointF &, Qt::HitTestAccuracy ) const { return 0; }
virtual void documentChanged(int, int, int) { documentChangedCalled = true; }
virtual int pageCount() const { return 1; }
virtual QSizeF documentSize() const { return QSize(); }
virtual QRectF frameBoundingRect(QTextFrame *) const { return QRectF(); }
virtual QRectF blockBoundingRect(const QTextBlock &) const { return QRectF(); }
bool documentChangedCalled;
};
class tst_QSyntaxHighlighter : public QObject
{
Q_OBJECT
public:
inline tst_QSyntaxHighlighter() {}
public slots:
void init();
void cleanup();
private slots:
void basic();
void basicTwo();
void removeFormatsOnDelete();
void emptyBlocks();
void setCharFormat();
void highlightOnInit();
void stopHighlightingWhenStateDoesNotChange();
void unindent();
void highlightToEndOfDocument();
void highlightToEndOfDocument2();
void preservePreeditArea();
void task108530();
void avoidUnnecessaryRehighlight();
void noContentsChangedDuringHighlight();
void rehighlight();
private:
QTextDocument *doc;
QTestDocumentLayout *lout;
QTextCursor cursor;
};
void tst_QSyntaxHighlighter::init()
{
doc = new QTextDocument;
lout = new QTestDocumentLayout(doc);
doc->setDocumentLayout(lout);
cursor = QTextCursor(doc);
}
void tst_QSyntaxHighlighter::cleanup()
{
delete doc;
doc = 0;
}
class TestHighlighter : public QSyntaxHighlighter
{
public:
inline TestHighlighter(const QList<QTextLayout::FormatRange> &fmts, QTextDocument *parent)
: QSyntaxHighlighter(parent), formats(fmts), highlighted(false), callCount(0) {}
inline TestHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), highlighted(false), callCount(0) {}
virtual void highlightBlock(const QString &text)
{
for (int i = 0; i < formats.count(); ++i) {
const QTextLayout::FormatRange &range = formats.at(i);
setFormat(range.start, range.length, range.format);
}
highlighted = true;
highlightedText += text;
++callCount;
}
QList<QTextLayout::FormatRange> formats;
bool highlighted;
int callCount;
QString highlightedText;
};
QT_BEGIN_NAMESPACE
static bool operator==(const QTextLayout::FormatRange &lhs, const QTextLayout::FormatRange &rhs)
{
return lhs.start == rhs.start
&& lhs.length == rhs.length
&& lhs.format == rhs.format;
}
QT_END_NAMESPACE
void tst_QSyntaxHighlighter::basic()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 2;
range.format.setForeground(Qt::blue);
formats.append(range);
range.start = 4;
range.length = 2;
range.format.setFontItalic(true);
formats.append(range);
range.start = 9;
range.length = 2;
range.format.setFontUnderline(true);
formats.append(range);
TestHighlighter *hl = new TestHighlighter(formats, doc);
lout->documentChangedCalled = false;
doc->setPlainText("Hello World");
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
QVERIFY(doc->begin().layout()->additionalFormats() == formats);
}
class CommentTestHighlighter : public QSyntaxHighlighter
{
public:
inline CommentTestHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), highlighted(false) {}
inline void reset()
{
highlighted = false;
}
virtual void highlightBlock(const QString &text)
{
QTextCharFormat commentFormat;
commentFormat.setForeground(Qt::darkGreen);
commentFormat.setFontWeight(QFont::StyleItalic);
commentFormat.setFontFixedPitch(true);
int textLength = text.length();
if (text.startsWith(QLatin1Char(';'))){
// The entire line is a comment
setFormat(0, textLength, commentFormat);
highlighted = true;
}
}
bool highlighted;
};
void tst_QSyntaxHighlighter::basicTwo()
{
// Done for task 104409
CommentTestHighlighter *hl = new CommentTestHighlighter(doc);
doc->setPlainText("; a test");
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
}
void tst_QSyntaxHighlighter::removeFormatsOnDelete()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 9;
range.format.setForeground(Qt::blue);
formats.append(range);
TestHighlighter *hl = new TestHighlighter(formats, doc);
lout->documentChangedCalled = false;
doc->setPlainText("Hello World");
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
lout->documentChangedCalled = false;
QVERIFY(!doc->begin().layout()->additionalFormats().isEmpty());
delete hl;
QVERIFY(doc->begin().layout()->additionalFormats().isEmpty());
QVERIFY(lout->documentChangedCalled);
}
void tst_QSyntaxHighlighter::emptyBlocks()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.insertText("Foo");
cursor.insertBlock();
cursor.insertBlock();
hl->highlighted = false;
cursor.insertBlock();
QVERIFY(hl->highlighted);
}
void tst_QSyntaxHighlighter::setCharFormat()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.insertText("FooBar");
cursor.insertBlock();
cursor.insertText("Blah");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
QTextCharFormat fmt;
fmt.setFontItalic(true);
hl->highlighted = false;
hl->callCount = 0;
cursor.mergeCharFormat(fmt);
QVERIFY(hl->highlighted);
QCOMPARE(hl->callCount, 2);
}
void tst_QSyntaxHighlighter::highlightOnInit()
{
cursor.insertText("Hello");
cursor.insertBlock();
cursor.insertText("World");
TestHighlighter *hl = new TestHighlighter(doc);
QTest::qWait(100);
QVERIFY(hl->highlighted);
}
class StateTestHighlighter : public QSyntaxHighlighter
{
public:
inline StateTestHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), state(0), highlighted(false) {}
inline void reset()
{
highlighted = false;
state = 0;
}
virtual void highlightBlock(const QString &text)
{
highlighted = true;
if (text == QLatin1String("changestate"))
setCurrentBlockState(state++);
}
int state;
bool highlighted;
};
void tst_QSyntaxHighlighter::stopHighlightingWhenStateDoesNotChange()
{
cursor.insertText("state");
cursor.insertBlock();
cursor.insertText("changestate");
cursor.insertBlock();
cursor.insertText("keepstate");
cursor.insertBlock();
cursor.insertText("changestate");
cursor.insertBlock();
cursor.insertText("changestate");
StateTestHighlighter *hl = new StateTestHighlighter(doc);
QTest::qWait(100);
QVERIFY(hl->highlighted);
hl->reset();
// turn the text of the first block into 'changestate'
cursor.movePosition(QTextCursor::Start);
cursor.insertText("change");
// verify that we highlighted only to the 'keepstate' block,
// not beyond
QCOMPARE(hl->state, 2);
}
void tst_QSyntaxHighlighter::unindent()
{
const QString spaces(" ");
const QString text("Foobar");
QString plainText;
for (int i = 0; i < 5; ++i) {
cursor.insertText(spaces + text);
cursor.insertBlock();
plainText += spaces;
plainText += text;
plainText += QLatin1Char('\n');
}
QCOMPARE(doc->toPlainText(), plainText);
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
cursor.movePosition(QTextCursor::Start);
cursor.beginEditBlock();
plainText.clear();
for (int i = 0; i < 5; ++i) {
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 4);
cursor.removeSelectedText();
cursor.movePosition(QTextCursor::NextBlock);
plainText += text;
plainText += QLatin1Char('\n');
}
cursor.endEditBlock();
QCOMPARE(doc->toPlainText(), plainText);
QCOMPARE(hl->callCount, 5);
}
void tst_QSyntaxHighlighter::highlightToEndOfDocument()
{
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
cursor.movePosition(QTextCursor::Start);
cursor.beginEditBlock();
cursor.insertText("Hello");
cursor.insertBlock();
cursor.insertBlock();
cursor.insertText("World");
cursor.insertBlock();
cursor.endEditBlock();
QCOMPARE(hl->callCount, 4);
}
void tst_QSyntaxHighlighter::highlightToEndOfDocument2()
{
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
cursor.movePosition(QTextCursor::End);
cursor.beginEditBlock();
QTextBlockFormat fmt;
fmt.setAlignment(Qt::AlignLeft);
cursor.setBlockFormat(fmt);
cursor.insertText("Three\nLines\nHere");
cursor.endEditBlock();
QCOMPARE(hl->callCount, 3);
}
void tst_QSyntaxHighlighter::preservePreeditArea()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 8;
range.format.setForeground(Qt::blue);
formats << range;
range.start = 9;
range.length = 1;
range.format.setForeground(Qt::red);
formats << range;
TestHighlighter *hl = new TestHighlighter(formats, doc);
doc->setPlainText("Hello World");
cursor.movePosition(QTextCursor::Start);
QTextLayout *layout = cursor.block().layout();
layout->setPreeditArea(5, QString("foo"));
range.start = 5;
range.length = 3;
range.format.setFontUnderline(true);
formats.clear();
formats << range;
hl->callCount = 0;
cursor.beginEditBlock();
layout->setAdditionalFormats(formats);
cursor.endEditBlock();
QCOMPARE(hl->callCount, 1);
formats = layout->additionalFormats();
QCOMPARE(formats.count(), 3);
range = formats.at(0);
QCOMPARE(range.start, 5);
QCOMPARE(range.length, 3);
QVERIFY(range.format.fontUnderline());
range = formats.at(1);
QCOMPARE(range.start, 0);
QCOMPARE(range.length, 8 + 3);
range = formats.at(2);
QCOMPARE(range.start, 9 + 3);
QCOMPARE(range.length, 1);
}
void tst_QSyntaxHighlighter::task108530()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.insertText("test");
hl->callCount = 0;
hl->highlightedText.clear();
cursor.movePosition(QTextCursor::Start);
cursor.insertBlock();
QCOMPARE(hl->highlightedText, QString("test"));
QCOMPARE(hl->callCount, 2);
}
void tst_QSyntaxHighlighter::avoidUnnecessaryRehighlight()
{
TestHighlighter *hl = new TestHighlighter(doc);
QVERIFY(!hl->highlighted);
doc->setPlainText("Hello World");
QVERIFY(hl->highlighted);
hl->highlighted = false;
QTest::qWait(100);
QVERIFY(!hl->highlighted);
}
void tst_QSyntaxHighlighter::noContentsChangedDuringHighlight()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 10;
range.format.setForeground(Qt::blue);
formats.append(range);
TestHighlighter *hl = new TestHighlighter(formats, doc);
lout->documentChangedCalled = false;
QTextCursor cursor(doc);
QSignalSpy contentsChangedSpy(doc, SIGNAL(contentsChanged()));
cursor.insertText("Hello World");
QCOMPARE(contentsChangedSpy.count(), 1);
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
}
void tst_QSyntaxHighlighter::rehighlight()
{
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
doc->setPlainText("Hello");
hl->callCount = 0;
hl->rehighlight();
QCOMPARE(hl->callCount, 1);
}
QTEST_MAIN(tst_QSyntaxHighlighter)
#include "tst_qsyntaxhighlighter.moc"
<commit_msg>Added QSyntaxHighlighter::rehighlightBlock() auto test<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QTextDocument>
#include <QTextLayout>
#include <QDebug>
#include <QAbstractTextDocumentLayout>
#include <QSyntaxHighlighter>
//TESTED_CLASS=
//TESTED_FILES=
//
class QTestDocumentLayout : public QAbstractTextDocumentLayout
{
Q_OBJECT
public:
inline QTestDocumentLayout(QTextDocument *doc)
: QAbstractTextDocumentLayout(doc), documentChangedCalled(false) {}
virtual void draw(QPainter *, const QAbstractTextDocumentLayout::PaintContext &) {}
virtual int hitTest(const QPointF &, Qt::HitTestAccuracy ) const { return 0; }
virtual void documentChanged(int, int, int) { documentChangedCalled = true; }
virtual int pageCount() const { return 1; }
virtual QSizeF documentSize() const { return QSize(); }
virtual QRectF frameBoundingRect(QTextFrame *) const { return QRectF(); }
virtual QRectF blockBoundingRect(const QTextBlock &) const { return QRectF(); }
bool documentChangedCalled;
};
class tst_QSyntaxHighlighter : public QObject
{
Q_OBJECT
public:
inline tst_QSyntaxHighlighter() {}
public slots:
void init();
void cleanup();
private slots:
void basic();
void basicTwo();
void removeFormatsOnDelete();
void emptyBlocks();
void setCharFormat();
void highlightOnInit();
void stopHighlightingWhenStateDoesNotChange();
void unindent();
void highlightToEndOfDocument();
void highlightToEndOfDocument2();
void preservePreeditArea();
void task108530();
void avoidUnnecessaryRehighlight();
void noContentsChangedDuringHighlight();
void rehighlight();
void rehighlightBlock();
private:
QTextDocument *doc;
QTestDocumentLayout *lout;
QTextCursor cursor;
};
void tst_QSyntaxHighlighter::init()
{
doc = new QTextDocument;
lout = new QTestDocumentLayout(doc);
doc->setDocumentLayout(lout);
cursor = QTextCursor(doc);
}
void tst_QSyntaxHighlighter::cleanup()
{
delete doc;
doc = 0;
}
class TestHighlighter : public QSyntaxHighlighter
{
public:
inline TestHighlighter(const QList<QTextLayout::FormatRange> &fmts, QTextDocument *parent)
: QSyntaxHighlighter(parent), formats(fmts), highlighted(false), callCount(0) {}
inline TestHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), highlighted(false), callCount(0) {}
virtual void highlightBlock(const QString &text)
{
for (int i = 0; i < formats.count(); ++i) {
const QTextLayout::FormatRange &range = formats.at(i);
setFormat(range.start, range.length, range.format);
}
highlighted = true;
highlightedText += text;
++callCount;
}
QList<QTextLayout::FormatRange> formats;
bool highlighted;
int callCount;
QString highlightedText;
};
QT_BEGIN_NAMESPACE
static bool operator==(const QTextLayout::FormatRange &lhs, const QTextLayout::FormatRange &rhs)
{
return lhs.start == rhs.start
&& lhs.length == rhs.length
&& lhs.format == rhs.format;
}
QT_END_NAMESPACE
void tst_QSyntaxHighlighter::basic()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 2;
range.format.setForeground(Qt::blue);
formats.append(range);
range.start = 4;
range.length = 2;
range.format.setFontItalic(true);
formats.append(range);
range.start = 9;
range.length = 2;
range.format.setFontUnderline(true);
formats.append(range);
TestHighlighter *hl = new TestHighlighter(formats, doc);
lout->documentChangedCalled = false;
doc->setPlainText("Hello World");
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
QVERIFY(doc->begin().layout()->additionalFormats() == formats);
}
class CommentTestHighlighter : public QSyntaxHighlighter
{
public:
inline CommentTestHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), highlighted(false) {}
inline void reset()
{
highlighted = false;
}
virtual void highlightBlock(const QString &text)
{
QTextCharFormat commentFormat;
commentFormat.setForeground(Qt::darkGreen);
commentFormat.setFontWeight(QFont::StyleItalic);
commentFormat.setFontFixedPitch(true);
int textLength = text.length();
if (text.startsWith(QLatin1Char(';'))){
// The entire line is a comment
setFormat(0, textLength, commentFormat);
highlighted = true;
}
}
bool highlighted;
};
void tst_QSyntaxHighlighter::basicTwo()
{
// Done for task 104409
CommentTestHighlighter *hl = new CommentTestHighlighter(doc);
doc->setPlainText("; a test");
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
}
void tst_QSyntaxHighlighter::removeFormatsOnDelete()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 9;
range.format.setForeground(Qt::blue);
formats.append(range);
TestHighlighter *hl = new TestHighlighter(formats, doc);
lout->documentChangedCalled = false;
doc->setPlainText("Hello World");
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
lout->documentChangedCalled = false;
QVERIFY(!doc->begin().layout()->additionalFormats().isEmpty());
delete hl;
QVERIFY(doc->begin().layout()->additionalFormats().isEmpty());
QVERIFY(lout->documentChangedCalled);
}
void tst_QSyntaxHighlighter::emptyBlocks()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.insertText("Foo");
cursor.insertBlock();
cursor.insertBlock();
hl->highlighted = false;
cursor.insertBlock();
QVERIFY(hl->highlighted);
}
void tst_QSyntaxHighlighter::setCharFormat()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.insertText("FooBar");
cursor.insertBlock();
cursor.insertText("Blah");
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
QTextCharFormat fmt;
fmt.setFontItalic(true);
hl->highlighted = false;
hl->callCount = 0;
cursor.mergeCharFormat(fmt);
QVERIFY(hl->highlighted);
QCOMPARE(hl->callCount, 2);
}
void tst_QSyntaxHighlighter::highlightOnInit()
{
cursor.insertText("Hello");
cursor.insertBlock();
cursor.insertText("World");
TestHighlighter *hl = new TestHighlighter(doc);
QTest::qWait(100);
QVERIFY(hl->highlighted);
}
class StateTestHighlighter : public QSyntaxHighlighter
{
public:
inline StateTestHighlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent), state(0), highlighted(false) {}
inline void reset()
{
highlighted = false;
state = 0;
}
virtual void highlightBlock(const QString &text)
{
highlighted = true;
if (text == QLatin1String("changestate"))
setCurrentBlockState(state++);
}
int state;
bool highlighted;
};
void tst_QSyntaxHighlighter::stopHighlightingWhenStateDoesNotChange()
{
cursor.insertText("state");
cursor.insertBlock();
cursor.insertText("changestate");
cursor.insertBlock();
cursor.insertText("keepstate");
cursor.insertBlock();
cursor.insertText("changestate");
cursor.insertBlock();
cursor.insertText("changestate");
StateTestHighlighter *hl = new StateTestHighlighter(doc);
QTest::qWait(100);
QVERIFY(hl->highlighted);
hl->reset();
// turn the text of the first block into 'changestate'
cursor.movePosition(QTextCursor::Start);
cursor.insertText("change");
// verify that we highlighted only to the 'keepstate' block,
// not beyond
QCOMPARE(hl->state, 2);
}
void tst_QSyntaxHighlighter::unindent()
{
const QString spaces(" ");
const QString text("Foobar");
QString plainText;
for (int i = 0; i < 5; ++i) {
cursor.insertText(spaces + text);
cursor.insertBlock();
plainText += spaces;
plainText += text;
plainText += QLatin1Char('\n');
}
QCOMPARE(doc->toPlainText(), plainText);
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
cursor.movePosition(QTextCursor::Start);
cursor.beginEditBlock();
plainText.clear();
for (int i = 0; i < 5; ++i) {
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 4);
cursor.removeSelectedText();
cursor.movePosition(QTextCursor::NextBlock);
plainText += text;
plainText += QLatin1Char('\n');
}
cursor.endEditBlock();
QCOMPARE(doc->toPlainText(), plainText);
QCOMPARE(hl->callCount, 5);
}
void tst_QSyntaxHighlighter::highlightToEndOfDocument()
{
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
cursor.movePosition(QTextCursor::Start);
cursor.beginEditBlock();
cursor.insertText("Hello");
cursor.insertBlock();
cursor.insertBlock();
cursor.insertText("World");
cursor.insertBlock();
cursor.endEditBlock();
QCOMPARE(hl->callCount, 4);
}
void tst_QSyntaxHighlighter::highlightToEndOfDocument2()
{
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
cursor.movePosition(QTextCursor::End);
cursor.beginEditBlock();
QTextBlockFormat fmt;
fmt.setAlignment(Qt::AlignLeft);
cursor.setBlockFormat(fmt);
cursor.insertText("Three\nLines\nHere");
cursor.endEditBlock();
QCOMPARE(hl->callCount, 3);
}
void tst_QSyntaxHighlighter::preservePreeditArea()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 8;
range.format.setForeground(Qt::blue);
formats << range;
range.start = 9;
range.length = 1;
range.format.setForeground(Qt::red);
formats << range;
TestHighlighter *hl = new TestHighlighter(formats, doc);
doc->setPlainText("Hello World");
cursor.movePosition(QTextCursor::Start);
QTextLayout *layout = cursor.block().layout();
layout->setPreeditArea(5, QString("foo"));
range.start = 5;
range.length = 3;
range.format.setFontUnderline(true);
formats.clear();
formats << range;
hl->callCount = 0;
cursor.beginEditBlock();
layout->setAdditionalFormats(formats);
cursor.endEditBlock();
QCOMPARE(hl->callCount, 1);
formats = layout->additionalFormats();
QCOMPARE(formats.count(), 3);
range = formats.at(0);
QCOMPARE(range.start, 5);
QCOMPARE(range.length, 3);
QVERIFY(range.format.fontUnderline());
range = formats.at(1);
QCOMPARE(range.start, 0);
QCOMPARE(range.length, 8 + 3);
range = formats.at(2);
QCOMPARE(range.start, 9 + 3);
QCOMPARE(range.length, 1);
}
void tst_QSyntaxHighlighter::task108530()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.insertText("test");
hl->callCount = 0;
hl->highlightedText.clear();
cursor.movePosition(QTextCursor::Start);
cursor.insertBlock();
QCOMPARE(hl->highlightedText, QString("test"));
QCOMPARE(hl->callCount, 2);
}
void tst_QSyntaxHighlighter::avoidUnnecessaryRehighlight()
{
TestHighlighter *hl = new TestHighlighter(doc);
QVERIFY(!hl->highlighted);
doc->setPlainText("Hello World");
QVERIFY(hl->highlighted);
hl->highlighted = false;
QTest::qWait(100);
QVERIFY(!hl->highlighted);
}
void tst_QSyntaxHighlighter::noContentsChangedDuringHighlight()
{
QList<QTextLayout::FormatRange> formats;
QTextLayout::FormatRange range;
range.start = 0;
range.length = 10;
range.format.setForeground(Qt::blue);
formats.append(range);
TestHighlighter *hl = new TestHighlighter(formats, doc);
lout->documentChangedCalled = false;
QTextCursor cursor(doc);
QSignalSpy contentsChangedSpy(doc, SIGNAL(contentsChanged()));
cursor.insertText("Hello World");
QCOMPARE(contentsChangedSpy.count(), 1);
QVERIFY(hl->highlighted);
QVERIFY(lout->documentChangedCalled);
}
void tst_QSyntaxHighlighter::rehighlight()
{
TestHighlighter *hl = new TestHighlighter(doc);
hl->callCount = 0;
doc->setPlainText("Hello");
hl->callCount = 0;
hl->rehighlight();
QCOMPARE(hl->callCount, 1);
}
void tst_QSyntaxHighlighter::rehighlightBlock()
{
TestHighlighter *hl = new TestHighlighter(doc);
cursor.movePosition(QTextCursor::Start);
cursor.beginEditBlock();
cursor.insertText("Hello");
cursor.insertBlock();
cursor.insertText("World");
cursor.endEditBlock();
hl->callCount = 0;
hl->highlightedText.clear();
QTextBlock block = doc->begin();
hl->rehighlightBlock(block);
QCOMPARE(hl->highlightedText, QString("Hello"));
QCOMPARE(hl->callCount, 1);
hl->callCount = 0;
hl->highlightedText.clear();
hl->rehighlightBlock(block.next());
QCOMPARE(hl->highlightedText, QString("World"));
QCOMPARE(hl->callCount, 1);
}
QTEST_MAIN(tst_QSyntaxHighlighter)
#include "tst_qsyntaxhighlighter.moc"
<|endoftext|> |
<commit_before>#include <string.h>
#include <string>
#include "BufferedFileReader.h"
#include "BufferedFileWriter.h"
#include "mcut.h"
#define BUFFER_SIZE 1048576
/*
* Reverse memchr()
* Find the last occurrence of 'c' in the buffer 's' of size 'n'.
*/
void *memrchr(const void *s, int c, size_t n)
{
const unsigned char *cp;
if (n != 0) {
cp = (unsigned char *)s + n;
do {
if (*(--cp) == (unsigned char)c) {
return (void *)cp;
}
} while (--n != 0);
}
return (void *)0;
}
void parseContent(const char *content, size_t contentSize, const char *pattern, size_t &part1Size, size_t &part2Size)
{
const char *patternPos = strstr(content, pattern);
if (!patternPos) {
const void *lfPos = memrchr(content, '\n', contentSize);
if (!lfPos) {
part1Size = contentSize;
} else {
part1Size = (const char *)lfPos - content + 1;
}
part2Size = 0;
} else {
const void *lfPos = memrchr(content, '\n', patternPos - content);
if (!lfPos) {
part1Size = 0;
} else {
part1Size = (const char *)lfPos - content + 1;
}
part2Size = contentSize - part1Size;
}
}
void process(const char *file, const char *pattern)
{
std::string dest1Name = std::string(file) + "_1";
std::string dest2Name = std::string(file) + "_2";
BufferedFileReader reader(file);
BufferedFileWriter writer1(dest1Name.c_str());
BufferedFileWriter writer2(dest2Name.c_str());
char *content = (char *)malloc(BUFFER_SIZE + 1);
size_t contentSize = 0;
size_t part1Size = 0;
size_t part2Size = 0;
// search and write part1/part2 data
while (true) {
contentSize += reader.read(content + contentSize, BUFFER_SIZE - contentSize);
if (contentSize == 0) {
break;
}
content[contentSize] = 0;
parseContent(content, contentSize, pattern, part1Size, part2Size);
// printf("part1Size = %ld, part2Size = %ld\n", part1Size, part2Size);
putchar((part2Size > 0) ? '|' : '.');
writer1.write(content, part1Size);
writer2.write(content + part1Size, part2Size);
if (part2Size > 0) {
break;
}
contentSize -= part1Size;
memmove(content, content + part1Size, contentSize);
}
free(content);
// write part2 data
const void *data = NULL;
size_t dataSize = 0;
while ((dataSize = reader.read(data)) > 0) {
// printf("dataSize = %ld\n", 0, dataSize);
putchar('.');
writer2.write(data, dataSize);
}
putchar('\n');
}
void printHelp()
{
printf("mcut: Cut a file based on match\n");
printf("Usage\n");
printf("$ mcut <pattern> <input_file>\n");
}
int main(int argc, char *argv[])
{
if (argc != 3) {
printHelp();
return 1;
}
const char *pattern = argv[1];
const char *file = argv[2];
printf("pattern = %s\n", pattern);
printf("file = %s\n", file);
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
process(file, pattern);
return 0;
}
<commit_msg>fflush(stdout) to show progress<commit_after>#include <string.h>
#include <string>
#include "BufferedFileReader.h"
#include "BufferedFileWriter.h"
#include "mcut.h"
#define BUFFER_SIZE 1048576
/*
* Reverse memchr()
* Find the last occurrence of 'c' in the buffer 's' of size 'n'.
*/
void *memrchr(const void *s, int c, size_t n)
{
const unsigned char *cp;
if (n != 0) {
cp = (unsigned char *)s + n;
do {
if (*(--cp) == (unsigned char)c) {
return (void *)cp;
}
} while (--n != 0);
}
return (void *)0;
}
void parseContent(const char *content, size_t contentSize, const char *pattern, size_t &part1Size, size_t &part2Size)
{
const char *patternPos = strstr(content, pattern);
if (!patternPos) {
const void *lfPos = memrchr(content, '\n', contentSize);
if (!lfPos) {
part1Size = contentSize;
} else {
part1Size = (const char *)lfPos - content + 1;
}
part2Size = 0;
} else {
const void *lfPos = memrchr(content, '\n', patternPos - content);
if (!lfPos) {
part1Size = 0;
} else {
part1Size = (const char *)lfPos - content + 1;
}
part2Size = contentSize - part1Size;
}
}
void process(const char *file, const char *pattern)
{
std::string dest1Name = std::string(file) + "_1";
std::string dest2Name = std::string(file) + "_2";
BufferedFileReader reader(file);
BufferedFileWriter writer1(dest1Name.c_str());
BufferedFileWriter writer2(dest2Name.c_str());
char *content = (char *)malloc(BUFFER_SIZE + 1);
size_t contentSize = 0;
size_t part1Size = 0;
size_t part2Size = 0;
// search and write part1/part2 data
while (true) {
contentSize += reader.read(content + contentSize, BUFFER_SIZE - contentSize);
if (contentSize == 0) {
break;
}
content[contentSize] = 0;
parseContent(content, contentSize, pattern, part1Size, part2Size);
// printf("part1Size = %ld, part2Size = %ld\n", part1Size, part2Size);
putchar((part2Size > 0) ? '|' : '.');
fflush(stdout);
writer1.write(content, part1Size);
writer2.write(content + part1Size, part2Size);
if (part2Size > 0) {
break;
}
contentSize -= part1Size;
memmove(content, content + part1Size, contentSize);
}
free(content);
// write part2 data
const void *data = NULL;
size_t dataSize = 0;
while ((dataSize = reader.read(data)) > 0) {
// printf("dataSize = %ld\n", 0, dataSize);
putchar('.');
fflush(stdout);
writer2.write(data, dataSize);
}
putchar('\n');
}
void printHelp()
{
printf("mcut: Cut a file based on match\n");
printf("Usage\n");
printf("$ mcut <pattern> <input_file>\n");
}
int main(int argc, char *argv[])
{
if (argc != 3) {
printHelp();
return 1;
}
const char *pattern = argv[1];
const char *file = argv[2];
printf("pattern = %s\n", pattern);
printf("file = %s\n", file);
printf("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n");
process(file, pattern);
return 0;
}
<|endoftext|> |
<commit_before>#include <nan.h>
#include "input.h"
#include "output.h"
Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct;
Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct;
extern "C" {
void init (v8::Local<v8::Object> target)
{
NodeMidiOutput::Init(target);
NodeMidiInput::Init(target);
}
NODE_MODULE(midi, init)
}
<commit_msg>Use the NAN module init.<commit_after>#include <nan.h>
#include "input.h"
#include "output.h"
Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct;
Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct;
NAN_MODULE_INIT(InitAll) {
NodeMidiOutput::Init(target);
NodeMidiInput::Init(target);
}
NODE_MODULE(midi, InitAll)
<|endoftext|> |
<commit_before>
// This file is part of node-lmdb, the Node.js binding for lmdb
// Copyright (c) 2013 Timur Kristóf
// Licensed to you under the terms of 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.
#include "node-lmdb.h"
#include <string.h>
#include <stdio.h>
void setupExportMisc(Handle<Object> exports) {
Local<Object> versionObj = Nan::New<Object>();
int major, minor, patch;
char *str = mdb_version(&major, &minor, &patch);
versionObj->Set(Nan::New<String>("versionString").ToLocalChecked(), Nan::New<String>(str).ToLocalChecked());
versionObj->Set(Nan::New<String>("major").ToLocalChecked(), Nan::New<Integer>(major));
versionObj->Set(Nan::New<String>("minor").ToLocalChecked(), Nan::New<Integer>(minor));
versionObj->Set(Nan::New<String>("patch").ToLocalChecked(), Nan::New<Integer>(patch));
exports->Set(Nan::New<String>("version").ToLocalChecked(), versionObj);
}
void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Local<Object> options) {
Handle<Value> opt = options->Get(Nan::New<String>(name).ToLocalChecked());
if (opt->IsBoolean() ? opt->BooleanValue() : defaultValue) {
*flags |= flag;
}
}
argtokey_callback_t argToKey(const Handle<Value> &val, MDB_val &key, bool keyIsUint32) {
// Check key type
if (keyIsUint32 && !val->IsUint32()) {
Nan::ThrowError("Invalid key. keyIsUint32 specified on the database, but the given key was not an unsigned 32-bit integer");
return nullptr;
}
if (!keyIsUint32 && !val->IsString()) {
Nan::ThrowError("Invalid key. String key expected, because keyIsUint32 isn't specified on the database.");
return nullptr;
}
// Handle uint32_t key
if (keyIsUint32) {
uint32_t *v = new uint32_t;
*v = val->Uint32Value();
key.mv_size = sizeof(uint32_t);
key.mv_data = v;
return ([](MDB_val &key) -> void {
delete (uint32_t*)key.mv_data;
});
}
// Handle string key
CustomExternalStringResource::writeTo(val->ToString(), &key);
return ([](MDB_val &key) -> void {
delete[] (uint16_t*)key.mv_data;
});
return nullptr;
}
Handle<Value> keyToHandle(MDB_val &key, bool keyIsUint32) {
if (keyIsUint32) {
return Nan::New<Integer>(*((uint32_t*)key.mv_data));
}
else {
return valToString(key);
}
}
Handle<Value> valToString(MDB_val &data) {
auto resource = new CustomExternalStringResource(&data);
auto str = String::NewExternalTwoByte(Isolate::GetCurrent(), resource);
return str.ToLocalChecked();
// return Nan::New<String>(str).ToLocalChecked();
}
Handle<Value> valToBinary(MDB_val &data) {
// FIXME: It'd be better not to copy buffers, but I'm not sure
// about the ownership semantics of MDB_val, so let' be safe.
return Nan::CopyBuffer(
(char*)data.mv_data,
data.mv_size
).ToLocalChecked();
}
Handle<Value> valToNumber(MDB_val &data) {
return Nan::New<Number>(*((double*)data.mv_data));
}
Handle<Value> valToBoolean(MDB_val &data) {
return Nan::New<Boolean>(*((bool*)data.mv_data));
}
void consoleLog(const char *msg) {
Local<String> str = Nan::New("console.log('").ToLocalChecked();
str = String::Concat(str, Nan::New<String>(msg).ToLocalChecked());
str = String::Concat(str, Nan::New("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLog(Handle<Value> val) {
Local<String> str = Nan::New<String>("console.log('").ToLocalChecked();
str = String::Concat(str, val->ToString());
str = String::Concat(str, Nan::New<String>("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLogN(int n) {
char c[20];
memset(c, 0, 20 * sizeof(char));
sprintf(c, "%d", n);
consoleLog(c);
}
void CustomExternalStringResource::writeTo(Handle<String> str, MDB_val *val) {
unsigned int l = str->Length() + 1;
uint16_t *d = new uint16_t[l];
str->Write(d);
d[l - 1] = 0;
val->mv_data = d;
val->mv_size = l * sizeof(uint16_t);
}
CustomExternalStringResource::CustomExternalStringResource(MDB_val *val) {
// The UTF-16 data
this->d = (uint16_t*)(val->mv_data);
// Number of UTF-16 characters in the string
this->l = (val->mv_size / sizeof(uint16_t) - 1);
}
CustomExternalStringResource::~CustomExternalStringResource() { }
void CustomExternalStringResource::Dispose() {
// No need to do anything, the data is owned by LMDB, not us
}
const uint16_t *CustomExternalStringResource::data() const {
return this->d;
}
size_t CustomExternalStringResource::length() const {
return this->l;
}
<commit_msg>removed dead code<commit_after>
// This file is part of node-lmdb, the Node.js binding for lmdb
// Copyright (c) 2013 Timur Kristóf
// Licensed to you under the terms of 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.
#include "node-lmdb.h"
#include <string.h>
#include <stdio.h>
void setupExportMisc(Handle<Object> exports) {
Local<Object> versionObj = Nan::New<Object>();
int major, minor, patch;
char *str = mdb_version(&major, &minor, &patch);
versionObj->Set(Nan::New<String>("versionString").ToLocalChecked(), Nan::New<String>(str).ToLocalChecked());
versionObj->Set(Nan::New<String>("major").ToLocalChecked(), Nan::New<Integer>(major));
versionObj->Set(Nan::New<String>("minor").ToLocalChecked(), Nan::New<Integer>(minor));
versionObj->Set(Nan::New<String>("patch").ToLocalChecked(), Nan::New<Integer>(patch));
exports->Set(Nan::New<String>("version").ToLocalChecked(), versionObj);
}
void setFlagFromValue(int *flags, int flag, const char *name, bool defaultValue, Local<Object> options) {
Handle<Value> opt = options->Get(Nan::New<String>(name).ToLocalChecked());
if (opt->IsBoolean() ? opt->BooleanValue() : defaultValue) {
*flags |= flag;
}
}
argtokey_callback_t argToKey(const Handle<Value> &val, MDB_val &key, bool keyIsUint32) {
// Check key type
if (keyIsUint32 && !val->IsUint32()) {
Nan::ThrowError("Invalid key. keyIsUint32 specified on the database, but the given key was not an unsigned 32-bit integer");
return nullptr;
}
if (!keyIsUint32 && !val->IsString()) {
Nan::ThrowError("Invalid key. String key expected, because keyIsUint32 isn't specified on the database.");
return nullptr;
}
// Handle uint32_t key
if (keyIsUint32) {
uint32_t *v = new uint32_t;
*v = val->Uint32Value();
key.mv_size = sizeof(uint32_t);
key.mv_data = v;
return ([](MDB_val &key) -> void {
delete (uint32_t*)key.mv_data;
});
}
// Handle string key
CustomExternalStringResource::writeTo(val->ToString(), &key);
return ([](MDB_val &key) -> void {
delete[] (uint16_t*)key.mv_data;
});
return nullptr;
}
Handle<Value> keyToHandle(MDB_val &key, bool keyIsUint32) {
if (keyIsUint32) {
return Nan::New<Integer>(*((uint32_t*)key.mv_data));
}
else {
return valToString(key);
}
}
Handle<Value> valToString(MDB_val &data) {
auto resource = new CustomExternalStringResource(&data);
auto str = String::NewExternalTwoByte(Isolate::GetCurrent(), resource);
return str.ToLocalChecked();
}
Handle<Value> valToBinary(MDB_val &data) {
// FIXME: It'd be better not to copy buffers, but I'm not sure
// about the ownership semantics of MDB_val, so let' be safe.
return Nan::CopyBuffer(
(char*)data.mv_data,
data.mv_size
).ToLocalChecked();
}
Handle<Value> valToNumber(MDB_val &data) {
return Nan::New<Number>(*((double*)data.mv_data));
}
Handle<Value> valToBoolean(MDB_val &data) {
return Nan::New<Boolean>(*((bool*)data.mv_data));
}
void consoleLog(const char *msg) {
Local<String> str = Nan::New("console.log('").ToLocalChecked();
str = String::Concat(str, Nan::New<String>(msg).ToLocalChecked());
str = String::Concat(str, Nan::New("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLog(Handle<Value> val) {
Local<String> str = Nan::New<String>("console.log('").ToLocalChecked();
str = String::Concat(str, val->ToString());
str = String::Concat(str, Nan::New<String>("');").ToLocalChecked());
Local<Script> script = Nan::CompileScript(str).ToLocalChecked();
Nan::RunScript(script);
}
void consoleLogN(int n) {
char c[20];
memset(c, 0, 20 * sizeof(char));
sprintf(c, "%d", n);
consoleLog(c);
}
void CustomExternalStringResource::writeTo(Handle<String> str, MDB_val *val) {
unsigned int l = str->Length() + 1;
uint16_t *d = new uint16_t[l];
str->Write(d);
d[l - 1] = 0;
val->mv_data = d;
val->mv_size = l * sizeof(uint16_t);
}
CustomExternalStringResource::CustomExternalStringResource(MDB_val *val) {
// The UTF-16 data
this->d = (uint16_t*)(val->mv_data);
// Number of UTF-16 characters in the string
this->l = (val->mv_size / sizeof(uint16_t) - 1);
}
CustomExternalStringResource::~CustomExternalStringResource() { }
void CustomExternalStringResource::Dispose() {
// No need to do anything, the data is owned by LMDB, not us
}
const uint16_t *CustomExternalStringResource::data() const {
return this->d;
}
size_t CustomExternalStringResource::length() const {
return this->l;
}
<|endoftext|> |
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_FUNCTIONS_EVAL_IF_HPP
#define BOOST_BRIGAND_FUNCTIONS_EVAL_IF_HPP
#include <type_traits>
namespace brigand
{
template <typename Condition, typename A, typename B>
struct eval_if
{
using type = typename std::conditional<Condition::value, A, B>::type::type;
};
template <bool Condition, typename A, typename B>
struct eval_if_c
{
using type = typename std::conditional<Condition, A, B>::type::type;
};
}
#endif
<commit_msg>Delete eval_if.hpp<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string>
#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"
namespace webrtc {
namespace {
const int16_t kLimiterHeadroom = 29204; // == -1 dbFS
const int16_t kInt16Max = 0x7fff;
const int kSampleRateHz = 16000;
const int kTestDurationMs = 4000;
} // namespace
class MixingTest : public AfterInitializationFixture {
protected:
MixingTest()
: input_filename_(test::OutputPath() + "mixing_test_input.pcm"),
output_filename_(test::OutputPath() + "mixing_test_output.pcm") {
}
// Creates and mixes |num_remote_streams| which play a file "as microphone"
// with |num_local_streams| which play a file "locally", using a constant
// amplitude of |input_value|. The local streams manifest as "anonymous"
// mixing participants, meaning they will be mixed regardless of the number
// of participants. (A stream is a VoiceEngine "channel").
//
// The mixed output is verified to always fall between |max_output_value| and
// |min_output_value|, after a startup phase.
//
// |num_remote_streams_using_mono| of the remote streams use mono, with the
// remainder using stereo.
void RunMixingTest(int num_remote_streams,
int num_local_streams,
int num_remote_streams_using_mono,
int16_t input_value,
int16_t max_output_value,
int16_t min_output_value) {
ASSERT_LE(num_remote_streams_using_mono, num_remote_streams);
GenerateInputFile(input_value);
std::vector<int> local_streams(num_local_streams);
for (size_t i = 0; i < local_streams.size(); ++i) {
local_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, local_streams[i]);
}
StartLocalStreams(local_streams);
TEST_LOG("Playing %d local streams.\n", num_local_streams);
std::vector<int> remote_streams(num_remote_streams);
for (size_t i = 0; i < remote_streams.size(); ++i) {
remote_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, remote_streams[i]);
}
StartRemoteStreams(remote_streams, num_remote_streams_using_mono);
TEST_LOG("Playing %d remote streams.\n", num_remote_streams);
// Start recording the mixed output and wait.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */,
output_filename_.c_str()));
Sleep(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
StopLocalStreams(local_streams);
StopRemoteStreams(remote_streams);
VerifyMixedOutput(max_output_value, min_output_value);
// Cleanup the files in case another test uses different lengths.
ASSERT_EQ(0, remove(input_filename_.c_str()));
ASSERT_EQ(0, remove(output_filename_.c_str()));
}
private:
// Generate input file with constant values equal to |input_value|. The file
// will be one second longer than the duration of the test.
void GenerateInputFile(int16_t input_value) {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) {
// Verify the mixed output.
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
// Skip the first 100 ms to avoid initialization and ramping-in effects.
EXPECT_EQ(0, fseek(output_file, sizeof(output_value) * kSampleRateHz / 10,
SEEK_SET));
int samples_read = 0;
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
EXPECT_LE(output_value, max_output_value);
EXPECT_GE(output_value, min_output_value);
}
// Ensure the recording length is close to the duration of the test.
ASSERT_GE((samples_read * 1000.0f) / kSampleRateHz,
0.9f * kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
// Start up local streams ("anonymous" participants).
void StartLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StartPlayout(streams[i]));
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i],
input_filename_.c_str(), true));
}
}
void StopLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
// Start up remote streams ("normal" participants).
void StartRemoteStreams(const std::vector<int>& streams,
int num_remote_streams_using_mono) {
// Use L16 at 16kHz to minimize distortion (file recording is 16kHz and
// resampling will cause distortion).
CodecInst codec_inst;
strcpy(codec_inst.plname, "L16");
codec_inst.channels = 1;
codec_inst.plfreq = kSampleRateHz;
codec_inst.pltype = 105;
codec_inst.pacsize = codec_inst.plfreq / 100;
codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8; // 8 bits/byte.
for (int i = 0; i < num_remote_streams_using_mono; ++i) {
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
// The remainder of the streams will use stereo.
codec_inst.channels = 2;
codec_inst.pltype++;
for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) {
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
}
// Start up a single remote stream.
void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) {
EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst));
EXPECT_EQ(0, voe_base_->SetLocalReceiver(stream, port));
EXPECT_EQ(0, voe_base_->SetSendDestination(stream, port, "127.0.0.1"));
EXPECT_EQ(0, voe_base_->StartReceive(stream));
EXPECT_EQ(0, voe_base_->StartPlayout(stream));
EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst));
EXPECT_EQ(0, voe_base_->StartSend(stream));
EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream,
input_filename_.c_str(), true));
}
void StopRemoteStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopSend(streams[i]));
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->StopReceive(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
const std::string input_filename_;
const std::string output_filename_;
};
// These tests assume a maximum of three mixed participants. We typically allow
// a +/- 10% range around the expected output level to account for distortion
// from coding and processing in the loopback chain.
TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 3;
RunMixingTest(4, 0, 4, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
// Ensure the mixing saturation protection is working. We can do this because
// the mixing limiter is given some headroom, so the expected output is less
// than full scale.
TEST_F(MixingTest, VerifySaturationProtection) {
const int16_t kInputValue = 20000;
const int16_t kExpectedOutput = kLimiterHeadroom;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(kInputValue * 3, kInt16Max);
ASSERT_LT(1.1 * kExpectedOutput, kInt16Max);
RunMixingTest(3, 0, 3, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) {
const int16_t kInputValue = kInt16Max;
const int16_t kExpectedOutput = kInt16Max;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom);
// Tighter constraints are required here to properly test this.
RunMixingTest(1, 0, 1, kInputValue, kExpectedOutput,
0.95 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(1, 1, 1, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 4;
RunMixingTest(3, 1, 3, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyStereoAndMonoMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(2, 0, 1, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
} // namespace webrtc
<commit_msg>Avoid flakiness by skipping more output verification.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string>
#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"
namespace webrtc {
namespace {
const int16_t kLimiterHeadroom = 29204; // == -1 dbFS
const int16_t kInt16Max = 0x7fff;
const int kSampleRateHz = 16000;
const int kTestDurationMs = 3000;
const int kSkipOutputMs = 500;
} // namespace
class MixingTest : public AfterInitializationFixture {
protected:
MixingTest()
: input_filename_(test::OutputPath() + "mixing_test_input.pcm"),
output_filename_(test::OutputPath() + "mixing_test_output.pcm") {
}
// Creates and mixes |num_remote_streams| which play a file "as microphone"
// with |num_local_streams| which play a file "locally", using a constant
// amplitude of |input_value|. The local streams manifest as "anonymous"
// mixing participants, meaning they will be mixed regardless of the number
// of participants. (A stream is a VoiceEngine "channel").
//
// The mixed output is verified to always fall between |max_output_value| and
// |min_output_value|, after a startup phase.
//
// |num_remote_streams_using_mono| of the remote streams use mono, with the
// remainder using stereo.
void RunMixingTest(int num_remote_streams,
int num_local_streams,
int num_remote_streams_using_mono,
int16_t input_value,
int16_t max_output_value,
int16_t min_output_value) {
ASSERT_LE(num_remote_streams_using_mono, num_remote_streams);
GenerateInputFile(input_value);
std::vector<int> local_streams(num_local_streams);
for (size_t i = 0; i < local_streams.size(); ++i) {
local_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, local_streams[i]);
}
StartLocalStreams(local_streams);
TEST_LOG("Playing %d local streams.\n", num_local_streams);
std::vector<int> remote_streams(num_remote_streams);
for (size_t i = 0; i < remote_streams.size(); ++i) {
remote_streams[i] = voe_base_->CreateChannel();
EXPECT_NE(-1, remote_streams[i]);
}
StartRemoteStreams(remote_streams, num_remote_streams_using_mono);
TEST_LOG("Playing %d remote streams.\n", num_remote_streams);
// Start recording the mixed output and wait.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */,
output_filename_.c_str()));
Sleep(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
StopLocalStreams(local_streams);
StopRemoteStreams(remote_streams);
VerifyMixedOutput(max_output_value, min_output_value);
// Cleanup the files in case another test uses different lengths.
ASSERT_EQ(0, remove(input_filename_.c_str()));
ASSERT_EQ(0, remove(output_filename_.c_str()));
}
private:
// Generate input file with constant values equal to |input_value|. The file
// will be one second longer than the duration of the test.
void GenerateInputFile(int16_t input_value) {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) {
// Verify the mixed output.
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
// Skip the first segment to avoid initialization and ramping-in effects.
EXPECT_EQ(0, fseek(output_file, sizeof(output_value) *
kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET));
int samples_read = 0;
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
std::ostringstream trace_stream;
trace_stream << samples_read << " samples read";
SCOPED_TRACE(trace_stream.str());
EXPECT_LE(output_value, max_output_value);
EXPECT_GE(output_value, min_output_value);
}
// Ensure the recording length is close to the duration of the test.
ASSERT_GE((samples_read * 1000.0f) / kSampleRateHz,
kTestDurationMs - kSkipOutputMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
// Start up local streams ("anonymous" participants).
void StartLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StartPlayout(streams[i]));
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i],
input_filename_.c_str(), true));
}
}
void StopLocalStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
// Start up remote streams ("normal" participants).
void StartRemoteStreams(const std::vector<int>& streams,
int num_remote_streams_using_mono) {
// Use L16 at 16kHz to minimize distortion (file recording is 16kHz and
// resampling will cause distortion).
CodecInst codec_inst;
strcpy(codec_inst.plname, "L16");
codec_inst.channels = 1;
codec_inst.plfreq = kSampleRateHz;
codec_inst.pltype = 105;
codec_inst.pacsize = codec_inst.plfreq / 100;
codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8; // 8 bits/byte.
for (int i = 0; i < num_remote_streams_using_mono; ++i) {
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
// The remainder of the streams will use stereo.
codec_inst.channels = 2;
codec_inst.pltype++;
for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) {
StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
}
}
// Start up a single remote stream.
void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) {
EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst));
EXPECT_EQ(0, voe_base_->SetLocalReceiver(stream, port));
EXPECT_EQ(0, voe_base_->SetSendDestination(stream, port, "127.0.0.1"));
EXPECT_EQ(0, voe_base_->StartReceive(stream));
EXPECT_EQ(0, voe_base_->StartPlayout(stream));
EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst));
EXPECT_EQ(0, voe_base_->StartSend(stream));
EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream,
input_filename_.c_str(), true));
}
void StopRemoteStreams(const std::vector<int>& streams) {
for (size_t i = 0; i < streams.size(); ++i) {
EXPECT_EQ(0, voe_base_->StopSend(streams[i]));
EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
EXPECT_EQ(0, voe_base_->StopReceive(streams[i]));
EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
}
}
const std::string input_filename_;
const std::string output_filename_;
};
// These tests assume a maximum of three mixed participants. We typically allow
// a +/- 10% range around the expected output level to account for distortion
// from coding and processing in the loopback chain.
TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 3;
RunMixingTest(4, 0, 4, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
// Ensure the mixing saturation protection is working. We can do this because
// the mixing limiter is given some headroom, so the expected output is less
// than full scale.
TEST_F(MixingTest, VerifySaturationProtection) {
const int16_t kInputValue = 20000;
const int16_t kExpectedOutput = kLimiterHeadroom;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(kInputValue * 3, kInt16Max);
ASSERT_LT(1.1 * kExpectedOutput, kInt16Max);
RunMixingTest(3, 0, 3, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) {
const int16_t kInputValue = kInt16Max;
const int16_t kExpectedOutput = kInt16Max;
// If this isn't satisfied, we're not testing anything.
ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom);
// Tighter constraints are required here to properly test this.
RunMixingTest(1, 0, 1, kInputValue, kExpectedOutput,
0.95 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(1, 1, 1, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 4;
RunMixingTest(3, 1, 3, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
TEST_F(MixingTest, VerifyStereoAndMonoMixing) {
const int16_t kInputValue = 1000;
const int16_t kExpectedOutput = kInputValue * 2;
RunMixingTest(2, 0, 1, kInputValue, 1.1 * kExpectedOutput,
0.9 * kExpectedOutput);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002 - present, H. Hernan Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holders 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 COPYRIGHT HOLDER 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 "VulkanSystem.hpp"
#include "Foundation/Containers/Array.hpp"
#include "Rendering/Programs/SkyboxShaderProgram.hpp"
#include "Rendering/Programs/UnlitShaderProgram.hpp"
#include "Rendering/ShaderProgram.hpp"
#include "Rendering/VulkanCommandBuffer.hpp"
#include "Rendering/VulkanCommandPool.hpp"
#include "Rendering/VulkanFence.hpp"
#include "Rendering/VulkanRenderDevice.hpp"
#include "Rendering/VulkanSwapchain.hpp"
#include "SceneGraph/Camera.hpp"
#include "Simulation/AssetManager.hpp"
#include "Simulation/FileSystem.hpp"
#include "Simulation/Simulation.hpp"
#include "Simulation/Systems/RenderSystem.hpp"
using namespace crimild;
using namespace crimild::vulkan;
void VulkanSystem::start( void ) noexcept
{
initShaders();
createInstance()
&& createDebugMessenger()
&& createSurface()
&& createPhysicalDevice()
&& createRenderDevice()
&& createCommandPool()
&& recreateSwapchain();
}
/*
1. Acquire an image from the swapchain
2. Execute command buffer with that image as attachment in the framebuffer
3. Return the image to the swapchain for presentation
*/
void VulkanSystem::onRender( void ) noexcept
{
auto renderDevice = crimild::get_ptr( m_renderDevice );
if ( renderDevice == nullptr ) {
CRIMILD_LOG_ERROR( "No valid render device instance" );
return;
}
// auto graphicsCommandBuffers = m_frameGraph->recordGraphicsCommands( m_currentFrame, m_recordWithNonConditionalPasses );
// auto computeCommandBuffers = m_frameGraph->recordComputeCommands( m_currentFrame, m_recordWithNonConditionalPasses );
auto renderSystem = RenderSystem::getInstance();
auto &graphicsCommandBuffers = renderSystem->getGraphicsCommands( m_currentFrame, m_recordWithNonConditionalPasses );
auto &computeCommandBuffers = renderSystem->getComputeCommands( m_currentFrame, m_recordWithNonConditionalPasses );
auto swapchain = crimild::get_ptr( m_swapchain );
auto wait = crimild::get_ptr( m_imageAvailableSemaphores[ m_currentFrame ] );
auto signal = crimild::get_ptr( m_renderFinishedSemaphores[ m_currentFrame ] );
auto fence = crimild::get_ptr( m_inFlightFences[ m_currentFrame ] );
// Wait for any pending operations to complete
fence->wait();
fence->reset();
// Acquire the next image available image from the swapchain
// Execution of command buffers is asynchrounous. It must be set up to
// wait on image adquisition to finish
auto result = swapchain->acquireNextImage( wait );
if ( !result.success ) {
if ( result.outOfDate ) {
// No image is available since environemnt has changed
// Maybe window was resized.
// Recreate swapchain and related objects
cleanSwapchain();
recreateSwapchain();
return;
} else {
CRIMILD_LOG_ERROR( "No image available" );
exit( -1 );
}
}
auto imageIndex = result.imageIndex;
// TODO: This migth be a bit slow...
updateVertexBuffers();
updateIndexBuffers();
updateUniformBuffers();
// Submit graphic commands to the render device, with the selected
// image as attachment in the framebuffer
renderDevice->submitGraphicsCommands(
wait,
graphicsCommandBuffers,
imageIndex,
signal,
fence );
// Return the image to the swapchain so it can be presented
auto presentationResult = swapchain->presentImage( imageIndex, signal );
if ( !presentationResult.success ) {
if ( presentationResult.outOfDate ) {
cleanSwapchain();
recreateSwapchain();
return;
} else {
CRIMILD_LOG_ERROR( "Failed to present image" );
exit( -1 );
}
}
computeCommandBuffers.each(
[ & ]( auto commandBuffer ) {
renderDevice->submitComputeCommands( crimild::get_ptr( commandBuffer ) );
renderDevice->waitIdle();
} );
m_currentFrame = ( m_currentFrame + 1 ) % swapchain->getImages().size();
if ( m_recordWithNonConditionalPasses && m_currentFrame == 0 ) {
// We have been rendering using command buffers that included conditional render passes
// We need to record all commands again now, without the conditional passes.
// If m_currentFrame == 0, that means we have rendered all in-flight frames already
m_recordWithNonConditionalPasses = false;
}
}
void VulkanSystem::stop( void ) noexcept
{
System::stop();
cleanSwapchain();
m_commandPool = nullptr;
m_renderDevice = nullptr;
m_physicalDevice = nullptr;
m_debugMessenger = nullptr;
m_surface = nullptr;
m_instance = nullptr;
RenderDeviceManager::cleanup();
PhysicalDeviceManager::cleanup();
VulkanDebugMessengerManager::cleanup();
VulkanSurfaceManager::cleanup();
VulkanInstanceManager::cleanup();
}
crimild::Bool VulkanSystem::createInstance( void ) noexcept
{
auto settings = Simulation::getInstance()->getSettings();
auto appName = settings->get< std::string >( Settings::SETTINGS_APP_NAME, "Crimild" );
auto appVersionMajor = settings->get< crimild::UInt32 >( Settings::SETTINGS_APP_VERSION_MAJOR, 1 );
auto appVersionMinor = settings->get< crimild::UInt32 >( Settings::SETTINGS_APP_VERSION_MINOR, 0 );
auto appVersionPatch = settings->get< crimild::UInt32 >( Settings::SETTINGS_APP_VERSION_PATCH, 0 );
m_instance = create(
VulkanInstance::Descriptor {
.appName = appName,
.appVersionMajor = appVersionMajor,
.appVersionMinor = appVersionMinor,
.appVersionPatch = appVersionPatch } );
return m_instance != nullptr;
}
crimild::Bool VulkanSystem::createDebugMessenger( void ) noexcept
{
m_debugMessenger = create(
VulkanDebugMessenger::Descriptor {
.instance = crimild::get_ptr( m_instance ) } );
return m_debugMessenger != nullptr;
}
crimild::Bool VulkanSystem::createSurface( void ) noexcept
{
m_surface = create(
VulkanSurface::Descriptor {
.instance = crimild::get_ptr( m_instance ) } );
if ( m_surface == nullptr ) {
return false;
}
attach( crimild::get_ptr( m_surface ) );
return true;
}
crimild::Bool VulkanSystem::createPhysicalDevice( void ) noexcept
{
m_physicalDevice = create(
PhysicalDevice::Descriptor {
.instance = crimild::get_ptr( m_instance ),
.surface = crimild::get_ptr( m_surface ) } );
return m_physicalDevice != nullptr;
}
crimild::Bool VulkanSystem::createRenderDevice( void ) noexcept
{
m_renderDevice = m_physicalDevice->create( RenderDevice::Descriptor {} );
return m_renderDevice != nullptr;
}
crimild::Bool VulkanSystem::createSwapchain( void ) noexcept
{
auto settings = Simulation::getInstance()->getSettings();
auto width = settings->get< crimild::UInt >( "video.width", 0 );
auto height = settings->get< crimild::UInt >( "video.height", 0 );
m_swapchain = m_renderDevice->create(
Swapchain::Descriptor {
.extent = Vector2ui { width, height } } );
if ( m_swapchain == nullptr ) {
return false;
}
settings->set( "video.width", m_swapchain->extent.width );
settings->set( "video.height", m_swapchain->extent.height );
if ( auto mainCamera = Camera::getMainCamera() ) {
mainCamera->setAspectRatio( ( crimild::Real32 ) m_swapchain->extent.width / ( crimild::Real32 ) m_swapchain->extent.height );
}
// Reset existing command buffers
m_recordWithNonConditionalPasses = true;
return true;
}
void VulkanSystem::cleanSwapchain( void ) noexcept
{
if ( auto renderDevice = crimild::get_ptr( m_renderDevice ) ) {
CRIMILD_LOG_TRACE( "Waiting for pending operations" );
m_renderDevice->waitIdle();
static_cast< DescriptorSetManager * >( renderDevice )->clear();
static_cast< DescriptorSetLayoutManager * >( renderDevice )->clear();
static_cast< DescriptorPoolManager * >( renderDevice )->clear();
static_cast< UniformBufferManager * >( renderDevice )->clear();
static_cast< CommandBufferManager * >( renderDevice )->clear();
static_cast< GraphicsPipelineManager * >( renderDevice )->clear();
static_cast< ComputePipelineManager * >( renderDevice )->clear();
static_cast< RenderPassManager * >( renderDevice )->clear();
static_cast< ImageViewManager * >( renderDevice )->clear();
static_cast< ImageManager * >( renderDevice )->clear();
renderDevice->reset( crimild::get_ptr( m_commandPool ) );
}
m_inFlightFences.clear();
m_imageAvailableSemaphores.clear();
m_renderFinishedSemaphores.clear();
m_swapchain = nullptr;
m_currentFrame = 0;
}
crimild::Bool VulkanSystem::recreateSwapchain( void ) noexcept
{
cleanSwapchain();
return createSwapchain()
&& createSyncObjects();
}
crimild::Bool VulkanSystem::createSyncObjects( void ) noexcept
{
auto renderDevice = crimild::get_ptr( m_renderDevice );
for ( auto i = 0l; i < m_swapchain->getImages().size(); i++ ) {
m_imageAvailableSemaphores.push_back( renderDevice->create( Semaphore::Descriptor {} ) );
m_renderFinishedSemaphores.push_back( renderDevice->create( Semaphore::Descriptor {} ) );
m_inFlightFences.push_back( renderDevice->create( Fence::Descriptor {} ) );
}
return true;
}
crimild::Bool VulkanSystem::createCommandPool( void ) noexcept
{
auto renderDevice = crimild::get_ptr( m_renderDevice );
auto queueFamilyIndices = utils::findQueueFamilies( m_physicalDevice->handler, m_surface->handler );
m_commandPool = renderDevice->create(
CommandPool::Descriptor {
.queueFamilyIndex = queueFamilyIndices.graphicsFamily[ 0 ],
} );
return m_commandPool != nullptr;
}
void VulkanSystem::updateVertexBuffers( void ) noexcept
{
getRenderDevice()->updateVertexBuffers();
}
void VulkanSystem::updateIndexBuffers( void ) noexcept
{
getRenderDevice()->updateIndexBuffers();
}
void VulkanSystem::updateUniformBuffers( void ) noexcept
{
getRenderDevice()->updateUniformBuffers( 0 );
}
void VulkanSystem::initShaders( void ) noexcept
{
auto createShader = []( Shader::Stage stage, const unsigned char *rawData, crimild::Size size ) {
std::vector< char > data( size + ( size % 4 ) );
memcpy( &data[ 0 ], rawData, size );
return crimild::alloc< Shader >( stage, data );
};
auto assets = AssetManager::getInstance();
assets->get< UnlitShaderProgram >()->setShaders(
{
[ & ] {
#include "Rendering/Shaders/unlit/unlit.vert.inl"
return createShader( Shader::Stage::VERTEX, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
[ & ] {
#include "Rendering/Shaders/unlit/unlit.frag.inl"
return createShader( Shader::Stage::FRAGMENT, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
} );
assets->get< SkyboxShaderProgram >()->setShaders(
{
[ & ] {
#include "Rendering/Shaders/unlit/skybox.vert.inl"
return createShader( Shader::Stage::VERTEX, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
[ & ] {
#include "Rendering/Shaders/unlit/skybox.frag.inl"
return createShader( Shader::Stage::FRAGMENT, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
} );
}
<commit_msg>Fix Vulkan issue in Release builds<commit_after>/*
* Copyright (c) 2002 - present, H. Hernan Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holders 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 COPYRIGHT HOLDER 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 "VulkanSystem.hpp"
#include "Foundation/Containers/Array.hpp"
#include "Rendering/Programs/SkyboxShaderProgram.hpp"
#include "Rendering/Programs/UnlitShaderProgram.hpp"
#include "Rendering/ShaderProgram.hpp"
#include "Rendering/VulkanCommandBuffer.hpp"
#include "Rendering/VulkanCommandPool.hpp"
#include "Rendering/VulkanFence.hpp"
#include "Rendering/VulkanRenderDevice.hpp"
#include "Rendering/VulkanSwapchain.hpp"
#include "SceneGraph/Camera.hpp"
#include "Simulation/AssetManager.hpp"
#include "Simulation/FileSystem.hpp"
#include "Simulation/Simulation.hpp"
#include "Simulation/Systems/RenderSystem.hpp"
using namespace crimild;
using namespace crimild::vulkan;
void VulkanSystem::start( void ) noexcept
{
initShaders();
createInstance()
&& createDebugMessenger()
&& createSurface()
&& createPhysicalDevice()
&& createRenderDevice()
&& createCommandPool()
&& recreateSwapchain();
}
/*
1. Acquire an image from the swapchain
2. Execute command buffer with that image as attachment in the framebuffer
3. Return the image to the swapchain for presentation
*/
void VulkanSystem::onRender( void ) noexcept
{
auto renderDevice = crimild::get_ptr( m_renderDevice );
if ( renderDevice == nullptr ) {
CRIMILD_LOG_ERROR( "No valid render device instance" );
return;
}
// auto graphicsCommandBuffers = m_frameGraph->recordGraphicsCommands( m_currentFrame, m_recordWithNonConditionalPasses );
// auto computeCommandBuffers = m_frameGraph->recordComputeCommands( m_currentFrame, m_recordWithNonConditionalPasses );
auto renderSystem = RenderSystem::getInstance();
auto &graphicsCommandBuffers = renderSystem->getGraphicsCommands( m_currentFrame, m_recordWithNonConditionalPasses );
auto &computeCommandBuffers = renderSystem->getComputeCommands( m_currentFrame, m_recordWithNonConditionalPasses );
auto swapchain = crimild::get_ptr( m_swapchain );
auto wait = crimild::get_ptr( m_imageAvailableSemaphores[ m_currentFrame ] );
auto signal = crimild::get_ptr( m_renderFinishedSemaphores[ m_currentFrame ] );
auto fence = crimild::get_ptr( m_inFlightFences[ m_currentFrame ] );
// Wait for any pending operations to complete
fence->wait();
fence->reset();
// Acquire the next image available image from the swapchain
// Execution of command buffers is asynchrounous. It must be set up to
// wait on image adquisition to finish
auto result = swapchain->acquireNextImage( wait );
if ( !result.success ) {
if ( result.outOfDate ) {
// No image is available since environemnt has changed
// Maybe window was resized.
// Recreate swapchain and related objects
cleanSwapchain();
recreateSwapchain();
return;
} else {
CRIMILD_LOG_ERROR( "No image available" );
exit( -1 );
}
}
auto imageIndex = result.imageIndex;
// TODO: This migth be a bit slow...
updateVertexBuffers();
updateIndexBuffers();
updateUniformBuffers();
// Submit graphic commands to the render device, with the selected
// image as attachment in the framebuffer
renderDevice->submitGraphicsCommands(
wait,
graphicsCommandBuffers,
imageIndex,
signal,
fence );
// Return the image to the swapchain so it can be presented
auto presentationResult = swapchain->presentImage( imageIndex, signal );
if ( !presentationResult.success ) {
if ( presentationResult.outOfDate ) {
cleanSwapchain();
recreateSwapchain();
return;
} else {
CRIMILD_LOG_ERROR( "Failed to present image" );
exit( -1 );
}
}
computeCommandBuffers.each(
[ & ]( auto commandBuffer ) {
renderDevice->submitComputeCommands( crimild::get_ptr( commandBuffer ) );
renderDevice->waitIdle();
} );
m_currentFrame = ( m_currentFrame + 1 ) % swapchain->getImages().size();
if ( m_recordWithNonConditionalPasses && m_currentFrame == 0 ) {
// We have been rendering using command buffers that included conditional render passes
// We need to record all commands again now, without the conditional passes.
// If m_currentFrame == 0, that means we have rendered all in-flight frames already
m_recordWithNonConditionalPasses = false;
}
}
void VulkanSystem::stop( void ) noexcept
{
System::stop();
cleanSwapchain();
m_commandPool = nullptr;
m_renderDevice = nullptr;
m_physicalDevice = nullptr;
m_debugMessenger = nullptr;
m_surface = nullptr;
m_instance = nullptr;
RenderDeviceManager::cleanup();
PhysicalDeviceManager::cleanup();
VulkanDebugMessengerManager::cleanup();
VulkanSurfaceManager::cleanup();
VulkanInstanceManager::cleanup();
}
crimild::Bool VulkanSystem::createInstance( void ) noexcept
{
auto settings = Simulation::getInstance()->getSettings();
auto appName = settings->get< std::string >( Settings::SETTINGS_APP_NAME, "Crimild" );
auto appVersionMajor = settings->get< crimild::UInt32 >( Settings::SETTINGS_APP_VERSION_MAJOR, 1 );
auto appVersionMinor = settings->get< crimild::UInt32 >( Settings::SETTINGS_APP_VERSION_MINOR, 0 );
auto appVersionPatch = settings->get< crimild::UInt32 >( Settings::SETTINGS_APP_VERSION_PATCH, 0 );
m_instance = create(
VulkanInstance::Descriptor {
.appName = appName,
.appVersionMajor = appVersionMajor,
.appVersionMinor = appVersionMinor,
.appVersionPatch = appVersionPatch } );
return m_instance != nullptr;
}
crimild::Bool VulkanSystem::createDebugMessenger( void ) noexcept
{
m_debugMessenger = create(
VulkanDebugMessenger::Descriptor {
.instance = crimild::get_ptr( m_instance ) } );
// Never fails (Debug messenger is disabled for Release builds)
return true;
}
crimild::Bool VulkanSystem::createSurface( void ) noexcept
{
CRIMILD_LOG_TRACE( "Creating Vulkan surface" );
m_surface = create(
VulkanSurface::Descriptor {
.instance = crimild::get_ptr( m_instance ) } );
if ( m_surface == nullptr ) {
CRIMILD_LOG_ERROR( "Failed to create Vulkan surface" );
return false;
}
attach( crimild::get_ptr( m_surface ) );
CRIMILD_LOG_ERROR( "Vulkan Surface created" );
return true;
}
crimild::Bool VulkanSystem::createPhysicalDevice( void ) noexcept
{
m_physicalDevice = create(
PhysicalDevice::Descriptor {
.instance = crimild::get_ptr( m_instance ),
.surface = crimild::get_ptr( m_surface ) } );
return m_physicalDevice != nullptr;
}
crimild::Bool VulkanSystem::createRenderDevice( void ) noexcept
{
m_renderDevice = m_physicalDevice->create( RenderDevice::Descriptor {} );
return m_renderDevice != nullptr;
}
crimild::Bool VulkanSystem::createSwapchain( void ) noexcept
{
auto settings = Simulation::getInstance()->getSettings();
auto width = settings->get< crimild::UInt >( "video.width", 0 );
auto height = settings->get< crimild::UInt >( "video.height", 0 );
m_swapchain = m_renderDevice->create(
Swapchain::Descriptor {
.extent = Vector2ui { width, height } } );
if ( m_swapchain == nullptr ) {
return false;
}
settings->set( "video.width", m_swapchain->extent.width );
settings->set( "video.height", m_swapchain->extent.height );
if ( auto mainCamera = Camera::getMainCamera() ) {
mainCamera->setAspectRatio( ( crimild::Real32 ) m_swapchain->extent.width / ( crimild::Real32 ) m_swapchain->extent.height );
}
// Reset existing command buffers
m_recordWithNonConditionalPasses = true;
return true;
}
void VulkanSystem::cleanSwapchain( void ) noexcept
{
if ( auto renderDevice = crimild::get_ptr( m_renderDevice ) ) {
CRIMILD_LOG_TRACE( "Waiting for pending operations" );
m_renderDevice->waitIdle();
static_cast< DescriptorSetManager * >( renderDevice )->clear();
static_cast< DescriptorSetLayoutManager * >( renderDevice )->clear();
static_cast< DescriptorPoolManager * >( renderDevice )->clear();
static_cast< UniformBufferManager * >( renderDevice )->clear();
static_cast< CommandBufferManager * >( renderDevice )->clear();
static_cast< GraphicsPipelineManager * >( renderDevice )->clear();
static_cast< ComputePipelineManager * >( renderDevice )->clear();
static_cast< RenderPassManager * >( renderDevice )->clear();
static_cast< ImageViewManager * >( renderDevice )->clear();
static_cast< ImageManager * >( renderDevice )->clear();
renderDevice->reset( crimild::get_ptr( m_commandPool ) );
}
m_inFlightFences.clear();
m_imageAvailableSemaphores.clear();
m_renderFinishedSemaphores.clear();
m_swapchain = nullptr;
m_currentFrame = 0;
}
crimild::Bool VulkanSystem::recreateSwapchain( void ) noexcept
{
cleanSwapchain();
return createSwapchain()
&& createSyncObjects();
}
crimild::Bool VulkanSystem::createSyncObjects( void ) noexcept
{
auto renderDevice = crimild::get_ptr( m_renderDevice );
for ( auto i = 0l; i < m_swapchain->getImages().size(); i++ ) {
m_imageAvailableSemaphores.push_back( renderDevice->create( Semaphore::Descriptor {} ) );
m_renderFinishedSemaphores.push_back( renderDevice->create( Semaphore::Descriptor {} ) );
m_inFlightFences.push_back( renderDevice->create( Fence::Descriptor {} ) );
}
return true;
}
crimild::Bool VulkanSystem::createCommandPool( void ) noexcept
{
auto renderDevice = crimild::get_ptr( m_renderDevice );
auto queueFamilyIndices = utils::findQueueFamilies( m_physicalDevice->handler, m_surface->handler );
m_commandPool = renderDevice->create(
CommandPool::Descriptor {
.queueFamilyIndex = queueFamilyIndices.graphicsFamily[ 0 ],
} );
return m_commandPool != nullptr;
}
void VulkanSystem::updateVertexBuffers( void ) noexcept
{
getRenderDevice()->updateVertexBuffers();
}
void VulkanSystem::updateIndexBuffers( void ) noexcept
{
getRenderDevice()->updateIndexBuffers();
}
void VulkanSystem::updateUniformBuffers( void ) noexcept
{
getRenderDevice()->updateUniformBuffers( 0 );
}
void VulkanSystem::initShaders( void ) noexcept
{
auto createShader = []( Shader::Stage stage, const unsigned char *rawData, crimild::Size size ) {
std::vector< char > data( size + ( size % 4 ) );
memcpy( &data[ 0 ], rawData, size );
return crimild::alloc< Shader >( stage, data );
};
auto assets = AssetManager::getInstance();
assets->get< UnlitShaderProgram >()->setShaders(
{
[ & ] {
#include "Rendering/Shaders/unlit/unlit.vert.inl"
return createShader( Shader::Stage::VERTEX, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
[ & ] {
#include "Rendering/Shaders/unlit/unlit.frag.inl"
return createShader( Shader::Stage::FRAGMENT, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
} );
assets->get< SkyboxShaderProgram >()->setShaders(
{
[ & ] {
#include "Rendering/Shaders/unlit/skybox.vert.inl"
return createShader( Shader::Stage::VERTEX, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
[ & ] {
#include "Rendering/Shaders/unlit/skybox.frag.inl"
return createShader( Shader::Stage::FRAGMENT, RESOURCE_BYTES, sizeof( RESOURCE_BYTES ) );
}(),
} );
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "configuration.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/drt/drtlightingengine.h"
#include "renderer/kernel/lighting/pt/ptlightingengine.h"
#include "renderer/kernel/lighting/sppm/sppmlightingengine.h"
#include "renderer/kernel/rendering/final/uniformpixelrenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
// Standard headers.
#include <cassert>
#include <cstring>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// Configuration class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID Configuration::get_class_uid()
{
return g_class_uid;
}
Configuration::Configuration(const char* name)
: Entity(g_class_uid)
, m_base(0)
{
set_name(name);
}
void Configuration::release()
{
delete this;
}
void Configuration::set_base(const Configuration* base)
{
m_base = base;
}
const Configuration* Configuration::get_base() const
{
return m_base;
}
ParamArray Configuration::get_inherited_parameters() const
{
if (m_base)
{
ParamArray params = m_base->m_params;
params.merge(m_params);
return params;
}
else
{
return m_params;
}
}
Dictionary Configuration::get_metadata()
{
ParamArray metadata;
metadata.insert(
"sampling_mode",
Dictionary()
.insert("type", "enum")
.insert("values", "rng|qmc")
.insert("default", "rng")
.insert("help", "Sampler to use when generating samples")
.insert(
"options",
Dictionary()
.insert("rng", Dictionary().insert("help", "Random sampler"))
.insert("qmc", Dictionary().insert("help", "Quasi Monte Carlo sampler"))));
metadata.insert(
"lighting_engine",
Dictionary()
.insert("type", "enum")
.insert("values", "drt|pt|sppm")
.insert("default", "pt")
.insert("help", "Lighting engine used when rendering")
.insert(
"options",
Dictionary()
.insert("drt", Dictionary().insert("help", "Distribution ray tracing"))
.insert("pt", Dictionary().insert("help", "Unidirectional path tracing"))
.insert("sppm", Dictionary().insert("help", "Stochastic progressive photon mapping"))));
metadata.insert(
"rendering_threads",
Dictionary()
.insert("type", "int")
.insert("help", "Number of threads to use for rendering"));
metadata.dictionaries().insert(
"texture_store",
TextureStore::get_params_metadata());
metadata.dictionaries().insert(
"uniform_pixel_renderer",
UniformPixelRendererFactory::get_params_metadata());
metadata.dictionaries().insert(
"generic_frame_renderer",
GenericFrameRendererFactory::get_params_metadata());
metadata.dictionaries().insert(
"progressive_frame_renderer",
ProgressiveFrameRendererFactory::get_params_metadata());
metadata.dictionaries().insert("drt", DRTLightingEngineFactory::get_params_metadata());
metadata.dictionaries().insert("pt", PTLightingEngineFactory::get_params_metadata());
metadata.dictionaries().insert("sppm", SPPMLightingEngineFactory::get_params_metadata());
return metadata;
}
//
// ConfigurationFactory class implementation.
//
auto_release_ptr<Configuration> ConfigurationFactory::create(const char* name)
{
assert(name);
return auto_release_ptr<Configuration>(new Configuration(name));
}
auto_release_ptr<Configuration> ConfigurationFactory::create(
const char* name,
const ParamArray& params)
{
assert(name);
auto_release_ptr<Configuration> configuration(new Configuration(name));
configuration->get_parameters().merge(params);
return configuration;
}
//
// BaseConfigurationFactory class implementation.
//
auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_final()
{
auto_release_ptr<Configuration> configuration(new Configuration("base_final"));
ParamArray& parameters = configuration->get_parameters();
parameters.insert("frame_renderer", "generic");
parameters.insert("tile_renderer", "generic");
parameters.insert("pixel_renderer", "uniform");
parameters.dictionaries().insert(
"uniform_pixel_renderer",
ParamArray()
.insert("samples", "64"));
parameters.insert("sample_renderer", "generic");
parameters.insert("lighting_engine", "pt");
return configuration;
}
auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_interactive()
{
auto_release_ptr<Configuration> configuration(new Configuration("base_interactive"));
ParamArray& parameters = configuration->get_parameters();
parameters.insert("frame_renderer", "progressive");
parameters.insert("sample_generator", "generic");
parameters.insert("sample_renderer", "generic");
parameters.insert("lighting_engine", "pt");
return configuration;
}
bool BaseConfigurationFactory::is_base_final_configuration(const char* name)
{
assert(name);
return strcmp(name, "base_final") == 0;
}
bool BaseConfigurationFactory::is_base_interactive_configuration(const char* name)
{
assert(name);
return strcmp(name, "base_interactive") == 0;
}
bool BaseConfigurationFactory::is_base_configuration(const char* name)
{
return is_base_final_configuration(name) || is_base_interactive_configuration(name);
}
} // namespace renderer
<commit_msg>set the sampling mode (to RNG) in base final and interactive configurations.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2015 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "configuration.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/drt/drtlightingengine.h"
#include "renderer/kernel/lighting/pt/ptlightingengine.h"
#include "renderer/kernel/lighting/sppm/sppmlightingengine.h"
#include "renderer/kernel/rendering/final/uniformpixelrenderer.h"
#include "renderer/kernel/rendering/generic/genericframerenderer.h"
#include "renderer/kernel/rendering/progressive/progressiveframerenderer.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
// Standard headers.
#include <cassert>
#include <cstring>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// Configuration class implementation.
//
namespace
{
const UniqueID g_class_uid = new_guid();
}
UniqueID Configuration::get_class_uid()
{
return g_class_uid;
}
Configuration::Configuration(const char* name)
: Entity(g_class_uid)
, m_base(0)
{
set_name(name);
}
void Configuration::release()
{
delete this;
}
void Configuration::set_base(const Configuration* base)
{
m_base = base;
}
const Configuration* Configuration::get_base() const
{
return m_base;
}
ParamArray Configuration::get_inherited_parameters() const
{
if (m_base)
{
ParamArray params = m_base->m_params;
params.merge(m_params);
return params;
}
else
{
return m_params;
}
}
Dictionary Configuration::get_metadata()
{
ParamArray metadata;
metadata.insert(
"sampling_mode",
Dictionary()
.insert("type", "enum")
.insert("values", "rng|qmc")
.insert("default", "rng")
.insert("help", "Sampler to use when generating samples")
.insert(
"options",
Dictionary()
.insert("rng", Dictionary().insert("help", "Random sampler"))
.insert("qmc", Dictionary().insert("help", "Quasi Monte Carlo sampler"))));
metadata.insert(
"lighting_engine",
Dictionary()
.insert("type", "enum")
.insert("values", "drt|pt|sppm")
.insert("default", "pt")
.insert("help", "Lighting engine used when rendering")
.insert(
"options",
Dictionary()
.insert("drt", Dictionary().insert("help", "Distribution ray tracing"))
.insert("pt", Dictionary().insert("help", "Unidirectional path tracing"))
.insert("sppm", Dictionary().insert("help", "Stochastic progressive photon mapping"))));
metadata.insert(
"rendering_threads",
Dictionary()
.insert("type", "int")
.insert("help", "Number of threads to use for rendering"));
metadata.dictionaries().insert(
"texture_store",
TextureStore::get_params_metadata());
metadata.dictionaries().insert(
"uniform_pixel_renderer",
UniformPixelRendererFactory::get_params_metadata());
metadata.dictionaries().insert(
"generic_frame_renderer",
GenericFrameRendererFactory::get_params_metadata());
metadata.dictionaries().insert(
"progressive_frame_renderer",
ProgressiveFrameRendererFactory::get_params_metadata());
metadata.dictionaries().insert("drt", DRTLightingEngineFactory::get_params_metadata());
metadata.dictionaries().insert("pt", PTLightingEngineFactory::get_params_metadata());
metadata.dictionaries().insert("sppm", SPPMLightingEngineFactory::get_params_metadata());
return metadata;
}
//
// ConfigurationFactory class implementation.
//
auto_release_ptr<Configuration> ConfigurationFactory::create(const char* name)
{
assert(name);
return auto_release_ptr<Configuration>(new Configuration(name));
}
auto_release_ptr<Configuration> ConfigurationFactory::create(
const char* name,
const ParamArray& params)
{
assert(name);
auto_release_ptr<Configuration> configuration(new Configuration(name));
configuration->get_parameters().merge(params);
return configuration;
}
//
// BaseConfigurationFactory class implementation.
//
auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_final()
{
auto_release_ptr<Configuration> configuration(new Configuration("base_final"));
ParamArray& parameters = configuration->get_parameters();
parameters.insert("sampling_mode", "rng");
parameters.insert("frame_renderer", "generic");
parameters.insert("tile_renderer", "generic");
parameters.insert("pixel_renderer", "uniform");
parameters.dictionaries().insert(
"uniform_pixel_renderer",
ParamArray()
.insert("samples", "64"));
parameters.insert("sample_renderer", "generic");
parameters.insert("lighting_engine", "pt");
return configuration;
}
auto_release_ptr<Configuration> BaseConfigurationFactory::create_base_interactive()
{
auto_release_ptr<Configuration> configuration(new Configuration("base_interactive"));
ParamArray& parameters = configuration->get_parameters();
parameters.insert("sampling_mode", "rng");
parameters.insert("frame_renderer", "progressive");
parameters.insert("sample_generator", "generic");
parameters.insert("sample_renderer", "generic");
parameters.insert("lighting_engine", "pt");
return configuration;
}
bool BaseConfigurationFactory::is_base_final_configuration(const char* name)
{
assert(name);
return strcmp(name, "base_final") == 0;
}
bool BaseConfigurationFactory::is_base_interactive_configuration(const char* name)
{
assert(name);
return strcmp(name, "base_interactive") == 0;
}
bool BaseConfigurationFactory::is_base_configuration(const char* name)
{
return is_base_final_configuration(name) || is_base_interactive_configuration(name);
}
} // namespace renderer
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "frame_dropper.h"
#include "internal_defines.h"
#include "trace.h"
namespace webrtc
{
VCMFrameDropper::VCMFrameDropper(WebRtc_Word32 vcmId)
:
_vcmId(vcmId),
_keyFrameSizeAvgKbits(0.9f),
_keyFrameRatio(0.99f),
_dropRatio(0.9f, 0.96f)
{
Reset();
}
void
VCMFrameDropper::Reset()
{
_keyFrameRatio.Reset(0.99f);
_keyFrameRatio.Apply(1.0f, 1.0f/300.0f); // 1 key frame every 10th second in 30 fps
_keyFrameSizeAvgKbits.Reset(0.9f);
_keyFrameCount = 0;
_accumulator = 0.0f;
_accumulatorMax = 150.0f; // assume 300 kb/s and 0.5 s window
_targetBitRate = 300.0f;
_incoming_frame_rate = 30;
_keyFrameSpreadFrames = 0.5f * _incoming_frame_rate;
_dropNext = false;
_dropRatio.Reset(0.9f);
_dropRatio.Apply(0.0f, 0.0f); // Initialize to 0
_dropCount = 0;
_windowSize = 0.5f;
_wasBelowMax = true;
_enabled = true;
_fastMode = false; // start with normal (non-aggressive) mode
// Cap for the encoder buffer level/accumulator, in secs.
_cap_buffer_size = 3.0f;
// Cap on maximum amount of dropped frames between kept frames, in secs.
_max_time_drops = 4.0f;
}
void
VCMFrameDropper::Enable(bool enable)
{
_enabled = enable;
}
void
VCMFrameDropper::Fill(WebRtc_UWord32 frameSizeBytes, bool deltaFrame)
{
if (!_enabled)
{
return;
}
float frameSizeKbits = 8.0f * static_cast<float>(frameSizeBytes) / 1000.0f;
if (!deltaFrame && !_fastMode) // fast mode does not treat key-frames any different
{
_keyFrameSizeAvgKbits.Apply(1, frameSizeKbits);
_keyFrameRatio.Apply(1.0, 1.0);
if (frameSizeKbits > _keyFrameSizeAvgKbits.Value())
{
// Remove the average key frame size since we
// compensate for key frames when adding delta
// frames.
frameSizeKbits -= _keyFrameSizeAvgKbits.Value();
}
else
{
// Shouldn't be negative, so zero is the lower bound.
frameSizeKbits = 0;
}
if (_keyFrameRatio.Value() > 1e-5 && 1 / _keyFrameRatio.Value() < _keyFrameSpreadFrames)
{
// We are sending key frames more often than our upper bound for
// how much we allow the key frame compensation to be spread
// out in time. Therefor we must use the key frame ratio rather
// than keyFrameSpreadFrames.
_keyFrameCount = static_cast<WebRtc_Word32>(1 / _keyFrameRatio.Value() + 0.5);
}
else
{
// Compensate for the key frame the following frames
_keyFrameCount = static_cast<WebRtc_Word32>(_keyFrameSpreadFrames + 0.5);
}
}
else
{
// Decrease the keyFrameRatio
_keyFrameRatio.Apply(1.0, 0.0);
}
// Change the level of the accumulator (bucket)
_accumulator += frameSizeKbits;
CapAccumulator();
}
void
VCMFrameDropper::Leak(WebRtc_UWord32 inputFrameRate)
{
if (!_enabled)
{
return;
}
if (inputFrameRate < 1)
{
return;
}
if (_targetBitRate < 0.0f)
{
return;
}
_keyFrameSpreadFrames = 0.5f * inputFrameRate;
// T is the expected bits per frame (target). If all frames were the same size,
// we would get T bits per frame. Notice that T is also weighted to be able to
// force a lower frame rate if wanted.
float T = _targetBitRate / inputFrameRate;
if (_keyFrameCount > 0)
{
// Perform the key frame compensation
if (_keyFrameRatio.Value() > 0 && 1 / _keyFrameRatio.Value() < _keyFrameSpreadFrames)
{
T -= _keyFrameSizeAvgKbits.Value() * _keyFrameRatio.Value();
}
else
{
T -= _keyFrameSizeAvgKbits.Value() / _keyFrameSpreadFrames;
}
_keyFrameCount--;
}
_accumulator -= T;
UpdateRatio();
}
void
VCMFrameDropper::UpdateNack(WebRtc_UWord32 nackBytes)
{
if (!_enabled)
{
return;
}
_accumulator += static_cast<float>(nackBytes) * 8.0f / 1000.0f;
}
void
VCMFrameDropper::FillBucket(float inKbits, float outKbits)
{
_accumulator += (inKbits - outKbits);
}
void
VCMFrameDropper::UpdateRatio()
{
if (_accumulator > 1.3f * _accumulatorMax)
{
// Too far above accumulator max, react faster
_dropRatio.UpdateBase(0.8f);
}
else
{
// Go back to normal reaction
_dropRatio.UpdateBase(0.9f);
}
if (_accumulator > _accumulatorMax)
{
// We are above accumulator max, and should ideally
// drop a frame. Increase the dropRatio and drop
// the frame later.
if (_wasBelowMax)
{
_dropNext = true;
}
if (_fastMode)
{
// always drop in aggressive mode
_dropNext = true;
}
_dropRatio.Apply(1.0f, 1.0f);
_dropRatio.UpdateBase(0.9f);
}
else
{
_dropRatio.Apply(1.0f, 0.0f);
}
if (_accumulator < 0.0f)
{
_accumulator = 0.0f;
}
_wasBelowMax = _accumulator < _accumulatorMax;
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId), "FrameDropper: dropRatio = %f accumulator = %f, accumulatorMax = %f", _dropRatio.Value(), _accumulator, _accumulatorMax);
}
// This function signals when to drop frames to the caller. It makes use of the dropRatio
// to smooth out the drops over time.
bool
VCMFrameDropper::DropFrame()
{
if (!_enabled)
{
return false;
}
if (_dropNext)
{
_dropNext = false;
_dropCount = 0;
}
if (_dropRatio.Value() >= 0.5f) // Drops per keep
{
// limit is the number of frames we should drop between each kept frame
// to keep our drop ratio. limit is positive in this case.
float denom = 1.0f - _dropRatio.Value();
if (denom < 1e-5)
{
denom = (float)1e-5;
}
WebRtc_Word32 limit = static_cast<WebRtc_Word32>(1.0f / denom - 1.0f + 0.5f);
// Put a bound on the max amount of dropped frames between each kept
// frame, in terms of frame rate and window size (secs).
int max_limit = static_cast<int>(_incoming_frame_rate *
_max_time_drops);
if (limit > max_limit) {
limit = max_limit;
}
if (_dropCount < 0)
{
// Reset the _dropCount since it was negative and should be positive.
if (_dropRatio.Value() > 0.4f)
{
_dropCount = -_dropCount;
}
else
{
_dropCount = 0;
}
}
if (_dropCount < limit)
{
// As long we are below the limit we should drop frames.
_dropCount++;
return true;
}
else
{
// Only when we reset _dropCount a frame should be kept.
_dropCount = 0;
return false;
}
}
else if (_dropRatio.Value() > 0.0f && _dropRatio.Value() < 0.5f) // Keeps per drop
{
// limit is the number of frames we should keep between each drop
// in order to keep the drop ratio. limit is negative in this case,
// and the _dropCount is also negative.
float denom = _dropRatio.Value();
if (denom < 1e-5)
{
denom = (float)1e-5;
}
WebRtc_Word32 limit = -static_cast<WebRtc_Word32>(1.0f / denom - 1.0f + 0.5f);
if (_dropCount > 0)
{
// Reset the _dropCount since we have a positive
// _dropCount, and it should be negative.
if (_dropRatio.Value() < 0.6f)
{
_dropCount = -_dropCount;
}
else
{
_dropCount = 0;
}
}
if (_dropCount > limit)
{
if (_dropCount == 0)
{
// Drop frames when we reset _dropCount.
_dropCount--;
return true;
}
else
{
// Keep frames as long as we haven't reached limit.
_dropCount--;
return false;
}
}
else
{
_dropCount = 0;
return false;
}
}
_dropCount = 0;
return false;
// A simpler version, unfiltered and quicker
//bool dropNext = _dropNext;
//_dropNext = false;
//return dropNext;
}
void
VCMFrameDropper::SetRates(float bitRate, float incoming_frame_rate)
{
// Bit rate of -1 means infinite bandwidth.
_accumulatorMax = bitRate * _windowSize; // bitRate * windowSize (in seconds)
if (_targetBitRate > 0.0f && bitRate < _targetBitRate && _accumulator > _accumulatorMax)
{
// Rescale the accumulator level if the accumulator max decreases
_accumulator = bitRate / _targetBitRate * _accumulator;
}
_targetBitRate = bitRate;
CapAccumulator();
_incoming_frame_rate = incoming_frame_rate;
}
float
VCMFrameDropper::ActualFrameRate(WebRtc_UWord32 inputFrameRate) const
{
if (!_enabled)
{
return static_cast<float>(inputFrameRate);
}
return inputFrameRate * (1.0f - _dropRatio.Value());
}
// Put a cap on the accumulator, i.e., don't let it grow beyond some level.
// This is a temporary fix for screencasting where very large frames from
// encoder will cause very slow response (too many frame drops).
void VCMFrameDropper::CapAccumulator() {
float max_accumulator = _targetBitRate * _cap_buffer_size;
if (_accumulator > max_accumulator) {
_accumulator = max_accumulator;
}
}
}
<commit_msg>VCM: Removing frame drop enable from Reset call BUG = 1387<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "frame_dropper.h"
#include "internal_defines.h"
#include "trace.h"
namespace webrtc
{
VCMFrameDropper::VCMFrameDropper(WebRtc_Word32 vcmId)
:
_vcmId(vcmId),
_keyFrameSizeAvgKbits(0.9f),
_keyFrameRatio(0.99f),
_dropRatio(0.9f, 0.96f),
_enabled(true)
{
Reset();
}
void
VCMFrameDropper::Reset()
{
_keyFrameRatio.Reset(0.99f);
_keyFrameRatio.Apply(1.0f, 1.0f/300.0f); // 1 key frame every 10th second in 30 fps
_keyFrameSizeAvgKbits.Reset(0.9f);
_keyFrameCount = 0;
_accumulator = 0.0f;
_accumulatorMax = 150.0f; // assume 300 kb/s and 0.5 s window
_targetBitRate = 300.0f;
_incoming_frame_rate = 30;
_keyFrameSpreadFrames = 0.5f * _incoming_frame_rate;
_dropNext = false;
_dropRatio.Reset(0.9f);
_dropRatio.Apply(0.0f, 0.0f); // Initialize to 0
_dropCount = 0;
_windowSize = 0.5f;
_wasBelowMax = true;
_fastMode = false; // start with normal (non-aggressive) mode
// Cap for the encoder buffer level/accumulator, in secs.
_cap_buffer_size = 3.0f;
// Cap on maximum amount of dropped frames between kept frames, in secs.
_max_time_drops = 4.0f;
}
void
VCMFrameDropper::Enable(bool enable)
{
_enabled = enable;
}
void
VCMFrameDropper::Fill(WebRtc_UWord32 frameSizeBytes, bool deltaFrame)
{
if (!_enabled)
{
return;
}
float frameSizeKbits = 8.0f * static_cast<float>(frameSizeBytes) / 1000.0f;
if (!deltaFrame && !_fastMode) // fast mode does not treat key-frames any different
{
_keyFrameSizeAvgKbits.Apply(1, frameSizeKbits);
_keyFrameRatio.Apply(1.0, 1.0);
if (frameSizeKbits > _keyFrameSizeAvgKbits.Value())
{
// Remove the average key frame size since we
// compensate for key frames when adding delta
// frames.
frameSizeKbits -= _keyFrameSizeAvgKbits.Value();
}
else
{
// Shouldn't be negative, so zero is the lower bound.
frameSizeKbits = 0;
}
if (_keyFrameRatio.Value() > 1e-5 && 1 / _keyFrameRatio.Value() < _keyFrameSpreadFrames)
{
// We are sending key frames more often than our upper bound for
// how much we allow the key frame compensation to be spread
// out in time. Therefor we must use the key frame ratio rather
// than keyFrameSpreadFrames.
_keyFrameCount = static_cast<WebRtc_Word32>(1 / _keyFrameRatio.Value() + 0.5);
}
else
{
// Compensate for the key frame the following frames
_keyFrameCount = static_cast<WebRtc_Word32>(_keyFrameSpreadFrames + 0.5);
}
}
else
{
// Decrease the keyFrameRatio
_keyFrameRatio.Apply(1.0, 0.0);
}
// Change the level of the accumulator (bucket)
_accumulator += frameSizeKbits;
CapAccumulator();
}
void
VCMFrameDropper::Leak(WebRtc_UWord32 inputFrameRate)
{
if (!_enabled)
{
return;
}
if (inputFrameRate < 1)
{
return;
}
if (_targetBitRate < 0.0f)
{
return;
}
_keyFrameSpreadFrames = 0.5f * inputFrameRate;
// T is the expected bits per frame (target). If all frames were the same size,
// we would get T bits per frame. Notice that T is also weighted to be able to
// force a lower frame rate if wanted.
float T = _targetBitRate / inputFrameRate;
if (_keyFrameCount > 0)
{
// Perform the key frame compensation
if (_keyFrameRatio.Value() > 0 && 1 / _keyFrameRatio.Value() < _keyFrameSpreadFrames)
{
T -= _keyFrameSizeAvgKbits.Value() * _keyFrameRatio.Value();
}
else
{
T -= _keyFrameSizeAvgKbits.Value() / _keyFrameSpreadFrames;
}
_keyFrameCount--;
}
_accumulator -= T;
UpdateRatio();
}
void
VCMFrameDropper::UpdateNack(WebRtc_UWord32 nackBytes)
{
if (!_enabled)
{
return;
}
_accumulator += static_cast<float>(nackBytes) * 8.0f / 1000.0f;
}
void
VCMFrameDropper::FillBucket(float inKbits, float outKbits)
{
_accumulator += (inKbits - outKbits);
}
void
VCMFrameDropper::UpdateRatio()
{
if (_accumulator > 1.3f * _accumulatorMax)
{
// Too far above accumulator max, react faster
_dropRatio.UpdateBase(0.8f);
}
else
{
// Go back to normal reaction
_dropRatio.UpdateBase(0.9f);
}
if (_accumulator > _accumulatorMax)
{
// We are above accumulator max, and should ideally
// drop a frame. Increase the dropRatio and drop
// the frame later.
if (_wasBelowMax)
{
_dropNext = true;
}
if (_fastMode)
{
// always drop in aggressive mode
_dropNext = true;
}
_dropRatio.Apply(1.0f, 1.0f);
_dropRatio.UpdateBase(0.9f);
}
else
{
_dropRatio.Apply(1.0f, 0.0f);
}
if (_accumulator < 0.0f)
{
_accumulator = 0.0f;
}
_wasBelowMax = _accumulator < _accumulatorMax;
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId), "FrameDropper: dropRatio = %f accumulator = %f, accumulatorMax = %f", _dropRatio.Value(), _accumulator, _accumulatorMax);
}
// This function signals when to drop frames to the caller. It makes use of the dropRatio
// to smooth out the drops over time.
bool
VCMFrameDropper::DropFrame()
{
if (!_enabled)
{
return false;
}
if (_dropNext)
{
_dropNext = false;
_dropCount = 0;
}
if (_dropRatio.Value() >= 0.5f) // Drops per keep
{
// limit is the number of frames we should drop between each kept frame
// to keep our drop ratio. limit is positive in this case.
float denom = 1.0f - _dropRatio.Value();
if (denom < 1e-5)
{
denom = (float)1e-5;
}
WebRtc_Word32 limit = static_cast<WebRtc_Word32>(1.0f / denom - 1.0f + 0.5f);
// Put a bound on the max amount of dropped frames between each kept
// frame, in terms of frame rate and window size (secs).
int max_limit = static_cast<int>(_incoming_frame_rate *
_max_time_drops);
if (limit > max_limit) {
limit = max_limit;
}
if (_dropCount < 0)
{
// Reset the _dropCount since it was negative and should be positive.
if (_dropRatio.Value() > 0.4f)
{
_dropCount = -_dropCount;
}
else
{
_dropCount = 0;
}
}
if (_dropCount < limit)
{
// As long we are below the limit we should drop frames.
_dropCount++;
return true;
}
else
{
// Only when we reset _dropCount a frame should be kept.
_dropCount = 0;
return false;
}
}
else if (_dropRatio.Value() > 0.0f && _dropRatio.Value() < 0.5f) // Keeps per drop
{
// limit is the number of frames we should keep between each drop
// in order to keep the drop ratio. limit is negative in this case,
// and the _dropCount is also negative.
float denom = _dropRatio.Value();
if (denom < 1e-5)
{
denom = (float)1e-5;
}
WebRtc_Word32 limit = -static_cast<WebRtc_Word32>(1.0f / denom - 1.0f + 0.5f);
if (_dropCount > 0)
{
// Reset the _dropCount since we have a positive
// _dropCount, and it should be negative.
if (_dropRatio.Value() < 0.6f)
{
_dropCount = -_dropCount;
}
else
{
_dropCount = 0;
}
}
if (_dropCount > limit)
{
if (_dropCount == 0)
{
// Drop frames when we reset _dropCount.
_dropCount--;
return true;
}
else
{
// Keep frames as long as we haven't reached limit.
_dropCount--;
return false;
}
}
else
{
_dropCount = 0;
return false;
}
}
_dropCount = 0;
return false;
// A simpler version, unfiltered and quicker
//bool dropNext = _dropNext;
//_dropNext = false;
//return dropNext;
}
void
VCMFrameDropper::SetRates(float bitRate, float incoming_frame_rate)
{
// Bit rate of -1 means infinite bandwidth.
_accumulatorMax = bitRate * _windowSize; // bitRate * windowSize (in seconds)
if (_targetBitRate > 0.0f && bitRate < _targetBitRate && _accumulator > _accumulatorMax)
{
// Rescale the accumulator level if the accumulator max decreases
_accumulator = bitRate / _targetBitRate * _accumulator;
}
_targetBitRate = bitRate;
CapAccumulator();
_incoming_frame_rate = incoming_frame_rate;
}
float
VCMFrameDropper::ActualFrameRate(WebRtc_UWord32 inputFrameRate) const
{
if (!_enabled)
{
return static_cast<float>(inputFrameRate);
}
return inputFrameRate * (1.0f - _dropRatio.Value());
}
// Put a cap on the accumulator, i.e., don't let it grow beyond some level.
// This is a temporary fix for screencasting where very large frames from
// encoder will cause very slow response (too many frame drops).
void VCMFrameDropper::CapAccumulator() {
float max_accumulator = _targetBitRate * _cap_buffer_size;
if (_accumulator > max_accumulator) {
_accumulator = max_accumulator;
}
}
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
//
// =============================================================================
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/FlatTerrain.h"
#include "chrono_vehicle/powertrain/SimplePowertrain.h"
#include "chrono_vehicle/utils/ChVehicleIrrApp.h"
#include "chrono_vehicle/tracked_vehicle/utils/ChTrackTestRig.h"
#include "chrono_vehicle/tracked_vehicle/utils/ChIrrGuiDriverTTR.h"
#include "m113/M113_TrackAssembly.h"
using namespace chrono;
using namespace chrono::vehicle;
using namespace m113;
// =============================================================================
// USER SETTINGS
// =============================================================================
double post_limit = 0.2;
// Simulation step size
double step_size = 1e-3;
double render_step_size = 1.0 / 50; // Time interval between two render frames
// =============================================================================
// JSON file for track test rig
std::string suspensionTest_file("hmmwv/suspensionTest/HMMWV_ST_front.json");
// JSON file for vehicle and vehicle side
std::string vehicle_file("hmmwv/vehicle/HMMWV_Vehicle.json");
int side = 0;
// Dummy powertrain
std::string simplepowertrain_file("generic/powertrain/SimplePowertrain.json");
// =============================================================================
int main(int argc, char* argv[]) {
// Create an M113 track assembly.
ChSharedPtr<M113_TrackAssembly> track_assembly(new M113_TrackAssembly(LEFT, MESH));
// Create and initialize the testing mechanism.
ChVector<> sprocket_loc(3, 1, 0);
ChVector<> idler_loc(-3, 1, 0);
std::vector<ChVector<> > susp_locs(5);
susp_locs[0] = ChVector<>(2, 1, -0.5);
susp_locs[1] = ChVector<>(1, 1, -0.5);
susp_locs[2] = ChVector<>(0, 1, -0.5);
susp_locs[3] = ChVector<>(-1, 1, -0.5);
susp_locs[4] = ChVector<>(-2, 1, -0.5);
ChTrackTestRig rig(track_assembly, sprocket_loc, idler_loc, susp_locs);
rig.Initialize(ChCoordsys<>());
// Create and initialize the powertrain system (not used).
SimplePowertrain powertrain(vehicle::GetDataFile(simplepowertrain_file));
powertrain.Initialize();
// Create the vehicle Irrlicht application.
ChVehicleIrrApp app(rig, powertrain, L"Suspension Test Rig");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(rig.GetPostPosition(), 6.0, 2.0);
app.SetTimestep(step_size);
app.AssetBindAll();
app.AssetUpdateAll();
// Create the driver system and set the time response for keyboard inputs.
ChIrrGuiDriverTTR driver(app, post_limit);
double steering_time = 1.0; // time to go from 0 to max
double displacement_time = 2.0; // time to go from 0 to max applied post motion
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetDisplacementDelta(render_step_size / displacement_time * post_limit);
// ---------------
// Simulation loop
// ---------------
// Inter-module communication data
TireForces tire_forces(2);
WheelStates wheel_states(2);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
TrackShoeForces shoe_forces(1);
// Initialize simulation frame counter
int step_number = 0;
ChRealtimeStepTimer realtime_timer;
while (app.GetDevice()->run()) {
// Render scene
if (step_number % render_steps == 0) {
app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
app.DrawAll();
app.EndScene();
}
// Collect output data from modules
double steering_input = driver.GetSteering();
double post_input = driver.GetDisplacement();
// Update modules (process inputs from other modules)
double time = rig.GetChTime();
driver.Update(time);
rig.Update(time, post_input, shoe_forces);
app.Update("", steering_input, 0, 0);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
rig.Advance(step);
app.Advance(step);
// Increment frame number
step_number++;
}
return 0;
}
<commit_msg>Set proper initial subsystem locations in demo_TrackTestRig<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
//
// =============================================================================
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/FlatTerrain.h"
#include "chrono_vehicle/powertrain/SimplePowertrain.h"
#include "chrono_vehicle/utils/ChVehicleIrrApp.h"
#include "chrono_vehicle/tracked_vehicle/utils/ChTrackTestRig.h"
#include "chrono_vehicle/tracked_vehicle/utils/ChIrrGuiDriverTTR.h"
#include "m113/M113_TrackAssembly.h"
using namespace chrono;
using namespace chrono::vehicle;
using namespace m113;
// =============================================================================
// USER SETTINGS
// =============================================================================
double post_limit = 0.2;
// Simulation step size
double step_size = 1e-3;
double render_step_size = 1.0 / 50; // Time interval between two render frames
// =============================================================================
// JSON file for track test rig
std::string suspensionTest_file("hmmwv/suspensionTest/HMMWV_ST_front.json");
// JSON file for vehicle and vehicle side
std::string vehicle_file("hmmwv/vehicle/HMMWV_Vehicle.json");
int side = 0;
// Dummy powertrain
std::string simplepowertrain_file("generic/powertrain/SimplePowertrain.json");
// =============================================================================
int main(int argc, char* argv[]) {
// Create an M113 track assembly.
ChSharedPtr<M113_TrackAssembly> track_assembly(new M113_TrackAssembly(LEFT, PRIMITIVES));
// Create and initialize the testing mechanism.
ChVector<> sprocket_loc(0, 1, 0);
ChVector<> idler_loc(-3.93, 1, -0.15); //// Original x value: -3.97
std::vector<ChVector<> > susp_locs(5);
susp_locs[0] = ChVector<>(-0.65, 1, -0.215);
susp_locs[1] = ChVector<>(-1.3175, 1, -0.215);
susp_locs[2] = ChVector<>(-1.985, 1, -0.215);
susp_locs[3] = ChVector<>(-2.6525, 1, -0.215);
susp_locs[4] = ChVector<>(-3.32, 1, -0.215);
ChTrackTestRig rig(track_assembly, sprocket_loc, idler_loc, susp_locs);
rig.GetSystem()->Set_G_acc(ChVector<>(0, 0, 0));
rig.Initialize(ChCoordsys<>());
// Create and initialize the powertrain system (not used).
SimplePowertrain powertrain(vehicle::GetDataFile(simplepowertrain_file));
powertrain.Initialize();
// Create the vehicle Irrlicht application.
ChVector<> target_point = rig.GetPostPosition();
////ChVector<> target_point = idler_loc;
////ChVector<> target_point = sprocket_loc;
ChVehicleIrrApp app(rig, powertrain, L"Suspension Test Rig");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(target_point, 3.0, 1.0);
app.SetChaseCameraPosition(target_point + ChVector<>(0, 3, 0));
app.SetTimestep(step_size);
app.AssetBindAll();
app.AssetUpdateAll();
// Create the driver system and set the time response for keyboard inputs.
ChIrrGuiDriverTTR driver(app, post_limit);
double steering_time = 1.0; // time to go from 0 to max
double displacement_time = 2.0; // time to go from 0 to max applied post motion
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetDisplacementDelta(render_step_size / displacement_time * post_limit);
// ---------------
// Simulation loop
// ---------------
// Inter-module communication data
TireForces tire_forces(2);
WheelStates wheel_states(2);
// Number of simulation steps between two 3D view render frames
int render_steps = (int)std::ceil(render_step_size / step_size);
TrackShoeForces shoe_forces(1);
// Initialize simulation frame counter
int step_number = 0;
ChRealtimeStepTimer realtime_timer;
while (app.GetDevice()->run()) {
// Render scene
if (step_number % render_steps == 0) {
app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
app.DrawAll();
app.EndScene();
}
// Collect output data from modules
double steering_input = driver.GetSteering();
double post_input = driver.GetDisplacement();
// Update modules (process inputs from other modules)
double time = rig.GetChTime();
driver.Update(time);
rig.Update(time, post_input, shoe_forces);
app.Update("", steering_input, 0, 0);
// Advance simulation for one timestep for all modules
double step = realtime_timer.SuggestSimulationStep(step_size);
driver.Advance(step);
rig.Advance(step);
app.Advance(step);
// Increment frame number
step_number++;
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef __TENSOR3_HPP_INCLUDED
#define __TENSOR3_HPP_INCLUDED
#include "matrix.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
namespace linear_algebra
{
class Tensor3
{
// `class Tensor3` uses the same coordinate order as MATLAB,
// to make testing easier. So: y, x, z.
// y = 0 is the uppermost slice
// x = 0 is the leftmost slice.
// z = 0 is the front slice.
public:
// constructor.
Tensor3(uint32_t height, uint32_t width, uint32_t depth);
// copy constructor.
Tensor3(Tensor3& old_tensor3);
// constructor.
Tensor3(Matrix& old_matrix);
// destructor.
~Tensor3();
// Inspired by http://stackoverflow.com/questions/6969881/operator-overload/6969904#6969904
class Proxy2D
{
public:
Proxy2D(float** array_of_arrays) : array_of_arrays(array_of_arrays) { }
class Proxy
{
public:
Proxy(float* proxy_array) : proxy_array(proxy_array) { }
float& operator[](const uint32_t index)
{
return proxy_array[index];
}
private:
float* proxy_array;
};
Proxy operator[](const uint32_t index)
{
return array_of_arrays[index];
}
private:
float** array_of_arrays;
};
void operator<<(const float rhs);
void operator<<(const std::vector<float>& rhs);
bool operator==(const Tensor3& rhs);
bool operator!=(const Tensor3& rhs);
Proxy2D operator[](const uint32_t index)
{
return Proxy2D(array_of_arrays_of_arrays[index]);
}
private:
bool is_cube;
uint32_t width;
uint32_t height;
uint32_t depth;
bool is_fully_populated;
// For populating, the order of coordinates from
// the one changing fastest to the one changing slowest is:
// x, y, z
int32_t next_x_to_populate;
int32_t next_y_to_populate;
int32_t next_z_to_populate;
float*** array_of_arrays_of_arrays;
};
}
#endif
<commit_msg>Bugfix: Visual Studio seem to require `public` access when overloading.<commit_after>#ifndef __TENSOR3_HPP_INCLUDED
#define __TENSOR3_HPP_INCLUDED
#include "matrix.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
namespace linear_algebra
{
class Tensor3
{
// `class Tensor3` uses the same coordinate order as MATLAB,
// to make testing easier. So: y, x, z.
// y = 0 is the uppermost slice
// x = 0 is the leftmost slice.
// z = 0 is the front slice.
public:
// constructor.
Tensor3(uint32_t height, uint32_t width, uint32_t depth);
// copy constructor.
Tensor3(Tensor3& old_tensor3);
// constructor.
Tensor3(Matrix& old_matrix);
// destructor.
~Tensor3();
// Inspired by http://stackoverflow.com/questions/6969881/operator-overload/6969904#6969904
class Proxy2D
{
public:
Proxy2D(float** array_of_arrays) : array_of_arrays(array_of_arrays) { }
class Proxy
{
public:
Proxy(float* proxy_array) : proxy_array(proxy_array) { }
float& operator[](const uint32_t index)
{
return proxy_array[index];
}
private:
float* proxy_array;
};
Proxy operator[](const uint32_t index)
{
return array_of_arrays[index];
}
private:
float** array_of_arrays;
};
void operator<<(const float rhs);
void operator<<(const std::vector<float>& rhs);
bool operator==(const Tensor3& rhs);
bool operator!=(const Tensor3& rhs);
Proxy2D operator[](const uint32_t index)
{
return Proxy2D(array_of_arrays_of_arrays[index]);
}
bool is_cube;
uint32_t width;
uint32_t height;
uint32_t depth;
private:
bool is_fully_populated;
// For populating, the order of coordinates from
// the one changing fastest to the one changing slowest is:
// x, y, z
int32_t next_x_to_populate;
int32_t next_y_to_populate;
int32_t next_z_to_populate;
float*** array_of_arrays_of_arrays;
};
}
#endif
<|endoftext|> |
<commit_before>/*
* FlightVars
* Copyright (c) 2014 Alvaro Polo
*
* 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/.
*/
#ifndef FLIGHTVARS_MQTT_CODECS_H
#define FLIGHTVARS_MQTT_CODECS_H
#include <flightvars/mqtt/codecs/connect.hpp>
#include <flightvars/mqtt/codecs/fixed-header.hpp>
#include <flightvars/mqtt/codecs/types.hpp>
namespace flightvars { namespace mqtt {
/**
* Decode a MQTT message from its fixed header and the buffer that contains the message content.
*
* The given buffer should be ready to extract the bytes corresponding to the message body.
*/
shared_message decode(const fixed_header& header, io::buffer& buff) {
switch (header.msg_type) {
case message_type::CONNECT: {
auto connect = codecs::decoder<connect_message>::decode(buff);
return std::make_shared<message>(header, connect);
break;
}
default:
throw std::runtime_error(util::format("cannot decode message of unknown type %s",
message_type_str(header.msg_type)));
}
}
}}
#endif
<commit_msg>Add `encode()` function in `codecs.hpp`<commit_after>/*
* FlightVars
* Copyright (c) 2014 Alvaro Polo
*
* 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/.
*/
#ifndef FLIGHTVARS_MQTT_CODECS_H
#define FLIGHTVARS_MQTT_CODECS_H
#include <flightvars/mqtt/codecs/connect.hpp>
#include <flightvars/mqtt/codecs/fixed-header.hpp>
#include <flightvars/mqtt/codecs/types.hpp>
namespace flightvars { namespace mqtt {
/**
* Encode a MQTT message into the given buffer.
*
* The buffer is flipped after encoded bytes are transferred.
*/
void encode(const message& msg, io::buffer& buff) {
auto header = msg.header();
codecs::encoder<fixed_header>::encode(header, buff);
switch (header.msg_type) {
case message_type::CONNECT:
codecs::encoder<connect_message>::encode(msg.connect().get(), buff);
break;
default:
throw std::runtime_error(util::format("cannot encode message of unknown type %s",
message_type_str(header.msg_type)));
}
buff.flip();
}
/**
* Decode a MQTT message from its fixed header and the buffer that contains the message content.
*
* The given buffer should be ready to extract the bytes corresponding to the message body.
*/
shared_message decode(const fixed_header& header, io::buffer& buff) {
switch (header.msg_type) {
case message_type::CONNECT: {
auto connect = codecs::decoder<connect_message>::decode(buff);
return std::make_shared<message>(header, connect);
break;
}
default:
throw std::runtime_error(util::format("cannot decode message of unknown type %s",
message_type_str(header.msg_type)));
}
}
}}
#endif
<|endoftext|> |
<commit_before>#include "Variant.h"
#include "split.h"
#include "cdflib.hpp"
#include "pdflib.hpp"
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <getopt.h>
using namespace std;
using namespace vcf;
struct pop{
double nalt ;
double nref ;
double af ;
double nhomr;
double nhoma;
double nhet ;
double ngeno;
double fis ;
vector<int> geno_index ;
vector< vector< double > > unphred_p;
};
double unphred(string phred){
double unphred = atof(phred.c_str());
unphred = unphred / -10;
return unphred;
}
void initPop(pop & population){
population.nalt = 0;
population.nref = 0;
population.af = 0;
population.nhomr = 0;
population.nhoma = 0;
population.nhet = 0;
population.ngeno = 0;
population.fis = 0;
}
void loadPop( vector< map< string, vector<string> > >& group, pop & population){
vector< map< string, vector<string> > >::iterator targ_it = group.begin();
for(; targ_it != group.end(); targ_it++){
population.ngeno += 1;
string genotype = (*targ_it)["GT"].front();
vector<double> phreds;
phreds.push_back( unphred((*targ_it)["PL"][0]));
phreds.push_back( unphred((*targ_it)["PL"][1]));
phreds.push_back( unphred((*targ_it)["PL"][2]));
population.unphred_p.push_back(phreds);
while(1){
if(genotype == "0/0"){
population.nhomr += 1;
population.nref += 2;
population.geno_index.push_back(0);
break;
}
if(genotype == "0/1"){
population.nhet += 1;
population.nref += 1;
population.nalt += 1;
population.geno_index.push_back(1);
break;
}
if(genotype == "1/1"){
population.nhoma += 1;
population.nalt += 2;
population.geno_index.push_back(2);
break;
}
if(genotype == "0|0"){
population.nhomr += 1;
population.nref += 2;
population.geno_index.push_back(0);
break;
}
if(genotype == "0|1"){
population.nhet += 1;
population.nref += 1;
population.nalt += 1;
population.geno_index.push_back(1);
break;
}
if(genotype == "1|1"){
population.nhoma += 1;
population.nalt += 2;
population.geno_index.push_back(2);
break;
}
cerr << "FATAL: unknown genotype" << endl;
exit(1);
}
}
if(population.nalt == 0 && population.nref == 0){
population.af = -1;
}
else{
population.af = (population.nalt / (population.nref + population.nalt));
if(population.nhet > 0){
population.fis = ( 1 - ((population.nhet/population.ngeno) / (2*population.af*(1 - population.af))));
}
else{
population.fis = 1;
}
if(population.fis < 0){
population.fis = 0.00001;
}
}
}
double bound(double v){
if(v <= 0.00001){
return 0.00001;
}
if(v >= 0.99999){
return 0.99999;
}
return v;
}
void loadIndices(map<int, int> & index, string set){
vector<string> indviduals = split(set, ",");
vector<string>::iterator it = indviduals.begin();
for(; it != indviduals.end(); it++){
index[ atoi( (*it).c_str() ) ] = 1;
}
}
void getPosterior(pop & population, double *alpha, double *beta){
int ng = population.geno_index.size();
for(int i = 0 ; i < ng; i++){
double aa = population.unphred_p[i][0] ;
double ab = population.unphred_p[i][1] ;
double bb = population.unphred_p[i][2] ;
double norm = log(exp(aa) + exp(ab) + exp(bb));
int gi = population.geno_index[i];
(*alpha) += exp(ab - norm);
(*beta ) += exp(ab - norm);
(*alpha) += 2 * exp(aa - norm);
(*beta ) += 2 * exp(bb - norm);
}
}
int main(int argc, char** argv) {
// set the random seed for MCMC
srand((unsigned)time(NULL));
// the filename
string filename = "NA";
// set region to scaffold
string region = "NA";
// using vcflib; thanks to Erik Garrison
VariantCallFile variantFile;
// zero based index for the target and background indivudals
map<int, int> it, ib;
// deltaaf is the difference of allele frequency we bother to look at
string deltaaf ;
double daf = 0;
//
int counts = 0;
const struct option longopts[] =
{
{"version" , 0, 0, 'v'},
{"help" , 0, 0, 'h'},
{"counts" , 0, 0, 'c'},
{"file" , 1, 0, 'f'},
{"target" , 1, 0, 't'},
{"background", 1, 0, 'b'},
{"deltaaf" , 1, 0, 'd'},
{"region" , 1, 0, 'r'},
{0,0,0,0}
};
int index;
int iarg=0;
while(iarg != -1)
{
iarg = getopt_long(argc, argv, "r:d:t:b:f:chv", longopts, &index);
switch (iarg)
{
case 'h':
cerr << endl << endl;
cerr << "INFO: help" << endl;
cerr << "INFO: description:" << endl;
cerr << " pFst is a probabilistic approach for detecting differences in allele frequencies between " << endl;
cerr << " a target and background. pFst uses the conjugated form of the beta-binomial distributions to estimate " << endl;
cerr << " the posterior distribution for the background's allele frequency. pFst calculates the probability of observing " << endl;
cerr << " the target's allele frequency given the posterior distribution of the background. By default " << endl;
cerr << " pFst uses the genotype likelihoods to estimate alpha, beta and the allele frequency of the target group. If you would like to assume " << endl;
cerr << " all genotypes are correct set the count flag equal to one. " << endl << endl;
cerr << "Output : 3 columns : " << endl;
cerr << " 1. seqid " << endl;
cerr << " 2. position " << endl;
cerr << " 3. pFst probability " << endl << endl;
cerr << "INFO: usage: pFst --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf --deltaaf 0.1" << endl;
cerr << endl;
cerr << "INFO: required: t,target -- a zero bases comma seperated list of target individuals corrisponding to VCF columns" << endl;
cerr << "INFO: required: b,background -- a zero bases comma seperated list of target individuals corrisponding to VCF columns" << endl;
cerr << "INFO: required: f,file a -- proper formatted VCF. the FORMAT field MUST contain \"PL\"" << endl;
cerr << "INFO: optional: d,deltaaf -- skip sites were the difference in allele frequency is less than deltaaf, default is zero" << endl;
cerr << "INFO: optional: c,counts -- use genotype counts rather than genotype likelihoods to estimate parameters, default false" << endl;
cerr << endl;
cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : [email protected] " << endl;
cerr << endl << endl;
return 0;
case 'v':
cerr << endl << endl;
cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : [email protected] " << endl;
return 0;
case 'c':
cerr << "INFO: using genotype counts rather than gentoype likelihoods" << endl;
counts = 1;
break;
case 't':
loadIndices(ib, optarg);
cerr << "INFO: There are " << ib.size() << " individuals in the target" << endl;
cerr << "INFO: target ids: " << optarg << endl;
break;
case 'b':
loadIndices(it, optarg);
cerr << "INFO: There are " << it.size() << " individuals in the background" << endl;
cerr << "INFO: background ids: " << optarg << endl;
break;
case 'f':
cerr << "INFO: File: " << optarg << endl;
filename = optarg;
break;
case 'd':
cerr << "INFO: only scoring sites where the allele frequency difference is greater than: " << optarg << endl;
deltaaf = optarg;
daf = atof(deltaaf.c_str());
break;
case 'r':
cerr << "INFO: set seqid region to : " << optarg << endl;
region = optarg;
break;
default:
break;
}
}
variantFile.open(filename);
if(region != "NA"){
variantFile.setRegion(region);
}
if (!variantFile.is_open()) {
return 1;
}
Variant var(variantFile);
while (variantFile.getNextVariant(var)) {
map<string, map<string, vector<string> > >::iterator s = var.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();
// biallelic sites naturally
if(var.alt.size() > 1){
continue;
}
vector < map< string, vector<string> > > target, background, total;
int index = 0;
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
if(sample["GT"].front() != "./."){
if(it.find(index) != it.end() ){
target.push_back(sample);
total.push_back(sample);
}
if(ib.find(index) != ib.end()){
background.push_back(sample);
total.push_back(sample);
}
}
index += 1;
}
if(target.size() < 5 || background.size() < 5 ){
continue;
}
pop popt, popb, popTotal;
initPop(popt);
initPop(popb);
initPop(popTotal);
loadPop(target, popt);
loadPop(background, popb);
loadPop(total, popTotal);
if(popt.af == -1 || popb.af == -1){
continue;
}
if(popt.af == 1 && popb.af == 1){
continue;
}
if(popt.af == 0 && popb.af == 0){
continue;
}
double afdiff = abs(popt.af - popb.af);
if(afdiff < daf){
continue;
}
double alphaT = 0.01;
double alphaB = 0.01;
double betaT = 0.01;
double betaB = 0.01;
if(counts == 1){
alphaT += popt.nref ;
alphaB += popb.nref ;
betaT += popt.nalt ;
betaB += popb.nalt ;
}
else{
getPosterior(popt, &alphaT, &betaT);
getPosterior(popb, &alphaB, &betaB);
}
double targm = alphaT / ( alphaT + betaT );
double backm = alphaB / ( alphaB + betaB );
double xa = targm - 0.001;
double xb = targm + 0.001;
if(xa <= 0){
xa = 0;
xb = 0.002;
}
if(xb >= 1){
xa = 0.998;
xb = 1;
}
double dph = r8_beta_pdf(alphaB, betaB, xa);
double dpl = r8_beta_pdf(alphaB, betaB, xb);
double p = ((dph + dpl)/2) * 0.01;
cout << var.sequenceName << "\t" << var.position << "\t" << p << endl ;
}
return 0;
}
<commit_msg>docs docs docs<commit_after>#include "Variant.h"
#include "split.h"
#include "cdflib.hpp"
#include "pdflib.hpp"
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <getopt.h>
using namespace std;
using namespace vcf;
struct pop{
double nalt ;
double nref ;
double af ;
double nhomr;
double nhoma;
double nhet ;
double ngeno;
double fis ;
vector<int> geno_index ;
vector< vector< double > > unphred_p;
};
double unphred(string phred){
double unphred = atof(phred.c_str());
unphred = unphred / -10;
return unphred;
}
void initPop(pop & population){
population.nalt = 0;
population.nref = 0;
population.af = 0;
population.nhomr = 0;
population.nhoma = 0;
population.nhet = 0;
population.ngeno = 0;
population.fis = 0;
}
void loadPop( vector< map< string, vector<string> > >& group, pop & population){
vector< map< string, vector<string> > >::iterator targ_it = group.begin();
for(; targ_it != group.end(); targ_it++){
population.ngeno += 1;
string genotype = (*targ_it)["GT"].front();
vector<double> phreds;
phreds.push_back( unphred((*targ_it)["PL"][0]));
phreds.push_back( unphred((*targ_it)["PL"][1]));
phreds.push_back( unphred((*targ_it)["PL"][2]));
population.unphred_p.push_back(phreds);
while(1){
if(genotype == "0/0"){
population.nhomr += 1;
population.nref += 2;
population.geno_index.push_back(0);
break;
}
if(genotype == "0/1"){
population.nhet += 1;
population.nref += 1;
population.nalt += 1;
population.geno_index.push_back(1);
break;
}
if(genotype == "1/1"){
population.nhoma += 1;
population.nalt += 2;
population.geno_index.push_back(2);
break;
}
if(genotype == "0|0"){
population.nhomr += 1;
population.nref += 2;
population.geno_index.push_back(0);
break;
}
if(genotype == "0|1"){
population.nhet += 1;
population.nref += 1;
population.nalt += 1;
population.geno_index.push_back(1);
break;
}
if(genotype == "1|1"){
population.nhoma += 1;
population.nalt += 2;
population.geno_index.push_back(2);
break;
}
cerr << "FATAL: unknown genotype" << endl;
exit(1);
}
}
if(population.nalt == 0 && population.nref == 0){
population.af = -1;
}
else{
population.af = (population.nalt / (population.nref + population.nalt));
if(population.nhet > 0){
population.fis = ( 1 - ((population.nhet/population.ngeno) / (2*population.af*(1 - population.af))));
}
else{
population.fis = 1;
}
if(population.fis < 0){
population.fis = 0.00001;
}
}
}
double bound(double v){
if(v <= 0.00001){
return 0.00001;
}
if(v >= 0.99999){
return 0.99999;
}
return v;
}
void loadIndices(map<int, int> & index, string set){
vector<string> indviduals = split(set, ",");
vector<string>::iterator it = indviduals.begin();
for(; it != indviduals.end(); it++){
index[ atoi( (*it).c_str() ) ] = 1;
}
}
void getPosterior(pop & population, double *alpha, double *beta){
int ng = population.geno_index.size();
for(int i = 0 ; i < ng; i++){
double aa = population.unphred_p[i][0] ;
double ab = population.unphred_p[i][1] ;
double bb = population.unphred_p[i][2] ;
double norm = log(exp(aa) + exp(ab) + exp(bb));
int gi = population.geno_index[i];
(*alpha) += exp(ab - norm);
(*beta ) += exp(ab - norm);
(*alpha) += 2 * exp(aa - norm);
(*beta ) += 2 * exp(bb - norm);
}
}
int main(int argc, char** argv) {
// set the random seed for MCMC
srand((unsigned)time(NULL));
// the filename
string filename = "NA";
// set region to scaffold
string region = "NA";
// using vcflib; thanks to Erik Garrison
VariantCallFile variantFile;
// zero based index for the target and background indivudals
map<int, int> it, ib;
// deltaaf is the difference of allele frequency we bother to look at
string deltaaf ;
double daf = 0;
//
int counts = 0;
const struct option longopts[] =
{
{"version" , 0, 0, 'v'},
{"help" , 0, 0, 'h'},
{"counts" , 0, 0, 'c'},
{"file" , 1, 0, 'f'},
{"target" , 1, 0, 't'},
{"background", 1, 0, 'b'},
{"deltaaf" , 1, 0, 'd'},
{"region" , 1, 0, 'r'},
{0,0,0,0}
};
int index;
int iarg=0;
while(iarg != -1)
{
iarg = getopt_long(argc, argv, "r:d:t:b:f:chv", longopts, &index);
switch (iarg)
{
case 'h':
cerr << endl << endl;
cerr << "INFO: help" << endl;
cerr << "INFO: description:" << endl;
cerr << " pFst is a probabilistic approach for detecting differences in allele frequencies between two populations, " << endl;
cerr << " a target and background. pFst uses the conjugated form of the beta-binomial distributions to estimate " << endl;
cerr << " the posterior distribution for the background's allele frequency. pFst calculates the probability of observing " << endl;
cerr << " the target's allele frequency given the posterior distribution of the background. By default " << endl;
cerr << " pFst uses the genotype likelihoods to estimate alpha, beta and the allele frequency of the target group. If you would like to assume " << endl;
cerr << " all genotypes are correct set the count flag equal to one. " << endl << endl;
cerr << "Output : 3 columns : " << endl;
cerr << " 1. seqid " << endl;
cerr << " 2. position " << endl;
cerr << " 3. pFst probability " << endl << endl;
cerr << "INFO: usage: pFst --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf --deltaaf 0.1" << endl;
cerr << endl;
cerr << "INFO: required: t,target -- a zero bases comma seperated list of target individuals corrisponding to VCF columns" << endl;
cerr << "INFO: required: b,background -- a zero bases comma seperated list of background individuals corrisponding to VCF columns" << endl;
cerr << "INFO: required: f,file a -- proper formatted VCF. the FORMAT field MUST contain \"PL\"" << endl;
cerr << "INFO: optional: d,deltaaf -- skip sites where the difference in allele frequencies is less than deltaaf, default is zero" << endl;
cerr << "INFO: optional: c,counts -- use genotype counts rather than genotype likelihoods to estimate parameters, default false" << endl;
cerr << endl;
cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : [email protected] " << endl;
cerr << endl << endl;
return 0;
case 'v':
cerr << endl << endl;
cerr << "INFO: version 1.0.0 ; date: April 2014 ; author: Zev Kronenberg; email : [email protected] " << endl;
return 0;
case 'c':
cerr << "INFO: using genotype counts rather than gentoype likelihoods" << endl;
counts = 1;
break;
case 't':
loadIndices(ib, optarg);
cerr << "INFO: There are " << ib.size() << " individuals in the target" << endl;
cerr << "INFO: target ids: " << optarg << endl;
break;
case 'b':
loadIndices(it, optarg);
cerr << "INFO: There are " << it.size() << " individuals in the background" << endl;
cerr << "INFO: background ids: " << optarg << endl;
break;
case 'f':
cerr << "INFO: File: " << optarg << endl;
filename = optarg;
break;
case 'd':
cerr << "INFO: only scoring sites where the allele frequency difference is greater than: " << optarg << endl;
deltaaf = optarg;
daf = atof(deltaaf.c_str());
break;
case 'r':
cerr << "INFO: set seqid region to : " << optarg << endl;
region = optarg;
break;
default:
break;
}
}
variantFile.open(filename);
if(region != "NA"){
variantFile.setRegion(region);
}
if (!variantFile.is_open()) {
return 1;
}
Variant var(variantFile);
while (variantFile.getNextVariant(var)) {
map<string, map<string, vector<string> > >::iterator s = var.samples.begin();
map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();
// biallelic sites naturally
if(var.alt.size() > 1){
continue;
}
vector < map< string, vector<string> > > target, background, total;
int index = 0;
for (; s != sEnd; ++s) {
map<string, vector<string> >& sample = s->second;
if(sample["GT"].front() != "./."){
if(it.find(index) != it.end() ){
target.push_back(sample);
total.push_back(sample);
}
if(ib.find(index) != ib.end()){
background.push_back(sample);
total.push_back(sample);
}
}
index += 1;
}
if(target.size() < 5 || background.size() < 5 ){
continue;
}
pop popt, popb, popTotal;
initPop(popt);
initPop(popb);
initPop(popTotal);
loadPop(target, popt);
loadPop(background, popb);
loadPop(total, popTotal);
if(popt.af == -1 || popb.af == -1){
continue;
}
if(popt.af == 1 && popb.af == 1){
continue;
}
if(popt.af == 0 && popb.af == 0){
continue;
}
double afdiff = abs(popt.af - popb.af);
if(afdiff < daf){
continue;
}
double alphaT = 0.01;
double alphaB = 0.01;
double betaT = 0.01;
double betaB = 0.01;
if(counts == 1){
alphaT += popt.nref ;
alphaB += popb.nref ;
betaT += popt.nalt ;
betaB += popb.nalt ;
}
else{
getPosterior(popt, &alphaT, &betaT);
getPosterior(popb, &alphaB, &betaB);
}
double targm = alphaT / ( alphaT + betaT );
double backm = alphaB / ( alphaB + betaB );
double xa = targm - 0.001;
double xb = targm + 0.001;
if(xa <= 0){
xa = 0;
xb = 0.002;
}
if(xb >= 1){
xa = 0.998;
xb = 1;
}
double dph = r8_beta_pdf(alphaB, betaB, xa);
double dpl = r8_beta_pdf(alphaB, betaB, xb);
double p = ((dph + dpl)/2) * 0.01;
cout << var.sequenceName << "\t" << var.position << "\t" << p << endl ;
}
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/freq/sync.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file sync.C
/// @brief Synchronous function implementations
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#include <vector>
#include <map>
#include <fapi2.H>
#include <mss.H>
#include <freq/sync.H>
#include <lib/utils/find.H>
using fapi2::TARGET_TYPE_DIMM;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_SYSTEM;
namespace mss
{
///
/// @brief Retrieves a mapping of MSS frequency values per mcbist target
/// @param[in] i_targets vector of controller targets
/// @param[out] o_freq_map dimm speed map <key, value> = (mcbist target, frequency)
/// @param[out] o_is_speed_equal true if all map dimm speeds are the same
/// @return FAPI2_RC_SUCCESS iff successful
///
fapi2::ReturnCode dimm_speed_map(const std::vector< fapi2::Target<TARGET_TYPE_MCBIST> >& i_targets,
std::map< fapi2::Target<TARGET_TYPE_MCBIST>, uint64_t >& o_freq_map,
speed_equality& o_is_speed_equal)
{
FAPI_INF("---- In dimm_speed_pairs ----");
if(i_targets.empty())
{
FAPI_ERR("Empty target vector found when constructing dimm speed mapping!");
return fapi2::FAPI2_RC_INVALID_PARAMETER;
}
// Getting a sample freq value from an arbitrary target (first one)
// to compare against all other target freq values
uint64_t l_comparator = 0;
FAPI_TRY( mss::freq(i_targets[0], l_comparator), "Failed accessor to mss_freq" );
o_is_speed_equal = speed_equality::EQUAL_DIMM_SPEEDS;
// Loop through all MCSBISTs and store dimm speeds
for (const auto& l_mcbist : i_targets)
{
uint64_t l_dimm_speed = 0;
FAPI_TRY( mss::freq(l_mcbist, l_dimm_speed), "Failed accessor to mss_freq" );
if(l_comparator != l_dimm_speed)
{
o_is_speed_equal = speed_equality::NOT_EQUAL_DIMM_SPEEDS;
}
FAPI_INF("%s: Dimm speed %d MT/s", c_str(l_mcbist), l_dimm_speed);
o_freq_map.emplace( std::make_pair(l_mcbist, l_dimm_speed) );
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Deconfigures MCS targets connected to MCBIST
/// @param[in] i_target the controller target
/// @param[in] i_dimm_speed dimm speed in MT/s
/// @param[in] i_nest_freq nest freq in MHz
/// @return true if hardware was deconfigured
///
bool deconfigure(const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint64_t i_dimm_speed,
const uint32_t i_nest_freq)
{
FAPI_INF("---- In deconfigure ----");
bool l_is_hw_deconfigured = false;
// TODO - RTC 155347 fix dimm speed & nest comparison if needed
if(i_dimm_speed != i_nest_freq)
{
// Deconfigure MCSes
for( const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(i_target) )
{
l_is_hw_deconfigured = true;
PLAT_FAPI_ASSERT_NOEXIT(false,
fapi2::MSS_FREQ_NOT_EQUAL_NEST_FREQ()
.set_MSS_FREQ(i_dimm_speed)
.set_NEST_FREQ(i_nest_freq)
.set_MCS_TARGET(l_mcs),
"Deconfiguring %s",
mss::c_str(l_mcs) );
}// end for
}// end if
return l_is_hw_deconfigured;
}
///
/// @brief Selects synchronous mode and performs requirements enforced by ATTR_REQUIRED_SYNCH_MODE
/// @param[in] i_freq_map dimm speed mapping
/// @param[in] i_equal_dimm_speed tracks whether map has equal dimm speeds
/// @param[in] i_nest_freq nest frequency
/// @param[in] i_required_sync_mode system policy to enforce synchronous mode
/// @param[out] o_selected_sync_mode final synchronous mode
/// @return FAPI2_RC_SUCCESS iff successful
///
fapi2::ReturnCode select_sync_mode(const std::map< fapi2::Target<TARGET_TYPE_MCBIST>, uint64_t >& i_freq_map,
const speed_equality i_equal_dimm_speed,
const uint32_t i_nest_freq,
const uint8_t i_required_sync_mode,
sync_mode& o_selected_sync_mode)
{
FAPI_INF("---- In select_sync_mode ----");
// Implementing frequency handling discussion:
// https://w3-connections.ibm.com/forums/html/topic?id=1222318f-5992-4342-a858-b75594df1be3&ps=
// Summary: We will always use async mode if we don't see a perfect match of dimm frequencies that match the nest
switch(i_equal_dimm_speed)
{
case speed_equality::EQUAL_DIMM_SPEEDS:
// Do not run synchronously, even if the frequencies match
if (i_required_sync_mode == fapi2::ENUM_ATTR_REQUIRED_SYNCH_MODE_NEVER)
{
o_selected_sync_mode = sync_mode::MC_NOT_IN_SYNC;
break;
}
// Run synchronously if the dimm and nest freq matches
// Implicitly covers case when ATTR_REQUIRED_SYNCH_MODE is
// ALWAYS and UNDETERMINED
if( i_freq_map.begin()->second == i_nest_freq)
{
o_selected_sync_mode = sync_mode::MC_IN_SYNC;
}
else
{
o_selected_sync_mode = sync_mode::MC_NOT_IN_SYNC;
}
break;
case speed_equality::NOT_EQUAL_DIMM_SPEEDS:
// Require matching frequencies and deconfigure memory that does not match the nest
if( i_required_sync_mode == fapi2::ENUM_ATTR_REQUIRED_SYNCH_MODE_ALWAYS )
{
for(const auto& l_it : i_freq_map)
{
// This can be refactored to return info people might
// need. Until then this returns true if hw was deconfigured
// FFDC prints out location
deconfigure(l_it.first, l_it.second, i_nest_freq);
}// end for
}// end if
// Implicitly covers case when ATTR_REQUIRED_SYNCH_MODE is
// NEVER, ALWAYS, and UNDETERMINED
o_selected_sync_mode = sync_mode::MC_NOT_IN_SYNC;
break;
default:
FAPI_ERR("Invalid speed_equality parameter!");
return fapi2::FAPI2_RC_INVALID_PARAMETER;
break;
}// end switch
return fapi2::FAPI2_RC_SUCCESS;
}
}// mss
<commit_msg>Change mss build to account for double free in wrappers<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/freq/sync.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file sync.C
/// @brief Synchronous function implementations
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#include <vector>
#include <map>
#include <fapi2.H>
#include <mss.H>
#include <lib/freq/sync.H>
#include <lib/utils/find.H>
using fapi2::TARGET_TYPE_DIMM;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_SYSTEM;
namespace mss
{
///
/// @brief Retrieves a mapping of MSS frequency values per mcbist target
/// @param[in] i_targets vector of controller targets
/// @param[out] o_freq_map dimm speed map <key, value> = (mcbist target, frequency)
/// @param[out] o_is_speed_equal true if all map dimm speeds are the same
/// @return FAPI2_RC_SUCCESS iff successful
///
fapi2::ReturnCode dimm_speed_map(const std::vector< fapi2::Target<TARGET_TYPE_MCBIST> >& i_targets,
std::map< fapi2::Target<TARGET_TYPE_MCBIST>, uint64_t >& o_freq_map,
speed_equality& o_is_speed_equal)
{
FAPI_INF("---- In dimm_speed_pairs ----");
if(i_targets.empty())
{
FAPI_ERR("Empty target vector found when constructing dimm speed mapping!");
return fapi2::FAPI2_RC_INVALID_PARAMETER;
}
// Getting a sample freq value from an arbitrary target (first one)
// to compare against all other target freq values
uint64_t l_comparator = 0;
FAPI_TRY( mss::freq(i_targets[0], l_comparator), "Failed accessor to mss_freq" );
o_is_speed_equal = speed_equality::EQUAL_DIMM_SPEEDS;
// Loop through all MCSBISTs and store dimm speeds
for (const auto& l_mcbist : i_targets)
{
uint64_t l_dimm_speed = 0;
FAPI_TRY( mss::freq(l_mcbist, l_dimm_speed), "Failed accessor to mss_freq" );
if(l_comparator != l_dimm_speed)
{
o_is_speed_equal = speed_equality::NOT_EQUAL_DIMM_SPEEDS;
}
FAPI_INF("%s: Dimm speed %d MT/s", c_str(l_mcbist), l_dimm_speed);
o_freq_map.emplace( std::make_pair(l_mcbist, l_dimm_speed) );
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Deconfigures MCS targets connected to MCBIST
/// @param[in] i_target the controller target
/// @param[in] i_dimm_speed dimm speed in MT/s
/// @param[in] i_nest_freq nest freq in MHz
/// @return true if hardware was deconfigured
///
bool deconfigure(const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint64_t i_dimm_speed,
const uint32_t i_nest_freq)
{
FAPI_INF("---- In deconfigure ----");
bool l_is_hw_deconfigured = false;
// TODO - RTC 155347 fix dimm speed & nest comparison if needed
if(i_dimm_speed != i_nest_freq)
{
// Deconfigure MCSes
for( const auto& l_mcs : mss::find_targets<TARGET_TYPE_MCS>(i_target) )
{
l_is_hw_deconfigured = true;
PLAT_FAPI_ASSERT_NOEXIT(false,
fapi2::MSS_FREQ_NOT_EQUAL_NEST_FREQ()
.set_MSS_FREQ(i_dimm_speed)
.set_NEST_FREQ(i_nest_freq)
.set_MCS_TARGET(l_mcs),
"Deconfiguring %s",
mss::c_str(l_mcs) );
}// end for
}// end if
return l_is_hw_deconfigured;
}
///
/// @brief Selects synchronous mode and performs requirements enforced by ATTR_REQUIRED_SYNCH_MODE
/// @param[in] i_freq_map dimm speed mapping
/// @param[in] i_equal_dimm_speed tracks whether map has equal dimm speeds
/// @param[in] i_nest_freq nest frequency
/// @param[in] i_required_sync_mode system policy to enforce synchronous mode
/// @param[out] o_selected_sync_mode final synchronous mode
/// @return FAPI2_RC_SUCCESS iff successful
///
fapi2::ReturnCode select_sync_mode(const std::map< fapi2::Target<TARGET_TYPE_MCBIST>, uint64_t >& i_freq_map,
const speed_equality i_equal_dimm_speed,
const uint32_t i_nest_freq,
const uint8_t i_required_sync_mode,
sync_mode& o_selected_sync_mode)
{
FAPI_INF("---- In select_sync_mode ----");
// Implementing frequency handling discussion:
// https://w3-connections.ibm.com/forums/html/topic?id=1222318f-5992-4342-a858-b75594df1be3&ps=
// Summary: We will always use async mode if we don't see a perfect match of dimm frequencies that match the nest
switch(i_equal_dimm_speed)
{
case speed_equality::EQUAL_DIMM_SPEEDS:
// Do not run synchronously, even if the frequencies match
if (i_required_sync_mode == fapi2::ENUM_ATTR_REQUIRED_SYNCH_MODE_NEVER)
{
o_selected_sync_mode = sync_mode::MC_NOT_IN_SYNC;
break;
}
// Run synchronously if the dimm and nest freq matches
// Implicitly covers case when ATTR_REQUIRED_SYNCH_MODE is
// ALWAYS and UNDETERMINED
if( i_freq_map.begin()->second == i_nest_freq)
{
o_selected_sync_mode = sync_mode::MC_IN_SYNC;
}
else
{
o_selected_sync_mode = sync_mode::MC_NOT_IN_SYNC;
}
break;
case speed_equality::NOT_EQUAL_DIMM_SPEEDS:
// Require matching frequencies and deconfigure memory that does not match the nest
if( i_required_sync_mode == fapi2::ENUM_ATTR_REQUIRED_SYNCH_MODE_ALWAYS )
{
for(const auto& l_it : i_freq_map)
{
// This can be refactored to return info people might
// need. Until then this returns true if hw was deconfigured
// FFDC prints out location
deconfigure(l_it.first, l_it.second, i_nest_freq);
}// end for
}// end if
// Implicitly covers case when ATTR_REQUIRED_SYNCH_MODE is
// NEVER, ALWAYS, and UNDETERMINED
o_selected_sync_mode = sync_mode::MC_NOT_IN_SYNC;
break;
default:
FAPI_ERR("Invalid speed_equality parameter!");
return fapi2::FAPI2_RC_INVALID_PARAMETER;
break;
}// end switch
return fapi2::FAPI2_RC_SUCCESS;
}
}// mss
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PagePropertySetContext.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:29:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#include "PagePropertySetContext.hxx"
#endif
#ifndef _XMLBACKGROUNDIMAGECONTEXT_HXX
#include "XMLBackgroundImageContext.hxx"
#endif
#ifndef _XMLTEXTCOLUMNSCONTEXT_HXX
#include "XMLTextColumnsContext.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _XMLOFF_XMLFOOTNOTESEPARATORIMPORT_HXX
#include "XMLFootnoteSeparatorImport.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
PagePropertySetContext::PagePropertySetContext(
SvXMLImport& rImport, sal_uInt16 nPrfx,
const OUString& rLName,
const Reference< xml::sax::XAttributeList > & xAttrList,
sal_uInt32 nFam,
::std::vector< XMLPropertyState > &rProps,
const UniReference < SvXMLImportPropertyMapper > &rMap,
sal_Int32 nStartIndex, sal_Int32 nEndIndex,
const PageContextType aTempType ) :
SvXMLPropertySetContext( rImport, nPrfx, rLName, xAttrList, nFam,
rProps, rMap, nStartIndex, nEndIndex )
{
aType = aTempType;
}
PagePropertySetContext::~PagePropertySetContext()
{
}
SvXMLImportContext *PagePropertySetContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList,
::std::vector< XMLPropertyState > &rProperties,
const XMLPropertyState& rProp )
{
sal_Int32 nPos = CTF_PM_GRAPHICPOSITION;
sal_Int32 nFil = CTF_PM_GRAPHICFILTER;
switch ( aType )
{
case Header:
{
nPos = CTF_PM_HEADERGRAPHICPOSITION;
nFil = CTF_PM_HEADERGRAPHICFILTER;
}
break;
case Footer:
{
nPos = CTF_PM_FOOTERGRAPHICPOSITION;
nFil = CTF_PM_FOOTERGRAPHICFILTER;
}
break;
default:
break;
}
SvXMLImportContext *pContext = 0;
switch( mxMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex ) )
{
case CTF_PM_GRAPHICURL:
case CTF_PM_HEADERGRAPHICURL:
case CTF_PM_FOOTERGRAPHICURL:
DBG_ASSERT( rProp.mnIndex >= 2 &&
nPos == mxMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-2 ) &&
nFil == mxMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-1 ),
"invalid property map!");
pContext =
new XMLBackgroundImageContext( GetImport(), nPrefix,
rLocalName, xAttrList,
rProp,
rProp.mnIndex-2,
rProp.mnIndex-1,
-1,
rProperties );
break;
case CTF_PM_TEXTCOLUMNS:
#ifndef SVX_LIGHT
pContext = new XMLTextColumnsContext( GetImport(), nPrefix,
rLocalName, xAttrList, rProp,
rProperties );
#else
// create default context to skip content
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
#endif // #ifndef SVX_LIGHT
break;
case CTF_PM_FTN_LINE_WEIGTH:
#ifndef SVX_LIGHT
pContext = new XMLFootnoteSeparatorImport(
GetImport(), nPrefix, rLocalName, rProperties,
mxMapper->getPropertySetMapper(), rProp.mnIndex);
#else
// create default context to skip content
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName);
#endif // #ifndef SVX_LIGHT
break;
}
if( !pContext )
pContext = SvXMLPropertySetContext::CreateChildContext( nPrefix, rLocalName,
xAttrList,
rProperties, rProp );
return pContext;
}
<commit_msg>INTEGRATION: CWS impresstables2 (1.12.80); FILE MERGED 2007/08/01 14:26:12 cl 1.12.80.2: RESYNC: (1.12-1.13); FILE MERGED 2007/07/27 09:09:53 cl 1.12.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PagePropertySetContext.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2008-03-12 10:44:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#include "PagePropertySetContext.hxx"
#endif
#ifndef _XMLBACKGROUNDIMAGECONTEXT_HXX
#include "XMLBackgroundImageContext.hxx"
#endif
#ifndef _XMLTEXTCOLUMNSCONTEXT_HXX
#include "XMLTextColumnsContext.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _XMLOFF_XMLFOOTNOTESEPARATORIMPORT_HXX
#include "XMLFootnoteSeparatorImport.hxx"
#endif
using ::rtl::OUString;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
PagePropertySetContext::PagePropertySetContext(
SvXMLImport& rImport, sal_uInt16 nPrfx,
const OUString& rLName,
const Reference< xml::sax::XAttributeList > & xAttrList,
sal_uInt32 nFam,
::std::vector< XMLPropertyState > &rProps,
const UniReference < SvXMLImportPropertyMapper > &rMap,
sal_Int32 nStartIndex, sal_Int32 nEndIndex,
const PageContextType aTempType ) :
SvXMLPropertySetContext( rImport, nPrfx, rLName, xAttrList, nFam,
rProps, rMap, nStartIndex, nEndIndex )
{
aType = aTempType;
}
PagePropertySetContext::~PagePropertySetContext()
{
}
SvXMLImportContext *PagePropertySetContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList,
::std::vector< XMLPropertyState > &rProperties,
const XMLPropertyState& rProp )
{
sal_Int32 nPos = CTF_PM_GRAPHICPOSITION;
sal_Int32 nFil = CTF_PM_GRAPHICFILTER;
switch ( aType )
{
case Header:
{
nPos = CTF_PM_HEADERGRAPHICPOSITION;
nFil = CTF_PM_HEADERGRAPHICFILTER;
}
break;
case Footer:
{
nPos = CTF_PM_FOOTERGRAPHICPOSITION;
nFil = CTF_PM_FOOTERGRAPHICFILTER;
}
break;
default:
break;
}
SvXMLImportContext *pContext = 0;
switch( mxMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex ) )
{
case CTF_PM_GRAPHICURL:
case CTF_PM_HEADERGRAPHICURL:
case CTF_PM_FOOTERGRAPHICURL:
DBG_ASSERT( rProp.mnIndex >= 2 &&
nPos == mxMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-2 ) &&
nFil == mxMapper->getPropertySetMapper()
->GetEntryContextId( rProp.mnIndex-1 ),
"invalid property map!");
pContext =
new XMLBackgroundImageContext( GetImport(), nPrefix,
rLocalName, xAttrList,
rProp,
rProp.mnIndex-2,
rProp.mnIndex-1,
-1,
rProperties );
break;
case CTF_PM_TEXTCOLUMNS:
#ifndef SVX_LIGHT
pContext = new XMLTextColumnsContext( GetImport(), nPrefix,
rLocalName, xAttrList, rProp,
rProperties );
#else
// create default context to skip content
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
#endif // #ifndef SVX_LIGHT
break;
case CTF_PM_FTN_LINE_WEIGTH:
#ifndef SVX_LIGHT
pContext = new XMLFootnoteSeparatorImport(
GetImport(), nPrefix, rLocalName, rProperties,
mxMapper->getPropertySetMapper(), rProp.mnIndex);
#else
// create default context to skip content
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName);
#endif // #ifndef SVX_LIGHT
break;
}
if( !pContext )
pContext = SvXMLPropertySetContext::CreateChildContext( nPrefix, rLocalName,
xAttrList,
rProperties, rProp );
return pContext;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ChartOASISTContext.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-07-13 08:43:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_CHARTOASISTCONTEXT_HXX
#include "ChartOASISTContext.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
// -----------------------------------------------------------------------------
TYPEINIT1( XMLChartOASISTransformerContext, XMLTransformerContext );
XMLChartOASISTransformerContext::XMLChartOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLTransformerContext( rImp, rQName )
{
}
XMLChartOASISTransformerContext::~XMLChartOASISTransformerContext()
{
}
void XMLChartOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_CHART_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
OUString aAddInName;
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_IN2INCH:
{
OUString aAttrValue( rAttrValue );
if( XMLTransformerBase::ReplaceSingleInWithInch(
aAttrValue ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_DECODE_STYLE_NAME_REF:
{
OUString aAttrValue( rAttrValue );
if( GetTransformer().DecodeStyleName(aAttrValue) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_REMOVE_ANY_NAMESPACE_PREFIX:
OSL_ENSURE( IsXMLToken( aLocalName, XML_CLASS ),
"unexpected class token" );
{
OUString aChartClass;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName(
rAttrValue,
&aChartClass );
if( XML_NAMESPACE_CHART == nPrefix )
{
pMutableAttrList->SetValueByIndex( i, aChartClass );
}
else if ( XML_NAMESPACE_OOO == nPrefix )
{
pMutableAttrList->SetValueByIndex( i,
GetXMLToken(XML_ADD_IN ) );
aAddInName = aChartClass;
}
}
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
if( aAddInName.getLength() > 0 )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_CHART,
GetXMLToken( XML_ADD_IN_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aAddInName );
}
XMLTransformerContext::StartElement( xAttrList );
}
<commit_msg>INTEGRATION: CWS schoasis01 (1.2.78); FILE MERGED 2004/10/14 15:10:08 bm 1.2.78.1: warning removed<commit_after>/*************************************************************************
*
* $RCSfile: ChartOASISTContext.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-11-09 18:29:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_CHARTOASISTCONTEXT_HXX
#include "ChartOASISTContext.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
// -----------------------------------------------------------------------------
TYPEINIT1( XMLChartOASISTransformerContext, XMLTransformerContext );
XMLChartOASISTransformerContext::XMLChartOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLTransformerContext( rImp, rQName )
{
}
XMLChartOASISTransformerContext::~XMLChartOASISTransformerContext()
{
}
void XMLChartOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_CHART_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
OUString aAddInName;
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_IN2INCH:
{
OUString aAttrValue( rAttrValue );
if( XMLTransformerBase::ReplaceSingleInWithInch(
aAttrValue ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_DECODE_STYLE_NAME_REF:
{
OUString aAttrValue( rAttrValue );
if( GetTransformer().DecodeStyleName(aAttrValue) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_REMOVE_ANY_NAMESPACE_PREFIX:
OSL_ENSURE( IsXMLToken( aLocalName, XML_CLASS ),
"unexpected class token" );
{
if( XML_NAMESPACE_CHART == nPrefix )
{
pMutableAttrList->SetValueByIndex( i, aLocalName );
}
else if ( XML_NAMESPACE_OOO == nPrefix )
{
pMutableAttrList->SetValueByIndex( i,
GetXMLToken(XML_ADD_IN ) );
aAddInName = aLocalName;
}
}
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
if( aAddInName.getLength() > 0 )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_CHART,
GetXMLToken( XML_ADD_IN_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aAddInName );
}
XMLTransformerContext::StartElement( xAttrList );
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.