<commit_before>/* medViewContainerMulti.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Wed Mar 17 11:01:46 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 56
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medViewContainer_p.h"
#include "medViewContainerMulti.h"
#include "medViewPool.h"

#include <dtkCore/dtkAbstractView.h>

#include <medCore/medAbstractView.h>
#include <medCore/medViewManager.h>

medViewContainerSingle2::~medViewContainerSingle2()
{
}

void medViewContainerSingle2::setView (dtkAbstractView *view)
{
    d->layout->setContentsMargins(1, 1, 1, 1);
    d->layout->addWidget(view->widget(), 0, 0);
    d->view = view;

    // d->pool->appendView (view); // only difference with medViewContainerSingle: do not add the view to the pool
    connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));
}

bool medViewContainerSingle2::isLeaf(void) const
{
    return true;
}

void medViewContainerSingle2::onViewClosing (void)
{
    if (d->view) {
        d->layout->removeWidget(d->view->widget());
        d->view->widget()->hide();
        disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));
        // d->pool->removeView (d->view); // do not remove it from the pool
        d->view = NULL;
    }

    // qDebug() << this << __func__;
    // qDebug() << "isRoot:    " << this->isRoot();
    // qDebug() << "isLeaf:    " << this->isLeaf();
    // qDebug() << "isEmpty:   " << this->isEmpty();
    // qDebug() << "isCurrent: " << this->isCurrent();
}

class medViewContainerMultiPrivate
{
public:
    QList<dtkAbstractView *> views;
};

medViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate)
{
}

medViewContainerMulti::~medViewContainerMulti()
{
    medViewContainer::setView(0);

    delete d2;
    d2 = NULL;
}

void medViewContainerMulti::split(int rows, int cols)
{
    Q_UNUSED(rows);
    Q_UNUSED(cols);

    // Don't split a multi view container

    return;
}

dtkAbstractView *medViewContainerMulti::view(void) const
{
    return NULL;
}

QList<dtkAbstractView*> medViewContainerMulti::views (void) const
{
    return d2->views;
}

void medViewContainerMulti::setView(dtkAbstractView *view)
{
    if (!view)
        return;

    if (d2->views.contains (view))
        return;

    QList<QWidget *> content;
    for(int i = 0; i < d->layout->rowCount() ; i++) {
        for(int j = 0; j < d->layout->columnCount() ; j++) {
            if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
                content << item->widget();
                d->layout->removeItem(item);
            }
        }
    }

    medViewContainer *container = new medViewContainerSingle2(this);
    container->setAcceptDrops(false);
    container->setView(view);
    content << container;

    this->layout(content);

    medViewContainer::setView (view);

    d2->views << view;

    // d->view = view; // set in medViewContainer::setView(view)

    // d->view->reset();

    if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
        d->pool->appendView (medView);

    connect (view, SIGNAL (closing()),         this, SLOT (onViewClosing()));
    connect (view, SIGNAL (fullScreen(bool)),  this, SLOT (onViewFullScreen(bool)));
    connect (view, SIGNAL (changeDaddy(bool)),
             this, SLOT (onDaddyChanged(bool)));

    this->setCurrent( container );
    emit viewAdded (view);
}

void medViewContainerMulti::layout(QList<QWidget *> content)
{
    int row = 0;
    int col = 0, colmax = 0;

    for(int i = 0; i < content.count()-1; i++) {

        if(((col+1)*(row+1)) <= content.count()-1) {

            qreal rratio = qMin(((qreal)this->height()/(qreal)(row+2)), ((qreal)this->width()/(qreal)(col+1)));
            qreal cratio = qMin(((qreal)this->height()/(qreal)(row+1)), ((qreal)this->width()/(qreal)(col+2)));

            if(rratio > cratio) {
                row++;
                col = 0;
            } else {
                col++;
            }

            colmax = qMax(col, colmax);
        }
    }

    int layout_row = 0;
    int layout_col = 0;

    for(int i = 0; i < content.size(); i++) {

        d->layout->addWidget(content.at(i), layout_row, layout_col);

        if(layout_col == colmax) {
            layout_row++;
            layout_col = 0;
        } else {
            layout_col++;
        }
    }

    d->layout->setContentsMargins(1, 1, 1, 1);
}

void medViewContainerMulti::onViewClosing (void)
{
    if (dtkAbstractView *view =
        dynamic_cast<dtkAbstractView *>(this->sender())) {

        // needed for selecting another container as current afterwards
        QWidget * predContainer   = NULL;
        QWidget * succContainer   = NULL;
        bool      closedItemFound = false;

        QWidget * closedContainer =
            dynamic_cast< QWidget * >( view->widget()->parent() );
        QList<QWidget *> content;
        for (int i = 0; i < d->layout->rowCount(); i++) {
            for (int j = 0; j < d->layout->columnCount(); j++) {
                QLayoutItem * item = d->layout->itemAtPosition(i, j);
                if ( item != NULL ) {
                    QWidget * container = item->widget();
                    if ( container == closedContainer ) {
                        container->hide();
                        closedItemFound = true;
                    }
                    else {
                        content << container; // keep the container in layout
                        container->show(); // in case view was hidden

                        // remember the predecessor resp. successor of
                        // the closed container
                        if ( closedItemFound ) {
                            if ( succContainer == NULL )
                                succContainer = container;
                        }
                        else
                            predContainer = container;
                    }

                    d->layout->removeItem(item);
                }
            }
        }

        disconnect (view, SIGNAL (closing()),
                    this, SLOT (onViewClosing()));
        disconnect (view, SIGNAL (fullScreen(bool)),
                    this, SLOT (onViewFullScreen(bool)));
        disconnect (d->view, SIGNAL (changeDaddy(bool)),
                    this,    SLOT (onDaddyChanged(bool)));

        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
            d->pool->removeView (medView);

        d2->views.removeOne (view);

        emit viewRemoved (view);

        view->close();

        delete closedContainer;

        this->layout (content);

        medViewContainer * current =
            dynamic_cast< medViewContainer * >( succContainer );
        if ( current == NULL )
            current = dynamic_cast< medViewContainer * >( predContainer );
        if ( current == NULL )
            current = this;
        this->setCurrent( current );

        this->update();

        // qDebug() << this << __func__;
        // qDebug() << "isRoot:    " << this->isRoot();
        // qDebug() << "isLeaf:    " << this->isLeaf();
        // qDebug() << "isEmpty:   " << this->isEmpty();
        // qDebug() << "isCurrent: " << this->isCurrent();
    }
}

void medViewContainerMulti::onViewFullScreen (bool value)
{
  if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) {
      if (value) {
          QList<QWidget *> content;
	  for(int i = 0; i < d->layout->rowCount() ; i++) {
            for(int j = 0; j < d->layout->columnCount() ; j++) {
	      if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
		if(item->widget()!=view->widget()->parent())
		  item->widget()->hide();
	      }
            }
	  }
      }
      else {
	QList<QWidget *> content;
	for(int i = 0; i < d->layout->rowCount() ; i++) {
	  for(int j = 0; j < d->layout->columnCount() ; j++) {
	    if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
	      if(item->widget()!=view->widget()->parent())
		item->widget()->show();
	  }
	  }
	}
      }
  }
}

void medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event)
{
    medViewContainer::dragEnterEvent(event);
}

void medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event)
{
    medViewContainer::dragMoveEvent(event);
}

void medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event)
{
    medViewContainer::dragLeaveEvent(event);
}

void medViewContainerMulti::dropEvent(QDropEvent *event)
{
    if(medViewContainerMulti *container = dynamic_cast<medViewContainerMulti *>(this->parentWidget())) {
        this->setCurrent(container);
    }
    else {
        this->setCurrent(this);
    }

    medViewContainer::dropEvent(event);
}

void medViewContainerMulti::focusInEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}

void medViewContainerMulti::focusOutEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}
<commit_msg>fix bug<commit_after>/* medViewContainerMulti.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Wed Mar 17 11:01:46 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 56
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medViewContainer_p.h"
#include "medViewContainerMulti.h"
#include "medViewPool.h"

#include <dtkCore/dtkAbstractView.h>

#include <medCore/medAbstractView.h>
#include <medCore/medViewManager.h>

medViewContainerSingle2::~medViewContainerSingle2()
{
}

void medViewContainerSingle2::setView (dtkAbstractView *view)
{
    d->layout->setContentsMargins(1, 1, 1, 1);
    d->layout->addWidget(view->widget(), 0, 0);
    d->view = view;

    // d->pool->appendView (view); // only difference with medViewContainerSingle: do not add the view to the pool
    connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));
}

bool medViewContainerSingle2::isLeaf(void) const
{
    return true;
}

void medViewContainerSingle2::onViewClosing (void)
{
    if (d->view) {
        d->layout->removeWidget(d->view->widget());
        d->view->widget()->hide();
        disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));
        // d->pool->removeView (d->view); // do not remove it from the pool
        d->view = NULL;
    }

    // qDebug() << this << __func__;
    // qDebug() << "isRoot:    " << this->isRoot();
    // qDebug() << "isLeaf:    " << this->isLeaf();
    // qDebug() << "isEmpty:   " << this->isEmpty();
    // qDebug() << "isCurrent: " << this->isCurrent();
}

class medViewContainerMultiPrivate
{
public:
    QList<dtkAbstractView *> views;
};

medViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate)
{
}

medViewContainerMulti::~medViewContainerMulti()
{
    medViewContainer::setView(0);

    delete d2;
    d2 = NULL;
}

void medViewContainerMulti::split(int rows, int cols)
{
    Q_UNUSED(rows);
    Q_UNUSED(cols);

    // Don't split a multi view container

    return;
}

dtkAbstractView *medViewContainerMulti::view(void) const
{
    return NULL;
}

QList<dtkAbstractView*> medViewContainerMulti::views (void) const
{
    return d2->views;
}

void medViewContainerMulti::setView(dtkAbstractView *view)
{
    if (!view)
        return;

    if (d2->views.contains (view))
        return;

    QList<QWidget *> content;
    for(int i = 0; i < d->layout->rowCount() ; i++) {
        for(int j = 0; j < d->layout->columnCount() ; j++) {
            if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
                content << item->widget();
                d->layout->removeItem(item);
            }
        }
    }

    medViewContainer *container = new medViewContainerSingle2(this);
    container->setAcceptDrops(false);
    container->setView(view);
    content << container;

    this->layout(content);

    medViewContainer::setView (view);

    d2->views << view;

    // d->view = view; // set in medViewContainer::setView(view)

    // d->view->reset();

    if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
        d->pool->appendView (medView);

    connect (view, SIGNAL (closing()),         this, SLOT (onViewClosing()));
    connect (view, SIGNAL (fullScreen(bool)),  this, SLOT (onViewFullScreen(bool)));
    connect (view, SIGNAL (changeDaddy(bool)),
             this, SLOT (onDaddyChanged(bool)));

    this->setCurrent( container );
    emit viewAdded (view);
}

void medViewContainerMulti::layout(QList<QWidget *> content)
{
    int row = 0;
    int col = 0, colmax = 0;

    for(int i = 0; i < content.count()-1; i++) {

        if(((col+1)*(row+1)) <= content.count()-1) {

            qreal rratio = qMin(((qreal)this->height()/(qreal)(row+2)), ((qreal)this->width()/(qreal)(col+1)));
            qreal cratio = qMin(((qreal)this->height()/(qreal)(row+1)), ((qreal)this->width()/(qreal)(col+2)));

            if(rratio > cratio) {
                row++;
                col = 0;
            } else {
                col++;
            }

            colmax = qMax(col, colmax);
        }
    }

    int layout_row = 0;
    int layout_col = 0;

    for(int i = 0; i < content.size(); i++) {

        d->layout->addWidget(content.at(i), layout_row, layout_col);

        if(layout_col == colmax) {
            layout_row++;
            layout_col = 0;
        } else {
            layout_col++;
        }
    }

    d->layout->setContentsMargins(1, 1, 1, 1);
}

void medViewContainerMulti::onViewClosing (void)
{
    if (dtkAbstractView *view =
        dynamic_cast<dtkAbstractView *>(this->sender())) {

        // needed for selecting another container as current afterwards
        QWidget * predContainer   = NULL;
        QWidget * succContainer   = NULL;
        bool      closedItemFound = false;

        QWidget * closedContainer =
            dynamic_cast< QWidget * >( view->widget()->parent() );
        QList<QWidget *> content;
        for (int i = 0; i < d->layout->rowCount(); i++) {
            for (int j = 0; j < d->layout->columnCount(); j++) {
                QLayoutItem * item = d->layout->itemAtPosition(i, j);
                if ( item != NULL ) {
                    QWidget * container = item->widget();
                    if ( container == closedContainer ) {
                        container->hide();
                        closedItemFound = true;
                    }
                    else {
                        content << container; // keep the container in layout
                        container->show(); // in case view was hidden

                        // remember the predecessor resp. successor of
                        // the closed container
                        if ( closedItemFound ) {
                            if ( succContainer == NULL )
                                succContainer = container;
                        }
                        else
                            predContainer = container;
                    }

                    d->layout->removeItem(item);
                }
            }
        }

        disconnect (view, SIGNAL (closing()),
                    this, SLOT (onViewClosing()));
        disconnect (view, SIGNAL (fullScreen(bool)),
                    this, SLOT (onViewFullScreen(bool)));
        disconnect (view, SIGNAL (changeDaddy(bool)),
                    this, SLOT (onDaddyChanged(bool)));

        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
            d->pool->removeView (medView);

        d2->views.removeOne (view);

        emit viewRemoved (view);

        view->close();

        delete closedContainer;

        this->layout (content);

        medViewContainer * current =
            dynamic_cast< medViewContainer * >( succContainer );
        if ( current == NULL )
            current = dynamic_cast< medViewContainer * >( predContainer );
        if ( current == NULL )
            current = this;
        this->setCurrent( current );

        this->update();

        // qDebug() << this << __func__;
        // qDebug() << "isRoot:    " << this->isRoot();
        // qDebug() << "isLeaf:    " << this->isLeaf();
        // qDebug() << "isEmpty:   " << this->isEmpty();
        // qDebug() << "isCurrent: " << this->isCurrent();
    }
}

void medViewContainerMulti::onViewFullScreen (bool value)
{
  if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) {
      if (value) {
          QList<QWidget *> content;
	  for(int i = 0; i < d->layout->rowCount() ; i++) {
            for(int j = 0; j < d->layout->columnCount() ; j++) {
	      if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
		if(item->widget()!=view->widget()->parent())
		  item->widget()->hide();
	      }
            }
	  }
      }
      else {
	QList<QWidget *> content;
	for(int i = 0; i < d->layout->rowCount() ; i++) {
	  for(int j = 0; j < d->layout->columnCount() ; j++) {
	    if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
	      if(item->widget()!=view->widget()->parent())
		item->widget()->show();
	  }
	  }
	}
      }
  }
}

void medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event)
{
    medViewContainer::dragEnterEvent(event);
}

void medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event)
{
    medViewContainer::dragMoveEvent(event);
}

void medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event)
{
    medViewContainer::dragLeaveEvent(event);
}

void medViewContainerMulti::dropEvent(QDropEvent *event)
{
    if(medViewContainerMulti *container = dynamic_cast<medViewContainerMulti *>(this->parentWidget())) {
        this->setCurrent(container);
    }
    else {
        this->setCurrent(this);
    }

    medViewContainer::dropEvent(event);
}

void medViewContainerMulti::focusInEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}

void medViewContainerMulti::focusOutEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <boost/program_options.hpp>
#include <qi/trackable.hpp>
#include <qi/applicationsession.hpp>
#include <qi/anyvalue.hpp>

static void onDisconnected(const std::string& /*errorMessage*/)
{
  ::qi::Application::stop();
}

static std::string _address;
static std::string _listenAddress;
static bool _standAlone = false;

static void parseAddress()
{
  namespace po = boost::program_options;
  po::options_description desc("ApplicationSession options");

  desc.add_options()
      ("qi-url", po::value<std::string>(&_address), "The address of the service directory")
      ("qi-listen-url", po::value<std::string>(&_listenAddress), "The url to listen to")
      ("qi-standalone", "create a standalone session (this will use qi-listen-url if provided");

  po::variables_map vm;
  po::parsed_options parsed =
      po::command_line_parser(qi::Application::arguments()).options(desc).allow_unregistered().run();
  po::store(parsed, vm);
  po::notify(vm);

  qi::Application::setArguments(po::collect_unrecognized(parsed.options, po::include_positional));
  _standAlone = vm.count("qi-standalone");

  {
    po::options_description descTmp;
    descTmp.add_options()
        ("help,h", "");

    po::variables_map vmTmp;
    po::store(po::command_line_parser(qi::Application::arguments()).options(descTmp).allow_unregistered().run(),
              vmTmp);

    if (vmTmp.count("help"))
      std::cout << desc << std::endl;
  }
}

// This function is used to add the callback before the call of Application's constructor
static int& addParseOptions(int& argc)
{
  qi::Application::atEnter(parseAddress);
  return argc;
}

namespace qi
{
class ApplicationSessionPrivate : public Trackable<ApplicationSessionPrivate>
{
public:
  ApplicationSessionPrivate(const ApplicationSession::Config& config)
    : _session(new qi::Session)
    , _init(false)
  {
    if (!(config.option() & qi::ApplicationSession::Option_NoAutoExit))
    {
      _session->disconnected.connect(&::onDisconnected);
    }

    if (_standAlone && !_address.empty())
      throw std::runtime_error("You cannot be standAlone if you specified --qi-url to connect");

    _standAlone = _standAlone ? _standAlone : config.defaultStandAlone();
    if (!_address.empty())
    {
      _url = Url(_address, "tcp", 9559);
      _standAlone = false;
    }
    else
    {
      _url = config.defaultUrl();
    }
    _listenUrl = _listenAddress.empty() ? config.defaultListenUrl() : Url(_listenAddress, "tcp", 9559);
  }

  virtual ~ApplicationSessionPrivate()
  {
    destroy();
    qi::Application::stop();
    _session->close();
  }

  void connect()
  {
    if (_standAlone)
    {
      _session->listenStandalone(_listenUrl);
      return;
    }

    // listen + connect
    _session->connect(_url);
    if (!_listenAddress.empty())
      _session->listen(_listenUrl);
  }

public:
  SessionPtr _session;
  bool _init;
  Url _url;
  Url _listenUrl;
  boost::mutex _mutex;
};

enum StateMachineConfig
{
  StateMachineConfig_unset = 0,
  StateMachineConfig_standAlone = 1,
  StateMachineConfig_connect = 2,
};

ApplicationSession::Config::Config()
  : _stateMachine(StateMachineConfig_unset)
  , _opt(Option_None)
  , _url("tcp://127.0.0.1:9559")
  , _listenUrl("tcp://0.0.0.0:9559")
{
}

ApplicationSession::Config::~Config()
{
}

ApplicationSession::Config& ApplicationSession::Config::setDefaultStandAlone(bool standAlone)
{
  if (_stateMachine == StateMachineConfig_connect)
    throw std::runtime_error("You cannot be standAlone if you specified url to connect");

  if (standAlone)
    _stateMachine = StateMachineConfig_standAlone;

  return *this;
}
bool ApplicationSession::Config::defaultStandAlone() const
{
  return _stateMachine == StateMachineConfig_standAlone;
}

ApplicationSession::Config& ApplicationSession::Config::setOption(ApplicationSession::Option opt)
{
  _opt = opt;
  return *this;
}
ApplicationSession::Option ApplicationSession::Config::option() const
{
  return _opt;
}

ApplicationSession::Config& ApplicationSession::Config::setDefaultUrl(const Url& url)
{
  if (_stateMachine == StateMachineConfig_standAlone)
    throw std::runtime_error("You cannot specify url to connect if you are standAlone");

  _url = url;
  _stateMachine = StateMachineConfig_connect;
  return *this;
}
const Url& ApplicationSession::Config::defaultUrl() const
{
  return _url;
}

ApplicationSession::Config& ApplicationSession::Config::setDefaultListenUrl(const Url& listenUrl)
{
  _listenUrl = listenUrl;
  return *this;
}
const Url& ApplicationSession::Config::defaultListenUrl() const
{
  return _listenUrl;
}

ApplicationSession::Config& ApplicationSession::Config::setName(const std::string& name)
{
  _name = name;
  return *this;
}
const std::string& ApplicationSession::Config::name() const
{
  return _name;
}

static void envConfigInit(qi::ApplicationSession::Config& conf)
{
  std::string listenUrl = qi::os::getenv("QI_LISTEN_URL");
  std::string sdUrl = qi::os::getenv("QI_URL");

  if (listenUrl.length())
    conf.setDefaultListenUrl(Url(listenUrl));
  if (sdUrl.length())
    conf.setDefaultUrl(sdUrl);
}

ApplicationSession::ApplicationSession(int& argc, char**& argv, int opt, const Url& url)
  : Application(::addParseOptions(argc), argv)
{
  Config config;
  envConfigInit(config);
  config.setDefaultUrl(url);
  config.setOption((Option)opt);

  _p = new ApplicationSessionPrivate(config);
}
ApplicationSession::ApplicationSession(const std::string& name,
                                       int& argc,
                                       char**& argv,
                                       int opt,
                                       const Url& url)
  : Application(::addParseOptions(argc), argv, name)
{
  Config config;
  envConfigInit(config);
  config.setName(name);
  config.setDefaultUrl(url);
  config.setOption((Option)opt);

  _p = new ApplicationSessionPrivate(config);
}

ApplicationSession::ApplicationSession(int& argc, char**& argv, const Config& defaultConfig)
  : Application(::addParseOptions(argc), argv, defaultConfig.name())
{
  Config config(defaultConfig);
  envConfigInit(config);
  _p = new ApplicationSessionPrivate(config);
}

ApplicationSession::~ApplicationSession()
{
  delete _p;
  _p = 0;
}

SessionPtr ApplicationSession::session()
{
  return _p->_session;
}

Url ApplicationSession::url()
{
  return _p->_url;
}

Url ApplicationSession::listenUrl()
{
  return _p->_listenUrl;
}

void ApplicationSession::start()
{
  startSession();
}

void ApplicationSession::startSession()
{
  {
    boost::mutex::scoped_lock lock(_p->_mutex);

    if (_p->_init)
    {
      return;
    }
    _p->_init = true;
  }

  // The connection is asynchronous, therefore a wait is expected here
  _p->connect();
}

void ApplicationSession::run()
{
  startSession();
  Application::run();
}
}
<commit_msg>ApplicationSession: fix initialization<commit_after>/*
 * Copyright (c) 2013 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <boost/program_options.hpp>
#include <qi/trackable.hpp>
#include <qi/applicationsession.hpp>
#include <qi/anyvalue.hpp>

static void onDisconnected(const std::string& /*errorMessage*/)
{
  ::qi::Application::stop();
}

static std::string _address;
static std::string _listenAddress;
static bool _standAlone = false;

static void parseAddress()
{
  namespace po = boost::program_options;
  po::options_description desc("ApplicationSession options");

  desc.add_options()
      ("qi-url", po::value<std::string>(&_address), "The address of the service directory")
      ("qi-listen-url", po::value<std::string>(&_listenAddress), "The url to listen to")
      ("qi-standalone", "create a standalone session (this will use qi-listen-url if provided");

  po::variables_map vm;
  po::parsed_options parsed =
      po::command_line_parser(qi::Application::arguments()).options(desc).allow_unregistered().run();
  po::store(parsed, vm);
  po::notify(vm);

  qi::Application::setArguments(po::collect_unrecognized(parsed.options, po::include_positional));
  _standAlone = vm.count("qi-standalone");

  {
    po::options_description descTmp;
    descTmp.add_options()
        ("help,h", "");

    po::variables_map vmTmp;
    po::store(po::command_line_parser(qi::Application::arguments()).options(descTmp).allow_unregistered().run(),
              vmTmp);

    if (vmTmp.count("help"))
      std::cout << desc << std::endl;
  }
}

// This function is used to add the callback before the call of Application's constructor
static int& addParseOptions(int& argc)
{
  qi::Application::atEnter(parseAddress);
  return argc;
}

namespace qi
{
class ApplicationSessionPrivate : public Trackable<ApplicationSessionPrivate>
{
public:
  ApplicationSessionPrivate(const ApplicationSession::Config& config)
    : _session(new qi::Session)
    , _init(false)
  {
    if (!(config.option() & qi::ApplicationSession::Option_NoAutoExit))
    {
      _session->disconnected.connect(&::onDisconnected);
    }

    if (_standAlone && !_address.empty())
      throw std::runtime_error("You cannot be standAlone if you specified --qi-url to connect");

    _standAlone = _standAlone ? _standAlone : config.defaultStandAlone();
    if (!_address.empty())
    {
      _url = Url(_address, "tcp", 9559);
      _standAlone = false;
    }
    else
    {
      _url = config.defaultUrl();
    }
    _listenUrl = _listenAddress.empty() ? config.defaultListenUrl() : Url(_listenAddress, "tcp", 9559);
  }

  virtual ~ApplicationSessionPrivate()
  {
    destroy();
    qi::Application::stop();
    _session->close();
  }

  void connect()
  {
    if (_standAlone)
    {
      _session->listenStandalone(_listenUrl);
      return;
    }

    // listen + connect
    _session->connect(_url);
    if (!_listenAddress.empty())
      _session->listen(_listenUrl);
  }

public:
  SessionPtr _session;
  bool _init;
  Url _url;
  Url _listenUrl;
  boost::mutex _mutex;
};

enum StateMachineConfig
{
  StateMachineConfig_unset = 0,
  StateMachineConfig_standAlone = 1,
  StateMachineConfig_connect = 2,
};

ApplicationSession::Config::Config()
  : _stateMachine(StateMachineConfig_unset)
  , _opt(Option_None)
  , _url("tcp://127.0.0.1:9559")
  , _listenUrl("tcp://0.0.0.0:9559")
{
}

ApplicationSession::Config::~Config()
{
}

ApplicationSession::Config& ApplicationSession::Config::setDefaultStandAlone(bool standAlone)
{
  if (_stateMachine == StateMachineConfig_connect)
    throw std::runtime_error("You cannot be standAlone if you specified url to connect");

  if (standAlone)
    _stateMachine = StateMachineConfig_standAlone;

  return *this;
}
bool ApplicationSession::Config::defaultStandAlone() const
{
  return _stateMachine == StateMachineConfig_standAlone;
}

ApplicationSession::Config& ApplicationSession::Config::setOption(ApplicationSession::Option opt)
{
  _opt = opt;
  return *this;
}
ApplicationSession::Option ApplicationSession::Config::option() const
{
  return _opt;
}

ApplicationSession::Config& ApplicationSession::Config::setDefaultUrl(const Url& url)
{
  if (_stateMachine == StateMachineConfig_standAlone)
    throw std::runtime_error("You cannot specify url to connect if you are standAlone");

  _url = url;
  _stateMachine = StateMachineConfig_connect;
  return *this;
}
const Url& ApplicationSession::Config::defaultUrl() const
{
  return _url;
}

ApplicationSession::Config& ApplicationSession::Config::setDefaultListenUrl(const Url& listenUrl)
{
  _listenUrl = listenUrl;
  return *this;
}
const Url& ApplicationSession::Config::defaultListenUrl() const
{
  return _listenUrl;
}

ApplicationSession::Config& ApplicationSession::Config::setName(const std::string& name)
{
  _name = name;
  return *this;
}
const std::string& ApplicationSession::Config::name() const
{
  return _name;
}

static void envConfigInit(qi::ApplicationSession::Config& conf)
{
  std::string listenUrl = qi::os::getenv("QI_LISTEN_URL");
  std::string sdUrl = qi::os::getenv("QI_URL");

  if (listenUrl.length())
    conf.setDefaultListenUrl(Url(listenUrl));
  if (sdUrl.length() && !conf.defaultStandAlone())
    conf.setDefaultUrl(sdUrl);
}

ApplicationSession::ApplicationSession(int& argc, char**& argv, int opt, const Url& url)
  : Application(::addParseOptions(argc), argv)
{
  Config config;
  envConfigInit(config);
  config.setDefaultUrl(url);
  config.setOption((Option)opt);

  _p = new ApplicationSessionPrivate(config);
}
ApplicationSession::ApplicationSession(const std::string& name,
                                       int& argc,
                                       char**& argv,
                                       int opt,
                                       const Url& url)
  : Application(::addParseOptions(argc), argv, name)
{
  Config config;
  envConfigInit(config);
  config.setName(name);
  config.setDefaultUrl(url);
  config.setOption((Option)opt);

  _p = new ApplicationSessionPrivate(config);
}

ApplicationSession::ApplicationSession(int& argc, char**& argv, const Config& defaultConfig)
  : Application(::addParseOptions(argc), argv, defaultConfig.name())
{
  Config config(defaultConfig);
  envConfigInit(config);
  _p = new ApplicationSessionPrivate(config);
}

ApplicationSession::~ApplicationSession()
{
  delete _p;
  _p = 0;
}

SessionPtr ApplicationSession::session()
{
  return _p->_session;
}

Url ApplicationSession::url()
{
  return _p->_url;
}

Url ApplicationSession::listenUrl()
{
  return _p->_listenUrl;
}

void ApplicationSession::start()
{
  startSession();
}

void ApplicationSession::startSession()
{
  {
    boost::mutex::scoped_lock lock(_p->_mutex);

    if (_p->_init)
    {
      return;
    }
    _p->_init = true;
  }

  // The connection is asynchronous, therefore a wait is expected here
  _p->connect();
}

void ApplicationSession::run()
{
  startSession();
  Application::run();
}
}
<|endoftext|>


<commit_before>/* Copyright (C) 2019 European Spallation Source, ERIC. See LICENSE file */
//===----------------------------------------------------------------------===//
///
/// \file
///
/// \brief using nlohmann json parser to read configurations from file
//===----------------------------------------------------------------------===//

#include <common/Log.h>
#include <loki/geometry/Config.h>
#include <common/JsonFile.h>

namespace Loki {

///
Config::Config() {}

Config::Config(std::string ConfigFile) {
    nlohmann::json root = from_json_file(ConfigFile);

    try {
      auto Name = root["Detector"].get<std::string>();

      // Assumed the same for all straws in all banks
      Resolution = root["StrawResolution"].get<unsigned int>();

      auto PanelConfig = root["PanelConfig"];
      uint8_t Index{0};
      for (auto &Mapping : PanelConfig) {
        auto Ring = Mapping["Bank"].get<unsigned int>();
        assert(Ring == Index);
        bool Vertical = Mapping["Vertical"].get<bool>();
        auto TubesZ = Mapping["TubesZ"].get<unsigned int>();
        auto TubesN = Mapping["TubesN"].get<unsigned int>();
        auto StrawOffset = Mapping["StrawOffset"].get<unsigned int>();

        NTubesTotal += TubesZ * TubesN;

        LOG(INIT, Sev::Info, "JSON config - Detector {}, Ring {}, Vertical {}, TubesZ {}, TubesN {}, StrawOffset {}",
          Name, Ring, Vertical, TubesZ, TubesN, StrawOffset);

        PanelGeometry Temp(TubesZ, TubesN, StrawOffset);
        Panels.push_back(Temp);
        Index++;
      }

      Pixels = NTubesTotal * PanelGeometry::NStraws * Resolution;
      Geometry = new ESSGeometry(Resolution, NTubesTotal * 7, 1, 1);

    }
    catch (...) {
      LOG(INIT, Sev::Error, "JSON config - error: Invalid Json file: {}", ConfigFile);
      throw std::runtime_error("Invalid Json file");
      return;
    }
}

} // namespace
<commit_msg>remove assert on loki configuration parsing as it no longer applies<commit_after>/* Copyright (C) 2019 European Spallation Source, ERIC. See LICENSE file */
//===----------------------------------------------------------------------===//
///
/// \file
///
/// \brief using nlohmann json parser to read configurations from file
//===----------------------------------------------------------------------===//

#include <common/Log.h>
#include <loki/geometry/Config.h>
#include <common/JsonFile.h>

namespace Loki {

///
Config::Config() {}

Config::Config(std::string ConfigFile) {
    nlohmann::json root = from_json_file(ConfigFile);

    try {
      auto Name = root["Detector"].get<std::string>();

      // Assumed the same for all straws in all banks
      Resolution = root["StrawResolution"].get<unsigned int>();

      auto PanelConfig = root["PanelConfig"];
      for (auto &Mapping : PanelConfig) {
        auto Ring = Mapping["Bank"].get<unsigned int>();
        bool Vertical = Mapping["Vertical"].get<bool>();
        auto TubesZ = Mapping["TubesZ"].get<unsigned int>();
        auto TubesN = Mapping["TubesN"].get<unsigned int>();
        auto StrawOffset = Mapping["StrawOffset"].get<unsigned int>();

        NTubesTotal += TubesZ * TubesN;

        LOG(INIT, Sev::Info, "JSON config - Detector {}, Ring {}, Vertical {}, TubesZ {}, TubesN {}, StrawOffset {}",
          Name, Ring, Vertical, TubesZ, TubesN, StrawOffset);

        PanelGeometry Temp(TubesZ, TubesN, StrawOffset);
        Panels.push_back(Temp);
      }

      Pixels = NTubesTotal * PanelGeometry::NStraws * Resolution;
      Geometry = new ESSGeometry(Resolution, NTubesTotal * 7, 1, 1);

    }
    catch (...) {
      LOG(INIT, Sev::Error, "JSON config - error: Invalid Json file: {}", ConfigFile);
      throw std::runtime_error("Invalid Json file");
      return;
    }
}

} // namespace
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/resource.h>
#include <asm/errno.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <malloc.h>
#include <string.h>
#include <utility>
#include <map>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <linux/netfilter.h>

#include <tins/tins.h>
#include "HostMapping.h"
#include "AITF_packet.h"
#include "AITF_connect_state.h"
#include "numbers.c"

#define TLONG 30

using namespace Tins;
using namespace std;

extern HostMapping hosts;

map<AITF_identity, AITF_connect_state> ostate_table;
map<AITF_identity, AITF_connect_state> istate_table;

vector<RRFilter> block_rules;

typedef enum{
	ENFORCE, REQUEST, VERIFY, CORRECT, BLOCK, CEASE
} AITF_type;

typedef struct thread_data{
	IP::address_type addr;
	char buff[1500];
	ssize_t size;
} thread_data;

uint64_t generateNonce(){
	return generate_key();
}

int block_verdict(RREntry r, IP::address_type addr){
	struct timeval start_time;
    gettimeofday(&start_time, NULL);
	int verdict;
	int bypass = start_time.tv_sec;

	for (int i = 0; i < block_rules.size(); i++){
		if (bypass > block_rules.at(i).ttl()){
			continue;
		}
		verdict = block_rules.at(i).match(r, addr);
		if (verdict == 1){
			return NF_ACCEPT;
		}
		if (verdict == 0){
			return NF_DROP;
		}
	}
	return NF_ACCEPT;
}

void send_AITF_message(AITF_packet pack, IP::address_type addr){

	cout << "SENDING PACKET: DEST: " << addr.to_string();
	cout << pack.to_string();

	uint8_t* data = (uint8_t*)malloc(pack.packet_size());
	pack.serialize(data, pack.packet_size());

	int status, sd, len, s, r;
	struct addrinfo hints;
	struct addrinfo *servinfo, *p; // will point to the results

	const char *url, *port;

	port = "11467";
	url = addr.to_string().c_str();

	memset(&hints, 0 , sizeof(hints)); // make sure the stuct is empty
	hints.ai_family = AF_INET; // only IPv4
	hints.ai_socktype = SOCK_DGRAM; // Use a UDP connection
	// getaddrinfo() - fills out an address structure for us with the destination server's info
	if((status = getaddrinfo(url, port, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
		return;
	}

	// loop through all results and connect to the first one we can
	for(p = servinfo; p != NULL; p = p->ai_next)
	{
		if ((sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
	 	 perror("client: socket");
	 	 continue;
		}
		if((connect(sd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0) {
		  	close(sd);
	 	 	perror("client: connect");
		  continue;
		}
		break;
	}
	if (p == NULL) {
		fprintf(stderr, "client: failed to connect\n");
		return;
	}
	freeaddrinfo(servinfo);

	s = send(sd, data, pack.packet_size(), 0);

	close(sd);

	return;
}

uint64_t generateRandomValue(IP::address_type addr, int x){
	return hash_for_destination(addr, x - 1);
}

void AITF_escalation(AITF_packet pack){
	cout << endl << pack.to_string() << endl;

	uint64_t nonce1 = generateNonce();
	ostate_table[pack.identity()].set_nonce1(nonce1);

	AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, ostate_table[pack.identity()].currentRoute()+1, pack.identity());

	ostate_table[pack.identity()].set_currentRoute(request.pointer());

	cout << endl << request.to_string() << endl;

	if (request.identity().filters().size() > request.pointer()){
		send_AITF_message(request, request.identity().filters()[request.pointer()].address());
	}else{
		ostate_table.erase(request.identity());
	}
	return;
}

void AITF_enforce(AITF_packet pack, IP::address_type addr){
	cout << "Host enabled " << hosts.isEnabledHost(addr) << " " << addr << endl;
	if (hosts.isEnabledHost(addr)){
		struct timeval start_time;
    	gettimeofday(&start_time, NULL);
		int bypass = start_time.tv_sec;

		if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() <= bypass){

			ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);

			AITF_escalation(pack);
		}else{
			AITF_connect_state cstate(0,0,0);
			ostate_table.insert(std::make_pair(pack.identity(), cstate));

			uint64_t nonce1 = generateNonce();
			ostate_table[pack.identity()].set_nonce1(nonce1);
			ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);
			ostate_table[pack.identity()].set_currentRoute(1);

			AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, (uint32_t)1, pack.identity().filters(), pack.identity().victim(), pack.identity().size());

			if (request.identity().filters().size() >= 2){
				send_AITF_message(request, request.identity().filters()[1].address());
			}else{
				ostate_table.erase(request.identity());
			}
		}
	}
	return;
}

void AITF_request(AITF_packet pack){
	vector<NetworkInterface> ip_addrs = NetworkInterface::all();
	IP::address_type addr;
	int x;
	int y;
	for (x = ip_addrs.size()-1; x >= 0; x--){
		if (ip_addrs[x].addresses().ip_addr == pack.identity().filters()[pack.pointer()].address()){
			addr = ip_addrs[x].addresses().ip_addr;
			break;
		}
	}

	RRFilter rent = pack.identity().filters()[pack.pointer()];

	//Check the random numbers
	if (generateRandomValue(pack.identity().victim(),1) == rent.random_number_1() || generateRandomValue(pack.identity().victim(),1) == rent.random_number_2()){
		// SEND VERIFY
		AITF_connect_state cstate(0,0,0);
		istate_table[pack.identity()] = cstate;

		// SET NONCE2
		uint64_t nonce2 = generateNonce();
		istate_table[pack.identity()].set_nonce2(nonce2);

		AITF_packet verify((uint8_t)VERIFY, pack.nonce1(), nonce2, pack.pointer(), pack.identity());

		send_AITF_message(verify, verify.identity().victim());
	}else{
		vector<RRFilter> nfilter = pack.identity().filters();
		// SEND CORRECT
		uint64_t r1 = generateRandomValue(pack.identity().victim(), 1);
		uint64_t r2 = generateRandomValue(pack.identity().victim(), 2);
		AITF_packet correct = AITF_packet((uint8_t)CORRECT, pack.nonce1(), (uint64_t)0, pack.pointer(), r1, r2, pack.identity());

		send_AITF_message(correct, correct.identity().victim());
	}

	return;
}

void AITF_verify(AITF_packet pack){
	struct timeval start_time;
    gettimeofday(&start_time, NULL);
	int bypass = start_time.tv_sec;

	if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() <= bypass){

		ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);

		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			AITF_packet block((uint8_t)BLOCK, (uint64_t)0, pack.nonce2(), pack.pointer(), pack.identity());

			send_AITF_message(block, pack.identity().filters()[pack.pointer()].address());
		}
	}
	return;
}

void AITF_correct(AITF_packet pack){
	struct timeval start_time;
    gettimeofday(&start_time, NULL);
	int bypass = start_time.tv_sec;

	if (ostate_table.count(pack.identity())){

		ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);

		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			vector<RRFilter> rent = pack.identity().filters();
			rent[pack.pointer()].set_random_number_1(pack.crn1());
			rent[pack.pointer()].set_random_number_2(pack.crn2());
			rent[pack.pointer()].set_match_type(2);
			AITF_packet enforce = AITF_packet((uint8_t)ENFORCE, (uint64_t)0, (uint64_t)0, pack.pointer(), rent, pack.identity().victim(), rent.size());

			ostate_table.erase(pack.identity());
			ostate_table[enforce.identity()] = cstate;
			ostate_table[enforce.identity()].set_currentRoute(pack.pointer());

			cout << endl << "ENFORCE: " << enforce.to_string() << endl;

			AITF_enforce(enforce, pack.identity().victim());
		}
	}
	return;
}

void AITF_block(AITF_packet pack){
	if (istate_table.count(pack.identity())){
		AITF_connect_state cstate = istate_table.at(pack.identity());
		if (cstate.nonce2() == pack.nonce2()){
			vector<RRFilter> rent = pack.identity().filters();

			RRFilter block = rent.at(pack.pointer()-1);

			cout << endl << "INSTALLING BLOCK: " << block.to_string() << endl;

			struct timeval start_time;
    		gettimeofday(&start_time, NULL);

			block.set_ttl(start_time.tv_sec + TLONG);
			block_rules.push_back(block);

			istate_table.erase(pack.identity());
		}
	}

	return;
}

void AITF_cease(AITF_packet pack){
	// NEVER CEASE! MARCH FORWARDS!
	return;
}

void AITF_action(thread_data* data){

	AITF_packet apacket = AITF_packet((uint8_t*)data->buff, data->size);

	cout << apacket.to_string();

	switch(apacket.packet_type())
	{
		case 0:
			AITF_enforce(apacket, data->addr);
			break;
		case 1:
			AITF_request(apacket);
			break;
		case 2:
			AITF_verify(apacket);
			break;
		case 3:
			AITF_correct(apacket);
			break;
		case 4:
			AITF_block(apacket);
			break;
		case 5:
		default:
			AITF_cease(apacket);
	}
	free(data);
}

void AITF_daemon(void* data){
	int portNumber = 11467;

	struct sockaddr_in serv_addr, client_addr;
	int fd = 0;
	int fdlisten = 0;
	int fdconn = 0;
	int out = 0;
	unsigned int client = sizeof(client_addr);

	// Establish the socket that will be used for listening
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	printf("Socket: %d\n", fd);

	// Do a bind of that socket
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(portNumber);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind( fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

	// Set up to listen
	listen( fd, 10);
	fdlisten = fd;

	ssize_t tsdata;
	thread_data* buff;
	while(1)
	{
		buff = (thread_data*) malloc(sizeof(thread_data));
		tsdata =  recvfrom(fdlisten, buff->buff, 1500, 0, (struct sockaddr *)&client_addr, &client);

		if (tsdata > 0){
			uint32_t conn_addr = client_addr.sin_addr.s_addr;
			buff->addr = IP::address_type(conn_addr);
			buff->size = tsdata;
			//pthread_t helper;
			//pthread_create(&helper, NULL, (void*(*)(void*))AITF_action, buff);
			AITF_action(buff);
		}else{
			free(buff);
		}
	}
}

int intializeAITF(void* filtertable){
	int aitf_thread = 0;
	pthread_t helper;
	pthread_create(&helper, NULL, (void*(*)(void*))AITF_daemon, filtertable);

}<commit_msg>fixed ttl<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/resource.h>
#include <asm/errno.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <malloc.h>
#include <string.h>
#include <utility>
#include <map>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <linux/netfilter.h>

#include <tins/tins.h>
#include "HostMapping.h"
#include "AITF_packet.h"
#include "AITF_connect_state.h"
#include "numbers.c"

#define TLONG 30

using namespace Tins;
using namespace std;

extern HostMapping hosts;

map<AITF_identity, AITF_connect_state> ostate_table;
map<AITF_identity, AITF_connect_state> istate_table;

vector<RRFilter> block_rules;

typedef enum{
	ENFORCE, REQUEST, VERIFY, CORRECT, BLOCK, CEASE
} AITF_type;

typedef struct thread_data{
	IP::address_type addr;
	char buff[1500];
	ssize_t size;
} thread_data;

uint64_t generateNonce(){
	return generate_key();
}

int block_verdict(RREntry r, IP::address_type addr){
	struct timeval start_time;
    gettimeofday(&start_time, NULL);
	int verdict;
	int bypass = start_time.tv_sec;

	for (int i = 0; i < block_rules.size(); i++){
		if (bypass > block_rules.at(i).ttl()){
			continue;
		}
		verdict = block_rules.at(i).match(r, addr);
		if (verdict == 1){
			return NF_ACCEPT;
		}
		if (verdict == 0){
			return NF_DROP;
		}
	}
	return NF_ACCEPT;
}

void send_AITF_message(AITF_packet pack, IP::address_type addr){

	cout << "SENDING PACKET: DEST: " << addr.to_string();
	cout << pack.to_string();

	uint8_t* data = (uint8_t*)malloc(pack.packet_size());
	pack.serialize(data, pack.packet_size());

	int status, sd, len, s, r;
	struct addrinfo hints;
	struct addrinfo *servinfo, *p; // will point to the results

	const char *url, *port;

	port = "11467";
	url = addr.to_string().c_str();

	memset(&hints, 0 , sizeof(hints)); // make sure the stuct is empty
	hints.ai_family = AF_INET; // only IPv4
	hints.ai_socktype = SOCK_DGRAM; // Use a UDP connection
	// getaddrinfo() - fills out an address structure for us with the destination server's info
	if((status = getaddrinfo(url, port, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
		return;
	}

	// loop through all results and connect to the first one we can
	for(p = servinfo; p != NULL; p = p->ai_next)
	{
		if ((sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
	 	 perror("client: socket");
	 	 continue;
		}
		if((connect(sd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0) {
		  	close(sd);
	 	 	perror("client: connect");
		  continue;
		}
		break;
	}
	if (p == NULL) {
		fprintf(stderr, "client: failed to connect\n");
		return;
	}
	freeaddrinfo(servinfo);

	s = send(sd, data, pack.packet_size(), 0);

	close(sd);

	return;
}

uint64_t generateRandomValue(IP::address_type addr, int x){
	return hash_for_destination(addr, x - 1);
}

void AITF_escalation(AITF_packet pack){
	cout << endl << pack.to_string() << endl;

	uint64_t nonce1 = generateNonce();
	ostate_table[pack.identity()].set_nonce1(nonce1);

	AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, ostate_table[pack.identity()].currentRoute()+1, pack.identity());

	ostate_table[pack.identity()].set_currentRoute(request.pointer());

	cout << endl << request.to_string() << endl;

	if (request.identity().filters().size() > request.pointer()){
		send_AITF_message(request, request.identity().filters()[request.pointer()].address());
	}else{
		ostate_table.erase(request.identity());
	}
	return;
}

void AITF_enforce(AITF_packet pack, IP::address_type addr){
	cout << "Host enabled " << hosts.isEnabledHost(addr) << " " << addr << endl;
	if (hosts.isEnabledHost(addr)){
		struct timeval start_time;
    	gettimeofday(&start_time, NULL);
		int bypass = start_time.tv_sec;

		if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() <= bypass){

			ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);

			AITF_escalation(pack);
		}else{
			AITF_connect_state cstate(0,0,0);
			ostate_table.insert(std::make_pair(pack.identity(), cstate));

			uint64_t nonce1 = generateNonce();
			ostate_table[pack.identity()].set_nonce1(nonce1);
			ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);
			ostate_table[pack.identity()].set_currentRoute(1);

			AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, (uint32_t)1, pack.identity().filters(), pack.identity().victim(), pack.identity().size());

			if (request.identity().filters().size() >= 2){
				send_AITF_message(request, request.identity().filters()[1].address());
			}else{
				ostate_table.erase(request.identity());
			}
		}
	}
	return;
}

void AITF_request(AITF_packet pack){
	vector<NetworkInterface> ip_addrs = NetworkInterface::all();
	IP::address_type addr;
	int x;
	int y;
	for (x = ip_addrs.size()-1; x >= 0; x--){
		if (ip_addrs[x].addresses().ip_addr == pack.identity().filters()[pack.pointer()].address()){
			addr = ip_addrs[x].addresses().ip_addr;
			break;
		}
	}

	RRFilter rent = pack.identity().filters()[pack.pointer()];

	//Check the random numbers
	if (generateRandomValue(pack.identity().victim(),1) == rent.random_number_1() || generateRandomValue(pack.identity().victim(),1) == rent.random_number_2()){
		// SEND VERIFY
		AITF_connect_state cstate(0,0,0);
		istate_table[pack.identity()] = cstate;

		// SET NONCE2
		uint64_t nonce2 = generateNonce();
		istate_table[pack.identity()].set_nonce2(nonce2);

		AITF_packet verify((uint8_t)VERIFY, pack.nonce1(), nonce2, pack.pointer(), pack.identity());

		send_AITF_message(verify, verify.identity().victim());
	}else{
		vector<RRFilter> nfilter = pack.identity().filters();
		// SEND CORRECT
		uint64_t r1 = generateRandomValue(pack.identity().victim(), 1);
		uint64_t r2 = generateRandomValue(pack.identity().victim(), 2);
		AITF_packet correct = AITF_packet((uint8_t)CORRECT, pack.nonce1(), (uint64_t)0, pack.pointer(), r1, r2, pack.identity());

		send_AITF_message(correct, correct.identity().victim());
	}

	return;
}

void AITF_verify(AITF_packet pack){
	struct timeval start_time;
    gettimeofday(&start_time, NULL);
	int bypass = start_time.tv_sec;

	if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() <= bypass){

		ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);

		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			AITF_packet block((uint8_t)BLOCK, (uint64_t)0, pack.nonce2(), pack.pointer(), pack.identity());

			send_AITF_message(block, pack.identity().filters()[pack.pointer()].address());
		}
	}
	return;
}

void AITF_correct(AITF_packet pack){
	struct timeval start_time;
    gettimeofday(&start_time, NULL);
	int bypass = start_time.tv_sec;

	if (ostate_table.count(pack.identity())){

		ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6);

		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			vector<RRFilter> rent = pack.identity().filters();
			rent[pack.pointer()].set_random_number_1(pack.crn1());
			rent[pack.pointer()].set_random_number_2(pack.crn2());
			rent[pack.pointer()].set_match_type(2);
			AITF_packet enforce = AITF_packet((uint8_t)ENFORCE, (uint64_t)0, (uint64_t)0, pack.pointer(), rent, pack.identity().victim(), rent.size());

			ostate_table.erase(pack.identity());
			ostate_table[enforce.identity()] = cstate;
			ostate_table[enforce.identity()].set_ttl(bypass+TLONG-TLONG/6);
			ostate_table[enforce.identity()].set_currentRoute(pack.pointer());

			cout << endl << "ENFORCE: " << enforce.to_string() << endl;

			AITF_enforce(enforce, pack.identity().victim());
		}
	}
	return;
}

void AITF_block(AITF_packet pack){
	if (istate_table.count(pack.identity())){
		AITF_connect_state cstate = istate_table.at(pack.identity());
		if (cstate.nonce2() == pack.nonce2()){
			vector<RRFilter> rent = pack.identity().filters();

			RRFilter block = rent.at(pack.pointer()-1);

			cout << endl << "INSTALLING BLOCK: " << block.to_string() << endl;

			struct timeval start_time;
    		gettimeofday(&start_time, NULL);

			block.set_ttl(start_time.tv_sec + TLONG);
			block_rules.push_back(block);

			istate_table.erase(pack.identity());
		}
	}

	return;
}

void AITF_cease(AITF_packet pack){
	// NEVER CEASE! MARCH FORWARDS!
	return;
}

void AITF_action(thread_data* data){

	AITF_packet apacket = AITF_packet((uint8_t*)data->buff, data->size);

	cout << apacket.to_string();

	switch(apacket.packet_type())
	{
		case 0:
			AITF_enforce(apacket, data->addr);
			break;
		case 1:
			AITF_request(apacket);
			break;
		case 2:
			AITF_verify(apacket);
			break;
		case 3:
			AITF_correct(apacket);
			break;
		case 4:
			AITF_block(apacket);
			break;
		case 5:
		default:
			AITF_cease(apacket);
	}
	free(data);
}

void AITF_daemon(void* data){
	int portNumber = 11467;

	struct sockaddr_in serv_addr, client_addr;
	int fd = 0;
	int fdlisten = 0;
	int fdconn = 0;
	int out = 0;
	unsigned int client = sizeof(client_addr);

	// Establish the socket that will be used for listening
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	printf("Socket: %d\n", fd);

	// Do a bind of that socket
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(portNumber);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind( fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

	// Set up to listen
	listen( fd, 10);
	fdlisten = fd;

	ssize_t tsdata;
	thread_data* buff;
	while(1)
	{
		buff = (thread_data*) malloc(sizeof(thread_data));
		tsdata =  recvfrom(fdlisten, buff->buff, 1500, 0, (struct sockaddr *)&client_addr, &client);

		if (tsdata > 0){
			uint32_t conn_addr = client_addr.sin_addr.s_addr;
			buff->addr = IP::address_type(conn_addr);
			buff->size = tsdata;
			//pthread_t helper;
			//pthread_create(&helper, NULL, (void*(*)(void*))AITF_action, buff);
			AITF_action(buff);
		}else{
			free(buff);
		}
	}
}

int intializeAITF(void* filtertable){
	int aitf_thread = 0;
	pthread_t helper;
	pthread_create(&helper, NULL, (void*(*)(void*))AITF_daemon, filtertable);

}<|endoftext|>


<commit_before>#include <fstream>
#include <iomanip>
#include "PrintRecords.h"

using namespace std;

namespace samples
{
	Record ReadRecord(istream& stream, bool bPrompt)
	{
		Record record;

		if (bPrompt)
		{
			cout << "First name: ";
		}
		stream >> record.FirstName;

		if (bPrompt)
		{
			cout << "Last name: ";
		}
		stream >> record.LastName;

		if (bPrompt)
		{
			cout << "Student ID: ";
		}
		stream >> record.StudentID;

		if (bPrompt)
		{
			cout << "Score:  ";
		}
		stream >> record.Score;

		return record;
	}

	void DisplayRecords(fstream& fileStream)
	{
		fileStream.seekg(0);

		string line;
		while (true)
		{
			getline(fileStream, line);

			if (fileStream.eof())
			{
				fileStream.clear();
				break;
			}
			cout << line << endl;
		}
	}

	void WriteFileRecord(fstream& outputStream, const Record& record)
	{
		outputStream.seekp(0, ios_base::end);

		outputStream << record.FirstName << " "
			<< record.LastName << " "
			<< record.StudentID << " "
			<< record.Score << endl;

		outputStream.flush();
	}

	void ManageRecordsExample()
	{
		cout << "+------------------------------+" << endl;
		cout << "|    Manage Records Example    |" << endl;
		cout << "+------------------------------+" << endl;

		fstream fileStream;
		fileStream.open("studentRecords.dat", ios_base::in | ios_base::out);

		bool bExit = false;
		while (!bExit)
		{
			char command = ' ';

			cout << "a: add" << endl
				<< "d: display" << endl
				<< "x: exit" << endl;

			cin >> command;
			cin.ignore(LLONG_MAX, '\n');

			switch (command)
			{
			case 'a':
			{
				Record record = ReadRecord(cin, true);
				WriteFileRecord(fileStream, record);
				break;
			}
			case 'd':
			{
				DisplayRecords(fileStream);
				break;
			}
			case 'x':
			{
				bExit = true;
				break;
			}
			default:
				cout << "invalid input" << endl;
				break;
			}
		}

		fileStream.close();
	}
}<commit_msg>modified<commit_after>#include <fstream>
#include <iomanip>
#include "PrintRecords.h"

using namespace std;

namespace samples
{
	Record ReadRecord(istream& stream, bool bPrompt)
	{
		Record record;

		if (bPrompt)
		{
			cout << "First name: ";
		}
		stream >> record.FirstName;

		if (bPrompt)
		{
			cout << "Last name: ";
		}
		stream >> record.LastName;

		if (bPrompt)
		{
			cout << "Student ID: ";
		}
		stream >> record.StudentID;

		if (bPrompt)
		{
			cout << "Score:  ";
		}
		stream >> record.Score;

		return record;
	}

	void DisplayRecords(fstream& fileStream)
	{
		fileStream.seekg(0);

		string line;
		while (true)
		{
			getline(fileStream, line);

			if (fileStream.eof())
			{
				fileStream.clear();
				break;
			}
			cout << line << endl;
		}
	}

	void WriteFileRecord(fstream& outputStream, const Record& record)
	{
		outputStream.seekp(0, ios_base::end);

		outputStream << record.FirstName << " "
			<< record.LastName << " "
			<< record.StudentID << " "
			<< record.Score << endl;

		outputStream.flush();
	}

	void ManageRecordsExample()
	{
		cout << "+------------------------------+" << endl;
		cout << "|    Manage Records Example    |" << endl;
		cout << "+------------------------------+" << endl;

		fstream fileStream;
		fileStream.open("studentRecords.dat", ios_base::in | ios_base::out);

		bool bExit = false;
		while (!bExit)
		{
			char command = ' ';

			cout << "a: add" << endl
				<< "d: display" << endl
				<< "x: exit" << endl;

			cin >> command;
			cin.ignore(LLONG_MAX, '\n');

			switch (command)
			{
			case 'a':
			{
				Record record = ReadRecord(cin, true);
				WriteFileRecord(fileStream, record);
				break;
			}
			case 'd':
			{
				DisplayRecords(fileStream);
				break;
			}
			case 'x':
			{
				bExit = true;
				break;
			}
			default:
			{
				cout << "invalid input" << endl;
				break;
			}
			}
		}

		fileStream.close();
	}
}<|endoftext|>


<commit_before>// ************************************************************************* //
// * Daily Programmer 2016-03-17 easy: IRC Making a Connection             * //
// * https://www.reddit.com/r/dailyprogrammer/comments/4ad23z/             * //
// ************************************************************************* //

#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <string>
using std::string;

int main(const int argc, const char** argv)
{
    string server;
    unsigned int port = 0;
    string nickName;
    string userName;
    string realName;
    if (argc > 1)
    {
        ifstream configFile(argv[1]);
        if (configFile.is_open())
        {
            getline(configFile, server);
            size_t found = server.find(':');
            if (found < server.size())
            {
                port = stoul(server.substr(found + 1, server.size() - found - 1));
                server = server.substr(0, found);
            }
            getline(configFile, nickName);
            getline(configFile, userName);
            getline(configFile, realName);
            configFile.close();
        }
    }
    else
    {
        cout << "Enter Server: ";
        cin >> server;
        cout << "Enter Port: ";
        cin >> port;
        cout << "Enter Nickname: ";
        cin >> nickName;
        cout << "Enter Username: ";
        cin >> userName;
        cout << "Enter Real name: ";
        cin >> realName;
    }
    return 0;
}
<commit_msg>merging<commit_after>// ************************************************************************* //
// * Daily Programmer 2016-03-17 easy: IRC Making a Connection             * //
// * https://www.reddit.com/r/dailyprogrammer/comments/4ad23z/             * //
// ************************************************************************* //

#include <iostream>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <string>
using std::string;

int main(const int argc, const char** argv)
{
    string server;
    unsigned int port = 0;
    string nickName;
    string userName;
    string realName;
    if (argc > 1)
    {
        ifstream configFile(argv[1]);
        if (configFile.is_open())
        {
            getline(configFile, server);
            size_t found = server.find(':');
            if (found < server.size())
            {
                port = stoul(server.substr(found + 1, server.size() - found - 1));
                server = server.substr(0, found);
            }
            getline(configFile, nickName);
            getline(configFile, userName);
            getline(configFile, realName);
            configFile.close();
        }
    }
    else
    {
        cout << "Enter Server: ";
        cin >> server;
        cout << "Enter Port: ";
        cin >> port;
        cout << "Enter Nickname: ";
        cin >> nickName;
        cout << "Enter Username: ";
        cin >> userName;
        cout << "Enter Real name: ";
        cin >> realName;
    }
    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sessions/content/content_serialized_navigation_driver.h"

#include "base/memory/singleton.h"
#include "components/sessions/serialized_navigation_entry.h"
#include "content/public/common/page_state.h"
#include "content/public/common/referrer.h"
#include "content/public/common/url_constants.h"

namespace sessions {

namespace {
const int kObsoleteReferrerPolicyAlways = 0;
const int kObsoleteReferrerPolicyDefault = 1;
const int kObsoleteReferrerPolicyNever = 2;
const int kObsoleteReferrerPolicyOrigin = 3;
}  // namespace

// static
SerializedNavigationDriver* SerializedNavigationDriver::Get() {
  return ContentSerializedNavigationDriver::GetInstance();
}

// static
ContentSerializedNavigationDriver*
ContentSerializedNavigationDriver::GetInstance() {
  return Singleton<ContentSerializedNavigationDriver,
      LeakySingletonTraits<ContentSerializedNavigationDriver>>::get();
}

ContentSerializedNavigationDriver::ContentSerializedNavigationDriver() {
}

ContentSerializedNavigationDriver::~ContentSerializedNavigationDriver() {
}

int ContentSerializedNavigationDriver::GetDefaultReferrerPolicy() const {
  return blink::WebReferrerPolicyDefault;
}

bool ContentSerializedNavigationDriver::MapReferrerPolicyToOldValues(
    int referrer_policy,
    int* mapped_referrer_policy) const {
  switch (referrer_policy) {
    case blink::WebReferrerPolicyAlways:
    case blink::WebReferrerPolicyDefault:
      // "always" and "default" are the same value in all versions.
      *mapped_referrer_policy = referrer_policy;
      return true;

    case blink::WebReferrerPolicyOrigin:
      // "origin" exists in the old encoding.
      *mapped_referrer_policy = kObsoleteReferrerPolicyOrigin;
      return true;

    default:
      // Everything else is mapped to never.
      *mapped_referrer_policy = kObsoleteReferrerPolicyNever;
      return false;
  }
}

bool ContentSerializedNavigationDriver::MapReferrerPolicyToNewValues(
    int referrer_policy,
    int* mapped_referrer_policy) const {
  switch (referrer_policy) {
    case kObsoleteReferrerPolicyAlways:
    case kObsoleteReferrerPolicyDefault:
      // "always" and "default" are the same value in all versions.
      *mapped_referrer_policy = referrer_policy;
      return true;

    default:
      // Since we don't know what encoding was used, we map the rest to "never".
      *mapped_referrer_policy = blink::WebReferrerPolicyNever;
      return false;
  }
}

std::string
ContentSerializedNavigationDriver::GetSanitizedPageStateForPickle(
    const SerializedNavigationEntry* navigation) const {
  if (!navigation->has_post_data_) {
    return navigation->encoded_page_state_;
  }
  content::PageState page_state =
      content::PageState::CreateFromEncodedData(
          navigation->encoded_page_state_);
  return page_state.RemovePasswordData().ToEncodedData();
}

void ContentSerializedNavigationDriver::Sanitize(
    SerializedNavigationEntry* navigation) const {
  content::Referrer old_referrer(
      navigation->referrer_url_,
      static_cast<blink::WebReferrerPolicy>(navigation->referrer_policy_));
  content::Referrer new_referrer =
      content::Referrer::SanitizeForRequest(navigation->virtual_url_,
                                            old_referrer);

  // No need to compare the policy, as it doesn't change during
  // sanitization. If there has been a change, the referrer needs to be
  // stripped from the page state as well.
  if (navigation->referrer_url_ != new_referrer.url) {
    navigation->referrer_url_ = GURL();
    navigation->referrer_policy_ = GetDefaultReferrerPolicy();
    navigation->encoded_page_state_ =
        StripReferrerFromPageState(navigation->encoded_page_state_);
  }

#if defined(OS_ANDROID)
  // Rewrite the old new tab and welcome page URLs to the new NTP URL.
  if (navigation->virtual_url_.SchemeIs(content::kChromeUIScheme) &&
      (navigation->virtual_url_.host() == "welcome" ||
       navigation->virtual_url_.host() == "newtab")) {
    navigation->virtual_url_ = GURL("chrome-native://newtab/");
    navigation->original_request_url_ = navigation->virtual_url_;
    navigation->encoded_page_state_ = content::PageState::CreateFromURL(
        navigation->virtual_url_).ToEncodedData();
  }
#endif  // defined(OS_ANDROID)
}

std::string ContentSerializedNavigationDriver::StripReferrerFromPageState(
      const std::string& page_state) const {
  return content::PageState::CreateFromEncodedData(page_state)
      .RemoveReferrer()
      .ToEncodedData();
}

}  // namespace sessions
<commit_msg>Revert of [Android] Rewrite old new tab and welcome page URLs. (patchset #1 id:1 of https://codereview.chromium.org/1290663004/ )<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/sessions/content/content_serialized_navigation_driver.h"

#include "base/memory/singleton.h"
#include "components/sessions/serialized_navigation_entry.h"
#include "content/public/common/page_state.h"
#include "content/public/common/referrer.h"

namespace sessions {

namespace {
const int kObsoleteReferrerPolicyAlways = 0;
const int kObsoleteReferrerPolicyDefault = 1;
const int kObsoleteReferrerPolicyNever = 2;
const int kObsoleteReferrerPolicyOrigin = 3;
}  // namespace

// static
SerializedNavigationDriver* SerializedNavigationDriver::Get() {
  return ContentSerializedNavigationDriver::GetInstance();
}

// static
ContentSerializedNavigationDriver*
ContentSerializedNavigationDriver::GetInstance() {
  return Singleton<ContentSerializedNavigationDriver,
      LeakySingletonTraits<ContentSerializedNavigationDriver>>::get();
}

ContentSerializedNavigationDriver::ContentSerializedNavigationDriver() {
}

ContentSerializedNavigationDriver::~ContentSerializedNavigationDriver() {
}

int ContentSerializedNavigationDriver::GetDefaultReferrerPolicy() const {
  return blink::WebReferrerPolicyDefault;
}

bool ContentSerializedNavigationDriver::MapReferrerPolicyToOldValues(
    int referrer_policy,
    int* mapped_referrer_policy) const {
  switch (referrer_policy) {
    case blink::WebReferrerPolicyAlways:
    case blink::WebReferrerPolicyDefault:
      // "always" and "default" are the same value in all versions.
      *mapped_referrer_policy = referrer_policy;
      return true;

    case blink::WebReferrerPolicyOrigin:
      // "origin" exists in the old encoding.
      *mapped_referrer_policy = kObsoleteReferrerPolicyOrigin;
      return true;

    default:
      // Everything else is mapped to never.
      *mapped_referrer_policy = kObsoleteReferrerPolicyNever;
      return false;
  }
}

bool ContentSerializedNavigationDriver::MapReferrerPolicyToNewValues(
    int referrer_policy,
    int* mapped_referrer_policy) const {
  switch (referrer_policy) {
    case kObsoleteReferrerPolicyAlways:
    case kObsoleteReferrerPolicyDefault:
      // "always" and "default" are the same value in all versions.
      *mapped_referrer_policy = referrer_policy;
      return true;

    default:
      // Since we don't know what encoding was used, we map the rest to "never".
      *mapped_referrer_policy = blink::WebReferrerPolicyNever;
      return false;
  }
}

std::string
ContentSerializedNavigationDriver::GetSanitizedPageStateForPickle(
    const SerializedNavigationEntry* navigation) const {
  if (!navigation->has_post_data_) {
    return navigation->encoded_page_state_;
  }
  content::PageState page_state =
      content::PageState::CreateFromEncodedData(
          navigation->encoded_page_state_);
  return page_state.RemovePasswordData().ToEncodedData();
}

void ContentSerializedNavigationDriver::Sanitize(
    SerializedNavigationEntry* navigation) const {
  content::Referrer old_referrer(
      navigation->referrer_url_,
      static_cast<blink::WebReferrerPolicy>(navigation->referrer_policy_));
  content::Referrer new_referrer =
      content::Referrer::SanitizeForRequest(navigation->virtual_url_,
                                            old_referrer);

  // No need to compare the policy, as it doesn't change during
  // sanitization. If there has been a change, the referrer needs to be
  // stripped from the page state as well.
  if (navigation->referrer_url_ != new_referrer.url) {
    navigation->referrer_url_ = GURL();
    navigation->referrer_policy_ = GetDefaultReferrerPolicy();
    navigation->encoded_page_state_ =
        StripReferrerFromPageState(navigation->encoded_page_state_);
  }
}

std::string ContentSerializedNavigationDriver::StripReferrerFromPageState(
      const std::string& page_state) const {
  return content::PageState::CreateFromEncodedData(page_state)
      .RemoveReferrer()
      .ToEncodedData();
}

}  // namespace sessions
<|endoftext|>


<commit_before>#pragma once
#include <atomic>
#include <functional>
#include <memory>

#include <observable/detail/compiler_config.hpp>
OBSERVABLE_BEGIN_CONFIGURE_WARNINGS

namespace observable {

//! Infinite subscription that will not unsubscribe the associated observer
//! when destroyed.
//!
//! \ingroup observable
class infinite_subscription
{
public:
    //! Create a subscription with the specified unsubscribe functor.
    //!
    //! \param[in] unsubscribe Calling this functor will unsubscribe the
    //!                        associated observer.
    //! \note This is for internal use by subject instances.
    explicit infinite_subscription(std::function<void()> const & unsubscribe) :
        unsubscribe_ { unsubscribe }
    { }

    //! Unsubscribe the associated observer from receiving notifications.
    //!
    //! Only the first call of this method will have an effect.
    //!
    //! \note If release() has been called, this method will have no effect.
    void unsubscribe()
    {
        if(!called_ || !unsubscribe_ || called_->test_and_set())
            return;

        try {
            if(unsubscribe_) unsubscribe_();
        } catch(...) {
            called_->clear();
            throw;
        }
    }

    //! Disassociate the subscription from the subscribed observer.
    //!
    //! After calling this method, calling unsubscribe() or destroying the
    //! subscription instance will have no effect.
    //!
    //! \return Functor taking no parameters that will perform the unsubscribe
    //!         when called.
    //!         For example: ``subscription.release()()`` is equivalent to
    //!         ``subscription.unsubscribe()``.
    auto release()
    {
        using std::swap;
        decltype(unsubscribe_) unsub = []() { };
        swap(unsub, unsubscribe_);

        return unsub;
    }

public:
    //! This class is default-constructible.
    infinite_subscription() =default;

    //! This class is not copy-constructible.
    infinite_subscription(infinite_subscription const & ) =delete;

    //! This class is not copy-assignable.
    auto operator=(infinite_subscription const &) -> infinite_subscription & =delete;

    //! This class is move-constructible.
    infinite_subscription(infinite_subscription &&) = default;

    //! This class is move-assignable.
    auto operator=(infinite_subscription &&) -> infinite_subscription & =default;

private:
    std::function<void()> unsubscribe_ { []() { } };

    // std::call_once with a std::once_flag would have worked, but it requires
    // pthreads on Linux. We're using this in order not to bring in that
    // dependency.
    std::unique_ptr<std::atomic_flag> called_ { std::make_unique<std::atomic_flag>() };
};

//! Unsubscribe the associated observer when destroyed.
//!
//! \note All methods of this class can be safely called in parallel, from multiple
//!       threads.
//!
//! \ingroup observable
class unique_subscription final : public infinite_subscription
{
public:
    //! Create an empty subscription.
    //!
    //! \note Calling unsubscribe on an empty subscription will have no effect.
    unique_subscription() =default;

    //! Create an unique subscription from an infinite_subscription.
    //!
    //! \param[in] sub An infinite subscription that will be converted to an
    //!                unique_subscription.
    unique_subscription(infinite_subscription && sub) :
        infinite_subscription(std::move(sub))
    { }

    //! Destructor. Will call unsubscribe().
    //!
    //! \note If release() has been called, this will have no effect.
    ~unique_subscription() { unsubscribe(); }

    using infinite_subscription::operator=;

public:
    //! This class is not copy-constructible.
    unique_subscription(unique_subscription const & ) =delete;

    //! This class is not copy-assignable.
    auto operator=(unique_subscription const &) -> unique_subscription & =delete;

    //! This class is move-constructible.
    unique_subscription(unique_subscription &&) = default;

    //! This class is move-assignable.
    auto operator=(unique_subscription &&) -> unique_subscription & =default;
};

//! Unsubscribe the associated observer when the last instance of the class is
//! destroyed.
//!
//! \note All methods of this class can be safely called in parallel, from multiple
//!       threads.
//!
//! \ingroup observable
class shared_subscription final
{
public:
    //! Create a shared subscription from a temporary infinite subscription.
    //!
    //! \param subscription An infinite subscription that will be converted to a
    //!                     shared subscription.
    //! \note The unique subscription will be released.
    explicit shared_subscription(infinite_subscription && subscription) :
        unsubscribe_ { std::make_shared<unique_subscription>(std::move(subscription)) }
    {
    }

    //! Create an empty shared subscription.
    //!
    //! Calling unsubscribe on an empty shared subscription will have no effect.
    shared_subscription() noexcept =default;

    //! Unsubscribe the associated observer from receiving notifications.
    //!
    //! Only the first call of this method will have an effect.
    void unsubscribe() { unsubscribe_.reset(); }

    //! Return true if the subscription is not empty.
    explicit operator bool() const noexcept { return !!unsubscribe_; }

public:
    //! This class is not copy-constructible.
    shared_subscription(shared_subscription const & ) =default;

    //! This class is not copy-assignable.
    auto operator=(shared_subscription const &) -> shared_subscription & =default;

    //! This class is move-constructible.
    shared_subscription(shared_subscription &&) = default;

    //! This class is move-assignable.
    auto operator=(shared_subscription &&) -> shared_subscription & =default;

private:
    std::shared_ptr<unique_subscription> unsubscribe_;
};

}

OBSERVABLE_END_CONFIGURE_WARNINGS
<commit_msg>Fix comments<commit_after>#pragma once
#include <atomic>
#include <functional>
#include <memory>

#include <observable/detail/compiler_config.hpp>
OBSERVABLE_BEGIN_CONFIGURE_WARNINGS

namespace observable {

//! Infinite subscription that will not unsubscribe the associated observer
//! when destroyed.
//!
//! \ingroup observable
class infinite_subscription
{
public:
    //! Create a subscription with the specified unsubscribe functor.
    //!
    //! \param[in] unsubscribe Calling this functor will unsubscribe the
    //!                        associated observer.
    //! \note This is for internal use by subject instances.
    explicit infinite_subscription(std::function<void()> const & unsubscribe) :
        unsubscribe_ { unsubscribe }
    { }

    //! Unsubscribe the associated observer from receiving notifications.
    //!
    //! Only the first call of this method will have an effect.
    //!
    //! \note If release() has been called, this method will have no effect.
    void unsubscribe()
    {
        if(!called_ || !unsubscribe_ || called_->test_and_set())
            return;

        try {
            if(unsubscribe_) unsubscribe_();
        } catch(...) {
            called_->clear();
            throw;
        }
    }

    //! Disassociate the subscription from the subscribed observer.
    //!
    //! After calling this method, calling unsubscribe() or destroying the
    //! subscription instance will have no effect.
    //!
    //! \return Functor taking no parameters that will perform the unsubscribe
    //!         when called.
    //!         For example: ``subscription.release()()`` is equivalent to
    //!         ``subscription.unsubscribe()``.
    auto release()
    {
        using std::swap;
        decltype(unsubscribe_) unsub = []() { };
        swap(unsub, unsubscribe_);

        return unsub;
    }

public:
    //! This class is default-constructible.
    infinite_subscription() =default;

    //! This class is not copy-constructible.
    infinite_subscription(infinite_subscription const & ) =delete;

    //! This class is not copy-assignable.
    auto operator=(infinite_subscription const &) -> infinite_subscription & =delete;

    //! This class is move-constructible.
    infinite_subscription(infinite_subscription &&) = default;

    //! This class is move-assignable.
    auto operator=(infinite_subscription &&) -> infinite_subscription & =default;

private:
    std::function<void()> unsubscribe_ { []() { } };

    // std::call_once with a std::once_flag would have worked, but it requires
    // pthreads on Linux. We're using this in order not to bring in that
    // dependency.
    std::unique_ptr<std::atomic_flag> called_ { std::make_unique<std::atomic_flag>() };
};

//! Unsubscribe the associated observer when destroyed.
//!
//! \note All methods of this class can be safely called in parallel, from multiple
//!       threads.
//!
//! \ingroup observable
class unique_subscription final : public infinite_subscription
{
public:
    //! Create an empty subscription.
    //!
    //! \note Calling unsubscribe on an empty subscription will have no effect.
    unique_subscription() =default;

    //! Create an unique subscription from an infinite_subscription.
    //!
    //! \param[in] sub An infinite subscription that will be converted to an
    //!                unique_subscription.
    unique_subscription(infinite_subscription && sub) :
        infinite_subscription(std::move(sub))
    { }

    //! Destructor. Will call unsubscribe().
    //!
    //! \note If release() has been called, this will have no effect.
    ~unique_subscription() { unsubscribe(); }

    using infinite_subscription::operator=;

public:
    //! This class is not copy-constructible.
    unique_subscription(unique_subscription const & ) =delete;

    //! This class is not copy-assignable.
    auto operator=(unique_subscription const &) -> unique_subscription & =delete;

    //! This class is move-constructible.
    unique_subscription(unique_subscription &&) = default;

    //! This class is move-assignable.
    auto operator=(unique_subscription &&) -> unique_subscription & =default;
};

//! Unsubscribe the associated observer when the last instance of the class is
//! destroyed.
//!
//! \note All methods of this class can be safely called in parallel, from multiple
//!       threads.
//!
//! \ingroup observable
class shared_subscription final
{
public:
    //! Create a shared subscription from a temporary infinite subscription.
    //!
    //! \param subscription An infinite subscription that will be converted to a
    //!                     shared subscription.
    //! \note The unique subscription will be released.
    explicit shared_subscription(infinite_subscription && subscription) :
        unsubscribe_ { std::make_shared<unique_subscription>(std::move(subscription)) }
    {
    }

    //! Create an empty shared subscription.
    //!
    //! Calling unsubscribe on an empty shared subscription will have no effect.
    shared_subscription() noexcept =default;

    //! Unsubscribe the associated observer from receiving notifications.
    //!
    //! Only the first call of this method will have an effect.
    void unsubscribe() { unsubscribe_.reset(); }

    //! Return true if the subscription is not empty.
    explicit operator bool() const noexcept { return !!unsubscribe_; }

public:
    //! This class is copy-constructible.
    shared_subscription(shared_subscription const & ) =default;

    //! This class is copy-assignable.
    auto operator=(shared_subscription const &) -> shared_subscription & =default;

    //! This class is move-constructible.
    shared_subscription(shared_subscription &&) = default;

    //! This class is move-assignable.
    auto operator=(shared_subscription &&) -> shared_subscription & =default;

private:
    std::shared_ptr<unique_subscription> unsubscribe_;
};

}

OBSERVABLE_END_CONFIGURE_WARNINGS
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Heiko Strathmann
 */
#include <shogun/labels/BinaryLabels.h>

using namespace shogun;

void test_sigmoid_fitting()
{
	CBinaryLabels* labels=new CBinaryLabels(10);
	labels->set_values(SGVector<float64_t>(labels->get_num_labels()));

	for (index_t i=0; i<labels->get_num_labels(); ++i)
		labels->set_value(i%2==0 ? 1 : -1, i);

	labels->get_values().display_vector("scores");
	labels->scores_to_probabilities();

	/* only two probabilities will be the result, repeatedly,
	 * assert against reference implementation */
	ASSERT(CMath::abs(labels->get_value(0)-0.8571428439385661)<10E-15);
	ASSERT(CMath::abs(labels->get_value(1)-0.14285715606143384)<10E-15);

	SG_UNREF(labels);
}

int main()
{
	init_shogun_with_defaults();

//	sg_io->set_loglevel(MSG_DEBUG);

	test_sigmoid_fitting();

	exit_shogun();
	return 0;
}

<commit_msg>removed assertions and print probabilities<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Heiko Strathmann
 */
#include <shogun/labels/BinaryLabels.h>

using namespace shogun;

void test_sigmoid_fitting()
{
	CBinaryLabels* labels=new CBinaryLabels(10);
	labels->set_values(SGVector<float64_t>(labels->get_num_labels()));

	for (index_t i=0; i<labels->get_num_labels(); ++i)
		labels->set_value(i%2==0 ? 1 : -1, i);

	labels->get_values().display_vector("scores");
	labels->scores_to_probabilities();
	labels->get_values().display_vector("probabilities");

	SG_UNREF(labels);
}

int main()
{
	init_shogun_with_defaults();

//	sg_io->set_loglevel(MSG_DEBUG);

	test_sigmoid_fitting();

	exit_shogun();
	return 0;
}

<|endoftext|>


<commit_before>// 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.

#ifndef __STOUT_TRY_HPP__
#define __STOUT_TRY_HPP__

#include <assert.h>

#include <iostream>
#include <string>

#include <stout/abort.hpp>
#include <stout/error.hpp>
#include <stout/option.hpp>
#include <stout/some.hpp>

// This class can represent only one of these states at a time:
//   1) A value of T.
//   2) An error state, with a corresponding error string.
// Calling 'isSome' will return true if it stores a value, in which
// case calling 'get' will return a constant reference to the T
// stored. Calling 'isError' will return true if it stores an error,
// in which case calling 'error' will return the error string.
template <typename T, typename E = Error>
class Try
{
public:
  static_assert(
      std::is_base_of<Error, E>::value,
      "An error type must be, or be inherited from 'Error'.");

  static Try some(const T& t) { return Try(t); }
  static Try error(const E& e) { return Try(e); }

  Try(const T& t)
    : data(Some(t)) {}

  template <
      typename U,
      typename = typename std::enable_if<
          std::is_constructible<T, const U&>::value>::type>
  Try(const U& u) : data(Some(u)) {}

  Try(const E& error) : error_(error) {}

  Try(T&& t)
    : data(Some(std::move(t))) {}

  // We don't need to implement these because we are leveraging
  // Option<T>.
  Try(const Try& that) = default;
  Try(Try&& that) = default;

  ~Try() = default;

  Try& operator=(const Try& that) = default;
  Try& operator=(Try&& that) = default;

  // 'isSome' and 'isError' are mutually exclusive. They correspond
  // to the underlying state of the Option.
  bool isSome() const { return data.isSome(); }
  bool isError() const { return data.isNone(); }

  const T& get() const
  {
    if (!data.isSome()) {
      assert(error_.isSome());
      ABORT("Try::get() but state == ERROR: " + error_->message);
    }
    return data.get();
  }

  T& get()
  {
    return const_cast<T&>(static_cast<const Try&>(*this).get());
  }

  const T* operator->() const { return &get(); }
  T* operator->() { return &get(); }

  // NOTE: This function is intended to return the error of type `E`.
  // However, we return a `std::string` if `E` == `Error` since that's what it
  // used to return, and it's the only data that `Error` holds anyway.
  const typename std::conditional<
      std::is_same<E, Error>::value, std::string, E>::type& error() const
  {
    assert(data.isNone());
    assert(error_.isSome());
    return error_impl(error_.get());
  }

private:
  static const std::string& error_impl(const Error& err) { return err.message; }

  template <typename Err>
  static const Err& error_impl(const Err& err) { return err; }

  // We leverage Option<T> to avoid dynamic allocation of T. This
  // means that the storage for T will be included in this object
  // (Try<T>). Since Option<T> keeps track of whether a value is
  // stored, we just ask it when we want to know whether we are
  // storing a value or an error. Another advantage of leveraging
  // Option<T> is that it takes care of all the manual construction
  // and destruction. This makes the code for Try<T> really simple!
  Option<T> data;
  Option<E> error_;
};

#endif // __STOUT_TRY_HPP__
<commit_msg>Added rvalue reference Try::get overloads.<commit_after>// 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.

#ifndef __STOUT_TRY_HPP__
#define __STOUT_TRY_HPP__

#include <assert.h>

#include <iostream>
#include <string>

#include <stout/abort.hpp>
#include <stout/error.hpp>
#include <stout/option.hpp>
#include <stout/some.hpp>

// This class can represent only one of these states at a time:
//   1) A value of T.
//   2) An error state, with a corresponding error string.
// Calling 'isSome' will return true if it stores a value, in which
// case calling 'get' will return a constant reference to the T
// stored. Calling 'isError' will return true if it stores an error,
// in which case calling 'error' will return the error string.
template <typename T, typename E = Error>
class Try
{
public:
  static_assert(
      std::is_base_of<Error, E>::value,
      "An error type must be, or be inherited from 'Error'.");

  static Try some(const T& t) { return Try(t); }
  static Try error(const E& e) { return Try(e); }

  Try(const T& t)
    : data(Some(t)) {}

  template <
      typename U,
      typename = typename std::enable_if<
          std::is_constructible<T, const U&>::value>::type>
  Try(const U& u) : data(Some(u)) {}

  Try(const E& error) : error_(error) {}

  Try(T&& t)
    : data(Some(std::move(t))) {}

  // We don't need to implement these because we are leveraging
  // Option<T>.
  Try(const Try& that) = default;
  Try(Try&& that) = default;

  ~Try() = default;

  Try& operator=(const Try& that) = default;
  Try& operator=(Try&& that) = default;

  // 'isSome' and 'isError' are mutually exclusive. They correspond
  // to the underlying state of the Option.
  bool isSome() const { return data.isSome(); }
  bool isError() const { return data.isNone(); }

  T& get() & { return get(*this); }
  const T& get() const & { return get(*this); }
  T&& get() && { return get(std::move(*this)); }
  const T&& get() const && { return get(std::move(*this)); }

  const T* operator->() const { return &get(); }
  T* operator->() { return &get(); }

  // NOTE: This function is intended to return the error of type `E`.
  // However, we return a `std::string` if `E` == `Error` since that's what it
  // used to return, and it's the only data that `Error` holds anyway.
  const typename std::conditional<
      std::is_same<E, Error>::value, std::string, E>::type& error() const
  {
    assert(data.isNone());
    assert(error_.isSome());
    return error_impl(error_.get());
  }

private:
  static const std::string& error_impl(const Error& err) { return err.message; }

  template <typename Self>
  static auto get(Self&& self) -> decltype(std::forward<Self>(self).data.get())
  {
    if (!self.data.isSome()) {
      assert(self.error_.isSome());
      ABORT("Try::get() but state == ERROR: " + self.error_->message);
    }
    return std::forward<Self>(self).data.get();
  }

  template <typename Err>
  static const Err& error_impl(const Err& err) { return err; }

  // We leverage Option<T> to avoid dynamic allocation of T. This
  // means that the storage for T will be included in this object
  // (Try<T>). Since Option<T> keeps track of whether a value is
  // stored, we just ask it when we want to know whether we are
  // storing a value or an error. Another advantage of leveraging
  // Option<T> is that it takes care of all the manual construction
  // and destruction. This makes the code for Try<T> really simple!
  Option<T> data;
  Option<E> error_;
};

#endif // __STOUT_TRY_HPP__
<|endoftext|>


<commit_before>// Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's
// (representing land) connected 4-directionally (horizontal or vertical.) You
// may assume all four edges of the grid are surrounded by water.

// Find the maximum area of an island in the given 2D array. (If there is no
// island, the maximum area is 0.)

// Example 1:

// [[0,0,1,0,0,0,0,1,0,0,0,0,0],
//  [0,0,0,0,0,0,0,1,1,1,0,0,0],
//  [0,1,1,0,1,0,0,0,0,0,0,0,0],
//  [0,1,0,0,1,1,0,0,1,0,1,0,0],
//  [0,1,0,0,1,1,0,0,1,1,1,0,0],
//  [0,0,0,0,0,0,0,0,0,0,1,0,0],
//  [0,0,0,0,0,0,0,1,1,1,0,0,0],
//  [0,0,0,0,0,0,0,1,1,0,0,0,0]]

// Given the above grid, return 6. Note the answer is not 11, because the island
// must be connected 4-directionally.

// Example 2:

// [[0,0,0,0,0,0,0,0]]

// Given the above grid, return 0.

// Note: The length of each dimension in the given grid does not exceed 50.

<commit_msg>695 max area of island<commit_after>// Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's
// (representing land) connected 4-directionally (horizontal or vertical.) You
// may assume all four edges of the grid are surrounded by water.

// Find the maximum area of an island in the given 2D array. (If there is no
// island, the maximum area is 0.)

// Example 1:

// [[0,0,1,0,0,0,0,1,0,0,0,0,0],
//  [0,0,0,0,0,0,0,1,1,1,0,0,0],
//  [0,1,1,0,1,0,0,0,0,0,0,0,0],
//  [0,1,0,0,1,1,0,0,1,0,1,0,0],
//  [0,1,0,0,1,1,0,0,1,1,1,0,0],
//  [0,0,0,0,0,0,0,0,0,0,1,0,0],
//  [0,0,0,0,0,0,0,1,1,1,0,0,0],
//  [0,0,0,0,0,0,0,1,1,0,0,0,0]]

// Given the above grid, return 6. Note the answer is not 11, because the island
// must be connected 4-directionally.

// Example 2:

// [[0,0,0,0,0,0,0,0]]

// Given the above grid, return 0.

// Note: The length of each dimension in the given grid does not exceed 50.

// dfs
class Solution {
    int dfs(vector<vector<int>> &g, int i, int j) {
        if (i < 0 || i == g.size() || j < 0 || j == g[0].size() || !g[i][j])
            return 0;
        g[i][j] = 0;
        return 1 + dfs(g, i, j - 1) + dfs(g, i, j + 1) + dfs(g, i - 1, j) +
               dfs(g, i + 1, j);
    }

  public:
    int maxAreaOfIsland(vector<vector<int>> &grid) {
        int ret = 0;

        for (int i = 0; i < grid.size(); ++i)
            for (int j = 0; j < grid[0].size(); ++j)
                if (grid[i][j])
                    ret = max(ret, dfs(grid, i, j));

        return ret;
    }
};<|endoftext|>