text
stringlengths
54
60.6k
<commit_before>92ee2bae-2d3e-11e5-89e0-c82a142b6f9b<commit_msg>9350cade-2d3e-11e5-a753-c82a142b6f9b<commit_after>9350cade-2d3e-11e5-a753-c82a142b6f9b<|endoftext|>
<commit_before>8d6dfd35-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd36-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd36-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>cb0431b8-35ca-11e5-90c1-6c40088e03e4<commit_msg>cb0ac500-35ca-11e5-b576-6c40088e03e4<commit_after>cb0ac500-35ca-11e5-b576-6c40088e03e4<|endoftext|>
<commit_before>77e0e9ec-2d53-11e5-baeb-247703a38240<commit_msg>77e168f4-2d53-11e5-baeb-247703a38240<commit_after>77e168f4-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>65836f14-2fa5-11e5-83f3-00012e3d3f12<commit_msg>658591f4-2fa5-11e5-a1c8-00012e3d3f12<commit_after>658591f4-2fa5-11e5-a1c8-00012e3d3f12<|endoftext|>
<commit_before>1f83d990-585b-11e5-a3d4-6c40088e03e4<commit_msg>1f8ae000-585b-11e5-b14e-6c40088e03e4<commit_after>1f8ae000-585b-11e5-b14e-6c40088e03e4<|endoftext|>
<commit_before>/* * pab.cpp * * Copyright (C) 1999 Don Sanders <dsanders@kde.org> */ #include "abbrowser.h" #include "browserentryeditor.h" #include <qkeycode.h> //#include <kfm.h> #include <kiconloader.h> #include <klocale.h> #include <kglobal.h> #include <kmenubar.h> #include <kconfig.h> #include "undo.h" #include "browserwidget.h" #include "entry.h" Pab::Pab() { setCaption( i18n( "Address Book Browser" )); document = new ContactEntryList(); view = new PabWidget( document, this, "Abbrowser" ); // tell the KTMainWindow that this is indeed the main widget setView(view); // create a popup menu -- in this case, the File menu QPopupMenu* p = new QPopupMenu; p->insertItem(i18n("&Sync"), this, SLOT(save()), CTRL+Key_S); p->insertItem(i18n("&New Contact"), this, SLOT(newContact()), CTRL+Key_N); /* p->insertItem(i18n("New &Group"), this, SLOT(newGroup()), CTRL+Key_G); */ p->insertSeparator(); p->insertItem(i18n("&Send Mail"), view, SLOT(sendMail())); p->insertSeparator(); p->insertItem(i18n("&Properties"), view, SLOT(properties())); p->insertItem(i18n("&Delete"), view, SLOT(clear()), Key_Delete); p->insertSeparator(); p->insertItem(i18n("&Quit"), kapp, SLOT(quit()), CTRL+Key_Q); edit = new QPopupMenu; undoId = edit->insertItem(i18n("Undo"), this, SLOT(undo())); redoId = edit->insertItem(i18n("Redo"), this, SLOT(redo())); edit->insertSeparator(); edit->insertItem(i18n("Cut"), view, SLOT(cut()), CTRL+Key_X); edit->insertItem(i18n("Copy"), view, SLOT(copy()), CTRL+Key_C); edit->insertItem(i18n("Paste"), view, SLOT(paste()), CTRL+Key_V); edit->insertSeparator(); edit->insertItem(i18n("Select All"), view, SLOT(selectAll()), CTRL+Key_A); edit->setItemEnabled( undoId, false ); edit->setItemEnabled( redoId, false ); QObject::connect( edit, SIGNAL( aboutToShow() ), this, SLOT( updateEditMenu() )); QPopupMenu* v = new QPopupMenu; v->insertItem(i18n("Choose Fields..."), view, SLOT(showSelectNameDialog()) ); v->insertItem(i18n("Options..."), view, SLOT(viewOptions()) ); v->insertSeparator(); v->insertItem(i18n("Restore defaults"), view, SLOT(defaultSettings()) ); // v->insertSeparator(); // v->insertItem(i18n("Refresh"), view, SLOT(refresh()), Key_F5 ); // put our newly created menu into the main menu bar menuBar()->insertItem(i18n("&File"), p); menuBar()->insertItem(i18n("&Edit"), edit); menuBar()->insertItem(i18n("&View"), v); menuBar()->insertSeparator(); // KDE will generate a short help menu automagically p = helpMenu( i18n("Abbrowser --- KDE Address Book\n\n" "(c) 2000AD The KDE PIM Team \n")); menuBar()->insertItem(i18n("&Help"), p); toolBar()->insertButton(BarIcon("filenew"), // icon 0, // button id SIGNAL(clicked()), // action this, SLOT(newContact()), // result i18n("Add a new entry")); // tooltip text toolBar()->insertButton(BarIcon("pencil"), // icon 0, // button id SIGNAL(clicked()), // action view, SLOT(properties()), // result i18n("Change this entry")); // tooltip text toolBar()->insertButton(BarIcon("eraser"), // icon 0, // button id SIGNAL(clicked()), // action view, SLOT(clear()), // result i18n("Remove this entry")); // tooltip text toolBar()->insertSeparator(); toolBar()->insertButton(BarIcon("filemail"), // icon 0, // button id SIGNAL(clicked()), // action view, SLOT(sendMail()), // result i18n("Send email")); // tooltip text toolBar()->setFullSize(true); // we do want a status bar enableStatusBar(); connect( kapp, SIGNAL( aboutToQuit() ), this, SLOT( saveConfig() ) ); resize( sizeHint() ); readConfig(); } void Pab::newContact() { ContactDialog *cd = new PabNewContactDialog( this, i18n( "Address Book Entry Editor" )); connect( cd, SIGNAL( add( ContactEntry* ) ), view, SLOT( addNewEntry( ContactEntry* ) )); cd->show(); } void Pab::addEmail( QString addr ) { view->addEntry( addr ); return; } void Pab::save() { document->commit(); document->refresh(); view->saveConfig(); view->readConfig(); view->reconstructListView(); //xxx document->save( "entries.txt" ); UndoStack::instance()->clear(); RedoStack::instance()->clear(); } void Pab::readConfig() { KConfig *config = kapp->config(); int w, h; config->setGroup("Geometry"); QString str = config->readEntry("Browser", ""); if (!str.isEmpty() && str.find(',')>=0) { sscanf(str,"%d,%d",&w,&h); resize(w,h); } } void Pab::saveConfig() { view->saveConfig(); KConfig *config = kapp->config(); config->setGroup("Geometry"); QRect r = geometry(); QString s; s.sprintf("%i,%i", r.width(), r.height()); config->writeEntry("Browser", s); config->sync(); } Pab::~Pab() { saveConfig(); delete document; } void Pab::saveCe() { debug( "saveCe()" ); //xxx ce->save( "entry.txt" ); } void Pab::saveProperties(KConfig *) { // the 'config' object points to the session managed // config file. anything you write here will be available // later when this app is restored //what I want to save //windowsize //background image/underlining color/alternating color1,2 //chosen fields //chosen fieldsWidths // e.g., config->writeEntry("key", var); } void Pab::readProperties(KConfig *) { // the 'config' object points to the session managed // config file. this function is automatically called whenever // the app is being restored. read in here whatever you wrote // in 'saveProperties' // e.g., var = config->readEntry("key"); } void Pab::undo() { debug( "Pab::undo()" ); UndoStack::instance()->undo(); } void Pab::redo() { RedoStack::instance()->redo(); } void Pab::updateEditMenu() { debug( "UpdateEditMenu()" ); UndoStack *undo = UndoStack::instance(); RedoStack *redo = RedoStack::instance(); if (undo->isEmpty()) edit->changeItem( undoId, i18n( "Undo" ) ); else edit->changeItem( undoId, i18n( "Undo" ) + " " + undo->top()->name() ); edit->setItemEnabled( undoId, !undo->isEmpty() ); if (redo->isEmpty()) edit->changeItem( redoId, i18n( "Redo" ) ); else edit->changeItem( redoId, i18n( "Redo" ) + " " + redo->top()->name() ); edit->setItemEnabled( redoId, !redo->isEmpty() ); } <commit_msg>Bug fix<commit_after>/* * pab.cpp * * Copyright (C) 1999 Don Sanders <dsanders@kde.org> */ #include "abbrowser.h" #include "browserentryeditor.h" #include <qkeycode.h> //#include <kfm.h> #include <kiconloader.h> #include <klocale.h> #include <kglobal.h> #include <kmenubar.h> #include <kconfig.h> #include "undo.h" #include "browserwidget.h" #include "entry.h" Pab::Pab() { setCaption( i18n( "Address Book Browser" )); document = new ContactEntryList(); view = new PabWidget( document, this, "Abbrowser" ); // tell the KTMainWindow that this is indeed the main widget setView(view); // create a popup menu -- in this case, the File menu QPopupMenu* p = new QPopupMenu; p->insertItem(i18n("&Sync"), this, SLOT(save()), CTRL+Key_S); p->insertItem(i18n("&New Contact"), this, SLOT(newContact()), CTRL+Key_N); /* p->insertItem(i18n("New &Group"), this, SLOT(newGroup()), CTRL+Key_G); */ p->insertSeparator(); p->insertItem(i18n("&Send Mail"), view, SLOT(sendMail())); p->insertSeparator(); p->insertItem(i18n("&Properties"), view, SLOT(properties())); p->insertItem(i18n("&Delete"), view, SLOT(clear()), Key_Delete); p->insertSeparator(); p->insertItem(i18n("&Quit"), kapp, SLOT(quit()), CTRL+Key_Q); edit = new QPopupMenu; undoId = edit->insertItem(i18n("Undo"), this, SLOT(undo())); redoId = edit->insertItem(i18n("Redo"), this, SLOT(redo())); edit->insertSeparator(); edit->insertItem(i18n("Cut"), view, SLOT(cut()), CTRL+Key_X); edit->insertItem(i18n("Copy"), view, SLOT(copy()), CTRL+Key_C); edit->insertItem(i18n("Paste"), view, SLOT(paste()), CTRL+Key_V); edit->insertSeparator(); edit->insertItem(i18n("Select All"), view, SLOT(selectAll()), CTRL+Key_A); edit->setItemEnabled( undoId, false ); edit->setItemEnabled( redoId, false ); QObject::connect( edit, SIGNAL( aboutToShow() ), this, SLOT( updateEditMenu() )); QPopupMenu* v = new QPopupMenu; v->insertItem(i18n("Choose Fields..."), view, SLOT(showSelectNameDialog()) ); v->insertItem(i18n("Options..."), view, SLOT(viewOptions()) ); v->insertSeparator(); v->insertItem(i18n("Restore defaults"), view, SLOT(defaultSettings()) ); // v->insertSeparator(); // v->insertItem(i18n("Refresh"), view, SLOT(refresh()), Key_F5 ); // put our newly created menu into the main menu bar menuBar()->insertItem(i18n("&File"), p); menuBar()->insertItem(i18n("&Edit"), edit); menuBar()->insertItem(i18n("&View"), v); menuBar()->insertSeparator(); // KDE will generate a short help menu automagically p = helpMenu( i18n("Abbrowser --- KDE Address Book\n\n" "(c) 2000AD The KDE PIM Team \n")); menuBar()->insertItem(i18n("&Help"), p); toolBar()->insertButton(BarIcon("filenew"), // icon 0, // button id SIGNAL(clicked()), // action this, SLOT(newContact()), // result i18n("Add a new entry")); // tooltip text toolBar()->insertButton(BarIcon("pencil"), // icon 0, // button id SIGNAL(clicked()), // action view, SLOT(properties()), // result i18n("Change this entry")); // tooltip text toolBar()->insertButton(BarIcon("eraser"), // icon 0, // button id SIGNAL(clicked()), // action view, SLOT(clear()), // result i18n("Remove this entry")); // tooltip text toolBar()->insertSeparator(); toolBar()->insertButton(BarIcon("filemail"), // icon 0, // button id SIGNAL(clicked()), // action view, SLOT(sendMail()), // result i18n("Send email")); // tooltip text toolBar()->setFullSize(true); // we do want a status bar enableStatusBar(); connect( kapp, SIGNAL( aboutToQuit() ), this, SLOT( saveConfig() ) ); resize( sizeHint() ); readConfig(); } void Pab::newContact() { ContactDialog *cd = new PabNewContactDialog( this, i18n( "Address Book Entry Editor" )); connect( cd, SIGNAL( add( ContactEntry* ) ), view, SLOT( addNewEntry( ContactEntry* ) )); cd->show(); } void Pab::addEmail( QString addr ) { view->addEmail( addr ); return; } void Pab::save() { document->commit(); document->refresh(); view->saveConfig(); view->readConfig(); view->reconstructListView(); //xxx document->save( "entries.txt" ); UndoStack::instance()->clear(); RedoStack::instance()->clear(); } void Pab::readConfig() { KConfig *config = kapp->config(); int w, h; config->setGroup("Geometry"); QString str = config->readEntry("Browser", ""); if (!str.isEmpty() && str.find(',')>=0) { sscanf(str,"%d,%d",&w,&h); resize(w,h); } } void Pab::saveConfig() { view->saveConfig(); KConfig *config = kapp->config(); config->setGroup("Geometry"); QRect r = geometry(); QString s; s.sprintf("%i,%i", r.width(), r.height()); config->writeEntry("Browser", s); config->sync(); } Pab::~Pab() { saveConfig(); delete document; } void Pab::saveCe() { debug( "saveCe()" ); //xxx ce->save( "entry.txt" ); } void Pab::saveProperties(KConfig *) { // the 'config' object points to the session managed // config file. anything you write here will be available // later when this app is restored //what I want to save //windowsize //background image/underlining color/alternating color1,2 //chosen fields //chosen fieldsWidths // e.g., config->writeEntry("key", var); } void Pab::readProperties(KConfig *) { // the 'config' object points to the session managed // config file. this function is automatically called whenever // the app is being restored. read in here whatever you wrote // in 'saveProperties' // e.g., var = config->readEntry("key"); } void Pab::undo() { debug( "Pab::undo()" ); UndoStack::instance()->undo(); } void Pab::redo() { RedoStack::instance()->redo(); } void Pab::updateEditMenu() { debug( "UpdateEditMenu()" ); UndoStack *undo = UndoStack::instance(); RedoStack *redo = RedoStack::instance(); if (undo->isEmpty()) edit->changeItem( undoId, i18n( "Undo" ) ); else edit->changeItem( undoId, i18n( "Undo" ) + " " + undo->top()->name() ); edit->setItemEnabled( undoId, !undo->isEmpty() ); if (redo->isEmpty()) edit->changeItem( redoId, i18n( "Redo" ) ); else edit->changeItem( redoId, i18n( "Redo" ) + " " + redo->top()->name() ); edit->setItemEnabled( redoId, !redo->isEmpty() ); } <|endoftext|>
<commit_before>69d05b02-2fa5-11e5-b069-00012e3d3f12<commit_msg>69d22fc2-2fa5-11e5-b6ac-00012e3d3f12<commit_after>69d22fc2-2fa5-11e5-b6ac-00012e3d3f12<|endoftext|>
<commit_before>#include "html5viewer/html5viewer.h" #include "ClientWrapper.hpp" #include "Utilities.hpp" #include <boost/thread.hpp> #include <bts/blockchain/config.hpp> #include <signal.h> #include <QApplication> #include <QSettings> #include <QPixmap> #include <QErrorMessage> #include <QSplashScreen> #include <QDir> #include <QWebSettings> #include <QWebPage> #include <QWebFrame> #include <QJsonDocument> #include <QGraphicsWebView> #include <QTimer> #include <QAuthenticator> #include <QNetworkReply> #include <QResource> #include <QGraphicsWidget> #include <QMainWindow> #include <QMenuBar> #include <QLayout> #include <boost/program_options.hpp> #include <bts/client/client.hpp> #include <bts/net/upnp.hpp> #include <bts/blockchain/chain_database.hpp> #include <bts/rpc/rpc_server.hpp> #include <bts/cli/cli.hpp> #include <bts/utilities/git_revision.hpp> #include <fc/filesystem.hpp> #include <fc/thread/thread.hpp> #include <fc/log/file_appender.hpp> #include <fc/log/logger_config.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/git_revision.hpp> #include <fc/io/json.hpp> #include <fc/log/logger_config.hpp> #include <boost/iostreams/tee.hpp> #include <boost/iostreams/stream.hpp> #include <fstream> #include <iostream> #include <iomanip> #ifdef NDEBUG #include "config_prod.hpp" #else #include "config_dev.hpp" #endif int main( int argc, char** argv ) { QCoreApplication::setOrganizationName( "BitShares" ); QCoreApplication::setOrganizationDomain( "bitshares.org" ); QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME ); QApplication app(argc, argv); app.setWindowIcon(QIcon(":/images/qtapp.ico")); auto menuBar = new QMenuBar(nullptr); auto fileMenu = menuBar->addMenu("File"); fileMenu->addAction("&Import Wallet")->setEnabled(false); fileMenu->addAction("&Export Wallet")->setEnabled(false); fileMenu->addAction("&Change Password")->setEnabled(false); fileMenu->addAction("&Quit", &app, SLOT(quit())); menuBar->show(); QTimer fc_tasks; fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } ); fc_tasks.start(33); QPixmap pixmap(":/images/splash_screen.jpg"); QSplashScreen splash(pixmap); splash.showMessage(QObject::tr("Loading configuration..."), Qt::AlignCenter | Qt::AlignBottom, Qt::white); splash.show(); QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false ); QMainWindow mainWindow; auto viewer = new Html5Viewer; ClientWrapper client; viewer->webView()->page()->settings()->setAttribute( QWebSettings::PluginsEnabled, false ); viewer->setOrientation(Html5Viewer::ScreenOrientationAuto); viewer->webView()->setAcceptHoverEvents(true); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", &client); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("utilities", new Utilities, QWebFrame::ScriptOwnership); viewer->webView()->setFocus(Qt::ActiveWindowFocusReason); mainWindow.resize(1200,800); mainWindow.setCentralWidget(viewer); QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired, [&client](QNetworkReply*, QAuthenticator *auth) { auth->setUser(client.http_url().userName()); auth->setPassword(client.http_url().password()); }); client.connect(&client, &ClientWrapper::initialized, [&viewer,&client]() { ilog( "Client initialized; loading web interface from ${url}", ("url", client.http_url().toString().toStdString()) ); viewer->webView()->load(client.http_url()); }); viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [&mainWindow,&splash](bool ok) { ilog( "Webview loaded: ${status}", ("status", ok) ); mainWindow.show(); splash.finish(&mainWindow); }); client.connect(&client, &ClientWrapper::error, [&](QString errorString) { splash.showMessage(errorString, Qt::AlignCenter | Qt::AlignBottom, Qt::white); fc::usleep( fc::seconds(3) ); }); try { client.initialize(); return app.exec(); } catch ( const fc::exception& e) { elog( "${e}", ("e",e.to_detail_string() ) ); QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() ); } } <commit_msg>Add Accounts menu<commit_after>#include "html5viewer/html5viewer.h" #include "ClientWrapper.hpp" #include "Utilities.hpp" #include <boost/thread.hpp> #include <bts/blockchain/config.hpp> #include <signal.h> #include <QApplication> #include <QSettings> #include <QPixmap> #include <QErrorMessage> #include <QSplashScreen> #include <QDir> #include <QWebSettings> #include <QWebPage> #include <QWebFrame> #include <QJsonDocument> #include <QGraphicsWebView> #include <QTimer> #include <QAuthenticator> #include <QNetworkReply> #include <QResource> #include <QGraphicsWidget> #include <QMainWindow> #include <QMenuBar> #include <QLayout> #include <boost/program_options.hpp> #include <bts/client/client.hpp> #include <bts/net/upnp.hpp> #include <bts/blockchain/chain_database.hpp> #include <bts/rpc/rpc_server.hpp> #include <bts/cli/cli.hpp> #include <bts/utilities/git_revision.hpp> #include <fc/filesystem.hpp> #include <fc/thread/thread.hpp> #include <fc/log/file_appender.hpp> #include <fc/log/logger_config.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/git_revision.hpp> #include <fc/io/json.hpp> #include <fc/log/logger_config.hpp> #include <boost/iostreams/tee.hpp> #include <boost/iostreams/stream.hpp> #include <fstream> #include <iostream> #include <iomanip> #ifdef NDEBUG #include "config_prod.hpp" #else #include "config_dev.hpp" #endif int main( int argc, char** argv ) { QCoreApplication::setOrganizationName( "BitShares" ); QCoreApplication::setOrganizationDomain( "bitshares.org" ); QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME ); QApplication app(argc, argv); app.setWindowIcon(QIcon(":/images/qtapp.ico")); auto menuBar = new QMenuBar(nullptr); auto fileMenu = menuBar->addMenu("&File"); fileMenu->addAction("&Import Wallet")->setEnabled(false); fileMenu->addAction("&Export Wallet")->setEnabled(false); fileMenu->addAction("&Change Password")->setEnabled(false); fileMenu->addAction("&Quit", &app, SLOT(quit())); auto accountMenu = menuBar->addMenu("&Accounts"); //We'll populate this menu below, in the handler for loadFinished //We don't know the URL yet! menuBar->show(); QTimer fc_tasks; fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } ); fc_tasks.start(33); QPixmap pixmap(":/images/splash_screen.jpg"); QSplashScreen splash(pixmap); splash.showMessage(QObject::tr("Loading configuration..."), Qt::AlignCenter | Qt::AlignBottom, Qt::white); splash.show(); QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false ); QMainWindow mainWindow; auto viewer = new Html5Viewer; ClientWrapper client; viewer->webView()->page()->settings()->setAttribute( QWebSettings::PluginsEnabled, false ); viewer->setOrientation(Html5Viewer::ScreenOrientationAuto); viewer->webView()->setAcceptHoverEvents(true); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", &client); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("account_menu", accountMenu); viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("utilities", new Utilities, QWebFrame::ScriptOwnership); viewer->webView()->setFocus(Qt::ActiveWindowFocusReason); mainWindow.resize(1200,800); mainWindow.setCentralWidget(viewer); QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired, [&client](QNetworkReply*, QAuthenticator *auth) { auth->setUser(client.http_url().userName()); auth->setPassword(client.http_url().password()); }); client.connect(&client, &ClientWrapper::initialized, [&viewer,&client,accountMenu]() { ilog( "Client initialized; loading web interface from ${url}", ("url", client.http_url().toString().toStdString()) ); viewer->webView()->load(client.http_url()); //Now we know the URL of the app, so we can create the items in the Accounts menu QObject::connect(accountMenu->addAction("&Go to My Accounts"), &QAction::triggered, [&viewer,&client](){ viewer->loadUrl(client.http_url().toString() + "/#/accounts"); }); QObject::connect(accountMenu->addAction("&Create Account"), &QAction::triggered, [&viewer,&client](){ viewer->loadUrl(client.http_url().toString() + "/#/create/account"); }); accountMenu->addAction("&Import Account")->setEnabled(false); }); viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [&mainWindow,&splash,&viewer](bool ok) { ilog( "Webview loaded: ${status}", ("status", ok) ); mainWindow.show(); splash.finish(&mainWindow); }); client.connect(&client, &ClientWrapper::error, [&](QString errorString) { splash.showMessage(errorString, Qt::AlignCenter | Qt::AlignBottom, Qt::white); fc::usleep( fc::seconds(3) ); }); try { client.initialize(); return app.exec(); } catch ( const fc::exception& e) { elog( "${e}", ("e",e.to_detail_string() ) ); QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() ); } } <|endoftext|>
<commit_before>f2afa107-327f-11e5-a75e-9cf387a8033e<commit_msg>f2b58e61-327f-11e5-a10a-9cf387a8033e<commit_after>f2b58e61-327f-11e5-a10a-9cf387a8033e<|endoftext|>
<commit_before>125b0264-585b-11e5-9104-6c40088e03e4<commit_msg>12629db4-585b-11e5-aa7e-6c40088e03e4<commit_after>12629db4-585b-11e5-aa7e-6c40088e03e4<|endoftext|>
<commit_before>5ae7ecf9-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ecfa-2d16-11e5-af21-0401358ea401<commit_after>5ae7ecfa-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>b5e8c3f3-2e4f-11e5-9da7-28cfe91dbc4b<commit_msg>b5f0115c-2e4f-11e5-9b98-28cfe91dbc4b<commit_after>b5f0115c-2e4f-11e5-9b98-28cfe91dbc4b<|endoftext|>
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved. /** \file main.cpp * * \brief Contains main function, and possibly some small amount * of other code, relating to Phatbooks application. * * \author Matthew Harvey * \date 04 July 2012. * * Copyright (c) 2012, Matthew Harvey. All rights reserved. */ // TODO HIGH PRIORITY Tooltips aren't showing on Windows. // TODO Make it so the user can toggle logging level via the GUI. // TODO Make the installer create an association on the user's system // between the Phatbooks file extension and the Phatbooks application. // See CMake book, page. 162. // TODO (For GUI). Users will probably expect // right-clicking to cause a context-dependent menu to pop up. // TODO The application should automatically create a zipped backup // file so that the session can be recovered if something goes wrong. // TODO The database file should perhaps have a checksum to guard // against its contents changing other than via the application. // TODO Facilitate automatic checking for updates from user's // machine, as well as easy process for providing updates // via NSIS. It appears that the default configuration of CPack/NSIS is // such that updates will not overwrite existing files. Some manual NSIS // scripting may be required to enable this. Also take into account that // the user may have to restart their computer in the event that they have // files open while the installer (or "updater") is running (although I // \e think that the default configuration under CPack does this // automatically). // TODO Write the licence. // TODO Ensure that option for the user to lauch directly from the // installer, works correctly. // TODO Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. // TODO On Fedora, recompile and install wxWidgets with an additional // configure flag, viz. --with-gnomeprint (sp?). // TODO Set the version number in a single location and find a way // to ensure this is reflected consistently everywhere it appears // (website, installer, licence text etc.). // TODO We need a proper solution to the potential for integer overflow. // Mostly we use jewel::Decimal arithmetic - which will throw if unsafe - // but we're not actually handling these exceptions for the user. The // program would just crash. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. #include "application.hpp" #include "string_conv.hpp" #include "graphical_session.hpp" #include <boost/filesystem.hpp> #include <boost/scoped_ptr.hpp> #include <jewel/assert.hpp> #include <jewel/exception.hpp> #include <jewel/log.hpp> #include <jewel/on_windows.hpp> #include <tclap/CmdLine.h> #include <wx/log.h> #include <wx/snglinst.h> #include <wx/string.h> #include <wx/utils.h> #include <cstdlib> #include <cstring> #include <exception> #include <fstream> #include <ios> #include <iostream> #include <string> #include <typeinfo> using boost::scoped_ptr; using jewel::Log; using phatbooks::Application; using phatbooks::gui::GraphicalSession; using phatbooks::wx_to_std8; using std::abort; using std::cerr; using std::clog; using std::cout; using std::endl; using std::ofstream; using std::set_terminate; using std::string; using std::strlen; using std::set_terminate; using TCLAP::ArgException; using TCLAP::CmdLine; using TCLAP::UnlabeledValueArg; namespace filesystem = boost::filesystem; namespace { void flush_standard_output_streams() { JEWEL_LOG_MESSAGE(Log::info, "Flushing standard output streams."); cerr.flush(); clog.flush(); cout.flush(); JEWEL_LOG_MESSAGE(Log::info, "Flushed standard output streams."); return; } void my_terminate_handler() { JEWEL_LOG_MESSAGE(Log::error, "Entered terminate handler."); // TODO HIGH PRIORITY This seems like a good idea, but is there // a hidden catch? (Custom terminate handling should not be done // lightly...) // flush_standard_output_streams(); abort(); } bool ensure_dir_exists(string const& p_directory) { if (filesystem::exists(p_directory)) { return true; } return filesystem::create_directory(p_directory); } void configure_logging() { Log::set_threshold(Log::trace); # ifdef JEWEL_ON_WINDOWS // TODO What if this directory doesn't exist? Will it be created? // Do we need to create it in the installer? string const a("C:\\ProgramData\\"); string const b("Phatbooks\\"); string const c("logs\\"); bool ok = ensure_dir_exists(a); if (ok) ok = ensure_dir_exists(a + b); if (ok) ok = ensure_dir_exists(a + b + c); if (!ok) { cerr << "Could not create log file." << endl; return; } string const log_dir = a + b + c; # else string const log_dir = "/tmp/"; # endif // JEWEL_ON_WINDOWS string const log_name = log_dir + wx_to_std8(Application::application_name()) + ".log"; Log::set_filepath(log_name); return; } } // end anonymous namespace int main(int argc, char** argv) { try { configure_logging(); JEWEL_LOG_MESSAGE(Log::info, "Configured logging."); set_terminate(my_terminate_handler); JEWEL_LOG_MESSAGE ( Log::info, "Terminate handler has been set to my_terminate_handler." ); // Enable exceptions on standard output streams.... // On second thought, let's not do this. What if some distant // library function writes to std::cerr for example in its // destructor, for some reason, relying on this action being // exception-safe? Let's keep the standard behaviour // (i.e. let's comment out the below). // cout.exceptions(std::ios::badbit | std::ios::failbit); // clog.exceptions(std::ios::badbit | std::ios::failbit); // cerr.exceptions(std::ios::badbit | std::ios::failbit); // Prevent multiple instances run by the same user JEWEL_LOG_TRACE(); bool another_is_running = false; wxString const app_name = Application::application_name(); wxString const instance_identifier = app_name + wxString::Format("-%s", wxGetUserId().c_str()); scoped_ptr<wxSingleInstanceChecker> const m_checker ( new wxSingleInstanceChecker(instance_identifier) ); if (m_checker->IsAnotherRunning()) { another_is_running = true; // to which we will respond below } // Process command line arguments JEWEL_LOG_TRACE(); CmdLine cmd(wx_to_std8(Application::application_name())); UnlabeledValueArg<string> filepath_arg ( "FILE", "File to open or create", false, "", "string" ); cmd.add(filepath_arg); cmd.parse(argc, argv); string const filepath_str = filepath_arg.getValue(); GraphicalSession graphical_session; if (another_is_running) { // We tell the GraphicalSession of an existing instance // so that it can this session with a graphical // message box, which it can only do after wxWidgets' // initialization code has run. graphical_session.notify_existing_application_instance(); } // Note phatbooks::Session currently requires a std::string to // be passed here. // TODO This may require a wstring or wxString if we want to // support non-ASCII filenames on Windows. We would need to // change the interface with phatbooks::Session. if (filepath_str.empty()) { return graphical_session.run(); } JEWEL_ASSERT (!filepath_str.empty()); return graphical_session.run(filepath_str); } catch (ArgException& e) { JEWEL_LOG_MESSAGE(Log::error, "ArgException e caught in main."); JEWEL_LOG_VALUE(Log::error, e.error()); JEWEL_LOG_VALUE(Log::error, e.argId()); cerr << "error: " << e.error() << " for arg " << e.argId() << endl; flush_standard_output_streams(); return 1; } catch (jewel::Exception& e) { JEWEL_LOG_MESSAGE ( Log::error, "jewel::Exception e caught in main." ); JEWEL_LOG_VALUE(Log::error, e); cerr << e << endl; if (strlen(e.type()) == 0) { JEWEL_LOG_VALUE(Log::error, typeid(e).name()); cerr << "typeid(e).name(): " << typeid(e).name() << '\n' << endl; } flush_standard_output_streams(); JEWEL_LOG_MESSAGE(Log::error, "Rethrowing e."); throw; } catch (std::exception& e) { JEWEL_LOG_MESSAGE(Log::error, "std::exception e caught in main."); JEWEL_LOG_VALUE(Log::error, typeid(e).name()); JEWEL_LOG_VALUE(Log::error, e.what()); cerr << "EXCEPTION:" << endl; cerr << "typeid(e).name(): " << typeid(e).name() << endl; cerr << "e.what(): " << e.what() << endl; flush_standard_output_streams(); JEWEL_LOG_MESSAGE(Log::error, "Rethrowing e."); throw; } // This is necessary to guarantee the stack is fully unwound no // matter what exception is thrown - we're not ONLY doing it // for the logging and flushing. catch (...) { JEWEL_LOG_MESSAGE(Log::error, "Unknown exception caught in main."); cerr << "Unknown exception caught in main." << endl; flush_standard_output_streams(); JEWEL_LOG_MESSAGE(Log::error, "Rethrowing unknown exception."); throw; } } <commit_msg>Made it so that program returns with error message if attempt is made to run from console passing as command line argument a file that does not already exist. Otherwise the program just crashes anyway; but this way it crashes with a nicer error message. We don't intend to allow the user to create a NEW Phatbooks file from the command line - must use the GUI for this.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved. /** \file main.cpp * * \brief Contains main function, and possibly some small amount * of other code, relating to Phatbooks application. * * \author Matthew Harvey * \date 04 July 2012. * * Copyright (c) 2012, Matthew Harvey. All rights reserved. */ // TODO HIGH PRIORITY Tooltips aren't showing on Windows. // TODO Make it so the user can toggle logging level via the GUI. // TODO Make the installer create an association on the user's system // between the Phatbooks file extension and the Phatbooks application. // See CMake book, page. 162. // TODO (For GUI). Users will probably expect // right-clicking to cause a context-dependent menu to pop up. // TODO The application should automatically create a zipped backup // file so that the session can be recovered if something goes wrong. // TODO The database file should perhaps have a checksum to guard // against its contents changing other than via the application. // TODO Facilitate automatic checking for updates from user's // machine, as well as easy process for providing updates // via NSIS. It appears that the default configuration of CPack/NSIS is // such that updates will not overwrite existing files. Some manual NSIS // scripting may be required to enable this. Also take into account that // the user may have to restart their computer in the event that they have // files open while the installer (or "updater") is running (although I // \e think that the default configuration under CPack does this // automatically). // TODO Write the licence. // TODO Ensure that option for the user to lauch directly from the // installer, works correctly. // TODO Create a decent icon for the application. We want this // in both .ico form (for Windows executable icon) and .xpm // form (for icon for Frame). Note, when I exported my // "token icon" using GIMP to .ico format, and later used this // to create a double-clickable icon in Windows, only the text // on the icon appeared, and the background image became // transparent for some reason. Furthermore, when set as the // large in-windows icon in the CPack/NSIS installer, the icon // wasn't showing at all. // TODO On Fedora, recompile and install wxWidgets with an additional // configure flag, viz. --with-gnomeprint (sp?). // TODO Set the version number in a single location and find a way // to ensure this is reflected consistently everywhere it appears // (website, installer, licence text etc.). // TODO We need a proper solution to the potential for integer overflow. // Mostly we use jewel::Decimal arithmetic - which will throw if unsafe - // but we're not actually handling these exceptions for the user. The // program would just crash. // TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen // i.e. laptop. #include "application.hpp" #include "string_conv.hpp" #include "graphical_session.hpp" #include <boost/filesystem.hpp> #include <boost/scoped_ptr.hpp> #include <jewel/assert.hpp> #include <jewel/exception.hpp> #include <jewel/log.hpp> #include <jewel/on_windows.hpp> #include <tclap/CmdLine.h> #include <wx/log.h> #include <wx/snglinst.h> #include <wx/string.h> #include <wx/utils.h> #include <cstdlib> #include <cstring> #include <exception> #include <fstream> #include <ios> #include <iostream> #include <string> #include <typeinfo> using boost::scoped_ptr; using jewel::Log; using phatbooks::Application; using phatbooks::gui::GraphicalSession; using phatbooks::wx_to_std8; using std::abort; using std::cerr; using std::clog; using std::cout; using std::endl; using std::ofstream; using std::set_terminate; using std::string; using std::strlen; using std::set_terminate; using TCLAP::ArgException; using TCLAP::CmdLine; using TCLAP::UnlabeledValueArg; namespace filesystem = boost::filesystem; namespace { void flush_standard_output_streams() { JEWEL_LOG_MESSAGE(Log::info, "Flushing standard output streams."); cerr.flush(); clog.flush(); cout.flush(); JEWEL_LOG_MESSAGE(Log::info, "Flushed standard output streams."); return; } void my_terminate_handler() { JEWEL_LOG_MESSAGE(Log::error, "Entered terminate handler."); // TODO HIGH PRIORITY This seems like a good idea, but is there // a hidden catch? (Custom terminate handling should not be done // lightly...) // flush_standard_output_streams(); abort(); } bool ensure_dir_exists(string const& p_directory) { if (filesystem::exists(p_directory)) { return true; } return filesystem::create_directory(p_directory); } void configure_logging() { Log::set_threshold(Log::trace); # ifdef JEWEL_ON_WINDOWS // TODO What if this directory doesn't exist? Will it be created? // Do we need to create it in the installer? string const a("C:\\ProgramData\\"); string const b("Phatbooks\\"); string const c("logs\\"); bool ok = ensure_dir_exists(a); if (ok) ok = ensure_dir_exists(a + b); if (ok) ok = ensure_dir_exists(a + b + c); if (!ok) { cerr << "Could not create log file." << endl; return; } string const log_dir = a + b + c; # else string const log_dir = "/tmp/"; # endif // JEWEL_ON_WINDOWS string const log_name = log_dir + wx_to_std8(Application::application_name()) + ".log"; Log::set_filepath(log_name); return; } } // end anonymous namespace int main(int argc, char** argv) { try { configure_logging(); JEWEL_LOG_MESSAGE(Log::info, "Configured logging."); set_terminate(my_terminate_handler); JEWEL_LOG_MESSAGE ( Log::info, "Terminate handler has been set to my_terminate_handler." ); // Enable exceptions on standard output streams.... // On second thought, let's not do this. What if some distant // library function writes to std::cerr for example in its // destructor, for some reason, relying on this action being // exception-safe? Let's keep the standard behaviour // (i.e. let's comment out the below). // cout.exceptions(std::ios::badbit | std::ios::failbit); // clog.exceptions(std::ios::badbit | std::ios::failbit); // cerr.exceptions(std::ios::badbit | std::ios::failbit); // Prevent multiple instances run by the same user JEWEL_LOG_TRACE(); bool another_is_running = false; wxString const app_name = Application::application_name(); wxString const instance_identifier = app_name + wxString::Format("-%s", wxGetUserId().c_str()); scoped_ptr<wxSingleInstanceChecker> const m_checker ( new wxSingleInstanceChecker(instance_identifier) ); if (m_checker->IsAnotherRunning()) { another_is_running = true; // to which we will respond below } // Process command line arguments JEWEL_LOG_TRACE(); CmdLine cmd(wx_to_std8(Application::application_name())); UnlabeledValueArg<string> filepath_arg ( "FILE", "File to open", false, "", "string" ); cmd.add(filepath_arg); cmd.parse(argc, argv); string const filepath_str = filepath_arg.getValue(); if (!filepath_str.empty() && !filesystem::exists(filepath_str)) { cerr << "File does not exist.\n" << "To create a new file using the GUI, run with no command " << "line arguments." << endl; return 1; } GraphicalSession graphical_session; if (another_is_running) { // We tell the GraphicalSession of an existing instance // so that it can this session with a graphical // message box, which it can only do after wxWidgets' // initialization code has run. graphical_session.notify_existing_application_instance(); } // Note phatbooks::Session currently requires a std::string to // be passed here. // TODO This may require a wstring or wxString if we want to // support non-ASCII filenames on Windows. We would need to // change the interface with phatbooks::Session. if (filepath_str.empty()) { return graphical_session.run(); } JEWEL_ASSERT (!filepath_str.empty()); return graphical_session.run(filepath_str); } catch (ArgException& e) { JEWEL_LOG_MESSAGE(Log::error, "ArgException e caught in main."); JEWEL_LOG_VALUE(Log::error, e.error()); JEWEL_LOG_VALUE(Log::error, e.argId()); cerr << "error: " << e.error() << " for arg " << e.argId() << endl; flush_standard_output_streams(); return 1; } catch (jewel::Exception& e) { JEWEL_LOG_MESSAGE ( Log::error, "jewel::Exception e caught in main." ); JEWEL_LOG_VALUE(Log::error, e); cerr << e << endl; if (strlen(e.type()) == 0) { JEWEL_LOG_VALUE(Log::error, typeid(e).name()); cerr << "typeid(e).name(): " << typeid(e).name() << '\n' << endl; } flush_standard_output_streams(); JEWEL_LOG_MESSAGE(Log::error, "Rethrowing e."); throw; } catch (std::exception& e) { JEWEL_LOG_MESSAGE(Log::error, "std::exception e caught in main."); JEWEL_LOG_VALUE(Log::error, typeid(e).name()); JEWEL_LOG_VALUE(Log::error, e.what()); cerr << "EXCEPTION:" << endl; cerr << "typeid(e).name(): " << typeid(e).name() << endl; cerr << "e.what(): " << e.what() << endl; flush_standard_output_streams(); JEWEL_LOG_MESSAGE(Log::error, "Rethrowing e."); throw; } // This is necessary to guarantee the stack is fully unwound no // matter what exception is thrown - we're not ONLY doing it // for the logging and flushing. catch (...) { JEWEL_LOG_MESSAGE(Log::error, "Unknown exception caught in main."); cerr << "Unknown exception caught in main." << endl; flush_standard_output_streams(); JEWEL_LOG_MESSAGE(Log::error, "Rethrowing unknown exception."); throw; } } <|endoftext|>
<commit_before>13bc61d0-2f67-11e5-ae13-6c40088e03e4<commit_msg>13c4076c-2f67-11e5-a50c-6c40088e03e4<commit_after>13c4076c-2f67-11e5-a50c-6c40088e03e4<|endoftext|>
<commit_before>a97a00b8-2e4f-11e5-8484-28cfe91dbc4b<commit_msg>a9808b7a-2e4f-11e5-a256-28cfe91dbc4b<commit_after>a9808b7a-2e4f-11e5-a256-28cfe91dbc4b<|endoftext|>
<commit_before>442859ae-5216-11e5-8a98-6c40088e03e4<commit_msg>442ff6e6-5216-11e5-9a97-6c40088e03e4<commit_after>442ff6e6-5216-11e5-9a97-6c40088e03e4<|endoftext|>
<commit_before>38722402-ad5a-11e7-acbd-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>38df7573-ad5a-11e7-841c-ac87a332f658<|endoftext|>
<commit_before>68b463b6-2fa5-11e5-b940-00012e3d3f12<commit_msg>68b63874-2fa5-11e5-b3cb-00012e3d3f12<commit_after>68b63874-2fa5-11e5-b3cb-00012e3d3f12<|endoftext|>
<commit_before>4e6380d0-5216-11e5-b7de-6c40088e03e4<commit_msg>4e6bcc70-5216-11e5-87d9-6c40088e03e4<commit_after>4e6bcc70-5216-11e5-87d9-6c40088e03e4<|endoftext|>
<commit_before>e80d2a9c-313a-11e5-babe-3c15c2e10482<commit_msg>e81314c0-313a-11e5-8bb6-3c15c2e10482<commit_after>e81314c0-313a-11e5-8bb6-3c15c2e10482<|endoftext|>
<commit_before>#include <QtGui/QApplication> #include "ImageVis3D.h" int main(int argc, char* argv[]) { QApplication app( argc, argv ); MainWindow mainWindow(0, Qt::Window); mainWindow.show(); return app.exec(); }<commit_msg><commit_after>#include <QtGui/QApplication> #include "ImageVis3D.h" int main(int argc, char* argv[]) { QApplication app( argc, argv ); MainWindow mainWindow(0, Qt::Window); mainWindow.show(); return app.exec(); } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main(){ ddddddddddd cout << "this is jenkins test" << endl; } <commit_msg>fix build error<commit_after>#include <iostream> using namespace std; int main(){ cout << "this is jenkins test" << endl; } <|endoftext|>
<commit_before>8d6dfc93-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfc94-2d14-11e5-af21-0401358ea401<commit_after>8d6dfc94-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>ab7ae724-35ca-11e5-bc47-6c40088e03e4<commit_msg>ab81e678-35ca-11e5-acde-6c40088e03e4<commit_after>ab81e678-35ca-11e5-acde-6c40088e03e4<|endoftext|>
<commit_before>f3068b54-585a-11e5-9f45-6c40088e03e4<commit_msg>f30d1b0c-585a-11e5-a714-6c40088e03e4<commit_after>f30d1b0c-585a-11e5-a714-6c40088e03e4<|endoftext|>
<commit_before>5bf67432-2d16-11e5-af21-0401358ea401<commit_msg>5bf67433-2d16-11e5-af21-0401358ea401<commit_after>5bf67433-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8b33252c-2d14-11e5-af21-0401358ea401<commit_msg>8b33252d-2d14-11e5-af21-0401358ea401<commit_after>8b33252d-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>6e589f0c-2e3a-11e5-ab80-c03896053bdd<commit_msg>6e69b92e-2e3a-11e5-a820-c03896053bdd<commit_after>6e69b92e-2e3a-11e5-a820-c03896053bdd<|endoftext|>
<commit_before>#include <iostream> #include <ring.h> #include <array> #include <utility> int main() { using namespace std::rel_ops; std::array< int, 3 > baseArray; sg14::ring_span< int > ringBuffer( baseArray.begin(), baseArray.end() ); ringBuffer.push_back( 1 ); ringBuffer.push_back( 2 ); ringBuffer.push_back( 3 ); ringBuffer.push_back( 5 ); assert( ringBuffer.front() == 2 ); for ( const auto& value : ringBuffer ) { std::cout << value << " "; } std::cout << '\n'; } <commit_msg>Added filter function<commit_after>#include <iostream> #include <ring.h> #include <array> #include <utility> #include <numeric> int main() { using namespace std::rel_ops; std::array< int, 3 > baseArray; sg14::ring_span< int > ringBuffer( baseArray.begin(), baseArray.end() ); ringBuffer.push_back( 1 ); ringBuffer.push_back( 2 ); ringBuffer.push_back( 3 ); ringBuffer.push_back( 5 ); assert( ringBuffer.front() == 2 ); for ( const auto& value : ringBuffer ) { std::cout << value << " "; } std::cout << '\n'; std::array< int, 3 > filterCoeff = {1, 2, 1 }; // in interrupt loop or the like ringBuffer.push_back( 7 ); std::cout << std::inner_product( ringBuffer.begin(), ringBuffer.end(), filterCoeff.begin() , 0 ); } <|endoftext|>
<commit_before>5b03fd36-5216-11e5-ad93-6c40088e03e4<commit_msg>5b0bc00a-5216-11e5-999e-6c40088e03e4<commit_after>5b0bc00a-5216-11e5-999e-6c40088e03e4<|endoftext|>
<commit_before>9101ad85-2d14-11e5-af21-0401358ea401<commit_msg>9101ad86-2d14-11e5-af21-0401358ea401<commit_after>9101ad86-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>459a0166-2e3a-11e5-bb50-c03896053bdd<commit_msg>45a8f838-2e3a-11e5-b779-c03896053bdd<commit_after>45a8f838-2e3a-11e5-b779-c03896053bdd<|endoftext|>
<commit_before>8fd048f2-2d14-11e5-af21-0401358ea401<commit_msg>8fd048f3-2d14-11e5-af21-0401358ea401<commit_after>8fd048f3-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>d72c001c-585a-11e5-84b9-6c40088e03e4<commit_msg>d732a0e8-585a-11e5-88d4-6c40088e03e4<commit_after>d732a0e8-585a-11e5-88d4-6c40088e03e4<|endoftext|>
<commit_before>7f6cf5f1-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf5f2-2d15-11e5-af21-0401358ea401<commit_after>7f6cf5f2-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>e5bc26cc-2e4e-11e5-a1b1-28cfe91dbc4b<commit_msg>e5c43917-2e4e-11e5-9150-28cfe91dbc4b<commit_after>e5c43917-2e4e-11e5-9150-28cfe91dbc4b<|endoftext|>
<commit_before>5e5893fe-2d16-11e5-af21-0401358ea401<commit_msg>5e5893ff-2d16-11e5-af21-0401358ea401<commit_after>5e5893ff-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>820bf217-2749-11e6-a462-e0f84713e7b8<commit_msg>Did a thing<commit_after>82198f85-2749-11e6-a4c9-e0f84713e7b8<|endoftext|>
<commit_before>129fd488-2f67-11e5-9a36-6c40088e03e4<commit_msg>12a65e98-2f67-11e5-9350-6c40088e03e4<commit_after>12a65e98-2f67-11e5-9350-6c40088e03e4<|endoftext|>
<commit_before>6ad4f9c6-2fa5-11e5-9caf-00012e3d3f12<commit_msg>6ad6a774-2fa5-11e5-b768-00012e3d3f12<commit_after>6ad6a774-2fa5-11e5-b768-00012e3d3f12<|endoftext|>
<commit_before>#include <iostream> using namespace std; int main(){ cout << "hola mundo"; retrun 0; } <commit_msg>Update main.cpp<commit_after>#include <iostream> using namespace std; int main(){ cout << "hola mundo"<<endl; retrun 0; } <|endoftext|>
<commit_before>db374b2b-313a-11e5-80b8-3c15c2e10482<commit_msg>db3d7663-313a-11e5-abe2-3c15c2e10482<commit_after>db3d7663-313a-11e5-abe2-3c15c2e10482<|endoftext|>
<commit_before>312c30fe-2f67-11e5-ab69-6c40088e03e4<commit_msg>313321c8-2f67-11e5-9c58-6c40088e03e4<commit_after>313321c8-2f67-11e5-9c58-6c40088e03e4<|endoftext|>
<commit_before>a2bd12ba-2e4f-11e5-9db4-28cfe91dbc4b<commit_msg>a2ca249e-2e4f-11e5-860a-28cfe91dbc4b<commit_after>a2ca249e-2e4f-11e5-860a-28cfe91dbc4b<|endoftext|>
<commit_before>cb84e7a4-35ca-11e5-b78d-6c40088e03e4<commit_msg>cb90cc22-35ca-11e5-8d53-6c40088e03e4<commit_after>cb90cc22-35ca-11e5-8d53-6c40088e03e4<|endoftext|>
<commit_before>f7cdde08-585a-11e5-abfd-6c40088e03e4<commit_msg>f7d4aa08-585a-11e5-8cf0-6c40088e03e4<commit_after>f7d4aa08-585a-11e5-8cf0-6c40088e03e4<|endoftext|>
<commit_before>e73908f0-313a-11e5-9ffc-3c15c2e10482<commit_msg>e73ec5ee-313a-11e5-a216-3c15c2e10482<commit_after>e73ec5ee-313a-11e5-a216-3c15c2e10482<|endoftext|>
<commit_before>dd19661c-313a-11e5-8a78-3c15c2e10482<commit_msg>dd203d73-313a-11e5-85a4-3c15c2e10482<commit_after>dd203d73-313a-11e5-85a4-3c15c2e10482<|endoftext|>
<commit_before>efe76c45-327f-11e5-b4b1-9cf387a8033e<commit_msg>efefaffa-327f-11e5-895d-9cf387a8033e<commit_after>efefaffa-327f-11e5-895d-9cf387a8033e<|endoftext|>
<commit_before>#include <unistd.h> #include <getopt.h> #include <openssl/sha.h> #include "SHA1.h" #include "MD5ex.h" #include "SHA256.h" #include "SHA512ex.h" using namespace std; vector<unsigned char> StringToVector(unsigned char * str) { vector<unsigned char> ret; for(unsigned int x = 0; x < strlen((char*)str); x++) { ret.push_back(str[x]); } return ret; } void DigestToRaw(string hash, unsigned char * raw) { transform(hash.begin(), hash.end(), hash.begin(), ::tolower); string alpha("0123456789abcdef"); for(unsigned int x = 0; x < (hash.length() / 2); x++) { raw[x] = (unsigned char)((alpha.find(hash.at((x * 2))) << 4)); raw[x] |= (unsigned char)(alpha.find(hash.at((x * 2) + 1))); } } vector<unsigned char> * GenerateRandomData() { vector<unsigned char> * ret = new vector<unsigned char>(); int length = rand() % 128; for(int x = 0; x < length; x++) { ret->push_back((rand() % (126 - 32)) + 32); } return ret; } void TestExtender(Extender * sex) { //First generate a signature, with randomly generated data vector<unsigned char> * vkey = GenerateRandomData(); vector<unsigned char> * vmessage = GenerateRandomData(); vector<unsigned char> * additionalData = GenerateRandomData(); unsigned char * firstSig; unsigned char * secondSig; sex->GenerateSignature(*vkey, *vmessage, &firstSig); if(sex->ValidateSignature(*vkey, *vmessage, firstSig)) { vector<unsigned char> * newData = sex->GenerateStretchedData(*vmessage, vkey->size(), firstSig, *additionalData, &secondSig); if(sex->ValidateSignature(*vkey, *newData, secondSig)) { cout << "Test passed." << endl; delete vkey; delete vmessage; delete additionalData; delete newData; return; } else { cout << "Generated data failed to be verified as correctly signed." << endl; delete vkey; delete vmessage; delete additionalData; delete newData; return; } } else { cout << "Initial signature check failed." << endl; delete vkey; delete vmessage; delete additionalData; return; } } Extender * GetExtenderForHash(string sig) { if(sig.length() == 40) { return new SHA1ex(); } else if(sig.length() == 64) { return new SHA256ex(); } else if(sig.length() == 32) { return new MD5ex(); } else if(sig.length() == 128) { return new SHA512ex(); } return NULL; } void PrintHelp() { cout << "HashPump [-h help] [-t test] [-s signature] [-d data] [-a additional] [-k keylength]" << endl; } int main(int argc, char ** argv) { string sig; string data; int keylength; string datatoadd; Extender * sex; bool run_tests = false; while(1) { int option_index = 0; static struct option long_options[] = { {"test", no_argument, 0, 0}, {"signature", required_argument, 0, 0}, {"data", required_argument, 0, 0}, {"additional", required_argument, 0, 0}, {"keylength", required_argument, 0, 0}, {"help", no_argument, 0, 0}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "ts:d:a:k:h", long_options, &option_index); if (c == -1) break; switch(c) { case 0: switch(option_index) { case 0: run_tests = true; break; case 1: sig.assign(optarg); sex = GetExtenderForHash(sig); if(sex == NULL) { cout << "Unsupported signature size." << endl; return 0; } break; case 2: data.assign(optarg); break; case 3: datatoadd.assign(optarg); break; case 4: keylength = atoi(optarg); break; case 5: PrintHelp(); return 0; } break; case 't': run_tests = true; break; case 's': sig.assign(optarg); sex = GetExtenderForHash(sig); if(sex == NULL) { cout << "Unsupported hash size." << endl; return 0; } break; case 'd': data.assign(optarg); break; case 'a': datatoadd.assign(optarg); break; case 'k': keylength = atoi(optarg); break; case 'h': PrintHelp(); return 0; } } if(run_tests) { //Just a simple way to force tests cout << "Testing SHA1" << endl; TestExtender(new SHA1ex()); cout << "Testing SHA256" << endl; TestExtender(new SHA256ex()); cout << "Testing SHA512" << endl; TestExtender(new SHA512ex()); cout << "Testing MD5" << endl; TestExtender(new MD5ex()); cout << "Testing concluded" << endl; return 0; } if(sig.size() == 0) { cout << "Input Signature: "; cin >> sig; sex = GetExtenderForHash(sig); if(sex == NULL) { cout << "Unsupported hash size." << endl; return 0; } } if(data.size() == 0) { cout << "Input Data: "; cin >> data; } if(keylength == 0) { cout << "Input Key Length: "; cin >> keylength; } if(datatoadd.size() == 0) { cout << "Input Data to Add: "; cin >> datatoadd; } vector<unsigned char> vmessage = StringToVector((unsigned char*)data.c_str()); vector<unsigned char> vtoadd = StringToVector((unsigned char*)datatoadd.c_str()); unsigned char firstSig[20]; DigestToRaw(sig, firstSig); unsigned char * secondSig; vector<unsigned char> * secondMessage = sex->GenerateStretchedData(vmessage, keylength, firstSig, vtoadd, &secondSig); for(int x = 0; x < 20; x++) { printf("%02x", secondSig[x]); } cout << endl; for(unsigned int x = 0; x < secondMessage->size(); x++) { unsigned char c = secondMessage->at(x); if(c >= 32 && c <= 126) { cout << c; } else { printf("\\x%02x", c); } } delete secondMessage; cout << endl; return 0; } <commit_msg>Added a version to the help display<commit_after>#include <unistd.h> #include <getopt.h> #include <openssl/sha.h> #include "SHA1.h" #include "MD5ex.h" #include "SHA256.h" #include "SHA512ex.h" using namespace std; vector<unsigned char> StringToVector(unsigned char * str) { vector<unsigned char> ret; for(unsigned int x = 0; x < strlen((char*)str); x++) { ret.push_back(str[x]); } return ret; } void DigestToRaw(string hash, unsigned char * raw) { transform(hash.begin(), hash.end(), hash.begin(), ::tolower); string alpha("0123456789abcdef"); for(unsigned int x = 0; x < (hash.length() / 2); x++) { raw[x] = (unsigned char)((alpha.find(hash.at((x * 2))) << 4)); raw[x] |= (unsigned char)(alpha.find(hash.at((x * 2) + 1))); } } vector<unsigned char> * GenerateRandomData() { vector<unsigned char> * ret = new vector<unsigned char>(); int length = rand() % 128; for(int x = 0; x < length; x++) { ret->push_back((rand() % (126 - 32)) + 32); } return ret; } void TestExtender(Extender * sex) { //First generate a signature, with randomly generated data vector<unsigned char> * vkey = GenerateRandomData(); vector<unsigned char> * vmessage = GenerateRandomData(); vector<unsigned char> * additionalData = GenerateRandomData(); unsigned char * firstSig; unsigned char * secondSig; sex->GenerateSignature(*vkey, *vmessage, &firstSig); if(sex->ValidateSignature(*vkey, *vmessage, firstSig)) { vector<unsigned char> * newData = sex->GenerateStretchedData(*vmessage, vkey->size(), firstSig, *additionalData, &secondSig); if(sex->ValidateSignature(*vkey, *newData, secondSig)) { cout << "Test passed." << endl; delete vkey; delete vmessage; delete additionalData; delete newData; return; } else { cout << "Generated data failed to be verified as correctly signed." << endl; delete vkey; delete vmessage; delete additionalData; delete newData; return; } } else { cout << "Initial signature check failed." << endl; delete vkey; delete vmessage; delete additionalData; return; } } Extender * GetExtenderForHash(string sig) { if(sig.length() == 40) { return new SHA1ex(); } else if(sig.length() == 64) { return new SHA256ex(); } else if(sig.length() == 32) { return new MD5ex(); } else if(sig.length() == 128) { return new SHA512ex(); } return NULL; } void PrintHelp() { cout << "HashPump [-h help] [-t test] [-s signature] [-d data] [-a additional] [-k keylength]" << endl; cout << " HashPump generates strings to exploit signatures vulnerable to the Hash Length Extension Attack." << endl; cout << " -h --help Display this message." << endl; cout << " -t --test Run tests to verify each algorithm is operating properly." << endl; cout << " -s --signature The signature from known message." << endl; cout << " -d --data The data from the known message." << endl; cout << " -a --additional The information you would like to add to the known message." << endl; cout << " -k --keylength The length in bytes of the key being used to sign the original message with." << endl; cout << " Version 1.0 with MD5, SHA1, SHA256 and SHA512 support." << endl; cout << " <Developed by bwall(@bwallHatesTwits)>" << endl; } int main(int argc, char ** argv) { string sig; string data; int keylength; string datatoadd; Extender * sex; bool run_tests = false; while(1) { int option_index = 0; static struct option long_options[] = { {"test", no_argument, 0, 0}, {"signature", required_argument, 0, 0}, {"data", required_argument, 0, 0}, {"additional", required_argument, 0, 0}, {"keylength", required_argument, 0, 0}, {"help", no_argument, 0, 0}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "ts:d:a:k:h", long_options, &option_index); if (c == -1) break; switch(c) { case 0: switch(option_index) { case 0: run_tests = true; break; case 1: sig.assign(optarg); sex = GetExtenderForHash(sig); if(sex == NULL) { cout << "Unsupported signature size." << endl; return 0; } break; case 2: data.assign(optarg); break; case 3: datatoadd.assign(optarg); break; case 4: keylength = atoi(optarg); break; case 5: PrintHelp(); return 0; } break; case 't': run_tests = true; break; case 's': sig.assign(optarg); sex = GetExtenderForHash(sig); if(sex == NULL) { cout << "Unsupported hash size." << endl; return 0; } break; case 'd': data.assign(optarg); break; case 'a': datatoadd.assign(optarg); break; case 'k': keylength = atoi(optarg); break; case 'h': PrintHelp(); return 0; } } if(run_tests) { //Just a simple way to force tests cout << "Testing SHA1" << endl; TestExtender(new SHA1ex()); cout << "Testing SHA256" << endl; TestExtender(new SHA256ex()); cout << "Testing SHA512" << endl; TestExtender(new SHA512ex()); cout << "Testing MD5" << endl; TestExtender(new MD5ex()); cout << "Testing concluded" << endl; return 0; } if(sig.size() == 0) { cout << "Input Signature: "; cin >> sig; sex = GetExtenderForHash(sig); if(sex == NULL) { cout << "Unsupported hash size." << endl; return 0; } } if(data.size() == 0) { cout << "Input Data: "; cin >> data; } if(keylength == 0) { cout << "Input Key Length: "; cin >> keylength; } if(datatoadd.size() == 0) { cout << "Input Data to Add: "; cin >> datatoadd; } vector<unsigned char> vmessage = StringToVector((unsigned char*)data.c_str()); vector<unsigned char> vtoadd = StringToVector((unsigned char*)datatoadd.c_str()); unsigned char firstSig[20]; DigestToRaw(sig, firstSig); unsigned char * secondSig; vector<unsigned char> * secondMessage = sex->GenerateStretchedData(vmessage, keylength, firstSig, vtoadd, &secondSig); for(int x = 0; x < 20; x++) { printf("%02x", secondSig[x]); } cout << endl; for(unsigned int x = 0; x < secondMessage->size(); x++) { unsigned char c = secondMessage->at(x); if(c >= 32 && c <= 126) { cout << c; } else { printf("\\x%02x", c); } } delete secondMessage; cout << endl; return 0; } <|endoftext|>
<commit_before>92323ad9-2d14-11e5-af21-0401358ea401<commit_msg>92323ada-2d14-11e5-af21-0401358ea401<commit_after>92323ada-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5bf67338-2d16-11e5-af21-0401358ea401<commit_msg>5bf67339-2d16-11e5-af21-0401358ea401<commit_after>5bf67339-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5c91406e-2748-11e6-bcdb-e0f84713e7b8<commit_msg>almost working<commit_after>5c9d4dab-2748-11e6-bae4-e0f84713e7b8<|endoftext|>
<commit_before>f737bc54-2e4e-11e5-8932-28cfe91dbc4b<commit_msg>f73e0733-2e4e-11e5-a3d9-28cfe91dbc4b<commit_after>f73e0733-2e4e-11e5-a3d9-28cfe91dbc4b<|endoftext|>
<commit_before>#include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "USART.h" #include "USART_Debug.h" #include "DS3231.h" #include "CommandReader.h" USART_Data c0d; USART C0; TWI_Data twi_d; DS3231 rtc; CommandReader cmdReader(&rtc); void initClocks(){ OSC.CTRL |= OSC_RC32MEN_bm | OSC_RC32KEN_bm; /* Enable the internal 32MHz & 32KHz oscillators */ while(!(OSC.STATUS & OSC_RC32KRDY_bm)); /* Wait for 32Khz oscillator to stabilize */ while(!(OSC.STATUS & OSC_RC32MRDY_bm)); /* Wait for 32MHz oscillator to stabilize */ DFLLRC32M.CTRL = DFLL_ENABLE_bm ; /* Enable DFLL - defaults to calibrate against internal 32Khz clock */ CCP = CCP_IOREG_gc; /* Disable register security for clock update */ CLK.CTRL = CLK_SCLKSEL_RC32M_gc; /* Switch to 32MHz clock */ OSC.CTRL &= ~OSC_RC2MEN_bm; /* Disable 2Mhz oscillator */ } void setupUSART(){ c0d.baudRate = 9600; c0d.port = &PORTC; c0d.usart_port = &USARTC0; c0d.rxPin = PIN2_bm; c0d.txPin = PIN3_bm; C0 = USART(&c0d, false); } void setupTWI(uint8_t address){ /* * rtcData.baud_hz = 400000L; rtcData.master_addr = 0x00; rtcData.maxDataLength = 64; rtcData.port = 0x00; rtcData.twi_port = &TWIE; */ twi_d.baud_hz = 400000L; twi_d.master_addr = 0x00; twi_d.maxDataLength = 64; twi_d.port = &PORTE; twi_d.twi_port = &TWIE; rtc = DS3231(&twi_d, address); } void pollBus(TWI * t){ register8_t * i2cAddresses; i2cAddresses = t->pollBus(); //char i2c_data[64];// for(uint8_t i = 0; i < 127; i++){ if (i == 127){ printf("%x\n", i2cAddresses[i]); } if (i % 25 == 0){ printf("\n"); } printf("%x, ", i2cAddresses[i]); } } void restartInterrupts(){ cli(); PMIC.CTRL |= PMIC_HILVLEN_bm | PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm; sei(); } // Temporary time setting function (move to cmd config class) void setDate(DS3231 * rtc){ printf("Setting time..\n"); struct tm time; time.tm_year = 2016; time.tm_mon = 3; time.tm_mday = 2; time.tm_hour = 14; time.tm_min = 15; time.tm_sec = 55; rtc->setTime(&time); } // Temp. alarm setting function void setAlarm(DS3231 * rtc){ printf("Setting alarm.\n"); struct tm time; time.tm_mday = 0; time.tm_hour = 0; time.tm_min = 0; time.tm_sec = 5; rtc->setAlarmInterval(&time, weekDay); } void setupPortAInterrupts(){ PORTA.PIN5CTRL = PORT_OPC_PULLDOWN_gc | PORT_ISC_RISING_gc; PORTA.INT0MASK = PIN5_bm; PORTA.INTCTRL = PORT_INT0LVL_MED_gc; } // Alarm Interrupt routine ISR(PORTA_INT0_vect){ } int main(){ initClocks(); restartInterrupts(); setupPortAInterrupts(); setupUSART(); setDebugOutputPort(&USARTC0); PORTB.DIR = 0b1111; PORTE.DIR = 0x03; printf("\nPROGRAM BEGIN..\n\n"); _delay_ms(200); setupTWI(0x68); //cmdReader = CommandReader(&rtc); //setAlarm(&rtc); //pollBus(&rtc); //setDate(&rtc); // startup commands - set time, alarm, etc cmdReader.mainLoop(); // get the current time struct tm time_rcv = *rtc.getTime(); printf("%d/%d/%d %d:%d::%d\n", time_rcv.tm_mday, time_rcv.tm_mon, time_rcv.tm_year, time_rcv.tm_hour, time_rcv.tm_min, time_rcv.tm_sec); uint8_t out = 0x01; // LED looping test while(1){ //printf("Oh hi. %d\n", i++); PORTB.OUT = out; out = (out << 1); if(out == 0b1000){ out = 0x01; } _delay_ms(1000); time_rcv = *rtc.getTime(); printf("%02d/%02d/%02d %02d:%02d::%02d\n", time_rcv.tm_mday, time_rcv.tm_mon, time_rcv.tm_year, time_rcv.tm_hour, time_rcv.tm_min, time_rcv.tm_sec); } return 0; } <commit_msg>setting up for rtc alarm usage..<commit_after>#include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "USART.h" #include "USART_Debug.h" #include "DS3231.h" #include "CommandReader.h" #define DS3231_ADDR 0x68 USART_Data uc0d; USART UC0; TWI_Data twi_d; DS3231 rtc; CommandReader cmdReader(&rtc); #define ALARM_FLAG 0x01 volatile uint8_t interrupt_status = 0x00; void initClocks(){ OSC.CTRL |= OSC_RC32MEN_bm | OSC_RC32KEN_bm; /* Enable the internal 32MHz & 32KHz oscillators */ while(!(OSC.STATUS & OSC_RC32KRDY_bm)); /* Wait for 32Khz oscillator to stabilize */ while(!(OSC.STATUS & OSC_RC32MRDY_bm)); /* Wait for 32MHz oscillator to stabilize */ DFLLRC32M.CTRL = DFLL_ENABLE_bm ; /* Enable DFLL - defaults to calibrate against internal 32Khz clock */ CCP = CCP_IOREG_gc; /* Disable register security for clock update */ CLK.CTRL = CLK_SCLKSEL_RC32M_gc; /* Switch to 32MHz clock */ OSC.CTRL &= ~OSC_RC2MEN_bm; /* Disable 2Mhz oscillator */ } void setupUSART(){ uc0d.baudRate = 9600; uc0d.port = &PORTC; uc0d.usart_port = &USARTC0; uc0d.rxPin = PIN2_bm; uc0d.txPin = PIN3_bm; UC0 = USART(&uc0d, false); } void setupTWI(uint8_t address){ /* * rtcData.baud_hz = 400000L; rtcData.master_addr = 0x00; rtcData.maxDataLength = 64; rtcData.port = 0x00; rtcData.twi_port = &TWIE; */ twi_d.baud_hz = 400000L; twi_d.master_addr = 0x00; twi_d.maxDataLength = 64; twi_d.port = &PORTE; twi_d.twi_port = &TWIE; rtc = DS3231(&twi_d, address); } void pollBus(TWI * t){ register8_t * i2cAddresses; i2cAddresses = t->pollBus(); //char i2c_data[64];// for(uint8_t i = 0; i < 127; i++){ if (i == 127){ printf("%x\n", i2cAddresses[i]); } if (i % 25 == 0){ printf("\n"); } printf("%x, ", i2cAddresses[i]); } } void restartInterrupts(){ cli(); PMIC.CTRL |= PMIC_HILVLEN_bm | PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm; sei(); } // Temporary time setting function (move to cmd config class) void setDate(DS3231 * rtc){ printf("Setting time..\n"); struct tm time; time.tm_year = 2016; time.tm_mon = 3; time.tm_mday = 2; time.tm_hour = 14; time.tm_min = 15; time.tm_sec = 55; rtc->setTime(&time); } // Temp. alarm setting function void setAlarm(DS3231 * rtc){ printf("Setting alarm.\n"); struct tm time; time.tm_mday = 0; time.tm_hour = 0; time.tm_min = 0; time.tm_sec = 5; rtc->setAlarmInterval(&time, weekDay); } void setupPortAInterrupts(){ PORTA.PIN5CTRL = PORT_OPC_PULLDOWN_gc | PORT_ISC_RISING_gc; PORTA.INT0MASK = PIN5_bm; PORTA.INTCTRL = PORT_INT0LVL_MED_gc; } // Alarm Interrupt routine ISR(PORTA_INT0_vect){ interrupt_status &= ALARM_FLAG; } int main(){ initClocks(); restartInterrupts(); setupPortAInterrupts(); setupUSART(); setDebugOutputPort(&USARTC0); PORTB.DIR = 0b1111; PORTE.DIR = 0x03; printf("\nPROGRAM BEGIN..\n\n"); _delay_ms(200); setupTWI(DS3231_ADDR); //cmdReader = CommandReader(&rtc); //setAlarm(&rtc); //pollBus(&rtc); //setDate(&rtc); // startup commands - set time, alarm, etc cmdReader.mainLoop(); // get the current time struct tm time_rcv = *rtc.getTime(); printf("%d/%d/%d %d:%d::%d\n", time_rcv.tm_mday, time_rcv.tm_mon, time_rcv.tm_year, time_rcv.tm_hour, time_rcv.tm_min, time_rcv.tm_sec); uint8_t out = 0x01; // LED looping test while(1){ //printf("Oh hi. %d\n", i++); PORTB.OUT = out; out = (out << 1); if(out == 0b1000){ out = 0x01; } if(interrupt_status && ALARM_FLAG){ printf("RTC alarm triggered!!!\n"); out &= 0b1000; rtc.resetAlarm1Flag(); rtc.setNextIntervalAlarm(); interrupt_status &= ~ALARM_FLAG; } _delay_ms(1000); time_rcv = *rtc.getTime(); printf("%02d/%02d/%02d %02d:%02d::%02d\n", time_rcv.tm_mday, time_rcv.tm_mon, time_rcv.tm_year, time_rcv.tm_hour, time_rcv.tm_min, time_rcv.tm_sec); } return 0; } <|endoftext|>
<commit_before>7085c205-4b02-11e5-8039-28cfe9171a43<commit_msg>fix for the previous fix<commit_after>70908f70-4b02-11e5-b75c-28cfe9171a43<|endoftext|>
<commit_before>6f8b5934-5216-11e5-994e-6c40088e03e4<commit_msg>6f920286-5216-11e5-b5ba-6c40088e03e4<commit_after>6f920286-5216-11e5-b5ba-6c40088e03e4<|endoftext|>
<commit_before>25942b63-2e4f-11e5-a7f5-28cfe91dbc4b<commit_msg>259c507a-2e4f-11e5-80f4-28cfe91dbc4b<commit_after>259c507a-2e4f-11e5-80f4-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <random> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #define O_BINARY 0 const int RECORD_SIZE = 8 * 1024; int first_record; int last_record; size_t get_file_size(const char *); void write_records(void); int main(int argc, char **argv) { // required for argument parsing int fflag = 0; int c; const char * def_filename = "device-file"; char * filename; extern char *optarg; extern int optind; static char usage[] = "usage: %s -f filename\n"; // permanent values int num_records, file_size; while ((c = getopt(argc, argv, "f:")) != -1) { switch (c) { case 'f': filename = optarg; fflag = 1; break; default: // implement other options, such as help, etc. break; } } if (fflag == 0) { // need to implement default filename filename = strdup(def_filename); } file_size = (int) get_file_size(filename); num_records = file_size / RECORD_SIZE; first_record = 0; last_record = num_records; std::cout << "File range is 0 to " << file_size << "." << std::endl; std::cout << "Number of possible records: " << num_records << std::endl; write_records(); return 0; } void write_records(void) { long thread_id = 0; long record_id = 1; long address; long checksum = 1; std::random_device rd; std::mt19937 generator(rd()); std::uniform_int_distribution<> distr(first_record, last_record); for (int i = 0; i < 10; i++) { address = distr(generator); std::cout << "Record: " << thread_id << " " << record_id << " " << address << " " << checksum << std::endl; record_id++; } } // https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file size_t get_file_size(const char * filename) { size_t file_size; char *buffer; struct stat stbuf; int fd; fd = open(filename, O_BINARY); if (fd == -1) { /* Handle error */ } if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode))) { /* Handle error */ } file_size = stbuf.st_size; buffer = (char*)malloc(file_size); if (buffer == NULL) { /* Handle error */ } return file_size; }<commit_msg>Implemented threadsafe random, checksum<commit_after>#include <iostream> #include <random> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include "thread_info.h" #include "thread_local.h" #define O_BINARY 0 const int RECORD_SIZE = 8 * 1024; int first_record; int last_record; size_t get_file_size(const char *); void create_record(thread_info *); void worker_thread_init(void); int intRand(); uint64_t Fletcher64 (long *, int); int main(int argc, char **argv) { // required for argument parsing int fflag = 0; int c; const char * def_filename = "device-file"; char * filename; extern char *optarg; extern int optind; static char usage[] = "usage: %s -f filename\n"; // permanent values int num_records, file_size; while ((c = getopt(argc, argv, "f:")) != -1) { switch (c) { case 'f': filename = optarg; fflag = 1; break; default: // implement other options, such as help, etc. break; } } if (fflag == 0) { // need to implement default filename filename = strdup(def_filename); } file_size = (int) get_file_size(filename); num_records = file_size / RECORD_SIZE; first_record = 0; last_record = num_records; std::cout << "File range is 0 to " << file_size << "." << std::endl; std::cout << "Number of possible records: " << num_records << std::endl; worker_thread_init(); return 0; } void worker_thread_init(void) { // set up running record... thread_info * record_data = (thread_info *) malloc(sizeof(record_data)); // replace with thread id record_data->thread_id = 0; record_data->record_num = 1; for (int i = 0; i < 10; i++) create_record(record_data); } void create_record(thread_info * record_data) { long record_size = RECORD_SIZE / sizeof(long); std::cout << "Expecting record_size = 8KB / sizeof(long) but got record_size = " << record_size << " sizeof(long) = " << sizeof(long) << sizeof(int) << std::endl; long * record = (long *) malloc(record_size * sizeof(record)); long address = intRand(); long checksum = 1; record[0] = record_data->thread_id; record[1] = record_data->record_num; record[2] = address; for (int i = 3; i < record_size - 1; i++) { record[i] = record[i-1] + record[0] * record[1] * i + record[2]; } checksum = Fletcher64(record, record_size - 1); record[record_size - 1] = Fletcher64(record, record_size - 1); std::cout << "Record: " << record[0] << " " << record[1] << " " << record[2] << " " << checksum << " " << record[record_size-1] << std::endl; std::cout << "Checksums match? " << (checksum == record[record_size-1]) << std::endl; record_data->record_num += 1; free(record); } // https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek()+and+ftell()+to+compute+the+size+of+a+regular+file size_t get_file_size(const char * filename) { size_t file_size; char *buffer; struct stat stbuf; int fd; fd = open(filename, O_BINARY); if (fd == -1) { /* Handle error */ } if ((fstat(fd, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode))) { /* Handle error */ } file_size = stbuf.st_size; buffer = (char*)malloc(file_size); if (buffer == NULL) { /* Handle error */ } return file_size; } int intRand() { static thread_local std::mt19937* generator; if (!generator) generator = new std::mt19937(clock()); std::uniform_int_distribution<int> distribution(first_record, last_record); return distribution(*generator); } uint64_t Fletcher64 (long * data, int number_to_checksum) { uint64_t sum1 = 0; uint64_t sum2 = 0; uint64_t mod_value = 4294967296; for(int i = 0; i < number_to_checksum; i++) { sum1 = (sum1 + data[i]) % mod_value; sum2 = (sum2 + sum1) % mod_value; } return (sum2 << 32) | sum1; }<|endoftext|>
<commit_before>98dfb714-35ca-11e5-b9f4-6c40088e03e4<commit_msg>98e6ba66-35ca-11e5-98f1-6c40088e03e4<commit_after>98e6ba66-35ca-11e5-98f1-6c40088e03e4<|endoftext|>
<commit_before>32073e5c-2e3a-11e5-8393-c03896053bdd<commit_msg>3216aa7a-2e3a-11e5-928b-c03896053bdd<commit_after>3216aa7a-2e3a-11e5-928b-c03896053bdd<|endoftext|>
<commit_before>222c6864-2f67-11e5-9c52-6c40088e03e4<commit_msg>22331270-2f67-11e5-a29f-6c40088e03e4<commit_after>22331270-2f67-11e5-a29f-6c40088e03e4<|endoftext|>
<commit_before>#include <memory> #include <cstdlib> #include <stlw/log.hpp> #include <stlw/result.hpp> #include <engine/window/window.hpp> #include <engine/gfx/gfx.hpp> #include <game/game.hpp> #include <engine/window/sdl_window.hpp> #include <engine/gfx/opengl_gfx.hpp> #include <game/boomhs/boomhs.hpp> int main(int argc, char *argv[]) { auto logger = stlw::log_factory::make_logger("logfile", "txt", 23, 59); auto const on_error = [&](auto const& error) { logger.error(error); return EXIT_FAILURE; }; // Select windowing library as SDL. namespace w = engine::window; using window_lib = w::library_wrapper<w::sdl_library>; logger.debug("Initializing window library globals."); DO_MONAD_OR_ELSE_RETURN(auto _, window_lib::init(), on_error); logger.debug("Setting up stack guard to unitialize window library globals."); ON_SCOPE_EXIT( []() { window_lib::destroy(); }); logger.debug("Instantiating window instance."); DO_MONAD_OR_ELSE_RETURN(auto window, window_lib::make_window(), on_error); // Initialize graphics renderer namespace r = engine::gfx; using render_lib = r::library_wrapper<r::opengl::opengl_library>; auto renderer = render_lib::make_renderer(std::move(window)); // Selecting the game using game_factory = game::game_factory; using game_lib = game::boomhs::boomhs_library; // Initialize the game instance. logger.debug("Instantiating boomhs instance."); auto game = game_factory::make_game(logger); logger.debug("Starting boomhs game loop."); DO_MONAD_OR_ELSE_RETURN(auto __, (game.run<decltype(renderer), game_lib>(std::move(renderer))), on_error); logger.debug("Game loop finished successfully! Ending program now !!"); return EXIT_SUCCESS; } <commit_msg>minutae<commit_after>#include <memory> #include <cstdlib> #include <stlw/log.hpp> #include <stlw/result.hpp> #include <engine/window/window.hpp> #include <engine/gfx/gfx.hpp> #include <game/game.hpp> #include <engine/window/sdl_window.hpp> #include <engine/gfx/opengl_gfx.hpp> #include <game/boomhs/boomhs.hpp> int main(int argc, char *argv[]) { auto logger = stlw::log_factory::make_logger("logfile", "txt", 23, 59); auto const on_error = [&](auto const& error) { logger.error(error); return EXIT_FAILURE; }; // Select windowing library as SDL. namespace w = engine::window; using window_lib = w::library_wrapper<w::sdl_library>; logger.debug("Initializing window library globals."); DO_MONAD_OR_ELSE_RETURN(auto _, window_lib::init(), on_error); logger.debug("Setting up stack guard to unitialize window library globals."); ON_SCOPE_EXIT( []() { window_lib::destroy(); }); logger.debug("Instantiating window instance."); DO_MONAD_OR_ELSE_RETURN(auto window, window_lib::make_window(), on_error); // Initialize graphics renderer namespace gfx = engine::gfx; using gfx_lib = gfx::library_wrapper<gfx::opengl::opengl_library>; auto renderer = gfx_lib::make_renderer(std::move(window)); // Selecting the game using game_factory = game::game_factory; using game_lib = game::boomhs::boomhs_library; // Initialize the game instance. logger.debug("Instantiating boomhs instance."); auto game = game_factory::make_game(logger); logger.debug("Starting boomhs game loop."); DO_MONAD_OR_ELSE_RETURN(auto __, (game.run<decltype(renderer), game_lib>(std::move(renderer))), on_error); logger.debug("Game loop finished successfully! Ending program now."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before> [[noreturn]] int main(int argc, char* argv[]) { }<commit_msg>main.cxx will serve as my scratchpad for testing<commit_after>#include "binary.hxx" [[noreturn]] int main(int argc, char* argv[]) { auto x = 4; binary<decltype(x)> bin{x}; }<|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <vector> #include "templateio.hpp" #include "parser_combinators.hpp" #include "profile.hpp" using namespace std; //---------------------------------------------------------------------------- // Example Expression Evaluating File Parser. enum op {add = 0, sub = 1, mul = 2, div = 3}; struct return_int { return_int() {} void operator() (int *res, string const& num) const { *res = stoi(num); } } const return_int; struct return_op { return_op() {} void operator() ( enum op *res, int choice, string const& add, string const& sub, string const& mul, string const& div ) const { *res = static_cast<enum op>(choice); } } const return_op; struct return_left { return_left() {} void operator() (int *res, int left) const { *res = left; } } const return_left; struct return_right { return_right() {} void operator() (int *res, enum op opr, int right) const { switch (opr) { case op::add: *res += right; break; case op::sub: *res -= right; break; case op::mul: *res *= right; break; case op::div: *res /= right; break; } } } const return_right; auto const recognise_number = some(accept(is_digit)); auto const recognise_space = many(accept(is_space)); auto const parse_operand = discard(recognise_space) && all(return_int, recognise_number); auto const parse_operator = discard(recognise_space) && any(return_op, accept(is_char('+')), accept(is_char('-')), accept(is_char('*')), accept(is_char('/'))); auto const parse = all(return_left, parse_operand) && many(all(return_right, parse_operator, parse_operand)); class csv_parser { pstream in; public: csv_parser(fstream &fs) : in(fs) {} int operator() () { decltype(parse)::result_type a; bool b; { profile<csv_parser> p; b = parse(in, &a); } if (b) { cout << "OK\n"; } else { cout << "FAIL\n"; } cout << a << "\n"; return in.get_count(); } }; //---------------------------------------------------------------------------- int main(int const argc, char const *argv[]) { if (argc < 1) { cerr << "no input files\n"; } else { for (int i = 1; i < argc; ++i) { try { fstream in(argv[i], ios_base::in); cout << argv[i] << "\n"; if (in.is_open()) { csv_parser csv(in); profile<csv_parser>::reset(); int const chars_read = csv(); double const mb_per_s = static_cast<double>(chars_read) / static_cast<double>(profile<csv_parser>::report()); cout << "parsed: " << mb_per_s << "MB/s\n"; } } catch (parse_error& e) { cerr << argv[i] << ": " << e.what() << " " << e.exp << " found "; if (is_print(e.sym)) { cerr << "'" << static_cast<char>(e.sym) << "'"; } else { cerr << "0x" << hex << e.sym; } cerr << " at line " << e.row << ", column " << e.col << "\n"; return 2; } } } } <commit_msg>update example to show (polymorphic) recursive expression<commit_after>#include <fstream> #include <iostream> #include <vector> #include "templateio.hpp" #include "parser_combinators.hpp" #include "profile.hpp" using namespace std; //---------------------------------------------------------------------------- // Example Expression Evaluating File Parser. enum class op {add = 0, sub = 1, mul = 2, div = 3}; ostream& operator<< (ostream &in, op opr) { switch (opr) { case op::add: in << " + "; break; case op::sub: in << " - "; break; case op::mul: in << " * "; break; case op::div: in << " / "; break; } return in; } struct return_int { return_int() {} void operator() (int *res, string const& num) const { *res = stoi(num); } } const return_int; struct return_op { return_op() {} void operator() ( enum op *res, int choice, string const& add, string const& sub, string const& mul, string const& div ) const { *res = static_cast<enum op>(choice); } } const return_op; struct return_exp { return_exp() {} void operator() (int *res, int left, enum op opr, int right) const { switch (opr) { case op::add: *res = left + right; break; case op::sub: *res = left - right; break; case op::mul: *res = left * right; break; case op::div: *res = left / right; break; } } } const return_exp; auto const recognise_number = some(accept(is_digit)); auto const recognise_space = many(accept(is_space)); auto const recognise_start = recognise_space && accept(is_char('(')); auto const recognise_end = recognise_space && accept(is_char(')')); auto const parse_operand = discard(recognise_space) && all(return_int, recognise_number); auto const parse_operator = discard(recognise_space) && any(return_op, accept(is_char('+')), accept(is_char('-')), accept(is_char('*')), accept(is_char('/'))); parser_reference<int> expression_parser; auto const expression = discard(recognise_start) && all(return_exp, log("left", expression_parser || parse_operand), log("op", parse_operator), log("right", expression_parser || parse_operand) ) && discard(recognise_end); class csv_parser { pstream in; public: csv_parser(fstream &fs) : in(fs) {} int operator() () { expression_parser = expression; auto const parser = expression; decltype(parser)::result_type a {}; bool b; { profile<csv_parser> p; b = parser(in, &a); } if (b) { cout << "OK\n"; } else { cout << "FAIL\n"; } cout << a << "\n"; return in.get_count(); } }; //---------------------------------------------------------------------------- int main(int const argc, char const *argv[]) { if (argc < 1) { cerr << "no input files\n"; } else { for (int i = 1; i < argc; ++i) { try { fstream in(argv[i], ios_base::in); cout << argv[i] << "\n"; if (in.is_open()) { csv_parser csv(in); profile<csv_parser>::reset(); int const chars_read = csv(); double const mb_per_s = static_cast<double>(chars_read) / static_cast<double>(profile<csv_parser>::report()); cout << "parsed: " << mb_per_s << "MB/s\n"; } } catch (parse_error& e) { cerr << argv[i] << ": " << e.what() << " " << e.exp << " found "; if (is_print(e.sym)) { cerr << "'" << static_cast<char>(e.sym) << "'"; } else { cerr << "0x" << hex << e.sym; } cerr << " at line " << e.row << ", column " << e.col << "\n"; return 2; } } } } <|endoftext|>
<commit_before>#include "../mtlpp.hpp" #include "window.hpp" mtlpp::Device g_device; mtlpp::CommandQueue g_commandQueue; mtlpp::Buffer g_vertexBuffer; mtlpp::RenderPipelineState g_renderPipelineState; void Render(const Window& win) { mtlpp::CommandBuffer commandBuffer = g_commandQueue.CommandBuffer(); mtlpp::RenderPassDescriptor renderPassDesc = win.GetRenderPassDescriptor(); if (renderPassDesc) { mtlpp::RenderCommandEncoder renderCommandEncoder = commandBuffer.RenderCommandEncoder(renderPassDesc); renderCommandEncoder.SetRenderPipelineState(g_renderPipelineState); renderCommandEncoder.SetVertexBuffer(g_vertexBuffer, 0, 0); renderCommandEncoder.Draw(mtlpp::PrimitiveType::Triangle, 0, 3); renderCommandEncoder.EndEncoding(); commandBuffer.Present(win.GetDrawable()); } commandBuffer.Commit(); commandBuffer.WaitUntilCompleted(); } int main() { const char shadersSrc[] = R"""( #include <metal_stdlib> using namespace metal; vertex float4 vertFunc ( const device packed_float3* vertexArray [[buffer(0)]], unsigned int vID[[vertex_id]]) { return float4(vertexArray[vID], 1.0); } fragment half4 fragFunc () { return half4(1.0); } )"""; const float vertexData[] = { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, }; g_device = mtlpp::Device::CreateSystemDefaultDevice(); g_commandQueue = g_device.NewCommandQueue(); mtlpp::Library library = g_device.NewLibrary(shadersSrc, mtlpp::CompileOptions(), nullptr); mtlpp::Function vertFunc = library.NewFunction("vertFunc"); mtlpp::Function fragFunc = library.NewFunction("fragFunc"); g_vertexBuffer = g_device.NewBuffer(vertexData, sizeof(vertexData), mtlpp::ResourceOptions::CpuCacheModeDefaultCache); mtlpp::RenderPipelineDescriptor renderPipelineDesc; renderPipelineDesc.SetVertexFunction(vertFunc); renderPipelineDesc.SetFragmentFunction(fragFunc); renderPipelineDesc.GetColorAttachments()[0].SetPixelFormat(mtlpp::PixelFormat::RGBA8Unorm); g_renderPipelineState = g_device.NewRenderPipelineState(renderPipelineDesc, nullptr); Window win(g_device, &Render, 320, 240); Window::Run(); return 0; } <commit_msg>Cleanup.<commit_after>#include "../mtlpp.hpp" #include "window.hpp" mtlpp::Device g_device; mtlpp::CommandQueue g_commandQueue; mtlpp::Buffer g_vertexBuffer; mtlpp::RenderPipelineState g_renderPipelineState; void Render(const Window& win) { mtlpp::CommandBuffer commandBuffer = g_commandQueue.CommandBuffer(); mtlpp::RenderPassDescriptor renderPassDesc = win.GetRenderPassDescriptor(); if (renderPassDesc) { mtlpp::RenderCommandEncoder renderCommandEncoder = commandBuffer.RenderCommandEncoder(renderPassDesc); renderCommandEncoder.SetRenderPipelineState(g_renderPipelineState); renderCommandEncoder.SetVertexBuffer(g_vertexBuffer, 0, 0); renderCommandEncoder.Draw(mtlpp::PrimitiveType::Triangle, 0, 3); renderCommandEncoder.EndEncoding(); commandBuffer.Present(win.GetDrawable()); } commandBuffer.Commit(); commandBuffer.WaitUntilCompleted(); } int main() { const char shadersSrc[] = R"""( #include <metal_stdlib> using namespace metal; vertex float4 vertFunc( const device packed_float3* vertexArray [[buffer(0)]], unsigned int vID[[vertex_id]]) { return float4(vertexArray[vID], 1.0); } fragment half4 fragFunc() { return half4(1.0, 0.0, 0.0, 1.0); } )"""; const float vertexData[] = { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, }; g_device = mtlpp::Device::CreateSystemDefaultDevice(); g_commandQueue = g_device.NewCommandQueue(); mtlpp::Library library = g_device.NewLibrary(shadersSrc, mtlpp::CompileOptions(), nullptr); mtlpp::Function vertFunc = library.NewFunction("vertFunc"); mtlpp::Function fragFunc = library.NewFunction("fragFunc"); g_vertexBuffer = g_device.NewBuffer(vertexData, sizeof(vertexData), mtlpp::ResourceOptions::CpuCacheModeDefaultCache); mtlpp::RenderPipelineDescriptor renderPipelineDesc; renderPipelineDesc.SetVertexFunction(vertFunc); renderPipelineDesc.SetFragmentFunction(fragFunc); renderPipelineDesc.GetColorAttachments()[0].SetPixelFormat(mtlpp::PixelFormat::BGRA8Unorm); g_renderPipelineState = g_device.NewRenderPipelineState(renderPipelineDesc, nullptr); Window win(g_device, &Render, 320, 240); Window::Run(); return 0; } <|endoftext|>
<commit_before>#include "utils.hpp" void Menu::run(){ sf::RenderWindow window(sf::VideoMode(W_WIDTH, W_HEIGHT), APP_NAME); //sf::Texture spriteSheet; //if (!spriteSheet.loadFromFile("./images/spriteSheet.jpg")) std::cout << "Error loading spriteSheet" << std::endl; sf::RectangleShape bg; //bg.setTexture(spriteSheet); //bg.setTextureRect(posx,posy,midax,miday) bg.setFillColor(sf::Color(0,0,0)); sf::RectangleShape play; play.setFillColor(sf::Color(255,255,255)); play.setSize(sf::Vector2f(100,50)); play.setPosition(20,20); sf::RectangleShape credits; credits.setFillColor(sf::Color(255,255,255)); credits.setSize(sf::Vector2f(100,50)); credits.setPosition(20,90); sf::RectangleShape exit; exit.setFillColor(sf::Color(255,255,255)); exit.setSize(sf::Vector2f(100,50)); exit.setPosition(20,160); sf::RectangleShape cursorAim; cursorAim.setSize(sf::Vector2f(2,2)); cursorAim.setOrigin(1,1); while (window.isOpen()){ window.clear(); sf::Event event; while (window.pollEvent(event)){ if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed){ if (event.key.code == sf::Keyboard::Escape){ window.close(); } } if (event.type == sf::Event::MouseButtonReleased){ cursorAim.setPosition(sf::Mouse::getPosition(window)); if (cursorAim.intersects(play)){ std::cout << "Play ok!" << std::endl; //Hide buttons //joc.play() //Show buttons } else if (cursorAim.instersects(credits)){ std::cout << "Credits ok!" << std::endl; //Hide buttons //Roll the credits //Display buttons } else if (cursorAim.intersects(exit)){ window.close; } } } window.draw(bg); window.draw(play); window.draw(credits); window.draw(exit); window.display(); } }<commit_msg>MENYS M!<commit_after>#include "utils.hpp" void Menu::run(){ sf::RenderWindow window(sf::VideoMode(W_WIDTH, W_HEIGHT), APP_NAME); //sf::Texture spriteSheet; //if (!spriteSheet.loadFromFile("./images/spriteSheet.jpg")) std::cout << "Error loading spriteSheet" << std::endl; sf::RectangleShape bg; //bg.setTexture(spriteSheet); //bg.setTextureRect(posx,posy,midax,miday) bg.setFillColor(sf::Color(0,0,0)); sf::RectangleShape play; play.setFillColor(sf::Color(255,255,255)); play.setSize(sf::Vector2f(150,50)); play.setPosition(20,20); sf::IntRect Rplay(20,20,150,50); sf::RectangleShape credits; credits.setFillColor(sf::Color(255,255,255)); credits.setSize(sf::Vector2f(150,50)); credits.setPosition(20,90); sf::IntRect Rcred(20,90,150,50); sf::RectangleShape exit; exit.setFillColor(sf::Color(255,255,255)); exit.setSize(sf::Vector2f(150,50)); exit.setPosition(20,160); sf::IntRect Rexit(20,160,150,50); while (window.isOpen()){ window.clear(); sf::Event event; while (window.pollEvent(event)){ if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed){ if (event.key.code == sf::Keyboard::Escape){ window.close(); } } if (event.type == sf::Event::MouseButtonReleased){ sf::Vector2i mousepos = sf::Mouse::getPosition(window); sf::IntRect cursorAim(mousepos.x-1,mousepos.y-1,2,2); if (cursorAim.intersects(Rplay)){ std::cout << "Play ok!" << std::endl; //Hide buttons //joc.play() //Show buttons } else if (cursorAim.intersects(Rcred)){ std::cout << "Credits ok!" << std::endl; //Hide buttons //Roll the credits //Display buttons } else if (cursorAim.intersects(Rexit)){ window.close(); } } } window.draw(bg); window.draw(play); window.draw(credits); window.draw(exit); window.display(); } }<|endoftext|>
<commit_before>/*- * Copyright (c) 2008 Michael Marner <michael@20papercups.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // include system headers #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> // include openGL headers #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <wcl/camera/CameraException.h> #include <wcl/camera/VirtualCamera.h> #include <wcl/camera/CameraFactory.h> #define WIDTH 640 using namespace std; using namespace wcl; Camera *cam; unsigned char* data; void usage() { printf("Usage: camera [-l|-h|devicenode]\n" "\n" "eg: camera /dev/video0\n" "\n" "Options:\n" "\n" "-h = List this help\n" "-l = List available cameras then exit\n" "If no device node is given the first available camera is used. If no physical camera exists, the virtual camera is used\n" ); } /** * Initialise OpenGL */ GLvoid init() { glShadeModel(GL_SMOOTH); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)]; // create a texture for the image... glTexImage2D(GL_TEXTURE_2D, //target 0, //level of detail 3, //colour components cam->getActiveConfiguration().width, //width cam->getActiveConfiguration().height, //height 0, //border GL_RGB, //image format GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); } /** * Constantly fetch a new image from the camera to display */ GLvoid idle() { glutPostRedisplay(); } /** * Display Loop. */ GLvoid display() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); const unsigned char* frame = cam->getFrame(Camera::RGB8); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cam->getActiveConfiguration().width, cam->getActiveConfiguration().height, GL_RGB, GL_UNSIGNED_BYTE, frame); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,0,0); glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex2f(0,0); glTexCoord2f(1,1); glVertex2f(1,0); glTexCoord2f(1,0); glVertex2f(1,1); glTexCoord2f(0,0); glVertex2f(0,1); glEnd(); glFlush(); glutSwapBuffers(); // print out any opengl errors to the console GLenum error = glGetError(); if (error != GL_NO_ERROR) { cout << gluErrorString(error) << endl; } } /** * This doesn't do what it is supposed to do! */ GLvoid reshape(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glViewport(0,0, (GLsizei)width, (GLsizei)height); } void keyboard(unsigned char key, int w, int h) { if(key==27) exit(EXIT_SUCCESS); } void listCameras() { cout << "Searching for Cameras..." << endl; std::vector<Camera *> cameras = CameraFactory::getCameras(CameraFactory::ALL); CameraFactory::printDetails(false); } int main(int argc, char** argv) { if(argc >= 2){ if( strcmp(argv[1],"--help") == 0 || strcmp(argv[1],"-h" ) == 0){ usage(); return 1; } if( strcmp(argv[1],"-l") == 0){ listCameras(); return 1; } } try { if( argc == 2 ){ cout << "Attempting to use Camera specified:" << argv[1] <<endl; cam = CameraFactory::getCamera(argv[1], CameraFactory::ALL); } else { cout << "No Camera Specified, using CameraFactory to find the first camera..." << endl; cout << "Searching for Cameras..." << endl; std::vector<Camera *> cameras = CameraFactory::getCameras(CameraFactory::ALL); CameraFactory::printDetails(false); if( cameras.size() == 0 ){ cout << "No physical camera's found, using virtual camera" << endl; cam = new VirtualCamera(); } else { cam = CameraFactory::getCamera(CameraFactory::ALL); } } if (cam == NULL ){ std::cout << "No usable cameras found" << std::endl; exit(0); } /* * Print out camera details */ cam->printDetails(); cout << "Setting Camera to a width of " << WIDTH << " pixels" << endl; Camera::Configuration c; c.width = WIDTH; cam->setConfiguration(cam->findConfiguration(c)); //Set power frequency compensation to 50 Hz //this is noncritical so don't stop the program if it fails try { cam->setControlValue(Camera::POWER_FREQUENCY, 1); }catch(CameraException &e){} // Create GLUT window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height); glutCreateWindow(argv[0]); init(); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutIdleFunc(idle); // GO! glutMainLoop(); cout << "Deleting Cam" << endl; cam->shutdown(); delete cam; } catch (Exception &e) { cout << "Exception Occured: " << e.what() << endl; } return 0; } <commit_msg>examples: Commonize where the search scope is set<commit_after>/*- * Copyright (c) 2008 Michael Marner <michael@20papercups.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // include system headers #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> // include openGL headers #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <wcl/camera/CameraException.h> #include <wcl/camera/VirtualCamera.h> #include <wcl/camera/CameraFactory.h> #define WIDTH 640 #define SEARCHSCOPE CameraFactory::NETWORK using namespace std; using namespace wcl; Camera *cam; unsigned char* data; void usage() { printf("Usage: camera [-l|-h|devicenode]\n" "\n" "eg: camera /dev/video0\n" "\n" "Options:\n" "\n" "-h = List this help\n" "-l = List available cameras then exit\n" "If no device node is given the first available camera is used. If no physical camera exists, the virtual camera is used\n" ); } /** * Initialise OpenGL */ GLvoid init() { glShadeModel(GL_SMOOTH); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)]; // create a texture for the image... glTexImage2D(GL_TEXTURE_2D, //target 0, //level of detail 3, //colour components cam->getActiveConfiguration().width, //width cam->getActiveConfiguration().height, //height 0, //border GL_RGB, //image format GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); } /** * Constantly fetch a new image from the camera to display */ GLvoid idle() { glutPostRedisplay(); } /** * Display Loop. */ GLvoid display() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); const unsigned char* frame = cam->getFrame(Camera::RGB8); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cam->getActiveConfiguration().width, cam->getActiveConfiguration().height, GL_RGB, GL_UNSIGNED_BYTE, frame); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1,0,0); glBegin(GL_QUADS); glTexCoord2f(0,1); glVertex2f(0,0); glTexCoord2f(1,1); glVertex2f(1,0); glTexCoord2f(1,0); glVertex2f(1,1); glTexCoord2f(0,0); glVertex2f(0,1); glEnd(); glFlush(); glutSwapBuffers(); // print out any opengl errors to the console GLenum error = glGetError(); if (error != GL_NO_ERROR) { cout << gluErrorString(error) << endl; } } /** * This doesn't do what it is supposed to do! */ GLvoid reshape(int width, int height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,1,0,1); glMatrixMode(GL_MODELVIEW); glViewport(0,0, (GLsizei)width, (GLsizei)height); } void keyboard(unsigned char key, int w, int h) { if(key==27) exit(EXIT_SUCCESS); } void listCameras() { cout << "Searching for Cameras..." << endl; std::vector<Camera *> cameras = CameraFactory::getCameras(SEARCHSCOPE); CameraFactory::printDetails(false,SEARCHSCOPE); } int main(int argc, char** argv) { if(argc >= 2){ if( strcmp(argv[1],"--help") == 0 || strcmp(argv[1],"-h" ) == 0){ usage(); return 1; } if( strcmp(argv[1],"-l") == 0){ listCameras(); return 1; } } try { if( argc == 2 ){ cout << "Attempting to use Camera specified:" << argv[1] <<endl; cam = CameraFactory::getCamera(argv[1], SEARCHSCOPE); } else { cout << "No Camera Specified, using CameraFactory to find the first camera..." << endl; cout << "Searching for Cameras..." << endl; std::vector<Camera *> cameras = CameraFactory::getCameras(SEARCHSCOPE); CameraFactory::printDetails(false, SEARCHSCOPE); if( cameras.size() == 0 ){ cout << "No physical camera's found, using virtual camera" << endl; cam = new VirtualCamera(); } else { cam = CameraFactory::getCamera(SEARCHSCOPE); } } if (cam == NULL ){ std::cout << "No usable cameras found" << std::endl; exit(0); } /* * Print out camera details */ cam->printDetails(); cout << "Setting Camera to a width of " << WIDTH << " pixels" << endl; Camera::Configuration c; c.width = WIDTH; cam->setConfiguration(cam->findConfiguration(c)); //Set power frequency compensation to 50 Hz //this is noncritical so don't stop the program if it fails try { cam->setControlValue(Camera::POWER_FREQUENCY, 1); }catch(CameraException &e){} // Create GLUT window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height); glutCreateWindow(argv[0]); init(); // register callbacks glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutIdleFunc(idle); // GO! glutMainLoop(); cout << "Deleting Cam" << endl; cam->shutdown(); delete cam; } catch (Exception &e) { cout << "Exception Occured: " << e.what() << endl; } 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 <iostream> #include <fstream> #include <iterator> #include <exception> #include <boost/format.hpp> //#include <boost/date_time/posix_time/posix_time.hpp> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; void set_cursor(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(h, c); } void clear() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', 80 * 50, c, &n); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void set_cursor(int x, int y) { std::cout << "\033[" << y << ";" << x << "H"; } void clear() { std::cout << "\033[2J"; } #endif std::string to_string(float v) { std::stringstream s; s.precision(4); s.flags(std::ios_base::right); s.width(5); s.fill(' '); s << v; return s.str(); } std::string add_suffix(float val) { const char* prefix[] = {"B ", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (val < 1024.f) return to_string(val) + prefix[i]; val /= 1024.f; } return to_string(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; // TEMPORARY boost::filesystem::path::default_name_check(boost::filesystem::no_check); if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, press q.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); // limit upload rate to 100 kB/s // s.set_upload_rate_limit(100 * 1024); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, boost::filesystem::path("", boost::filesystem::native))); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } clear(); set_cursor(0, 0); for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued "; break; case torrent_status::checking_files: std::cout << "checking "; break; case torrent_status::downloading: std::cout << "dloading "; break; case torrent_status::seeding: std::cout << "seeding "; break; }; // calculate download and upload speeds i->get_peer_info(peers); float down = s.download_rate; float up = s.upload_rate; unsigned int total_down = s.total_download; unsigned int total_up = s.total_upload; int num_peers = peers.size(); /* std::cout << boost::format("%f%% p:%d d:(%s) %s/s u:(%s) %s/s\n") % (s.progress*100) % num_peers % add_suffix(total_down) % add_suffix(down) % add_suffix(total_up) % add_suffix(up); */ std::cout << (s.progress*100) << "% p:" << num_peers << " d:(" << add_suffix(total_down) << ") " << add_suffix(down) << "/s u:(" << add_suffix(total_up) << ") " << add_suffix(up) << "/s\n"; boost::posix_time::time_duration t = s.next_announce; // std::cout << "next announce: " << boost::posix_time::to_simple_string(t) << "\n"; std::cout << "next announce: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << "\n"; for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { std::cout << "d: " << add_suffix(i->down_speed) << "/s (" << add_suffix(i->total_download) << ") u: " << add_suffix(i->up_speed) << "/s (" << add_suffix(i->total_upload) << ") diff: " << add_suffix(i->total_download - i->total_upload) << " flags: " << static_cast<const char*>((i->flags & peer_info::interesting)?"I":"_") << static_cast<const char*>((i->flags & peer_info::choked)?"C":"_") << static_cast<const char*>((i->flags & peer_info::remote_interested)?"i":"_") << static_cast<const char*>((i->flags & peer_info::remote_choked)?"c":"_") << "\n"; } /* i->get_download_queue(queue); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { std::cout << i->piece_index << ": "; for (int j = 0; j < i->blocks_in_piece; ++j) { if (i->finished_blocks[j]) std::cout << "+"; else if (i->requested_blocks[j]) std::cout << "-"; else std::cout << "."; } std::cout << "\n"; } */ std::cout << "___________________________________\n"; } } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <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 <iostream> #include <fstream> #include <iterator> #include <exception> #include <boost/format.hpp> //#include <boost/date_time/posix_time/posix_time.hpp> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; void set_cursor(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(h, c); } void clear() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', 80 * 50, c, &n); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void set_cursor(int x, int y) { std::cout << "\033[" << y << ";" << x << "H"; } void clear() { std::cout << "\033[2J"; } #endif std::string to_string(float v) { std::stringstream s; s.precision(3); s.flags(std::ios_base::right); s.width(4); s.fill(' '); s << v; return s.str(); } std::string add_suffix(float val) { const char* prefix[] = {"B ", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (abs(val) < 1024.f) return to_string(val) + prefix[i]; val /= 1024.f; } return to_string(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; // TEMPORARY // boost::filesystem::path::default_name_check(boost::filesystem::no_check); if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, press q.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); // limit upload rate to 100 kB/s // s.set_upload_rate_limit(100 * 1024); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, boost::filesystem::path("", boost::filesystem::native))); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } clear(); set_cursor(0, 0); for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued "; break; case torrent_status::checking_files: std::cout << "checking "; break; case torrent_status::downloading: std::cout << "dloading "; break; case torrent_status::seeding: std::cout << "seeding "; break; }; // calculate download and upload speeds i->get_peer_info(peers); float down = s.download_rate; float up = s.upload_rate; int total_down = s.total_download; int total_up = s.total_upload; int num_peers = peers.size(); /* std::cout << boost::format("%f%% p:%d d:(%s) %s/s u:(%s) %s/s\n") % (s.progress*100) % num_peers % add_suffix(total_down) % add_suffix(down) % add_suffix(total_up) % add_suffix(up); */ std::cout << (s.progress*100) << "% "; for (int i = 0; i < 50; ++i) { if (i / 50.f > s.progress) std::cout << "-"; else std::cout << "#"; } std::cout << "\n"; std::cout << "peers:" << num_peers << " d:" << add_suffix(down) << "/s (" << add_suffix(total_down) << ") u:" << add_suffix(up) << "/s (" << add_suffix(total_up) << ") diff: " << add_suffix(total_down - total_up) << "\n"; boost::posix_time::time_duration t = s.next_announce; // std::cout << "next announce: " << boost::posix_time::to_simple_string(t) << "\n"; std::cout << "next announce: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << "\n"; for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { std::cout << "d: " << add_suffix(i->down_speed) << "/s (" << add_suffix(i->total_download) << ") u: " << add_suffix(i->up_speed) << "/s (" << add_suffix(i->total_upload) << ") df: " << add_suffix((int)i->total_download - (int)i->total_upload) << " f: " << static_cast<const char*>((i->flags & peer_info::interesting)?"I":"_") << static_cast<const char*>((i->flags & peer_info::choked)?"C":"_") << static_cast<const char*>((i->flags & peer_info::remote_interested)?"i":"_") << static_cast<const char*>((i->flags & peer_info::remote_choked)?"c":"_") << "\n"; } std::cout << "___________________________________\n"; i->get_download_queue(queue); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { std::cout.width(4); std::cout.fill(' '); std::cout << i->piece_index << ": |"; for (int j = 0; j < i->blocks_in_piece; ++j) { if (i->finished_blocks[j]) std::cout << "#"; else if (i->requested_blocks[j]) std::cout << "="; else std::cout << "-"; } std::cout << "|\n"; } std::cout << "___________________________________\n"; } } } catch (std::exception& e) { std::cout << e.what() << "\n"; } 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 <iostream> #include <fstream> #include <iterator> #include <exception> #include <boost/format.hpp> //#include <boost/date_time/posix_time/posix_time.hpp> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; void set_cursor(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(h, c); } void clear() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', 80 * 50, c, &n); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void set_cursor(int x, int y) { std::cout << "\033[" << y << ";" << x << "H"; } void clear() { std::cout << "\033[2J"; } #endif std::string to_string(float v) { std::stringstream s; s.precision(4); s.flags(std::ios_base::right); s.width(5); s.fill(' '); s << v; return s.str(); } std::string add_suffix(float val) { const char* prefix[] = {"B ", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (val < 1024.f) return to_string(val) + prefix[i]; val /= 1024.f; } return to_string(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; // TEMPORARY boost::filesystem::path::default_name_check(boost::filesystem::no_check); if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, press q.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); // limit upload rate to 100 kB/s // s.set_upload_rate_limit(100 * 1024); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, boost::filesystem::path("", boost::filesystem::native))); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } clear(); set_cursor(0, 0); for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued "; break; case torrent_status::checking_files: std::cout << "checking "; break; case torrent_status::downloading: std::cout << "dloading "; break; case torrent_status::seeding: std::cout << "seeding "; break; }; // calculate download and upload speeds i->get_peer_info(peers); float down = s.download_rate; float up = s.upload_rate; unsigned int total_down = s.total_download; unsigned int total_up = s.total_upload; int num_peers = peers.size(); /* std::cout << boost::format("%f%% p:%d d:(%s) %s/s u:(%s) %s/s\n") % (s.progress*100) % num_peers % add_suffix(total_down) % add_suffix(down) % add_suffix(total_up) % add_suffix(up); */ std::cout << (s.progress*100) << "% p:" << num_peers << " d:(" << add_suffix(total_down) << ") " << add_suffix(down) << "/s u:(" << add_suffix(total_up) << ") " << add_suffix(up) << "/s\n"; boost::posix_time::time_duration t = s.next_announce; // std::cout << "next announce: " << boost::posix_time::to_simple_string(t) << "\n"; std::cout << "next announce: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << "\n"; for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { std::cout << "d: " << add_suffix(i->down_speed) << "/s (" << add_suffix(i->total_download) << ") u: " << add_suffix(i->up_speed) << "/s (" << add_suffix(i->total_upload) << ") diff: " << add_suffix(i->total_download - i->total_upload) << " flags: " << static_cast<const char*>((i->flags & peer_info::interesting)?"I":"_") << static_cast<const char*>((i->flags & peer_info::choked)?"C":"_") << static_cast<const char*>((i->flags & peer_info::remote_interested)?"i":"_") << static_cast<const char*>((i->flags & peer_info::remote_choked)?"c":"_") << "\n"; } /* i->get_download_queue(queue); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { std::cout << i->piece_index << ": "; for (int j = 0; j < i->blocks_in_piece; ++j) { if (i->finished_blocks[j]) std::cout << "+"; else if (i->requested_blocks[j]) std::cout << "-"; else std::cout << "."; } std::cout << "\n"; } */ std::cout << "___________________________________\n"; } } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <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 <iostream> #include <fstream> #include <iterator> #include <exception> #include <boost/format.hpp> //#include <boost/date_time/posix_time/posix_time.hpp> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; void set_cursor(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(h, c); } void clear() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', 80 * 50, c, &n); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void set_cursor(int x, int y) { std::cout << "\033[" << y << ";" << x << "H"; } void clear() { std::cout << "\033[2J"; } #endif std::string to_string(float v) { std::stringstream s; s.precision(3); s.flags(std::ios_base::right); s.width(4); s.fill(' '); s << v; return s.str(); } std::string add_suffix(float val) { const char* prefix[] = {"B ", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (abs(val) < 1024.f) return to_string(val) + prefix[i]; val /= 1024.f; } return to_string(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; // TEMPORARY // boost::filesystem::path::default_name_check(boost::filesystem::no_check); if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, press q.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); // limit upload rate to 100 kB/s // s.set_upload_rate_limit(100 * 1024); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, boost::filesystem::path("", boost::filesystem::native))); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } clear(); set_cursor(0, 0); for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued "; break; case torrent_status::checking_files: std::cout << "checking "; break; case torrent_status::downloading: std::cout << "dloading "; break; case torrent_status::seeding: std::cout << "seeding "; break; }; // calculate download and upload speeds i->get_peer_info(peers); float down = s.download_rate; float up = s.upload_rate; int total_down = s.total_download; int total_up = s.total_upload; int num_peers = peers.size(); /* std::cout << boost::format("%f%% p:%d d:(%s) %s/s u:(%s) %s/s\n") % (s.progress*100) % num_peers % add_suffix(total_down) % add_suffix(down) % add_suffix(total_up) % add_suffix(up); */ std::cout << (s.progress*100) << "% "; for (int i = 0; i < 50; ++i) { if (i / 50.f > s.progress) std::cout << "-"; else std::cout << "#"; } std::cout << "\n"; std::cout << "peers:" << num_peers << " d:" << add_suffix(down) << "/s (" << add_suffix(total_down) << ") u:" << add_suffix(up) << "/s (" << add_suffix(total_up) << ") diff: " << add_suffix(total_down - total_up) << "\n"; boost::posix_time::time_duration t = s.next_announce; // std::cout << "next announce: " << boost::posix_time::to_simple_string(t) << "\n"; std::cout << "next announce: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << "\n"; for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { std::cout << "d: " << add_suffix(i->down_speed) << "/s (" << add_suffix(i->total_download) << ") u: " << add_suffix(i->up_speed) << "/s (" << add_suffix(i->total_upload) << ") df: " << add_suffix((int)i->total_download - (int)i->total_upload) << " f: " << static_cast<const char*>((i->flags & peer_info::interesting)?"I":"_") << static_cast<const char*>((i->flags & peer_info::choked)?"C":"_") << static_cast<const char*>((i->flags & peer_info::remote_interested)?"i":"_") << static_cast<const char*>((i->flags & peer_info::remote_choked)?"c":"_") << "\n"; } std::cout << "___________________________________\n"; i->get_download_queue(queue); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { std::cout.width(4); std::cout.fill(' '); std::cout << i->piece_index << ": |"; for (int j = 0; j < i->blocks_in_piece; ++j) { if (i->finished_blocks[j]) std::cout << "#"; else if (i->requested_blocks[j]) std::cout << "="; else std::cout << "-"; } std::cout << "|\n"; } std::cout << "___________________________________\n"; } } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <|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. // Note that the single accessor, Module::Get(), is not actually implemented // in this file. This is an intentional hook that allows users of ppapi's // C++ wrapper objects to provide difference semantics for how the singleton // object is accessed. // // In general, users of ppapi will also link in ppp_entrypoints.cc, which // provides a simple default implementation of Module::Get(). // // A notable exception where the default ppp_entrypoints will not work is // when implementing "internal plugins" that are statically linked into the // browser. In this case, the process may actually have multiple Modules // loaded at once making a traditional "singleton" unworkable. To get around // this, the users of ppapi need to get creative about how to properly // implement the Module::Get() so that ppapi's C++ wrappers can find the // right Module object. One example solution is to use thread local storage // to change the Module* returned based on which thread is invoking the // function. Leaving Module::Get() unimplemented provides a hook for // implementing such behavior. #include "ppapi/cpp/module.h" #include <string.h> #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_var.h" #include "ppapi/c/ppp_find.h" #include "ppapi/c/ppp_instance.h" #include "ppapi/c/ppp_printing.h" #include "ppapi/c/ppp_scrollbar.h" #include "ppapi/c/ppp_widget.h" #include "ppapi/c/ppp_zoom.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/rect.h" #include "ppapi/cpp/resource.h" #include "ppapi/cpp/scrollbar.h" #include "ppapi/cpp/url_loader.h" #include "ppapi/cpp/var.h" #include "ppapi/cpp/widget.h" namespace pp { // PPP_Instance implementation ------------------------------------------------- bool Instance_New(PP_Instance instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* obj = module_singleton->CreateInstance(instance); if (obj) { module_singleton->current_instances_[instance] = obj; return true; } return false; } void Instance_Delete(PP_Instance instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Module::InstanceMap::iterator found = module_singleton->current_instances_.find(instance); if (found == module_singleton->current_instances_.end()) return; // Remove it from the map before deleting to try to catch reentrancy. Instance* obj = found->second; module_singleton->current_instances_.erase(found); delete obj; } bool Instance_Initialize(PP_Instance pp_instance, uint32_t argc, const char* argn[], const char* argv[]) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return false; return instance->Init(argc, argn, argv); } bool Instance_HandleDocumentLoad(PP_Instance pp_instance, PP_Resource pp_url_loader) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return false; return instance->HandleDocumentLoad(URLLoader(pp_url_loader)); } bool Instance_HandleEvent(PP_Instance pp_instance, const PP_Event* event) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return false; return instance->HandleEvent(*event); } PP_Var Instance_GetInstanceObject(PP_Instance pp_instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return Var().Detach(); Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return Var().Detach(); return instance->GetInstanceObject().Detach(); } void Instance_ViewChanged(PP_Instance pp_instance, const PP_Rect* position, const PP_Rect* clip) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return; instance->ViewChanged(*position, *clip); } PP_Var GetSelectedText(PP_Instance pp_instance, bool html) { Module* module_singleton = Module::Get(); if (!module_singleton) return Var().Detach(); Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return Var().Detach(); return instance->GetSelectedText(html).Detach(); } static PPP_Instance instance_interface = { &Instance_New, &Instance_Delete, &Instance_Initialize, &Instance_HandleDocumentLoad, &Instance_HandleEvent, &Instance_GetInstanceObject, &Instance_ViewChanged, }; // PPP_Printing implementation ------------------------------------------------- PP_PrintOutputFormat* Printing_QuerySupportedFormats( PP_Instance pp_instance, uint32_t* format_count) { Module* module_singleton = Module::Get(); if (!module_singleton) { *format_count = 0; return NULL; } Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) { *format_count = 0; return NULL; } return instance->QuerySupportedPrintOutputFormats(format_count); } int32_t Printing_Begin(PP_Instance pp_instance, const PP_PrintSettings* print_settings) { Module* module_singleton = Module::Get(); if (!module_singleton) return 0; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return 0; // See if we support the specified print output format. uint32_t format_count = 0; const PP_PrintOutputFormat* formats = instance->QuerySupportedPrintOutputFormats(&format_count); if (!formats) return 0; for (uint32_t index = 0; index < format_count; index++) { if (formats[index] == print_settings->format) return instance->PrintBegin(*print_settings); } return 0; } PP_Resource Printing_PrintPages(PP_Instance pp_instance, const PP_PrintPageNumberRange* page_ranges, uint32_t page_range_count) { Module* module_singleton = Module::Get(); if (!module_singleton) return Resource().pp_resource(); Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return Resource().pp_resource(); return instance->PrintPages(page_ranges, page_range_count).pp_resource(); } void Printing_End(PP_Instance pp_instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return; return instance->PrintEnd(); } static PPP_Printing printing_interface = { &Printing_QuerySupportedFormats, &Printing_Begin, &Printing_PrintPages, &Printing_End, }; // PPP_Widget implementation --------------------------------------------------- void Widget_Invalidate(PP_Instance instance_id, PP_Resource widget_id, const PP_Rect* dirty_rect) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->InvalidateWidget(Widget(widget_id), *dirty_rect); } static PPP_Widget widget_interface = { &Widget_Invalidate, }; // PPP_Scrollbar implementation ------------------------------------------------ void Scrollbar_ValueChanged(PP_Instance instance_id, PP_Resource scrollbar_id, uint32_t value) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->ScrollbarValueChanged(Scrollbar(scrollbar_id), value); } static PPP_Scrollbar scrollbar_interface = { &Scrollbar_ValueChanged, }; // PPP_Zoom implementation ------------------------------------------------ void Zoom(PP_Instance instance_id, float scale, bool text_only) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->Zoom(scale, text_only); } static PPP_Zoom zoom_interface = { &Zoom, }; // PPP_Find implementation ------------------------------------------------ bool StartFind(PP_Instance instance_id, const char* text, bool case_sensitive) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return false; return instance->StartFind(text, case_sensitive); } void SelectFindResult(PP_Instance instance_id, bool forward) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->SelectFindResult(forward); } void StopFind(PP_Instance instance_id) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->StopFind(); } static PPP_Find find_interface = { &StartFind, &SelectFindResult, &StopFind, }; // Module ---------------------------------------------------------------------- Module::Module() : pp_module_(NULL), get_browser_interface_(NULL), core_(NULL) { } Module::~Module() { delete core_; core_ = NULL; } const void* Module::GetInstanceInterface(const char* interface_name) { if (strcmp(interface_name, PPP_INSTANCE_INTERFACE) == 0) return &instance_interface; if (strcmp(interface_name, PPP_PRINTING_INTERFACE) == 0) return &printing_interface; if (strcmp(interface_name, PPP_WIDGET_INTERFACE) == 0) return &widget_interface; if (strcmp(interface_name, PPP_SCROLLBAR_INTERFACE) == 0) return &scrollbar_interface; if (strcmp(interface_name, PPP_ZOOM_INTERFACE) == 0) return &zoom_interface; if (strcmp(interface_name, PPP_FIND_INTERFACE) == 0) return &find_interface; return NULL; } const void* Module::GetBrowserInterface(const char* interface_name) { return get_browser_interface_(interface_name); } Instance* Module::InstanceForPPInstance(PP_Instance instance) { InstanceMap::iterator found = current_instances_.find(instance); if (found == current_instances_.end()) return NULL; return found->second; } bool Module::InternalInit(PP_Module mod, PPB_GetInterface get_browser_interface) { pp_module_ = mod; get_browser_interface_ = get_browser_interface; // Get the core interface which we require to run. const PPB_Core* core = reinterpret_cast<const PPB_Core*>(GetBrowserInterface( PPB_CORE_INTERFACE)); if (!core) return false; core_ = new Core(core); return Init(); } } // namespace pp <commit_msg>Hook up GetSelectedText properly to avoid a crash on right-click.<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. // Note that the single accessor, Module::Get(), is not actually implemented // in this file. This is an intentional hook that allows users of ppapi's // C++ wrapper objects to provide difference semantics for how the singleton // object is accessed. // // In general, users of ppapi will also link in ppp_entrypoints.cc, which // provides a simple default implementation of Module::Get(). // // A notable exception where the default ppp_entrypoints will not work is // when implementing "internal plugins" that are statically linked into the // browser. In this case, the process may actually have multiple Modules // loaded at once making a traditional "singleton" unworkable. To get around // this, the users of ppapi need to get creative about how to properly // implement the Module::Get() so that ppapi's C++ wrappers can find the // right Module object. One example solution is to use thread local storage // to change the Module* returned based on which thread is invoking the // function. Leaving Module::Get() unimplemented provides a hook for // implementing such behavior. #include "ppapi/cpp/module.h" #include <string.h> #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_var.h" #include "ppapi/c/ppp_find.h" #include "ppapi/c/ppp_instance.h" #include "ppapi/c/ppp_printing.h" #include "ppapi/c/ppp_scrollbar.h" #include "ppapi/c/ppp_widget.h" #include "ppapi/c/ppp_zoom.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/rect.h" #include "ppapi/cpp/resource.h" #include "ppapi/cpp/scrollbar.h" #include "ppapi/cpp/url_loader.h" #include "ppapi/cpp/var.h" #include "ppapi/cpp/widget.h" namespace pp { // PPP_Instance implementation ------------------------------------------------- bool Instance_New(PP_Instance instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* obj = module_singleton->CreateInstance(instance); if (obj) { module_singleton->current_instances_[instance] = obj; return true; } return false; } void Instance_Delete(PP_Instance instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Module::InstanceMap::iterator found = module_singleton->current_instances_.find(instance); if (found == module_singleton->current_instances_.end()) return; // Remove it from the map before deleting to try to catch reentrancy. Instance* obj = found->second; module_singleton->current_instances_.erase(found); delete obj; } bool Instance_Initialize(PP_Instance pp_instance, uint32_t argc, const char* argn[], const char* argv[]) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return false; return instance->Init(argc, argn, argv); } bool Instance_HandleDocumentLoad(PP_Instance pp_instance, PP_Resource pp_url_loader) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return false; return instance->HandleDocumentLoad(URLLoader(pp_url_loader)); } bool Instance_HandleEvent(PP_Instance pp_instance, const PP_Event* event) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return false; return instance->HandleEvent(*event); } PP_Var Instance_GetInstanceObject(PP_Instance pp_instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return Var().Detach(); Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return Var().Detach(); return instance->GetInstanceObject().Detach(); } void Instance_ViewChanged(PP_Instance pp_instance, const PP_Rect* position, const PP_Rect* clip) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return; instance->ViewChanged(*position, *clip); } PP_Var Instance_GetSelectedText(PP_Instance pp_instance, bool html) { Module* module_singleton = Module::Get(); if (!module_singleton) return Var().Detach(); Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return Var().Detach(); return instance->GetSelectedText(html).Detach(); } static PPP_Instance instance_interface = { &Instance_New, &Instance_Delete, &Instance_Initialize, &Instance_HandleDocumentLoad, &Instance_HandleEvent, &Instance_GetInstanceObject, &Instance_ViewChanged, &Instance_GetSelectedText, }; // PPP_Printing implementation ------------------------------------------------- PP_PrintOutputFormat* Printing_QuerySupportedFormats( PP_Instance pp_instance, uint32_t* format_count) { Module* module_singleton = Module::Get(); if (!module_singleton) { *format_count = 0; return NULL; } Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) { *format_count = 0; return NULL; } return instance->QuerySupportedPrintOutputFormats(format_count); } int32_t Printing_Begin(PP_Instance pp_instance, const PP_PrintSettings* print_settings) { Module* module_singleton = Module::Get(); if (!module_singleton) return 0; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return 0; // See if we support the specified print output format. uint32_t format_count = 0; const PP_PrintOutputFormat* formats = instance->QuerySupportedPrintOutputFormats(&format_count); if (!formats) return 0; for (uint32_t index = 0; index < format_count; index++) { if (formats[index] == print_settings->format) return instance->PrintBegin(*print_settings); } return 0; } PP_Resource Printing_PrintPages(PP_Instance pp_instance, const PP_PrintPageNumberRange* page_ranges, uint32_t page_range_count) { Module* module_singleton = Module::Get(); if (!module_singleton) return Resource().pp_resource(); Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return Resource().pp_resource(); return instance->PrintPages(page_ranges, page_range_count).pp_resource(); } void Printing_End(PP_Instance pp_instance) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(pp_instance); if (!instance) return; return instance->PrintEnd(); } static PPP_Printing printing_interface = { &Printing_QuerySupportedFormats, &Printing_Begin, &Printing_PrintPages, &Printing_End, }; // PPP_Widget implementation --------------------------------------------------- void Widget_Invalidate(PP_Instance instance_id, PP_Resource widget_id, const PP_Rect* dirty_rect) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->InvalidateWidget(Widget(widget_id), *dirty_rect); } static PPP_Widget widget_interface = { &Widget_Invalidate, }; // PPP_Scrollbar implementation ------------------------------------------------ void Scrollbar_ValueChanged(PP_Instance instance_id, PP_Resource scrollbar_id, uint32_t value) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->ScrollbarValueChanged(Scrollbar(scrollbar_id), value); } static PPP_Scrollbar scrollbar_interface = { &Scrollbar_ValueChanged, }; // PPP_Zoom implementation ------------------------------------------------ void Zoom(PP_Instance instance_id, float scale, bool text_only) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->Zoom(scale, text_only); } static PPP_Zoom zoom_interface = { &Zoom, }; // PPP_Find implementation ------------------------------------------------ bool StartFind(PP_Instance instance_id, const char* text, bool case_sensitive) { Module* module_singleton = Module::Get(); if (!module_singleton) return false; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return false; return instance->StartFind(text, case_sensitive); } void SelectFindResult(PP_Instance instance_id, bool forward) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->SelectFindResult(forward); } void StopFind(PP_Instance instance_id) { Module* module_singleton = Module::Get(); if (!module_singleton) return; Instance* instance = module_singleton->InstanceForPPInstance(instance_id); if (!instance) return; return instance->StopFind(); } static PPP_Find find_interface = { &StartFind, &SelectFindResult, &StopFind, }; // Module ---------------------------------------------------------------------- Module::Module() : pp_module_(NULL), get_browser_interface_(NULL), core_(NULL) { } Module::~Module() { delete core_; core_ = NULL; } const void* Module::GetInstanceInterface(const char* interface_name) { if (strcmp(interface_name, PPP_INSTANCE_INTERFACE) == 0) return &instance_interface; if (strcmp(interface_name, PPP_PRINTING_INTERFACE) == 0) return &printing_interface; if (strcmp(interface_name, PPP_WIDGET_INTERFACE) == 0) return &widget_interface; if (strcmp(interface_name, PPP_SCROLLBAR_INTERFACE) == 0) return &scrollbar_interface; if (strcmp(interface_name, PPP_ZOOM_INTERFACE) == 0) return &zoom_interface; if (strcmp(interface_name, PPP_FIND_INTERFACE) == 0) return &find_interface; return NULL; } const void* Module::GetBrowserInterface(const char* interface_name) { return get_browser_interface_(interface_name); } Instance* Module::InstanceForPPInstance(PP_Instance instance) { InstanceMap::iterator found = current_instances_.find(instance); if (found == current_instances_.end()) return NULL; return found->second; } bool Module::InternalInit(PP_Module mod, PPB_GetInterface get_browser_interface) { pp_module_ = mod; get_browser_interface_ = get_browser_interface; // Get the core interface which we require to run. const PPB_Core* core = reinterpret_cast<const PPB_Core*>(GetBrowserInterface( PPB_CORE_INTERFACE)); if (!core) return false; core_ = new Core(core); return Init(); } } // namespace pp <|endoftext|>
<commit_before>// Challenge 03: // Larges prime palendrome less than 1000 #include <iostream> #include <string> #include <math.h> using namespace std; bool isPrime(int test) { switch(test) { case 1 : return false; case 2 : return true; default : // get rid of evens first if (test % 2 == 0) return false; // test only odd divisors in the loop for (int mod = 3; mod < sqrt(test) + 1 ; mod+=2) { if (test % mod == 0) return false; } return true; } } bool isPalindrome(int input) { std::string test = "" + input; for (int i = 0, j = test.length() - 1 ; i < j ; i++, j-- ) { if (test[i] != test[j]) return false; } return true; } int main(int argc, char ** argv) { for (int i = 1000; i > 0 ; i++) { if (isPrime(i)) { if (isPalindrome(i)) { std::cout << i << std::endl; } } } return 0; } <commit_msg>fix cpp for challenge 3<commit_after>// Challenge 03: // Larges prime palendrome less than 1000 #include <iostream> #include <string> #include <math.h> using namespace std; bool isPrime(int test) { switch(test) { case 1 : return false; case 2 : return true; default : // get rid of evens first if (test % 2 == 0) return false; // test only odd divisors in the loop for (int mod = 3; mod < sqrt(test) + 1 ; mod+=2) { if (test % mod == 0) return false; } return true; } } bool isPalindrome(int input) { std::string test = std::to_string(input); for (int i = 0, j = test.length() - 1 ; i < j ; i++, j-- ) { if (test.at(i) != test.at(j)) return false; } return true; } int main(int argc, char ** argv) { for (int i = 1000; i > 0 ; i--) { if (isPrime(i)) { if (isPalindrome(i)) { std::cout << i << std::endl; return 0; } } } return 1; } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // ecasignalview.cpp: A simple command-line tools for monitoring // signal amplitude. // Copyright (C) 1999-2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> #include <string> #include <vector> #include <cassert> #include <cmath> #include <cstdio> #include <signal.h> #include <unistd.h> #include <kvutils/kvu_com_line.h> #include <kvutils/kvu_utils.h> #include <kvutils/kvu_numtostr.h> #include <eca-control-interface.h> #include "ecicpp_helpers.h" #if defined(ECA_USE_NCURSES_H) || defined(ECA_USE_NCURSES_NCURSES_H) || defined(ECA_USE_CURSES_H) #define ECASV_USE_CURSES 1 #ifdef ECA_USE_NCURSES_H #include <ncurses.h> #include <term.h> /* for setupterm() */ #elif ECA_USE_NCURSES_CURSES_H #include <ncurses/nnurses.h> #include <term.h> /* for setupterm() */ #else #include <curses.h> #include <term.h> /* for setupterm() */ #endif #endif /* ECA_*CURSES_H */ /** * Import namespaces */ using namespace std; /** * Type definitions */ struct ecasv_channel_stats { double last_peak; double drawn_peak; double max_peak; long int clipped_samples; }; /** * Function declarations */ int main(int argc, char *argv[]); void ecasv_parse_command_line(int argc, char *argv[]); void ecasv_fill_defaults(void); std::string ecasv_cop_to_string(ECA_CONTROL_INTERFACE* cop); void ecasv_output_init(void); void ecasv_output_cleanup(void); void ecasv_print_vu_meters(ECA_CONTROL_INTERFACE* eci, std::vector<struct ecasv_channel_stats>* chstats); void ecasv_update_chstats(std::vector<struct ecasv_channel_stats>* chstats, int ch, double value); void ecasv_create_bar(double value, int barlen, unsigned char* barbuf); void ecasv_print_usage(void); void ecasv_signal_handler(int signum); /** * Static global variables */ static const string ecatools_signalview_version = "20021028-5"; static const double ecasv_clipped_threshold_const = 1.0f - 1.0f / 16384.0f; static const int ecasv_bar_length_const = 32; static const int ecasv_header_height_const = 10; static const long int ecasv_rate_default_const = 50; static const long int ecasv_buffersize_default_const = 128; static unsigned char ecasv_bar_buffer[ecasv_bar_length_const + 1] = { 0 }; static bool ecasv_enable_debug, ecasv_enable_cumulative_mode; static long int ecasv_buffersize, ecasv_rate_msec; static string ecasv_input, ecasv_output, ecasv_format_string; static int ecasv_chcount = 0; static ECA_CONTROL_INTERFACE* ecasv_eci_repp = 0; /** * Function definitions */ int main(int argc, char *argv[]) { struct sigaction es_handler; es_handler.sa_handler = ecasv_signal_handler; sigemptyset(&es_handler.sa_mask); es_handler.sa_flags = 0; sigaction(SIGTERM, &es_handler, 0); sigaction(SIGINT, &es_handler, 0); sigaction(SIGQUIT, &es_handler, 0); sigaction(SIGABRT, &es_handler, 0); ecasv_parse_command_line(argc,argv); ECA_CONTROL_INTERFACE eci; eci.command("cs-add default"); eci.command("c-add default"); eci.command("cs-set-param -b:" + kvu_numtostr(ecasv_buffersize)); if (ecasv_format_string.size() > 0) { eci.command("cs-set-audio-format " + ecasv_format_string); } string format; if (ecicpp_add_input(&eci, ecasv_input, &format) < 0) return -1; cout << "Using audio format -f:" << format << "\n"; ecasv_chcount = ecicpp_format_channels(format); cout << "Setting up " << ecasv_chcount << " separate channels for analysis." << endl; if (ecicpp_add_output(&eci, ecasv_output, format) < 0) return -1; ecasv_eci_repp = &eci; vector<struct ecasv_channel_stats> chstats; eci.command("cop-add -evp"); eci.command("cop-add -ev"); if (ecasv_enable_cumulative_mode == true) { eci.command("cop-set 2,1,1"); } eci.command("cop-select 1"); if (ecicpp_connect_chainsetup(&eci, "default") < 0) { return -1; } int secs = 0, msecs = ecasv_rate_msec; while(msecs > 999) { ++secs; msecs -= 1000; } ecasv_output_init(); eci.command("start"); while(true) { kvu_sleep(secs, msecs * 1000000); ecasv_print_vu_meters(&eci, &chstats); } ecasv_output_cleanup(); return 0; } void ecasv_parse_command_line(int argc, char *argv[]) { COMMAND_LINE cline = COMMAND_LINE (argc, argv); if (cline.size() == 0 || cline.has("--version") || cline.has("--help") || cline.has("-h")) { ecasv_print_usage(); exit(1); } ecasv_enable_debug = false; ecasv_enable_cumulative_mode = false; ecasv_rate_msec = 0; ecasv_buffersize = 0; cline.begin(); cline.next(); // 1st argument while (cline.end() != true) { string arg = cline.current(); if (arg.size() > 0) { if (arg[0] != '-') { if (ecasv_input == "") ecasv_input = arg; else if (ecasv_output == "") ecasv_output = arg; } else { string prefix = kvu_get_argument_prefix(arg); if (prefix == "b") ecasv_buffersize = atol(kvu_get_argument_number(1, arg).c_str()); if (prefix == "c") ecasv_enable_cumulative_mode = true; if (prefix == "d") ecasv_enable_debug = true; if (prefix == "f") ecasv_format_string = string(arg.begin() + 3, arg.end()); if (prefix == "r") ecasv_rate_msec = atol(kvu_get_argument_number(1, arg).c_str()); } } cline.next(); } ecasv_fill_defaults(); } void ecasv_fill_defaults(void) { // ECA_RESOURCES ecarc; if (ecasv_input.size() == 0) ecasv_input = "/dev/dsp"; if (ecasv_output.size() == 0) ecasv_output = "null"; if (ecasv_buffersize == 0) ecasv_buffersize = ecasv_buffersize_default_const; if (ecasv_rate_msec == 0) ecasv_rate_msec = ecasv_rate_default_const; if (ecasv_format_string.size() == 0) ecasv_format_string = "s16_le,2,44100,i"; // ecarc.resource("default-audio-format"); } string ecasv_cop_to_string(ECA_CONTROL_INTERFACE* eci) { eci->command("cop-status"); return(eci->last_string()); } void ecasv_output_init(void) { #ifdef ECASV_USE_CURSES initscr(); erase(); mvprintw(0, 0, "******************************************************\n"); mvprintw(1, 0, "* ecasignalview v%s (C) 1999-2002 Kai Vehmanen \n", ecatools_signalview_version.c_str()); mvprintw(2, 0, "******************************************************\n\n"); mvprintw(4, 0, "input=\"%s\"\noutput=\"%s\"\naudio_format=\"%s\", refresh_rate_ms='%ld', buffersize='%ld'\n", ecasv_input.c_str(), ecasv_output.c_str(), ecasv_format_string.c_str(), ecasv_rate_msec, ecasv_buffersize); memset(ecasv_bar_buffer, ' ', ecasv_bar_length_const - 4); ecasv_bar_buffer[ecasv_bar_length_const - 4] = 0; mvprintw(8, 0, "channel-# %s| max-peak clipped-samples\n", ecasv_bar_buffer); mvprintw(9, 0, "----------------------------------------------------------------\n"); move(12, 0); refresh(); #endif } void ecasv_output_cleanup(void) { #ifdef ECASV_USE_CURSES endwin(); #endif // FIXME: should be enabled #if 0 if (ecasv_eci_repp != 0) { cout << endl << endl << endl; ecasv_eci_repp->command("cop-status"); } #endif } void ecasv_print_vu_meters(ECA_CONTROL_INTERFACE* eci, vector<struct ecasv_channel_stats>* chstats) { #ifdef ECASV_USE_CURSES for(int n = 0; n < ecasv_chcount; n++) { eci->command("copp-select " + kvu_numtostr(n + 1)); eci->command("copp-get"); double value = eci->last_float(); ecasv_update_chstats(chstats, n, value); ecasv_create_bar((*chstats)[n].drawn_peak, ecasv_bar_length_const, ecasv_bar_buffer); mvprintw(ecasv_header_height_const+n, 0, "Ch-%d: %s| %.5f %ld\n", n + 1, ecasv_bar_buffer, (*chstats)[n].max_peak, (*chstats)[n].clipped_samples); } move(ecasv_header_height_const + 2 + ecasv_chcount, 0); refresh(); #else cout << ecasv_cop_to_string(eci) << endl; #endif } void ecasv_update_chstats(vector<struct ecasv_channel_stats>* chstats, int ch, double value) { /* 1. in case a new channel is encoutered */ if (static_cast<int>(chstats->size()) <= ch) { chstats->resize(ch + 1); } /* 2. update last_peak and drawn_peak */ (*chstats)[ch].last_peak = value; if ((*chstats)[ch].last_peak < (*chstats)[ch].drawn_peak) { (*chstats)[ch].drawn_peak *= ((*chstats)[ch].last_peak / (*chstats)[ch].drawn_peak); } else { (*chstats)[ch].drawn_peak = (*chstats)[ch].last_peak; } /* 3. update max_peak */ if (value > (*chstats)[ch].max_peak) { (*chstats)[ch].max_peak = value; } /* 4. update clipped_samples counter */ if (value > ecasv_clipped_threshold_const) { (*chstats)[ch].clipped_samples++; } } void ecasv_create_bar(double value, int barlen, unsigned char* barbuf) { int curlen = static_cast<int>(rint(((value / 1.0f) * barlen))); for(int n = 0; n < barlen; n++) { if (n <= curlen) barbuf[n] = '*'; else barbuf[n] = ' '; } } void ecasv_print_usage(void) { cerr << "****************************************************************************\n"; cerr << "* ecasignalview, v" << ecatools_signalview_version << "\n"; cerr << "* (C) 1999-2002 Kai Vehmanen, released under GPL licence\n"; cerr << "****************************************************************************\n"; cerr << "\nUSAGE: ecasignalview [options] [input] [output] \n"; cerr << "\toptions:\n"; cerr << "\t\t-b:buffersize\n"; // cerr << "\t\t-c (cumulative mode)\n"; cerr << "\t\t-d (debug mode)\n"; cerr << "\t\t-f:bits,channels,samplerate\n"; cerr << "\t\t-r:refresh_msec\n\n"; } void ecasv_signal_handler(int signum) { cerr << "Unexpected interrupt... cleaning up.\n"; ecasv_output_cleanup(); exit(1); } <commit_msg>Fix ncurses compilation.<commit_after>// ------------------------------------------------------------------------ // ecasignalview.cpp: A simple command-line tools for monitoring // signal amplitude. // Copyright (C) 1999-2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> #include <string> #include <vector> #include <cassert> #include <cmath> #include <cstdio> #include <signal.h> #include <unistd.h> #include <kvutils/kvu_com_line.h> #include <kvutils/kvu_utils.h> #include <kvutils/kvu_numtostr.h> #include <eca-control-interface.h> #include "ecicpp_helpers.h" #if defined(ECA_USE_NCURSES_H) || defined(ECA_USE_NCURSES_NCURSES_H) || defined(ECA_USE_CURSES_H) #define ECASV_USE_CURSES 1 #ifdef ECA_USE_NCURSES_H #include <ncurses.h> #include <term.h> /* for setupterm() */ #elif ECA_USE_NCURSES_NCURSES_H #include <ncurses/ncurses.h> #include <ncurses/term.h> /* for setupterm() */ #else #include <curses.h> #include <term.h> /* for setupterm() */ #endif #endif /* ECA_*CURSES_H */ /** * Import namespaces */ using namespace std; /** * Type definitions */ struct ecasv_channel_stats { double last_peak; double drawn_peak; double max_peak; long int clipped_samples; }; /** * Function declarations */ int main(int argc, char *argv[]); void ecasv_parse_command_line(int argc, char *argv[]); void ecasv_fill_defaults(void); std::string ecasv_cop_to_string(ECA_CONTROL_INTERFACE* cop); void ecasv_output_init(void); void ecasv_output_cleanup(void); void ecasv_print_vu_meters(ECA_CONTROL_INTERFACE* eci, std::vector<struct ecasv_channel_stats>* chstats); void ecasv_update_chstats(std::vector<struct ecasv_channel_stats>* chstats, int ch, double value); void ecasv_create_bar(double value, int barlen, unsigned char* barbuf); void ecasv_print_usage(void); void ecasv_signal_handler(int signum); /** * Static global variables */ static const string ecatools_signalview_version = "20021028-5"; static const double ecasv_clipped_threshold_const = 1.0f - 1.0f / 16384.0f; static const int ecasv_bar_length_const = 32; static const int ecasv_header_height_const = 10; static const long int ecasv_rate_default_const = 50; static const long int ecasv_buffersize_default_const = 128; static unsigned char ecasv_bar_buffer[ecasv_bar_length_const + 1] = { 0 }; static bool ecasv_enable_debug, ecasv_enable_cumulative_mode; static long int ecasv_buffersize, ecasv_rate_msec; static string ecasv_input, ecasv_output, ecasv_format_string; static int ecasv_chcount = 0; static ECA_CONTROL_INTERFACE* ecasv_eci_repp = 0; /** * Function definitions */ int main(int argc, char *argv[]) { struct sigaction es_handler; es_handler.sa_handler = ecasv_signal_handler; sigemptyset(&es_handler.sa_mask); es_handler.sa_flags = 0; sigaction(SIGTERM, &es_handler, 0); sigaction(SIGINT, &es_handler, 0); sigaction(SIGQUIT, &es_handler, 0); sigaction(SIGABRT, &es_handler, 0); ecasv_parse_command_line(argc,argv); ECA_CONTROL_INTERFACE eci; eci.command("cs-add default"); eci.command("c-add default"); eci.command("cs-set-param -b:" + kvu_numtostr(ecasv_buffersize)); if (ecasv_format_string.size() > 0) { eci.command("cs-set-audio-format " + ecasv_format_string); } string format; if (ecicpp_add_input(&eci, ecasv_input, &format) < 0) return -1; cout << "Using audio format -f:" << format << "\n"; ecasv_chcount = ecicpp_format_channels(format); cout << "Setting up " << ecasv_chcount << " separate channels for analysis." << endl; if (ecicpp_add_output(&eci, ecasv_output, format) < 0) return -1; ecasv_eci_repp = &eci; vector<struct ecasv_channel_stats> chstats; eci.command("cop-add -evp"); eci.command("cop-add -ev"); if (ecasv_enable_cumulative_mode == true) { eci.command("cop-set 2,1,1"); } eci.command("cop-select 1"); if (ecicpp_connect_chainsetup(&eci, "default") < 0) { return -1; } int secs = 0, msecs = ecasv_rate_msec; while(msecs > 999) { ++secs; msecs -= 1000; } ecasv_output_init(); eci.command("start"); while(true) { kvu_sleep(secs, msecs * 1000000); ecasv_print_vu_meters(&eci, &chstats); } ecasv_output_cleanup(); return 0; } void ecasv_parse_command_line(int argc, char *argv[]) { COMMAND_LINE cline = COMMAND_LINE (argc, argv); if (cline.size() == 0 || cline.has("--version") || cline.has("--help") || cline.has("-h")) { ecasv_print_usage(); exit(1); } ecasv_enable_debug = false; ecasv_enable_cumulative_mode = false; ecasv_rate_msec = 0; ecasv_buffersize = 0; cline.begin(); cline.next(); // 1st argument while (cline.end() != true) { string arg = cline.current(); if (arg.size() > 0) { if (arg[0] != '-') { if (ecasv_input == "") ecasv_input = arg; else if (ecasv_output == "") ecasv_output = arg; } else { string prefix = kvu_get_argument_prefix(arg); if (prefix == "b") ecasv_buffersize = atol(kvu_get_argument_number(1, arg).c_str()); if (prefix == "c") ecasv_enable_cumulative_mode = true; if (prefix == "d") ecasv_enable_debug = true; if (prefix == "f") ecasv_format_string = string(arg.begin() + 3, arg.end()); if (prefix == "r") ecasv_rate_msec = atol(kvu_get_argument_number(1, arg).c_str()); } } cline.next(); } ecasv_fill_defaults(); } void ecasv_fill_defaults(void) { // ECA_RESOURCES ecarc; if (ecasv_input.size() == 0) ecasv_input = "/dev/dsp"; if (ecasv_output.size() == 0) ecasv_output = "null"; if (ecasv_buffersize == 0) ecasv_buffersize = ecasv_buffersize_default_const; if (ecasv_rate_msec == 0) ecasv_rate_msec = ecasv_rate_default_const; if (ecasv_format_string.size() == 0) ecasv_format_string = "s16_le,2,44100,i"; // ecarc.resource("default-audio-format"); } string ecasv_cop_to_string(ECA_CONTROL_INTERFACE* eci) { eci->command("cop-status"); return(eci->last_string()); } void ecasv_output_init(void) { #ifdef ECASV_USE_CURSES initscr(); erase(); mvprintw(0, 0, "******************************************************\n"); mvprintw(1, 0, "* ecasignalview v%s (C) 1999-2002 Kai Vehmanen \n", ecatools_signalview_version.c_str()); mvprintw(2, 0, "******************************************************\n\n"); mvprintw(4, 0, "input=\"%s\"\noutput=\"%s\"\naudio_format=\"%s\", refresh_rate_ms='%ld', buffersize='%ld'\n", ecasv_input.c_str(), ecasv_output.c_str(), ecasv_format_string.c_str(), ecasv_rate_msec, ecasv_buffersize); memset(ecasv_bar_buffer, ' ', ecasv_bar_length_const - 4); ecasv_bar_buffer[ecasv_bar_length_const - 4] = 0; mvprintw(8, 0, "channel-# %s| max-peak clipped-samples\n", ecasv_bar_buffer); mvprintw(9, 0, "----------------------------------------------------------------\n"); move(12, 0); refresh(); #endif } void ecasv_output_cleanup(void) { #ifdef ECASV_USE_CURSES endwin(); #endif // FIXME: should be enabled #if 0 if (ecasv_eci_repp != 0) { cout << endl << endl << endl; ecasv_eci_repp->command("cop-status"); } #endif } void ecasv_print_vu_meters(ECA_CONTROL_INTERFACE* eci, vector<struct ecasv_channel_stats>* chstats) { #ifdef ECASV_USE_CURSES for(int n = 0; n < ecasv_chcount; n++) { eci->command("copp-select " + kvu_numtostr(n + 1)); eci->command("copp-get"); double value = eci->last_float(); ecasv_update_chstats(chstats, n, value); ecasv_create_bar((*chstats)[n].drawn_peak, ecasv_bar_length_const, ecasv_bar_buffer); mvprintw(ecasv_header_height_const+n, 0, "Ch-%d: %s| %.5f %ld\n", n + 1, ecasv_bar_buffer, (*chstats)[n].max_peak, (*chstats)[n].clipped_samples); } move(ecasv_header_height_const + 2 + ecasv_chcount, 0); refresh(); #else cout << ecasv_cop_to_string(eci) << endl; #endif } void ecasv_update_chstats(vector<struct ecasv_channel_stats>* chstats, int ch, double value) { /* 1. in case a new channel is encoutered */ if (static_cast<int>(chstats->size()) <= ch) { chstats->resize(ch + 1); } /* 2. update last_peak and drawn_peak */ (*chstats)[ch].last_peak = value; if ((*chstats)[ch].last_peak < (*chstats)[ch].drawn_peak) { (*chstats)[ch].drawn_peak *= ((*chstats)[ch].last_peak / (*chstats)[ch].drawn_peak); } else { (*chstats)[ch].drawn_peak = (*chstats)[ch].last_peak; } /* 3. update max_peak */ if (value > (*chstats)[ch].max_peak) { (*chstats)[ch].max_peak = value; } /* 4. update clipped_samples counter */ if (value > ecasv_clipped_threshold_const) { (*chstats)[ch].clipped_samples++; } } void ecasv_create_bar(double value, int barlen, unsigned char* barbuf) { int curlen = static_cast<int>(rint(((value / 1.0f) * barlen))); for(int n = 0; n < barlen; n++) { if (n <= curlen) barbuf[n] = '*'; else barbuf[n] = ' '; } } void ecasv_print_usage(void) { cerr << "****************************************************************************\n"; cerr << "* ecasignalview, v" << ecatools_signalview_version << "\n"; cerr << "* (C) 1999-2002 Kai Vehmanen, released under GPL licence\n"; cerr << "****************************************************************************\n"; cerr << "\nUSAGE: ecasignalview [options] [input] [output] \n"; cerr << "\toptions:\n"; cerr << "\t\t-b:buffersize\n"; // cerr << "\t\t-c (cumulative mode)\n"; cerr << "\t\t-d (debug mode)\n"; cerr << "\t\t-f:bits,channels,samplerate\n"; cerr << "\t\t-r:refresh_msec\n\n"; } void ecasv_signal_handler(int signum) { cerr << "Unexpected interrupt... cleaning up.\n"; ecasv_output_cleanup(); exit(1); } <|endoftext|>
<commit_before> #include <iostream> #include <fstream> #include <utility> #include <ctime> // TCLAP #include "tclap/CmdLine.h" #include "cereal/archives/json.hpp" #include "rb-filesystem.hpp" #include <sdsl/bit_vectors.hpp> #include <cstdio> #include <cstdlib> #include <libgen.h> #include <sparsepp/spp.h> #include <boost/dynamic_bitset.hpp> using spp::sparse_hash_map; // Custom Headers //#include "uint128_t.hpp" //#include "debug.h" #include "kmer.hpp" //using namespace std; //using namespace sdsl; #include <cstdlib> #include <sys/timeb.h> #include "rb-pack-color.hpp" #include <bitset> #include "rb-vec.hpp" #define LOG2(X) ((unsigned) (8*sizeof (unsigned long long) - __builtin_clzll((X)) - 1)) int getMilliCount() { timeb tb; ftime(&tb); int nCount = tb.millitm + (tb.time & 0xfffff) * 1000; return nCount; } int getMilliSpan(int nTimeStart) { int nSpan = getMilliCount() - nTimeStart; if(nSpan < 0) nSpan += 0x100000 * 1000; return nSpan; } std::string file_extension = ".<extension>"; void parse_arguments(int argc, char **argv, parameters_t & params) { TCLAP::CmdLine cmd("Cosmo Copyright (c) Alex Bowe (alexbowe.com) 2014", ' ', VERSION); TCLAP::UnlabeledValueArg<std::string> input_filename_arg("input", "Input file. Currently only supports DSK's binary format (for k<=64).", true, "", "input_file", cmd); TCLAP::UnlabeledValueArg<std::string> num_colors_arg("num_colors", "Number of colors", true, "", "num colors", cmd); TCLAP::UnlabeledValueArg<std::string> res_dir_arg("dir", "Result directory. Should have created the directory first.", true, "", "res_dir", cmd); TCLAP::UnlabeledValueArg<std::string> pass_arg("pass", "1pass or 2pass", false, "", "pass", cmd); cmd.parse( argc, argv ); params.input_filename = input_filename_arg.getValue(); params.num_colors = atoi(num_colors_arg.getValue().c_str()); params.res_dir = res_dir_arg.getValue(); params.pass = pass_arg.getValue(); } void deserialize_color_bv(std::ifstream &colorfile, color_bv &value) { colorfile.read((char *)&value, sizeof(color_bv)); } bool serialize_info(uint64_t num_colors, uint64_t num_edges, uint64_t num_eqCls, std::string label_type, std::string select_type, std::string eqtable_type, std::string res_dir) { std::string jsonFileName = res_dir + "/info.json"; std::ofstream jsonFile(jsonFileName); { cereal::JSONOutputArchive archive(jsonFile); archive(cereal::make_nvp("label_type", label_type)); archive(cereal::make_nvp("select_type", select_type)); archive(cereal::make_nvp("eqtable_type", eqtable_type)); archive(cereal::make_nvp("num_colors", num_colors)); archive(cereal::make_nvp("num_edges", num_edges)); archive(cereal::make_nvp("num_eqCls", num_eqCls)); } jsonFile.close(); return true; } template <class T1, class T2, class T3> class ColorPacker { public: T1 lblvec; T2 rnkvec; T3 eqTvec; public: ColorPacker(uint64_t eqBitSize, uint64_t lblBitSize) : lblvec(lblBitSize), rnkvec(lblBitSize+1), eqTvec(eqBitSize) { //TODO fillout info file // color cnt // kmer cnt // ... } size_t insertColorLabel(uint64_t num, uint64_t pos) { // most significant bit of number goes down to the end of the bitset uint8_t nbits = static_cast<uint8_t>(floor(LOG2(num+2))); uint64_t lbl = num - ((1<<nbits) - 2); lblvec.setInt(pos, lbl, nbits); return pos + nbits; /*uint8_t nbits = static_cast<uint8_t>(num==0?1:ceil(log2(num+1))); lblvec.setInt(pos, num, nbits); return pos + nbits; */ } bool storeAll(std::string dir, uint64_t bitvecSize, uint64_t eqClsSize) { return eqTvec.serialize(dir + "/eqTable", eqClsSize) && lblvec.serialize(dir + "/lbl", bitvecSize) && rnkvec.serialize(dir + "/rnk", bitvecSize+1); } }; int main(int argc, char * argv[]) { bool sort = true; bool compress = true; std::cerr << "pack-color compiled with supported colors=" << NUM_COLS << std::endl; std::cerr <<"Starting" << std::endl; parameters_t params; parse_arguments(argc, argv, params); if (params.pass == "1pass") sort = false; //Anything else means apply sorting!! HeHe!! if (!rainbowfish::fs::FileExists(params.res_dir.c_str())) { rainbowfish::fs::MakeDir(params.res_dir.c_str()); } const char * file_name = params.input_filename.c_str(); std::cerr << "file name: " << file_name << std::endl; const char * res_dir = params.res_dir.c_str();//"bitvectors"; // Open File std::ifstream colorfile(file_name, std::ios::in|std::ios::binary); colorfile.seekg(0, colorfile.end); size_t end = colorfile.tellg(); std::cerr << "file size: " << end << std::endl; std::cerr << "sizeof(color_bv): " << sizeof(color_bv) << std::endl; size_t num_color = params.num_colors; size_t num_edges = end / sizeof(color_bv); int startTime = getMilliCount(); int checkPointTime = getMilliCount(); int allocationTime = getMilliCount(); //FIRST ROUND going over all edges // Read file and fill out equivalence classes std::cerr << "edges: " << num_edges << " colors: " << num_color << " Total: " << num_edges * num_color << std::endl; ColorPacker<RBVecCompressed, RBVecCompressed, RBVecCompressed> * cp; // ColorPacker<RBVec, RBVec, RBVec> * cp; std::vector<std::pair<color_bv, uint64_t>> eqClsVec; uint64_t curPos = 0; if (sort) { sparse_hash_map<color_bv, uint64_t> eqCls; colorfile.seekg(0, colorfile.beg); for (size_t i=0; i < num_edges; i++) { if (i % 100000000 == 0) { std::cerr<<getMilliSpan(checkPointTime) << " ms : "<<i<<std::endl; checkPointTime = getMilliCount(); } color_bv value; deserialize_color_bv(colorfile, value); if (eqCls.find(value)==eqCls.end()) eqCls[value] = 1; else eqCls[value] = eqCls[value]+1; } std::cerr << getMilliSpan(allocationTime) << " ms : Succinct builder object allocated" << std::endl; checkPointTime = getMilliCount(); // Put data in hashmap to vector for further probable sorting!! eqClsVec.reserve(eqCls.size()); for (const auto& c : eqCls) { eqClsVec.push_back(c); } // sort the hashmap auto cmp = [](std::pair<color_bv, uint64_t> const & a, std::pair<color_bv, uint64_t> const & b) { return a.second > b.second; }; std::sort(eqClsVec.begin(), eqClsVec.end(), cmp); // replacing labels instead of k-mer counts as the hash map values int lbl = 0; size_t totalBits = 0; uint64_t total_edges = 0; for (const auto& c : eqClsVec) { std::cout <<lbl<< " , "<< c.second<<"\n "; total_edges += c.second; //for (uint64_t k=0;k<num_color;k++) if (c.first[k] == true) std::cout<<k<<" "; //std::cout<<"\n"; totalBits += (lbl==0?c.second:ceil(log2(lbl+1))*c.second); eqCls[c.first] = lbl++; } std::cerr << getMilliSpan(checkPointTime) << " ms : (Sorting eq vector and ) assigning a label to each eq class." << std::endl; std::cerr << " Total edge vs total edge: "<<total_edges<<" vs "<< num_edges<<"\n"; size_t vecBits = totalBits; totalBits *= 2; totalBits += num_color * eqCls.size(); std::cerr << "total bits: " << totalBits << " or " << totalBits/(8*pow(1024,2)) << " MB\n"; cp = new ColorPacker<RBVecCompressed, RBVecCompressed, RBVecCompressed>(eqCls.size()*num_color, vecBits); // cp = new ColorPacker<RBVec, RBVec, RBVec>(eqCls.size()*num_color, vecBits); // SECOND ROUND going over all edges checkPointTime = getMilliCount(); int packStartTime = getMilliCount(); // create label & rank vectors colorfile.seekg(0, colorfile.beg); for (size_t i=0; i < num_edges; i++) { if (i % 100000000 == 0) { std::cerr<<getMilliSpan(checkPointTime) << " ms : "<<i<<std::endl; checkPointTime = getMilliCount(); } color_bv value; deserialize_color_bv(colorfile, value); (cp->rnkvec).set(curPos); curPos = cp->insertColorLabel(eqCls[value], curPos); } (cp->rnkvec).set(curPos); std::cerr << "\n" << getMilliSpan(packStartTime) << " ms : Packing label & rank into bitvector." << std::endl; } else { sparse_hash_map<color_bv, std::pair<uint64_t, uint64_t>> eqCls; checkPointTime = getMilliCount(); int packStartTime = getMilliCount(); // create label & rank vectors colorfile.seekg(0, colorfile.beg); cp = new ColorPacker<RBVecCompressed, RBVecCompressed, RBVecCompressed>(num_color*num_color, 2*num_edges*num_color); // cp = new ColorPacker<RBVec, RBVec, RBVec>(num_color*num_color, 2*num_edges*num_color); for (size_t i=0; i < num_edges; i++) { if (i % 100000000 == 0) { std::cerr<<getMilliSpan(checkPointTime) << " ms : "<<i<<std::endl; checkPointTime = getMilliCount(); } color_bv value; deserialize_color_bv(colorfile, value); if (eqCls.find(value)==eqCls.end()) { eqCls[value] = std::make_pair(eqClsVec.size(), 1); eqClsVec.push_back(std::make_pair(value, eqCls[value].first)); } else eqCls[value].second += 1; (cp->rnkvec).set(curPos); curPos = cp->insertColorLabel(eqCls[value].first, curPos); } (cp->rnkvec).set(curPos); std::cerr << "\n" << getMilliSpan(packStartTime) << " ms : Packing label & rank into bitvector." << std::endl; uint64_t eqCntr = 0; for (const auto& c : eqClsVec) { std::cout<<eqCntr++<<" , "<<(eqCls[c.first]).second<<"\n"; } } // pack eqTable in bitvector checkPointTime = getMilliCount(); uint64_t i = 0; for (const auto& c : eqClsVec) { for (size_t j = 0; j < num_color; ++j) { if (c.first[j]) (cp->eqTvec).set(i); i++; } } std::cerr << getMilliSpan(checkPointTime) << " ms : Packing eq. table into bitvector." << std::endl; checkPointTime = getMilliCount(); cp->storeAll(res_dir, curPos, eqClsVec.size()*num_color); std::cerr << getMilliSpan(checkPointTime) << " ms : Storing all three bitvectors." << std::endl << std::endl; serialize_info(num_color, num_edges, eqClsVec.size(), "uncompressed", "compressed", "compressed", res_dir); std::cerr << getMilliSpan(startTime)/1000.0 << " s : Total Time." << std::endl; } <commit_msg>Correct the way we calculate totalBits.<commit_after> #include <iostream> #include <fstream> #include <utility> #include <ctime> // TCLAP #include "tclap/CmdLine.h" #include "cereal/archives/json.hpp" #include "rb-filesystem.hpp" #include <sdsl/bit_vectors.hpp> #include <cstdio> #include <cstdlib> #include <libgen.h> #include <sparsepp/spp.h> #include <boost/dynamic_bitset.hpp> using spp::sparse_hash_map; // Custom Headers //#include "uint128_t.hpp" //#include "debug.h" #include "kmer.hpp" //using namespace std; //using namespace sdsl; #include <cstdlib> #include <sys/timeb.h> #include "rb-pack-color.hpp" #include <bitset> #include "rb-vec.hpp" #define LOG2(X) ((unsigned) (8*sizeof (unsigned long long) - __builtin_clzll((X)) - 1)) int getMilliCount() { timeb tb; ftime(&tb); int nCount = tb.millitm + (tb.time & 0xfffff) * 1000; return nCount; } int getMilliSpan(int nTimeStart) { int nSpan = getMilliCount() - nTimeStart; if(nSpan < 0) nSpan += 0x100000 * 1000; return nSpan; } std::string file_extension = ".<extension>"; void parse_arguments(int argc, char **argv, parameters_t & params) { TCLAP::CmdLine cmd("Cosmo Copyright (c) Alex Bowe (alexbowe.com) 2014", ' ', VERSION); TCLAP::UnlabeledValueArg<std::string> input_filename_arg("input", "Input file. Currently only supports DSK's binary format (for k<=64).", true, "", "input_file", cmd); TCLAP::UnlabeledValueArg<std::string> num_colors_arg("num_colors", "Number of colors", true, "", "num colors", cmd); TCLAP::UnlabeledValueArg<std::string> res_dir_arg("dir", "Result directory. Should have created the directory first.", true, "", "res_dir", cmd); TCLAP::UnlabeledValueArg<std::string> pass_arg("pass", "1pass or 2pass", false, "", "pass", cmd); cmd.parse( argc, argv ); params.input_filename = input_filename_arg.getValue(); params.num_colors = atoi(num_colors_arg.getValue().c_str()); params.res_dir = res_dir_arg.getValue(); params.pass = pass_arg.getValue(); } void deserialize_color_bv(std::ifstream &colorfile, color_bv &value) { colorfile.read((char *)&value, sizeof(color_bv)); } bool serialize_info(uint64_t num_colors, uint64_t num_edges, uint64_t num_eqCls, std::string label_type, std::string select_type, std::string eqtable_type, std::string res_dir) { std::string jsonFileName = res_dir + "/info.json"; std::ofstream jsonFile(jsonFileName); { cereal::JSONOutputArchive archive(jsonFile); archive(cereal::make_nvp("label_type", label_type)); archive(cereal::make_nvp("select_type", select_type)); archive(cereal::make_nvp("eqtable_type", eqtable_type)); archive(cereal::make_nvp("num_colors", num_colors)); archive(cereal::make_nvp("num_edges", num_edges)); archive(cereal::make_nvp("num_eqCls", num_eqCls)); } jsonFile.close(); return true; } template <class T1, class T2, class T3> class ColorPacker { public: T1 lblvec; T2 rnkvec; T3 eqTvec; public: ColorPacker(uint64_t eqBitSize, uint64_t lblBitSize) : lblvec(lblBitSize), rnkvec(lblBitSize+1), eqTvec(eqBitSize) { //TODO fillout info file // color cnt // kmer cnt // ... } size_t insertColorLabel(uint64_t num, uint64_t pos) { // most significant bit of number goes down to the end of the bitset uint8_t nbits = static_cast<uint8_t>(LOG2(num+2)); uint64_t lbl = num - ((1<<nbits) - 2); lblvec.setInt(pos, lbl, nbits); return pos + nbits; /*uint8_t nbits = static_cast<uint8_t>(num==0?1:ceil(log2(num+1))); lblvec.setInt(pos, num, nbits); return pos + nbits; */ } bool storeAll(std::string dir, uint64_t bitvecSize, uint64_t eqClsSize) { return eqTvec.serialize(dir + "/eqTable", eqClsSize) && lblvec.serialize(dir + "/lbl", bitvecSize) && rnkvec.serialize(dir + "/rnk", bitvecSize+1); } }; int main(int argc, char * argv[]) { int startTime = getMilliCount(); bool sort = true; bool compress = true; //std::cerr << "pack-color compiled with supported colors=" << NUM_COLS << std::endl; //std::cerr <<"Starting" << std::endl; parameters_t params; parse_arguments(argc, argv, params); if (params.pass == "1pass") sort = false; //Anything else means apply sorting!! HeHe!! if (!rainbowfish::fs::FileExists(params.res_dir.c_str())) { rainbowfish::fs::MakeDir(params.res_dir.c_str()); } const char * file_name = params.input_filename.c_str(); //std::cerr << "file name: " << file_name << std::endl; const char * res_dir = params.res_dir.c_str();//"bitvectors"; // Open File std::ifstream colorfile(file_name, std::ios::in|std::ios::binary); colorfile.seekg(0, colorfile.end); size_t end = colorfile.tellg(); //std::cerr << "file size: " << end << std::endl; //std::cerr << "sizeof(color_bv): " << sizeof(color_bv) << std::endl; size_t num_color = params.num_colors; size_t num_edges = end / sizeof(color_bv); int checkPointTime = getMilliCount(); int allocationTime = getMilliCount(); //FIRST ROUND going over all edges // Read file and fill out equivalence classes //std::cerr << "edges: " << num_edges << " colors: " << num_color << " Total: " << num_edges * num_color << std::endl; // ColorPacker<RBVecCompressed, RBVecCompressed, RBVecCompressed> * cp; // ColorPacker<RBVec, RBVec, RBVec> * cp; ColorPacker<RBVec, RBVecCompressed, RBVecCompressed> * cp; std::vector<std::pair<color_bv, uint64_t>> eqClsVec; uint64_t curPos = 0; if (sort) { sparse_hash_map<color_bv, uint64_t> eqCls; colorfile.seekg(0, colorfile.beg); for (size_t i=0; i < num_edges; i++) { if (i % 100000000 == 0) { std::cerr<<getMilliSpan(checkPointTime) << " ms : "<<i<< " out of "<<num_edges<<std::endl; checkPointTime = getMilliCount(); } color_bv value; deserialize_color_bv(colorfile, value); if (eqCls.find(value)==eqCls.end()) eqCls[value] = 1; else eqCls[value] = eqCls[value]+1; } //std::cerr << getMilliSpan(allocationTime) << " ms : Succinct builder object allocated" << std::endl; //checkPointTime = getMilliCount(); // Put data in hashmap to vector for further probable sorting!! eqClsVec.reserve(eqCls.size()); for (const auto& c : eqCls) { eqClsVec.push_back(c); } // sort the hashmap auto cmp = [](std::pair<color_bv, uint64_t> const & a, std::pair<color_bv, uint64_t> const & b) { return a.second > b.second; }; std::sort(eqClsVec.begin(), eqClsVec.end(), cmp); // replacing labels instead of k-mer counts as the hash map values int lbl = 0; size_t totalBits = 0; uint64_t total_edges = 0; for (const auto& c : eqClsVec) { //std::cout <<lbl<< " , "<< c.second<<"\n "; total_edges += c.second; //for (uint64_t k=0;k<num_color;k++) if (c.first[k] == true) std::cout<<k<<" "; //std::cout<<"\n"; //totalBits += (lbl==0?c.second:ceil(log2(lbl+1))*c.second); totalBits += floor(LOG2(lbl+2))*c.second; eqCls[c.first] = lbl++; } //std::cerr << getMilliSpan(checkPointTime) << " ms : (Sorting eq vector and ) assigning a label to each eq class." << std::endl; //std::cerr << " Total edge vs total edge: "<<total_edges<<" vs "<< num_edges<<"\n"; size_t vecBits = totalBits; totalBits *= 2; totalBits += num_color * eqCls.size(); std::cerr << "total bits: " << totalBits << " or " << totalBits/(8*pow(1024,2)) << " MB\n"; // cp = new ColorPacker<RBVecCompressed, RBVecCompressed, RBVecCompressed>(eqCls.size()*num_color, vecBits); // cp = new ColorPacker<RBVec, RBVec, RBVec>(eqCls.size()*num_color, vecBits); cp = new ColorPacker<RBVec, RBVecCompressed, RBVecCompressed>(eqCls.size()*num_color, vecBits); // SECOND ROUND going over all edges //checkPointTime = getMilliCount(); int packStartTime = getMilliCount(); // create label & rank vectors colorfile.seekg(0, colorfile.beg); for (size_t i=0; i < num_edges; i++) { if (i % 100000000 == 0) { std::cerr<<getMilliSpan(checkPointTime) << " ms : "<<i<<" out of "<<num_edges<<std::endl; checkPointTime = getMilliCount(); } color_bv value; deserialize_color_bv(colorfile, value); (cp->rnkvec).set(curPos); curPos = cp->insertColorLabel(eqCls[value], curPos); } (cp->rnkvec).set(curPos); //std::cerr << "\n" << getMilliSpan(packStartTime) << " ms : Packing label & rank into bitvector." << std::endl; } else { sparse_hash_map<color_bv, std::pair<uint64_t, uint64_t>> eqCls; //checkPointTime = getMilliCount(); int packStartTime = getMilliCount(); // create label & rank vectors colorfile.seekg(0, colorfile.beg); // cp = new ColorPacker<RBVecCompressed, RBVecCompressed, RBVecCompressed>(num_color*num_color, 2*num_edges*num_color); // cp = new ColorPacker<RBVec, RBVec, RBVec>(num_color*num_color, 2*num_edges*num_color); cp = new ColorPacker<RBVec, RBVecCompressed, RBVecCompressed>(num_color*num_color, 2*num_edges*num_color); for (size_t i=0; i < num_edges; i++) { if (i % 100000000 == 0) { std::cerr<<getMilliSpan(checkPointTime) << " ms : "<<i<<" out of "<<num_edges<<std::endl; checkPointTime = getMilliCount(); } color_bv value; deserialize_color_bv(colorfile, value); if (eqCls.find(value)==eqCls.end()) { eqCls[value] = std::make_pair(eqClsVec.size(), 1); eqClsVec.push_back(std::make_pair(value, eqCls[value].first)); } else eqCls[value].second += 1; (cp->rnkvec).set(curPos); curPos = cp->insertColorLabel(eqCls[value].first, curPos); } (cp->rnkvec).set(curPos); //std::cerr << "\n" << getMilliSpan(packStartTime) << " ms : Packing label & rank into bitvector." << std::endl; uint64_t eqCntr = 0; /*for (const auto& c : eqClsVec) { std::cout<<eqCntr++<<" , "<<(eqCls[c.first]).second<<"\n"; }*/ } // pack eqTable in bitvector //checkPointTime = getMilliCount(); uint64_t i = 0; for (const auto& c : eqClsVec) { for (size_t j = 0; j < num_color; ++j) { if (c.first[j]) (cp->eqTvec).set(i); i++; } } //std::cerr << getMilliSpan(checkPointTime) << " ms : Packing eq. table into bitvector." << std::endl; //checkPointTime = getMilliCount(); cp->storeAll(res_dir, curPos, eqClsVec.size()*num_color); //std::cerr << getMilliSpan(checkPointTime) << " ms : Storing all three bitvectors." << std::endl << std::endl; serialize_info(num_color, num_edges, eqClsVec.size(), "uncompressed", "compressed", "compressed", res_dir); std::cerr << getMilliSpan(startTime)/1000.0 << " s : Total Time." << std::endl; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <cctype> #include <cstdlib> #include "node.hpp" using std::string; using std::stringstream; using std::cout; using std::cerr; using std::endl; namespace Sass { size_t Node::fresh = 0; size_t Node::copied = 0; Node Node::clone() const { Node n; n.line_number = line_number; n.token = token; n.numeric_value = numeric_value; n.type = type; n.has_rules_or_comments = has_rules_or_comments; n.has_rulesets = has_rulesets; n.has_propsets = has_propsets; n.has_backref = has_backref; n.from_variable = from_variable; n.eval_me = eval_me; n.is_hex = is_hex; if (children) { n.children = new vector<Node>(); n.children->reserve(size()); for (int i = 0; i < size(); ++i) { n << at(i); } } ++fresh; return n; } string Node::to_string(const string& prefix) const { switch (type) { case selector_group: { // really only needed for arg to :not string result(at(0).to_string("")); for (int i = 1; i < size(); ++i) { result += ", "; result += at(i).to_string(""); } return result; } break; case selector: { string result; if (!has_backref && !prefix.empty()) { result += prefix; result += ' '; } if (children->at(0).type == selector_combinator) { result += string(children->at(0).token); result += ' '; } else { result += children->at(0).to_string(prefix); } for (int i = 1; i < children->size(); ++i) { result += children->at(i).to_string(prefix); } return result; } break; case selector_combinator: { if (std::isspace(token.begin[0])) return string(" "); else return string(" ") += string(token) += string(" "); } break; case simple_selector_sequence: { string result; for (int i = 0; i < children->size(); ++i) { result += children->at(i).to_string(prefix); } return result; } break; case pseudo_negation: { string result(children->at(0).to_string(prefix)); result += children->at(1).to_string(prefix); result += ')'; return result; } break; case functional_pseudo: { string result(children->at(0).to_string(prefix)); for (int i = 1; i < children->size(); ++i) { result += children->at(i).to_string(prefix); } result += ')'; return result; } break; case attribute_selector: { string result("["); for (int i = 0; i < 3; ++i) { result += children->at(i).to_string(prefix); } result += ']'; return result; } break; case backref: { return prefix; } break; case comma_list: { string result(children->at(0).to_string(prefix)); for (int i = 1; i < children->size(); ++i) { result += ", "; result += children->at(i).to_string(prefix); } return result; } break; case space_list: { string result(children->at(0).to_string(prefix)); for (int i = 1; i < children->size(); ++i) { result += " "; result += children->at(i).to_string(prefix); } return result; } break; case expression: case term: { string result(children->at(0).to_string(prefix)); // for (int i = 2; i < children->size(); i += 2) { // // result += " "; // result += children->at(i).to_string(prefix); // } for (int i = 1; i < children->size(); ++i) { if (!(children->at(i).type == add || // children->at(i).type == sub || // another edge case -- consider uncommenting children->at(i).type == mul)) { result += children->at(i).to_string(prefix); } } return result; } break; //edge case case sub: { return "-"; } break; case div: { return "/"; } break; case numeric_dimension: { stringstream ss; // ss.setf(std::ios::fixed, std::ios::floatfield); // ss.precision(3); ss << numeric_value << string(token); return ss.str(); } break; case number: { stringstream ss; // ss.setf(std::ios::fixed, std::ios::floatfield); // ss.precision(3); ss << numeric_value; return ss.str(); } break; case hex_triple: { double a = children->at(0).numeric_value; double b = children->at(1).numeric_value; double c = children->at(2).numeric_value; if (a >= 0xff && b >= 0xff && c >= 0xff) { return "white"; } else if (a >= 0xff && b >= 0xff && c == 0) { return "yellow"; } else if (a == 0 && b >= 0xff && c >= 0xff) { return "aqua"; } else if (a >= 0xff && b == 0 && c >= 0xff) { return "fuchsia"; } else if (a >= 0xff && b == 0 && c == 0) { return "red"; } else if (a == 0 && b >= 0xff && c == 0) { return "lime"; } else if (a == 0 && b == 0 && c >= 0xff) { return "blue"; } else if (a <= 0 && b <= 0 && c <= 0) { return "black"; } else { stringstream ss; ss << '#' << std::setw(2) << std::setfill('0') << std::hex; for (int i = 0; i < 3; ++i) { double x = children->at(i).numeric_value; if (x > 0xff) x = 0xff; else if (x < 0) x = 0; ss << std::hex << std::setw(2) << static_cast<unsigned long>(x); } return ss.str(); } } break; case uri: { string result("url("); result += string(token); result += ")"; return result; } break; default: { return string(token); } break; } } void Node::echo(stringstream& buf, size_t depth) { string indentation(2*depth, ' '); switch (type) { case comment: buf << indentation << string(token) << endl; break; case ruleset: buf << indentation; children->at(0).echo(buf, depth); children->at(1).echo(buf, depth); break; case selector_group: children->at(0).echo(buf, depth); for (int i = 1; i < children->size(); ++i) { buf << ", "; children->at(i).echo(buf, depth); } break; case selector: for (int i = 0; i < children->size(); ++i) { children->at(i).echo(buf, depth); } break; case selector_combinator: if (std::isspace(token.begin[0])) buf << ' '; else buf << ' ' << string(token) << ' '; break; case simple_selector_sequence: for (int i = 0; i < children->size(); ++i) { buf << children->at(i).to_string(string()); } break; case simple_selector: buf << string(token); break; case block: buf << " {" << endl; for (int i = 0; i < children->size(); children->at(i++).echo(buf, depth+1)) ; buf << indentation << "}" << endl; break; case rule: buf << indentation; children->at(0).echo(buf, depth); buf << ": "; children->at(1).echo(buf, depth); buf << ';' << endl; break; case property: buf << string(token); break; case values: for (int i = 0; i < children->size(); children->at(i++).echo(buf, depth)) ; break; case value: buf << ' ' << string(token); break; } } void Node::emit_nested_css(stringstream& buf, size_t depth, const vector<string>& prefixes) { switch (type) { case root: for (int i = 0; i < children->size(); ++i) { children->at(i).emit_nested_css(buf, depth, prefixes); } break; case ruleset: { Node sel_group(children->at(0)); Node block(children->at(1)); vector<string> new_prefixes; if (prefixes.empty()) { new_prefixes.reserve(sel_group.children->size()); for (int i = 0; i < sel_group.children->size(); ++i) { new_prefixes.push_back(sel_group.children->at(i).to_string(string())); } } else { new_prefixes.reserve(prefixes.size() * sel_group.children->size()); for (int i = 0; i < prefixes.size(); ++i) { for (int j = 0; j < sel_group.children->size(); ++j) { new_prefixes.push_back(sel_group.children->at(j).to_string(prefixes[i])); } } } if (block.has_rules_or_comments) { buf << string(2*depth, ' ') << new_prefixes[0]; for (int i = 1; i < new_prefixes.size(); ++i) { buf << ", " << new_prefixes[i]; } buf << " {"; for (int i = 0; i < block.children->size(); ++i) { Type stm_type = block.children->at(i).type; if (stm_type == comment || stm_type == rule) { block.children->at(i).emit_nested_css(buf, depth+1); // NEED OVERLOADED VERSION FOR COMMENTS AND RULES } } buf << " }" << endl; ++depth; // if we printed content at this level, we need to indent any nested rulesets } if (block.has_rulesets) { for (int i = 0; i < block.children->size(); ++i) { if (block.children->at(i).type == ruleset) { block.children->at(i).emit_nested_css(buf, depth, new_prefixes); } } } if (block.has_rules_or_comments) --depth; if (depth == 0 && prefixes.empty()) buf << endl; } break; default: emit_nested_css(buf, depth); // pass it along to the simpler version break; } } void Node::emit_nested_css(stringstream& buf, size_t depth) { switch (type) { case rule: buf << endl << string(2*depth, ' '); children->at(0).emit_nested_css(buf, depth); // property children->at(1).emit_nested_css(buf, depth); // values buf << ";"; break; case property: buf << string(token) << ": "; break; case values: for (int i = 0; i < children->size(); ++i) { buf << " " << string(children->at(i).token); } break; case comment: if (depth != 0) buf << endl; buf << string(2*depth, ' ') << string(token); if (depth == 0) buf << endl; break; default: buf << to_string(""); break; } } void Node::emit_expanded_css(stringstream& buf, const string& prefix) { // switch (type) { // case selector: // if (!prefix.empty()) buf << " "; // buf << string(token); // break; // case comment: // if (!prefix.empty()) buf << " "; // buf << string(token) << endl; // break; // case property: // buf << string(token) << ":"; // break; // case values: // for (int i = 0; i < children.size(); ++i) { // buf << " " << string(children[i].token); // } // break; // case rule: // buf << " "; // children[0].emit_expanded_css(buf, prefix); // children[1].emit_expanded_css(buf, prefix); // buf << ";" << endl; // break; // case clauses: // if (children.size() > 0) { // buf << " {" << endl; // for (int i = 0; i < children.size(); ++i) // children[i].emit_expanded_css(buf, prefix); // buf << "}" << endl; // } // for (int i = 0; i < opt_children.size(); ++i) // opt_children[i].emit_expanded_css(buf, prefix); // break; // case ruleset: // // buf << prefix; // if (children[1].children.size() > 0) { // buf << prefix << (prefix.empty() ? "" : " "); // children[0].emit_expanded_css(buf, ""); // } // string newprefix(prefix.empty() ? prefix : prefix + " "); // children[1].emit_expanded_css(buf, newprefix + string(children[0].token)); // if (prefix.empty()) buf << endl; // break; // } } }<commit_msg>Whoops, need to do a deep copy.<commit_after>#include <iostream> #include <iomanip> #include <string> #include <cctype> #include <cstdlib> #include "node.hpp" using std::string; using std::stringstream; using std::cout; using std::cerr; using std::endl; namespace Sass { size_t Node::fresh = 0; size_t Node::copied = 0; Node Node::clone() const { Node n; n.line_number = line_number; n.token = token; n.numeric_value = numeric_value; n.type = type; n.has_rules_or_comments = has_rules_or_comments; n.has_rulesets = has_rulesets; n.has_propsets = has_propsets; n.has_backref = has_backref; n.from_variable = from_variable; n.eval_me = eval_me; n.is_hex = is_hex; if (children) { n.children = new vector<Node>(); n.children->reserve(size()); for (int i = 0; i < size(); ++i) { n << at(i).clone(); } } ++fresh; return n; } string Node::to_string(const string& prefix) const { switch (type) { case selector_group: { // really only needed for arg to :not string result(at(0).to_string("")); for (int i = 1; i < size(); ++i) { result += ", "; result += at(i).to_string(""); } return result; } break; case selector: { string result; if (!has_backref && !prefix.empty()) { result += prefix; result += ' '; } if (children->at(0).type == selector_combinator) { result += string(children->at(0).token); result += ' '; } else { result += children->at(0).to_string(prefix); } for (int i = 1; i < children->size(); ++i) { result += children->at(i).to_string(prefix); } return result; } break; case selector_combinator: { if (std::isspace(token.begin[0])) return string(" "); else return string(" ") += string(token) += string(" "); } break; case simple_selector_sequence: { string result; for (int i = 0; i < children->size(); ++i) { result += children->at(i).to_string(prefix); } return result; } break; case pseudo_negation: { string result(children->at(0).to_string(prefix)); result += children->at(1).to_string(prefix); result += ')'; return result; } break; case functional_pseudo: { string result(children->at(0).to_string(prefix)); for (int i = 1; i < children->size(); ++i) { result += children->at(i).to_string(prefix); } result += ')'; return result; } break; case attribute_selector: { string result("["); for (int i = 0; i < 3; ++i) { result += children->at(i).to_string(prefix); } result += ']'; return result; } break; case backref: { return prefix; } break; case comma_list: { string result(children->at(0).to_string(prefix)); for (int i = 1; i < children->size(); ++i) { result += ", "; result += children->at(i).to_string(prefix); } return result; } break; case space_list: { string result(children->at(0).to_string(prefix)); for (int i = 1; i < children->size(); ++i) { result += " "; result += children->at(i).to_string(prefix); } return result; } break; case expression: case term: { string result(children->at(0).to_string(prefix)); // for (int i = 2; i < children->size(); i += 2) { // // result += " "; // result += children->at(i).to_string(prefix); // } for (int i = 1; i < children->size(); ++i) { if (!(children->at(i).type == add || // children->at(i).type == sub || // another edge case -- consider uncommenting children->at(i).type == mul)) { result += children->at(i).to_string(prefix); } } return result; } break; //edge case case sub: { return "-"; } break; case div: { return "/"; } break; case numeric_dimension: { stringstream ss; // ss.setf(std::ios::fixed, std::ios::floatfield); // ss.precision(3); ss << numeric_value << string(token); return ss.str(); } break; case number: { stringstream ss; // ss.setf(std::ios::fixed, std::ios::floatfield); // ss.precision(3); ss << numeric_value; return ss.str(); } break; case hex_triple: { double a = children->at(0).numeric_value; double b = children->at(1).numeric_value; double c = children->at(2).numeric_value; if (a >= 0xff && b >= 0xff && c >= 0xff) { return "white"; } else if (a >= 0xff && b >= 0xff && c == 0) { return "yellow"; } else if (a == 0 && b >= 0xff && c >= 0xff) { return "aqua"; } else if (a >= 0xff && b == 0 && c >= 0xff) { return "fuchsia"; } else if (a >= 0xff && b == 0 && c == 0) { return "red"; } else if (a == 0 && b >= 0xff && c == 0) { return "lime"; } else if (a == 0 && b == 0 && c >= 0xff) { return "blue"; } else if (a <= 0 && b <= 0 && c <= 0) { return "black"; } else { stringstream ss; ss << '#' << std::setw(2) << std::setfill('0') << std::hex; for (int i = 0; i < 3; ++i) { double x = children->at(i).numeric_value; if (x > 0xff) x = 0xff; else if (x < 0) x = 0; ss << std::hex << std::setw(2) << static_cast<unsigned long>(x); } return ss.str(); } } break; case uri: { string result("url("); result += string(token); result += ")"; return result; } break; default: { return string(token); } break; } } void Node::echo(stringstream& buf, size_t depth) { string indentation(2*depth, ' '); switch (type) { case comment: buf << indentation << string(token) << endl; break; case ruleset: buf << indentation; children->at(0).echo(buf, depth); children->at(1).echo(buf, depth); break; case selector_group: children->at(0).echo(buf, depth); for (int i = 1; i < children->size(); ++i) { buf << ", "; children->at(i).echo(buf, depth); } break; case selector: for (int i = 0; i < children->size(); ++i) { children->at(i).echo(buf, depth); } break; case selector_combinator: if (std::isspace(token.begin[0])) buf << ' '; else buf << ' ' << string(token) << ' '; break; case simple_selector_sequence: for (int i = 0; i < children->size(); ++i) { buf << children->at(i).to_string(string()); } break; case simple_selector: buf << string(token); break; case block: buf << " {" << endl; for (int i = 0; i < children->size(); children->at(i++).echo(buf, depth+1)) ; buf << indentation << "}" << endl; break; case rule: buf << indentation; children->at(0).echo(buf, depth); buf << ": "; children->at(1).echo(buf, depth); buf << ';' << endl; break; case property: buf << string(token); break; case values: for (int i = 0; i < children->size(); children->at(i++).echo(buf, depth)) ; break; case value: buf << ' ' << string(token); break; } } void Node::emit_nested_css(stringstream& buf, size_t depth, const vector<string>& prefixes) { switch (type) { case root: for (int i = 0; i < children->size(); ++i) { children->at(i).emit_nested_css(buf, depth, prefixes); } break; case ruleset: { Node sel_group(children->at(0)); Node block(children->at(1)); vector<string> new_prefixes; if (prefixes.empty()) { new_prefixes.reserve(sel_group.children->size()); for (int i = 0; i < sel_group.children->size(); ++i) { new_prefixes.push_back(sel_group.children->at(i).to_string(string())); } } else { new_prefixes.reserve(prefixes.size() * sel_group.children->size()); for (int i = 0; i < prefixes.size(); ++i) { for (int j = 0; j < sel_group.children->size(); ++j) { new_prefixes.push_back(sel_group.children->at(j).to_string(prefixes[i])); } } } if (block.has_rules_or_comments) { buf << string(2*depth, ' ') << new_prefixes[0]; for (int i = 1; i < new_prefixes.size(); ++i) { buf << ", " << new_prefixes[i]; } buf << " {"; for (int i = 0; i < block.children->size(); ++i) { Type stm_type = block.children->at(i).type; if (stm_type == comment || stm_type == rule) { block.children->at(i).emit_nested_css(buf, depth+1); // NEED OVERLOADED VERSION FOR COMMENTS AND RULES } } buf << " }" << endl; ++depth; // if we printed content at this level, we need to indent any nested rulesets } if (block.has_rulesets) { for (int i = 0; i < block.children->size(); ++i) { if (block.children->at(i).type == ruleset) { block.children->at(i).emit_nested_css(buf, depth, new_prefixes); } } } if (block.has_rules_or_comments) --depth; if (depth == 0 && prefixes.empty()) buf << endl; } break; default: emit_nested_css(buf, depth); // pass it along to the simpler version break; } } void Node::emit_nested_css(stringstream& buf, size_t depth) { switch (type) { case rule: buf << endl << string(2*depth, ' '); children->at(0).emit_nested_css(buf, depth); // property children->at(1).emit_nested_css(buf, depth); // values buf << ";"; break; case property: buf << string(token) << ": "; break; case values: for (int i = 0; i < children->size(); ++i) { buf << " " << string(children->at(i).token); } break; case comment: if (depth != 0) buf << endl; buf << string(2*depth, ' ') << string(token); if (depth == 0) buf << endl; break; default: buf << to_string(""); break; } } void Node::emit_expanded_css(stringstream& buf, const string& prefix) { // switch (type) { // case selector: // if (!prefix.empty()) buf << " "; // buf << string(token); // break; // case comment: // if (!prefix.empty()) buf << " "; // buf << string(token) << endl; // break; // case property: // buf << string(token) << ":"; // break; // case values: // for (int i = 0; i < children.size(); ++i) { // buf << " " << string(children[i].token); // } // break; // case rule: // buf << " "; // children[0].emit_expanded_css(buf, prefix); // children[1].emit_expanded_css(buf, prefix); // buf << ";" << endl; // break; // case clauses: // if (children.size() > 0) { // buf << " {" << endl; // for (int i = 0; i < children.size(); ++i) // children[i].emit_expanded_css(buf, prefix); // buf << "}" << endl; // } // for (int i = 0; i < opt_children.size(); ++i) // opt_children[i].emit_expanded_css(buf, prefix); // break; // case ruleset: // // buf << prefix; // if (children[1].children.size() > 0) { // buf << prefix << (prefix.empty() ? "" : " "); // children[0].emit_expanded_css(buf, ""); // } // string newprefix(prefix.empty() ? prefix : prefix + " "); // children[1].emit_expanded_css(buf, newprefix + string(children[0].token)); // if (prefix.empty()) buf << endl; // break; // } } }<|endoftext|>
<commit_before>// Copyright 2018 Google Inc. 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. // // Author: ericv@google.com (Eric Veach) #include "s2/encoded_s2shape_index.h" #include <memory> #include "s2/third_party/absl/memory/memory.h" #include "s2/mutable_s2shape_index.h" using absl::make_unique; using std::unique_ptr; using std::vector; bool EncodedS2ShapeIndex::Iterator::Locate(const S2Point& target) { return LocateImpl(target, this); } EncodedS2ShapeIndex::CellRelation EncodedS2ShapeIndex::Iterator::Locate( S2CellId target) { return LocateImpl(target, this); } unique_ptr<EncodedS2ShapeIndex::IteratorBase> EncodedS2ShapeIndex::Iterator::Clone() const { return make_unique<Iterator>(*this); } void EncodedS2ShapeIndex::Iterator::Copy(const IteratorBase& other) { *this = *down_cast<const Iterator*>(&other); } S2Shape* EncodedS2ShapeIndex::GetShape(int id) const { // This method is called when a shape has not been decoded yet. unique_ptr<S2Shape> shape = (*shape_factory_)[id]; if (shape) shape->id_ = id; S2Shape* expected = kUndecodedShape(); if (shapes_[id].compare_exchange_strong(expected, shape.get(), std::memory_order_relaxed)) { return shape.release(); // Ownership has been transferred to shapes_. } return shapes_[id].load(std::memory_order_relaxed); } inline const S2ShapeIndexCell* EncodedS2ShapeIndex::GetCell(int i) const { if (cell_decoded(i)) { auto cell = cells_[i].load(std::memory_order_acquire); if (cell != nullptr) return cell; } // We decode the cell before acquiring the spinlock in order to minimize the // time that the lock is held. auto cell = make_unique<S2ShapeIndexCell>(); Decoder decoder = encoded_cells_.GetDecoder(i); if (!cell->Decode(num_shape_ids(), &decoder)) { return nullptr; } SpinLockHolder l(&cells_lock_); if (test_and_set_cell_decoded(i)) { // This cell has already been decoded. return cells_[i].load(std::memory_order_relaxed); } if (cell_cache_.size() < max_cell_cache_size()) { cell_cache_.push_back(i); } cells_[i].store(cell.get(), std::memory_order_relaxed); return cell.release(); // Ownership has been transferred to cells_. } const S2ShapeIndexCell* EncodedS2ShapeIndex::Iterator::GetCell() const { return index_->GetCell(cell_pos_); } EncodedS2ShapeIndex::EncodedS2ShapeIndex() { } EncodedS2ShapeIndex::~EncodedS2ShapeIndex() { // Although Minimize() does slightly more than required for destruction // (i.e., it resets vector elements to their default values), this does not // affect benchmark times. Minimize(); } bool EncodedS2ShapeIndex::Init(Decoder* decoder, const ShapeFactory& shape_factory) { Minimize(); uint64 max_edges_version; if (!decoder->get_varint64(&max_edges_version)) return false; int version = max_edges_version & 3; if (version != MutableS2ShapeIndex::kCurrentEncodingVersionNumber) { return false; } options_.set_max_edges_per_cell(max_edges_version >> 2); // AtomicShape is a subtype of std::atomic<S2Shape*> that changes the // default constructor value to kUndecodedShape(). This saves the effort of // initializing all the elements twice. shapes_ = std::vector<AtomicShape>(shape_factory.size()); shape_factory_ = shape_factory.Clone(); if (!cell_ids_.Init(decoder)) return false; // The cells_ elements are *uninitialized memory*. Instead we have bit // vector (cells_decoded_) to indicate which elements of cells_ are valid. // This reduces constructor times by more than a factor of 50, since rather // than needing to initialize one 64-bit pointer per cell to zero, we only // need to initialize one bit per cell to zero. // // For very large S2ShapeIndexes the internal memset() call to initialize // cells_decoded_ still takes about 4 microseconds per million cells, but // this seems reasonable relative to other likely costs (I/O, etc). cells_ = make_unique<std::atomic<S2ShapeIndexCell*>[]>(cell_ids_.size()); cells_decoded_ = vector<std::atomic<uint64>>((cell_ids_.size() + 63) >> 6); return encoded_cells_.Init(decoder); } void EncodedS2ShapeIndex::Minimize() { for (auto& atomic_shape : shapes_) { S2Shape* shape = atomic_shape.load(std::memory_order_relaxed); if (shape != kUndecodedShape() && shape != nullptr) { atomic_shape.store(kUndecodedShape(), std::memory_order_relaxed); delete shape; } } if (cell_cache_.size() < max_cell_cache_size()) { // When only a tiny fraction of the cells are decoded, we keep track of // those cells in cell_cache_ to avoid the cost of scanning the // cells_decoded_ vector. (The cost is only about 1 cycle per 64 cells, // but for a huge polygon with 1 million cells that's still 16000 cycles.) for (int pos : cell_cache_) { cells_decoded_[pos >> 6].store(0, std::memory_order_relaxed); delete cells_[pos].load(std::memory_order_relaxed); } } else { // Scan the cells_decoded_ vector looking for cells that must be deleted. for (int i = cells_decoded_.size(), base = 0; --i >= 0; base += 64) { uint64 bits = cells_decoded_[i].load(std::memory_order_relaxed); if (bits == 0) continue; do { int offset = Bits::FindLSBSetNonZero64(bits); delete cells_[(i << 6) + offset].load(std::memory_order_relaxed); bits &= bits - 1; } while (bits != 0); cells_decoded_[i].store(0, std::memory_order_relaxed); } } cell_cache_.clear(); } size_t EncodedS2ShapeIndex::SpaceUsed() const { // TODO(ericv): Add SpaceUsed() method to S2Shape base class,and Include // memory owned by the allocated S2Shapes (here and in S2ShapeIndex). size_t size = sizeof(*this); size += shapes_.capacity() * sizeof(std::atomic<S2Shape*>); size += cell_ids_.size() * sizeof(std::atomic<S2ShapeIndexCell*>); // cells_ size += cells_decoded_.capacity() * sizeof(std::atomic<uint64>); size += cell_cache_.capacity() * sizeof(int); return size; } <commit_msg>Fix uninitialized memory access<commit_after>// Copyright 2018 Google Inc. 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. // // Author: ericv@google.com (Eric Veach) #include "s2/encoded_s2shape_index.h" #include <memory> #include "s2/third_party/absl/memory/memory.h" #include "s2/mutable_s2shape_index.h" using absl::make_unique; using std::unique_ptr; using std::vector; bool EncodedS2ShapeIndex::Iterator::Locate(const S2Point& target) { return LocateImpl(target, this); } EncodedS2ShapeIndex::CellRelation EncodedS2ShapeIndex::Iterator::Locate( S2CellId target) { return LocateImpl(target, this); } unique_ptr<EncodedS2ShapeIndex::IteratorBase> EncodedS2ShapeIndex::Iterator::Clone() const { return make_unique<Iterator>(*this); } void EncodedS2ShapeIndex::Iterator::Copy(const IteratorBase& other) { *this = *down_cast<const Iterator*>(&other); } S2Shape* EncodedS2ShapeIndex::GetShape(int id) const { // This method is called when a shape has not been decoded yet. unique_ptr<S2Shape> shape = (*shape_factory_)[id]; if (shape) shape->id_ = id; S2Shape* expected = kUndecodedShape(); if (shapes_[id].compare_exchange_strong(expected, shape.get(), std::memory_order_relaxed)) { return shape.release(); // Ownership has been transferred to shapes_. } return shapes_[id].load(std::memory_order_relaxed); } inline const S2ShapeIndexCell* EncodedS2ShapeIndex::GetCell(int i) const { if (cell_decoded(i)) { auto cell = cells_[i].load(std::memory_order_acquire); if (cell != nullptr) return cell; } // We decode the cell before acquiring the spinlock in order to minimize the // time that the lock is held. auto cell = make_unique<S2ShapeIndexCell>(); Decoder decoder = encoded_cells_.GetDecoder(i); if (!cell->Decode(num_shape_ids(), &decoder)) { return nullptr; } SpinLockHolder l(&cells_lock_); if (test_and_set_cell_decoded(i)) { // This cell has already been decoded. return cells_[i].load(std::memory_order_relaxed); } if (cell_cache_.size() < max_cell_cache_size()) { cell_cache_.push_back(i); } cells_[i].store(cell.get(), std::memory_order_relaxed); return cell.release(); // Ownership has been transferred to cells_. } const S2ShapeIndexCell* EncodedS2ShapeIndex::Iterator::GetCell() const { return index_->GetCell(cell_pos_); } EncodedS2ShapeIndex::EncodedS2ShapeIndex() { } EncodedS2ShapeIndex::~EncodedS2ShapeIndex() { // Although Minimize() does slightly more than required for destruction // (i.e., it resets vector elements to their default values), this does not // affect benchmark times. Minimize(); } bool EncodedS2ShapeIndex::Init(Decoder* decoder, const ShapeFactory& shape_factory) { Minimize(); uint64 max_edges_version; if (!decoder->get_varint64(&max_edges_version)) return false; int version = max_edges_version & 3; if (version != MutableS2ShapeIndex::kCurrentEncodingVersionNumber) { return false; } options_.set_max_edges_per_cell(max_edges_version >> 2); // AtomicShape is a subtype of std::atomic<S2Shape*> that changes the // default constructor value to kUndecodedShape(). This saves the effort of // initializing all the elements twice. shapes_ = std::vector<AtomicShape>(shape_factory.size()); shape_factory_ = shape_factory.Clone(); if (!cell_ids_.Init(decoder)) return false; // The cells_ elements are *uninitialized memory*. Instead we have bit // vector (cells_decoded_) to indicate which elements of cells_ are valid. // This reduces constructor times by more than a factor of 50, since rather // than needing to initialize one 64-bit pointer per cell to zero, we only // need to initialize one bit per cell to zero. // // For very large S2ShapeIndexes the internal memset() call to initialize // cells_decoded_ still takes about 4 microseconds per million cells, but // this seems reasonable relative to other likely costs (I/O, etc). cells_ = make_unique<std::atomic<S2ShapeIndexCell*>[]>(cell_ids_.size()); cells_decoded_ = vector<std::atomic<uint64>>((cell_ids_.size() + 63) >> 6); return encoded_cells_.Init(decoder); } void EncodedS2ShapeIndex::Minimize() { if (cells_ == nullptr) return; // Not initialized yet. for (auto& atomic_shape : shapes_) { S2Shape* shape = atomic_shape.load(std::memory_order_relaxed); if (shape != kUndecodedShape() && shape != nullptr) { atomic_shape.store(kUndecodedShape(), std::memory_order_relaxed); delete shape; } } if (cell_cache_.size() < max_cell_cache_size()) { // When only a tiny fraction of the cells are decoded, we keep track of // those cells in cell_cache_ to avoid the cost of scanning the // cells_decoded_ vector. (The cost is only about 1 cycle per 64 cells, // but for a huge polygon with 1 million cells that's still 16000 cycles.) for (int pos : cell_cache_) { cells_decoded_[pos >> 6].store(0, std::memory_order_relaxed); delete cells_[pos].load(std::memory_order_relaxed); } } else { // Scan the cells_decoded_ vector looking for cells that must be deleted. for (int i = cells_decoded_.size(), base = 0; --i >= 0; base += 64) { uint64 bits = cells_decoded_[i].load(std::memory_order_relaxed); if (bits == 0) continue; do { int offset = Bits::FindLSBSetNonZero64(bits); delete cells_[(i << 6) + offset].load(std::memory_order_relaxed); bits &= bits - 1; } while (bits != 0); cells_decoded_[i].store(0, std::memory_order_relaxed); } } cell_cache_.clear(); } size_t EncodedS2ShapeIndex::SpaceUsed() const { // TODO(ericv): Add SpaceUsed() method to S2Shape base class,and Include // memory owned by the allocated S2Shapes (here and in S2ShapeIndex). size_t size = sizeof(*this); size += shapes_.capacity() * sizeof(std::atomic<S2Shape*>); size += cell_ids_.size() * sizeof(std::atomic<S2ShapeIndexCell*>); // cells_ size += cells_decoded_.capacity() * sizeof(std::atomic<uint64>); size += cell_cache_.capacity() * sizeof(int); return size; } <|endoftext|>
<commit_before>#include "rosplan_knowledge_base/KnowledgeBase.h" namespace KCL_rosplan { /*-----------------*/ /* knowledge query */ /*-----------------*/ bool KnowledgeBase::queryKnowledge(rosplan_knowledge_msgs::KnowledgeQueryService::Request &req, rosplan_knowledge_msgs::KnowledgeQueryService::Response &res) { res.all_true = true; std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator iit; for(iit = req.knowledge.begin(); iit!=req.knowledge.end(); iit++) { bool present = false; if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // check if instance exists std::vector<std::string>::iterator sit; sit = find(domain_instances[iit->instance_type].begin(), domain_instances[iit->instance_type].end(), iit->instance_name); present = (sit!=domain_instances[iit->instance_type].end()); } else if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION) { // check if function exists; TODO inequalities std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_functions.begin(); pit!=domain_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(*iit, *pit)) { present = true; pit = domain_functions.end(); } } } else if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) { // check if fact is true std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(*iit, *pit)) { present = true; break; } } } if(!present) { res.all_true = false; res.false_knowledge.push_back(*iit); } } return true; } /*------------------*/ /* knowledge update */ /*------------------*/ bool KnowledgeBase::updateKnowledge(rosplan_knowledge_msgs::KnowledgeUpdateService::Request &req, rosplan_knowledge_msgs::KnowledgeUpdateService::Response &res) { if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE) addKnowledge(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_GOAL) addMissionGoal(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_KNOWLEDGE) removeKnowledge(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_GOAL) removeMissionGoal(req.knowledge); res.success = true; return true; } /*----------------*/ /* removing items */ /*----------------*/ void KnowledgeBase::removeKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg) { if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // search for instance std::vector<std::string>::iterator iit; for(iit = domain_instances[msg.instance_type].begin(); iit!=domain_instances[msg.instance_type].end(); iit++) { std::string name = *iit; if(name.compare(msg.instance_name)==0 || msg.instance_name.compare("")==0) { // remove instance from knowledge base ROS_INFO("KCL: (KB) Removing instance (%s, %s)", msg.instance_type.c_str(), (msg.instance_name.compare("")==0) ? "ALL" : msg.instance_name.c_str()); iit = domain_instances[msg.instance_type].erase(iit); if(iit!=domain_instances[msg.instance_type].begin()) iit--; plan_filter.checkFilters(msg, false); // remove affected domain attributes std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsInstance(*pit, name)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", pit->attribute_name.c_str()); plan_filter.checkFilters(*pit, false); pit = domain_attributes.erase(pit); if(pit!=domain_attributes.begin()) pit--; if(pit==domain_attributes.end()) break; } } // remove affected instance attributes for(pit=instance_attributes[name].begin(); pit!=instance_attributes[name].end(); pit++) { if(KnowledgeComparitor::containsInstance(*pit, name)) { ROS_INFO("KCL: (KB) Removing instance attribute (%s, %s)", name.c_str(), pit->attribute_name.c_str()); plan_filter.checkFilters(*pit, false); pit = instance_attributes[name].erase(pit); if(pit!=instance_attributes[name].begin()) pit--; if(pit==instance_attributes[name].end()) break; } } // finish if(iit==domain_instances[msg.instance_type].end()) break; } } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION) { // remove domain attribute (function) from knowledge base std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_functions.begin(); pit!=domain_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", msg.attribute_name.c_str()); plan_filter.checkFilters(msg, false); pit = domain_functions.erase(pit); if(pit!=domain_functions.begin()) pit--; if(pit==domain_functions.end()) break; } } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) { // remove domain attribute (predicate) from knowledge base std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", msg.attribute_name.c_str()); plan_filter.checkFilters(msg, false); pit = domain_attributes.erase(pit); if(pit!=domain_attributes.begin()) pit--; if(pit==domain_attributes.end()) break; } } } } /** * remove mission goal */ void KnowledgeBase::removeMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg) { bool changed = false; std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator git; for(git=domain_goals.begin(); git!=domain_goals.end(); git++) { if(KnowledgeComparitor::containsKnowledge(msg, *git)) { ROS_INFO("KCL: (KB) Removing goal (%s)", msg.attribute_name.c_str()); git = domain_goals.erase(git); if(git!=domain_goals.begin()) git--; if(git==domain_goals.end()) break; } } if(changed) { rosplan_knowledge_msgs::Notification notMsg; notMsg.function = rosplan_knowledge_msgs::Notification::REMOVED; notMsg.knowledge_item = msg; plan_filter.notification_publisher.publish(notMsg); } } /*--------------*/ /* adding items */ /*--------------*/ /* * add an instance, domain predicate, or function to the knowledge base */ void KnowledgeBase::addKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg) { if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // check if instance is already in knowledge base std::vector<std::string>::iterator iit; iit = find(domain_instances[msg.instance_type].begin(), domain_instances[msg.instance_type].end(), msg.instance_name); // add instance if(iit==domain_instances[msg.instance_type].end()) { ROS_INFO("KCL: (KB) Adding instance (%s, %s)", msg.instance_type.c_str(), msg.instance_name.c_str()); domain_instances[msg.instance_type].push_back(msg.instance_name); plan_filter.checkFilters(msg, true); } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) { // add domain attribute std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) return; } ROS_INFO("KCL: (KB) Adding domain attribute (%s)", msg.attribute_name.c_str()); domain_attributes.push_back(msg); plan_filter.checkFilters(msg, true); } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION) { // add domain function std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_functions.begin(); pit!=domain_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { // already added TODO value check ROS_INFO("KCL: (KB) Updating domain function (%s)", msg.attribute_name.c_str()); pit->function_value = msg.function_value; return; } } ROS_INFO("KCL: (KB) Adding domain function (%s)", msg.attribute_name.c_str()); domain_functions.push_back(msg); plan_filter.checkFilters(msg, true); } } /* * add mission goal to knowledge base */ void KnowledgeBase::addMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_goals.begin(); pit!=domain_goals.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) return; } ROS_INFO("KCL: (KB) Adding mission goal (%s)", msg.attribute_name.c_str()); domain_goals.push_back(msg); } /*----------------*/ /* fetching items */ /*----------------*/ bool KnowledgeBase::getInstances(rosplan_knowledge_msgs::GetInstanceService::Request &req, rosplan_knowledge_msgs::GetInstanceService::Response &res) { ROS_INFO("KCL: (KB) Sending %s getInstances", req.type_name.c_str()); // fetch the instances of the correct type if(""==req.type_name) { std::map<std::string,std::vector<std::string> >::iterator iit; for(iit=domain_instances.begin(); iit != domain_instances.end(); iit++) { for(size_t j=0; j<iit->second.size(); j++) res.instances.push_back(iit->second[j]); } } else { std::map<std::string,std::vector<std::string> >::iterator iit; iit = domain_instances.find(req.type_name); if(iit != domain_instances.end()) { for(size_t j=0; j<iit->second.size(); j++) res.instances.push_back(iit->second[j]); } } return true; } bool KnowledgeBase::getDomainAttr(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res) { ROS_INFO("KCL: (KB) Sending getDomainAttr response for %s", req.predicate_name.c_str()); // fetch the knowledgeItems of the correct attribute for(size_t i=0; i<domain_attributes.size(); i++) { if(0==req.predicate_name.compare(domain_attributes[i].attribute_name) || ""==req.predicate_name) res.attributes.push_back(domain_attributes[i]); } // ...or fetch the knowledgeItems of the correct function for(size_t i=0; i<domain_functions.size(); i++) { if(0==req.predicate_name.compare(domain_functions[i].attribute_name) || ""==req.predicate_name) res.attributes.push_back(domain_functions[i]); } return true; } bool KnowledgeBase::getCurrentGoals(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res) { ROS_INFO("KCL: (KB) Sending getCurrentGoals response"); // fetch the knowledgeItems of the correct attribute for(size_t i=0; i<domain_goals.size(); i++) { res.attributes.push_back(domain_goals[i]); } return true; } } // close namespace /*-------------*/ /* main method */ /*-------------*/ int main(int argc, char **argv) { ros::init(argc, argv, "KCL_knowledge_base"); ros::NodeHandle n; KCL_rosplan::KnowledgeBase kb; // TESTING kb.domain_instances["robot"].push_back("kenny"); // END TESTING */ // query knowledge ros::ServiceServer queryServer = n.advertiseService("/kcl_rosplan/query_knowledge_base", &KCL_rosplan::KnowledgeBase::queryKnowledge, &kb); // update knowledge ros::ServiceServer updateServer = n.advertiseService("/kcl_rosplan/update_knowledge_base", &KCL_rosplan::KnowledgeBase::updateKnowledge, &kb); // environment services ros::ServiceServer instanceServer = n.advertiseService("/kcl_rosplan/get_instances", &KCL_rosplan::KnowledgeBase::getInstances, &kb); ros::ServiceServer domainServer = n.advertiseService("/kcl_rosplan/get_domain_attributes", &KCL_rosplan::KnowledgeBase::getDomainAttr, &kb); ros::ServiceServer goalServer = n.advertiseService("/kcl_rosplan/get_current_goals", &KCL_rosplan::KnowledgeBase::getCurrentGoals, &kb); // filter kb.plan_filter.notification_publisher = n.advertise<rosplan_knowledge_msgs::Notification>("/kcl_rosplan/notification", 10, true); ros::Subscriber planningFilterSub = n.subscribe("/kcl_rosplan/plan_filter", 100, &KCL_rosplan::PlanFilter::planningFilterCallback, &kb.plan_filter); ros::Subscriber missionFilterSub = n.subscribe("/kcl_rosplan/plan_filter", 100, &KCL_rosplan::PlanFilter::missionFilterCallback, &kb.plan_filter); // wait for and clear mongoDB ROS_INFO("KCL: (KB) Waiting for MongoDB"); ros::service::waitForService("/message_store/delete",-1); system("mongo message_store --eval \"printjson(db.message_store.remove())\""); ROS_INFO("KCL: (KB) Ready to receive"); ros::spin(); return 0; } <commit_msg>Removed test robot<commit_after>#include "rosplan_knowledge_base/KnowledgeBase.h" namespace KCL_rosplan { /*-----------------*/ /* knowledge query */ /*-----------------*/ bool KnowledgeBase::queryKnowledge(rosplan_knowledge_msgs::KnowledgeQueryService::Request &req, rosplan_knowledge_msgs::KnowledgeQueryService::Response &res) { res.all_true = true; std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator iit; for(iit = req.knowledge.begin(); iit!=req.knowledge.end(); iit++) { bool present = false; if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // check if instance exists std::vector<std::string>::iterator sit; sit = find(domain_instances[iit->instance_type].begin(), domain_instances[iit->instance_type].end(), iit->instance_name); present = (sit!=domain_instances[iit->instance_type].end()); } else if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION) { // check if function exists; TODO inequalities std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_functions.begin(); pit!=domain_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(*iit, *pit)) { present = true; pit = domain_functions.end(); } } } else if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) { // check if fact is true std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(*iit, *pit)) { present = true; break; } } } if(!present) { res.all_true = false; res.false_knowledge.push_back(*iit); } } return true; } /*------------------*/ /* knowledge update */ /*------------------*/ bool KnowledgeBase::updateKnowledge(rosplan_knowledge_msgs::KnowledgeUpdateService::Request &req, rosplan_knowledge_msgs::KnowledgeUpdateService::Response &res) { if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE) addKnowledge(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_GOAL) addMissionGoal(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_KNOWLEDGE) removeKnowledge(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_GOAL) removeMissionGoal(req.knowledge); res.success = true; return true; } /*----------------*/ /* removing items */ /*----------------*/ void KnowledgeBase::removeKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg) { if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // search for instance std::vector<std::string>::iterator iit; for(iit = domain_instances[msg.instance_type].begin(); iit!=domain_instances[msg.instance_type].end(); iit++) { std::string name = *iit; if(name.compare(msg.instance_name)==0 || msg.instance_name.compare("")==0) { // remove instance from knowledge base ROS_INFO("KCL: (KB) Removing instance (%s, %s)", msg.instance_type.c_str(), (msg.instance_name.compare("")==0) ? "ALL" : msg.instance_name.c_str()); iit = domain_instances[msg.instance_type].erase(iit); if(iit!=domain_instances[msg.instance_type].begin()) iit--; plan_filter.checkFilters(msg, false); // remove affected domain attributes std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsInstance(*pit, name)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", pit->attribute_name.c_str()); plan_filter.checkFilters(*pit, false); pit = domain_attributes.erase(pit); if(pit!=domain_attributes.begin()) pit--; if(pit==domain_attributes.end()) break; } } // remove affected instance attributes for(pit=instance_attributes[name].begin(); pit!=instance_attributes[name].end(); pit++) { if(KnowledgeComparitor::containsInstance(*pit, name)) { ROS_INFO("KCL: (KB) Removing instance attribute (%s, %s)", name.c_str(), pit->attribute_name.c_str()); plan_filter.checkFilters(*pit, false); pit = instance_attributes[name].erase(pit); if(pit!=instance_attributes[name].begin()) pit--; if(pit==instance_attributes[name].end()) break; } } // finish if(iit==domain_instances[msg.instance_type].end()) break; } } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION) { // remove domain attribute (function) from knowledge base std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_functions.begin(); pit!=domain_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", msg.attribute_name.c_str()); plan_filter.checkFilters(msg, false); pit = domain_functions.erase(pit); if(pit!=domain_functions.begin()) pit--; if(pit==domain_functions.end()) break; } } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) { // remove domain attribute (predicate) from knowledge base std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", msg.attribute_name.c_str()); plan_filter.checkFilters(msg, false); pit = domain_attributes.erase(pit); if(pit!=domain_attributes.begin()) pit--; if(pit==domain_attributes.end()) break; } } } } /** * remove mission goal */ void KnowledgeBase::removeMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg) { bool changed = false; std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator git; for(git=domain_goals.begin(); git!=domain_goals.end(); git++) { if(KnowledgeComparitor::containsKnowledge(msg, *git)) { ROS_INFO("KCL: (KB) Removing goal (%s)", msg.attribute_name.c_str()); git = domain_goals.erase(git); if(git!=domain_goals.begin()) git--; if(git==domain_goals.end()) break; } } if(changed) { rosplan_knowledge_msgs::Notification notMsg; notMsg.function = rosplan_knowledge_msgs::Notification::REMOVED; notMsg.knowledge_item = msg; plan_filter.notification_publisher.publish(notMsg); } } /*--------------*/ /* adding items */ /*--------------*/ /* * add an instance, domain predicate, or function to the knowledge base */ void KnowledgeBase::addKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg) { if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // check if instance is already in knowledge base std::vector<std::string>::iterator iit; iit = find(domain_instances[msg.instance_type].begin(), domain_instances[msg.instance_type].end(), msg.instance_name); // add instance if(iit==domain_instances[msg.instance_type].end()) { ROS_INFO("KCL: (KB) Adding instance (%s, %s)", msg.instance_type.c_str(), msg.instance_name.c_str()); domain_instances[msg.instance_type].push_back(msg.instance_name); plan_filter.checkFilters(msg, true); } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_ATTRIBUTE) { // add domain attribute std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_attributes.begin(); pit!=domain_attributes.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) return; } ROS_INFO("KCL: (KB) Adding domain attribute (%s)", msg.attribute_name.c_str()); domain_attributes.push_back(msg); plan_filter.checkFilters(msg, true); } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::DOMAIN_FUNCTION) { // add domain function std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_functions.begin(); pit!=domain_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { // already added TODO value check ROS_INFO("KCL: (KB) Updating domain function (%s)", msg.attribute_name.c_str()); pit->function_value = msg.function_value; return; } } ROS_INFO("KCL: (KB) Adding domain function (%s)", msg.attribute_name.c_str()); domain_functions.push_back(msg); plan_filter.checkFilters(msg, true); } } /* * add mission goal to knowledge base */ void KnowledgeBase::addMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=domain_goals.begin(); pit!=domain_goals.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) return; } ROS_INFO("KCL: (KB) Adding mission goal (%s)", msg.attribute_name.c_str()); domain_goals.push_back(msg); } /*----------------*/ /* fetching items */ /*----------------*/ bool KnowledgeBase::getInstances(rosplan_knowledge_msgs::GetInstanceService::Request &req, rosplan_knowledge_msgs::GetInstanceService::Response &res) { ROS_INFO("KCL: (KB) Sending %s getInstances", req.type_name.c_str()); // fetch the instances of the correct type if(""==req.type_name) { std::map<std::string,std::vector<std::string> >::iterator iit; for(iit=domain_instances.begin(); iit != domain_instances.end(); iit++) { for(size_t j=0; j<iit->second.size(); j++) res.instances.push_back(iit->second[j]); } } else { std::map<std::string,std::vector<std::string> >::iterator iit; iit = domain_instances.find(req.type_name); if(iit != domain_instances.end()) { for(size_t j=0; j<iit->second.size(); j++) res.instances.push_back(iit->second[j]); } } return true; } bool KnowledgeBase::getDomainAttr(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res) { ROS_INFO("KCL: (KB) Sending getDomainAttr response for %s", req.predicate_name.c_str()); // fetch the knowledgeItems of the correct attribute for(size_t i=0; i<domain_attributes.size(); i++) { if(0==req.predicate_name.compare(domain_attributes[i].attribute_name) || ""==req.predicate_name) res.attributes.push_back(domain_attributes[i]); } // ...or fetch the knowledgeItems of the correct function for(size_t i=0; i<domain_functions.size(); i++) { if(0==req.predicate_name.compare(domain_functions[i].attribute_name) || ""==req.predicate_name) res.attributes.push_back(domain_functions[i]); } return true; } bool KnowledgeBase::getCurrentGoals(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res) { ROS_INFO("KCL: (KB) Sending getCurrentGoals response"); // fetch the knowledgeItems of the correct attribute for(size_t i=0; i<domain_goals.size(); i++) { res.attributes.push_back(domain_goals[i]); } return true; } } // close namespace /*-------------*/ /* main method */ /*-------------*/ int main(int argc, char **argv) { ros::init(argc, argv, "KCL_knowledge_base"); ros::NodeHandle n; KCL_rosplan::KnowledgeBase kb; // query knowledge ros::ServiceServer queryServer = n.advertiseService("/kcl_rosplan/query_knowledge_base", &KCL_rosplan::KnowledgeBase::queryKnowledge, &kb); // update knowledge ros::ServiceServer updateServer = n.advertiseService("/kcl_rosplan/update_knowledge_base", &KCL_rosplan::KnowledgeBase::updateKnowledge, &kb); // fetch knowledge ros::ServiceServer instanceServer = n.advertiseService("/kcl_rosplan/get_instances", &KCL_rosplan::KnowledgeBase::getInstances, &kb); ros::ServiceServer domainServer = n.advertiseService("/kcl_rosplan/get_domain_attributes", &KCL_rosplan::KnowledgeBase::getDomainAttr, &kb); ros::ServiceServer goalServer = n.advertiseService("/kcl_rosplan/get_current_goals", &KCL_rosplan::KnowledgeBase::getCurrentGoals, &kb); // planning and mission filter kb.plan_filter.notification_publisher = n.advertise<rosplan_knowledge_msgs::Notification>("/kcl_rosplan/notification", 10, true); ros::Subscriber planningFilterSub = n.subscribe("/kcl_rosplan/plan_filter", 100, &KCL_rosplan::PlanFilter::planningFilterCallback, &kb.plan_filter); ros::Subscriber missionFilterSub = n.subscribe("/kcl_rosplan/plan_filter", 100, &KCL_rosplan::PlanFilter::missionFilterCallback, &kb.plan_filter); // wait for and clear mongoDB ROS_INFO("KCL: (KB) Waiting for MongoDB"); ros::service::waitForService("/message_store/delete",-1); system("mongo message_store --eval \"printjson(db.message_store.remove())\""); ROS_INFO("KCL: (KB) Ready to receive"); ros::spin(); return 0; } <|endoftext|>
<commit_before>//===- ValueNumbering.cpp - Value #'ing Implementation ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the non-abstract Value Numbering methods as well as a // default implementation for the analysis group. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/ValueNumbering.h" #include "llvm/Support/InstVisitor.h" #include "llvm/BasicBlock.h" #include "llvm/Instructions.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/Support/Compiler.h" using namespace llvm; char ValueNumbering::ID = 0; // Register the ValueNumbering interface, providing a nice name to refer to. static RegisterAnalysisGroup<ValueNumbering> V("Value Numbering"); /// ValueNumbering destructor: DO NOT move this to the header file for /// ValueNumbering or else clients of the ValueNumbering class may not depend on /// the ValueNumbering.o file in the current .a file, causing alias analysis /// support to not be included in the tool correctly! /// ValueNumbering::~ValueNumbering() {} //===----------------------------------------------------------------------===// // Basic ValueNumbering Pass Implementation //===----------------------------------------------------------------------===// // // Because of the way .a files work, the implementation of the BasicVN class // MUST be in the ValueNumbering file itself, or else we run the risk of // ValueNumbering being used, but the default implementation not being linked // into the tool that uses it. As such, we register and implement the class // here. // namespace { /// BasicVN - This class is the default implementation of the ValueNumbering /// interface. It walks the SSA def-use chains to trivially identify /// lexically identical expressions. This does not require any ahead of time /// analysis, so it is a very fast default implementation. /// struct VISIBILITY_HIDDEN BasicVN : public ImmutablePass, public ValueNumbering { static char ID; // Class identification, replacement for typeinfo BasicVN() : ImmutablePass((intptr_t)&ID) {} /// getEqualNumberNodes - Return nodes with the same value number as the /// specified Value. This fills in the argument vector with any equal /// values. /// /// This is where our implementation is. /// virtual void getEqualNumberNodes(Value *V1, std::vector<Value*> &RetVals) const; }; } char BasicVN::ID = 0; // Register this pass... static RegisterPass<BasicVN> X("basicvn", "Basic Value Numbering (default GVN impl)", false, true); // Declare that we implement the ValueNumbering interface static RegisterAnalysisGroup<ValueNumbering, true> Y(X); namespace { /// BVNImpl - Implement BasicVN in terms of a visitor class that /// handles the different types of instructions as appropriate. /// struct VISIBILITY_HIDDEN BVNImpl : public InstVisitor<BVNImpl> { std::vector<Value*> &RetVals; explicit BVNImpl(std::vector<Value*> &RV) : RetVals(RV) {} void visitCastInst(CastInst &I); void visitGetElementPtrInst(GetElementPtrInst &I); void visitCmpInst(CmpInst &I); void handleBinaryInst(Instruction &I); void visitBinaryOperator(Instruction &I) { handleBinaryInst(I); } void visitShiftInst(Instruction &I) { handleBinaryInst(I); } void visitExtractElementInst(Instruction &I) { handleBinaryInst(I); } void handleTernaryInst(Instruction &I); void visitSelectInst(Instruction &I) { handleTernaryInst(I); } void visitInsertElementInst(Instruction &I) { handleTernaryInst(I); } void visitShuffleVectorInst(Instruction &I) { handleTernaryInst(I); } void visitInstruction(Instruction &) { // Cannot value number calls or terminator instructions. } }; } ImmutablePass *llvm::createBasicVNPass() { return new BasicVN(); } // getEqualNumberNodes - Return nodes with the same value number as the // specified Value. This fills in the argument vector with any equal values. // void BasicVN::getEqualNumberNodes(Value *V, std::vector<Value*> &RetVals) const{ assert(V->getType() != Type::VoidTy && "Can only value number non-void values!"); // We can only handle the case where I is an instruction! if (Instruction *I = dyn_cast<Instruction>(V)) BVNImpl(RetVals).visit(I); } void BVNImpl::visitCastInst(CastInst &CI) { Instruction &I = (Instruction&)CI; Value *Op = I.getOperand(0); Function *F = I.getParent()->getParent(); for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE; ++UI) if (CastInst *Other = dyn_cast<CastInst>(*UI)) // Check that the opcode is the same if (Other->getOpcode() == Instruction::CastOps(I.getOpcode()) && // Check that the destination types are the same Other->getType() == I.getType() && // Is it embedded in the same function? (This could be false if LHS // is a constant or global!) Other->getParent()->getParent() == F && // Check to see if this new cast is not I. Other != &I) { // These instructions are identical. Add to list... RetVals.push_back(Other); } } void BVNImpl::visitCmpInst(CmpInst &CI1) { Value *LHS = CI1.getOperand(0); for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end(); UI != UE; ++UI) if (CmpInst *CI2 = dyn_cast<CmpInst>(*UI)) // Check to see if this compare instruction is not CI, but same opcode, // same predicate, and in the same function. if (CI2 != &CI1 && CI2->getOpcode() == CI1.getOpcode() && CI2->getPredicate() == CI1.getPredicate() && CI2->getParent()->getParent() == CI1.getParent()->getParent()) // If the operands are the same if ((CI2->getOperand(0) == CI1.getOperand(0) && CI2->getOperand(1) == CI1.getOperand(1)) || // Or the compare is commutative and the operands are reversed (CI1.isCommutative() && CI2->getOperand(0) == CI1.getOperand(1) && CI2->getOperand(1) == CI1.getOperand(0))) // Then the instructiosn are identical, add to list. RetVals.push_back(CI2); } // isIdenticalBinaryInst - Return true if the two binary instructions are // identical. // static inline bool isIdenticalBinaryInst(const Instruction &I1, const Instruction *I2) { // Is it embedded in the same function? (This could be false if LHS // is a constant or global!) if (I1.getOpcode() != I2->getOpcode() || I1.getParent()->getParent() != I2->getParent()->getParent()) return false; // If they are CmpInst instructions, check their predicates if (CmpInst *CI1 = dyn_cast<CmpInst>(&const_cast<Instruction&>(I1))) if (CI1->getPredicate() != cast<CmpInst>(I2)->getPredicate()) return false; // They are identical if both operands are the same! if (I1.getOperand(0) == I2->getOperand(0) && I1.getOperand(1) == I2->getOperand(1)) return true; // If the instruction is commutative, the instruction can match if the // operands are swapped! // if ((I1.getOperand(0) == I2->getOperand(1) && I1.getOperand(1) == I2->getOperand(0)) && I1.isCommutative()) return true; return false; } // isIdenticalTernaryInst - Return true if the two ternary instructions are // identical. // static inline bool isIdenticalTernaryInst(const Instruction &I1, const Instruction *I2) { // Is it embedded in the same function? (This could be false if LHS // is a constant or global!) if (I1.getParent()->getParent() != I2->getParent()->getParent()) return false; // They are identical if all operands are the same! return I1.getOperand(0) == I2->getOperand(0) && I1.getOperand(1) == I2->getOperand(1) && I1.getOperand(2) == I2->getOperand(2); } void BVNImpl::handleBinaryInst(Instruction &I) { Value *LHS = I.getOperand(0); for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end(); UI != UE; ++UI) if (Instruction *Other = dyn_cast<Instruction>(*UI)) // Check to see if this new binary operator is not I, but same operand... if (Other != &I && isIdenticalBinaryInst(I, Other)) { // These instructions are identical. Handle the situation. RetVals.push_back(Other); } } // IdenticalComplexInst - Return true if the two instructions are the same, by // using a brute force comparison. This is useful for instructions with an // arbitrary number of arguments. // static inline bool IdenticalComplexInst(const Instruction *I1, const Instruction *I2) { assert(I1->getOpcode() == I2->getOpcode()); // Equal if they are in the same function... return I1->getParent()->getParent() == I2->getParent()->getParent() && // And return the same type... I1->getType() == I2->getType() && // And have the same number of operands... I1->getNumOperands() == I2->getNumOperands() && // And all of the operands are equal. std::equal(I1->op_begin(), I1->op_end(), I2->op_begin()); } void BVNImpl::visitGetElementPtrInst(GetElementPtrInst &I) { Value *Op = I.getOperand(0); // Try to pick a local operand if possible instead of a constant or a global // that might have a lot of uses. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) if (isa<Instruction>(I.getOperand(i)) || isa<Argument>(I.getOperand(i))) { Op = I.getOperand(i); break; } for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE; ++UI) if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI)) // Check to see if this new getelementptr is not I, but same operand... if (Other != &I && IdenticalComplexInst(&I, Other)) { // These instructions are identical. Handle the situation. RetVals.push_back(Other); } } void BVNImpl::handleTernaryInst(Instruction &I) { Value *Op0 = I.getOperand(0); Instruction *OtherInst; for (Value::use_iterator UI = Op0->use_begin(), UE = Op0->use_end(); UI != UE; ++UI) if ((OtherInst = dyn_cast<Instruction>(*UI)) && OtherInst->getOpcode() == I.getOpcode()) { // Check to see if this new select is not I, but has the same operands. if (OtherInst != &I && isIdenticalTernaryInst(I, OtherInst)) { // These instructions are identical. Handle the situation. RetVals.push_back(OtherInst); } } } // Ensure that users of ValueNumbering.h will link with this file DEFINING_FILE_FOR(BasicValueNumbering) <commit_msg>convert another operand loop to iterator formulation<commit_after>//===- ValueNumbering.cpp - Value #'ing Implementation ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the non-abstract Value Numbering methods as well as a // default implementation for the analysis group. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/ValueNumbering.h" #include "llvm/Support/InstVisitor.h" #include "llvm/BasicBlock.h" #include "llvm/Instructions.h" #include "llvm/Pass.h" #include "llvm/Type.h" #include "llvm/Support/Compiler.h" using namespace llvm; char ValueNumbering::ID = 0; // Register the ValueNumbering interface, providing a nice name to refer to. static RegisterAnalysisGroup<ValueNumbering> V("Value Numbering"); /// ValueNumbering destructor: DO NOT move this to the header file for /// ValueNumbering or else clients of the ValueNumbering class may not depend on /// the ValueNumbering.o file in the current .a file, causing alias analysis /// support to not be included in the tool correctly! /// ValueNumbering::~ValueNumbering() {} //===----------------------------------------------------------------------===// // Basic ValueNumbering Pass Implementation //===----------------------------------------------------------------------===// // // Because of the way .a files work, the implementation of the BasicVN class // MUST be in the ValueNumbering file itself, or else we run the risk of // ValueNumbering being used, but the default implementation not being linked // into the tool that uses it. As such, we register and implement the class // here. // namespace { /// BasicVN - This class is the default implementation of the ValueNumbering /// interface. It walks the SSA def-use chains to trivially identify /// lexically identical expressions. This does not require any ahead of time /// analysis, so it is a very fast default implementation. /// struct VISIBILITY_HIDDEN BasicVN : public ImmutablePass, public ValueNumbering { static char ID; // Class identification, replacement for typeinfo BasicVN() : ImmutablePass((intptr_t)&ID) {} /// getEqualNumberNodes - Return nodes with the same value number as the /// specified Value. This fills in the argument vector with any equal /// values. /// /// This is where our implementation is. /// virtual void getEqualNumberNodes(Value *V1, std::vector<Value*> &RetVals) const; }; } char BasicVN::ID = 0; // Register this pass... static RegisterPass<BasicVN> X("basicvn", "Basic Value Numbering (default GVN impl)", false, true); // Declare that we implement the ValueNumbering interface static RegisterAnalysisGroup<ValueNumbering, true> Y(X); namespace { /// BVNImpl - Implement BasicVN in terms of a visitor class that /// handles the different types of instructions as appropriate. /// struct VISIBILITY_HIDDEN BVNImpl : public InstVisitor<BVNImpl> { std::vector<Value*> &RetVals; explicit BVNImpl(std::vector<Value*> &RV) : RetVals(RV) {} void visitCastInst(CastInst &I); void visitGetElementPtrInst(GetElementPtrInst &I); void visitCmpInst(CmpInst &I); void handleBinaryInst(Instruction &I); void visitBinaryOperator(Instruction &I) { handleBinaryInst(I); } void visitShiftInst(Instruction &I) { handleBinaryInst(I); } void visitExtractElementInst(Instruction &I) { handleBinaryInst(I); } void handleTernaryInst(Instruction &I); void visitSelectInst(Instruction &I) { handleTernaryInst(I); } void visitInsertElementInst(Instruction &I) { handleTernaryInst(I); } void visitShuffleVectorInst(Instruction &I) { handleTernaryInst(I); } void visitInstruction(Instruction &) { // Cannot value number calls or terminator instructions. } }; } ImmutablePass *llvm::createBasicVNPass() { return new BasicVN(); } // getEqualNumberNodes - Return nodes with the same value number as the // specified Value. This fills in the argument vector with any equal values. // void BasicVN::getEqualNumberNodes(Value *V, std::vector<Value*> &RetVals) const{ assert(V->getType() != Type::VoidTy && "Can only value number non-void values!"); // We can only handle the case where I is an instruction! if (Instruction *I = dyn_cast<Instruction>(V)) BVNImpl(RetVals).visit(I); } void BVNImpl::visitCastInst(CastInst &CI) { Instruction &I = (Instruction&)CI; Value *Op = I.getOperand(0); Function *F = I.getParent()->getParent(); for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE; ++UI) if (CastInst *Other = dyn_cast<CastInst>(*UI)) // Check that the opcode is the same if (Other->getOpcode() == Instruction::CastOps(I.getOpcode()) && // Check that the destination types are the same Other->getType() == I.getType() && // Is it embedded in the same function? (This could be false if LHS // is a constant or global!) Other->getParent()->getParent() == F && // Check to see if this new cast is not I. Other != &I) { // These instructions are identical. Add to list... RetVals.push_back(Other); } } void BVNImpl::visitCmpInst(CmpInst &CI1) { Value *LHS = CI1.getOperand(0); for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end(); UI != UE; ++UI) if (CmpInst *CI2 = dyn_cast<CmpInst>(*UI)) // Check to see if this compare instruction is not CI, but same opcode, // same predicate, and in the same function. if (CI2 != &CI1 && CI2->getOpcode() == CI1.getOpcode() && CI2->getPredicate() == CI1.getPredicate() && CI2->getParent()->getParent() == CI1.getParent()->getParent()) // If the operands are the same if ((CI2->getOperand(0) == CI1.getOperand(0) && CI2->getOperand(1) == CI1.getOperand(1)) || // Or the compare is commutative and the operands are reversed (CI1.isCommutative() && CI2->getOperand(0) == CI1.getOperand(1) && CI2->getOperand(1) == CI1.getOperand(0))) // Then the instructiosn are identical, add to list. RetVals.push_back(CI2); } // isIdenticalBinaryInst - Return true if the two binary instructions are // identical. // static inline bool isIdenticalBinaryInst(const Instruction &I1, const Instruction *I2) { // Is it embedded in the same function? (This could be false if LHS // is a constant or global!) if (I1.getOpcode() != I2->getOpcode() || I1.getParent()->getParent() != I2->getParent()->getParent()) return false; // If they are CmpInst instructions, check their predicates if (CmpInst *CI1 = dyn_cast<CmpInst>(&const_cast<Instruction&>(I1))) if (CI1->getPredicate() != cast<CmpInst>(I2)->getPredicate()) return false; // They are identical if both operands are the same! if (I1.getOperand(0) == I2->getOperand(0) && I1.getOperand(1) == I2->getOperand(1)) return true; // If the instruction is commutative, the instruction can match if the // operands are swapped! // if ((I1.getOperand(0) == I2->getOperand(1) && I1.getOperand(1) == I2->getOperand(0)) && I1.isCommutative()) return true; return false; } // isIdenticalTernaryInst - Return true if the two ternary instructions are // identical. // static inline bool isIdenticalTernaryInst(const Instruction &I1, const Instruction *I2) { // Is it embedded in the same function? (This could be false if LHS // is a constant or global!) if (I1.getParent()->getParent() != I2->getParent()->getParent()) return false; // They are identical if all operands are the same! return I1.getOperand(0) == I2->getOperand(0) && I1.getOperand(1) == I2->getOperand(1) && I1.getOperand(2) == I2->getOperand(2); } void BVNImpl::handleBinaryInst(Instruction &I) { Value *LHS = I.getOperand(0); for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end(); UI != UE; ++UI) if (Instruction *Other = dyn_cast<Instruction>(*UI)) // Check to see if this new binary operator is not I, but same operand... if (Other != &I && isIdenticalBinaryInst(I, Other)) { // These instructions are identical. Handle the situation. RetVals.push_back(Other); } } // IdenticalComplexInst - Return true if the two instructions are the same, by // using a brute force comparison. This is useful for instructions with an // arbitrary number of arguments. // static inline bool IdenticalComplexInst(const Instruction *I1, const Instruction *I2) { assert(I1->getOpcode() == I2->getOpcode()); // Equal if they are in the same function... return I1->getParent()->getParent() == I2->getParent()->getParent() && // And return the same type... I1->getType() == I2->getType() && // And have the same number of operands... I1->getNumOperands() == I2->getNumOperands() && // And all of the operands are equal. std::equal(I1->op_begin(), I1->op_end(), I2->op_begin()); } void BVNImpl::visitGetElementPtrInst(GetElementPtrInst &I) { Value *Op = I.getOperand(0); // Try to pick a local operand if possible instead of a constant or a global // that might have a lot of uses. for (User::op_iterator i = I.op_begin() + 1, e = I.op_end(); i != e; ++i) if (isa<Instruction>(*i) || isa<Argument>(*i)) { Op = *i; break; } for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE; ++UI) if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI)) // Check to see if this new getelementptr is not I, but same operand... if (Other != &I && IdenticalComplexInst(&I, Other)) { // These instructions are identical. Handle the situation. RetVals.push_back(Other); } } void BVNImpl::handleTernaryInst(Instruction &I) { Value *Op0 = I.getOperand(0); Instruction *OtherInst; for (Value::use_iterator UI = Op0->use_begin(), UE = Op0->use_end(); UI != UE; ++UI) if ((OtherInst = dyn_cast<Instruction>(*UI)) && OtherInst->getOpcode() == I.getOpcode()) { // Check to see if this new select is not I, but has the same operands. if (OtherInst != &I && isIdenticalTernaryInst(I, OtherInst)) { // These instructions are identical. Handle the situation. RetVals.push_back(OtherInst); } } } // Ensure that users of ValueNumbering.h will link with this file DEFINING_FILE_FOR(BasicValueNumbering) <|endoftext|>
<commit_before>/******************************************************************************* * * Copyright (c) 2017, DbgVis - The Debugger Visualizer * Copyright (c) 2017, Peter Andreas Entschev * All rights reserved. * * BSD 3-Clause License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <string> cv::Mat read_image(const std::string& s) { return cv::imread(s); } cv::Mat read_image_roi(const cv::Mat& img, cv::Rect roi) { return cv::Mat(img(roi)); } int main(int argc, char *argv[]) { cv::Mat img = read_image("bansko.png"); cv::Mat img_roi = read_image_roi(img, cv::Rect(100, 100, 100, 100)); return 0; } <commit_msg>Fixed OpenCV's example sample image path<commit_after>/******************************************************************************* * * Copyright (c) 2017, DbgVis - The Debugger Visualizer * Copyright (c) 2017, Peter Andreas Entschev * All rights reserved. * * BSD 3-Clause License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <string> cv::Mat read_image(const std::string& s) { return cv::imread(s); } cv::Mat read_image_roi(const cv::Mat& img, cv::Rect roi) { return cv::Mat(img(roi)); } int main(int argc, char *argv[]) { cv::Mat img = read_image("../samples/bansko.png"); cv::Mat img_roi = read_image_roi(img, cv::Rect(100, 100, 100, 100)); return 0; } <|endoftext|>
<commit_before>#ifndef FALCON_CONTROLLER #define FALCON_CONTROLLER #include <falcon/core/FalconDevice.h> #include <falcon/grip/FalconGripFourButton.h> #include <falcon/firmware/FalconFirmwareNovintSDK.h> #include <falcon/util/FalconFirmwareBinaryNvent.h> #include <falcon/kinematic/stamper/StamperUtils.h> #include <falcon/core/FalconGeometry.h> #include <falcon/gmtl/gmtl.h> #include <falcon/kinematic/FalconKinematicStamper.h> #include <iostream> using namespace std; using namespace libnifalcon; using namespace StamperKinematicImpl; class FalconController { public: typedef std::array<double, 3> FalconVect3; typedef std::array<int, 3> FalconEncoder; enum FalconGripButton {RIGHT, UP, PRINCIPAL, LEFT}; enum FalconLED {RED, GREEN, BLUE}; ///Construct a Falcon Controller object FalconController(ostream& logStream = cout); ///return the address of the instancied singleton FalconController* getSingleton(); ///Destroy the falcon controller object and reset the static singleton ~FalconController(); ///Run the IO update and get most recent motor encoder values void update(); ///Get the position with origin offset applied (as a std::array of 3 doubles) FalconVect3 getPosition(); ///Set the force exerced to the player hand (vector3 as a std::array of 3 doubles) void setForce(FalconVect3 f); ///Reset the force to (0,0,0); void setZeroForce(); ///Get if the specified button is down or not bool getButtonState(FalconGripButton button); ///Set on or off the wanted LED void setLED(FalconLED led, bool state = true); private: ///Run the device initialisation (firmware loading, grip and kinematics declaration, etc...) bool initialize(); ///Just for testing stuff during the developement of this class void test(); private: FalconDevice falcon; FalconEncoder encoder; FalconVect3 origin, force, position, zero; static FalconController* singleton; ostream& logger; int ledstate; }; #endif //FALCON_CONTROLLER<commit_msg>Comment class attributes<commit_after>#ifndef FALCON_CONTROLLER #define FALCON_CONTROLLER #include <falcon/core/FalconDevice.h> #include <falcon/grip/FalconGripFourButton.h> #include <falcon/firmware/FalconFirmwareNovintSDK.h> #include <falcon/util/FalconFirmwareBinaryNvent.h> #include <falcon/kinematic/stamper/StamperUtils.h> #include <falcon/core/FalconGeometry.h> #include <falcon/gmtl/gmtl.h> #include <falcon/kinematic/FalconKinematicStamper.h> #include <iostream> using namespace std; using namespace libnifalcon; using namespace StamperKinematicImpl; class FalconController { public: typedef std::array<double, 3> FalconVect3; typedef std::array<int, 3> FalconEncoder; enum FalconGripButton {RIGHT, UP, PRINCIPAL, LEFT}; enum FalconLED {RED, GREEN, BLUE}; ///Construct a Falcon Controller object FalconController(ostream& logStream = cout); ///return the address of the instancied singleton FalconController* getSingleton(); ///Destroy the falcon controller object and reset the static singleton ~FalconController(); ///Run the IO update and get most recent motor encoder values void update(); ///Get the position with origin offset applied (as a std::array of 3 doubles) FalconVect3 getPosition(); ///Set the force exerced to the player hand (vector3 as a std::array of 3 doubles) void setForce(FalconVect3 f); ///Reset the force to (0,0,0); void setZeroForce(); ///Get if the specified button is down or not bool getButtonState(FalconGripButton button); ///Set on or off the wanted LED void setLED(FalconLED led, bool state = true); private: ///Run the device initialisation (firmware loading, grip and kinematics declaration, etc...) bool initialize(); ///Just for testing stuff during the developement of this class void test(); private: FalconDevice falcon; //libnifalcon device FalconEncoder encoder; //raw encoder value FalconVect3 origin, force, position, zero; ostream& logger; //outputstream where this class will write log int ledstate; //bitmask of the falcon's LEDs static FalconController* singleton; }; #endif //FALCON_CONTROLLER<|endoftext|>
<commit_before>#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #include <QtSingleApplication> int main(int argc, char *argv[]) { QtSingleApplication app(argc, argv); QQmlApplicationEngine engine; app.setWindowIcon(QIcon("resources/icons/ykman.png")); QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1"; putenv(pythonNoBytecode.toUtf8().data()); QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks"; putenv(frameworks.toUtf8().data()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec(); } <commit_msg>Exit if multiple instances are running<commit_after>#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #include <QtSingleApplication> int main(int argc, char *argv[]) { QtSingleApplication app(argc, argv); if (app.isRunning()) { return 0; } QQmlApplicationEngine engine; app.setWindowIcon(QIcon("resources/icons/ykman.png")); QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1"; putenv(pythonNoBytecode.toUtf8().data()); QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks"; putenv(frameworks.toUtf8().data()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); return app.exec(); } <|endoftext|>
<commit_before>#include "opencv2/ts.hpp" #include "precomp.hpp" #include <climits> #include <algorithm> #include <cstdarg> namespace cv{namespace optim{ using std::vector; const void dprintf(const char* format,...){ #ifdef ALEX_DEBUG va_list args; va_start (args,format); vprintf(format,args); va_end(args); #endif } void const print_matrix(const Mat& X){ #ifdef ALEX_DEBUG dprintf("\ttype:%d vs %d,\tsize: %d-on-%d\n",X.type(),CV_64FC1,X.rows,X.cols); for(int i=0;i<X.rows;i++){ dprintf("\t["); for(int j=0;j<X.cols;j++){ dprintf("%g, ",X.at<double>(i,j)); } dprintf("]\n"); } #endif } void const print_simplex_state(const Mat& c,const Mat&b,double v,const vector<int>& N,const vector<int>& B){ #ifdef ALEX_DEBUG dprintf("\tprint simplex state\n"); dprintf("v=%g\n",v); dprintf("here c goes\n"); print_matrix(c); dprintf("non-basic: "); for (std::vector<int>::const_iterator it = N.begin() ; it != N.end(); ++it){ dprintf("%d, ",*it); } dprintf("\n"); dprintf("here b goes\n"); print_matrix(b); dprintf("basic: "); for (std::vector<int>::const_iterator it = B.begin() ; it != B.end(); ++it){ dprintf("%d, ",*it); } dprintf("\n"); #endif } /**Due to technical considerations, the format of input b and c is somewhat special: *both b and c should be one column bigger than corresponding b and c of linear problem and the leftmost column will be used internally by this procedure - it should not be cleaned before the call to procedure and may contain mess after it also initializes N and B and does not make any assumptions about their init values * @return SOLVELP_UNFEASIBLE if problem is unfeasible, 0 if feasible. */ const int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B); const inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>& N,vector<int>& B, int leaving_index,int entering_index); /**@return SOLVELP_UNBOUNDED means the problem is unbdd, SOLVELP_MULTI means multiple solutions, SOLVELP_SINGLE means one solution. */ const int inner_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B); const void swap_columns(Mat_<double>& A,int col1,int col2); //return codes:-2 (no_sol - unbdd),-1(no_sol - unfsbl), 0(single_sol), 1(multiple_sol=>least_l2_norm) int solveLP(const Mat& Func, const Mat& Constr, Mat& z){ dprintf("call to solveLP\n"); //sanity check (size, type, no. of channels) CV_Assert(Func.type()==CV_64FC1); CV_Assert(Constr.type()==CV_64FC1); CV_Assert(Func.rows==1); CV_Assert(Constr.cols-Func.cols==1); //copy arguments for we will shall modify them Mat_<double> bigC=Mat_<double>(1,Func.cols+1), bigB=Mat_<double>(Constr.rows,Constr.cols+1); Func.copyTo(bigC.colRange(1,bigC.cols)); Constr.copyTo(bigB.colRange(1,bigB.cols)); double v=0; vector<int> N,B; if(initialize_simplex(bigC,bigB,v,N,B)==SOLVELP_UNFEASIBLE){ return SOLVELP_UNFEASIBLE; } Mat_<double> c=bigC.colRange(1,bigC.cols), b=bigB.colRange(1,bigB.cols); int res=0; if((res=inner_simplex(c,b,v,N,B))==SOLVELP_UNBOUNDED){ return SOLVELP_UNBOUNDED; } //return the optimal solution const int z_size[]={1,c.cols}; z.create(2,z_size,CV_64FC1); MatIterator_<double> it=z.begin<double>(); for(int i=1;i<=c.cols;i++,it++){ std::vector<int>::iterator pos=B.begin(); if((pos=std::find(B.begin(),B.end(),i))==B.end()){ *it=0; }else{ *it=b.at<double>(pos-B.begin(),b.cols-1); } } return res; } const int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B){ N.resize(c.cols); N[0]=0; for (std::vector<int>::iterator it = N.begin()+1 ; it != N.end(); ++it){ *it=it[-1]+1; } B.resize(b.rows); B[0]=N.size(); for (std::vector<int>::iterator it = B.begin()+1 ; it != B.end(); ++it){ *it=it[-1]+1; } v=0; int k=0; { double min=DBL_MAX; for(int i=0;i<b.rows;i++){ if(b(i,b.cols-1)<min){ min=b(i,b.cols-1); k=i; } } } if(b(k,b.cols-1)>=0){ N.erase(N.begin()); return 0; } Mat_<double> old_c=c.clone(); c=0; c(0,0)=-1; for(int i=0;i<b.rows;i++){ b(i,0)=-1; } print_simplex_state(c,b,v,N,B); dprintf("\tWE MAKE PIVOT\n"); pivot(c,b,v,N,B,k,0); print_simplex_state(c,b,v,N,B); inner_simplex(c,b,v,N,B); dprintf("\tAFTER INNER_SIMPLEX\n"); print_simplex_state(c,b,v,N,B); vector<int>::iterator it=std::find(B.begin(),B.end(),0); if(it!=B.end()){ int it_offset=it-B.begin(); if(b(it_offset,b.cols-1)>0){ return SOLVELP_UNFEASIBLE; } pivot(c,b,v,N,B,it_offset,0); } it=std::find(N.begin(),N.end(),0); int it_offset=it-N.begin(); std::iter_swap(it,N.begin()); swap_columns(c,it_offset,0); swap_columns(b,it_offset,0); dprintf("after swaps\n"); print_simplex_state(c,b,v,N,B); //start from 1, because we ignore x_0 c=0; v=0; for(int i=1;i<old_c.cols;i++){ if((it=std::find(N.begin(),N.end(),i))!=N.end()){ dprintf("i=%d from nonbasic\n",i); fflush(stdout); int it_offset=it-N.begin(); c(0,it_offset)+=old_c(0,i); print_matrix(c); }else{ //cv::Mat_ dprintf("i=%d from basic\n",i); fflush(stdout); int it_offset=std::find(B.begin(),B.end(),i)-B.begin(); c-=old_c(0,i)*b.row(it_offset).colRange(0,b.cols-1); v+=old_c(0,i)*b(it_offset,b.cols-1); print_matrix(c); } } dprintf("after restore\n"); print_simplex_state(c,b,v,N,B); N.erase(N.begin()); return 0; } const int inner_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B){ int count=0; while(1){ dprintf("iteration #%d\n",count++); static MatIterator_<double> pos_ptr; int e=-1,pos_ctr=0,min_var=INT_MAX; bool all_nonzero=true; for(pos_ptr=c.begin();pos_ptr!=c.end();pos_ptr++,pos_ctr++){ if(*pos_ptr==0){ all_nonzero=false; } if(*pos_ptr>0){ if(N[pos_ctr]<min_var){ e=pos_ctr; min_var=N[pos_ctr]; } } } if(e==-1){ dprintf("hello from e==-1\n"); print_matrix(c); if(all_nonzero==true){ return SOLVELP_SINGLE; }else{ return SOLVELP_MULTI; } } int l=-1; min_var=INT_MAX; double min=DBL_MAX; int row_it=0; double ite=0; MatIterator_<double> min_row_ptr=b.begin(); for(MatIterator_<double> it=b.begin();it!=b.end();it+=b.cols,row_it++){ double myite=0; //check constraints, select the tightest one, reinforcing Bland's rule if((myite=it[e])>0){ double val=it[b.cols-1]/myite; if(val<min || (val==min && B[row_it]<min_var)){ min_var=B[row_it]; min_row_ptr=it; ite=myite; min=val; l=row_it; } } } if(l==-1){ return SOLVELP_UNBOUNDED; } dprintf("the tightest constraint is in row %d with %g\n",l,min); pivot(c,b,v,N,B,l,e); dprintf("objective, v=%g\n",v); print_matrix(c); dprintf("constraints\n"); print_matrix(b); dprintf("non-basic: "); for (std::vector<int>::iterator it = N.begin() ; it != N.end(); ++it){ dprintf("%d, ",*it); } dprintf("\nbasic: "); for (std::vector<int>::iterator it = B.begin() ; it != B.end(); ++it){ dprintf("%d, ",*it); } dprintf("\n"); } } const inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>& N,vector<int>& B, int leaving_index,int entering_index){ double coef=b(leaving_index,entering_index); for(int i=0;i<b.cols;i++){ if(i==entering_index){ b(leaving_index,i)=1/coef; }else{ b(leaving_index,i)/=coef; } } for(int i=0;i<b.rows;i++){ if(i!=leaving_index){ double coef=b(i,entering_index); for(int j=0;j<b.cols;j++){ if(j==entering_index){ b(i,j)=-coef*b(leaving_index,j); }else{ b(i,j)-=(coef*b(leaving_index,j)); } } } } //objective function coef=c(0,entering_index); for(int i=0;i<(b.cols-1);i++){ if(i==entering_index){ c(0,i)=-coef*b(leaving_index,i); }else{ c(0,i)-=coef*b(leaving_index,i); } } dprintf("v was %g\n",v); v+=coef*b(leaving_index,b.cols-1); int tmp=N[entering_index]; N[entering_index]=B[leaving_index]; B[leaving_index]=tmp; } const inline void swap_columns(Mat_<double>& A,int col1,int col2){ for(int i=0;i<A.rows;i++){ double tmp=A(i,col1); A(i,col1)=A(i,col2); A(i,col2)=tmp; } } }} <commit_msg>Fix qualifiers on aux functions for solveLP()<commit_after>#include "opencv2/ts.hpp" #include "precomp.hpp" #include <climits> #include <algorithm> #include <cstdarg> namespace cv{namespace optim{ using std::vector; static void dprintf(const char* format,...){ #ifdef ALEX_DEBUG va_list args; va_start (args,format); vprintf(format,args); va_end(args); #endif } static void print_matrix(const Mat& X){ #ifdef ALEX_DEBUG dprintf("\ttype:%d vs %d,\tsize: %d-on-%d\n",X.type(),CV_64FC1,X.rows,X.cols); for(int i=0;i<X.rows;i++){ dprintf("\t["); for(int j=0;j<X.cols;j++){ dprintf("%g, ",X.at<double>(i,j)); } dprintf("]\n"); } #endif } static void print_simplex_state(const Mat& c,const Mat&b,double v,const vector<int>& N,const vector<int>& B){ #ifdef ALEX_DEBUG dprintf("\tprint simplex state\n"); dprintf("v=%g\n",v); dprintf("here c goes\n"); print_matrix(c); dprintf("non-basic: "); for (std::vector<int>::const_iterator it = N.begin() ; it != N.end(); ++it){ dprintf("%d, ",*it); } dprintf("\n"); dprintf("here b goes\n"); print_matrix(b); dprintf("basic: "); for (std::vector<int>::const_iterator it = B.begin() ; it != B.end(); ++it){ dprintf("%d, ",*it); } dprintf("\n"); #endif } /**Due to technical considerations, the format of input b and c is somewhat special: *both b and c should be one column bigger than corresponding b and c of linear problem and the leftmost column will be used internally by this procedure - it should not be cleaned before the call to procedure and may contain mess after it also initializes N and B and does not make any assumptions about their init values * @return SOLVELP_UNFEASIBLE if problem is unfeasible, 0 if feasible. */ static int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B); static inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>& N,vector<int>& B, int leaving_index,int entering_index); /**@return SOLVELP_UNBOUNDED means the problem is unbdd, SOLVELP_MULTI means multiple solutions, SOLVELP_SINGLE means one solution. */ static int inner_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B); static void swap_columns(Mat_<double>& A,int col1,int col2); //return codes:-2 (no_sol - unbdd),-1(no_sol - unfsbl), 0(single_sol), 1(multiple_sol=>least_l2_norm) int solveLP(const Mat& Func, const Mat& Constr, Mat& z){ dprintf("call to solveLP\n"); //sanity check (size, type, no. of channels) CV_Assert(Func.type()==CV_64FC1); CV_Assert(Constr.type()==CV_64FC1); CV_Assert(Func.rows==1); CV_Assert(Constr.cols-Func.cols==1); //copy arguments for we will shall modify them Mat_<double> bigC=Mat_<double>(1,Func.cols+1), bigB=Mat_<double>(Constr.rows,Constr.cols+1); Func.copyTo(bigC.colRange(1,bigC.cols)); Constr.copyTo(bigB.colRange(1,bigB.cols)); double v=0; vector<int> N,B; if(initialize_simplex(bigC,bigB,v,N,B)==SOLVELP_UNFEASIBLE){ return SOLVELP_UNFEASIBLE; } Mat_<double> c=bigC.colRange(1,bigC.cols), b=bigB.colRange(1,bigB.cols); int res=0; if((res=inner_simplex(c,b,v,N,B))==SOLVELP_UNBOUNDED){ return SOLVELP_UNBOUNDED; } //return the optimal solution const int z_size[]={1,c.cols}; z.create(2,z_size,CV_64FC1); MatIterator_<double> it=z.begin<double>(); for(int i=1;i<=c.cols;i++,it++){ std::vector<int>::iterator pos=B.begin(); if((pos=std::find(B.begin(),B.end(),i))==B.end()){ *it=0; }else{ *it=b.at<double>(pos-B.begin(),b.cols-1); } } return res; } static int initialize_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B){ N.resize(c.cols); N[0]=0; for (std::vector<int>::iterator it = N.begin()+1 ; it != N.end(); ++it){ *it=it[-1]+1; } B.resize(b.rows); B[0]=N.size(); for (std::vector<int>::iterator it = B.begin()+1 ; it != B.end(); ++it){ *it=it[-1]+1; } v=0; int k=0; { double min=DBL_MAX; for(int i=0;i<b.rows;i++){ if(b(i,b.cols-1)<min){ min=b(i,b.cols-1); k=i; } } } if(b(k,b.cols-1)>=0){ N.erase(N.begin()); return 0; } Mat_<double> old_c=c.clone(); c=0; c(0,0)=-1; for(int i=0;i<b.rows;i++){ b(i,0)=-1; } print_simplex_state(c,b,v,N,B); dprintf("\tWE MAKE PIVOT\n"); pivot(c,b,v,N,B,k,0); print_simplex_state(c,b,v,N,B); inner_simplex(c,b,v,N,B); dprintf("\tAFTER INNER_SIMPLEX\n"); print_simplex_state(c,b,v,N,B); vector<int>::iterator it=std::find(B.begin(),B.end(),0); if(it!=B.end()){ int it_offset=it-B.begin(); if(b(it_offset,b.cols-1)>0){ return SOLVELP_UNFEASIBLE; } pivot(c,b,v,N,B,it_offset,0); } it=std::find(N.begin(),N.end(),0); int it_offset=it-N.begin(); std::iter_swap(it,N.begin()); swap_columns(c,it_offset,0); swap_columns(b,it_offset,0); dprintf("after swaps\n"); print_simplex_state(c,b,v,N,B); //start from 1, because we ignore x_0 c=0; v=0; for(int i=1;i<old_c.cols;i++){ if((it=std::find(N.begin(),N.end(),i))!=N.end()){ dprintf("i=%d from nonbasic\n",i); fflush(stdout); int it_offset=it-N.begin(); c(0,it_offset)+=old_c(0,i); print_matrix(c); }else{ //cv::Mat_ dprintf("i=%d from basic\n",i); fflush(stdout); int it_offset=std::find(B.begin(),B.end(),i)-B.begin(); c-=old_c(0,i)*b.row(it_offset).colRange(0,b.cols-1); v+=old_c(0,i)*b(it_offset,b.cols-1); print_matrix(c); } } dprintf("after restore\n"); print_simplex_state(c,b,v,N,B); N.erase(N.begin()); return 0; } static int inner_simplex(Mat_<double>& c, Mat_<double>& b,double& v,vector<int>& N,vector<int>& B){ int count=0; while(1){ dprintf("iteration #%d\n",count++); static MatIterator_<double> pos_ptr; int e=-1,pos_ctr=0,min_var=INT_MAX; bool all_nonzero=true; for(pos_ptr=c.begin();pos_ptr!=c.end();pos_ptr++,pos_ctr++){ if(*pos_ptr==0){ all_nonzero=false; } if(*pos_ptr>0){ if(N[pos_ctr]<min_var){ e=pos_ctr; min_var=N[pos_ctr]; } } } if(e==-1){ dprintf("hello from e==-1\n"); print_matrix(c); if(all_nonzero==true){ return SOLVELP_SINGLE; }else{ return SOLVELP_MULTI; } } int l=-1; min_var=INT_MAX; double min=DBL_MAX; int row_it=0; double ite=0; MatIterator_<double> min_row_ptr=b.begin(); for(MatIterator_<double> it=b.begin();it!=b.end();it+=b.cols,row_it++){ double myite=0; //check constraints, select the tightest one, reinforcing Bland's rule if((myite=it[e])>0){ double val=it[b.cols-1]/myite; if(val<min || (val==min && B[row_it]<min_var)){ min_var=B[row_it]; min_row_ptr=it; ite=myite; min=val; l=row_it; } } } if(l==-1){ return SOLVELP_UNBOUNDED; } dprintf("the tightest constraint is in row %d with %g\n",l,min); pivot(c,b,v,N,B,l,e); dprintf("objective, v=%g\n",v); print_matrix(c); dprintf("constraints\n"); print_matrix(b); dprintf("non-basic: "); for (std::vector<int>::iterator it = N.begin() ; it != N.end(); ++it){ dprintf("%d, ",*it); } dprintf("\nbasic: "); for (std::vector<int>::iterator it = B.begin() ; it != B.end(); ++it){ dprintf("%d, ",*it); } dprintf("\n"); } } static inline void pivot(Mat_<double>& c,Mat_<double>& b,double& v,vector<int>& N,vector<int>& B, int leaving_index,int entering_index){ double coef=b(leaving_index,entering_index); for(int i=0;i<b.cols;i++){ if(i==entering_index){ b(leaving_index,i)=1/coef; }else{ b(leaving_index,i)/=coef; } } for(int i=0;i<b.rows;i++){ if(i!=leaving_index){ double coef=b(i,entering_index); for(int j=0;j<b.cols;j++){ if(j==entering_index){ b(i,j)=-coef*b(leaving_index,j); }else{ b(i,j)-=(coef*b(leaving_index,j)); } } } } //objective function coef=c(0,entering_index); for(int i=0;i<(b.cols-1);i++){ if(i==entering_index){ c(0,i)=-coef*b(leaving_index,i); }else{ c(0,i)-=coef*b(leaving_index,i); } } dprintf("v was %g\n",v); v+=coef*b(leaving_index,b.cols-1); int tmp=N[entering_index]; N[entering_index]=B[leaving_index]; B[leaving_index]=tmp; } static inline void swap_columns(Mat_<double>& A,int col1,int col2){ for(int i=0;i<A.rows;i++){ double tmp=A(i,col1); A(i,col1)=A(i,col2); A(i,col2)=tmp; } } }} <|endoftext|>
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/region.hpp> #include <hadesmem/process.hpp> #include <hadesmem/module_list.hpp> #include <hadesmem/region_list.hpp> #include <hadesmem/pelib/export.hpp> #include <hadesmem/process_list.hpp> #include <hadesmem/process_entry.hpp> #include <hadesmem/pelib/pe_file.hpp> #include <hadesmem/pelib/import_dir.hpp> #include <hadesmem/detail/initialize.hpp> #include <hadesmem/pelib/export_list.hpp> #include <hadesmem/pelib/import_thunk.hpp> #include <hadesmem/pelib/import_dir_list.hpp> #include <hadesmem/pelib/import_thunk_list.hpp> namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } void DumpRegions(hadesmem::Process const& process) { std::wcout << "\nRegions:\n"; hadesmem::RegionList const regions(process); for (auto const& region : regions) { std::wcout << "\n"; std::wcout << "\tBase: " << PtrToString(region.GetBase()) << "\n"; std::wcout << "\tAllocation Base: " << PtrToString(region.GetAllocBase()) << "\n"; std::wcout << "\tAllocation Protect: " << std::hex << region.GetAllocProtect() << std::dec << "\n"; std::wcout << "\tSize: " << std::hex << region.GetSize() << std::dec << "\n"; std::wcout << "\tState: " << std::hex << region.GetState() << std::dec << "\n"; std::wcout << "\tProtect: " << std::hex << region.GetProtect() << std::dec << "\n"; std::wcout << "\tType: " << std::hex << region.GetType() << std::dec << "\n"; } } void DumpExports(hadesmem::Process const& process, hadesmem::Module const& module) { std::wcout << "\n\tExports:\n"; hadesmem::PeFile pe_file(process, module.GetHandle(), hadesmem::PeFileType::Image); hadesmem::ExportList exports(process, pe_file); for (auto const& e : exports) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tRVA: " << std::hex << e.GetRva() << std::dec << "\n"; std::wcout << "\t\tVA: " << PtrToString(e.GetVa()) << "\n"; std::wcout << "\t\tName: " << e.GetName().c_str() << "\n"; std::wcout << "\t\tOrdinal: " << e.GetOrdinal() << "\n"; std::wcout << "\t\tByName: " << e.ByName() << "\n"; std::wcout << "\t\tByOrdinal: " << e.ByOrdinal() << "\n"; std::wcout << "\t\tIsForwarded: " << e.IsForwarded() << "\n"; std::wcout << "\t\tForwarder: " << e.GetForwarder().c_str() << "\n"; std::wcout << "\t\tForwarderModule: " << e.GetForwarderModule().c_str() << "\n"; std::wcout << "\t\tForwarderFunction: " << e.GetForwarderFunction().c_str() << "\n"; std::wcout << "\t\tIsForwardedByOrdinal: " << e.IsForwardedByOrdinal() << "\n"; if (e.IsForwardedByOrdinal()) { try { std::wcout << "\t\tForwarderOrdinal: " << e.GetForwarderOrdinal() << "\n"; } catch (std::exception const& /*e*/) { std::wcout << "\t\tForwarderOrdinal Invalid.\n"; } } std::wcout << std::noboolalpha; } } void DumpImports(hadesmem::Process const& process, hadesmem::Module const& module) { std::wcout << "\n\tImport Dirs:\n"; hadesmem::PeFile pe_file(process, module.GetHandle(), hadesmem::PeFileType::Image); hadesmem::ImportDirList import_dirs(process, pe_file); for (auto const& dir : import_dirs) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tCharacteristics: " << std::hex << dir.GetCharacteristics() << std::dec << "\n"; std::wcout << "\t\tTimeDateStamp: " << dir.GetTimeDateStamp() << "\n"; std::wcout << "\t\tForwarderChain: " << dir.GetForwarderChain() << "\n"; std::wcout << "\t\tName (Raw): " << std::hex << dir.GetNameRaw() << std::dec << "\n"; std::wcout << "\t\tName: " << dir.GetName().c_str() << "\n"; std::wcout << "\t\tFirstThunk: " << std::hex << dir.GetFirstThunk() << std::dec << "\n"; std::wcout << "\n\t\tImport Thunks:\n"; // Images without an INT are valid, but after an image like this is loaded // it is impossible to recover the name table. if (!dir.GetCharacteristics()) { std::wcout << "\n\t\t\tWARNING! No INT for this module.\n"; continue; } hadesmem::ImportThunkList import_thunks(process, pe_file, dir.GetCharacteristics()); for (auto const& thunk : import_thunks) { std::wcout << "\n"; std::wcout << "\t\t\tAddressOfData: " << thunk.GetAddressOfData() << "\n"; std::wcout << "\t\t\tOrdinalRaw: " << thunk.GetOrdinalRaw() << "\n"; std::wcout << "\t\t\tByOrdinal: " << thunk.ByOrdinal() << "\n"; if (thunk.ByOrdinal()) { std::wcout << "\t\t\tOrdinal: " << thunk.GetOrdinal() << "\n"; } else { std::wcout << "\t\t\tHint: " << thunk.GetHint() << "\n"; std::wcout << "\t\t\tName: " << thunk.GetName().c_str() << "\n"; } std::wcout << "\t\t\tFunction: " << std::hex << thunk.GetFunction() << std::dec << "\n"; } std::wcout << std::noboolalpha; } } void DumpModules(hadesmem::Process const& process) { std::wcout << "\nModules:\n"; hadesmem::ModuleList const modules(process); for (auto const& module : modules) { std::wcout << "\n"; std::wcout << "\tHandle: " << PtrToString(module.GetHandle()) << "\n"; std::wcout << "\tSize: " << std::hex << module.GetSize() << std::dec << "\n"; std::wcout << "\tName: " << module.GetName() << "\n"; std::wcout << "\tPath: " << module.GetPath() << "\n"; DumpExports(process, module); DumpImports(process, module); } } void DumpProcessEntry(hadesmem::ProcessEntry const& process_entry) { std::wcout << "\n"; std::wcout << "ID: " << process_entry.GetId() << "\n"; std::wcout << "Threads: " << process_entry.GetThreads() << "\n"; std::wcout << "Parent: " << process_entry.GetParentId() << "\n"; std::wcout << "Priority: " << process_entry.GetPriority() << "\n"; std::wcout << "Name: " << process_entry.GetName() << "\n"; std::unique_ptr<hadesmem::Process> process; try { process.reset(new hadesmem::Process(process_entry.GetId())); } catch (std::exception const& /*e*/) { std::wcout << "\nCould not open process for further inspection.\n\n"; return; } std::wcout << "Path: " << hadesmem::GetPath(*process) << "\n"; std::wcout << "WoW64: " << (hadesmem::IsWoW64(*process) ? "Yes" : "No") << "\n"; DumpModules(*process); DumpRegions(*process); } } int main(int /*argc*/, char* /*argv*/[]) { try { hadesmem::detail::DisableUserModeCallbackExceptionFilter(); hadesmem::detail::EnableCrtDebugFlags(); hadesmem::detail::EnableTerminationOnHeapCorruption(); hadesmem::detail::EnableBottomUpRand(); hadesmem::detail::ImbueAllDefault(); std::cout << "HadesMem Dumper\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } DWORD pid = 0; if (var_map.count("pid")) { pid = var_map["pid"].as<DWORD>(); } try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } if (pid) { hadesmem::ProcessList const processes; auto iter = std::find_if(std::begin(processes), std::end(processes), [pid] (hadesmem::ProcessEntry const& process_entry) { return process_entry.GetId() == pid; }); if (iter != std::end(processes)) { DumpProcessEntry(*iter); } else { HADESMEM_THROW_EXCEPTION(hadesmem::Error() << hadesmem::ErrorString("Failed to find requested process.")); } } else { std::wcout << "\nProcesses:\n"; hadesmem::ProcessList const processes; for (auto const& process_entry : processes) { DumpProcessEntry(process_entry); } } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <commit_msg>* Formatting and output improvement.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/error.hpp> #include <hadesmem/module.hpp> #include <hadesmem/region.hpp> #include <hadesmem/process.hpp> #include <hadesmem/module_list.hpp> #include <hadesmem/region_list.hpp> #include <hadesmem/pelib/export.hpp> #include <hadesmem/process_list.hpp> #include <hadesmem/process_entry.hpp> #include <hadesmem/pelib/pe_file.hpp> #include <hadesmem/pelib/import_dir.hpp> #include <hadesmem/detail/initialize.hpp> #include <hadesmem/pelib/export_list.hpp> #include <hadesmem/pelib/import_thunk.hpp> #include <hadesmem/pelib/import_dir_list.hpp> #include <hadesmem/pelib/import_thunk_list.hpp> namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } void DumpRegions(hadesmem::Process const& process) { std::wcout << "\nRegions:\n"; hadesmem::RegionList const regions(process); for (auto const& region : regions) { std::wcout << "\n"; std::wcout << "\tBase: " << PtrToString(region.GetBase()) << "\n"; std::wcout << "\tAllocation Base: " << PtrToString(region.GetAllocBase()) << "\n"; std::wcout << "\tAllocation Protect: " << std::hex << region.GetAllocProtect() << std::dec << "\n"; std::wcout << "\tSize: " << std::hex << region.GetSize() << std::dec << "\n"; std::wcout << "\tState: " << std::hex << region.GetState() << std::dec << "\n"; std::wcout << "\tProtect: " << std::hex << region.GetProtect() << std::dec << "\n"; std::wcout << "\tType: " << std::hex << region.GetType() << std::dec << "\n"; } } void DumpExports(hadesmem::Process const& process, hadesmem::Module const& module) { std::wcout << "\n\tExports:\n"; hadesmem::PeFile pe_file(process, module.GetHandle(), hadesmem::PeFileType::Image); hadesmem::ExportList exports(process, pe_file); for (auto const& e : exports) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tRVA: " << std::hex << e.GetRva() << std::dec << "\n"; std::wcout << "\t\tVA: " << PtrToString(e.GetVa()) << "\n"; std::wcout << "\t\tName: " << e.GetName().c_str() << "\n"; std::wcout << "\t\tOrdinal: " << e.GetOrdinal() << "\n"; std::wcout << "\t\tByName: " << e.ByName() << "\n"; std::wcout << "\t\tByOrdinal: " << e.ByOrdinal() << "\n"; std::wcout << "\t\tIsForwarded: " << e.IsForwarded() << "\n"; if (e.IsForwarded()) { std::wcout << "\t\tForwarder: " << e.GetForwarder().c_str() << "\n"; std::wcout << "\t\tForwarderModule: " << e.GetForwarderModule().c_str() << "\n"; std::wcout << "\t\tForwarderFunction: " << e.GetForwarderFunction().c_str() << "\n"; std::wcout << "\t\tIsForwardedByOrdinal: " << e.IsForwardedByOrdinal() << "\n"; if (e.IsForwardedByOrdinal()) { try { std::wcout << "\t\tForwarderOrdinal: " << e.GetForwarderOrdinal() << "\n"; } catch (std::exception const& /*e*/) { std::wcout << "\t\tForwarderOrdinal Invalid.\n"; } } } std::wcout << std::noboolalpha; } } void DumpImports(hadesmem::Process const& process, hadesmem::Module const& module) { std::wcout << "\n\tImport Dirs:\n"; hadesmem::PeFile pe_file(process, module.GetHandle(), hadesmem::PeFileType::Image); hadesmem::ImportDirList import_dirs(process, pe_file); for (auto const& dir : import_dirs) { std::wcout << std::boolalpha; std::wcout << "\n"; std::wcout << "\t\tCharacteristics: " << std::hex << dir.GetCharacteristics() << std::dec << "\n"; std::wcout << "\t\tTimeDateStamp: " << dir.GetTimeDateStamp() << "\n"; std::wcout << "\t\tForwarderChain: " << dir.GetForwarderChain() << "\n"; std::wcout << "\t\tName (Raw): " << std::hex << dir.GetNameRaw() << std::dec << "\n"; std::wcout << "\t\tName: " << dir.GetName().c_str() << "\n"; std::wcout << "\t\tFirstThunk: " << std::hex << dir.GetFirstThunk() << std::dec << "\n"; std::wcout << "\n\t\tImport Thunks:\n"; // Images without an INT are valid, but after an image like this is loaded // it is impossible to recover the name table. if (!dir.GetCharacteristics()) { std::wcout << "\n\t\t\tWARNING! No INT for this module.\n"; continue; } hadesmem::ImportThunkList import_thunks(process, pe_file, dir.GetCharacteristics()); for (auto const& thunk : import_thunks) { std::wcout << "\n"; std::wcout << "\t\t\tAddressOfData: " << thunk.GetAddressOfData() << "\n"; std::wcout << "\t\t\tOrdinalRaw: " << thunk.GetOrdinalRaw() << "\n"; std::wcout << "\t\t\tByOrdinal: " << thunk.ByOrdinal() << "\n"; if (thunk.ByOrdinal()) { std::wcout << "\t\t\tOrdinal: " << thunk.GetOrdinal() << "\n"; } else { std::wcout << "\t\t\tHint: " << thunk.GetHint() << "\n"; std::wcout << "\t\t\tName: " << thunk.GetName().c_str() << "\n"; } std::wcout << "\t\t\tFunction: " << std::hex << thunk.GetFunction() << std::dec << "\n"; } std::wcout << std::noboolalpha; } } void DumpModules(hadesmem::Process const& process) { std::wcout << "\nModules:\n"; hadesmem::ModuleList const modules(process); for (auto const& module : modules) { std::wcout << "\n"; std::wcout << "\tHandle: " << PtrToString(module.GetHandle()) << "\n"; std::wcout << "\tSize: " << std::hex << module.GetSize() << std::dec << "\n"; std::wcout << "\tName: " << module.GetName() << "\n"; std::wcout << "\tPath: " << module.GetPath() << "\n"; DumpExports(process, module); DumpImports(process, module); } } void DumpProcessEntry(hadesmem::ProcessEntry const& process_entry) { std::wcout << "\n"; std::wcout << "ID: " << process_entry.GetId() << "\n"; std::wcout << "Threads: " << process_entry.GetThreads() << "\n"; std::wcout << "Parent: " << process_entry.GetParentId() << "\n"; std::wcout << "Priority: " << process_entry.GetPriority() << "\n"; std::wcout << "Name: " << process_entry.GetName() << "\n"; std::unique_ptr<hadesmem::Process> process; try { process.reset(new hadesmem::Process(process_entry.GetId())); } catch (std::exception const& /*e*/) { std::wcout << "\nCould not open process for further inspection.\n\n"; return; } std::wcout << "Path: " << hadesmem::GetPath(*process) << "\n"; std::wcout << "WoW64: " << (hadesmem::IsWoW64(*process) ? "Yes" : "No") << "\n"; DumpModules(*process); DumpRegions(*process); } } int main(int /*argc*/, char* /*argv*/[]) { try { hadesmem::detail::DisableUserModeCallbackExceptionFilter(); hadesmem::detail::EnableCrtDebugFlags(); hadesmem::detail::EnableTerminationOnHeapCorruption(); hadesmem::detail::EnableBottomUpRand(); hadesmem::detail::ImbueAllDefault(); std::cout << "HadesMem Dumper\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help")) { std::cout << '\n' << opts_desc << '\n'; return 1; } DWORD pid = 0; if (var_map.count("pid")) { pid = var_map["pid"].as<DWORD>(); } try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } if (pid) { hadesmem::ProcessList const processes; auto iter = std::find_if(std::begin(processes), std::end(processes), [pid] (hadesmem::ProcessEntry const& process_entry) { return process_entry.GetId() == pid; }); if (iter != std::end(processes)) { DumpProcessEntry(*iter); } else { HADESMEM_THROW_EXCEPTION(hadesmem::Error() << hadesmem::ErrorString("Failed to find requested process.")); } } else { std::wcout << "\nProcesses:\n"; hadesmem::ProcessList const processes; for (auto const& process_entry : processes) { DumpProcessEntry(process_entry); } } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <|endoftext|>
<commit_before>#include <cmath> #include <dish.hpp> #include <item.hpp> #include <engineLimits.hpp> #include <debug.hpp> #include <errors.hpp> Dish::Dish(std::string name, Food* food, uint64_t foodMass, uint64_t amountOfPeople) : Stats {name, DISH_MIN_MASS, DISH_MAX_MASS, DISH_MIN_PRICE, DISH_MAX_PRICE, DISH_MIN_FATS, DISH_MAX_FATS, DISH_MIN_PROTEINS, DISH_MAX_PROTEINS, DISH_MIN_CARBOHYDRATES, DISH_MAX_CARBOHYDRATES, DISH_MIN_CALORIES, DISH_MAX_CALORIES} { setMass(foodMass); setPrice(std::round(food->getPrice()/food->getMass()*foodMass)); setFats(std::round(food->getFats()*foodMass/HUNDRED_GRAM)); setProteins(std::round(food->getProteins()*foodMass/HUNDRED_GRAM)); setCarbohydrates(std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM)); setCalories(std::round(food->getCalories()*foodMass/HUNDRED_GRAM)); setAmountOfPeople(amountOfPeople); ingridients.insert(std::pair<Food*, uint64_t>(food, foodMass)); food->registerDish(this); PRINT_OBJ("Created dish class " << NAME_ID); } Dish::~Dish(void) { PRINT_OBJ("Destroyed dish basic class " << NAME_ID); } Dish& Dish::operator=(const Dish& right) { if ( this == &right ) { return *this; } Dish::Stats::operator=(right); ingridients.clear(); for ( auto& entry: right.getIngridientMap() ) { addFood(entry.first, entry.second); } return *this; } void Dish::addFood(Food* const food, uint64_t foodMass) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; if ( foodMass < minMass || foodMass > maxMass ) { PRINT_ERR("Wrong food " << NAME_ID_CLASS(*food) << " mass value provided [" << foodMass << "]"); throw WrongDishMass(); } if ( ingridients.count(food) ) { PRINT_ERR("Could not add " << NAME_ID_CLASS(*food) << " food that is already in the dish"); throw AlreadySuchFoodInList(); } if ( ingridients.size() >= maxListItemsAmount ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish"); throw TooMuchFoodInMap(); } newMass = getMass() + foodMass; newPrice = getPrice() + std::round(food->getPrice()*foodMass/food->getMass()); newFats = getFats() + std::round(food->getFats()*foodMass/HUNDRED_GRAM); newProteins = getProteins() + std::round(food->getProteins()*foodMass/HUNDRED_GRAM); newCarbohydrates = getCarbohydrates() + std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM); newCalories = getCalories() + std::round(food->getCalories()*foodMass/HUNDRED_GRAM); if ( newMass > maxMass ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result mass is too big [" << newMass << "]"); throw TooBigDishMass(); } if ( newPrice > maxPrice ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result price is too big [" << newPrice << "]"); throw TooBigDishPrice(); } if ( newFats > maxFats ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result fats are too big [" << newFats << "]"); throw TooBigDishFats(); } if ( newProteins > maxProteins ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result proteins are too big [" << newProteins << "]"); throw TooBigDishProteins(); } if ( newCarbohydrates > maxCarbohydrates ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result carbohydrates are too big [" << newCarbohydrates << "]"); throw TooBigDishCarbohydrates(); } if ( newCalories > maxCalories ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result calories are too big [" << newCalories << "]"); throw TooBigDishCalories(); } setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); ingridients.insert(std::pair<Food *, uint64_t>(food, foodMass)); food->registerDish(this); PRINT_INFO("Food " << NAME_ID_CLASS(*food) << " was added to dish " << NAME_ID << ""); } void Dish::removeFood(Food* const food) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; uint64_t foodMass = ingridients[food]; if ( !ingridients.count(food) ) { PRINT_ERR("Could not remove food " << NAME_ID_CLASS(*food) << " that is not in the dish"); throw NoSuchFoodInMap(); } if ( ingridients.size() <= minListItemsAmount) { PRINT_ERR("Could not remove last " << NAME_ID_CLASS(*food) << " food in the dish"); throw LastFoodInMap(); } newMass = getMass() - foodMass; newPrice = getPrice() - std::round(food->getPrice()*foodMass/food->getMass()); newFats = getFats() - std::round(food->getFats()*foodMass/HUNDRED_GRAM); newProteins = getProteins() - std::round(food->getProteins()*foodMass/HUNDRED_GRAM); newCarbohydrates = getCarbohydrates() - std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM); newCalories = getCalories() - std::round(food->getCalories()*foodMass/HUNDRED_GRAM); setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); ingridients.erase(food); food->unregisterDish(this); PRINT_INFO("Food " << NAME_ID_CLASS(*food) << " was removed from dish " << NAME_ID << ""); } void Dish::changeFoodAmount(Food* const food, uint64_t foodMass) { uint64_t newPrice, newFats, newProteins, newCarbohydrates, newCalories; int64_t currentFoodMass = ingridients[food]; if ( foodMass < minMass || foodMass > maxMass ) { PRINT_ERR("Wrong food " << NAME_ID_CLASS(*food) << " mass value provided [" << foodMass << "]"); throw WrongDishMass(); } if ( !ingridients.count(food) ) { PRINT_ERR("Could not change " << NAME_ID_CLASS(*food) << " food that is not in the dish"); throw NoSuchFoodInMap(); } newPrice = getPrice() + std::round(food->getPrice()*foodMass/food->getMass()) - std::round(food->getPrice()*currentFoodMass/food->getMass()); newFats = getFats() + std::round(food->getFats()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getFats()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); newProteins = getProteins() + std::round(food->getProteins()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getProteins()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); newCarbohydrates = getCarbohydrates() + std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getCarbohydrates()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); newCalories = getCalories() + std::round(food->getCalories()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getCalories()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); if ( newPrice > maxPrice ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result price is too big [" << newPrice << "]"); throw TooBigDishPrice(); } if ( newFats > maxFats ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result fats are too big [" << newFats << "]"); throw TooBigDishFats(); } if ( newProteins > maxProteins ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result proteins are too big [" << newProteins << "]"); throw TooBigDishProteins(); } if ( newCarbohydrates > maxCarbohydrates ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result carbohydrates are too big [" << newCarbohydrates << "]"); throw TooBigDishCarbohydrates(); } if ( newCalories > maxCalories ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result calories are too big [" << newCalories << "]"); throw TooBigDishCalories(); } setMass(foodMass*amountOfPeople); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); ingridients[food] = foodMass; PRINT_INFO("Food " << NAME_ID_CLASS(*food) << " was changed in dish " << NAME_ID << ""); } void Dish::changeAmountOfPeople(uint64_t amountOfPeople) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; uint64_t currentAmountOfPeople = getAmountOfPeople(); if ( amountOfPeople < minAmountOfPeople || amountOfPeople > maxAmountOfPeople ) { PRINT_ERR("Wrong dish amount of people provided [" << amountOfPeople << "]"); throw WrongDishAmountOfPeople(); } newMass = std::round(getMass()*amountOfPeople/currentAmountOfPeople); newPrice = std::round(getPrice()*amountOfPeople/currentAmountOfPeople); newFats = std::round(getFats()*amountOfPeople/currentAmountOfPeople); newProteins = std::round(getProteins()*amountOfPeople/currentAmountOfPeople); newCarbohydrates = std::round(getCarbohydrates()*amountOfPeople/currentAmountOfPeople); newCalories = std::round(getCalories()*amountOfPeople/currentAmountOfPeople); if ( newMass > maxMass ) { PRINT_ERR("Could not change amount of people in the dish. Result mass is too big [" << newMass << "]"); throw TooBigDishMass(); } if ( newPrice > maxPrice ) { PRINT_ERR("Could not change amount of people in the dish. Result price is too big [" << newPrice << "]"); throw TooBigDishPrice(); } if ( newFats > maxFats ) { PRINT_ERR("Could not change amount of people in the dish. Result fats are too big [" << newFats << "]"); throw TooBigDishFats(); } if ( newProteins > maxProteins ) { PRINT_ERR("Could not change amount of people in the dish. Result proteins are too big [" << newProteins << "]"); throw TooBigDishProteins(); } if ( newCarbohydrates > maxCarbohydrates ) { PRINT_ERR("Could not change amount of people in the dish. Result carbohydrates are too big [" << newCarbohydrates << "]"); throw TooBigDishCarbohydrates(); } if ( newCalories > maxCalories ) { PRINT_ERR("Could not change amount of people in the dish. Result calories are too big [" << newCalories << "]"); throw TooBigDishCalories(); } setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); setAmountOfPeople(amountOfPeople); for ( auto& entry: ingridients ) { entry.second = entry.second * amountOfPeople / currentAmountOfPeople; } PRINT_INFO("Dish " << NAME_ID << " now have " << amountOfPeople << " people"); } void Dish::setAmountOfPeople(uint64_t amountOfPeople) { if ( amountOfPeople < minAmountOfPeople || amountOfPeople > maxAmountOfPeople ) { PRINT_ERR("Wrong dish amount of people provided [" << amountOfPeople << "]"); throw WrongPeopleStatsAmountOfPeople(); } this->amountOfPeople = amountOfPeople; PRINT_INFO("Dish class " << NAME_ID << " amount of people set to " << amountOfPeople); } uint64_t Dish::getAmountOfPeople(void) const { return amountOfPeople; } const std::map<Food*, uint64_t, Stats::Compare>& Dish::getIngridientMap(void) const { return ingridients; } std::ostream& operator<<(std::ostream& out, const Dish& dish) { #ifdef DEBUG std::map<Food*, uint64_t, Stats::Compare> dishMap = dish.getIngridientMap(); out << dynamic_cast<const Stats&>(dish) << std::endl; out << " INGRIDIENTS (" << dishMap.size() << "):" << std::endl; out << " >>> >>> >>>" << std::endl; for ( auto& entry: dishMap ) { out << " ingridient " << *entry.first << std::endl; out << " - mass in dish: " << entry.second << " gram" << std::endl; } out << " <<< <<< <<<"; #else out << dish.getName(); #endif return out; } <commit_msg>engine: Fix mass calculation algorythm on food edit<commit_after>#include <cmath> #include <dish.hpp> #include <item.hpp> #include <engineLimits.hpp> #include <debug.hpp> #include <errors.hpp> Dish::Dish(std::string name, Food* food, uint64_t foodMass, uint64_t amountOfPeople) : Stats {name, DISH_MIN_MASS, DISH_MAX_MASS, DISH_MIN_PRICE, DISH_MAX_PRICE, DISH_MIN_FATS, DISH_MAX_FATS, DISH_MIN_PROTEINS, DISH_MAX_PROTEINS, DISH_MIN_CARBOHYDRATES, DISH_MAX_CARBOHYDRATES, DISH_MIN_CALORIES, DISH_MAX_CALORIES} { setMass(foodMass); setPrice(std::round(food->getPrice()/food->getMass()*foodMass)); setFats(std::round(food->getFats()*foodMass/HUNDRED_GRAM)); setProteins(std::round(food->getProteins()*foodMass/HUNDRED_GRAM)); setCarbohydrates(std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM)); setCalories(std::round(food->getCalories()*foodMass/HUNDRED_GRAM)); setAmountOfPeople(amountOfPeople); ingridients.insert(std::pair<Food*, uint64_t>(food, foodMass)); food->registerDish(this); PRINT_OBJ("Created dish class " << NAME_ID); } Dish::~Dish(void) { PRINT_OBJ("Destroyed dish basic class " << NAME_ID); } Dish& Dish::operator=(const Dish& right) { if ( this == &right ) { return *this; } Dish::Stats::operator=(right); ingridients.clear(); for ( auto& entry: right.getIngridientMap() ) { addFood(entry.first, entry.second); } return *this; } void Dish::addFood(Food* const food, uint64_t foodMass) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; if ( foodMass < minMass || foodMass > maxMass ) { PRINT_ERR("Wrong food " << NAME_ID_CLASS(*food) << " mass value provided [" << foodMass << "]"); throw WrongDishMass(); } if ( ingridients.count(food) ) { PRINT_ERR("Could not add " << NAME_ID_CLASS(*food) << " food that is already in the dish"); throw AlreadySuchFoodInList(); } if ( ingridients.size() >= maxListItemsAmount ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish"); throw TooMuchFoodInMap(); } newMass = getMass() + foodMass; newPrice = getPrice() + std::round(food->getPrice()*foodMass/food->getMass()); newFats = getFats() + std::round(food->getFats()*foodMass/HUNDRED_GRAM); newProteins = getProteins() + std::round(food->getProteins()*foodMass/HUNDRED_GRAM); newCarbohydrates = getCarbohydrates() + std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM); newCalories = getCalories() + std::round(food->getCalories()*foodMass/HUNDRED_GRAM); if ( newMass > maxMass ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result mass is too big [" << newMass << "]"); throw TooBigDishMass(); } if ( newPrice > maxPrice ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result price is too big [" << newPrice << "]"); throw TooBigDishPrice(); } if ( newFats > maxFats ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result fats are too big [" << newFats << "]"); throw TooBigDishFats(); } if ( newProteins > maxProteins ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result proteins are too big [" << newProteins << "]"); throw TooBigDishProteins(); } if ( newCarbohydrates > maxCarbohydrates ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result carbohydrates are too big [" << newCarbohydrates << "]"); throw TooBigDishCarbohydrates(); } if ( newCalories > maxCalories ) { PRINT_ERR("Could not add new food " << NAME_ID_CLASS(*food) << " to the dish. Result calories are too big [" << newCalories << "]"); throw TooBigDishCalories(); } setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); ingridients.insert(std::pair<Food *, uint64_t>(food, foodMass)); food->registerDish(this); PRINT_INFO("Food " << NAME_ID_CLASS(*food) << " was added to dish " << NAME_ID << ""); } void Dish::removeFood(Food* const food) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; uint64_t foodMass = ingridients[food]; if ( !ingridients.count(food) ) { PRINT_ERR("Could not remove food " << NAME_ID_CLASS(*food) << " that is not in the dish"); throw NoSuchFoodInMap(); } if ( ingridients.size() <= minListItemsAmount) { PRINT_ERR("Could not remove last " << NAME_ID_CLASS(*food) << " food in the dish"); throw LastFoodInMap(); } newMass = getMass() - foodMass; newPrice = getPrice() - std::round(food->getPrice()*foodMass/food->getMass()); newFats = getFats() - std::round(food->getFats()*foodMass/HUNDRED_GRAM); newProteins = getProteins() - std::round(food->getProteins()*foodMass/HUNDRED_GRAM); newCarbohydrates = getCarbohydrates() - std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM); newCalories = getCalories() - std::round(food->getCalories()*foodMass/HUNDRED_GRAM); setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); ingridients.erase(food); food->unregisterDish(this); PRINT_INFO("Food " << NAME_ID_CLASS(*food) << " was removed from dish " << NAME_ID << ""); } void Dish::changeFoodAmount(Food* const food, uint64_t foodMass) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; int64_t currentFoodMass = ingridients[food]; if ( foodMass < minMass || foodMass > maxMass ) { PRINT_ERR("Wrong food " << NAME_ID_CLASS(*food) << " mass value provided [" << foodMass << "]"); throw WrongDishMass(); } if ( !ingridients.count(food) ) { PRINT_ERR("Could not change " << NAME_ID_CLASS(*food) << " food that is not in the dish"); throw NoSuchFoodInMap(); } newMass = getMass() + foodMass * amountOfPeople - currentFoodMass * amountOfPeople; newPrice = getPrice() + std::round(food->getPrice()*foodMass/food->getMass()) - std::round(food->getPrice()*currentFoodMass/food->getMass()); newFats = getFats() + std::round(food->getFats()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getFats()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); newProteins = getProteins() + std::round(food->getProteins()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getProteins()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); newCarbohydrates = getCarbohydrates() + std::round(food->getCarbohydrates()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getCarbohydrates()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); newCalories = getCalories() + std::round(food->getCalories()*foodMass/HUNDRED_GRAM*amountOfPeople) - std::round(food->getCalories()*currentFoodMass/HUNDRED_GRAM*amountOfPeople); if ( newMass > maxMass ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result mass is too big [" << newMass << "]"); throw TooBigDishMass(); } if ( newPrice > maxPrice ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result price is too big [" << newPrice << "]"); throw TooBigDishPrice(); } if ( newFats > maxFats ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result fats are too big [" << newFats << "]"); throw TooBigDishFats(); } if ( newProteins > maxProteins ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result proteins are too big [" << newProteins << "]"); throw TooBigDishProteins(); } if ( newCarbohydrates > maxCarbohydrates ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result carbohydrates are too big [" << newCarbohydrates << "]"); throw TooBigDishCarbohydrates(); } if ( newCalories > maxCalories ) { PRINT_ERR("Could not change food " << NAME_ID_CLASS(*food) << ". Result calories are too big [" << newCalories << "]"); throw TooBigDishCalories(); } setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); ingridients[food] = foodMass; PRINT_INFO("Food " << NAME_ID_CLASS(*food) << " was changed in dish " << NAME_ID << ""); } void Dish::changeAmountOfPeople(uint64_t amountOfPeople) { uint64_t newMass, newPrice, newFats, newProteins, newCarbohydrates, newCalories; uint64_t currentAmountOfPeople = getAmountOfPeople(); if ( amountOfPeople < minAmountOfPeople || amountOfPeople > maxAmountOfPeople ) { PRINT_ERR("Wrong dish amount of people provided [" << amountOfPeople << "]"); throw WrongDishAmountOfPeople(); } newMass = std::round(getMass()*amountOfPeople/currentAmountOfPeople); newPrice = std::round(getPrice()*amountOfPeople/currentAmountOfPeople); newFats = std::round(getFats()*amountOfPeople/currentAmountOfPeople); newProteins = std::round(getProteins()*amountOfPeople/currentAmountOfPeople); newCarbohydrates = std::round(getCarbohydrates()*amountOfPeople/currentAmountOfPeople); newCalories = std::round(getCalories()*amountOfPeople/currentAmountOfPeople); if ( newMass > maxMass ) { PRINT_ERR("Could not change amount of people in the dish. Result mass is too big [" << newMass << "]"); throw TooBigDishMass(); } if ( newPrice > maxPrice ) { PRINT_ERR("Could not change amount of people in the dish. Result price is too big [" << newPrice << "]"); throw TooBigDishPrice(); } if ( newFats > maxFats ) { PRINT_ERR("Could not change amount of people in the dish. Result fats are too big [" << newFats << "]"); throw TooBigDishFats(); } if ( newProteins > maxProteins ) { PRINT_ERR("Could not change amount of people in the dish. Result proteins are too big [" << newProteins << "]"); throw TooBigDishProteins(); } if ( newCarbohydrates > maxCarbohydrates ) { PRINT_ERR("Could not change amount of people in the dish. Result carbohydrates are too big [" << newCarbohydrates << "]"); throw TooBigDishCarbohydrates(); } if ( newCalories > maxCalories ) { PRINT_ERR("Could not change amount of people in the dish. Result calories are too big [" << newCalories << "]"); throw TooBigDishCalories(); } setMass(newMass); setPrice(newPrice); setFats(newFats); setProteins(newProteins); setCarbohydrates(newCarbohydrates); setCalories(newCalories); setAmountOfPeople(amountOfPeople); for ( auto& entry: ingridients ) { entry.second = entry.second * amountOfPeople / currentAmountOfPeople; } PRINT_INFO("Dish " << NAME_ID << " now have " << amountOfPeople << " people"); } void Dish::setAmountOfPeople(uint64_t amountOfPeople) { if ( amountOfPeople < minAmountOfPeople || amountOfPeople > maxAmountOfPeople ) { PRINT_ERR("Wrong dish amount of people provided [" << amountOfPeople << "]"); throw WrongPeopleStatsAmountOfPeople(); } this->amountOfPeople = amountOfPeople; PRINT_INFO("Dish class " << NAME_ID << " amount of people set to " << amountOfPeople); } uint64_t Dish::getAmountOfPeople(void) const { return amountOfPeople; } const std::map<Food*, uint64_t, Stats::Compare>& Dish::getIngridientMap(void) const { return ingridients; } std::ostream& operator<<(std::ostream& out, const Dish& dish) { #ifdef DEBUG std::map<Food*, uint64_t, Stats::Compare> dishMap = dish.getIngridientMap(); out << dynamic_cast<const Stats&>(dish) << std::endl; out << " INGRIDIENTS (" << dishMap.size() << "):" << std::endl; out << " >>> >>> >>>" << std::endl; for ( auto& entry: dishMap ) { out << " ingridient " << *entry.first << std::endl; out << " - mass in dish: " << entry.second << " gram" << std::endl; } out << " <<< <<< <<<"; #else out << dish.getName(); #endif return out; } <|endoftext|>
<commit_before>/** * @file src/tools/graphviz/GraphvizExportTool.cpp * @date Jul. 2016 * @author PhRG - opticalp.fr */ /* Copyright (c) 2016 Ph. Renaud-Goud / Opticalp 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 "GraphvizExportTool.h" #include "core/Module.h" #include "core/InPort.h" #include "core/OutPort.h" #include "core/DataProxy.h" #include "core/DataLogger.h" #include "core/DuplicatedSource.h" #include "core/ParameterGetter.h" #include "core/ParameterSetter.h" #include "core/Dispatcher.h" #include "Poco/Util/Application.h" #include "Poco/String.h" #include <fstream> #include <sstream> void GraphvizExportTool::writeDotFile(Poco::Path filePath) { std::ofstream file(filePath.toString().c_str()); if (file.is_open()) exportGraph(file); else throw Poco::FileException("writeDotFile", "not able to open the file " + filePath.toString() + " for writing"); file.close(); } std::string GraphvizExportTool::getDotString(bool withEdges) { std::ostringstream stream; exportGraph(stream); return stream.str(); } void GraphvizExportTool::exportModuleNode(std::ostream& out, SharedPtr<Module*> mod) { ParameterSet pSet; (*mod)->getParameterSet(&pSet); std::vector<InPort*> inP = (*mod)->getInPorts(); std::vector<OutPort*> outP = (*mod)->getOutPorts(); #ifdef OBSOLETE_RECORD out << " " << (*mod)->name() << " [shape=record, label=\"{"; // parameters for (ParameterSet::iterator it = pSet.begin(), ite = pSet.end(); it != ite; ) { out << "<param_" << it->name << "> " << it->name; it++; if (it != ite) out << " | "; } out << "} | { {"; // input ports for (std::vector<InPort*>::iterator it = inP.begin(), ite = inP.end(); it != ite; ) { SharedPtr<InPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getInPort(*it); out << "<" << portNameBase(getPortName(*port)) << "> " << (*port)->name(); it++; if (it != ite) out << " | "; } out << "} | " << (*mod)->name() << " | {"; // output ports for (std::vector<OutPort*>::iterator it = outP.begin(), ite = outP.end(); it != ite; ) { SharedPtr<OutPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getOutPort(*it); out << "<" << portNameBase(getPortName(*port)) << "> " << (*port)->name(); it++; if (it != ite) out << " | "; } out << "} }\"];" << std::endl; #else size_t rows = pSet.size(); bool paramSpan = false; if (rows < 3) { if (pSet.size()==2) rows = 4; else rows = 3; paramSpan = true; } size_t cols; bool colSpan = false; if (inP.empty() && outP.empty()) cols = 2; else if (inP.empty()) cols = 1 + outP.size(); else if (outP.empty()) cols = 1+ inP.size(); else if (inP.size() == outP.size()) cols = 1 + inP.size(); else { cols = 1 + inP.size() * outP.size(); colSpan = true; } out << " " << (*mod)->name() << " [shape=plaintext, label=<" << std::endl; out << " <TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">" << std::endl; for (size_t row=0; row<rows; row++) { out << " <TR>" << std::endl; for (size_t col=0; col<cols; col++) { if (col == 0) // parameter { if (!paramSpan) // row == param index { out << " <TD PORT=\"param_" << pSet.at(row).name << "\">"; out << pSet.at(row).name << "</TD>" << std::endl; } else { switch(pSet.size()) { case 2: if (row%2==0) { out << " <TD ROWSPAN=\"2\" PORT=\"param_" << pSet.at(row/2).name << "\">"; out << pSet.at(row/2).name << "</TD>" << std::endl; } break; case 1: if (row==0) { out << " <TD ROWSPAN=\"3\" PORT=\"param_" << pSet.at(row).name << "\">"; out << pSet.at(row).name << "</TD>" << std::endl; } break; case 0: if (row==0) { out << " <TD ROWSPAN=\"3\"> </TD>" << std::endl; } break; default: poco_bugcheck_msg("wrong parameterSet size"); } } } else if (row == 0) // input port { if (inP.empty()) { if (col==1) { out << " <TD COLSPAN=\"" << cols-1 << "\"> </TD>" << std::endl; } } else if (!colSpan) { SharedPtr<InPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getInPort(inP.at(col-1)); out << " <TD PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl; } else if ((col-1)%outP.size() == 0) { SharedPtr<InPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getInPort(inP.at((col-1)/outP.size())); out << " <TD COLSPAN=\"" << outP.size() << "\" "; out << "PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl;; } } else if ((row == 1) && (col == 1)) // module name { out << " <TD ROWSPAN=\"" << rows-2 << "\" "; out << "COLSPAN=\"" << cols-1 << "\" "; out << "PORT=\"" << (*mod)->name() << "\"> "; out << "<FONT POINT-SIZE=\"20\"><B>"; out << (*mod)->name() << "</B></FONT>"; out << "<I> (" << (*mod)->internalName() << ") </I><BR/>"; out << Poco::replace((*mod)->description(),"\n","<BR/>") ; out << " </TD> " << std::endl; } else if (row == rows-1) { if (outP.empty()) { if (col==1) { out << " <TD COLSPAN=\"" << cols-1 << "\"> </TD>" << std::endl; } } else if (!colSpan) { SharedPtr<OutPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getOutPort(outP.at(col-1)); out << " <TD PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl; } else if ((col-1)%inP.size() == 0) { SharedPtr<OutPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getOutPort(outP.at((col-1)/inP.size())); out << " <TD COLSPAN=\"" << inP.size() << "\" "; out << "PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl;; } } } out << " </TR>" << std::endl; } out << " </TABLE>\n >];" << std::endl; #endif } void GraphvizExportTool::exportDataProxyNode(std::ostream& out, DataProxy* proxy) { out << " " << proxy->name() << " [shape=box, label=\""; out << "data proxy: \n" << proxy->name() << "\"];" << std::endl; } void GraphvizExportTool::exportDataLoggerNode(std::ostream& out, DataLogger* logger) { out << " " << logger->name() << " [shape=box, label=\""; out << "data logger: \n" << logger->name() << "\"];" << std::endl; } void GraphvizExportTool::exportDuplicatedSourceNode(std::ostream& out, DuplicatedSource* source) { out << " " << source->name() << " [shape=box, label=\"" << source->name() << "\"];" << std::endl; } std::string GraphvizExportTool::getPortName(DataSource* source) { // source is: module out port OutPort* outPort = dynamic_cast<OutPort*>(source); if (outPort) return outPort->parent()->name() + ":outPort_" + outPort->name() + ":s"; // source is: parameter getter ParameterGetter* paramGet = dynamic_cast<ParameterGetter*>(source); if (paramGet) return paramGet->getParent()->name() + ":param_" + paramGet->getParameterName() + ":w"; // source is: duplicated source DuplicatedSource* dupSrc = dynamic_cast<DuplicatedSource*>(source); if (dupSrc) return dupSrc->name() + ":s"; // source is: data proxy DataProxy* proxy = dynamic_cast<DataProxy*>(source); if (proxy) return proxy->name() + ":s"; throw Poco::NotImplementedException("GraphvizExport->getPortName", "The given data source is not recognized: " + source->name()); } std::string GraphvizExportTool::getPortName(DataTarget* target) { // target is: module in port InPort* inPort = dynamic_cast<InPort*>(target); if (inPort) return inPort->parent()->name() + ":inPort_" + inPort->name() + ":n"; // target is: parameter getter ParameterGetter* paramGet = dynamic_cast<ParameterGetter*>(target); if (paramGet) return paramGet->getParent()->name() + ":param_" + paramGet->getParameterName() + ":w"; // target is: parameter setter ParameterSetter* paramSet = dynamic_cast<ParameterSetter*>(target); if (paramSet) return paramSet->getParent()->name() + ":param_" + paramSet->getParameterName() + ":w"; // target is: data proxy DataProxy* proxy = dynamic_cast<DataProxy*>(target); if (proxy) return proxy->name() + ":n"; // target is: data logger DataLogger* logger = dynamic_cast<DataLogger*>(target); if (logger) return logger->name() + ":n"; throw Poco::NotImplementedException("GraphvizExport->getPortName", "The given data target is not recognized: " + target->name()); } #include "Poco/StringTokenizer.h" std::string GraphvizExportTool::portNameBase(std::string complete) { Poco::StringTokenizer tok(complete, ":"); if (tok.count() == 3) return tok[1]; else poco_bugcheck_msg(("bad port name: " + complete + ", can not be split").c_str() ); throw Poco::BugcheckException(); } <commit_msg>Fix bug induced by debian amd64 poco 1.3.6p1<commit_after>/** * @file src/tools/graphviz/GraphvizExportTool.cpp * @date Jul. 2016 * @author PhRG - opticalp.fr */ /* Copyright (c) 2016 Ph. Renaud-Goud / Opticalp 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 "GraphvizExportTool.h" #include "core/Module.h" #include "core/InPort.h" #include "core/OutPort.h" #include "core/DataProxy.h" #include "core/DataLogger.h" #include "core/DuplicatedSource.h" #include "core/ParameterGetter.h" #include "core/ParameterSetter.h" #include "core/Dispatcher.h" #include "Poco/Util/Application.h" #include "Poco/String.h" #include <fstream> #include <sstream> void GraphvizExportTool::writeDotFile(Poco::Path filePath) { std::ofstream file(filePath.toString().c_str()); if (file.is_open()) exportGraph(file); else throw Poco::FileException("writeDotFile", "not able to open the file " + filePath.toString() + " for writing"); file.close(); } std::string GraphvizExportTool::getDotString(bool withEdges) { std::ostringstream stream; exportGraph(stream); return stream.str(); } void GraphvizExportTool::exportModuleNode(std::ostream& out, SharedPtr<Module*> mod) { ParameterSet pSet; (*mod)->getParameterSet(&pSet); std::vector<InPort*> inP = (*mod)->getInPorts(); std::vector<OutPort*> outP = (*mod)->getOutPorts(); #ifdef OBSOLETE_RECORD out << " " << (*mod)->name() << " [shape=record, label=\"{"; // parameters for (ParameterSet::iterator it = pSet.begin(), ite = pSet.end(); it != ite; ) { out << "<param_" << it->name << "> " << it->name; it++; if (it != ite) out << " | "; } out << "} | { {"; // input ports for (std::vector<InPort*>::iterator it = inP.begin(), ite = inP.end(); it != ite; ) { SharedPtr<InPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getInPort(*it); out << "<" << portNameBase(getPortName(*port)) << "> " << (*port)->name(); it++; if (it != ite) out << " | "; } out << "} | " << (*mod)->name() << " | {"; // output ports for (std::vector<OutPort*>::iterator it = outP.begin(), ite = outP.end(); it != ite; ) { SharedPtr<OutPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getOutPort(*it); out << "<" << portNameBase(getPortName(*port)) << "> " << (*port)->name(); it++; if (it != ite) out << " | "; } out << "} }\"];" << std::endl; #else size_t rows = pSet.size(); bool paramSpan = false; if (rows < 3) { if (pSet.size()==2) rows = 4; else rows = 3; paramSpan = true; } size_t cols; bool colSpan = false; if (inP.empty() && outP.empty()) cols = 2; else if (inP.empty()) cols = 1 + outP.size(); else if (outP.empty()) cols = 1+ inP.size(); else if (inP.size() == outP.size()) cols = 1 + inP.size(); else { cols = 1 + inP.size() * outP.size(); colSpan = true; } out << " " << (*mod)->name() << " [shape=plaintext, label=<" << std::endl; out << " <TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">" << std::endl; for (size_t row=0; row<rows; row++) { out << " <TR>" << std::endl; for (size_t col=0; col<cols; col++) { if (col == 0) // parameter { if (!paramSpan) // row == param index { out << " <TD PORT=\"param_" << pSet.at(row).name << "\">"; out << pSet.at(row).name << "</TD>" << std::endl; } else { switch(pSet.size()) { case 2: if (row%2==0) { out << " <TD ROWSPAN=\"2\" PORT=\"param_" << pSet.at(row/2).name << "\">"; out << pSet.at(row/2).name << "</TD>" << std::endl; } break; case 1: if (row==0) { out << " <TD ROWSPAN=\"3\" PORT=\"param_" << pSet.at(row).name << "\">"; out << pSet.at(row).name << "</TD>" << std::endl; } break; case 0: if (row==0) { out << " <TD ROWSPAN=\"3\"> </TD>" << std::endl; } break; default: poco_bugcheck_msg("wrong parameterSet size"); } } } else if (row == 0) // input port { if (inP.empty()) { if (col==1) { out << " <TD COLSPAN=\"" << cols-1 << "\"> </TD>" << std::endl; } } else if (!colSpan) { SharedPtr<InPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getInPort(inP.at(col-1)); out << " <TD PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl; } else if ((col-1)%outP.size() == 0) { SharedPtr<InPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getInPort(inP.at((col-1)/outP.size())); out << " <TD COLSPAN=\"" << outP.size() << "\" "; out << "PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl;; } } else if ((row == 1) && (col == 1)) // module name { out << " <TD ROWSPAN=\"" << rows-2 << "\" "; out << "COLSPAN=\"" << cols-1 << "\" "; out << "PORT=\"" << (*mod)->name() << "\"> "; out << "<FONT POINT-SIZE=\"20\"><B>"; out << (*mod)->name() << "</B></FONT>"; out << "<I> (" << (*mod)->internalName() << ") </I><BR/>"; #if POCO_VERSION > 0x01030600 out << Poco::replace((*mod)->description(),"\n","<BR/>") ; #else // Poco::replace has a bug in amd64 debian build for rev <= 1.3.6p1 out << (*mod)->description() ; #endif out << " </TD> " << std::endl; } else if (row == rows-1) { if (outP.empty()) { if (col==1) { out << " <TD COLSPAN=\"" << cols-1 << "\"> </TD>" << std::endl; } } else if (!colSpan) { SharedPtr<OutPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getOutPort(outP.at(col-1)); out << " <TD PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl; } else if ((col-1)%inP.size() == 0) { SharedPtr<OutPort*> port = Poco::Util::Application::instance() .getSubsystem<Dispatcher>() .getOutPort(outP.at((col-1)/inP.size())); out << " <TD COLSPAN=\"" << inP.size() << "\" "; out << "PORT=\"" << portNameBase(getPortName(*port)) << "\">"; out << (*port)->name() << "</TD>" << std::endl;; } } } out << " </TR>" << std::endl; } out << " </TABLE>\n >];" << std::endl; #endif } void GraphvizExportTool::exportDataProxyNode(std::ostream& out, DataProxy* proxy) { out << " " << proxy->name() << " [shape=box, label=\""; out << "data proxy: \n" << proxy->name() << "\"];" << std::endl; } void GraphvizExportTool::exportDataLoggerNode(std::ostream& out, DataLogger* logger) { out << " " << logger->name() << " [shape=box, label=\""; out << "data logger: \n" << logger->name() << "\"];" << std::endl; } void GraphvizExportTool::exportDuplicatedSourceNode(std::ostream& out, DuplicatedSource* source) { out << " " << source->name() << " [shape=box, label=\"" << source->name() << "\"];" << std::endl; } std::string GraphvizExportTool::getPortName(DataSource* source) { // source is: module out port OutPort* outPort = dynamic_cast<OutPort*>(source); if (outPort) return outPort->parent()->name() + ":outPort_" + outPort->name() + ":s"; // source is: parameter getter ParameterGetter* paramGet = dynamic_cast<ParameterGetter*>(source); if (paramGet) return paramGet->getParent()->name() + ":param_" + paramGet->getParameterName() + ":w"; // source is: duplicated source DuplicatedSource* dupSrc = dynamic_cast<DuplicatedSource*>(source); if (dupSrc) return dupSrc->name() + ":s"; // source is: data proxy DataProxy* proxy = dynamic_cast<DataProxy*>(source); if (proxy) return proxy->name() + ":s"; throw Poco::NotImplementedException("GraphvizExport->getPortName", "The given data source is not recognized: " + source->name()); } std::string GraphvizExportTool::getPortName(DataTarget* target) { // target is: module in port InPort* inPort = dynamic_cast<InPort*>(target); if (inPort) return inPort->parent()->name() + ":inPort_" + inPort->name() + ":n"; // target is: parameter getter ParameterGetter* paramGet = dynamic_cast<ParameterGetter*>(target); if (paramGet) return paramGet->getParent()->name() + ":param_" + paramGet->getParameterName() + ":w"; // target is: parameter setter ParameterSetter* paramSet = dynamic_cast<ParameterSetter*>(target); if (paramSet) return paramSet->getParent()->name() + ":param_" + paramSet->getParameterName() + ":w"; // target is: data proxy DataProxy* proxy = dynamic_cast<DataProxy*>(target); if (proxy) return proxy->name() + ":n"; // target is: data logger DataLogger* logger = dynamic_cast<DataLogger*>(target); if (logger) return logger->name() + ":n"; throw Poco::NotImplementedException("GraphvizExport->getPortName", "The given data target is not recognized: " + target->name()); } #include "Poco/StringTokenizer.h" std::string GraphvizExportTool::portNameBase(std::string complete) { Poco::StringTokenizer tok(complete, ":"); if (tok.count() == 3) return tok[1]; else poco_bugcheck_msg(("bad port name: " + complete + ", can not be split").c_str() ); throw Poco::BugcheckException(); } <|endoftext|>
<commit_before> // Copyright 2020 Google LLC // // 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 <gflags/gflags.h> #include <glog/logging.h> #include <syscall.h> #include <fstream> #include <iostream> #include "gdal_sapi.sapi.h" // NOLINT(build/include) #include "sandboxed_api/sandbox2/util/fileops.h" class GdalSapiSandbox : public GDALSandbox { public: GdalSapiSandbox(std::string path) : GDALSandbox(), file_path_(std::move(path)) {} std::unique_ptr<sandbox2::Policy> ModifyPolicy( sandbox2::PolicyBuilder*) override { return sandbox2::PolicyBuilder() .AllowDynamicStartup() .AllowRead() .AllowSystemMalloc() .AllowWrite() .AllowExit() .AllowStat() .AllowOpen() .AllowSyscalls({ __NR_futex, __NR_close, __NR_recvmsg, __NR_getdents64, __NR_lseek, __NR_getpid, __NR_sysinfo, __NR_prlimit64, __NR_ftruncate, __NR_unlink, }) .AddFile(file_path_) .BuildOrDie(); } private: std::string file_path_; }; absl::Status GdalMain(std::string filename) { // Reading GDALDataset from a (local, specific) file. GdalSapiSandbox sandbox(filename); SAPI_RETURN_IF_ERROR(sandbox.Init()); GDALApi api(&sandbox); sapi::v::CStr s(filename.data()); SAPI_RETURN_IF_ERROR(api.GDALAllRegister()); auto open = api.GDALOpen(s.PtrBoth(), GDALAccess::GA_ReadOnly); LOG(INFO) << "Dataset pointer adress: " << open.value() << std::endl; sapi::v::RemotePtr ptr_dataset(open.value()); LOG(INFO) << ptr_dataset.ToString() << std::endl; if (!open.value()) { return absl::AbortedError("NULL pointer for Dataset.\n"); } // Printing some general information about the dataset. auto driver = api.GDALGetDatasetDriver(&ptr_dataset); sapi::v::RemotePtr ptr_driver(driver.value()); auto driver_short_name = api.GDALGetDriverShortName(&ptr_driver); auto driver_long_name = api.GDALGetDriverLongName(&ptr_driver); sapi::v::RemotePtr ptr_driver_short_name(driver_short_name.value()); sapi::v::RemotePtr ptr_driver_long_name(driver_long_name.value()); LOG(INFO) << "Driver short name: " << sandbox.GetCString(ptr_driver_short_name).value().c_str(); LOG(INFO) << "Driver long name: " << sandbox.GetCString(ptr_driver_long_name).value().c_str(); // Checking that GetGeoTransform is valid. std::vector<double> adf_geo_transform(6); sapi::v::Array<double> adfGeoTransformArray(&adf_geo_transform[0], adf_geo_transform.size()); api.GDALGetGeoTransform(&ptr_dataset, adfGeoTransformArray.PtrBoth()) .IgnoreError(); LOG(INFO) << "Origin = (" << adf_geo_transform[0] << ", " << adf_geo_transform[3] << ")" << std::endl; LOG(INFO) << "Pixel Size = (" << adf_geo_transform[0] << ", " << adf_geo_transform[3] << ")" << std::endl; std::vector<int> n_blockX_size(1); std::vector<int> n_blockY_size(1); sapi::v::Array<int> nBlockXSizeArray(&n_blockX_size[0], n_blockX_size.size()); sapi::v::Array<int> nBlockYSizeArray(&n_blockY_size[0], n_blockY_size.size()); auto band = api.GDALGetRasterBand(&ptr_dataset, 1); LOG(INFO) << "Band pointer adress: " << band.value() << std::endl; if (!band.value()) { return absl::AbortedError("NULL pointer for Band.\n"); } sapi::v::RemotePtr ptr_band(band.value()); SAPI_RETURN_IF_ERROR(api.GDALGetBlockSize( &ptr_band, nBlockXSizeArray.PtrBoth(), nBlockYSizeArray.PtrBoth())); LOG(INFO) << "Block = " << n_blockX_size[0] << " x " << n_blockY_size[0] << std::endl; std::vector<int> b_got_min(1); std::vector<int> b_got_max(1); sapi::v::Array<int> b_got_min_array(&b_got_min[0], b_got_min.size()); sapi::v::Array<int> b_got_max_array(&b_got_max[0], b_got_max.size()); auto nX_size = api.GDALGetRasterBandXSize(&ptr_band); auto nY_size = api.GDALGetRasterBandYSize(&ptr_band); std::vector<int8_t> raster_data(nX_size.value() * nY_size.value(), -1); sapi::v::Array<int8_t> raster_data_array(&raster_data[0], raster_data.size()); api.GDALRasterIO(&ptr_band, GF_Read, 0, 0, nX_size.value(), nY_size.value(), raster_data_array.PtrBoth(), nX_size.value(), nY_size.value(), GDT_Byte, 0, 0) .IgnoreError(); std::cout << "Raster data info: " << raster_data_array.ToString() << std::endl; // To print the data content: `std::cout << raster_data_array.GetData() << // std::endl;` return absl::OkStatus(); } int main(int argc, char** argv) { // The file to be converted should be specified in the first argument while // running the program. if (argc < 2) { std::cout << "You need to provide a file name: ./raster " "your_tiff_file_absolute_path\n" "Example: ./raster /usr/home/username/file.tiff" << std::endl; return EXIT_FAILURE; } std::ifstream aux_file; aux_file.open(argv[1]); if (!aux_file.is_open()) { std::cout << "Your file name is not valid.\nUnable to open the file." << std::endl; return EXIT_FAILURE; } std::string filename(argv[1]); if (absl::Status status = GdalMain(filename); !status.ok()) { LOG(ERROR) << "Initialization failed: " << status.ToString(); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Resolving returning error for Transform and RasterIO functions<commit_after> // Copyright 2020 Google LLC // // 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 <gflags/gflags.h> #include <glog/logging.h> #include <syscall.h> #include <fstream> #include <iostream> #include "gdal_sapi.sapi.h" // NOLINT(build/include) #include "sandboxed_api/sandbox2/util/fileops.h" class GdalSapiSandbox : public GDALSandbox { public: GdalSapiSandbox(std::string path) : GDALSandbox(), file_path_(std::move(path)) {} std::unique_ptr<sandbox2::Policy> ModifyPolicy( sandbox2::PolicyBuilder*) override { return sandbox2::PolicyBuilder() .AllowDynamicStartup() .AllowRead() .AllowSystemMalloc() .AllowWrite() .AllowExit() .AllowStat() .AllowOpen() .AllowSyscalls({ __NR_futex, __NR_close, __NR_recvmsg, __NR_getdents64, __NR_lseek, __NR_getpid, __NR_sysinfo, __NR_prlimit64, __NR_ftruncate, __NR_unlink, }) .AddFile(file_path_) .BuildOrDie(); } private: std::string file_path_; }; absl::Status GdalMain(std::string filename) { // Reading GDALDataset from a (local, specific) file. GdalSapiSandbox sandbox(filename); SAPI_RETURN_IF_ERROR(sandbox.Init()); GDALApi api(&sandbox); sapi::v::CStr s(filename.data()); SAPI_RETURN_IF_ERROR(api.GDALAllRegister()); auto open = api.GDALOpen(s.PtrBoth(), GDALAccess::GA_ReadOnly); LOG(INFO) << "Dataset pointer adress: " << open.value() << std::endl; sapi::v::RemotePtr ptr_dataset(open.value()); LOG(INFO) << ptr_dataset.ToString() << std::endl; if (!open.value()) { return absl::AbortedError("NULL pointer for Dataset.\n"); } // Printing some general information about the dataset. auto driver = api.GDALGetDatasetDriver(&ptr_dataset); sapi::v::RemotePtr ptr_driver(driver.value()); auto driver_short_name = api.GDALGetDriverShortName(&ptr_driver); auto driver_long_name = api.GDALGetDriverLongName(&ptr_driver); sapi::v::RemotePtr ptr_driver_short_name(driver_short_name.value()); sapi::v::RemotePtr ptr_driver_long_name(driver_long_name.value()); LOG(INFO) << "Driver short name: " << sandbox.GetCString(ptr_driver_short_name).value().c_str(); LOG(INFO) << "Driver long name: " << sandbox.GetCString(ptr_driver_long_name).value().c_str(); // Checking that GetGeoTransform is valid. std::vector<double> adf_geo_transform(6); sapi::v::Array<double> adfGeoTransformArray(&adf_geo_transform[0], adf_geo_transform.size()); // For this function that returns CPLErr, the error-handling must be done // analyzing the returning object. // Same for GDALReturnsIO from below. CPLErr err; SAPI_ASSIGN_OR_RETURN(err, api.GDALGetGeoTransform(&ptr_dataset, adfGeoTransformArray.PtrBoth())); // If GDALGetGeoTransform generates an error. if (err != CE_None) { return absl::CancelledError(); } LOG(INFO) << "Origin = (" << adf_geo_transform[0] << ", " << adf_geo_transform[3] << ")" << std::endl; LOG(INFO) << "Pixel Size = (" << adf_geo_transform[0] << ", " << adf_geo_transform[3] << ")" << std::endl; std::vector<int> n_blockX_size(1); std::vector<int> n_blockY_size(1); sapi::v::Array<int> nBlockXSizeArray(&n_blockX_size[0], n_blockX_size.size()); sapi::v::Array<int> nBlockYSizeArray(&n_blockY_size[0], n_blockY_size.size()); auto band = api.GDALGetRasterBand(&ptr_dataset, 1); LOG(INFO) << "Band pointer adress: " << band.value() << std::endl; if (!band.value()) { return absl::AbortedError("NULL pointer for Band.\n"); } sapi::v::RemotePtr ptr_band(band.value()); SAPI_RETURN_IF_ERROR(api.GDALGetBlockSize( &ptr_band, nBlockXSizeArray.PtrBoth(), nBlockYSizeArray.PtrBoth())); LOG(INFO) << "Block = " << n_blockX_size[0] << " x " << n_blockY_size[0] << std::endl; std::vector<int> b_got_min(1); std::vector<int> b_got_max(1); sapi::v::Array<int> b_got_min_array(&b_got_min[0], b_got_min.size()); sapi::v::Array<int> b_got_max_array(&b_got_max[0], b_got_max.size()); auto nX_size = api.GDALGetRasterBandXSize(&ptr_band); auto nY_size = api.GDALGetRasterBandYSize(&ptr_band); std::vector<int8_t> raster_data(nX_size.value() * nY_size.value(), -1); sapi::v::Array<int8_t> raster_data_array(&raster_data[0], raster_data.size()); // We will use CPLErr type of returning value, as before with GDALGetGeoTransorm. SAPI_ASSIGN_OR_RETURN(err, api.GDALRasterIO(&ptr_band, GF_Read, 0, 0, nX_size.value(), nY_size.value(), raster_data_array.PtrBoth(), nX_size.value(), nY_size.value(), GDT_Byte, 0, 0)); // If GDALRasterIO generates an error. if (err != CE_None) { return absl::CancelledError(); } std::cout << "Raster data info: " << raster_data_array.ToString() << std::endl; // To print the data content: `std::cout << raster_data_array.GetData() << // std::endl;` return absl::OkStatus(); } int main(int argc, char** argv) { // The file to be converted should be specified in the first argument while // running the program. if (argc < 2) { std::cout << "You need to provide a file name: ./raster " "your_tiff_file_absolute_path\n" "Example: ./raster /usr/home/username/file.tiff" << std::endl; return EXIT_FAILURE; } std::ifstream aux_file; aux_file.open(argv[1]); if (!aux_file.is_open()) { std::cout << "Your file name is not valid.\nUnable to open the file." << std::endl; return EXIT_FAILURE; } std::string filename(argv[1]); if (absl::Status status = GdalMain(filename); !status.ok()) { LOG(ERROR) << "Initialization failed: " << status.ToString(); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <PageFrameAllocator.hh> #include <Parameters.hh> #include <Memory.hh> #include <Multiboot.hh> #include <Debug.hh> #include <Templates.hh> #include <Modules.hh> #include <Memory.hh> #include <Hal.hh> #include <X86/ThreadContext.hh> #include <cstring> #undef DEBUG #ifdef DEBUG # define D(x) x #else # define D(x) #endif namespace { uintptr_t heapEnd = HeapStart; uintptr_t stackEnd = StackStart; uintptr_t mapEnd = MapStart; MemorySegment memoryMap[MemoryMapMax]; unsigned int memoryMapCount = 0; PageCluster usedPages; PageCluster freePages; spinlock_softirq_t pagesLock; spinlock_softirq_t memoryMapLock; }; void Memory::addMemoryMapEntry(uintptr_t start, size_t length) { KASSERT(memoryMapCount < MemoryMapMax); memoryMap[memoryMapCount].address = start; memoryMap[memoryMapCount].size = length; memoryMapCount++; } void Memory::init() { printf("Listing Kernel sections:\n"); printf(".text: %p-%p\n", &__start_text, &__end_text); printf(".data: %p-%p\n", &__start_data, &__end_data); printf(".rodata: %p-%p\n", &__start_rodata, &__end_rodata); printf(".bss: %p-%p\n", &__start_bss, &__end_bss); printf("Page size: %u, PhysicalPage structure size: %zu\n", PageSize, sizeof(PhysicalPage)); spinlock_softirq_init(&pagesLock); spinlock_softirq_init(&memoryMapLock); usedPages.init(); freePages.init(); uintptr_t firstUsableMemory = max((uintptr_t )&__end_kernel, __end_modules); uintptr_t firstFreePage = roundTo<uintptr_t>(firstUsableMemory, PageSize) + PageSize * PageFrameCount; // init page clusters PhysicalPage* bootstrapPage = (PhysicalPage* )firstFreePage; bootstrapPage->init((uintptr_t )bootstrapPage - KernelVirtualBase); printf("Inserting bootstrap page to used pages cluster: %p\n", (void* )bootstrapPage->getAddress()); usedPages.insert(bootstrapPage); unsigned int freeStructures = PageSize / sizeof (PhysicalPage) - 1; KASSERT(freeStructures > 0); printf("Free structures: %u\n", freeStructures); PhysicalPage* p = bootstrapPage + 1; for (unsigned int i = 0; i < memoryMapCount; i++) { printf("Adding memory range %p-%p (%zu)\n", (void* )memoryMap[i].address, (void* )(memoryMap[i].address + memoryMap[i].size), memoryMap[i].size); for (uintptr_t addr = memoryMap[i].address; addr < memoryMap[i].address + memoryMap[i].size; addr += PageSize) { if (freeStructures == 0) { D(printf("Allocating new page structure\n")); //p = (PhysicalPage* )sbrk(PageSize) uintptr_t ppage = getPage(); KASSERT(ppage != 0); p = (PhysicalPage* )mapAnonymousPage(ppage); // XXX make a function for this KASSERT(p != 0); freeStructures = PageSize / sizeof (PhysicalPage); } p->init(addr); if ((addr >= KernelLoadAddress) && (addr < firstFreePage - KernelVirtualBase)) { D(printf("Found used page: %p\n", (void* )addr)); usedPages.insert(p); } else { D(printf("Inserting free page: %p\n", (void* )addr)); freePages.insert(p); } p++; freeStructures--; } } uintptr_t start = stackEnd; printf("Creating initial kernel stack: %p-%p (%u)\n", (void* )start, (void* )(start - StackSize), StackSize); for (uintptr_t stackAddress = (start - StackSize); stackAddress < start; stackAddress += PageSize) { uintptr_t stackPage = getPage(); KASSERT(stackPage != 0); bool success = mapPage(stackAddress, stackPage); KASSERT(success); } // add one unmapped page as guard stackEnd = start - StackSize - PageSize; // KASSERT(success); // printf("Freeing initial kernel stack: %p-%p\n", (void* )(initial_stack - InitialStackSize), (void* )initial_stack); // for (uintptr_t oldStack = initial_stack - InitialStackSize; // oldStack < initial_stack; // oldStack += PageSize) // { // unmap(oldStack); // } } // XXX curently this overlaps anon mappings, se we can only give one anon // mapped page as the kernel stack area #if 0 bool Memory::createKernelStack(uintptr_t& start) { start = stackEnd; printf("Creating new kernel stack: %p-%p (%u)\n", (void* )start, (void* )(start - StackSize), StackSize); for (uintptr_t stackAddress = (start - StackSize); stackAddress < start; stackAddress += PageSize) { uintptr_t stackPage = getPage(); KASSERT(stackPage != 0); bool success = mapPage(stackAddress, stackPage); KASSERT(success); } // add one unmapped page as guard stackEnd = start - StackSize - PageSize; return true; } #else bool Memory::createKernelStack(uintptr_t& top) { uintptr_t stackPage = getPage(); KASSERT(stackPage != 0); uintptr_t bottom = mapAnonymousPage(stackPage); KASSERT(bottom != 0); top = bottom + PageSize; printf("Creating new kernel stack: %p-%p (%u)\n", (void* )top, (void* )(bottom), PageSize); // uintptr_t newStack = Hal::initKernelStack(top, &Kernel::Thread::main, ); // top = newStack; return true; } #endif // anonymous mapping of a physical page // uintptr_t Memory::mapAnonymousPage(uintptr_t phys, int flags) { spinlock_softirq_enter(&memoryMapLock); mapEnd -= PageSize; uintptr_t virt = mapEnd; spinlock_softirq_exit(&memoryMapLock); if (virt <= (uintptr_t)&__end_kernel) // if (virt <= heapEnd) { printf("%p <= %p\n", (void*)virt, (void*)heapEnd); Debug::panic("Memory::mapPage: Kernel map namespace exhausted."); } // Debug::info("Mapping anonymous page: %p to %p\n", phys, mapEnd); bool success = mapPage(virt, phys, flags); if (!success) { return 0; } return virt; } // anonymous memory mapping // uintptr_t Memory::mapAnonymousRegion(size_t size, int flags) { size_t rsize = roundTo<uintptr_t>(size, PageSize); spinlock_softirq_enter(&memoryMapLock); mapEnd -= rsize; uintptr_t vaddr = mapEnd; spinlock_softirq_exit(&memoryMapLock); if (vaddr <= (uintptr_t)&__end_kernel) // if (vaddr <= heapEnd) { printf("%p <= %p\n", (void*)vaddr, (void*)heapEnd); Debug::panic("Memory::mapAnonymousRegion: Kernel map name space exhausted."); } for (size_t page = 0; page < rsize; page += PageSize) { uintptr_t emptyPage = getPage(); KASSERT(emptyPage != 0); bool success = mapPage(vaddr + page, emptyPage, flags); if (!success) { Debug::panic("mapRegion unsuccesful."); // XXX unmap and return error //return 0; } } return vaddr; } // anonymous mapping of a memory region // uintptr_t Memory::mapRegion(uintptr_t paddr, size_t size, int flags) { uintptr_t firstPage = roundDown(paddr, PageSize); uintptr_t lastPage = roundTo(paddr + size, PageSize); size_t rsize = lastPage - firstPage; D(printf("Memory::mapRegion: %p-%p\n", (void*)paddr, (void*)(paddr + size))); D(printf("Memory::mapRegion: mapping: %p-%p (%zu)\n", (void*)firstPage, (void*)lastPage, rsize)); spinlock_softirq_enter(&memoryMapLock); mapEnd -= rsize; uintptr_t vaddr = mapEnd; spinlock_softirq_exit(&memoryMapLock); uintptr_t offset = paddr - firstPage; if (vaddr <= (uintptr_t)&__end_kernel) // if (vaddr <= heapEnd) { printf("%p <= %p\n", (void*)vaddr, (void*)heapEnd); Debug::panic("Memory::mapRegion: Kernel map namespace exhausted."); } for (uintptr_t page = firstPage; page != lastPage; page += PageSize, vaddr += PageSize) { bool success = mapPage(vaddr, page, flags); if (!success) { Debug::panic("mapRegion unsuccesful."); // XXX unmap and return error //return 0; } } return mapEnd + offset; } bool Memory::unmapRegion(uintptr_t paddr, std::size_t size) { uintptr_t firstPage = roundDown(paddr, PageSize); uintptr_t lastPage = roundTo(paddr + size, PageSize); for (uintptr_t page = firstPage; page != lastPage; page += PageSize) { bool success = unmapPage(page); if (!success) { Debug::panic("unmapRegion unsuccesful."); } } return true; } // get a free physical page // uintptr_t Memory::getPage() { D(printf("Memory::getPage\n")); uintptr_t address = 0; spinlock_softirq_enter(&pagesLock); PhysicalPage* page = freePages.get(); if (page != 0) { usedPages.insert(page); address = page->getAddress(); } spinlock_softirq_exit(&pagesLock); D(printf("Memory::getPage done: %p\n", (void*)address)); return address; } // free a physical page // void Memory::putPage(uintptr_t address) { D(printf("Memory::putPage: %p\n", (void*)address)); spinlock_softirq_enter(&pagesLock); PhysicalPage* page = usedPages.find(address); if (page == 0) { spinlock_softirq_exit(&pagesLock); Debug::panic("Trying to free an unallocated physical page: %p\n", (void* )address); } usedPages.remove(page); freePages.insert(page); spinlock_softirq_exit(&pagesLock); } void* Memory::readPhysicalMemory(void* destination, const void* source, std::size_t size) { uintptr_t mapFirst = roundDown(uintptr_t(source), PageSize); uintptr_t mapLast = roundTo(uintptr_t(source) + size, PageSize); uintptr_t mapped = mapRegion(mapFirst, mapLast - mapFirst); std::memcpy(destination, reinterpret_cast<void*>(mapped + (uintptr_t(source) - mapFirst)), size); unmapRegion(mapped, mapLast - mapFirst); return destination; } <commit_msg>Make sure we never get zero size requests<commit_after>#include <PageFrameAllocator.hh> #include <Parameters.hh> #include <Memory.hh> #include <Multiboot.hh> #include <Debug.hh> #include <Templates.hh> #include <Modules.hh> #include <Memory.hh> #include <Hal.hh> #include <X86/ThreadContext.hh> #include <cstring> #undef DEBUG #ifdef DEBUG # define D(x) x #else # define D(x) #endif namespace { uintptr_t heapEnd = HeapStart; uintptr_t stackEnd = StackStart; uintptr_t mapEnd = MapStart; MemorySegment memoryMap[MemoryMapMax]; unsigned int memoryMapCount = 0; PageCluster usedPages; PageCluster freePages; spinlock_softirq_t pagesLock; spinlock_softirq_t memoryMapLock; }; void Memory::addMemoryMapEntry(uintptr_t start, size_t length) { KASSERT(memoryMapCount < MemoryMapMax); memoryMap[memoryMapCount].address = start; memoryMap[memoryMapCount].size = length; memoryMapCount++; } void Memory::init() { printf("Listing Kernel sections:\n"); printf(".text: %p-%p\n", &__start_text, &__end_text); printf(".data: %p-%p\n", &__start_data, &__end_data); printf(".rodata: %p-%p\n", &__start_rodata, &__end_rodata); printf(".bss: %p-%p\n", &__start_bss, &__end_bss); printf("Page size: %u, PhysicalPage structure size: %zu\n", PageSize, sizeof(PhysicalPage)); spinlock_softirq_init(&pagesLock); spinlock_softirq_init(&memoryMapLock); usedPages.init(); freePages.init(); uintptr_t firstUsableMemory = max((uintptr_t )&__end_kernel, __end_modules); uintptr_t firstFreePage = roundTo<uintptr_t>(firstUsableMemory, PageSize) + PageSize * PageFrameCount; // init page clusters PhysicalPage* bootstrapPage = (PhysicalPage* )firstFreePage; bootstrapPage->init((uintptr_t )bootstrapPage - KernelVirtualBase); printf("Inserting bootstrap page to used pages cluster: %p\n", (void* )bootstrapPage->getAddress()); usedPages.insert(bootstrapPage); unsigned int freeStructures = PageSize / sizeof (PhysicalPage) - 1; KASSERT(freeStructures > 0); printf("Free structures: %u\n", freeStructures); PhysicalPage* p = bootstrapPage + 1; for (unsigned int i = 0; i < memoryMapCount; i++) { printf("Adding memory range %p-%p (%zu)\n", (void* )memoryMap[i].address, (void* )(memoryMap[i].address + memoryMap[i].size), memoryMap[i].size); for (uintptr_t addr = memoryMap[i].address; addr < memoryMap[i].address + memoryMap[i].size; addr += PageSize) { if (freeStructures == 0) { D(printf("Allocating new page structure\n")); //p = (PhysicalPage* )sbrk(PageSize) uintptr_t ppage = getPage(); KASSERT(ppage != 0); p = (PhysicalPage* )mapAnonymousPage(ppage); // XXX make a function for this KASSERT(p != 0); freeStructures = PageSize / sizeof (PhysicalPage); } p->init(addr); if ((addr >= KernelLoadAddress) && (addr < firstFreePage - KernelVirtualBase)) { D(printf("Found used page: %p\n", (void* )addr)); usedPages.insert(p); } else { D(printf("Inserting free page: %p\n", (void* )addr)); freePages.insert(p); } p++; freeStructures--; } } uintptr_t start = stackEnd; printf("Creating initial kernel stack: %p-%p (%u)\n", (void* )start, (void* )(start - StackSize), StackSize); for (uintptr_t stackAddress = (start - StackSize); stackAddress < start; stackAddress += PageSize) { uintptr_t stackPage = getPage(); KASSERT(stackPage != 0); bool success = mapPage(stackAddress, stackPage); KASSERT(success); } // add one unmapped page as guard stackEnd = start - StackSize - PageSize; // KASSERT(success); // printf("Freeing initial kernel stack: %p-%p\n", (void* )(initial_stack - InitialStackSize), (void* )initial_stack); // for (uintptr_t oldStack = initial_stack - InitialStackSize; // oldStack < initial_stack; // oldStack += PageSize) // { // unmap(oldStack); // } } // XXX curently this overlaps anon mappings, se we can only give one anon // mapped page as the kernel stack area #if 0 bool Memory::createKernelStack(uintptr_t& start) { start = stackEnd; printf("Creating new kernel stack: %p-%p (%u)\n", (void* )start, (void* )(start - StackSize), StackSize); for (uintptr_t stackAddress = (start - StackSize); stackAddress < start; stackAddress += PageSize) { uintptr_t stackPage = getPage(); KASSERT(stackPage != 0); bool success = mapPage(stackAddress, stackPage); KASSERT(success); } // add one unmapped page as guard stackEnd = start - StackSize - PageSize; return true; } #else bool Memory::createKernelStack(uintptr_t& top) { uintptr_t stackPage = getPage(); KASSERT(stackPage != 0); uintptr_t bottom = mapAnonymousPage(stackPage); KASSERT(bottom != 0); top = bottom + PageSize; printf("Creating new kernel stack: %p-%p (%u)\n", (void* )top, (void* )(bottom), PageSize); // uintptr_t newStack = Hal::initKernelStack(top, &Kernel::Thread::main, ); // top = newStack; return true; } #endif // anonymous mapping of a physical page // uintptr_t Memory::mapAnonymousPage(uintptr_t phys, int flags) { spinlock_softirq_enter(&memoryMapLock); mapEnd -= PageSize; uintptr_t virt = mapEnd; spinlock_softirq_exit(&memoryMapLock); if (virt <= (uintptr_t)&__end_kernel) // if (virt <= heapEnd) { printf("%p <= %p\n", (void*)virt, (void*)heapEnd); Debug::panic("Memory::mapPage: Kernel map namespace exhausted."); } // Debug::info("Mapping anonymous page: %p to %p\n", phys, mapEnd); bool success = mapPage(virt, phys, flags); if (!success) { return 0; } return virt; } // anonymous memory mapping // uintptr_t Memory::mapAnonymousRegion(size_t size, int flags) { KASSERT(size != 0); size_t rsize = roundTo<uintptr_t>(size, PageSize); spinlock_softirq_enter(&memoryMapLock); mapEnd -= rsize; uintptr_t vaddr = mapEnd; spinlock_softirq_exit(&memoryMapLock); if (vaddr <= (uintptr_t)&__end_kernel) // if (vaddr <= heapEnd) { printf("%p <= %p\n", (void*)vaddr, (void*)heapEnd); Debug::panic("Memory::mapAnonymousRegion: Kernel map name space exhausted."); } for (size_t page = 0; page < rsize; page += PageSize) { uintptr_t emptyPage = getPage(); KASSERT(emptyPage != 0); bool success = mapPage(vaddr + page, emptyPage, flags); if (!success) { Debug::panic("mapRegion unsuccesful."); // XXX unmap and return error //return 0; } } return vaddr; } // anonymous mapping of a memory region // uintptr_t Memory::mapRegion(uintptr_t paddr, size_t size, int flags) { KASSERT(size != 0); uintptr_t firstPage = roundDown(paddr, PageSize); uintptr_t lastPage = roundTo(paddr + size, PageSize); size_t rsize = lastPage - firstPage; D(printf("Memory::mapRegion: %p-%p\n", (void*)paddr, (void*)(paddr + size))); D(printf("Memory::mapRegion: mapping: %p-%p (%zu)\n", (void*)firstPage, (void*)lastPage, rsize)); spinlock_softirq_enter(&memoryMapLock); mapEnd -= rsize; uintptr_t vaddr = mapEnd; spinlock_softirq_exit(&memoryMapLock); uintptr_t offset = paddr - firstPage; if (vaddr <= (uintptr_t)&__end_kernel) // if (vaddr <= heapEnd) { printf("%p <= %p\n", (void*)vaddr, (void*)heapEnd); Debug::panic("Memory::mapRegion: Kernel map namespace exhausted."); } for (uintptr_t page = firstPage; page != lastPage; page += PageSize, vaddr += PageSize) { bool success = mapPage(vaddr, page, flags); if (!success) { Debug::panic("mapRegion unsuccesful."); // XXX unmap and return error //return 0; } } return mapEnd + offset; } bool Memory::unmapRegion(uintptr_t paddr, std::size_t size) { KASSERT(size != 0); uintptr_t firstPage = roundDown(paddr, PageSize); uintptr_t lastPage = roundTo(paddr + size, PageSize); for (uintptr_t page = firstPage; page != lastPage; page += PageSize) { bool success = unmapPage(page); if (!success) { Debug::panic("unmapRegion unsuccesful."); } } return true; } // get a free physical page // uintptr_t Memory::getPage() { D(printf("Memory::getPage\n")); uintptr_t address = 0; spinlock_softirq_enter(&pagesLock); PhysicalPage* page = freePages.get(); if (page != 0) { usedPages.insert(page); address = page->getAddress(); } spinlock_softirq_exit(&pagesLock); D(printf("Memory::getPage done: %p\n", (void*)address)); return address; } // free a physical page // void Memory::putPage(uintptr_t address) { D(printf("Memory::putPage: %p\n", (void*)address)); spinlock_softirq_enter(&pagesLock); PhysicalPage* page = usedPages.find(address); if (page == 0) { spinlock_softirq_exit(&pagesLock); Debug::panic("Trying to free an unallocated physical page: %p\n", (void* )address); } usedPages.remove(page); freePages.insert(page); spinlock_softirq_exit(&pagesLock); } void* Memory::readPhysicalMemory(void* destination, const void* source, std::size_t size) { KASSERT(size != 0); uintptr_t mapFirst = roundDown(uintptr_t(source), PageSize); uintptr_t mapLast = roundTo(uintptr_t(source) + size, PageSize); uintptr_t mapped = mapRegion(mapFirst, mapLast - mapFirst); std::memcpy(destination, reinterpret_cast<void*>(mapped + (uintptr_t(source) - mapFirst)), size); unmapRegion(mapped, mapLast - mapFirst); return destination; } <|endoftext|>
<commit_before>#include "allocore/sound/al_AudioScene.hpp" namespace al{ Spatializer::Spatializer(const SpeakerLayout& sl){ unsigned numSpeakers = sl.speakers().size(); for(unsigned i=0;i<numSpeakers;++i){ mSpeakers.push_back(sl.speakers()[i]); } }; void AudioSceneObject::updateHistory(){ mPosHistory(mPose.pos()); } Listener::Listener(int numFrames_, Spatializer *spatializer) : mSpatializer(spatializer), mIsCompiled(false) { numFrames(numFrames_); } void Listener::numFrames(unsigned v){ if(mQuatHistory.size() != v) mQuatHistory.resize(v); mSpatializer->numFrames(v); } void Listener::updateHistory(int numFrames){ AudioSceneObject::updateHistory(); // Create a buffer of spherically interpolated quaternions from the previous // quat to the current quat: Quatd qnew = pose().quat(); Quatd::slerpBuffer(mQuatPrev, qnew, &mQuatHistory[0], numFrames); mQuatPrev = qnew; } void Listener::compile(){ mIsCompiled = true; mSpatializer->compile(*(this)); } SoundSource::SoundSource( double nearClip, double farClip, AttenuationLaw law, DopplerType dopplerType, double farBias, int delaySize ) : DistAtten<double>(nearClip, farClip, law, farBias), mSound(delaySize), mUseAtten(true), mDopplerType(dopplerType), mUsePerSampleProcessing(false) { // initialize the position history to be VERY FAR AWAY so that we don't deafen ourselves... for(int i=0; i<mPosHistory.size(); ++i){ mPosHistory(Vec3d(1000, 0, 0)); } presenceFilter.set(2700); } /*static*/ int SoundSource::bufferSize(double samplerate, double speedOfSound, double distance){ return (int)ceil(samplerate * distance / speedOfSound); } AudioScene::AudioScene(int numFrames_) : mNumFrames(0), mSpeedOfSound(340), mPerSampleProcessing(false) { numFrames(numFrames_); } AudioScene::~AudioScene(){ for( Listeners::iterator it = mListeners.begin(); it != mListeners.end(); ++it ){ delete (*it); } } void AudioScene::addSource(SoundSource& src){ mSources.push_back(&src); } void AudioScene::removeSource(SoundSource& src){ mSources.remove(&src); } void AudioScene::numFrames(int v){ if(mNumFrames != v){ mBuffer.resize(v); Listeners::iterator it = mListeners.begin(); while(it != mListeners.end()){ (*it)->numFrames(v); ++it; } mNumFrames = v; } } Listener * AudioScene::createListener(Spatializer* spatializer){ Listener * l = new Listener(mNumFrames, spatializer); l->compile(); mListeners.push_back(l); return l; } /* So, for large numbers of sources it quickly gets too expensive. Having one delayline per soundsource (for doppler) is itself quite taxing. e.g., at 44100kHz sampling rate, a speed of sound of 343m/s and an audible distance of 50m implies a delay of at least 6428 samples (need to add blocksize to that too). The actual buffersize sets the effective doppler far-clip; beyond this it always uses max-delay size (no doppler) The head-size sets the effective doppler near-clip. */ #if !ALLOCORE_GENERIC_AUDIOSCENE void AudioScene::render(AudioIOData& io) { const int numFrames = io.framesPerBuffer(); double sampleRate = io.framesPerSecond(); #else void AudioScene::render(float **outputBuffers, const int numFrames, const double sampleRate) { #endif // iterate through all listeners adding contribution from all sources for(unsigned il=0; il<mListeners.size(); ++il){ Listener& l = *mListeners[il]; Spatializer* spatializer = l.mSpatializer; spatializer->prepare(); // update listener history data: l.updateHistory(numFrames); // iterate through all sound sources for(Sources::iterator it = mSources.begin(); it != mSources.end(); ++it){ SoundSource& src = *(*it); // scalar factor to convert distances into delayline indices double distanceToSample = 0; if(src.dopplerType() == DOPPLER_SYMMETRICAL) distanceToSample = sampleRate / mSpeedOfSound; if(!src.usePerSampleProcessing()) //if our src is using per sample processing we will update this in the frame loop instead src.updateHistory(); if(mPerSampleProcessing) //audioscene per sample processing { // iterate time samples for(int i=0; i < numFrames; ++i){ Vec3d relpos; if(src.usePerSampleProcessing() && il == 0) //if src is using per sample processing, we can only do this for the first listener (TODO: better design for this) { src.updateHistory(); src.onProcessSample(i); relpos = src.posHistory()[0] - l.posHistory()[0]; if(src.dopplerType() == DOPPLER_PHYSICAL) { double currentDist = relpos.mag(); double prevDistance = (src.posHistory()[1] - l.posHistory()[0]).mag(); double sourceVel = (currentDist - prevDistance)*sampleRate; //positive when moving away, negative moving toward if(sourceVel == -mSpeedOfSound) sourceVel -= 0.001; //prevent divide by 0 / inf freq distanceToSample = fabs(sampleRate / (mSpeedOfSound + sourceVel)); } } else { // compute interpolated source position relative to listener // TODO: this tends to warble when moving fast double alpha = double(i)/numFrames; // moving average: // cheaper & slightly less warbly than cubic, // less glitchy than linear relpos = ( (src.posHistory()[3]-l.posHistory()[3])*(1.-alpha) + (src.posHistory()[2]-l.posHistory()[2]) + (src.posHistory()[1]-l.posHistory()[1]) + (src.posHistory()[0]-l.posHistory()[0])*(alpha) )/3.0; } //Compute distance in world-space units double dist = relpos.mag(); // Compute how many samples ago to read from buffer // Start with time delay due to speed of sound double samplesAgo = dist * distanceToSample; // Add on time delay (in samples) - only needed if the source is rendered per buffer if(!src.usePerSampleProcessing()) samplesAgo += (numFrames-i); // Is our delay line big enough? if(samplesAgo <= src.maxIndex()){ double gain = src.attenuation(dist); float s = src.readSample(samplesAgo) * gain; //s = src.presenceFilter(s); //TODO: causing stopband ripple here, why? #if !ALLOCORE_GENERIC_AUDIOSCENE spatializer->perform(io, src,relpos, numFrames, i, s); #else spatializer->perform(outputBuffers, src,relpos, numFrames, i, s); #endif } } //end for each frame } //end per sample processing else //more efficient, per buffer processing for audioscene (does not work well with doppler) { Vec3d relpos = src.pose().pos() - l.pose().pos(); double distance = relpos.mag(); double gain = src.attenuation(distance); for(int i = 0; i < numFrames; i++) { double readIndex = distance * distanceToSample; readIndex += (numFrames-i); mBuffer[i] = gain * src.readSample(readIndex); } #if !ALLOCORE_GENERIC_AUDIOSCENE spatializer->perform(io, src,relpos, numFrames, &mBuffer[0]); #else spatializer->perform(outputBuffers, src, relpos, numFrames, &mBuffer[0]); #endif } } //end for each source #if !ALLOCORE_GENERIC_AUDIOSCENE spatializer->finalize(io); #else spatializer->finalize(outputBuffers, numFrames); #endif } // end for each listener } } // al:: // From hydrogen bond... /* struct AmbiSource{ AmbiSource(uint32_t order, uint32_t dim) : doppler(0.1), dist(2, 0.001), angH(2), angV(2), enc(order, dim) {} void operator()(double * outA, double * inT, int numT, double dopScale=1, double distCoef=2, double ampOffset=0){ // do distance coding for(int i=0; i<numT; ++i){ double dis = dist(); // distance from source double amp = scl::clip(distToAmp(dis, distCoef) - ampOffset, 1.f); // computing amplitude of sound based on its distance (1/d^2) doppler.delay(dis*dopScale); inT[i] = doppler(inT[i] * amp); } enc.position(angH.stored() * M_PI, angV.stored() * M_PI); // loop ambi channels for(unsigned int c=0; c<enc.numChannels(); c++) { double * out = outA + numT*c; double w = enc.weights()[c]; // compute ambi-domain signals for(int i=0; i<numT; ++i) *out++ += inT[i] * w; } } // map distance from observer to a sound source to an amplitude value static double distToAmp(double d, double coef=2){ d = scl::abs(d); // positive vals only // we want amp=1 when distance=0 and a smooth transition across 0, so // we approximate 1/x with a polynomial d = (d + coef) / (d*d + d + coef); // 2nd order apx return d*d; //return exp(-d); } synz::Delay doppler; OnePole<> dist, angH, angV; // Low-pass filters on source position AmbiEncode<double> enc; }; // block rate // (double * outA, double * inT, int numT, double dopScale=1, double distCoef=2, double ampOffset=0) ambiH (io.aux(AMBI_NUM_SOURCES), io.aux(0), io.numFrames(), 1./32); ambiO (io.aux(AMBI_NUM_SOURCES), io.aux(1), io.numFrames(), 1./32, 2, 0.1); ambiZn(io.aux(AMBI_NUM_SOURCES), io.aux(2), io.numFrames(), 1./32, 2, 0.1); //---- Ambisonic decoding: static double chanMap[16] = { 2, 3, 4, 5, 6, 7, 8, 9, // MOTU #1 16, 17, 18, 19, 20, 21, 22, 23 // MOTU #2 }; //void decode(T ** dec, const T ** enc, uint32_t numDecFrames); // loop speakers for(int s=0; s < 16; ++s){ double * out = io.out(chanMap[s]); // loop ambi channels for(unsigned int c=0; c<ambiDec.numChannels(); c++){ double * in = io.aux(c + AMBI_NUM_SOURCES); double w = ambiDec.decodeWeight(s, c); for(unsigned int i=0; i<io.numFrames(); ++i) out[i] += *in++ * w * 8.f; } } */ <commit_msg>Fixed bug with AudioScene buffer indexing<commit_after>#include "allocore/sound/al_AudioScene.hpp" namespace al{ Spatializer::Spatializer(const SpeakerLayout& sl){ unsigned numSpeakers = sl.speakers().size(); for(unsigned i=0;i<numSpeakers;++i){ mSpeakers.push_back(sl.speakers()[i]); } }; void AudioSceneObject::updateHistory(){ mPosHistory(mPose.pos()); } Listener::Listener(int numFrames_, Spatializer *spatializer) : mSpatializer(spatializer), mIsCompiled(false) { numFrames(numFrames_); } void Listener::numFrames(unsigned v){ if(mQuatHistory.size() != v) mQuatHistory.resize(v); mSpatializer->numFrames(v); } void Listener::updateHistory(int numFrames){ AudioSceneObject::updateHistory(); // Create a buffer of spherically interpolated quaternions from the previous // quat to the current quat: Quatd qnew = pose().quat(); Quatd::slerpBuffer(mQuatPrev, qnew, &mQuatHistory[0], numFrames); mQuatPrev = qnew; } void Listener::compile(){ mIsCompiled = true; mSpatializer->compile(*(this)); } SoundSource::SoundSource( double nearClip, double farClip, AttenuationLaw law, DopplerType dopplerType, double farBias, int delaySize ) : DistAtten<double>(nearClip, farClip, law, farBias), mSound(delaySize), mUseAtten(true), mDopplerType(dopplerType), mUsePerSampleProcessing(false) { // initialize the position history to be VERY FAR AWAY so that we don't deafen ourselves... for(int i=0; i<mPosHistory.size(); ++i){ mPosHistory(Vec3d(1000, 0, 0)); } presenceFilter.set(2700); } /*static*/ int SoundSource::bufferSize(double samplerate, double speedOfSound, double distance){ return (int)ceil(samplerate * distance / speedOfSound); } AudioScene::AudioScene(int numFrames_) : mNumFrames(0), mSpeedOfSound(340), mPerSampleProcessing(false) { numFrames(numFrames_); } AudioScene::~AudioScene(){ for( Listeners::iterator it = mListeners.begin(); it != mListeners.end(); ++it ){ delete (*it); } } void AudioScene::addSource(SoundSource& src){ mSources.push_back(&src); } void AudioScene::removeSource(SoundSource& src){ mSources.remove(&src); } void AudioScene::numFrames(int v){ if(mNumFrames != v){ mBuffer.resize(v); Listeners::iterator it = mListeners.begin(); while(it != mListeners.end()){ (*it)->numFrames(v); ++it; } mNumFrames = v; } } Listener * AudioScene::createListener(Spatializer* spatializer){ Listener * l = new Listener(mNumFrames, spatializer); l->compile(); mListeners.push_back(l); return l; } /* So, for large numbers of sources it quickly gets too expensive. Having one delayline per soundsource (for doppler) is itself quite taxing. e.g., at 44100kHz sampling rate, a speed of sound of 343m/s and an audible distance of 50m implies a delay of at least 6428 samples (need to add blocksize to that too). The actual buffersize sets the effective doppler far-clip; beyond this it always uses max-delay size (no doppler) The head-size sets the effective doppler near-clip. */ #if !ALLOCORE_GENERIC_AUDIOSCENE void AudioScene::render(AudioIOData& io) { const int numFrames = io.framesPerBuffer(); double sampleRate = io.framesPerSecond(); #else void AudioScene::render(float **outputBuffers, const int numFrames, const double sampleRate) { #endif // iterate through all listeners adding contribution from all sources for(unsigned il=0; il<mListeners.size(); ++il){ Listener& l = *mListeners[il]; Spatializer* spatializer = l.mSpatializer; spatializer->prepare(); // update listener history data: l.updateHistory(numFrames); // iterate through all sound sources for(Sources::iterator it = mSources.begin(); it != mSources.end(); ++it){ SoundSource& src = *(*it); // scalar factor to convert distances into delayline indices double distanceToSample = 0; if(src.dopplerType() == DOPPLER_SYMMETRICAL) distanceToSample = sampleRate / mSpeedOfSound; if(!src.usePerSampleProcessing()) //if our src is using per sample processing we will update this in the frame loop instead src.updateHistory(); if(mPerSampleProcessing) //audioscene per sample processing { // iterate time samples for(int i=0; i < numFrames; ++i){ Vec3d relpos; if(src.usePerSampleProcessing() && il == 0) //if src is using per sample processing, we can only do this for the first listener (TODO: better design for this) { src.updateHistory(); src.onProcessSample(i); relpos = src.posHistory()[0] - l.posHistory()[0]; if(src.dopplerType() == DOPPLER_PHYSICAL) { double currentDist = relpos.mag(); double prevDistance = (src.posHistory()[1] - l.posHistory()[0]).mag(); double sourceVel = (currentDist - prevDistance)*sampleRate; //positive when moving away, negative moving toward if(sourceVel == -mSpeedOfSound) sourceVel -= 0.001; //prevent divide by 0 / inf freq distanceToSample = fabs(sampleRate / (mSpeedOfSound + sourceVel)); } } else { // compute interpolated source position relative to listener // TODO: this tends to warble when moving fast double alpha = double(i)/numFrames; // moving average: // cheaper & slightly less warbly than cubic, // less glitchy than linear relpos = ( (src.posHistory()[3]-l.posHistory()[3])*(1.-alpha) + (src.posHistory()[2]-l.posHistory()[2]) + (src.posHistory()[1]-l.posHistory()[1]) + (src.posHistory()[0]-l.posHistory()[0])*(alpha) )/3.0; } //Compute distance in world-space units double dist = relpos.mag(); // Compute how many samples ago to read from buffer // Start with time delay due to speed of sound double samplesAgo = dist * distanceToSample; // Add on time delay (in samples) - only needed if the source is rendered per buffer if(!src.usePerSampleProcessing()) samplesAgo += (numFrames-i); // Is our delay line big enough? if(samplesAgo <= src.maxIndex()){ double gain = src.attenuation(dist); float s = src.readSample(samplesAgo) * gain; //s = src.presenceFilter(s); //TODO: causing stopband ripple here, why? #if !ALLOCORE_GENERIC_AUDIOSCENE spatializer->perform(io, src,relpos, numFrames, i, s); #else spatializer->perform(outputBuffers, src,relpos, numFrames, i, s); #endif } } //end for each frame } //end per sample processing else //more efficient, per buffer processing for audioscene (does not work well with doppler) { Vec3d relpos = src.pose().pos() - l.pose().pos(); double distance = relpos.mag(); double gain = src.attenuation(distance); for(int i = 0; i < numFrames; i++) { double readIndex = distance * distanceToSample; readIndex += (numFrames - i - 1); mBuffer[i] = gain * src.readSample(readIndex); } #if !ALLOCORE_GENERIC_AUDIOSCENE spatializer->perform(io, src,relpos, numFrames, &mBuffer[0]); #else spatializer->perform(outputBuffers, src, relpos, numFrames, &mBuffer[0]); #endif } } //end for each source #if !ALLOCORE_GENERIC_AUDIOSCENE spatializer->finalize(io); #else spatializer->finalize(outputBuffers, numFrames); #endif } // end for each listener } } // al:: // From hydrogen bond... /* struct AmbiSource{ AmbiSource(uint32_t order, uint32_t dim) : doppler(0.1), dist(2, 0.001), angH(2), angV(2), enc(order, dim) {} void operator()(double * outA, double * inT, int numT, double dopScale=1, double distCoef=2, double ampOffset=0){ // do distance coding for(int i=0; i<numT; ++i){ double dis = dist(); // distance from source double amp = scl::clip(distToAmp(dis, distCoef) - ampOffset, 1.f); // computing amplitude of sound based on its distance (1/d^2) doppler.delay(dis*dopScale); inT[i] = doppler(inT[i] * amp); } enc.position(angH.stored() * M_PI, angV.stored() * M_PI); // loop ambi channels for(unsigned int c=0; c<enc.numChannels(); c++) { double * out = outA + numT*c; double w = enc.weights()[c]; // compute ambi-domain signals for(int i=0; i<numT; ++i) *out++ += inT[i] * w; } } // map distance from observer to a sound source to an amplitude value static double distToAmp(double d, double coef=2){ d = scl::abs(d); // positive vals only // we want amp=1 when distance=0 and a smooth transition across 0, so // we approximate 1/x with a polynomial d = (d + coef) / (d*d + d + coef); // 2nd order apx return d*d; //return exp(-d); } synz::Delay doppler; OnePole<> dist, angH, angV; // Low-pass filters on source position AmbiEncode<double> enc; }; // block rate // (double * outA, double * inT, int numT, double dopScale=1, double distCoef=2, double ampOffset=0) ambiH (io.aux(AMBI_NUM_SOURCES), io.aux(0), io.numFrames(), 1./32); ambiO (io.aux(AMBI_NUM_SOURCES), io.aux(1), io.numFrames(), 1./32, 2, 0.1); ambiZn(io.aux(AMBI_NUM_SOURCES), io.aux(2), io.numFrames(), 1./32, 2, 0.1); //---- Ambisonic decoding: static double chanMap[16] = { 2, 3, 4, 5, 6, 7, 8, 9, // MOTU #1 16, 17, 18, 19, 20, 21, 22, 23 // MOTU #2 }; //void decode(T ** dec, const T ** enc, uint32_t numDecFrames); // loop speakers for(int s=0; s < 16; ++s){ double * out = io.out(chanMap[s]); // loop ambi channels for(unsigned int c=0; c<ambiDec.numChannels(); c++){ double * in = io.aux(c + AMBI_NUM_SOURCES); double w = ambiDec.decodeWeight(s, c); for(unsigned int i=0; i<io.numFrames(); ++i) out[i] += *in++ * w * 8.f; } } */ <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.1 2001/08/24 12:48:48 tng * Schema: AllContentModel * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/RuntimeException.hpp> #include <framework/XMLElementDecl.hpp> #include <framework/XMLValidator.hpp> #include <validators/common/ContentSpecNode.hpp> #include <validators/common/AllContentModel.hpp> #include <validators/schema/SubstitutionGroupComparator.hpp> #include <validators/schema/XercesElementWildcard.hpp> // --------------------------------------------------------------------------- // AllContentModel: Constructors and Destructor // --------------------------------------------------------------------------- AllContentModel::AllContentModel(ContentSpecNode* const parentContentSpec , const bool isMixed) : fCount(0) , fChildren(0) , fChildOptional(0) , fNumRequired(0) , fIsMixed(isMixed) { // // Create a vector of unsigned ints that will be filled in with the // ids of the child nodes. It will be expanded as needed but we give // it an initial capacity of 64 which should be more than enough for // 99% of the scenarios. // ValueVectorOf<QName*> children(64); ValueVectorOf<bool> childOptional(64); // // Get the parent element's content spec. This is the head of the tree // of nodes that describes the content model. We will iterate this // tree. // ContentSpecNode* curNode = parentContentSpec; if (!curNode) ThrowXML(RuntimeException, XMLExcepts::CM_NoParentCSN); // And now call the private recursive method that iterates the tree buildChildList(curNode, children, childOptional); // // And now we know how many elements we need in our member list. So // fill them in. // fCount = children.size(); fChildren = new QName*[fCount]; fChildOptional = new bool[fCount]; for (unsigned int index = 0; index < fCount; index++) { fChildren[index] = children.elementAt(index); fChildOptional[index] = childOptional.elementAt(index); } } AllContentModel::~AllContentModel() { delete [] fChildren; delete [] fChildOptional; } // --------------------------------------------------------------------------- // AllContentModel: Implementation of the ContentModel virtual interface // --------------------------------------------------------------------------- // //Under the XML Schema mixed model, //the order and number of child elements appearing in an instance //must agree with //the order and number of child elements specified in the model. // int AllContentModel::validateContent( QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId) const { // If <all> had minOccurs of zero and there are // no children to validate, trivially validate if (!fNumRequired && !childCount) return -1; // Check for duplicate element bool* elementSeen = new bool[fCount]; // initialize the array for (unsigned int i = 0; i < fCount; i++) elementSeen[i] = false; // keep track of the required element seen unsigned int numRequiredSeen = 0; for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) { // Get the current child out of the source index const QName* curChild = children[outIndex]; // If its PCDATA, then we just accept that if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId) continue; // And try to find it in our list unsigned int inIndex = 0; for (; inIndex < fCount; inIndex++) { const QName* inChild = fChildren[inIndex]; if ((inChild->getURI() == curChild->getURI()) && (!XMLString::compareString(inChild->getLocalPart(), curChild->getLocalPart()))) { // found it // If this element was seen already, indicate an error was // found at the duplicate index. if (elementSeen[inIndex]) { delete [] elementSeen; return outIndex; } else elementSeen[inIndex] = true; if (!fChildOptional[inIndex]) numRequiredSeen++; break; } } // We did not find this one, so the validation failed if (inIndex == fCount) { delete [] elementSeen; return outIndex; } } delete [] elementSeen; // Were all the required elements of the <all> encountered? if (numRequiredSeen != fNumRequired) { return childCount; } // Everything seems to be ok, so return success // success return -1; } int AllContentModel::validateContentSpecial(QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId , GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool) const { SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool); // If <all> had minOccurs of zero and there are // no children to validate, trivially validate if (!fNumRequired && !childCount) return -1; // Check for duplicate element bool* elementSeen = new bool[fCount]; // initialize the array for (unsigned int i = 0; i < fCount; i++) elementSeen[i] = false; // keep track of the required element seen unsigned int numRequiredSeen = 0; for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) { // Get the current child out of the source index QName* const curChild = children[outIndex]; // If its PCDATA, then we just accept that if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId) continue; // And try to find it in our list unsigned int inIndex = 0; for (; inIndex < fCount; inIndex++) { QName* const inChild = fChildren[inIndex]; if ( comparator.isEquivalentTo(curChild, inChild)) { // match // If this element was seen already, indicate an error was // found at the duplicate index. if (elementSeen[inIndex]) { delete [] elementSeen; return outIndex; } else elementSeen[inIndex] = true; if (!fChildOptional[inIndex]) numRequiredSeen++; break; } } // We did not find this one, so the validation failed if (inIndex == fCount) { delete [] elementSeen; return outIndex; } } delete [] elementSeen; // Were all the required elements of the <all> encountered? if (numRequiredSeen != fNumRequired) { return childCount; } // Everything seems to be ok, so return success // success return -1; } void AllContentModel::checkUniqueParticleAttribution ( GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool , XMLValidator* const pValidator , unsigned int* const pContentSpecOrgURI ) { SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool); unsigned int i, j; // rename back for (i = 0; i < fCount; i++) { unsigned int orgURIIndex = fChildren[i]->getURI(); fChildren[i]->setURI(pContentSpecOrgURI[orgURIIndex]); } // check whether there is conflict between any two leaves for (i = 0; i < fCount; i++) { for (j = 0; j < fCount; j++) { // If this is text in a Schema mixed content model, skip it. if ( fIsMixed && (( fChildren[i]->getURI() == XMLElementDecl::fgPCDataElemId) || ( fChildren[j]->getURI() == XMLElementDecl::fgPCDataElemId))) continue; if (XercesElementWildcard::conflict(ContentSpecNode::Leaf, fChildren[i], ContentSpecNode::Leaf, fChildren[j], &comparator)) { pValidator->emitError(XMLValid::UniqueParticleAttributionFail, fChildren[i]->getRawName(), fChildren[j]->getRawName()); } } } } // --------------------------------------------------------------------------- // AllContentModel: Private helper methods // --------------------------------------------------------------------------- void AllContentModel::buildChildList(ContentSpecNode* const curNode , ValueVectorOf<QName*>& toFill , ValueVectorOf<bool>& toOptional) { // Get the type of spec node our current node is const ContentSpecNode::NodeTypes curType = curNode->getType(); if (curType == ContentSpecNode::All) { // Get both the child node pointers ContentSpecNode* leftNode = curNode->getFirst(); ContentSpecNode* rightNode = curNode->getSecond(); // Recurse on the left and right nodes buildChildList(leftNode, toFill, toOptional); buildChildList(rightNode, toFill, toOptional); } else if (curType == ContentSpecNode::Leaf) { // At leaf, add the element to list of elements permitted in the all toFill.addElement(curNode->getElement()); toOptional.addElement(false); fNumRequired++; } else if (curType == ContentSpecNode::ZeroOrOne) { // At ZERO_OR_ONE node, subtree must be an element // that was specified with minOccurs=0, maxOccurs=1 ContentSpecNode* leftNode = curNode->getFirst(); if (leftNode->getType() != ContentSpecNode::Leaf) ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType); toFill.addElement(leftNode->getElement()); toOptional.addElement(true); } else ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType); } <commit_msg>Schema: AllContentModel UPA Check typo fix<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2001/08/27 12:19:00 tng * Schema: AllContentModel UPA Check typo fix * * Revision 1.1 2001/08/24 12:48:48 tng * Schema: AllContentModel * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/RuntimeException.hpp> #include <framework/XMLElementDecl.hpp> #include <framework/XMLValidator.hpp> #include <validators/common/ContentSpecNode.hpp> #include <validators/common/AllContentModel.hpp> #include <validators/schema/SubstitutionGroupComparator.hpp> #include <validators/schema/XercesElementWildcard.hpp> // --------------------------------------------------------------------------- // AllContentModel: Constructors and Destructor // --------------------------------------------------------------------------- AllContentModel::AllContentModel(ContentSpecNode* const parentContentSpec , const bool isMixed) : fCount(0) , fChildren(0) , fChildOptional(0) , fNumRequired(0) , fIsMixed(isMixed) { // // Create a vector of unsigned ints that will be filled in with the // ids of the child nodes. It will be expanded as needed but we give // it an initial capacity of 64 which should be more than enough for // 99% of the scenarios. // ValueVectorOf<QName*> children(64); ValueVectorOf<bool> childOptional(64); // // Get the parent element's content spec. This is the head of the tree // of nodes that describes the content model. We will iterate this // tree. // ContentSpecNode* curNode = parentContentSpec; if (!curNode) ThrowXML(RuntimeException, XMLExcepts::CM_NoParentCSN); // And now call the private recursive method that iterates the tree buildChildList(curNode, children, childOptional); // // And now we know how many elements we need in our member list. So // fill them in. // fCount = children.size(); fChildren = new QName*[fCount]; fChildOptional = new bool[fCount]; for (unsigned int index = 0; index < fCount; index++) { fChildren[index] = children.elementAt(index); fChildOptional[index] = childOptional.elementAt(index); } } AllContentModel::~AllContentModel() { delete [] fChildren; delete [] fChildOptional; } // --------------------------------------------------------------------------- // AllContentModel: Implementation of the ContentModel virtual interface // --------------------------------------------------------------------------- // //Under the XML Schema mixed model, //the order and number of child elements appearing in an instance //must agree with //the order and number of child elements specified in the model. // int AllContentModel::validateContent( QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId) const { // If <all> had minOccurs of zero and there are // no children to validate, trivially validate if (!fNumRequired && !childCount) return -1; // Check for duplicate element bool* elementSeen = new bool[fCount]; // initialize the array for (unsigned int i = 0; i < fCount; i++) elementSeen[i] = false; // keep track of the required element seen unsigned int numRequiredSeen = 0; for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) { // Get the current child out of the source index const QName* curChild = children[outIndex]; // If its PCDATA, then we just accept that if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId) continue; // And try to find it in our list unsigned int inIndex = 0; for (; inIndex < fCount; inIndex++) { const QName* inChild = fChildren[inIndex]; if ((inChild->getURI() == curChild->getURI()) && (!XMLString::compareString(inChild->getLocalPart(), curChild->getLocalPart()))) { // found it // If this element was seen already, indicate an error was // found at the duplicate index. if (elementSeen[inIndex]) { delete [] elementSeen; return outIndex; } else elementSeen[inIndex] = true; if (!fChildOptional[inIndex]) numRequiredSeen++; break; } } // We did not find this one, so the validation failed if (inIndex == fCount) { delete [] elementSeen; return outIndex; } } delete [] elementSeen; // Were all the required elements of the <all> encountered? if (numRequiredSeen != fNumRequired) { return childCount; } // Everything seems to be ok, so return success // success return -1; } int AllContentModel::validateContentSpecial(QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId , GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool) const { SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool); // If <all> had minOccurs of zero and there are // no children to validate, trivially validate if (!fNumRequired && !childCount) return -1; // Check for duplicate element bool* elementSeen = new bool[fCount]; // initialize the array for (unsigned int i = 0; i < fCount; i++) elementSeen[i] = false; // keep track of the required element seen unsigned int numRequiredSeen = 0; for (unsigned int outIndex = 0; outIndex < childCount; outIndex++) { // Get the current child out of the source index QName* const curChild = children[outIndex]; // If its PCDATA, then we just accept that if (fIsMixed && curChild->getURI() == XMLElementDecl::fgPCDataElemId) continue; // And try to find it in our list unsigned int inIndex = 0; for (; inIndex < fCount; inIndex++) { QName* const inChild = fChildren[inIndex]; if ( comparator.isEquivalentTo(curChild, inChild)) { // match // If this element was seen already, indicate an error was // found at the duplicate index. if (elementSeen[inIndex]) { delete [] elementSeen; return outIndex; } else elementSeen[inIndex] = true; if (!fChildOptional[inIndex]) numRequiredSeen++; break; } } // We did not find this one, so the validation failed if (inIndex == fCount) { delete [] elementSeen; return outIndex; } } delete [] elementSeen; // Were all the required elements of the <all> encountered? if (numRequiredSeen != fNumRequired) { return childCount; } // Everything seems to be ok, so return success // success return -1; } void AllContentModel::checkUniqueParticleAttribution ( GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool , XMLValidator* const pValidator , unsigned int* const pContentSpecOrgURI ) { SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool); unsigned int i, j; // rename back for (i = 0; i < fCount; i++) { unsigned int orgURIIndex = fChildren[i]->getURI(); fChildren[i]->setURI(pContentSpecOrgURI[orgURIIndex]); } // check whether there is conflict between any two leaves for (i = 0; i < fCount; i++) { for (j = i+1; j < fCount; j++) { // If this is text in a Schema mixed content model, skip it. if ( fIsMixed && (( fChildren[i]->getURI() == XMLElementDecl::fgPCDataElemId) || ( fChildren[j]->getURI() == XMLElementDecl::fgPCDataElemId))) continue; if (XercesElementWildcard::conflict(ContentSpecNode::Leaf, fChildren[i], ContentSpecNode::Leaf, fChildren[j], &comparator)) { pValidator->emitError(XMLValid::UniqueParticleAttributionFail, fChildren[i]->getRawName(), fChildren[j]->getRawName()); } } } } // --------------------------------------------------------------------------- // AllContentModel: Private helper methods // --------------------------------------------------------------------------- void AllContentModel::buildChildList(ContentSpecNode* const curNode , ValueVectorOf<QName*>& toFill , ValueVectorOf<bool>& toOptional) { // Get the type of spec node our current node is const ContentSpecNode::NodeTypes curType = curNode->getType(); if (curType == ContentSpecNode::All) { // Get both the child node pointers ContentSpecNode* leftNode = curNode->getFirst(); ContentSpecNode* rightNode = curNode->getSecond(); // Recurse on the left and right nodes buildChildList(leftNode, toFill, toOptional); buildChildList(rightNode, toFill, toOptional); } else if (curType == ContentSpecNode::Leaf) { // At leaf, add the element to list of elements permitted in the all toFill.addElement(curNode->getElement()); toOptional.addElement(false); fNumRequired++; } else if (curType == ContentSpecNode::ZeroOrOne) { // At ZERO_OR_ONE node, subtree must be an element // that was specified with minOccurs=0, maxOccurs=1 ContentSpecNode* leftNode = curNode->getFirst(); if (leftNode->getType() != ContentSpecNode::Leaf) ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType); toFill.addElement(leftNode->getElement()); toOptional.addElement(true); } else ThrowXML(RuntimeException, XMLExcepts::CM_UnknownCMSpecType); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "libutils.h" #include "Config.h" #include "Exception.h" #include <fstream> #include <iostream> //#include "strutils.h" CConfig::CConfig(void) { } CConfig::~CConfig(void) { #ifdef _LIBUTILS_USE_XML_LIBXML2 m_Document.Close(); #endif } void CConfig::Close() { } void CConfig::Load(string ConfigFileName) { #ifdef _LIBUTILS_USE_XML_LIBXML2 // // Parse the XML file, catching any XML exceptions that might propogate // out of it. // m_Document.Load(ConfigFileName); #elif defined(USE_JSON) try { Json::Value root; ifstream file(ConfigFileName); file >> root; m_Document = root; } catch (Json::RuntimeError ex) { throw CHaException(CHaException::ErrParsingError, "Failed to parse JSON file %s. Error %s", ConfigFileName.c_str(), ex.what()); } /* string doc; getline(file, doc, (char)EOF); if (doc.length() == 0) throw CHaException(CHaException::ErrParsingError, "Failed to load JSON file %s. Error %s", ConfigFileName.c_str(), reader.getFormattedErrorMessages().c_str()); else if (doc[0] == (char)0xef) doc = doc.substr(3); bool parsingSuccessful = reader.parse(doc, root, std::ifstream::binary); if (!parsingSuccessful) throw CHaException(CHaException::ErrParsingError, "Failed to parse JSON file %s. Error %s", ConfigFileName.c_str(), reader.getFormattedErrorMessages().c_str()); */ #else # error usupported configuration #endif // } string CConfig::getStr(string path, bool bMandatory, string defaultValue) { return m_Document.getStr(path, bMandatory, defaultValue); } CConfigItem CConfig::getNode(const char* path) { return m_Document.getNode(path); } void CConfig::getList(const char* path, CConfigItemList &list) { m_Document.getList(path, list); } <commit_msg>bugix<commit_after>#include "stdafx.h" #include "libutils.h" #include "Config.h" #include "Exception.h" #include <fstream> #include <iostream> //#include "strutils.h" CConfig::CConfig(void) { } CConfig::~CConfig(void) { #ifdef _LIBUTILS_USE_XML_LIBXML2 m_Document.Close(); #endif } void CConfig::Close() { } void CConfig::Load(string ConfigFileName) { #ifdef _LIBUTILS_USE_XML_LIBXML2 // // Parse the XML file, catching any XML exceptions that might propogate // out of it. // m_Document.Load(ConfigFileName); #elif defined(USE_JSON) try { Json::Value root; ifstream file(ConfigFileName); file >> root; m_Document = root; } catch (std::exception ex) { throw CHaException(CHaException::ErrParsingError, "Failed to parse JSON file %s. Error %s", ConfigFileName.c_str(), ex.what()); } /* string doc; getline(file, doc, (char)EOF); if (doc.length() == 0) throw CHaException(CHaException::ErrParsingError, "Failed to load JSON file %s. Error %s", ConfigFileName.c_str(), reader.getFormattedErrorMessages().c_str()); else if (doc[0] == (char)0xef) doc = doc.substr(3); bool parsingSuccessful = reader.parse(doc, root, std::ifstream::binary); if (!parsingSuccessful) throw CHaException(CHaException::ErrParsingError, "Failed to parse JSON file %s. Error %s", ConfigFileName.c_str(), reader.getFormattedErrorMessages().c_str()); */ #else # error usupported configuration #endif // } string CConfig::getStr(string path, bool bMandatory, string defaultValue) { return m_Document.getStr(path, bMandatory, defaultValue); } CConfigItem CConfig::getNode(const char* path) { return m_Document.getNode(path); } void CConfig::getList(const char* path, CConfigItemList &list) { m_Document.getList(path, list); } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <david@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "cells.h" #include "log.h" #include "nextpnr.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN inline NetInfo *port_or_nullptr(const CellInfo *cell, IdString name) { auto found = cell->ports.find(name); if (found == cell->ports.end()) return nullptr; return found->second.net; } bool Arch::slicesCompatible(const std::vector<const CellInfo *> &cells) const { // TODO: allow different LSR/CLK and MUX/SRMODE settings once // routing details are worked out IdString clk_sig, lsr_sig; IdString CLKMUX, LSRMUX, SRMODE; bool first = true; for (auto cell : cells) { if (cell->sliceInfo.using_dff) { if (first) { clk_sig = cell->sliceInfo.clk_sig; lsr_sig = cell->sliceInfo.lsr_sig; CLKMUX = cell->sliceInfo.clkmux; LSRMUX = cell->sliceInfo.lsrmux; SRMODE = cell->sliceInfo.srmode; } else { if (cell->sliceInfo.clk_sig != clk_sig) return false; if (cell->sliceInfo.lsr_sig != lsr_sig) return false; if (cell->sliceInfo.clkmux != CLKMUX) return false; if (cell->sliceInfo.lsrmux != LSRMUX) return false; if (cell->sliceInfo.srmode != SRMODE) return false; } first = false; } } return true; } bool Arch::isBelLocationValid(BelId bel) const { if (getBelType(bel) == id_TRELLIS_SLICE) { std::vector<const CellInfo *> bel_cells; Loc bel_loc = getBelLocation(bel); for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) { CellInfo *cell_other = getBoundBelCell(bel_other); if (cell_other != nullptr) { bel_cells.push_back(cell_other); } } return slicesCompatible(bel_cells); } else { CellInfo *cell = getBoundBelCell(bel); if (cell == nullptr) return true; else return isValidBelForCell(cell, bel); } } bool Arch::isValidBelForCell(CellInfo *cell, BelId bel) const { if (cell->type == id_TRELLIS_SLICE) { NPNR_ASSERT(getBelType(bel) == id_TRELLIS_SLICE); std::vector<const CellInfo *> bel_cells; Loc bel_loc = getBelLocation(bel); for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) { CellInfo *cell_other = getBoundBelCell(bel_other); if (cell_other != nullptr && bel_other != bel) { bel_cells.push_back(cell_other); } } bel_cells.push_back(cell); return slicesCompatible(bel_cells); } else { // other checks return true; } } NEXTPNR_NAMESPACE_END <commit_msg>ecp5: Add DCU availability check<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <david@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "cells.h" #include "log.h" #include "nextpnr.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN inline NetInfo *port_or_nullptr(const CellInfo *cell, IdString name) { auto found = cell->ports.find(name); if (found == cell->ports.end()) return nullptr; return found->second.net; } bool Arch::slicesCompatible(const std::vector<const CellInfo *> &cells) const { // TODO: allow different LSR/CLK and MUX/SRMODE settings once // routing details are worked out IdString clk_sig, lsr_sig; IdString CLKMUX, LSRMUX, SRMODE; bool first = true; for (auto cell : cells) { if (cell->sliceInfo.using_dff) { if (first) { clk_sig = cell->sliceInfo.clk_sig; lsr_sig = cell->sliceInfo.lsr_sig; CLKMUX = cell->sliceInfo.clkmux; LSRMUX = cell->sliceInfo.lsrmux; SRMODE = cell->sliceInfo.srmode; } else { if (cell->sliceInfo.clk_sig != clk_sig) return false; if (cell->sliceInfo.lsr_sig != lsr_sig) return false; if (cell->sliceInfo.clkmux != CLKMUX) return false; if (cell->sliceInfo.lsrmux != LSRMUX) return false; if (cell->sliceInfo.srmode != SRMODE) return false; } first = false; } } return true; } bool Arch::isBelLocationValid(BelId bel) const { if (getBelType(bel) == id_TRELLIS_SLICE) { std::vector<const CellInfo *> bel_cells; Loc bel_loc = getBelLocation(bel); for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) { CellInfo *cell_other = getBoundBelCell(bel_other); if (cell_other != nullptr) { bel_cells.push_back(cell_other); } } return slicesCompatible(bel_cells); } else { CellInfo *cell = getBoundBelCell(bel); if (cell == nullptr) return true; else return isValidBelForCell(cell, bel); } } bool Arch::isValidBelForCell(CellInfo *cell, BelId bel) const { if (cell->type == id_TRELLIS_SLICE) { NPNR_ASSERT(getBelType(bel) == id_TRELLIS_SLICE); std::vector<const CellInfo *> bel_cells; Loc bel_loc = getBelLocation(bel); for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) { CellInfo *cell_other = getBoundBelCell(bel_other); if (cell_other != nullptr && bel_other != bel) { bel_cells.push_back(cell_other); } } bel_cells.push_back(cell); return slicesCompatible(bel_cells); } else if (cell->type == id_DCUA || cell->type == id_EXTREFB || cell->type == id_PCSCLKDIV) { return args.type != ArchArgs::LFE5U_25F && args.type != ArchArgs::LFE5U_45F && args.type != ArchArgs::LFE5U_85F; } else { // other checks return true; } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>#include "filtergraph.h" #include "camerafilter.h" #include "kvazaarfilter.h" #include "rgb32toyuv.h" #include "openhevcfilter.h" #include "yuvtorgb32.h" #include "framedsourcefilter.h" #include "rtpsinkfilter.h" #include "displayfilter.h" #include "audiocapturefilter.h" #include "audiooutputdevice.h" #include "audiooutput.h" #include "opusencoderfilter.h" #include "opusdecoderfilter.h" #include "speexaecfilter.h" #include "common.h" FilterGraph::FilterGraph(StatisticsInterface* stats): peers_(), videoSend_(), audioSend_(), selfView_(NULL), stats_(stats), format_() { Q_ASSERT(stats); // TODO negotiate these values with all included filters format_.setSampleRate(48000); format_.setChannelCount(2); format_.setSampleSize(16); format_.setSampleType(QAudioFormat::SignedInt); format_.setByteOrder(QAudioFormat::LittleEndian); format_.setCodec("audio/pcm"); } void FilterGraph::init(VideoWidget* selfView, QSize resolution) { resolution_ = resolution; selfView_ = selfView; frameRate_ = 30; initSelfView(selfView, resolution); } void FilterGraph::initSelfView(VideoWidget *selfView, QSize resolution) { if(videoSend_.size() > 0) { destroyFilters(videoSend_); } // Sending video graph videoSend_.push_back(new CameraFilter("", stats_, resolution)); if(selfView) { // connect selfview to camera DisplayFilter* selfviewFilter = new DisplayFilter("Self_", stats_, selfView, 1111); selfviewFilter->setProperties(true); videoSend_.push_back(selfviewFilter); videoSend_.at(0)->addOutConnection(videoSend_.back()); videoSend_.back()->start(); } } void FilterGraph::initVideoSend(QSize resolution) { if(videoSend_.size() != 2) { if(videoSend_.size() > 2) { destroyFilters(videoSend_); } initSelfView(selfView_, resolution_); } videoSend_.push_back(new RGB32toYUV("", stats_)); videoSend_.at(0)->addOutConnection(videoSend_.back()); // attach to camera videoSend_.back()->start(); KvazaarFilter* kvz = new KvazaarFilter("", stats_); kvz->init(resolution, frameRate_, 1); videoSend_.push_back(kvz); videoSend_.at(videoSend_.size() - 2)->addOutConnection(videoSend_.back()); videoSend_.back()->start(); } void FilterGraph::initAudioSend() { // Do this before adding participants, otherwise AEC filter wont get attached AudioCaptureFilter* capture = new AudioCaptureFilter("", stats_); capture->initializeAudio(format_); audioSend_.push_back(capture); OpusEncoderFilter *encoder = new OpusEncoderFilter("", stats_); encoder->init(format_); audioSend_.push_back(encoder); audioSend_.at(audioSend_.size() - 2)->addOutConnection(audioSend_.back()); audioSend_.back()->start(); } void FilterGraph::checkParticipant(int16_t id) { Q_ASSERT(stats_); Q_ASSERT(id > -1); qDebug() << "Checking participant with id:" << id; if(peers_.size() > (unsigned int)id) { if(peers_.at(id) != 0) { qDebug() << "Filter graph: Peer exists"; return; } else { qDebug() << "Filter graph: Replacing old participant with id:" << id; peers_.at(id) = new Peer; } } else { while(peers_.size() < (unsigned int)id) { peers_.push_back(0); } peers_.push_back(new Peer); qDebug() << "Filter graph: Adding participant to end"; } peers_.at(id)->output = 0; peers_.at(id)->audioFramedSource = 0; peers_.at(id)->videoFramedSource = 0; peers_.at(id)->audioSink = 0; peers_.at(id)->videoSink = 0; } void FilterGraph::sendVideoto(int16_t id, Filter *videoFramedSource) { Q_ASSERT(id > -1); Q_ASSERT(videoFramedSource); qDebug() << "Adding send video for peer:" << id; // make sure we are generating video if(videoSend_.size() < 3) { initVideoSend(resolution_); } // add participant if necessary checkParticipant(id); if(peers_.at(id)->videoFramedSource) { qWarning() << "Warning: We are already sending video to participant."; return; } peers_.at(id)->videoFramedSource = videoFramedSource; videoSend_.back()->addOutConnection(videoFramedSource); } void FilterGraph::receiveVideoFrom(int16_t id, Filter *videoSink, VideoWidget *view) { Q_ASSERT(id > -1); Q_ASSERT(videoSink); // add participant if necessary checkParticipant(id); if(peers_.at(id)->videoSink) { qWarning() << "Warning: We are receiving video from this participant:" << id; return; } peers_.at(id)->videoSink = videoSink; OpenHEVCFilter* decoder = new OpenHEVCFilter(QString::number(id) + "_", stats_); decoder->init(); peers_.at(id)->videoReceive.push_back(decoder); peers_.at(id)->videoSink->addOutConnection(peers_.at(id)->videoReceive.back()); peers_.at(id)->videoReceive.back()->start(); peers_.at(id)->videoReceive.push_back(new YUVtoRGB32(QString::number(id) + "_", stats_)); peers_.at(id)->videoReceive.at(peers_.at(id)->videoReceive.size()-2) ->addOutConnection(peers_.at(id)->videoReceive.back()); peers_.at(id)->videoReceive.back()->start(); peers_.at(id)->videoReceive.push_back(new DisplayFilter(QString::number(id) + "_", stats_, view, id)); peers_.at(id)->videoReceive.at(peers_.at(id)->videoReceive.size()-2) ->addOutConnection(peers_.at(id)->videoReceive.back()); peers_.at(id)->videoReceive.back()->start(); } void FilterGraph::sendAudioTo(int16_t id, Filter* audioFramedSource) { Q_ASSERT(id > -1); Q_ASSERT(audioFramedSource); // just in case it is wanted later. AEC filter has to be attached if(audioSend_.size() == 0) { initAudioSend(); } // add participant if necessary checkParticipant(id); if(peers_.at(id)->audioFramedSource) { qWarning() << "Warning: We are sending audio from to participant:" << id; return; } peers_.at(id)->audioFramedSource = audioFramedSource; audioSend_.back()->addOutConnection(audioFramedSource); } void FilterGraph::receiveAudioFrom(int16_t id, Filter* audioSink) { Q_ASSERT(id > -1); Q_ASSERT(audioSink); // just in case it is wanted later. AEC filter has to be attached if(AEC && audioSend_.size() == 0) { initAudioSend(); } // add participant if necessary checkParticipant(id); if(peers_.at(id)->audioSink) { qWarning() << "Warning: We are receiving video from this participant:" << id; return; } peers_.at(id)->audioSink = audioSink; OpusDecoderFilter *decoder = new OpusDecoderFilter(QString::number(id) + "_", stats_); decoder->init(format_); peers_.at(id)->audioReceive.push_back(decoder); peers_.at(id)->audioSink->addOutConnection(peers_.at(id)->audioReceive.back()); peers_.at(id)->audioReceive.back()->start(); if(audioSend_.size() > 0 && AEC) { peers_.at(id)->audioReceive.push_back(new SpeexAECFilter(QString::number(id) + "_", stats_, format_)); audioSend_.at(0)->addOutConnection(peers_.at(id)->audioReceive.back()); peers_.at(id)->audioReceive.at(peers_.at(id)->audioReceive.size()-2) ->addOutConnection(peers_.at(id)->audioReceive.back()); peers_.at(id)->audioReceive.back()->start(); } else { qWarning() << "WARNING: Did not attach echo cancellation"; } peers_.at(id)->output = new AudioOutput(stats_, id); peers_.at(id)->output->initializeAudio(format_); AudioOutputDevice* outputModule = peers_.at(id)->output->getOutputModule(); outputModule->init(peers_.at(id)->audioReceive.back()); } void FilterGraph::uninit() { for(Peer* p : peers_) { if(p != 0) { destroyPeer(p); p = 0; } } peers_.clear(); destroyFilters(videoSend_); destroyFilters(audioSend_); } void changeState(Filter* f, bool state) { if(state) { f->emptyBuffer(); f->start(); } else { f->stop(); f->emptyBuffer(); while(f->isRunning()) { qSleep(1); } } } void FilterGraph::mic(bool state) { if(audioSend_.size() > 0) { if(!state) { qDebug() << "Stopping microphone"; audioSend_.at(0)->stop(); } else { qDebug() << "Starting microphone"; audioSend_.at(0)->start(); } } } void FilterGraph::camera(bool state) { if(videoSend_.size() > 0) { if(!state) { qDebug() << "Stopping camera"; videoSend_.at(0)->stop(); } else { qDebug() << "Starting camera"; videoSend_.at(0)->start(); } } } void FilterGraph::running(bool state) { for(Filter* f : videoSend_) { changeState(f, state); } for(Filter* f : audioSend_) { changeState(f, state); } for(Peer* p : peers_) { if(p->audioFramedSource) { changeState(p->audioFramedSource, state); } if(p->videoFramedSource) { changeState(p->videoFramedSource, state); } for(Filter* f : p->audioReceive) { changeState(f, state); } for(Filter* f : p->videoReceive) { changeState(f, state); } } } void FilterGraph::destroyFilters(std::vector<Filter*>& filters) { qDebug() << "Destroying filter graph with" << filters.size() << "filters."; for( Filter *f : filters ) { changeState(f, false); delete f; } filters.clear(); } void FilterGraph::destroyPeer(Peer* peer) { if(peer->audioFramedSource) { audioSend_.back()->removeOutConnection(peer->audioFramedSource); //peer->audioFramedSource is destroyed by RTPStreamer peer->audioFramedSource = 0; if(AEC) { audioSend_.at(0)->removeOutConnection(peer->audioReceive.back()); } } if(peer->videoFramedSource) { videoSend_.back()->removeOutConnection(peer->videoFramedSource); //peer->videoFramedSource is destroyed by RTPStreamer peer->videoFramedSource = 0; } if(peer->audioSink) { peer->audioSink->removeOutConnection(peer->audioReceive.front()); } if(peer->videoSink) { peer->videoSink->removeOutConnection(peer->videoReceive.front()); } destroyFilters(peer->audioReceive); destroyFilters(peer->videoReceive); if(peer->output) { delete peer->output; peer->output = 0; } delete peer; } void FilterGraph::removeParticipant(int16_t id) { qDebug() << "Removing peer index:" << id << "/" << peers_.size(); Q_ASSERT(id < peers_.size()); if(peers_.at(id) != NULL) destroyPeer(peers_.at(id)); peers_.at(id) = NULL; } void FilterGraph::print() { QString audioDotFile = "digraph AudioGraph {\r\n"; for(auto f : audioSend_) { audioDotFile += f->printOutputs(); } for(unsigned int i = 0; i <peers_.size(); ++i) { for(auto f : peers_.at(i)->audioReceive) { audioDotFile += f->printOutputs(); } audioDotFile += peers_.at(i)->audioSink->printOutputs(); audioDotFile += peers_.at(i)->audioFramedSource->printOutputs(); } audioDotFile += "}"; qDebug() << audioDotFile; QString videoDotFile = "digraph VideoGraph {\r\n"; for(auto f : videoSend_) { videoDotFile += f->printOutputs(); } for(unsigned int i = 0; i <peers_.size(); ++i) { for(auto f : peers_.at(i)->videoReceive) { videoDotFile += f->printOutputs(); } videoDotFile += peers_.at(i)->videoSink->printOutputs(); videoDotFile += peers_.at(i)->videoFramedSource->printOutputs(); } videoDotFile += "}"; qDebug() << videoDotFile; QString aFilename="audiograph.dot"; QFile aFile( aFilename ); if ( aFile.open(QIODevice::WriteOnly) ) { QTextStream stream( &aFile ); stream << audioDotFile << endl; } QString vFilename="videograph.dot"; QFile vFile( vFilename ); if ( vFile.open(QIODevice::WriteOnly) ) { QTextStream stream( &vFile ); stream << videoDotFile << endl; } } <commit_msg>Added checks to filter graph for removed peer. This fixed a bug of crashing after the remote participant had quit.<commit_after>#include "filtergraph.h" #include "camerafilter.h" #include "kvazaarfilter.h" #include "rgb32toyuv.h" #include "openhevcfilter.h" #include "yuvtorgb32.h" #include "framedsourcefilter.h" #include "rtpsinkfilter.h" #include "displayfilter.h" #include "audiocapturefilter.h" #include "audiooutputdevice.h" #include "audiooutput.h" #include "opusencoderfilter.h" #include "opusdecoderfilter.h" #include "speexaecfilter.h" #include "common.h" FilterGraph::FilterGraph(StatisticsInterface* stats): peers_(), videoSend_(), audioSend_(), selfView_(NULL), stats_(stats), format_() { Q_ASSERT(stats); // TODO negotiate these values with all included filters format_.setSampleRate(48000); format_.setChannelCount(2); format_.setSampleSize(16); format_.setSampleType(QAudioFormat::SignedInt); format_.setByteOrder(QAudioFormat::LittleEndian); format_.setCodec("audio/pcm"); } void FilterGraph::init(VideoWidget* selfView, QSize resolution) { resolution_ = resolution; selfView_ = selfView; frameRate_ = 30; initSelfView(selfView, resolution); } void FilterGraph::initSelfView(VideoWidget *selfView, QSize resolution) { if(videoSend_.size() > 0) { destroyFilters(videoSend_); } // Sending video graph videoSend_.push_back(new CameraFilter("", stats_, resolution)); if(selfView) { // connect selfview to camera DisplayFilter* selfviewFilter = new DisplayFilter("Self_", stats_, selfView, 1111); selfviewFilter->setProperties(true); videoSend_.push_back(selfviewFilter); videoSend_.at(0)->addOutConnection(videoSend_.back()); videoSend_.back()->start(); } } void FilterGraph::initVideoSend(QSize resolution) { if(videoSend_.size() != 2) { if(videoSend_.size() > 2) { destroyFilters(videoSend_); } initSelfView(selfView_, resolution_); } videoSend_.push_back(new RGB32toYUV("", stats_)); videoSend_.at(0)->addOutConnection(videoSend_.back()); // attach to camera videoSend_.back()->start(); KvazaarFilter* kvz = new KvazaarFilter("", stats_); kvz->init(resolution, frameRate_, 1); videoSend_.push_back(kvz); videoSend_.at(videoSend_.size() - 2)->addOutConnection(videoSend_.back()); videoSend_.back()->start(); } void FilterGraph::initAudioSend() { // Do this before adding participants, otherwise AEC filter wont get attached AudioCaptureFilter* capture = new AudioCaptureFilter("", stats_); capture->initializeAudio(format_); audioSend_.push_back(capture); OpusEncoderFilter *encoder = new OpusEncoderFilter("", stats_); encoder->init(format_); audioSend_.push_back(encoder); audioSend_.at(audioSend_.size() - 2)->addOutConnection(audioSend_.back()); audioSend_.back()->start(); } void FilterGraph::checkParticipant(int16_t id) { Q_ASSERT(stats_); Q_ASSERT(id > -1); qDebug() << "Checking participant with id:" << id; if(peers_.size() > (unsigned int)id) { if(peers_.at(id) != NULL) { qDebug() << "Filter graph: Peer exists"; return; } else { qDebug() << "Filter graph: Replacing old participant with id:" << id; peers_.at(id) = new Peer; } } else { while(peers_.size() < (unsigned int)id) { peers_.push_back(0); } peers_.push_back(new Peer); qDebug() << "Filter graph: Adding participant to end"; } peers_.at(id)->output = 0; peers_.at(id)->audioFramedSource = 0; peers_.at(id)->videoFramedSource = 0; peers_.at(id)->audioSink = 0; peers_.at(id)->videoSink = 0; } void FilterGraph::sendVideoto(int16_t id, Filter *videoFramedSource) { Q_ASSERT(id > -1); Q_ASSERT(videoFramedSource); qDebug() << "Adding send video for peer:" << id; // make sure we are generating video if(videoSend_.size() < 3) { initVideoSend(resolution_); } // add participant if necessary checkParticipant(id); if(peers_.at(id)->videoFramedSource) { qWarning() << "Warning: We are already sending video to participant."; return; } peers_.at(id)->videoFramedSource = videoFramedSource; videoSend_.back()->addOutConnection(videoFramedSource); } void FilterGraph::receiveVideoFrom(int16_t id, Filter *videoSink, VideoWidget *view) { Q_ASSERT(id > -1); Q_ASSERT(videoSink); // add participant if necessary checkParticipant(id); if(peers_.at(id)->videoSink) { qWarning() << "Warning: We are receiving video from this participant:" << id; return; } peers_.at(id)->videoSink = videoSink; OpenHEVCFilter* decoder = new OpenHEVCFilter(QString::number(id) + "_", stats_); decoder->init(); peers_.at(id)->videoReceive.push_back(decoder); peers_.at(id)->videoSink->addOutConnection(peers_.at(id)->videoReceive.back()); peers_.at(id)->videoReceive.back()->start(); peers_.at(id)->videoReceive.push_back(new YUVtoRGB32(QString::number(id) + "_", stats_)); peers_.at(id)->videoReceive.at(peers_.at(id)->videoReceive.size()-2) ->addOutConnection(peers_.at(id)->videoReceive.back()); peers_.at(id)->videoReceive.back()->start(); peers_.at(id)->videoReceive.push_back(new DisplayFilter(QString::number(id) + "_", stats_, view, id)); peers_.at(id)->videoReceive.at(peers_.at(id)->videoReceive.size()-2) ->addOutConnection(peers_.at(id)->videoReceive.back()); peers_.at(id)->videoReceive.back()->start(); } void FilterGraph::sendAudioTo(int16_t id, Filter* audioFramedSource) { Q_ASSERT(id > -1); Q_ASSERT(audioFramedSource); // just in case it is wanted later. AEC filter has to be attached if(audioSend_.size() == 0) { initAudioSend(); } // add participant if necessary checkParticipant(id); if(peers_.at(id)->audioFramedSource) { qWarning() << "Warning: We are sending audio from to participant:" << id; return; } peers_.at(id)->audioFramedSource = audioFramedSource; audioSend_.back()->addOutConnection(audioFramedSource); } void FilterGraph::receiveAudioFrom(int16_t id, Filter* audioSink) { Q_ASSERT(id > -1); Q_ASSERT(audioSink); // just in case it is wanted later. AEC filter has to be attached if(AEC && audioSend_.size() == 0) { initAudioSend(); } // add participant if necessary checkParticipant(id); if(peers_.at(id)->audioSink) { qWarning() << "Warning: We are receiving video from this participant:" << id; return; } peers_.at(id)->audioSink = audioSink; OpusDecoderFilter *decoder = new OpusDecoderFilter(QString::number(id) + "_", stats_); decoder->init(format_); peers_.at(id)->audioReceive.push_back(decoder); peers_.at(id)->audioSink->addOutConnection(peers_.at(id)->audioReceive.back()); peers_.at(id)->audioReceive.back()->start(); if(audioSend_.size() > 0 && AEC) { peers_.at(id)->audioReceive.push_back(new SpeexAECFilter(QString::number(id) + "_", stats_, format_)); audioSend_.at(0)->addOutConnection(peers_.at(id)->audioReceive.back()); peers_.at(id)->audioReceive.at(peers_.at(id)->audioReceive.size()-2) ->addOutConnection(peers_.at(id)->audioReceive.back()); peers_.at(id)->audioReceive.back()->start(); } else { qWarning() << "WARNING: Did not attach echo cancellation"; } peers_.at(id)->output = new AudioOutput(stats_, id); peers_.at(id)->output->initializeAudio(format_); AudioOutputDevice* outputModule = peers_.at(id)->output->getOutputModule(); outputModule->init(peers_.at(id)->audioReceive.back()); } void FilterGraph::uninit() { for(Peer* p : peers_) { if(p != NULL) { destroyPeer(p); p = 0; } } peers_.clear(); destroyFilters(videoSend_); destroyFilters(audioSend_); } void changeState(Filter* f, bool state) { if(state) { f->emptyBuffer(); f->start(); } else { f->stop(); f->emptyBuffer(); while(f->isRunning()) { qSleep(1); } } } void FilterGraph::mic(bool state) { if(audioSend_.size() > 0) { if(!state) { qDebug() << "Stopping microphone"; audioSend_.at(0)->stop(); } else { qDebug() << "Starting microphone"; audioSend_.at(0)->start(); } } } void FilterGraph::camera(bool state) { if(videoSend_.size() > 0) { if(!state) { qDebug() << "Stopping camera"; videoSend_.at(0)->stop(); } else { qDebug() << "Starting camera"; videoSend_.at(0)->start(); } } } void FilterGraph::running(bool state) { for(Filter* f : videoSend_) { changeState(f, state); } for(Filter* f : audioSend_) { changeState(f, state); } for(Peer* p : peers_) { if(p != NULL) { if(p->audioFramedSource) { changeState(p->audioFramedSource, state); } if(p->videoFramedSource) { changeState(p->videoFramedSource, state); } for(Filter* f : p->audioReceive) { changeState(f, state); } for(Filter* f : p->videoReceive) { changeState(f, state); } } } } void FilterGraph::destroyFilters(std::vector<Filter*>& filters) { qDebug() << "Destroying filter graph with" << filters.size() << "filters."; for( Filter *f : filters ) { changeState(f, false); delete f; } filters.clear(); } void FilterGraph::destroyPeer(Peer* peer) { if(peer->audioFramedSource) { audioSend_.back()->removeOutConnection(peer->audioFramedSource); //peer->audioFramedSource is destroyed by RTPStreamer peer->audioFramedSource = 0; if(AEC) { audioSend_.at(0)->removeOutConnection(peer->audioReceive.back()); } } if(peer->videoFramedSource) { videoSend_.back()->removeOutConnection(peer->videoFramedSource); //peer->videoFramedSource is destroyed by RTPStreamer peer->videoFramedSource = 0; } if(peer->audioSink) { peer->audioSink->removeOutConnection(peer->audioReceive.front()); } if(peer->videoSink) { peer->videoSink->removeOutConnection(peer->videoReceive.front()); } destroyFilters(peer->audioReceive); destroyFilters(peer->videoReceive); if(peer->output) { delete peer->output; peer->output = 0; } delete peer; } void FilterGraph::removeParticipant(int16_t id) { qDebug() << "Removing peer index:" << id << "/" << peers_.size(); Q_ASSERT(id < peers_.size()); if(peers_.at(id) != NULL) destroyPeer(peers_.at(id)); peers_.at(id) = NULL; } void FilterGraph::print() { QString audioDotFile = "digraph AudioGraph {\r\n"; for(auto f : audioSend_) { audioDotFile += f->printOutputs(); } for(unsigned int i = 0; i <peers_.size(); ++i) { if(peers_.at(i) != NULL) { for(auto f : peers_.at(i)->audioReceive) { audioDotFile += f->printOutputs(); } audioDotFile += peers_.at(i)->audioSink->printOutputs(); audioDotFile += peers_.at(i)->audioFramedSource->printOutputs(); } } audioDotFile += "}"; qDebug() << audioDotFile; QString videoDotFile = "digraph VideoGraph {\r\n"; for(auto f : videoSend_) { videoDotFile += f->printOutputs(); } for(unsigned int i = 0; i <peers_.size(); ++i) { if(peers_.at(i) != NULL) { for(auto f : peers_.at(i)->videoReceive) { videoDotFile += f->printOutputs(); } videoDotFile += peers_.at(i)->videoSink->printOutputs(); videoDotFile += peers_.at(i)->videoFramedSource->printOutputs(); } } videoDotFile += "}"; qDebug() << videoDotFile; QString aFilename="audiograph.dot"; QFile aFile( aFilename ); if ( aFile.open(QIODevice::WriteOnly) ) { QTextStream stream( &aFile ); stream << audioDotFile << endl; } QString vFilename="videograph.dot"; QFile vFile( vFilename ); if ( vFile.open(QIODevice::WriteOnly) ) { QTextStream stream( &vFile ); stream << videoDotFile << endl; } } <|endoftext|>
<commit_before>//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool implements a just-in-time compiler for LLVM, allowing direct // execution of LLVM bytecode in an efficient manner. // //===----------------------------------------------------------------------===// #include "JIT.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/ModuleProvider.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetJITInfo.h" #include "Support/DynamicLinker.h" #include <iostream> using namespace llvm; JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji) : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) { setTargetData(TM.getTargetData()); // Initialize MCE MCE = createEmitter(*this); // Add target data PM.add (new TargetData (TM.getTargetData ())); // Compile LLVM Code down to machine code in the intermediate representation TJI.addPassesToJITCompile(PM); // Turn the machine code intermediate representation into bytes in memory that // may be executed. if (TM.addPassesToEmitMachineCode(PM, *MCE)) { std::cerr << "lli: target '" << TM.getName() << "' doesn't support machine code emission!\n"; abort(); } } JIT::~JIT() { delete MCE; delete &TM; } /// run - Start execution with the specified function and arguments. /// GenericValue JIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); GenericValue rv; void *FPtr = getPointerToFunction(F); assert(PFtr && "Pointer to fn's code was null after getPointerToFunction"); if (ArgValues.size() == 3) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))FPtr; // Call the function. rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2])); return rv; } else if (ArgValues.size() == 1) { int (*PF)(int) = (int(*)(int))FPtr; rv.IntVal = PF(ArgValues[0].IntVal); return rv; } // FIXME: This code should handle a couple of common cases efficiently, but // it should also implement the general case by code-gening a new anonymous // nullary function to call. std::cerr << "Sorry, unimplemented feature in the LLVM JIT. See LLVM" << " PR#419\n for details.\n"; abort(); return rv; } /// runJITOnFunction - Run the FunctionPassManager full of /// just-in-time compilation passes on F, hopefully filling in /// GlobalAddress[F] with the address of F's machine code. /// void JIT::runJITOnFunction(Function *F) { static bool isAlreadyCodeGenerating = false; assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!"); // JIT the function isAlreadyCodeGenerating = true; PM.run(*F); isAlreadyCodeGenerating = false; // If the function referred to a global variable that had not yet been // emitted, it allocates memory for the global, but doesn't emit it yet. Emit // all of these globals now. while (!PendingGlobals.empty()) { const GlobalVariable *GV = PendingGlobals.back(); PendingGlobals.pop_back(); EmitGlobalVariable(GV); } } /// getPointerToFunction - This method is used to get the address of the /// specified function, compiling it if neccesary. /// void *JIT::getPointerToFunction(Function *F) { if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // Check if function already code gen'd // Make sure we read in the function if it exists in this Module try { MP->materializeFunction(F); } catch ( std::string& errmsg ) { std::cerr << "Error reading bytecode file: " << errmsg << "\n"; abort(); } catch (...) { std::cerr << "Error reading bytecode file!\n"; abort(); } if (F->isExternal()) { void *Addr = getPointerToNamedFunction(F->getName()); addGlobalMapping(F, Addr); return Addr; } runJITOnFunction(F); void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); return Addr; } // getPointerToFunctionOrStub - If the specified function has been // code-gen'd, return a pointer to the function. If not, compile it, or use // a stub to implement lazy compilation if available. // void *JIT::getPointerToFunctionOrStub(Function *F) { // If we have already code generated the function, just return the address. if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // If the target supports "stubs" for functions, get a stub now. if (void *Ptr = TJI.getJITStubForFunction(F, *MCE)) return Ptr; // Otherwise, if the target doesn't support it, just codegen the function. return getPointerToFunction(F); } /// getOrEmitGlobalVariable - Return the address of the specified global /// variable, possibly emitting it to memory if needed. This is used by the /// Emitter. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) { void *Ptr = getPointerToGlobalIfAvailable(GV); if (Ptr) return Ptr; // If the global is external, just remember the address. if (GV->isExternal()) { Ptr = GetAddressOfSymbol(GV->getName().c_str()); if (Ptr == 0) { std::cerr << "Could not resolve external global address: " << GV->getName() << "\n"; abort(); } } else { // If the global hasn't been emitted to memory yet, allocate space. We will // actually initialize the global after current function has finished // compilation. Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())]; PendingGlobals.push_back(GV); } addGlobalMapping(GV, Ptr); return Ptr; } /// recompileAndRelinkFunction - This method is used to force a function /// which has already been compiled, to be compiled again, possibly /// after it has been modified. Then the entry to the old copy is overwritten /// with a branch to the new copy. If there was no old copy, this acts /// just like JIT::getPointerToFunction(). /// void *JIT::recompileAndRelinkFunction(Function *F) { void *OldAddr = getPointerToGlobalIfAvailable(F); // If it's not already compiled there is no reason to patch it up. if (OldAddr == 0) { return getPointerToFunction(F); } // Delete the old function mapping. addGlobalMapping(F, 0); // Recodegen the function runJITOnFunction(F); // Update state, forward the old function to the new function. void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); TJI.replaceMachineCodeForFunction(OldAddr, Addr); return Addr; } <commit_msg>Handle zero arg function case<commit_after>//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tool implements a just-in-time compiler for LLVM, allowing direct // execution of LLVM bytecode in an efficient manner. // //===----------------------------------------------------------------------===// #include "JIT.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/ModuleProvider.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetJITInfo.h" #include "Support/DynamicLinker.h" #include <iostream> using namespace llvm; JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji) : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) { setTargetData(TM.getTargetData()); // Initialize MCE MCE = createEmitter(*this); // Add target data PM.add (new TargetData (TM.getTargetData ())); // Compile LLVM Code down to machine code in the intermediate representation TJI.addPassesToJITCompile(PM); // Turn the machine code intermediate representation into bytes in memory that // may be executed. if (TM.addPassesToEmitMachineCode(PM, *MCE)) { std::cerr << "lli: target '" << TM.getName() << "' doesn't support machine code emission!\n"; abort(); } } JIT::~JIT() { delete MCE; delete &TM; } /// run - Start execution with the specified function and arguments. /// GenericValue JIT::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert(F && "Function *F was null at entry to run()"); GenericValue rv; void *FPtr = getPointerToFunction(F); assert(FPtr && "Pointer to fn's code was null after getPointerToFunction"); if (ArgValues.size() == 3) { int (*PF)(int, char **, const char **) = (int(*)(int, char **, const char **))FPtr; // Call the function. rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]), (const char **)GVTOP(ArgValues[2])); return rv; } else if (ArgValues.size() == 1) { int (*PF)(int) = (int(*)(int))FPtr; rv.IntVal = PF(ArgValues[0].IntVal); return rv; } else if (ArgValues.size() == 0) { int (*PF)() = (int(*)())FPtr; rv.IntVal = PF(); return rv; } // FIXME: This code should handle a couple of common cases efficiently, but // it should also implement the general case by code-gening a new anonymous // nullary function to call. std::cerr << "Sorry, unimplemented feature in the LLVM JIT. See LLVM" << " PR#419\n for details.\n"; abort(); return rv; } /// runJITOnFunction - Run the FunctionPassManager full of /// just-in-time compilation passes on F, hopefully filling in /// GlobalAddress[F] with the address of F's machine code. /// void JIT::runJITOnFunction(Function *F) { static bool isAlreadyCodeGenerating = false; assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!"); // JIT the function isAlreadyCodeGenerating = true; PM.run(*F); isAlreadyCodeGenerating = false; // If the function referred to a global variable that had not yet been // emitted, it allocates memory for the global, but doesn't emit it yet. Emit // all of these globals now. while (!PendingGlobals.empty()) { const GlobalVariable *GV = PendingGlobals.back(); PendingGlobals.pop_back(); EmitGlobalVariable(GV); } } /// getPointerToFunction - This method is used to get the address of the /// specified function, compiling it if neccesary. /// void *JIT::getPointerToFunction(Function *F) { if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // Check if function already code gen'd // Make sure we read in the function if it exists in this Module try { MP->materializeFunction(F); } catch ( std::string& errmsg ) { std::cerr << "Error reading bytecode file: " << errmsg << "\n"; abort(); } catch (...) { std::cerr << "Error reading bytecode file!\n"; abort(); } if (F->isExternal()) { void *Addr = getPointerToNamedFunction(F->getName()); addGlobalMapping(F, Addr); return Addr; } runJITOnFunction(F); void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); return Addr; } // getPointerToFunctionOrStub - If the specified function has been // code-gen'd, return a pointer to the function. If not, compile it, or use // a stub to implement lazy compilation if available. // void *JIT::getPointerToFunctionOrStub(Function *F) { // If we have already code generated the function, just return the address. if (void *Addr = getPointerToGlobalIfAvailable(F)) return Addr; // If the target supports "stubs" for functions, get a stub now. if (void *Ptr = TJI.getJITStubForFunction(F, *MCE)) return Ptr; // Otherwise, if the target doesn't support it, just codegen the function. return getPointerToFunction(F); } /// getOrEmitGlobalVariable - Return the address of the specified global /// variable, possibly emitting it to memory if needed. This is used by the /// Emitter. void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) { void *Ptr = getPointerToGlobalIfAvailable(GV); if (Ptr) return Ptr; // If the global is external, just remember the address. if (GV->isExternal()) { Ptr = GetAddressOfSymbol(GV->getName().c_str()); if (Ptr == 0) { std::cerr << "Could not resolve external global address: " << GV->getName() << "\n"; abort(); } } else { // If the global hasn't been emitted to memory yet, allocate space. We will // actually initialize the global after current function has finished // compilation. Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())]; PendingGlobals.push_back(GV); } addGlobalMapping(GV, Ptr); return Ptr; } /// recompileAndRelinkFunction - This method is used to force a function /// which has already been compiled, to be compiled again, possibly /// after it has been modified. Then the entry to the old copy is overwritten /// with a branch to the new copy. If there was no old copy, this acts /// just like JIT::getPointerToFunction(). /// void *JIT::recompileAndRelinkFunction(Function *F) { void *OldAddr = getPointerToGlobalIfAvailable(F); // If it's not already compiled there is no reason to patch it up. if (OldAddr == 0) { return getPointerToFunction(F); } // Delete the old function mapping. addGlobalMapping(F, 0); // Recodegen the function runJITOnFunction(F); // Update state, forward the old function to the new function. void *Addr = getPointerToGlobalIfAvailable(F); assert(Addr && "Code generation didn't add function to GlobalAddress table!"); TJI.replaceMachineCodeForFunction(OldAddr, Addr); return Addr; } <|endoftext|>
<commit_before>#ifndef _adb97dcb_a440_45a7_a9d4_3b33e43100d4 #define _adb97dcb_a440_45a7_a9d4_3b33e43100d4 #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #pragma GCC diagnostic ignored "-Wuninitialized" #endif namespace fn { template<typename T> class optional; namespace fn_ { /* * remove reference from a type, similar to std::remove_reference */ template<class R> struct remove_reference {typedef R T;}; template<class R> struct remove_reference<R&> {typedef R T;}; template<class R> struct remove_reference<R&&> {typedef R T;}; /* * cast to rvalue reference, similar to std::move */ template <class T> typename remove_reference<T>::T&& move(T&& a) { return ((typename remove_reference<T>::T&&)a); } template<typename T> class optional_ref; template<typename T> class optional_value; template<typename T> struct return_cast; /* * This helper allows for easier usage of a functions return type * in a type deduction context. * Additionally it works around a strange msvc internal compiler error. */ template<class F, class T> static auto return_type(F&& f,T&& value)->decltype(f(value)) { return f(value); } template<typename T> class optional_base { public: typedef T Type; bool valid() const { return !!value; } protected: optional_base(T* const p): value(p) {} private: friend class optional<T const&>; friend class optional<T const>; friend class optional<T&>; friend class optional<T>; friend class optional_value<T>; friend class optional_ref<T>; T* value = nullptr; public: template<typename F> T operator|(F fallback) const { return valid() ? *value : fallback; } bool operator==(T const& other_value) const { return valid() && (*value == other_value); } bool operator!=(T const& other_value) const { return !((*this) == other_value); } bool operator==(optional_base const& other) const { return (valid() && other.valid()) && (*value == *other.value); } bool operator!=(optional_base const& other) const { return !(*this == other); } template<typename EmptyF> auto operator||(EmptyF const& handle_no_value) const ->decltype(handle_no_value()) { if(!valid()){ return handle_no_value(); } else { return return_cast<decltype(handle_no_value())>::value(*value); } } T operator~() const { return (*this) | T{}; } }; template<typename T> class optional_value : public optional_base<T> { friend class optional<T>; friend class optional<T const>; friend class optional<T const&>; friend class optional<T&>; using optional_base<T>::value; protected: unsigned char value_mem[sizeof(T)]; optional_value(): optional_base<T>(nullptr) {} optional_value(T* v) : optional_base<T>(v) {} ~optional_value() { if(optional_base<T>::valid()){ reinterpret_cast<T*>(value_mem)->~T(); } } public: using optional_base<T>::valid; template<typename ValueF> auto operator>>(ValueF const& handle_value) const ->decltype( return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value) ) { if(valid()){ return return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value); } else{ return {}; } } }; template<typename T> class optional_ref : public optional_base<T> { friend class optional<T>; friend class optional<T const>; friend class optional<T const&>; friend class optional<T&>; using optional_base<T>::value; protected: optional_ref(): optional_base<T>(nullptr) {} optional_ref(T* v): optional_base<T>(v) {} optional_ref(T&& value): optional_base<T>(true,value) {} public: template<typename F> T& operator|(F& fallback) const { if(optional_base<T>::valid()){ return *optional_base<T>::value; } else{ return fallback; } } template<typename F> T operator|(F const& fallback) const { if(optional_base<T>::valid()){ return *optional_base<T>::value; } else{ return fallback; } } optional_ref& operator=(optional_ref const& other) { optional_base<T>::value = other.value; return *this; } public: using optional_base<T>::valid; template<typename ValueF> auto operator>>( ValueF const& handle_value) const ->decltype( return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value) ) { if(valid()){ return return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value); } else{ return {}; } } }; } template<typename T> class optional final : public fn_::optional_value<T> { using fn_::optional_value<T>::value_mem; friend class optional<T const>; friend class optional<T const&>; friend class optional<T&>; public: optional(): fn_::optional_value<T>() {} optional(T&& v): fn_::optional_value<T>(reinterpret_cast<T*>(value_mem)) { new (value_mem) T{fn_::move(v)}; } optional(optional<T>&& original): fn_::optional_value<T>( original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr ) { if(original.valid()){ new (value_mem) T{fn_::move(*original.value)}; original.value = nullptr; reinterpret_cast<T*>(original.value_mem)->~T(); } } optional& operator=(optional&& other) { if(other.valid()){ if(fn_::optional_value<T>::valid()){ *fn_::optional_value<T>::value = fn_::move(*other.value); } else{ new (value_mem) T{fn_::move(*other.value)}; fn_::optional_value<T>::value = reinterpret_cast<T*>(value_mem); } } else{ if(fn_::optional_value<T>::valid()){ reinterpret_cast<T*>(value_mem)->~T(); } fn_::optional_value<T>::value = nullptr; } return *this; } optional& operator=(optional const& other) { if(other.valid()){ if(fn_::optional_value<T>::valid()){ *fn_::optional_value<T>::value = *other.value; } else{ new (value_mem) T{*other.value}; fn_::optional_value<T>::value = reinterpret_cast<T*>(value_mem); } } else{ if(fn_::optional_value<T>::valid()){ reinterpret_cast<T*>(value_mem)->~T(); } fn_::optional_value<T>::value = nullptr; } return *this; } optional(T const& v): fn_::optional_value<T>(reinterpret_cast<T*>(value_mem)) { new (value_mem) T{v}; } optional(optional<T&> const& original): fn_::optional_value<T>( original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr ) { original >>[&](T const& v){ new (value_mem) T{v};}; } optional(optional<T const&> const& original): fn_::optional_value<T>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } optional(optional<T const> const& original): fn_::optional_value<T>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } optional(optional<T> const& original): fn_::optional_value<T>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } }; template<typename T> class optional<T const> final : public fn_::optional_value<T const> { using fn_::optional_value<T const>::value_mem; friend class optional<T>; public: optional(): fn_::optional_value<T const>() {} optional(T const& v): fn_::optional_value<T const>(reinterpret_cast<T*>(value_mem)) { new (value_mem) T{v}; } optional(optional<T>&& original): fn_::optional_value<T const>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { if(original.valid()){ new (value_mem) T{fn_::move(*original.value)}; original.value = nullptr; reinterpret_cast<T*>(value_mem)->~T(); } } optional(optional<T> const& original): fn_::optional_value<T const>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } optional(optional<T&> const& original): fn_::optional_value<T const>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } }; template<typename T> class optional<T&> final : public fn_::optional_ref<T> { friend class optional<T const&>; friend class optional<T const>; friend class optional<T>; public: optional(): fn_::optional_ref<T>() {} optional(T& v): fn_::optional_ref<T>(&v) {} optional(optional<T> const& original): fn_::optional_ref<T>(original.value) {} }; template<typename T> class optional<T const&> final : public fn_::optional_ref<T const> { friend class optional<T const>; friend class optional<T>; public: optional(): fn_::optional_ref<T const>() {} optional(T const& v): fn_::optional_ref<T const>(&v) {} optional(optional<T> const& original): fn_::optional_ref<T const>(original.value) {} optional(optional<T&> const& original): fn_::optional_ref<T const>(original.value) {} }; template<> class optional<void> final { bool no_value; public: optional(): no_value(true) {} optional(bool): no_value(false) {} template<typename EmptyF> void operator||(EmptyF const& handle_no_value) const { if(no_value){ return handle_no_value(); } } }; namespace fn_ { /* * Convert a functions return value to an optional. * This is needed for optional handler chaining. * In particular a specialization is implemented that * avoids getting optional<optional<T>>. */ template<typename T> struct return_cast { template<typename F,typename V> static optional<T> func(F&& f,V&& v) {return f(v);} template<typename V> static T value(V&& v) {return v;} }; template<> struct return_cast<void> { template<typename F,typename V> static optional<void> func(F&& f,V&& v) {f(v); return true;} template<typename V> static void value(V&&) {} }; template<typename T> struct return_cast<optional<T>> { template<typename F,typename V> static optional<T> func(F&& f,V&& v) {return f(v);} template<typename V> static T value(V&& v) {return v;} }; } } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #endif <commit_msg>fix some constuctor calls<commit_after>#ifndef _adb97dcb_a440_45a7_a9d4_3b33e43100d4 #define _adb97dcb_a440_45a7_a9d4_3b33e43100d4 #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #pragma GCC diagnostic ignored "-Wuninitialized" #endif namespace fn { template<typename T> class optional; namespace fn_ { /* * remove reference from a type, similar to std::remove_reference */ template<class R> struct remove_reference {typedef R T;}; template<class R> struct remove_reference<R&> {typedef R T;}; template<class R> struct remove_reference<R&&> {typedef R T;}; /* * cast to rvalue reference, similar to std::move */ template <class T> typename remove_reference<T>::T&& move(T&& a) { return ((typename remove_reference<T>::T&&)a); } template<typename T> class optional_ref; template<typename T> class optional_value; template<typename T> struct return_cast; /* * This helper allows for easier usage of a functions return type * in a type deduction context. * Additionally it works around a strange msvc internal compiler error. */ template<class F, class T> static auto return_type(F&& f,T&& value)->decltype(f(value)) { return f(value); } template<typename T> class optional_base { public: typedef T Type; bool valid() const { return !!value; } protected: optional_base(T* const p): value(p) {} private: friend class optional<T const&>; friend class optional<T const>; friend class optional<T&>; friend class optional<T>; friend class optional_value<T>; friend class optional_ref<T>; T* value = nullptr; public: template<typename F> T operator|(F fallback) const { return valid() ? *value : fallback; } bool operator==(T const& other_value) const { return valid() && (*value == other_value); } bool operator!=(T const& other_value) const { return !((*this) == other_value); } bool operator==(optional_base const& other) const { return (valid() && other.valid()) && (*value == *other.value); } bool operator!=(optional_base const& other) const { return !(*this == other); } template<typename EmptyF> auto operator||(EmptyF const& handle_no_value) const ->decltype(handle_no_value()) { if(!valid()){ return handle_no_value(); } else { return return_cast<decltype(handle_no_value())>::value(*value); } } T operator~() const { return (*this) | T{}; } }; template<typename T> class optional_value : public optional_base<T> { friend class optional<T>; friend class optional<T const>; friend class optional<T const&>; friend class optional<T&>; using optional_base<T>::value; protected: unsigned char value_mem[sizeof(T)]; optional_value(): optional_base<T>(nullptr) {} optional_value(T* v) : optional_base<T>(v) {} ~optional_value() { if(optional_base<T>::valid()){ reinterpret_cast<T*>(value_mem)->~T(); } } public: using optional_base<T>::valid; template<typename ValueF> auto operator>>(ValueF const& handle_value) const ->decltype( return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value) ) { if(valid()){ return return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value); } else{ return {}; } } }; template<typename T> class optional_ref : public optional_base<T> { friend class optional<T>; friend class optional<T const>; friend class optional<T const&>; friend class optional<T&>; using optional_base<T>::value; protected: optional_ref(): optional_base<T>(nullptr) {} optional_ref(T* v): optional_base<T>(v) {} optional_ref(T&& value): optional_base<T>(true,value) {} public: template<typename F> T& operator|(F& fallback) const { if(optional_base<T>::valid()){ return *optional_base<T>::value; } else{ return fallback; } } template<typename F> T operator|(F const& fallback) const { if(optional_base<T>::valid()){ return *optional_base<T>::value; } else{ return fallback; } } optional_ref& operator=(optional_ref const& other) { optional_base<T>::value = other.value; return *this; } public: using optional_base<T>::valid; template<typename ValueF> auto operator>>( ValueF const& handle_value) const ->decltype( return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value) ) { if(valid()){ return return_cast< decltype(return_type(handle_value,*value)) >::func(handle_value,*value); } else{ return {}; } } }; } template<typename T> class optional final : public fn_::optional_value<T> { using fn_::optional_value<T>::value_mem; friend class optional<T const>; friend class optional<T const&>; friend class optional<T&>; public: optional(): fn_::optional_value<T>() {} optional(T&& v): fn_::optional_value<T>(reinterpret_cast<T*>(value_mem)) { new (value_mem) T(fn_::move(v)); } optional(optional<T>&& original): fn_::optional_value<T>( original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr ) { if(original.valid()){ new (value_mem) T(fn_::move(*original.value)); original.value = nullptr; reinterpret_cast<T*>(original.value_mem)->~T(); } } optional& operator=(optional&& other) { if(other.valid()){ if(fn_::optional_value<T>::valid()){ *fn_::optional_value<T>::value = fn_::move(*other.value); } else{ new (value_mem) T(fn_::move(*other.value)); fn_::optional_value<T>::value = reinterpret_cast<T*>(value_mem); } } else{ if(fn_::optional_value<T>::valid()){ reinterpret_cast<T*>(value_mem)->~T(); } fn_::optional_value<T>::value = nullptr; } return *this; } optional& operator=(optional const& other) { if(other.valid()){ if(fn_::optional_value<T>::valid()){ *fn_::optional_value<T>::value = *other.value; } else{ new (value_mem) T{*other.value}; fn_::optional_value<T>::value = reinterpret_cast<T*>(value_mem); } } else{ if(fn_::optional_value<T>::valid()){ reinterpret_cast<T*>(value_mem)->~T(); } fn_::optional_value<T>::value = nullptr; } return *this; } optional(T const& v): fn_::optional_value<T>(reinterpret_cast<T*>(value_mem)) { new (value_mem) T{v}; } optional(optional<T&> const& original): fn_::optional_value<T>( original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr ) { original >>[&](T const& v){ new (value_mem) T(v);}; } optional(optional<T const&> const& original): fn_::optional_value<T>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T(v);}; } optional(optional<T const> const& original): fn_::optional_value<T>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T(v);}; } optional(optional<T> const& original): fn_::optional_value<T>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T(v);}; } }; template<typename T> class optional<T const> final : public fn_::optional_value<T const> { using fn_::optional_value<T const>::value_mem; friend class optional<T>; public: optional(): fn_::optional_value<T const>() {} optional(T const& v): fn_::optional_value<T const>(reinterpret_cast<T*>(value_mem)) { new (value_mem) T{v}; } optional(optional<T>&& original): fn_::optional_value<T const>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { if(original.valid()){ new (value_mem) T{fn_::move(*original.value)}; original.value = nullptr; reinterpret_cast<T*>(value_mem)->~T(); } } optional(optional<T> const& original): fn_::optional_value<T const>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } optional(optional<T&> const& original): fn_::optional_value<T const>(original.valid() ? reinterpret_cast<T*>(value_mem) : nullptr) { original >>[&](T const& v){ new (value_mem) T{v};}; } }; template<typename T> class optional<T&> final : public fn_::optional_ref<T> { friend class optional<T const&>; friend class optional<T const>; friend class optional<T>; public: optional(): fn_::optional_ref<T>() {} optional(T& v): fn_::optional_ref<T>(&v) {} optional(optional<T> const& original): fn_::optional_ref<T>(original.value) {} }; template<typename T> class optional<T const&> final : public fn_::optional_ref<T const> { friend class optional<T const>; friend class optional<T>; public: optional(): fn_::optional_ref<T const>() {} optional(T const& v): fn_::optional_ref<T const>(&v) {} optional(optional<T> const& original): fn_::optional_ref<T const>(original.value) {} optional(optional<T&> const& original): fn_::optional_ref<T const>(original.value) {} }; template<> class optional<void> final { bool no_value; public: optional(): no_value(true) {} optional(bool): no_value(false) {} template<typename EmptyF> void operator||(EmptyF const& handle_no_value) const { if(no_value){ return handle_no_value(); } } }; namespace fn_ { /* * Convert a functions return value to an optional. * This is needed for optional handler chaining. * In particular a specialization is implemented that * avoids getting optional<optional<T>>. */ template<typename T> struct return_cast { template<typename F,typename V> static optional<T> func(F&& f,V&& v) {return f(v);} template<typename V> static T value(V&& v) {return v;} }; template<> struct return_cast<void> { template<typename F,typename V> static optional<void> func(F&& f,V&& v) {f(v); return true;} template<typename V> static void value(V&&) {} }; template<typename T> struct return_cast<optional<T>> { template<typename F,typename V> static optional<T> func(F&& f,V&& v) {return f(v);} template<typename V> static T value(V&& v) {return v;} }; } } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #endif <|endoftext|>
<commit_before>#include "Networking.hpp" std::mutex coutMutex; std::string serializeMapSize(const hlt::Map & map) { std::string returnString = ""; std::ostringstream oss; oss << map.map_width << ' ' << map.map_height << ' '; returnString = oss.str(); return returnString; } std::string serializeProductions(const hlt::Map & map) { std::string returnString = ""; std::ostringstream oss; for(auto a = map.contents.begin(); a != map.contents.end(); a++) { for(auto b = a->begin(); b != a->end(); b++) { oss << (unsigned short)(b->production) << ' '; } } returnString = oss.str(); return returnString; } std::string Networking::serializeMap(const hlt::Map & map) { std::string returnString = ""; std::ostringstream oss; //Run-length encode of owners unsigned short currentOwner = map.contents[0][0].owner; unsigned short counter = 0; for(int a = 0; a < map.contents.size(); ++a) { for(int b = 0; b < map.contents[a].size(); ++b) { if(map.contents[a][b].owner == currentOwner) { counter++; } else { oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' '; counter = 1; currentOwner = map.contents[a][b].owner; } } } //Place the last run into the string oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' '; //Encoding of ages for(int a = 0; a < map.contents.size(); ++a) { for(int b = 0; b < map.contents[a].size(); ++b) { oss << (unsigned short)map.contents[a][b].strength << ' '; } } returnString = oss.str(); return returnString; } std::set<hlt::Move> Networking::deserializeMoveSet(std::string & inputString, const hlt::Map & m) { std::set<hlt::Move> moves = std::set<hlt::Move>(); std::stringstream iss(inputString); hlt::Location l; int d; while (iss >> l.x >> l.y >> d && m.inBounds(l)) moves.insert({ l, (unsigned char)d }); return moves; } void Networking::sendString(unsigned char playerTag, std::string &sendString) { //End message with newline character sendString += '\n'; #ifdef _WIN32 WinConnection connection = connections[playerTag - 1]; DWORD charsWritten; bool success; success = WriteFile(connection.write, sendString.c_str(), sendString.length(), &charsWritten, NULL); if(!success || charsWritten == 0) { if(!quiet_output) std::cout << "Problem writing to pipe\n"; throw 1; } #else UniConnection connection = connections[playerTag - 1]; ssize_t charsWritten = write(connection.write, sendString.c_str(), sendString.length()); if(charsWritten < sendString.length()) { if(!quiet_output) std::cout << "Problem writing to pipe\n"; throw 1; } #endif } std::string Networking::getString(unsigned char playerTag, unsigned int timeoutMillis) { srand(time(NULL)); std::string newString; #ifdef _WIN32 WinConnection connection = connections[playerTag - 1]; DWORD charsRead; bool success; char buffer; //Keep reading char by char until a newline while (true) { //Check to see that there are bytes in the pipe before reading //Throw error if no bytes in alloted time //Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full) DWORD bytesAvailable = 0; PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL); if(bytesAvailable < 1) { std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); while (bytesAvailable < 1) { if(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() > timeoutMillis) throw 1; PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL); } } success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL); if(!success || charsRead < 1) { if(!quiet_output) std::cout << "Pipe probably timed out\n"; throw 1; } if(buffer == '\n') break; else newString += buffer; } #else UniConnection connection = connections[playerTag - 1]; fd_set set; FD_ZERO(&set); /* clear the set */ FD_SET(connection.read, &set); /* add our file descriptor to the set */ struct timeval timeout; //Non-blocking. We'll check every ten millisecond to get a result. timeout.tv_sec = 0; timeout.tv_usec = 10000; char buffer; //The time we started at. std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); //Keep reading char by char until a newline bool shouldContinue = true; while(shouldContinue) { //Check if process is dead. int status; // ; //if((WIFEXITED(status) || WIFSIGNALED(status) || WIFSTOPPED(status)) && playerTag == 1) std::cout << "Here " << int(playerTag) << std::endl; if(waitpid(-processes[playerTag - 1], &status, WNOHANG) == processes[playerTag - 1] || std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() >= timeoutMillis) { killPlayer(playerTag); if(!quiet_output) { // Buffer error message output // If a bunch of bots fail at onces, we dont want to be writing to cout at the same time // That looks really weird std::string errorMessage = ""; errorMessage += std::string("Unix bot timed out or errored.\n"); playerLogs[playerTag-1].push_back(newString); errorMessage += "#---------ALL OF THE OUTPUT OF THE BOT THAT TIMED OUT----------#\n"; for(auto stringIter = playerLogs[playerTag-1].begin(); stringIter != playerLogs[playerTag-1].end(); stringIter++) { while(stringIter->size() < 60) stringIter->push_back(' '); errorMessage += "# " + *stringIter + " #\n"; } errorMessage += "#--------------------------------------------------------------#\n"; std::lock_guard<std::mutex> guard(coutMutex); std::cout << errorMessage; } throw 1; } //Check if there are bytes in the pipe for(int selectionResult = select(connection.read+1, &set, NULL, NULL, &timeout); selectionResult > 0; selectionResult--) { read(connection.read, &buffer, 1); if(buffer == '\n') { shouldContinue = false; break; } else newString += buffer; } //Reset timeout - we should consider it to be undefined. timeout.tv_sec = 0; timeout.tv_usec = 10000; } #endif //Python turns \n into \r\n if(newString.at(newString.size() - 1) == '\r') newString.pop_back(); playerLogs[playerTag-1].push_back(newString); return newString; } void Networking::startAndConnectBot(std::string command) { #ifdef _WIN32 command = "/C " + command; WinConnection parentConnection, childConnection; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; //Child stdout pipe if(!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) { if(!quiet_output) std::cout << "Could not create pipe\n"; throw 1; } if(!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) throw 1; //Child stdin pipe if(!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) { if(!quiet_output) std::cout << "Could not create pipe\n"; throw 1; } if(!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) throw 1; //MAKE SURE THIS MEMORY IS ERASED PROCESS_INFORMATION piProcInfo; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); STARTUPINFO siStartInfo; ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdError = childConnection.write; siStartInfo.hStdOutput = childConnection.write; siStartInfo.hStdInput = childConnection.read; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; //C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe //C:/Users/Michael/Anaconda3/python.exe //C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot bool success = CreateProcess( "C:\\windows\\system32\\cmd.exe", LPSTR(command.c_str()), //command line NULL, //process security attributes NULL, //primary thread security attributes TRUE, //handles are inherited 0, //creation flags NULL, //use parent's environment NULL, //use parent's current directory &siStartInfo, //STARTUPINFO pointer &piProcInfo ); //receives PROCESS_INFORMATION if(!success) { if(!quiet_output) std::cout << "Could not start process\n"; throw 1; } else { CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); processes.push_back(piProcInfo.hProcess); connections.push_back(parentConnection); } #else if(!quiet_output) std::cout << command << "\n"; pid_t pid = (pid_t)NULL; int writePipe[2]; int readPipe[2]; if(pipe(writePipe)) { if(!quiet_output) std::cout << "Error creating pipe\n"; throw 1; } if(pipe(readPipe)) { if(!quiet_output) std::cout << "Error creating pipe\n"; throw 1; } //Fork a child process pid = fork(); if(pid == 0) { //This is the child setpgid(getpid(), getpid()); dup2(writePipe[0], STDIN_FILENO); dup2(readPipe[1], STDOUT_FILENO); dup2(readPipe[1], STDERR_FILENO); execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL); //Nothing past the execl should be run exit(1); } else if(pid < 0) { if(!quiet_output) std::cout << "Fork failed\n"; throw 1; } UniConnection connection; connection.read = readPipe[0]; connection.write = writePipe[1]; connections.push_back(connection); processes.push_back(pid); #endif playerLogs.push_back(std::vector<std::string>(0)); } void Networking::handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::string * playerName) { try{ std::string playerTagString = std::to_string(playerTag), mapSizeString = serializeMapSize(m), mapString = serializeMap(m), prodString = serializeProductions(m); sendString(playerTag, playerTagString); sendString(playerTag, mapSizeString); sendString(playerTag, prodString); sendString(playerTag, mapString); std::string outMessage = "Init Message sent to player " + std::to_string(int(playerTag)) + ".\n"; if(!quiet_output) std::cout << outMessage; std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); *playerName = getString(playerTag, *playermillis).substr(0, 30); unsigned int millisTaken = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count(); std::string inMessage = "Init Message received from player " + std::to_string(int(playerTag)) + ", " + *playerName + ".\n"; if(!quiet_output) std::cout << inMessage; *playermillis -= millisTaken; } catch(...) { *playerName = "Bot #" + std::to_string(playerTag) + "; timed out during Init"; *playermillis = -1; } } void Networking::handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves) { try{ if(isProcessDead(playerTag)) return; //Send this bot the game map and the messages addressed to this bot std::string mapString = serializeMap(m); sendString(playerTag, mapString); moves->clear(); std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); std::string movesString = getString(playerTag, *playermillis); unsigned int millisTaken = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count(); *moves = deserializeMoveSet(movesString, m); *playermillis -= millisTaken; } catch(...) { *moves = std::set<hlt::Move>(); *playermillis = -1; } } void Networking::killPlayer(unsigned char playerTag) { if(isProcessDead(playerTag)) return; #ifdef _WIN32 HANDLE process = processes[playerTag - 1]; TerminateProcess(process, 0); processes[playerTag - 1] = NULL; connections[playerTag - 1].read = NULL; connections[playerTag - 1].write = NULL; if(!quiet_output) std::cout << "Player " << int(playerTag) << " is dead\n"; #else kill(-processes[playerTag - 1], SIGKILL); processes[playerTag - 1] = -1; connections[playerTag - 1].read = -1; connections[playerTag - 1].write = -1; #endif } bool Networking::isProcessDead(unsigned char playerTag) { #ifdef _WIN32 return processes[playerTag - 1] == NULL; #else return processes[playerTag - 1] == -1; #endif } int Networking::numberOfPlayers() { #ifdef _WIN32 return connections.size(); #else return connections.size(); #endif } <commit_msg>Removed unnecessary srand<commit_after>#include "Networking.hpp" std::mutex coutMutex; std::string serializeMapSize(const hlt::Map & map) { std::string returnString = ""; std::ostringstream oss; oss << map.map_width << ' ' << map.map_height << ' '; returnString = oss.str(); return returnString; } std::string serializeProductions(const hlt::Map & map) { std::string returnString = ""; std::ostringstream oss; for(auto a = map.contents.begin(); a != map.contents.end(); a++) { for(auto b = a->begin(); b != a->end(); b++) { oss << (unsigned short)(b->production) << ' '; } } returnString = oss.str(); return returnString; } std::string Networking::serializeMap(const hlt::Map & map) { std::string returnString = ""; std::ostringstream oss; //Run-length encode of owners unsigned short currentOwner = map.contents[0][0].owner; unsigned short counter = 0; for(int a = 0; a < map.contents.size(); ++a) { for(int b = 0; b < map.contents[a].size(); ++b) { if(map.contents[a][b].owner == currentOwner) { counter++; } else { oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' '; counter = 1; currentOwner = map.contents[a][b].owner; } } } //Place the last run into the string oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' '; //Encoding of ages for(int a = 0; a < map.contents.size(); ++a) { for(int b = 0; b < map.contents[a].size(); ++b) { oss << (unsigned short)map.contents[a][b].strength << ' '; } } returnString = oss.str(); return returnString; } std::set<hlt::Move> Networking::deserializeMoveSet(std::string & inputString, const hlt::Map & m) { std::set<hlt::Move> moves = std::set<hlt::Move>(); std::stringstream iss(inputString); hlt::Location l; int d; while (iss >> l.x >> l.y >> d && m.inBounds(l)) moves.insert({ l, (unsigned char)d }); return moves; } void Networking::sendString(unsigned char playerTag, std::string &sendString) { //End message with newline character sendString += '\n'; #ifdef _WIN32 WinConnection connection = connections[playerTag - 1]; DWORD charsWritten; bool success; success = WriteFile(connection.write, sendString.c_str(), sendString.length(), &charsWritten, NULL); if(!success || charsWritten == 0) { if(!quiet_output) std::cout << "Problem writing to pipe\n"; throw 1; } #else UniConnection connection = connections[playerTag - 1]; ssize_t charsWritten = write(connection.write, sendString.c_str(), sendString.length()); if(charsWritten < sendString.length()) { if(!quiet_output) std::cout << "Problem writing to pipe\n"; throw 1; } #endif } std::string Networking::getString(unsigned char playerTag, unsigned int timeoutMillis) { std::string newString; #ifdef _WIN32 WinConnection connection = connections[playerTag - 1]; DWORD charsRead; bool success; char buffer; //Keep reading char by char until a newline while (true) { //Check to see that there are bytes in the pipe before reading //Throw error if no bytes in alloted time //Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full) DWORD bytesAvailable = 0; PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL); if(bytesAvailable < 1) { std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); while (bytesAvailable < 1) { if(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() > timeoutMillis) throw 1; PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL); } } success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL); if(!success || charsRead < 1) { if(!quiet_output) std::cout << "Pipe probably timed out\n"; throw 1; } if(buffer == '\n') break; else newString += buffer; } #else UniConnection connection = connections[playerTag - 1]; fd_set set; FD_ZERO(&set); /* clear the set */ FD_SET(connection.read, &set); /* add our file descriptor to the set */ struct timeval timeout; //Non-blocking. We'll check every ten millisecond to get a result. timeout.tv_sec = 0; timeout.tv_usec = 10000; char buffer; //The time we started at. std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); //Keep reading char by char until a newline bool shouldContinue = true; while(shouldContinue) { //Check if process is dead. int status; if(waitpid(processes[playerTag - 1], &status, WNOHANG) == processes[playerTag - 1] || std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() >= timeoutMillis) { killPlayer(playerTag); std::cout << "Error!" << std::endl; if(!quiet_output) { // Buffer error message output // If a bunch of bots fail at onces, we dont want to be writing to cout at the same time // That looks really weird std::string errorMessage = ""; errorMessage += std::string("Unix bot timed out or errored.\n"); playerLogs[playerTag-1].push_back(newString); errorMessage += "#---------ALL OF THE OUTPUT OF THE BOT THAT TIMED OUT----------#\n"; for(auto stringIter = playerLogs[playerTag-1].begin(); stringIter != playerLogs[playerTag-1].end(); stringIter++) { while(stringIter->size() < 60) stringIter->push_back(' '); errorMessage += "# " + *stringIter + " #\n"; } errorMessage += "#--------------------------------------------------------------#\n"; std::lock_guard<std::mutex> guard(coutMutex); std::cout << errorMessage; } throw 1; } //Check if there are bytes in the pipe for(int selectionResult = select(connection.read+1, &set, NULL, NULL, &timeout); selectionResult > 0; selectionResult--) { read(connection.read, &buffer, 1); if(buffer == '\n') { shouldContinue = false; break; } else newString += buffer; } //Reset timeout - we should consider it to be undefined. timeout.tv_sec = 0; timeout.tv_usec = 10000; } #endif //Python turns \n into \r\n if(newString.at(newString.size() - 1) == '\r') newString.pop_back(); playerLogs[playerTag-1].push_back(newString); return newString; } void Networking::startAndConnectBot(std::string command) { #ifdef _WIN32 command = "/C " + command; WinConnection parentConnection, childConnection; SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; //Child stdout pipe if(!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) { if(!quiet_output) std::cout << "Could not create pipe\n"; throw 1; } if(!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) throw 1; //Child stdin pipe if(!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) { if(!quiet_output) std::cout << "Could not create pipe\n"; throw 1; } if(!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) throw 1; //MAKE SURE THIS MEMORY IS ERASED PROCESS_INFORMATION piProcInfo; ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); STARTUPINFO siStartInfo; ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdError = childConnection.write; siStartInfo.hStdOutput = childConnection.write; siStartInfo.hStdInput = childConnection.read; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; //C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe //C:/Users/Michael/Anaconda3/python.exe //C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot bool success = CreateProcess( "C:\\windows\\system32\\cmd.exe", LPSTR(command.c_str()), //command line NULL, //process security attributes NULL, //primary thread security attributes TRUE, //handles are inherited 0, //creation flags NULL, //use parent's environment NULL, //use parent's current directory &siStartInfo, //STARTUPINFO pointer &piProcInfo ); //receives PROCESS_INFORMATION if(!success) { if(!quiet_output) std::cout << "Could not start process\n"; throw 1; } else { CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); processes.push_back(piProcInfo.hProcess); connections.push_back(parentConnection); } #else if(!quiet_output) std::cout << command << "\n"; pid_t pid = (pid_t)NULL; int writePipe[2]; int readPipe[2]; if(pipe(writePipe)) { if(!quiet_output) std::cout << "Error creating pipe\n"; throw 1; } if(pipe(readPipe)) { if(!quiet_output) std::cout << "Error creating pipe\n"; throw 1; } //Fork a child process pid = fork(); if(pid == 0) { //This is the child setpgid(getpid(), getpid()); dup2(writePipe[0], STDIN_FILENO); dup2(readPipe[1], STDOUT_FILENO); dup2(readPipe[1], STDERR_FILENO); execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL); //Nothing past the execl should be run exit(1); } else if(pid < 0) { if(!quiet_output) std::cout << "Fork failed\n"; throw 1; } UniConnection connection; connection.read = readPipe[0]; connection.write = writePipe[1]; connections.push_back(connection); processes.push_back(pid); #endif playerLogs.push_back(std::vector<std::string>(0)); } void Networking::handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::string * playerName) { try{ std::string playerTagString = std::to_string(playerTag), mapSizeString = serializeMapSize(m), mapString = serializeMap(m), prodString = serializeProductions(m); sendString(playerTag, playerTagString); sendString(playerTag, mapSizeString); sendString(playerTag, prodString); sendString(playerTag, mapString); std::string outMessage = "Init Message sent to player " + std::to_string(int(playerTag)) + ".\n"; if(!quiet_output) std::cout << outMessage; std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); *playerName = getString(playerTag, *playermillis).substr(0, 30); unsigned int millisTaken = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count(); std::string inMessage = "Init Message received from player " + std::to_string(int(playerTag)) + ", " + *playerName + ".\n"; if(!quiet_output) std::cout << inMessage; *playermillis -= millisTaken; } catch(...) { *playerName = "Bot #" + std::to_string(playerTag) + "; timed out during Init"; *playermillis = -1; } } void Networking::handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves) { try{ if(isProcessDead(playerTag)) return; //Send this bot the game map and the messages addressed to this bot std::string mapString = serializeMap(m); sendString(playerTag, mapString); moves->clear(); std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now(); std::string movesString = getString(playerTag, *playermillis); unsigned int millisTaken = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count(); *moves = deserializeMoveSet(movesString, m); *playermillis -= millisTaken; } catch(...) { *moves = std::set<hlt::Move>(); *playermillis = -1; } } void Networking::killPlayer(unsigned char playerTag) { if(isProcessDead(playerTag)) return; #ifdef _WIN32 HANDLE process = processes[playerTag - 1]; TerminateProcess(process, 0); processes[playerTag - 1] = NULL; connections[playerTag - 1].read = NULL; connections[playerTag - 1].write = NULL; if(!quiet_output) std::cout << "Player " << int(playerTag) << " is dead\n"; #else kill(-processes[playerTag - 1], SIGKILL); processes[playerTag - 1] = -1; connections[playerTag - 1].read = -1; connections[playerTag - 1].write = -1; #endif } bool Networking::isProcessDead(unsigned char playerTag) { #ifdef _WIN32 return processes[playerTag - 1] == NULL; #else return processes[playerTag - 1] == -1; #endif } int Networking::numberOfPlayers() { #ifdef _WIN32 return connections.size(); #else return connections.size(); #endif } <|endoftext|>
<commit_before>//===- lib/ReaderWriter/ELF/WriterELF.cpp ---------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/ReaderWriter/Writer.h" #include "DynamicLibraryWriter.h" #include "ExecutableWriter.h" using namespace llvm; using namespace llvm::object; namespace lld { std::unique_ptr<Writer> createWriterELF(TargetHandlerBase *handler) { return std::move(handler->getWriter()); } } // namespace lld <commit_msg>Fix format.<commit_after>//===- lib/ReaderWriter/ELF/WriterELF.cpp ---------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/ReaderWriter/Writer.h" #include "DynamicLibraryWriter.h" #include "ExecutableWriter.h" using namespace llvm; using namespace llvm::object; namespace lld { std::unique_ptr<Writer> createWriterELF(TargetHandlerBase *handler) { return std::move(handler->getWriter()); } } // namespace lld <|endoftext|>
<commit_before>/* Copyright (C) 2003 Scott Wheeler <wheeler@kde.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <iomanip> #include <stdio.h> #include <fileref.h> #include <tag.h> #include <tpropertymap.h> using namespace std; TagLib::String formatSeconds(int seconds) { char secondsString[3]; sprintf(secondsString, "%02i", seconds); return secondsString; } int main(int argc, char *argv[]) { for(int i = 1; i < argc; i++) { cout << "******************** \"" << argv[i] << "\" ********************" << endl; TagLib::FileRef f(argv[i]); if(!f.isNull() && f.tag()) { TagLib::Tag *tag = f.tag(); cout << "-- TAG (basic) --" << endl; cout << "title - \"" << tag->title() << "\"" << endl; cout << "artist - \"" << tag->artist() << "\"" << endl; cout << "album - \"" << tag->album() << "\"" << endl; cout << "year - \"" << tag->year() << "\"" << endl; cout << "comment - \"" << tag->comment() << "\"" << endl; cout << "track - \"" << tag->track() << "\"" << endl; cout << "genre - \"" << tag->genre() << "\"" << endl; TagLib::PropertyMap tags = f.file()->properties(); unsigned int longest = 0; for(TagLib::PropertyMap::ConstIterator i = tags.begin(); i != tags.end(); ++i) { if (i->first.size() > longest) { longest = i->first.size(); } } cout << "-- TAG (properties) --" << endl; for(TagLib::PropertyMap::ConstIterator i = tags.begin(); i != tags.end(); ++i) { for(TagLib::StringList::ConstIterator j = i->second.begin(); j != i->second.end(); ++j) { cout << left << std::setw(longest) << i->first << " - " << '"' << *j << '"' << endl; } } } if(!f.isNull() && f.audioProperties()) { TagLib::AudioProperties *properties = f.audioProperties(); int seconds = properties->length() % 60; int minutes = (properties->length() - seconds) / 60; cout << "-- AUDIO --" << endl; cout << "bitrate - " << properties->bitrate() << endl; cout << "sample rate - " << properties->sampleRate() << endl; cout << "channels - " << properties->channels() << endl; cout << "length - " << minutes << ":" << formatSeconds(seconds) << endl; } } return 0; } <commit_msg>Avoid using sprintf() in tagreader.cpp to fix an MSVC warning.<commit_after>/* Copyright (C) 2003 Scott Wheeler <wheeler@kde.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <iomanip> #include <stdio.h> #include <fileref.h> #include <tag.h> #include <tpropertymap.h> using namespace std; int main(int argc, char *argv[]) { for(int i = 1; i < argc; i++) { cout << "******************** \"" << argv[i] << "\" ********************" << endl; TagLib::FileRef f(argv[i]); if(!f.isNull() && f.tag()) { TagLib::Tag *tag = f.tag(); cout << "-- TAG (basic) --" << endl; cout << "title - \"" << tag->title() << "\"" << endl; cout << "artist - \"" << tag->artist() << "\"" << endl; cout << "album - \"" << tag->album() << "\"" << endl; cout << "year - \"" << tag->year() << "\"" << endl; cout << "comment - \"" << tag->comment() << "\"" << endl; cout << "track - \"" << tag->track() << "\"" << endl; cout << "genre - \"" << tag->genre() << "\"" << endl; TagLib::PropertyMap tags = f.file()->properties(); unsigned int longest = 0; for(TagLib::PropertyMap::ConstIterator i = tags.begin(); i != tags.end(); ++i) { if (i->first.size() > longest) { longest = i->first.size(); } } cout << "-- TAG (properties) --" << endl; for(TagLib::PropertyMap::ConstIterator i = tags.begin(); i != tags.end(); ++i) { for(TagLib::StringList::ConstIterator j = i->second.begin(); j != i->second.end(); ++j) { cout << left << std::setw(longest) << i->first << " - " << '"' << *j << '"' << endl; } } } if(!f.isNull() && f.audioProperties()) { TagLib::AudioProperties *properties = f.audioProperties(); int seconds = properties->length() % 60; int minutes = (properties->length() - seconds) / 60; cout << "-- AUDIO --" << endl; cout << "bitrate - " << properties->bitrate() << endl; cout << "sample rate - " << properties->sampleRate() << endl; cout << "channels - " << properties->channels() << endl; cout << "length - " << minutes << ":" << setfill('0') << setw(2) << seconds << endl; } } return 0; } <|endoftext|>
<commit_before>#pragma once // `krbn::event_queue::entry` can be used safely in a multi-threaded environment. #include "event_queue/event.hpp" #include "event_queue/event_time_stamp.hpp" #include "json_utility.hpp" #include "types.hpp" namespace krbn { namespace event_queue { class entry final { public: // Constructors entry(device_id device_id, const event_time_stamp& event_time_stamp, const class event& event, event_type event_type, const class event& original_event, bool lazy = false) : device_id_(device_id), event_time_stamp_(event_time_stamp), valid_(true), lazy_(lazy), event_(event), event_type_(event_type), original_event_(original_event) { } entry& operator=(const entry& other) { device_id_ = other.device_id_; event_time_stamp_ = other.event_time_stamp_; valid_ = other.valid_; lazy_ = other.lazy_; event_ = other.event_; event_type_ = other.event_type_; original_event_ = other.original_event_; return *this; } entry(const entry& other) { *this = other; } static entry make_from_json(const nlohmann::json& json) { entry result(device_id::zero, event_time_stamp(absolute_time_point(0)), event(), event_type::key_down, event()); if (json.is_object()) { if (auto v = json_utility::find_optional<uint32_t>(json, "device_id")) { result.device_id_ = device_id(*v); } if (auto v = json_utility::find_json(json, "event_time_stamp")) { result.event_time_stamp_ = event_time_stamp::make_from_json(*v); } if (auto v = json_utility::find_optional<bool>(json, "valid")) { result.valid_ = *v; } if (auto v = json_utility::find_optional<bool>(json, "lazy")) { result.lazy_ = *v; } if (auto v = json_utility::find_json(json, "event")) { result.event_ = event::make_from_json(*v); } if (auto v = json_utility::find_json(json, "event_type")) { result.event_type_ = *v; } if (auto v = json_utility::find_json(json, "original_event")) { result.original_event_ = event::make_from_json(*v); } } return result; } // Methods device_id get_device_id(void) const { // We don't have to use mutex since there is not setter. return device_id_; } const event_time_stamp& get_event_time_stamp(void) const { // We don't have to use mutex since there is not setter. return event_time_stamp_; } event_time_stamp& get_event_time_stamp(void) { return const_cast<event_time_stamp&>(static_cast<const entry&>(*this).get_event_time_stamp()); } bool get_valid(void) const { std::lock_guard<std::mutex> lock(mutex_); return valid_; } void set_valid(bool value) { std::lock_guard<std::mutex> lock(mutex_); valid_ = value; } bool get_lazy(void) const { std::lock_guard<std::mutex> lock(mutex_); return lazy_; } void set_lazy(bool value) { std::lock_guard<std::mutex> lock(mutex_); lazy_ = value; } const event& get_event(void) const { // We don't have to use mutex since there is not setter. return event_; } event_type get_event_type(void) const { // We don't have to use mutex since there is not setter. return event_type_; } const event& get_original_event(void) const { // We don't have to use mutex since there is not setter. return original_event_; } nlohmann::json to_json(void) const { return nlohmann::json({ {"device_id", static_cast<uint32_t>(get_device_id())}, {"event_time_stamp", get_event_time_stamp()}, {"valid", get_valid()}, {"lazy", get_lazy()}, {"event", get_event()}, {"event_type", get_event_type()}, {"original_event", get_original_event()}, }); } bool operator==(const entry& other) const { return get_device_id() == other.get_device_id() && get_event_time_stamp() == other.get_event_time_stamp() && get_valid() == other.get_valid() && get_lazy() == other.get_lazy() && get_event() == other.get_event() && get_event_type() == other.get_event_type() && get_original_event() == other.get_original_event(); } bool operator!=(const entry& other) const { return !(*this == other); } private: device_id device_id_; event_time_stamp event_time_stamp_; bool valid_; bool lazy_; event event_; event_type event_type_; event original_event_; mutable std::mutex mutex_; }; inline std::ostream& operator<<(std::ostream& stream, const entry& value) { stream << std::endl << "{" << "\"device_id\":" << value.get_device_id() << ",\"event_time_stamp\":" << value.get_event_time_stamp() << ",\"valid\":" << value.get_valid() << ",\"lazy\":" << value.get_lazy() << ",\"event\":" << value.get_event() << ",\"event_type\":" << value.get_event_type() << ",\"original_event\":" << value.get_original_event() << "}"; return stream; } inline void to_json(nlohmann::json& json, const entry& value) { json = value.to_json(); } } // namespace event_queue } // namespace krbn <commit_msg>use type_safe::get<commit_after>#pragma once // `krbn::event_queue::entry` can be used safely in a multi-threaded environment. #include "event.hpp" #include "event_time_stamp.hpp" #include "json_utility.hpp" #include "types.hpp" namespace krbn { namespace event_queue { class entry final { public: // Constructors entry(device_id device_id, const event_time_stamp& event_time_stamp, const class event& event, event_type event_type, const class event& original_event, bool lazy = false) : device_id_(device_id), event_time_stamp_(event_time_stamp), valid_(true), lazy_(lazy), event_(event), event_type_(event_type), original_event_(original_event) { } entry& operator=(const entry& other) { device_id_ = other.device_id_; event_time_stamp_ = other.event_time_stamp_; valid_ = other.valid_; lazy_ = other.lazy_; event_ = other.event_; event_type_ = other.event_type_; original_event_ = other.original_event_; return *this; } entry(const entry& other) { *this = other; } static entry make_from_json(const nlohmann::json& json) { entry result(device_id(0), event_time_stamp(absolute_time_point(0)), event(), event_type::key_down, event()); if (json.is_object()) { if (auto v = json_utility::find_optional<uint32_t>(json, "device_id")) { result.device_id_ = device_id(*v); } if (auto v = json_utility::find_json(json, "event_time_stamp")) { result.event_time_stamp_ = event_time_stamp::make_from_json(*v); } if (auto v = json_utility::find_optional<bool>(json, "valid")) { result.valid_ = *v; } if (auto v = json_utility::find_optional<bool>(json, "lazy")) { result.lazy_ = *v; } if (auto v = json_utility::find_json(json, "event")) { result.event_ = event::make_from_json(*v); } if (auto v = json_utility::find_json(json, "event_type")) { result.event_type_ = *v; } if (auto v = json_utility::find_json(json, "original_event")) { result.original_event_ = event::make_from_json(*v); } } return result; } // Methods device_id get_device_id(void) const { // We don't have to use mutex since there is not setter. return device_id_; } const event_time_stamp& get_event_time_stamp(void) const { // We don't have to use mutex since there is not setter. return event_time_stamp_; } event_time_stamp& get_event_time_stamp(void) { return const_cast<event_time_stamp&>(static_cast<const entry&>(*this).get_event_time_stamp()); } bool get_valid(void) const { std::lock_guard<std::mutex> lock(mutex_); return valid_; } void set_valid(bool value) { std::lock_guard<std::mutex> lock(mutex_); valid_ = value; } bool get_lazy(void) const { std::lock_guard<std::mutex> lock(mutex_); return lazy_; } void set_lazy(bool value) { std::lock_guard<std::mutex> lock(mutex_); lazy_ = value; } const event& get_event(void) const { // We don't have to use mutex since there is not setter. return event_; } event_type get_event_type(void) const { // We don't have to use mutex since there is not setter. return event_type_; } const event& get_original_event(void) const { // We don't have to use mutex since there is not setter. return original_event_; } nlohmann::json to_json(void) const { return nlohmann::json({ {"device_id", type_safe::get(get_device_id())}, {"event_time_stamp", get_event_time_stamp()}, {"valid", get_valid()}, {"lazy", get_lazy()}, {"event", get_event()}, {"event_type", get_event_type()}, {"original_event", get_original_event()}, }); } bool operator==(const entry& other) const { return get_device_id() == other.get_device_id() && get_event_time_stamp() == other.get_event_time_stamp() && get_valid() == other.get_valid() && get_lazy() == other.get_lazy() && get_event() == other.get_event() && get_event_type() == other.get_event_type() && get_original_event() == other.get_original_event(); } bool operator!=(const entry& other) const { return !(*this == other); } private: device_id device_id_; event_time_stamp event_time_stamp_; bool valid_; bool lazy_; event event_; event_type event_type_; event original_event_; mutable std::mutex mutex_; }; inline std::ostream& operator<<(std::ostream& stream, const entry& value) { stream << std::endl << "{" << "\"device_id\":" << value.get_device_id() << ",\"event_time_stamp\":" << value.get_event_time_stamp() << ",\"valid\":" << value.get_valid() << ",\"lazy\":" << value.get_lazy() << ",\"event\":" << value.get_event() << ",\"event_type\":" << value.get_event_type() << ",\"original_event\":" << value.get_original_event() << "}"; return stream; } inline void to_json(nlohmann::json& json, const entry& value) { json = value.to_json(); } } // namespace event_queue } // namespace krbn <|endoftext|>
<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "ExceptionFilterTest.h" #include "EventReceiver.h" #include "ExceptionFilter.h" #include <stdexcept> #include <sstream> #include <iostream> using namespace std; string FormatMessage(int value) { std::stringstream sstr; sstr << "custom_exception: " << value; return sstr.str(); } class custom_exception: public std::exception { public: custom_exception(int value): m_value(value) { } int m_value; }; /// <summary> /// Exception type which can track its own destruction /// </summary> class tracking_exception: public std::exception { public: tracking_exception(int) { s_count++; } tracking_exception(const tracking_exception& rhs) { s_count++; } NOEXCEPT(~tracking_exception(void)) { s_count--; } static size_t s_count; }; size_t tracking_exception::s_count = 0; class ThrowingListener: public virtual EventReceiver { public: virtual void DoThrow(void) = 0; }; template<class Ex> class ThrowsWhenRun: public CoreThread { public: ThrowsWhenRun(void) { Ready(); } // This convoluted syntax is required to evade warnings on Mac decltype(throw_rethrowable Ex(100)) MakeException() { return throw_rethrowable Ex(100); } void Run(void) override { MakeException(); } }; template<int i = 200> class ThrowsWhenFired: public ThrowingListener { public: ThrowsWhenFired(void): hit(false) {} bool hit; void DoThrow(void) override { hit = true; throw_rethrowable custom_exception(i); } }; class GenericFilter: public ExceptionFilter { public: GenericFilter(void): m_hit(false), m_specific(false), m_generic(false), m_fireSpecific(false) { } bool m_hit; bool m_specific; bool m_generic; bool m_fireSpecific; virtual void Filter(const std::function<void()>& rethrower) override { m_hit = true; try { rethrower(); } catch(tracking_exception&) { } catch(custom_exception& custom) { EXPECT_EQ(100, custom.m_value) << "A filtered custom exception did not have the expected member field value"; m_specific = true; } catch(...) { m_generic = true; } } virtual void Filter(const std::function<void()>& rethrower, const EventReceiverProxyBase* pProxy, EventReceiver* pRecipient) override { m_hit = true; try { rethrower(); } catch(custom_exception& custom) { EXPECT_EQ(200, custom.m_value) << "A fired exception did not have the expected value, probable copy malfunction"; m_fireSpecific = true; } catch(...) { m_generic = true; } } }; TEST_F(ExceptionFilterTest, ExceptionDestruction) { // Add the exception filter type to the context first AutoRequired<GenericFilter> filter; // Now add something that will throw when it's run: AutoRequired<ThrowsWhenRun<tracking_exception>> thrower; // Run: m_create->InitiateCoreThreads(); thrower->Wait(); // Verify that the exception was destroyed the correct number of times: EXPECT_EQ(0UL, tracking_exception::s_count) << "Exception was not destroyed the correct number of times"; } TEST_F(ExceptionFilterTest, CheckThrowThrow) { class example { public: example() { throw std::exception(); } }; EXPECT_THROW(throw example(), std::exception) << "An exception type which throws from its ctor did not throw the expected type"; } TEST_F(ExceptionFilterTest, ThreadThrowsCheck) { // Add the exception filter type to the context first AutoRequired<GenericFilter> filter; // Now add something that will throw when it's run: AutoRequired<ThrowsWhenRun<custom_exception>> thrower; // Wait for the thrower to terminate, should be pretty fast: m_create->InitiateCoreThreads(); thrower->Wait(); // Hopefully the filter got hit in the right spot: EXPECT_TRUE(filter->m_hit) << "Filter was not invoked for a thrown exception"; EXPECT_TRUE(filter->m_specific) << "Filter did not correctly detect the exception type"; EXPECT_FALSE(filter->m_generic) << "Filter did not correctly filter out a specific exception"; } TEST_F(ExceptionFilterTest, FireThrowsCheck) { // Firing will occur at the parent context scope: AutoFired<ThrowingListener> broadcaster; // Create a subcontext AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); // Add the generic filter: AutoRequired<GenericFilter> filter; // Add a context member which will throw when its event is fired, and a firing class: AutoRequired<ThrowsWhenFired<>> fireThrower; // Add something to fire the exception: EXPECT_NO_THROW(broadcaster(&ThrowingListener::DoThrow)()); // Verify that the exception was filtered properly by the generic filter: EXPECT_TRUE(filter->m_fireSpecific) << "Filter was not invoked on a Fired exception"; // Verify that our context was torn down: EXPECT_TRUE(ctxt->ShouldStop()) << "An unhandled exception from a fire call in a context should have signalled it to stop"; // Verify that the parent context is intact: EXPECT_FALSE(m_create->ShouldStop()) << "An unhandled exception incorrectly terminated a parent context"; } TEST_F(ExceptionFilterTest, EnclosedThrowCheck) { // Create our listener: AutoRequired<GenericFilter> filter; // Now the subcontext: AutoCreateContext subCtxt; CurrentContextPusher pshr(subCtxt); // Create and start: AutoRequired<ThrowsWhenRun<custom_exception>> runThrower; subCtxt->InitiateCoreThreads(); // Wait for the exception to get thrown: subCtxt->Wait(); // Verify that the filter caught the exception: EXPECT_TRUE(filter->m_hit) << "Filter operating in a superior context did not catch an exception thrown from a child context"; } TEST_F(ExceptionFilterTest, VerifyThrowingRecipients) { // Create a pair of classes which throw exceptions: AutoRequired<ThrowsWhenFired<200>> v200; AutoRequired<ThrowsWhenFired<201>> v201; // Now try to throw: AutoFired<ThrowingListener> tl; tl(&ThrowingListener::DoThrow)(); // Verify that BOTH are hit: EXPECT_TRUE(v200->hit && v201->hit) << "Expected all receivers of a fired event will be processed, even if some throw exceptions"; }<commit_msg>Containment test extracted, further examination of this idea will be needed later<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "ExceptionFilterTest.h" #include "EventReceiver.h" #include "ExceptionFilter.h" #include <stdexcept> #include <sstream> #include <iostream> using namespace std; string FormatMessage(int value) { std::stringstream sstr; sstr << "custom_exception: " << value; return sstr.str(); } class custom_exception: public std::exception { public: custom_exception(int value): m_value(value) { } int m_value; }; /// <summary> /// Exception type which can track its own destruction /// </summary> class tracking_exception: public std::exception { public: tracking_exception(int) { s_count++; } tracking_exception(const tracking_exception& rhs) { s_count++; } NOEXCEPT(~tracking_exception(void)) { s_count--; } static size_t s_count; }; size_t tracking_exception::s_count = 0; class ThrowingListener: public virtual EventReceiver { public: virtual void DoThrow(void) = 0; }; template<class Ex> class ThrowsWhenRun: public CoreThread { public: ThrowsWhenRun(void) { Ready(); } // This convoluted syntax is required to evade warnings on Mac decltype(throw_rethrowable Ex(100)) MakeException() { return throw_rethrowable Ex(100); } void Run(void) override { MakeException(); } }; template<int i = 200> class ThrowsWhenFired: public ThrowingListener { public: ThrowsWhenFired(void): hit(false) {} bool hit; void DoThrow(void) override { hit = true; throw_rethrowable custom_exception(i); } }; class GenericFilter: public ExceptionFilter { public: GenericFilter(void): m_hit(false), m_specific(false), m_generic(false), m_fireSpecific(false) { } bool m_hit; bool m_specific; bool m_generic; bool m_fireSpecific; virtual void Filter(const std::function<void()>& rethrower) override { m_hit = true; try { rethrower(); } catch(tracking_exception&) { } catch(custom_exception& custom) { EXPECT_EQ(100, custom.m_value) << "A filtered custom exception did not have the expected member field value"; m_specific = true; } catch(...) { m_generic = true; } } virtual void Filter(const std::function<void()>& rethrower, const EventReceiverProxyBase* pProxy, EventReceiver* pRecipient) override { m_hit = true; try { rethrower(); } catch(custom_exception& custom) { EXPECT_EQ(200, custom.m_value) << "A fired exception did not have the expected value, probable copy malfunction"; m_fireSpecific = true; } catch(...) { m_generic = true; } } }; TEST_F(ExceptionFilterTest, ExceptionDestruction) { // Add the exception filter type to the context first AutoRequired<GenericFilter> filter; // Now add something that will throw when it's run: AutoRequired<ThrowsWhenRun<tracking_exception>> thrower; // Run: m_create->InitiateCoreThreads(); thrower->Wait(); // Verify that the exception was destroyed the correct number of times: EXPECT_EQ(0UL, tracking_exception::s_count) << "Exception was not destroyed the correct number of times"; } TEST_F(ExceptionFilterTest, CheckThrowThrow) { class example { public: example() { throw std::exception(); } }; EXPECT_THROW(throw example(), std::exception) << "An exception type which throws from its ctor did not throw the expected type"; } TEST_F(ExceptionFilterTest, ThreadThrowsCheck) { // Add the exception filter type to the context first AutoRequired<GenericFilter> filter; // Now add something that will throw when it's run: AutoRequired<ThrowsWhenRun<custom_exception>> thrower; // Wait for the thrower to terminate, should be pretty fast: m_create->InitiateCoreThreads(); thrower->Wait(); // Hopefully the filter got hit in the right spot: EXPECT_TRUE(filter->m_hit) << "Filter was not invoked for a thrown exception"; EXPECT_TRUE(filter->m_specific) << "Filter did not correctly detect the exception type"; EXPECT_FALSE(filter->m_generic) << "Filter did not correctly filter out a specific exception"; } TEST_F(ExceptionFilterTest, SimpleFilterCheck) { // Firing will occur at the parent context scope: AutoFired<ThrowingListener> broadcaster; // Add the generic filter: AutoRequired<GenericFilter> filter; // Add a context member which will throw when its event is fired, and a firing class: AutoRequired<ThrowsWhenFired<>> fireThrower; // Add something to fire the exception: EXPECT_NO_THROW(broadcaster(&ThrowingListener::DoThrow)()); // Verify that the exception was filtered properly by the generic filter: EXPECT_TRUE(filter->m_fireSpecific) << "Filter was not invoked on a Fired exception"; } TEST_F(ExceptionFilterTest, DISABLED_FireContainmentCheck) { // Firing will occur at the parent context scope: AutoFired<ThrowingListener> broadcaster; // Create a subcontext and add the fire thrower to it: AutoCreateContext ctxt; ctxt->Add<ThrowsWhenFired<>>(); // Now cause the exception to occur: EXPECT_NO_THROW(broadcaster(&ThrowingListener::DoThrow)()); // Verify that the context containing the fire thrower was torn down: EXPECT_TRUE(ctxt->ShouldStop()) << "An unhandled exception from a fire call in a context should have signalled it to stop"; // Verify that the parent context was protected: EXPECT_FALSE(m_create->ShouldStop()) << "An unhandled exception incorrectly terminated a parent context"; } TEST_F(ExceptionFilterTest, EnclosedThrowCheck) { // Create our listener: AutoRequired<GenericFilter> filter; // Now the subcontext: AutoCreateContext subCtxt; CurrentContextPusher pshr(subCtxt); // Create and start: AutoRequired<ThrowsWhenRun<custom_exception>> runThrower; subCtxt->InitiateCoreThreads(); // Wait for the exception to get thrown: subCtxt->Wait(); // Verify that the filter caught the exception: EXPECT_TRUE(filter->m_hit) << "Filter operating in a superior context did not catch an exception thrown from a child context"; } TEST_F(ExceptionFilterTest, VerifyThrowingRecipients) { // Create a pair of classes which throw exceptions: AutoRequired<ThrowsWhenFired<200>> v200; AutoRequired<ThrowsWhenFired<201>> v201; // Now try to throw: AutoFired<ThrowingListener> tl; tl(&ThrowingListener::DoThrow)(); // Verify that BOTH are hit: EXPECT_TRUE(v200->hit && v201->hit) << "Expected all receivers of a fired event will be processed, even if some throw exceptions"; }<|endoftext|>