code:
#include "MultiSettings.hpp"

#include <stdexcept>

#include <QObject>
#include <QSettings>
#include <QString>
#include <QStringList>
#include <QDir>
#include <QFont>
#include <QApplication>
#include <QStandardPaths>
#include <QMainWindow>
#include <QMenu>
#include <QAction>
#include <QActionGroup>
#include <QDialog>
#include <QLineEdit>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QFormLayout>
#include <QVBoxLayout>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QComboBox>
#include <QLabel>
#include <QList>
#include <QMetaObject>

#include "SettingsGroup.hpp"
#include "qt_helpers.hpp"
#include "SettingsGroup.hpp"
#include "MessageBox.hpp"

#include "pimpl_impl.hpp"

namespace
{
  char const * default_string = QT_TRANSLATE_NOOP ("MultiSettings", "Default");
  char const * multi_settings_root_group = "MultiSettings";
  char const * multi_settings_current_group_key = "CurrentMultiSettingsConfiguration";
  char const * multi_settings_current_name_key = "CurrentName";
  char const * multi_settings_place_holder_key = "MultiSettingsPlaceHolder";

  QString unescape_ampersands (QString s)
  {
    return s.replace ("&&", "&");
  }

  // calculate a useable and unique settings file path
  QString settings_path ()
  {
    auto const& config_directory = QStandardPaths::writableLocation (QStandardPaths::ConfigLocation);
    QDir config_path {config_directory}; // will be "." if config_directory is empty
    if (!config_path.mkpath ("."))
      {
        throw std::runtime_error {"Cannot find a usable configuration path \"" + config_path.path ().toStdString () + '"'};
      }
    return config_path.absoluteFilePath (QApplication::applicationName () + ".ini");
  }

  //
  // Dialog to get a valid new configuration name
  //
  class NameDialog final
    : public QDialog
  {
  public:
    explicit NameDialog (QString const& current_name,
                         QStringList const& current_names,
                         QWidget * parent = nullptr)
      : QDialog {parent}
    {
      setWindowTitle (tr ("New Configuration Name"));

      auto form_layout = new QFormLayout ();
      form_layout->addRow (tr ("Old name:"), &old_name_label_);
      old_name_label_.setText (current_name);
      form_layout->addRow (tr ("&New name:"), &name_line_edit_);

      auto main_layout = new QVBoxLayout (this);
      main_layout->addLayout (form_layout);

      auto button_box = new QDialogButtonBox {QDialogButtonBox::Ok | QDialogButtonBox::Cancel};
      button_box->button (QDialogButtonBox::Ok)->setEnabled (false);
      main_layout->addWidget (button_box);

      auto name_validator = new QRegularExpressionValidator {QRegularExpression {R"([^/\\]+)"}, this};
      name_line_edit_.setValidator (name_validator);

      connect (&name_line_edit_, &QLineEdit::textChanged, [current_names, button_box] (QString const& name) {
          bool valid {!current_names.contains (name.trimmed ())};
          button_box->button (QDialogButtonBox::Ok)->setEnabled (valid);
        });
      connect (button_box, &QDialogButtonBox::accepted, this, &QDialog::accept);
      connect (button_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
    }

    QString new_name () const
    {
      return name_line_edit_.text ().trimmed ();
    }

  private:
    QLabel old_name_label_;
    QLineEdit name_line_edit_;
  };

  //
  // Dialog to get a valid new existing name
  //
  class ExistingNameDialog final
    : public QDialog
  {
  public:
    explicit ExistingNameDialog (QStringList const& current_names, QWidget * parent = nullptr)
      : QDialog {parent}
    {
      setWindowTitle (tr ("Configuration to Clone From"));

      name_combo_box_.addItems (current_names);

      auto form_layout = new QFormLayout ();
      form_layout->addRow (tr ("&Source Configuration Name:"), &name_combo_box_);

      auto main_layout = new QVBoxLayout (this);
      main_layout->addLayout (form_layout);

      auto button_box = new QDialogButtonBox {QDialogButtonBox::Ok | QDialogButtonBox::Cancel};
      main_layout->addWidget (button_box);

      connect (button_box, &QDialogButtonBox::accepted, this, &QDialog::accept);
      connect (button_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
    }

    QString name () const
    {
      return name_combo_box_.currentText ();
    }

  private:
    QComboBox name_combo_box_;
  };
}

class MultiSettings::impl final
  : public QObject
{
  Q_OBJECT

public:
  explicit impl (MultiSettings const * parent, QString const& config_name);
  bool reposition ();
  void create_menu_actions (QMainWindow * main_window, QMenu * menu);
  bool exit ();

  QSettings settings_;

private:
  using Dictionary = QMap<QString, QVariant>;

  // create a configuration maintenance sub menu
  QMenu * create_sub_menu (QMainWindow * main_window,
                           QMenu * parent,
                           QString const& menu_title,
                           QActionGroup * = nullptr);

  // extract all settings from the current QSettings group
  Dictionary get_settings () const;

  // write the settings values from the dictionary to the current group
  void load_from (Dictionary const&, bool add_placeholder = true);

  // switch to this configuration
  void select_configuration (QMainWindow *, QMenu const *);

  // clone this configuration
  void clone_configuration (QMainWindow * main_window, QMenu *, QMenu const *);

  // update this configuration from another
  void clone_into_configuration (QMainWindow *, QMenu const *);

  // reset configuration to default values
  void reset_configuration (QMainWindow *, QMenu const *);

  // change configuration name
  void rename_configuration (QMainWindow *, QMenu *);

  // remove a configuration
  void delete_configuration (QMainWindow *, QMenu *);

  MultiSettings const * parent_;  // required for emitting signals
  bool name_change_emit_pending_; // delayed until menu built

  QFont original_font_;
  QString current_;

  // action to take on restart
  enum class RepositionType {unchanged, replace, save_and_replace} reposition_type_;
  Dictionary new_settings_;
  bool exit_flag_;              // false means loop around with new
                                // configuration
  QActionGroup * configurations_group_;
};

#include "MultiSettings.moc"
#include "moc_MultiSettings.cpp"

MultiSettings::MultiSettings (QString const& config_name)
  : m_ {this, config_name}
{
}

MultiSettings::~MultiSettings ()
{
}

QSettings * MultiSettings::settings ()
{
  return &m_->settings_;
}

QVariant MultiSettings::common_value (QString const& key, QVariant const& default_value) const
{
  QVariant value;
  QSettings * mutable_settings {const_cast<QSettings *> (&m_->settings_)};
  auto const& current_group = mutable_settings->group ();
  if (current_group.size ()) mutable_settings->endGroup ();
  {
    SettingsGroup alternatives {mutable_settings, multi_settings_root_group};
    value = mutable_settings->value (key, default_value);
  }
  if (current_group.size ()) mutable_settings->beginGroup (current_group);
  return value;
}

void MultiSettings::set_common_value (QString const& key, QVariant const& value)
{
  auto const& current_group = m_->settings_.group ();
  if (current_group.size ()) m_->settings_.endGroup ();
  {
    SettingsGroup alternatives {&m_->settings_, multi_settings_root_group};
    m_->settings_.setValue (key, value);
  }
  if (current_group.size ()) m_->settings_.beginGroup (current_group);
}

void MultiSettings::remove_common_value (QString const& key)
{
  if (!key.size ()) return;     // we don't allow global delete as it
                                // would break this classes data model
  auto const& current_group = m_->settings_.group ();
  if (current_group.size ()) m_->settings_.endGroup ();
  {
    SettingsGroup alternatives {&m_->settings_, multi_settings_root_group};
    m_->settings_.remove (key);
  }
  if (current_group.size ()) m_->settings_.beginGroup (current_group);
}

void MultiSettings::create_menu_actions (QMainWindow * main_window, QMenu * menu)
{
  m_->create_menu_actions (main_window, menu);
}

bool MultiSettings::exit ()
{
  return m_->exit ();
}

MultiSettings::impl::impl (MultiSettings const * parent, QString const& config_name)
  : settings_ {settings_path (), QSettings::IniFormat}
  , parent_ {parent}
  , name_change_emit_pending_ {true}
  , reposition_type_ {RepositionType::unchanged}
  , exit_flag_ {true}
  , configurations_group_ {new QActionGroup {this}}
{
  if (!settings_.isWritable ())
    {
      throw std::runtime_error {QString {"Cannot access \"%1\" for writing"}
        .arg (settings_.fileName ()).toStdString ()};
    }

  // deal with transient, now defunct, settings key
  if (settings_.contains (multi_settings_current_group_key))
    {
      current_ = settings_.value (multi_settings_current_group_key).toString ();
      settings_.remove (multi_settings_current_group_key);
      if (current_.size ())
        {
          {
            SettingsGroup alternatives {&settings_, multi_settings_root_group};
            {
              SettingsGroup source_group {&settings_, current_};
              new_settings_ = get_settings ();
            }
            settings_.setValue (multi_settings_current_name_key, tr (default_string));
          }
          reposition_type_ = RepositionType::save_and_replace;
          reposition ();
        }
      else
        {
          SettingsGroup alternatives {&settings_, multi_settings_root_group};
          settings_.setValue (multi_settings_current_name_key, tr (default_string));
        }
    }

  // bootstrap
  QStringList available_configurations;
  {
    SettingsGroup alternatives {&settings_, multi_settings_root_group};
    available_configurations = settings_.childGroups ();
    // use last selected configuration
    current_ = settings_.value (multi_settings_current_name_key).toString ();
    if (!current_.size ())
      {
        // no configurations so use default name
        current_ = tr (default_string);
        settings_.setValue (multi_settings_current_name_key, current_);
      }
  }

  if (config_name.size () && available_configurations.contains (config_name) && config_name != current_)
    {
      // switch to specified configuration
      {
        SettingsGroup alternatives {&settings_, multi_settings_root_group};
        // save the target settings
        SettingsGroup target_group {&settings_, config_name};
        new_settings_ = get_settings ();
      }
      current_ = config_name;
      reposition_type_ = RepositionType::save_and_replace;
      reposition ();
    }
  settings_.sync ();
}

// do actions that can only be done once all the windows are closed
bool MultiSettings::impl::reposition ()
{
  auto const& current_group = settings_.group ();
  if (current_group.size ()) settings_.endGroup ();
  switch (reposition_type_)
    {
    case RepositionType::save_and_replace:
      {
        // save the current settings with the other alternatives
        Dictionary saved_settings {get_settings ()};
        SettingsGroup alternatives {&settings_, multi_settings_root_group};
        // get the current configuration name
        auto const& previous_group_name = settings_.value (multi_settings_current_name_key, tr (default_string)).toString ();
        SettingsGroup save_group {&settings_, previous_group_name};
        load_from (saved_settings);
      }
      // fall through
    case RepositionType::replace:
      // and purge current settings
      for (auto const& key: settings_.allKeys ())
        {
          if (!key.contains (multi_settings_root_group))
            {
              settings_.remove (key);
            }
        }
      // insert the new settings
      load_from (new_settings_, false);
      if (!new_settings_.size ())
        {
          // if we are clearing the current settings then we must
          // reset the application font and the font in the
          // application style sheet, this is necessary since the
          // application instance is not recreated
          qApp->setFont (original_font_);
          qApp->setStyleSheet (qApp->styleSheet () + "* {" + font_as_stylesheet (original_font_) + '}');
        }
      // now we have set up the new current we can safely purge it
      // from the alternatives
      {
        SettingsGroup alternatives {&settings_, multi_settings_root_group};
        {
          SettingsGroup purge_group {&settings_, current_};
          settings_.remove (QString {});  // purge entire group
        }
        // switch to the specified configuration name
        settings_.setValue (multi_settings_current_name_key, current_);
      }
      settings_.sync ();
      // fall through
    case RepositionType::unchanged:
      new_settings_.clear ();
      break;
    }
  if (current_group.size ()) settings_.beginGroup (current_group);

  reposition_type_ = RepositionType::unchanged; // reset
  bool exit {exit_flag_};
  exit_flag_ = true;           // reset exit flag so normal exit works

  return exit;
}

// populate a pop up menu with the configurations sub-menus for
// maintenance including select, clone, clone from, delete, rename
// and, reset
void MultiSettings::impl::create_menu_actions (QMainWindow * main_window, QMenu * menu)
{
  auto const& current_group = settings_.group ();
  if (current_group.size ()) settings_.endGroup ();
  SettingsGroup alternatives {&settings_, multi_settings_root_group};
  // get the current configuration name
  auto const& current_configuration_name = settings_.value (multi_settings_current_name_key, tr (default_string)).toString ();
  // add the default configuration sub menu
  QMenu * default_menu = create_sub_menu (main_window, menu, current_configuration_name, configurations_group_);
  // and set as the current configuration
  default_menu->menuAction ()->setChecked (true);

  // get the existing alternatives
  auto const& available_configurations = settings_.childGroups ();

  // add all the other configurations
  for (auto const& configuration_name: available_configurations)
    {
      create_sub_menu (main_window, menu, configuration_name, configurations_group_);
    }

  if (current_group.size ()) settings_.beginGroup (current_group);

  if (name_change_emit_pending_)
    {
      Q_EMIT parent_->configurationNameChanged (unescape_ampersands (current_));
      name_change_emit_pending_ = false;
    }
}

// call this at the end of the main program loop to determine if the
// main window really wants to quit or to run again with a new configuration
bool MultiSettings::impl::exit ()
{
  // ensure that configuration name changed signal gets fired on restart
  name_change_emit_pending_ = true;

  // do any configuration swap required and return exit flag
  return reposition ();
}

QMenu * MultiSettings::impl::create_sub_menu (QMainWindow * main_window,
                                              QMenu * parent_menu,
                                              QString const& menu_title,
                                              QActionGroup * action_group)
{
  auto sub_menu = parent_menu->addMenu (menu_title);
  if (action_group) action_group->addAction (sub_menu->menuAction ());
  sub_menu->menuAction ()->setCheckable (true);

  // populate sub-menu actions before showing
  connect (sub_menu, &QMenu::aboutToShow, [this, main_window, parent_menu, sub_menu] () {
      // depopulate before populating and showing because on Mac OS X
      // there is an issue with depopulating in QMenu::aboutToHide()
      // with connections being disconnected before they are actioned
      while (!sub_menu->actions ().isEmpty ())
        {
          sub_menu->removeAction (sub_menu->actions ().last ());
        }

      bool is_current {sub_menu->menuAction ()->text () == current_};
      if (!is_current)
        {
          auto select_action = new QAction {tr ("&Switch To"), this};
          sub_menu->addAction (select_action);
          connect (select_action, &QAction::triggered, [this, main_window, sub_menu] (bool) {
              select_configuration (main_window, sub_menu);
            });
          sub_menu->addSeparator ();
        }

      auto clone_action = new QAction {tr ("&Clone"), this};
      sub_menu->addAction (clone_action);
      connect (clone_action, &QAction::triggered, [this, main_window, parent_menu, sub_menu] (bool) {
          clone_configuration (main_window, parent_menu, sub_menu);
        });

      auto const& current_group = settings_.group ();
      if (current_group.size ()) settings_.endGroup ();
      SettingsGroup alternatives {&settings_, multi_settings_root_group};
      if (settings_.childGroups ().size ())
        {
          auto clone_into_action = new QAction {tr ("Clone &Into ..."), this};
          sub_menu->addAction (clone_into_action);
          connect (clone_into_action, &QAction::triggered, [this, main_window, sub_menu] (bool) {
              clone_into_configuration (main_window, sub_menu);
            });
        }
      if (current_group.size ()) settings_.beginGroup (current_group);
      auto reset_action = new QAction {tr ("R&eset"), this};
      sub_menu->addAction (reset_action);
      connect (reset_action, &QAction::triggered, [this, main_window, sub_menu] (bool) {
          reset_configuration (main_window, sub_menu);
        });

      auto rename_action = new QAction {tr ("&Rename ..."), this};
      sub_menu->addAction (rename_action);
      connect (rename_action, &QAction::triggered, [this, main_window, sub_menu] (bool) {
          rename_configuration (main_window, sub_menu);
        });

      if (!is_current)
        {
          auto delete_action = new QAction {tr ("&Delete"), this};
          sub_menu->addAction (delete_action);
          connect (delete_action, &QAction::triggered, [this, main_window, sub_menu] (bool) {
              delete_configuration (main_window, sub_menu);
            });
        }
    });

  return sub_menu;
}

auto MultiSettings::impl::get_settings () const -> Dictionary
{
  Dictionary settings;
  for (auto const& key: settings_.allKeys ())
    {
      // filter out multi settings group and empty settings
      // placeholder
      if (!key.contains (multi_settings_root_group)
          && !key.contains (multi_settings_place_holder_key))
        {
          settings[key] = settings_.value (key);
        }
    }
  return settings;
}

void MultiSettings::impl::load_from (Dictionary const& dictionary, bool add_placeholder)
{
  if (dictionary.size ())
    {
      for (Dictionary::const_iterator iter = dictionary.constBegin ();
           iter != dictionary.constEnd (); ++iter)
        {
          settings_.setValue (iter.key (), iter.value ());
        }
    }
  else if (add_placeholder)
    {
      // add a placeholder key to stop the alternative configuration
      // name from disappearing
      settings_.setValue (multi_settings_place_holder_key, QVariant {});
    }
  settings_.sync ();
}

void MultiSettings::impl::select_configuration (QMainWindow * main_window, QMenu const * menu)
{
  auto const& target_name = menu->title ();

  if (target_name != current_)
    {
      {
        auto const& current_group = settings_.group ();
        if (current_group.size ()) settings_.endGroup ();
        // position to the alternative settings
        SettingsGroup alternatives {&settings_, multi_settings_root_group};
        // save the target settings
        SettingsGroup target_group {&settings_, target_name};
        new_settings_ = get_settings ();
        if (current_group.size ()) settings_.beginGroup (current_group);
      }
      // and set up the restart
      current_ = target_name;
      Q_EMIT parent_->configurationNameChanged (unescape_ampersands (current_));
      reposition_type_ = RepositionType::save_and_replace;
      exit_flag_ = false;
      main_window->close ();
    }
}

void MultiSettings::impl::clone_configuration (QMainWindow * main_window, QMenu * parent_menu, QMenu const * menu)
{
  auto const& current_group = settings_.group ();
  if (current_group.size ()) settings_.endGroup ();
  auto const& source_name = menu->title ();

  // settings to clone
  Dictionary source_settings;
  if (source_name == current_)
    {
      // grab the data to clone from the current settings
      source_settings = get_settings ();
    }
  SettingsGroup alternatives {&settings_, multi_settings_root_group};
  if (source_name != current_)
    {
      SettingsGroup source_group {&settings_, source_name};
      source_settings = get_settings ();
    }

  // find a new unique name
  QString new_name_root {source_name + " - Copy"};;
  QString new_name {new_name_root};
  unsigned index {0};
  do
    {
      if (index++) new_name = new_name_root + '(' + QString::number (index) + ')';
    }
  while (settings_.childGroups ().contains (new_name) || new_name == current_);
  SettingsGroup new_group {&settings_, new_name};
  load_from (source_settings);

  // insert the new configuration sub menu in the parent menu
  create_sub_menu (main_window, parent_menu, new_name, configurations_group_);
  if (current_group.size ()) settings_.beginGroup (current_group);
}

void MultiSettings::impl::clone_into_configuration (QMainWindow * main_window, QMenu const * menu)
{
  auto const& current_group = settings_.group ();
  if (current_group.size ()) settings_.endGroup ();
  auto const& target_name = menu->title ();

  // get the current configuration name
  QString current_group_name;
  QStringList sources;
  {
    SettingsGroup alternatives {&settings_, multi_settings_root_group};
    current_group_name = settings_.value (multi_settings_current_name_key).toString ();

    {
      // get the source configuration name for the clone
      sources = settings_.childGroups ();
      sources << current_group_name;
      sources.removeOne (target_name);
    }
  }

  // pick a source configuration
  ExistingNameDialog dialog {sources, main_window};
  if (sources.size () && (1 == sources.size () || QDialog::Accepted == dialog.exec ()))
    {
      QString source_name {1 == sources.size () ? sources.at (0) : dialog.name ()};
      if (MessageBox::Yes == MessageBox::query_message (main_window,
                                                        tr ("Clone Into Configuration"),
                                                        tr ("Confirm overwrite of all values for configuration \"%1\" with values from \"%2\"?")
                                                        .arg (unescape_ampersands (target_name))
                                                        .arg (unescape_ampersands (source_name))))
        {
          // grab the data to clone from
          if (source_name == current_group_name)
            {
              // grab the data to clone from the current settings
              new_settings_ = get_settings ();
            }
          else
            {
              SettingsGroup alternatives {&settings_, multi_settings_root_group};
              SettingsGroup source_group {&settings_, source_name};
              new_settings_ = get_settings ();
            }

          // purge target settings and replace
          if (target_name == current_)
            {
              // restart with new settings
              reposition_type_ = RepositionType::replace;
              exit_flag_ = false;
              main_window->close ();
            }
          else
            {
              SettingsGroup alternatives {&settings_, multi_settings_root_group};
              SettingsGroup target_group {&settings_, target_name};
              settings_.remove (QString {}); // purge entire group
              load_from (new_settings_);
              new_settings_.clear ();
            }
        }
    }
  if (current_group.size ()) settings_.beginGroup (current_group);
}

void MultiSettings::impl::reset_configuration (QMainWindow * main_window, QMenu const * menu)
{
  auto const& target_name = menu->title ();

  if (MessageBox::Yes != MessageBox::query_message (main_window,
                                                    tr ("Reset Configuration"),
                                                    tr ("Confirm reset to default values for configuration \"%1\"?")
                                                    .arg (unescape_ampersands (target_name))))
    {
      return;
    }

  if (target_name == current_)
    {
      // restart with default settings
      reposition_type_ = RepositionType::replace;
      new_settings_.clear ();
      exit_flag_ = false;
      main_window->close ();
    }
  else
    {
      auto const& current_group = settings_.group ();
      if (current_group.size ()) settings_.endGroup ();
      SettingsGroup alternatives {&settings_, multi_settings_root_group};
      SettingsGroup target_group {&settings_, target_name};
      settings_.remove (QString {}); // purge entire group
      // add a placeholder to stop alternative configuration name
      // being lost
      settings_.setValue (multi_settings_place_holder_key, QVariant {});
      settings_.sync ();
      if (current_group.size ()) settings_.beginGroup (current_group);
    }
}

void MultiSettings::impl::rename_configuration (QMainWindow * main_window, QMenu * menu)
{
  auto const& current_group = settings_.group ();
  if (current_group.size ()) settings_.endGroup ();
  auto const& target_name = menu->title ();

  // gather names we cannot use
  SettingsGroup alternatives {&settings_, multi_settings_root_group};
  auto invalid_names = settings_.childGroups ();
  invalid_names << settings_.value (multi_settings_current_name_key).toString ();

  // get the new name
  NameDialog dialog {target_name, invalid_names, main_window};
  if (QDialog::Accepted == dialog.exec ())
    {
      if (target_name == current_)
        {
          settings_.setValue (multi_settings_current_name_key, dialog.new_name ());
          settings_.sync ();
          current_ = dialog.new_name ();
          Q_EMIT parent_->configurationNameChanged (unescape_ampersands (current_));
        }
      else
        {
          // switch to the target group and fetch the configuration data
          Dictionary target_settings;
          {
            // grab the target configuration settings
            SettingsGroup target_group {&settings_, target_name};
            target_settings = get_settings ();
            // purge the old configuration data
            settings_.remove (QString {}); // purge entire group
          }
          // load into new configuration group name
          SettingsGroup target_group {&settings_, dialog.new_name ()};
          load_from (target_settings);
        }
      // change the action text in the menu
      menu->setTitle (dialog.new_name ());
    }
  if (current_group.size ()) settings_.beginGroup (current_group);
}

void MultiSettings::impl::delete_configuration (QMainWindow * main_window, QMenu * menu)
{
  auto const& target_name = menu->title ();

  if (target_name == current_)
    {
      return;               // suicide not allowed here
    }
  else
    {
      if (MessageBox::Yes != MessageBox::query_message (main_window,
                                                        tr ("Delete Configuration"),
                                                        tr ("Confirm deletion of configuration \"%1\"?")
                                                        .arg (unescape_ampersands (target_name))))
        {
          return;
        }
      auto const& current_group = settings_.group ();
      if (current_group.size ()) settings_.endGroup ();
      SettingsGroup alternatives {&settings_, multi_settings_root_group};
      SettingsGroup target_group {&settings_, target_name};
      // purge the configuration data
      settings_.remove (QString {}); // purge entire group
      settings_.sync ();
      if (current_group.size ()) settings_.beginGroup (current_group);
    }
  // update the menu
  menu->deleteLater ();
}


code:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_DETAIL_LINEAR_ALGEBRA_HPP
#define BOOST_UNITS_DETAIL_LINEAR_ALGEBRA_HPP

#include <boost/units/static_rational.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/arithmetic.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/assert.hpp>

#include <boost/units/dim.hpp>
#include <boost/units/dimensionless_type.hpp>
#include <boost/units/static_rational.hpp>
#include <boost/units/detail/dimension_list.hpp>
#include <boost/units/detail/sort.hpp>

namespace boost {

namespace units {

namespace detail {

// typedef list<rational> equation;

template<int N>
struct eliminate_from_pair_of_equations_impl;

template<class E1, class E2>
struct eliminate_from_pair_of_equations;

template<int N>
struct elimination_impl;

template<bool is_zero, bool element_is_last>
struct elimination_skip_leading_zeros_impl;

template<class Equation, class Vars>
struct substitute;

template<int N>
struct substitute_impl;

template<bool is_end>
struct solve_impl;

template<class T>
struct solve;

template<int N>
struct check_extra_equations_impl;

template<int N>
struct normalize_units_impl;

struct inconsistent {};

// generally useful utilies.

template<int N>
struct divide_equation {
    template<class Begin, class Divisor>
    struct apply {
        typedef list<typename mpl::divides<typename Begin::item, Divisor>::type, typename divide_equation<N - 1>::template apply<typename Begin::next, Divisor>::type> type;
    };
};

template<>
struct divide_equation<0> {
    template<class Begin, class Divisor>
    struct apply {
        typedef dimensionless_type type;
    };
};

// eliminate_from_pair_of_equations takes a pair of
// equations and eliminates the first variable.
//
// equation eliminate_from_pair_of_equations(equation l1, equation l2) {
//     rational x1 = l1.front();
//     rational x2 = l2.front();
//     return(transform(pop_front(l1), pop_front(l2), _1 * x2 - _2 * x1));
// }

template<int N>
struct eliminate_from_pair_of_equations_impl {
    template<class Begin1, class Begin2, class X1, class X2>
    struct apply {
        typedef list<
            typename mpl::minus<
                typename mpl::times<typename Begin1::item, X2>::type,
                typename mpl::times<typename Begin2::item, X1>::type
            >::type,
            typename eliminate_from_pair_of_equations_impl<N - 1>::template apply<
                typename Begin1::next,
                typename Begin2::next,
                X1,
                X2
            >::type
        > type;
    };
};

template<>
struct eliminate_from_pair_of_equations_impl<0> {
    template<class Begin1, class Begin2, class X1, class X2>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<class E1, class E2>
struct eliminate_from_pair_of_equations {
    typedef E1 begin1;
    typedef E2 begin2;
    typedef typename eliminate_from_pair_of_equations_impl<(E1::size::value - 1)>::template apply<
        typename begin1::next,
        typename begin2::next,
        typename begin1::item,
        typename begin2::item
    >::type type;
};

// Stage 1.  Determine which dimensions should
// have dummy base units.  For this purpose
// row reduce the matrix.

template<int N>
struct make_zero_vector {
    typedef list<static_rational<0>, typename make_zero_vector<N - 1>::type> type;
};
template<>
struct make_zero_vector<0> {
    typedef dimensionless_type type;
};

template<int Column, int TotalColumns>
struct create_row_of_identity {
    typedef list<static_rational<0>, typename create_row_of_identity<Column - 1, TotalColumns - 1>::type> type;
};
template<int TotalColumns>
struct create_row_of_identity<0, TotalColumns> {
    typedef list<static_rational<1>, typename make_zero_vector<TotalColumns - 1>::type> type;
};
template<int Column>
struct create_row_of_identity<Column, 0> {
    // error
};

template<int RemainingRows>
struct determine_extra_equations_impl;

template<bool first_is_zero, bool is_last>
struct determine_extra_equations_skip_zeros_impl;

// not the last row and not zero.
template<>
struct determine_extra_equations_skip_zeros_impl<false, false> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        // remove the equation being eliminated against from the set of equations.
        typedef typename determine_extra_equations_impl<RemainingRows - 1>::template apply<typename RowsBegin::next, typename RowsBegin::item>::type next_equations;
        // since this column was present, strip it out.
        typedef Result type;
    };
};

// the last row but not zero.
template<>
struct determine_extra_equations_skip_zeros_impl<false, true> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        // remove this equation.
        typedef dimensionless_type next_equations;
        // since this column was present, strip it out.
        typedef Result type;
    };
};

// the first columns is zero but it is not the last column.
// continue with the same loop.
template<>
struct determine_extra_equations_skip_zeros_impl<true, false> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        typedef typename RowsBegin::next::item next_row;
        typedef typename determine_extra_equations_skip_zeros_impl<
            next_row::item::Numerator == 0,
            RemainingRows == 2  // the next one will be the last.
        >::template apply<
            typename RowsBegin::next,
            RemainingRows - 1,
            CurrentColumn,
            TotalColumns,
            Result
        > next;
        typedef list<typename RowsBegin::item::next, typename next::next_equations> next_equations;
        typedef typename next::type type;
    };
};

// all the elements in this column are zero.
template<>
struct determine_extra_equations_skip_zeros_impl<true, true> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        typedef list<typename RowsBegin::item::next, dimensionless_type> next_equations;
        typedef list<typename create_row_of_identity<CurrentColumn, TotalColumns>::type, Result> type;
    };
};

template<int RemainingRows>
struct determine_extra_equations_impl {
    template<class RowsBegin, class EliminateAgainst>
    struct apply {
        typedef list<
            typename eliminate_from_pair_of_equations<typename RowsBegin::item, EliminateAgainst>::type,
            typename determine_extra_equations_impl<RemainingRows-1>::template apply<typename RowsBegin::next, EliminateAgainst>::type
        > type;
    };
};

template<>
struct determine_extra_equations_impl<0> {
    template<class RowsBegin, class EliminateAgainst>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<int RemainingColumns, bool is_done>
struct determine_extra_equations {
    template<class RowsBegin, int TotalColumns, class Result>
    struct apply {
        typedef typename RowsBegin::item top_row;
        typedef typename determine_extra_equations_skip_zeros_impl<
            top_row::item::Numerator == 0,
            RowsBegin::size::value == 1
        >::template apply<
            RowsBegin,
            RowsBegin::size::value,
            TotalColumns - RemainingColumns,
            TotalColumns,
            Result
        > column_info;
        typedef typename determine_extra_equations<
            RemainingColumns - 1,
            column_info::next_equations::size::value == 0
        >::template apply<
            typename column_info::next_equations,
            TotalColumns,
            typename column_info::type
        >::type type;
    };
};

template<int RemainingColumns>
struct determine_extra_equations<RemainingColumns, true> {
    template<class RowsBegin, int TotalColumns, class Result>
    struct apply {
        typedef typename determine_extra_equations<RemainingColumns - 1, true>::template apply<
            RowsBegin,
            TotalColumns,
            list<typename create_row_of_identity<TotalColumns - RemainingColumns, TotalColumns>::type, Result>
        >::type type;
    };
};

template<>
struct determine_extra_equations<0, true> {
    template<class RowsBegin, int TotalColumns, class Result>
    struct apply {
        typedef Result type;
    };
};

// Stage 2
// invert the matrix using Gauss-Jordan elimination

template<bool is_zero, bool is_last>
struct invert_strip_leading_zeroes;

template<int N>
struct invert_handle_after_pivot_row;

// When processing column N, none of the first N rows
// can be the pivot column.
template<int N>
struct invert_handle_inital_rows {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename invert_handle_inital_rows<N - 1>::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next
        > next;
        typedef typename RowsBegin::item current_row;
        typedef typename IdentityBegin::item current_identity_row;
        typedef typename next::pivot_row pivot_row;
        typedef typename next::identity_pivot_row identity_pivot_row;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_row::size::value) - 1>::template apply<
                typename current_row::next,
                pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::new_matrix
        > new_matrix;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_identity_row::size::value)>::template apply<
                current_identity_row,
                identity_pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::identity_result
        > identity_result;
    };
};

// This handles the switch to searching for a pivot column.
// The pivot row will be propagated up in the typedefs
// pivot_row and identity_pivot_row.  It is inserted here.
template<>
struct invert_handle_inital_rows<0> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename invert_strip_leading_zeroes<
            (current_row::item::Numerator == 0),
            (RowsBegin::size::value == 1)
        >::template apply<
            RowsBegin,
            IdentityBegin
        > next;
        // results
        typedef list<typename next::pivot_row, typename next::new_matrix> new_matrix;
        typedef list<typename next::identity_pivot_row, typename next::identity_result> identity_result;
        typedef typename next::pivot_row pivot_row;
        typedef typename next::identity_pivot_row identity_pivot_row;
    };
};

// The first internal element which is not zero.
template<>
struct invert_strip_leading_zeroes<false, false> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename current_row::item current_value;
        typedef typename divide_equation<(current_row::size::value - 1)>::template apply<typename current_row::next, current_value>::type new_equation;
        typedef typename divide_equation<(IdentityBegin::item::size::value)>::template apply<typename IdentityBegin::item, current_value>::type transformed_identity_equation;
        typedef typename invert_handle_after_pivot_row<(RowsBegin::size::value - 1)>::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next,
            new_equation,
            transformed_identity_equation
        > next;

        // results
        // Note that we don't add the pivot row to the
        // results here, because it needs to propagated up
        // to the diagonal.
        typedef typename next::new_matrix new_matrix;
        typedef typename next::identity_result identity_result;
        typedef new_equation pivot_row;
        typedef transformed_identity_equation identity_pivot_row;
    };
};

// The one and only non-zero element--at the end
template<>
struct invert_strip_leading_zeroes<false, true> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename current_row::item current_value;
        typedef typename divide_equation<(current_row::size::value - 1)>::template apply<typename current_row::next, current_value>::type new_equation;
        typedef typename divide_equation<(IdentityBegin::item::size::value)>::template apply<typename IdentityBegin::item, current_value>::type transformed_identity_equation;

        // results
        // Note that we don't add the pivot row to the
        // results here, because it needs to propagated up
        // to the diagonal.
        typedef dimensionless_type identity_result;
        typedef dimensionless_type new_matrix;
        typedef new_equation pivot_row;
        typedef transformed_identity_equation identity_pivot_row;
    };
};

// One of the initial zeroes
template<>
struct invert_strip_leading_zeroes<true, false> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename RowsBegin::next::item next_row;
        typedef typename invert_strip_leading_zeroes<
            next_row::item::Numerator == 0,
            RowsBegin::size::value == 2
        >::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next
        > next;
        typedef typename IdentityBegin::item current_identity_row;
        // these are propagated up.
        typedef typename next::pivot_row pivot_row;
        typedef typename next::identity_pivot_row identity_pivot_row;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_row::size::value - 1)>::template apply<
                typename current_row::next,
                pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::new_matrix
        > new_matrix;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_identity_row::size::value)>::template apply<
                current_identity_row,
                identity_pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::identity_result
        > identity_result;
    };
};

// the last element, and is zero.
// Should never happen.
template<>
struct invert_strip_leading_zeroes<true, true> {
};

template<int N>
struct invert_handle_after_pivot_row {
    template<class RowsBegin, class IdentityBegin, class MatrixPivot, class IdentityPivot>
    struct apply {
        typedef typename invert_handle_after_pivot_row<N - 1>::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next,
            MatrixPivot,
            IdentityPivot
        > next;
        typedef typename RowsBegin::item current_row;
        typedef typename IdentityBegin::item current_identity_row;
        typedef MatrixPivot pivot_row;
        typedef IdentityPivot identity_pivot_row;

        // results
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_row::size::value - 1)>::template apply<
                typename current_row::next,
                pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::new_matrix
        > new_matrix;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_identity_row::size::value)>::template apply<
                current_identity_row,
                identity_pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::identity_result
        > identity_result;
    };
};

template<>
struct invert_handle_after_pivot_row<0> {
    template<class RowsBegin, class IdentityBegin, class MatrixPivot, class IdentityPivot>
    struct apply {
        typedef dimensionless_type new_matrix;
        typedef dimensionless_type identity_result;
    };
};

template<int N>
struct invert_impl {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename invert_handle_inital_rows<RowsBegin::size::value - N>::template apply<RowsBegin, IdentityBegin> process_column;
        typedef typename invert_impl<N - 1>::template apply<
            typename process_column::new_matrix,
            typename process_column::identity_result
        >::type type;
    };
};

template<>
struct invert_impl<0> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef IdentityBegin type;
    };
};

template<int N>
struct make_identity {
    template<int Size>
    struct apply {
        typedef list<typename create_row_of_identity<Size - N, Size>::type, typename make_identity<N - 1>::template apply<Size>::type> type;
    };
};

template<>
struct make_identity<0> {
    template<int Size>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<class Matrix>
struct make_square_and_invert {
    typedef typename Matrix::item top_row;
    typedef typename determine_extra_equations<(top_row::size::value), false>::template apply<
        Matrix,                 // RowsBegin
        top_row::size::value,   // TotalColumns
        Matrix                  // Result
    >::type invertible;
    typedef typename invert_impl<invertible::size::value>::template apply<
        invertible,
        typename make_identity<invertible::size::value>::template apply<invertible::size::value>::type
    >::type type;
};

// find_base_dimensions takes a list of
// base_units and returns a sorted list
// of all the base_dimensions they use.
//
// list<base_dimension> find_base_dimensions(list<base_unit> l) {
//     set<base_dimension> dimensions;
//     for_each(base_unit unit : l) {
//         for_each(dim d : unit.dimension_type) {
//             dimensions = insert(dimensions, d.tag_type);
//         }
//     }
//     return(sort(dimensions, _1 > _2, front_inserter(list<base_dimension>())));
// }

typedef char set_no;
struct set_yes { set_no dummy[2]; };

template<class T>
struct wrap {};

struct set_end {
    static set_no lookup(...);
    typedef mpl::long_<0> size;
};

template<class T, class Next>
struct set : Next {
    using Next::lookup;
    static set_yes lookup(wrap<T>*);
    typedef T item;
    typedef Next next;
    typedef typename mpl::next<typename Next::size>::type size;
};

template<bool has_key>
struct set_insert;

template<>
struct set_insert<true> {
    template<class Set, class T>
    struct apply {
        typedef Set type;
    };
};

template<>
struct set_insert<false> {
    template<class Set, class T>
    struct apply {
        typedef set<T, Set> type;
    };
};

template<class Set, class T>
struct has_key {
    static const long size = sizeof(Set::lookup((wrap<T>*)0));
    static const bool value = (size == sizeof(set_yes));
};

template<int N>
struct find_base_dimensions_impl_impl {
    template<class Begin, class S>
    struct apply {
        typedef typename find_base_dimensions_impl_impl<N-1>::template apply<
            typename Begin::next,
            S
        >::type next;

        typedef typename set_insert<
            (has_key<next, typename Begin::item::tag_type>::value)
        >::template apply<
            next,
            typename Begin::item::tag_type
        >::type type;
    };
};

template<>
struct find_base_dimensions_impl_impl<0> {
    template<class Begin, class S>
    struct apply {
        typedef S type;
    };
};

template<int N>
struct find_base_dimensions_impl {
    template<class Begin>
    struct apply {
        typedef typename find_base_dimensions_impl_impl<(Begin::item::dimension_type::size::value)>::template apply<
            typename Begin::item::dimension_type,
            typename find_base_dimensions_impl<N-1>::template apply<typename Begin::next>::type
        >::type type;
    };
};

template<>
struct find_base_dimensions_impl<0> {
    template<class Begin>
    struct apply {
        typedef set_end type;
    };
};

template<class T>
struct find_base_dimensions {
    typedef typename insertion_sort<
        typename find_base_dimensions_impl<
            (T::size::value)
        >::template apply<T>::type
    >::type type;
};

// calculate_base_dimension_coefficients finds
// the coefficients corresponding to the first
// base_dimension in each of the dimension_lists.
// It returns two values.  The first result
// is a list of the coefficients.  The second
// is a list with all the incremented iterators.
// When we encounter a base_dimension that is
// missing from a dimension_list, we do not
// increment the iterator and we set the
// coefficient to zero.

template<bool has_dimension>
struct calculate_base_dimension_coefficients_func;

template<>
struct calculate_base_dimension_coefficients_func<true> {
    template<class T>
    struct apply {
        typedef typename T::item::value_type type;
        typedef typename T::next next;
    };
};

template<>
struct calculate_base_dimension_coefficients_func<false> {
    template<class T>
    struct apply {
        typedef static_rational<0> type;
        typedef T next;
    };
};

// begins_with_dimension returns true iff its first
// parameter is a valid iterator which yields its
// second parameter when dereferenced.

template<class Iterator>
struct begins_with_dimension {
    template<class Dim>
    struct apply :
        boost::is_same<
            Dim,
            typename Iterator::item::tag_type
        > {};
};

template<>
struct begins_with_dimension<dimensionless_type> {
    template<class Dim>
    struct apply : mpl::false_ {};
};

template<int N>
struct calculate_base_dimension_coefficients_impl {
    template<class BaseUnitDimensions,class Dim,class T>
    struct apply {
        typedef typename calculate_base_dimension_coefficients_func<
            begins_with_dimension<typename BaseUnitDimensions::item>::template apply<
                Dim
            >::value
        >::template apply<
            typename BaseUnitDimensions::item
        > result;
        typedef typename calculate_base_dimension_coefficients_impl<N-1>::template apply<
            typename BaseUnitDimensions::next,
            Dim,
            list<typename result::type, T>
        > next_;
        typedef typename next_::type type;
        typedef list<typename result::next, typename next_::next> next;
    };
};

template<>
struct calculate_base_dimension_coefficients_impl<0> {
    template<class Begin, class BaseUnitDimensions, class T>
    struct apply {
        typedef T type;
        typedef dimensionless_type next;
    };
};

// add_zeroes pushs N zeroes onto the
// front of a list.
//
// list<rational> add_zeroes(list<rational> l, int N) {
//     if(N == 0) {
//         return(l);
//     } else {
//         return(push_front(add_zeroes(l, N-1), 0));
//     }
// }

template<int N>
struct add_zeroes_impl {
    // If you get an error here and your base units are
    // in fact linearly independent, please report it.
    BOOST_MPL_ASSERT_MSG((N > 0), base_units_are_probably_not_linearly_independent, (void));
    template<class T>
    struct apply {
        typedef list<
            static_rational<0>,
            typename add_zeroes_impl<N-1>::template apply<T>::type
        > type;
    };
};

template<>
struct add_zeroes_impl<0> {
    template<class T>
    struct apply {
        typedef T type;
    };
};

// expand_dimensions finds the exponents of
// a set of dimensions in a dimension_list.
// the second parameter is assumed to be
// a superset of the base_dimensions of
// the first parameter.
//
// list<rational> expand_dimensions(dimension_list, list<base_dimension>);

template<int N>
struct expand_dimensions {
    template<class Begin, class DimensionIterator>
    struct apply {
        typedef typename calculate_base_dimension_coefficients_func<
            begins_with_dimension<DimensionIterator>::template apply<typename Begin::item>::value
        >::template apply<DimensionIterator> result;
        typedef list<
            typename result::type,
            typename expand_dimensions<N-1>::template apply<typename Begin::next, typename result::next>::type
        > type;
    };
};

template<>
struct expand_dimensions<0> {
    template<class Begin, class DimensionIterator>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<int N>
struct create_unit_matrix {
    template<class Begin, class Dimensions>
    struct apply {
        typedef typename create_unit_matrix<N - 1>::template apply<typename Begin::next, Dimensions>::type next;
        typedef list<typename expand_dimensions<Dimensions::size::value>::template apply<Dimensions, typename Begin::item::dimension_type>::type, next> type;
    };
};

template<>
struct create_unit_matrix<0> {
    template<class Begin, class Dimensions>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<class T>
struct normalize_units {
    typedef typename find_base_dimensions<T>::type dimensions;
    typedef typename create_unit_matrix<(T::size::value)>::template apply<
        T,
        dimensions
    >::type matrix;
    typedef typename make_square_and_invert<matrix>::type type;
    static const long extra = (type::size::value) - (T::size::value);
};

// multiply_add_units computes M x V
// where M is a matrix and V is a horizontal
// vector
//
// list<rational> multiply_add_units(list<list<rational> >, list<rational>);

template<int N>
struct multiply_add_units_impl {
    template<class Begin1, class Begin2 ,class X>
    struct apply {
        typedef list<
            typename mpl::plus<
                typename mpl::times<
                    typename Begin2::item,
                    X
                >::type,
                typename Begin1::item
            >::type,
            typename multiply_add_units_impl<N-1>::template apply<
                typename Begin1::next,
                typename Begin2::next,
                X
            >::type
        > type;
    };
};

template<>
struct multiply_add_units_impl<0> {
    template<class Begin1, class Begin2 ,class X>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<int N>
struct multiply_add_units {
    template<class Begin1, class Begin2>
    struct apply {
        typedef typename multiply_add_units_impl<
            (Begin2::item::size::value)
        >::template apply<
            typename multiply_add_units<N-1>::template apply<
                typename Begin1::next,
                typename Begin2::next
            >::type,
            typename Begin2::item,
            typename Begin1::item
        >::type type;
    };
};

template<>
struct multiply_add_units<1> {
    template<class Begin1, class Begin2>
    struct apply {
        typedef typename add_zeroes_impl<
            (Begin2::item::size::value)
        >::template apply<dimensionless_type>::type type1;
        typedef typename multiply_add_units_impl<
            (Begin2::item::size::value)
        >::template apply<
            type1,
            typename Begin2::item,
            typename Begin1::item
        >::type type;
    };
};

// strip_zeroes erases the first N elements of a list if
// they are all zero, otherwise returns inconsistent
//
// list strip_zeroes(list l, int N) {
//     if(N == 0) {
//         return(l);
//     } else if(l.front == 0) {
//         return(strip_zeroes(pop_front(l), N-1));
//     } else {
//         return(inconsistent);
//     }
// }

template<int N>
struct strip_zeroes_impl;

template<class T>
struct strip_zeroes_func {
    template<class L, int N>
    struct apply {
        typedef inconsistent type;
    };
};

template<>
struct strip_zeroes_func<static_rational<0> > {
    template<class L, int N>
    struct apply {
        typedef typename strip_zeroes_impl<N-1>::template apply<typename L::next>::type type;
    };
};

template<int N>
struct strip_zeroes_impl {
    template<class T>
    struct apply {
        typedef typename strip_zeroes_func<typename T::item>::template apply<T, N>::type type;
    };
};

template<>
struct strip_zeroes_impl<0> {
    template<class T>
    struct apply {
        typedef T type;
    };
};

// Given a list of base_units, computes the
// exponents of each base unit for a given
// dimension.
//
// list<rational> calculate_base_unit_exponents(list<base_unit> units, dimension_list dimensions);

template<class T>
struct is_base_dimension_unit {
    typedef mpl::false_ type;
    typedef void base_dimension_type;
};
template<class T>
struct is_base_dimension_unit<list<dim<T, static_rational<1> >, dimensionless_type> > {
    typedef mpl::true_ type;
    typedef T base_dimension_type;
};

template<int N>
struct is_simple_system_impl {
    template<class Begin, class Prev>
    struct apply {
        typedef is_base_dimension_unit<typename Begin::item::dimension_type> test;
        typedef mpl::and_<
            typename test::type,
            mpl::less<Prev, typename test::base_dimension_type>,
            typename is_simple_system_impl<N-1>::template apply<
                typename Begin::next,
                typename test::base_dimension_type
            >
        > type;
        static const bool value = (type::value);
    };
};

template<>
struct is_simple_system_impl<0> {
    template<class Begin, class Prev>
    struct apply : mpl::true_ {
    };
};

template<class T>
struct is_simple_system {
    typedef T Begin;
    typedef is_base_dimension_unit<typename Begin::item::dimension_type> test;
    typedef typename mpl::and_<
        typename test::type,
        typename is_simple_system_impl<
            T::size::value - 1
        >::template apply<
            typename Begin::next::type,
            typename test::base_dimension_type
        >
    >::type type;
    static const bool value = type::value;
};

template<bool>
struct calculate_base_unit_exponents_impl;

template<>
struct calculate_base_unit_exponents_impl<true> {
    template<class T, class Dimensions>
    struct apply {
        typedef typename expand_dimensions<(T::size::value)>::template apply<
            typename find_base_dimensions<T>::type,
            Dimensions
        >::type type;
    };
};

template<>
struct calculate_base_unit_exponents_impl<false> {
    template<class T, class Dimensions>
    struct apply {
        // find the units that correspond to each base dimension
        typedef normalize_units<T> base_solutions;
        // pad the dimension with zeroes so it can just be a
        // list of numbers, making the multiplication easy
        // e.g. if the arguments are list<pound, foot> and
        // list<mass,time^-2> then this step will
        // yield list<0,1,-2>
        typedef typename expand_dimensions<(base_solutions::dimensions::size::value)>::template apply<
            typename base_solutions::dimensions,
            Dimensions
        >::type dimensions;
        // take the unit corresponding to each base unit
        // multiply each of its exponents by the exponent
        // of the base_dimension in the result and sum.
        typedef typename multiply_add_units<dimensions::size::value>::template apply<
            dimensions,
            typename base_solutions::type
        >::type units;
        // Now, verify that the dummy units really
        // cancel out and remove them.
        typedef typename strip_zeroes_impl<base_solutions::extra>::template apply<units>::type type;
    };
};

template<class T, class Dimensions>
struct calculate_base_unit_exponents {
    typedef typename calculate_base_unit_exponents_impl<is_simple_system<T>::value>::template apply<T, Dimensions>::type type;
};

} // namespace detail

} // namespace units

} // namespace boost

#endif

license: mit


code:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

    This is an auto-generated file. Do not edit!
==============================================================================*/
#if FUSION_MAX_VECTOR_SIZE <= 10
#include <boost/fusion/tuple/detail/preprocessed/make_tuple10.hpp>
#elif FUSION_MAX_VECTOR_SIZE <= 20
#include <boost/fusion/tuple/detail/preprocessed/make_tuple20.hpp>
#elif FUSION_MAX_VECTOR_SIZE <= 30
#include <boost/fusion/tuple/detail/preprocessed/make_tuple30.hpp>
#elif FUSION_MAX_VECTOR_SIZE <= 40
#include <boost/fusion/tuple/detail/preprocessed/make_tuple40.hpp>
#elif FUSION_MAX_VECTOR_SIZE <= 50
#include <boost/fusion/tuple/detail/preprocessed/make_tuple50.hpp>
#else
#error "FUSION_MAX_VECTOR_SIZE out of bounds for preprocessed headers"
#endif


code:
// Copyright 2005-2009 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/functional/hash/hash.hpp>


code:
#ifndef BOOST_SERIALIZATION_COLLECTION_SIZE_TYPE_HPP
#define BOOST_SERIALIZATION_COLLECTION_SIZE_TYPE_HPP

// (C) Copyright 2005 Matthias Troyer
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <cstddef> // size_t
#include <boost/serialization/strong_typedef.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/is_bitwise_serializable.hpp>

namespace boost {
namespace serialization {

//BOOST_STRONG_TYPEDEF(std::size_t, collection_size_type)

class collection_size_type {
private:
    typedef std::size_t base_type;
    base_type t;
public:
    collection_size_type(): t(0) {};
    explicit collection_size_type(const std::size_t & t_) :
        t(t_)
    {}
    collection_size_type(const collection_size_type & t_) :
        t(t_.t)
    {}
    collection_size_type & operator=(const collection_size_type & rhs){
        t = rhs.t;
        return *this;
    }
    collection_size_type & operator=(const unsigned int & rhs){
        t = rhs;
        return *this;
    }
    // used for text output
    operator base_type () const {
        return t;
    }
    // used for text input
    operator base_type & () {
        return t;
    }
    bool operator==(const collection_size_type & rhs) const {
        return t == rhs.t;
    }
    bool operator<(const collection_size_type & rhs) const {
        return t < rhs.t;
    }
};

} } // end namespace boost::serialization

BOOST_CLASS_IMPLEMENTATION(collection_size_type, primitive_type)
BOOST_IS_BITWISE_SERIALIZABLE(collection_size_type)

#endif //BOOST_SERIALIZATION_COLLECTION_SIZE_TYPE_HPP


code:
// (C) Copyright David Abrahams 2001.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org for most recent version including documentation.

// Revision History
// 09 Feb 01  Applied John Maddock's Borland patch Moving <true>
//            specialization to unspecialized template (David Abrahams)
// 06 Feb 01  Created (David Abrahams)

#ifndef SELECT_TYPE_DWA20010206_HPP
# define SELECT_TYPE_DWA20010206_HPP

namespace boost { namespace detail {

  // Template class if_true -- select among 2 types based on a bool constant expression
  // Usage:
  //   typename if_true<(bool_const_expression)>::template then<true_type, false_type>::type

  // HP aCC cannot deal with missing names for template value parameters
  template <bool b> struct if_true
  {
      template <class T, class F>
      struct then { typedef T type; };
  };

  template <>
  struct if_true<false>
  {
      template <class T, class F>
      struct then { typedef F type; };
  };
}}
#endif // SELECT_TYPE_DWA20010206_HPP


code:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2014-2014. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTRUSIVE_DETAIL_STD_FWD_HPP
#define BOOST_INTRUSIVE_DETAIL_STD_FWD_HPP

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

//////////////////////////////////////////////////////////////////////////////
//                        Standard predeclarations
//////////////////////////////////////////////////////////////////////////////

#include <boost/move/detail/std_ns_begin.hpp>
BOOST_MOVE_STD_NS_BEG

template<class T>
struct less;

template<class T>
struct equal_to;

struct input_iterator_tag;
struct forward_iterator_tag;
struct bidirectional_iterator_tag;
struct random_access_iterator_tag;

BOOST_MOVE_STD_NS_END
#include <boost/move/detail/std_ns_end.hpp>

#endif //#ifndef BOOST_INTRUSIVE_DETAIL_STD_FWD_HPP


code:
// (C) Copyright Tobias Schwinger
//
// Use modification and distribution are subject to the boost Software License,
// Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt).

//------------------------------------------------------------------------------

// no include guards, this file is intended for multiple inclusions

  struct BOOST_FT_cc_name
  {
    typedef detail::encode_bits<0,BOOST_FT_cc_id> bits;
    typedef detail::constant<BOOST_FT_cc_mask> mask;
  };


code:
//  (C) Copyright John Maddock 2007.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//  This file is machine generated, do not edit by hand

// Unrolled polynomial evaluation using second order Horners rule
#ifndef BOOST_MATH_TOOLS_POLY_EVAL_11_HPP
#define BOOST_MATH_TOOLS_POLY_EVAL_11_HPP

namespace boost{ namespace math{ namespace tools{ namespace detail{

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T*, const V&, const mpl::int_<0>*) BOOST_MATH_NOEXCEPT(V)
{
   return static_cast<V>(0);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<1>*) BOOST_MATH_NOEXCEPT(V)
{
   return static_cast<V>(a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<2>*) BOOST_MATH_NOEXCEPT(V)
{
   return static_cast<V>(a[1] * x + a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<3>*) BOOST_MATH_NOEXCEPT(V)
{
   return static_cast<V>((a[2] * x + a[1]) * x + a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<4>*) BOOST_MATH_NOEXCEPT(V)
{
   return static_cast<V>(((a[3] * x + a[2]) * x + a[1]) * x + a[0]);
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<5>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = static_cast<V>(a[4] * x2 + a[2]);
   t[1] = static_cast<V>(a[3] * x2 + a[1]);
   t[0] *= x2;
   t[0] += static_cast<V>(a[0]);
   t[1] *= x;
   return t[0] + t[1];
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<6>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = a[5] * x2 + a[3];
   t[1] = a[4] * x2 + a[2];
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[1]);
   t[1] += static_cast<V>(a[0]);
   t[0] *= x;
   return t[0] + t[1];
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<7>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = static_cast<V>(a[6] * x2 + a[4]);
   t[1] = static_cast<V>(a[5] * x2 + a[3]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[2]);
   t[1] += static_cast<V>(a[1]);
   t[0] *= x2;
   t[0] += static_cast<V>(a[0]);
   t[1] *= x;
   return t[0] + t[1];
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<8>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = a[7] * x2 + a[5];
   t[1] = a[6] * x2 + a[4];
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[3]);
   t[1] += static_cast<V>(a[2]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[1]);
   t[1] += static_cast<V>(a[0]);
   t[0] *= x;
   return t[0] + t[1];
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<9>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = static_cast<V>(a[8] * x2 + a[6]);
   t[1] = static_cast<V>(a[7] * x2 + a[5]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[4]);
   t[1] += static_cast<V>(a[3]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[2]);
   t[1] += static_cast<V>(a[1]);
   t[0] *= x2;
   t[0] += static_cast<V>(a[0]);
   t[1] *= x;
   return t[0] + t[1];
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<10>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = a[9] * x2 + a[7];
   t[1] = a[8] * x2 + a[6];
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[5]);
   t[1] += static_cast<V>(a[4]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[3]);
   t[1] += static_cast<V>(a[2]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[1]);
   t[1] += static_cast<V>(a[0]);
   t[0] *= x;
   return t[0] + t[1];
}

template <class T, class V>
inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<11>*) BOOST_MATH_NOEXCEPT(V)
{
   V x2 = x * x;
   V t[2];
   t[0] = static_cast<V>(a[10] * x2 + a[8]);
   t[1] = static_cast<V>(a[9] * x2 + a[7]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[6]);
   t[1] += static_cast<V>(a[5]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[4]);
   t[1] += static_cast<V>(a[3]);
   t[0] *= x2;
   t[1] *= x2;
   t[0] += static_cast<V>(a[2]);
   t[1] += static_cast<V>(a[1]);
   t[0] *= x2;
   t[0] += static_cast<V>(a[0]);
   t[1] *= x;
   return t[0] + t[1];
}

}}}} // namespaces

#endif // include guard


code:
#ifndef BOOST_MPL_AUX_CLEAR_IMPL_HPP_INCLUDED
#define BOOST_MPL_AUX_CLEAR_IMPL_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#include <boost/mpl/clear_fwd.hpp>
#include <boost/mpl/aux_/traits_lambda_spec.hpp>
#include <boost/mpl/aux_/config/eti.hpp>

namespace boost { namespace mpl {

// no default implementation; the definition is needed to make MSVC happy

template< typename Tag >
struct clear_impl
{
    template< typename Sequence > struct apply;
};

BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC(1, clear_impl)

}}

#endif // BOOST_MPL_AUX_CLEAR_IMPL_HPP_INCLUDED


code:
// Copyright (C) 2005 Arkadiy Vertleyb
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_TYPEOF_ENCODE_DECODE_PARAMS_HPP_INCLUDED
#define BOOST_TYPEOF_ENCODE_DECODE_PARAMS_HPP_INCLUDED

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>

// Assumes iter0 contains initial iterator

#define BOOST_TYPEOF_DECODE_PARAM(z, n, text)   \
    typedef boost::type_of::decode_type<iter##n> decode##n;     \
    typedef typename decode##n::type p##n;      \
    typedef typename decode##n::iter BOOST_PP_CAT(iter, BOOST_PP_INC(n));

#define BOOST_TYPEOF_DECODE_PARAMS(n)\
    BOOST_PP_REPEAT(n, BOOST_TYPEOF_DECODE_PARAM, ~)

// The P0, P1, ... PN are encoded and added to V

#define BOOST_TYPEOF_ENCODE_PARAMS_BEGIN(z, n, text)\
    typename boost::type_of::encode_type<

#define BOOST_TYPEOF_ENCODE_PARAMS_END(z, n, text)\
    , BOOST_PP_CAT(P, n)>::type

#define BOOST_TYPEOF_ENCODE_PARAMS(n, ID)                   \
    BOOST_PP_REPEAT(n, BOOST_TYPEOF_ENCODE_PARAMS_BEGIN, ~) \
    typename boost::type_of::push_back<V, boost::mpl::size_t<ID> >::type      \
    BOOST_PP_REPEAT(n, BOOST_TYPEOF_ENCODE_PARAMS_END, ~)

#endif//BOOST_TYPEOF_ENCODE_DECODE_PARAMS_HPP_INCLUDED


code:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_CURRENT_BASE_DIMENSION_HPP
#define BOOST_UNITS_CURRENT_BASE_DIMENSION_HPP

#include <boost/units/config.hpp>
#include <boost/units/base_dimension.hpp>

namespace boost {

namespace units {

/// base dimension of current
struct current_base_dimension :
    boost::units::base_dimension<current_base_dimension,-6>
{ };

} // namespace units

} // namespace boost

#if BOOST_UNITS_HAS_BOOST_TYPEOF

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TYPE(boost::units::current_base_dimension)

#endif

namespace boost {

namespace units {

/// dimension of electric current (I)
typedef current_base_dimension::dimension_type    current_dimension;

} // namespace units

} // namespace boost

#endif // BOOST_UNITS_CURRENT_BASE_DIMENSION_HPP


code:
/*
Copyright Rene Rivera 2008-2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/predef/detail/test.h>

#ifndef BOOST_PREDEF_MAKE_H
#define BOOST_PREDEF_MAKE_H

/*
Shorthands for the common version number formats used by vendors...
*/

/*`
[heading `BOOST_PREDEF_MAKE_..` macros]

These set of macros decompose common vendor version number
macros which are composed version, revision, and patch digits.
The naming convention indicates:

* The base of the specified version number. "`BOOST_PREDEF_MAKE_0X`" for
  hexadecimal digits, and "`BOOST_PREDEF_MAKE_10`" for decimal digits.
* The format of the vendor version number. Where "`V`" indicates the version digits,
  "`R`" indicates the revision digits, "`P`" indicates the patch digits, and "`0`"
  indicates an ignored digit.

Macros are:
*/
/*` `BOOST_PREDEF_MAKE_0X_VRP(V)` */
#define BOOST_PREDEF_MAKE_0X_VRP(V) BOOST_VERSION_NUMBER((V&0xF00)>>8,(V&0xF0)>>4,(V&0xF))
/*` `BOOST_PREDEF_MAKE_0X_VVRP(V)` */
#define BOOST_PREDEF_MAKE_0X_VVRP(V) BOOST_VERSION_NUMBER((V&0xFF00)>>8,(V&0xF0)>>4,(V&0xF))
/*` `BOOST_PREDEF_MAKE_0X_VRPP(V)` */
#define BOOST_PREDEF_MAKE_0X_VRPP(V) BOOST_VERSION_NUMBER((V&0xF000)>>12,(V&0xF00)>>8,(V&0xFF))
/*` `BOOST_PREDEF_MAKE_0X_VVRR(V)` */
#define BOOST_PREDEF_MAKE_0X_VVRR(V) BOOST_VERSION_NUMBER((V&0xFF00)>>8,(V&0xFF),0)
/*` `BOOST_PREDEF_MAKE_0X_VRRPPPP(V)` */
#define BOOST_PREDEF_MAKE_0X_VRRPPPP(V) BOOST_VERSION_NUMBER((V&0xF000000)>>24,(V&0xFF0000)>>16,(V&0xFFFF))
/*` `BOOST_PREDEF_MAKE_0X_VVRRP(V)` */
#define BOOST_PREDEF_MAKE_0X_VVRRP(V) BOOST_VERSION_NUMBER((V&0xFF000)>>12,(V&0xFF0)>>4,(V&0xF))
/*` `BOOST_PREDEF_MAKE_0X_VRRPP000(V)` */
#define BOOST_PREDEF_MAKE_0X_VRRPP000(V) BOOST_VERSION_NUMBER((V&0xF0000000)>>28,(V&0xFF00000)>>20,(V&0xFF000)>>12)
/*` `BOOST_PREDEF_MAKE_0X_VVRRPP(V)` */
#define BOOST_PREDEF_MAKE_0X_VVRRPP(V) BOOST_VERSION_NUMBER((V&0xFF0000)>>16,(V&0xFF00)>>8,(V&0xFF))
/*` `BOOST_PREDEF_MAKE_10_VPPP(V)` */
#define BOOST_PREDEF_MAKE_10_VPPP(V) BOOST_VERSION_NUMBER(((V)/1000)%10,0,(V)%1000)
/*` `BOOST_PREDEF_MAKE_10_VRP(V)` */
#define BOOST_PREDEF_MAKE_10_VRP(V) BOOST_VERSION_NUMBER(((V)/100)%10,((V)/10)%10,(V)%10)
/*` `BOOST_PREDEF_MAKE_10_VRP000(V)` */
#define BOOST_PREDEF_MAKE_10_VRP000(V) BOOST_VERSION_NUMBER(((V)/100000)%10,((V)/10000)%10,((V)/1000)%10)
/*` `BOOST_PREDEF_MAKE_10_VRPP(V)` */
#define BOOST_PREDEF_MAKE_10_VRPP(V) BOOST_VERSION_NUMBER(((V)/1000)%10,((V)/100)%10,(V)%100)
/*` `BOOST_PREDEF_MAKE_10_VRR(V)` */
#define BOOST_PREDEF_MAKE_10_VRR(V) BOOST_VERSION_NUMBER(((V)/100)%10,(V)%100,0)
/*` `BOOST_PREDEF_MAKE_10_VRRPP(V)` */
#define BOOST_PREDEF_MAKE_10_VRRPP(V) BOOST_VERSION_NUMBER(((V)/10000)%10,((V)/100)%100,(V)%100)
/*` `BOOST_PREDEF_MAKE_10_VRR000(V)` */
#define BOOST_PREDEF_MAKE_10_VRR000(V) BOOST_VERSION_NUMBER(((V)/100000)%10,((V)/1000)%100,0)
/*` `BOOST_PREDEF_MAKE_10_VV00(V)` */
#define BOOST_PREDEF_MAKE_10_VV00(V) BOOST_VERSION_NUMBER(((V)/100)%100,0,0)
/*` `BOOST_PREDEF_MAKE_10_VVRR(V)` */
#define BOOST_PREDEF_MAKE_10_VVRR(V) BOOST_VERSION_NUMBER(((V)/100)%100,(V)%100,0)
/*` `BOOST_PREDEF_MAKE_10_VVRRPP(V)` */
#define BOOST_PREDEF_MAKE_10_VVRRPP(V) BOOST_VERSION_NUMBER(((V)/10000)%100,((V)/100)%100,(V)%100)
/*` `BOOST_PREDEF_MAKE_10_VVRR0PP00(V)` */
#define BOOST_PREDEF_MAKE_10_VVRR0PP00(V) BOOST_VERSION_NUMBER(((V)/10000000)%100,((V)/100000)%100,((V)/100)%100)
/*` `BOOST_PREDEF_MAKE_10_VVRR0PPPP(V)` */
#define BOOST_PREDEF_MAKE_10_VVRR0PPPP(V) BOOST_VERSION_NUMBER(((V)/10000000)%100,((V)/100000)%100,(V)%10000)
/*` `BOOST_PREDEF_MAKE_10_VVRR00PP00(V)` */
#define BOOST_PREDEF_MAKE_10_VVRR00PP00(V) BOOST_VERSION_NUMBER(((V)/100000000)%100,((V)/1000000)%100,((V)/100)%100)
/*`
[heading `BOOST_PREDEF_MAKE_*..` date macros]

Date decomposition macros return a date in the relative to the 1970
Epoch date. If the month is not available, January 1st is used as the month and day.
If the day is not available, but the month is, the 1st of the month is used as the day.
*/
/*` `BOOST_PREDEF_MAKE_DATE(Y,M,D)` */
#define BOOST_PREDEF_MAKE_DATE(Y,M,D) BOOST_VERSION_NUMBER((Y)%10000-1970,(M)%100,(D)%100)
/*` `BOOST_PREDEF_MAKE_YYYYMMDD(V)` */
#define BOOST_PREDEF_MAKE_YYYYMMDD(V) BOOST_PREDEF_MAKE_DATE(((V)/10000)%10000,((V)/100)%100,(V)%100)
/*` `BOOST_PREDEF_MAKE_YYYY(V)` */
#define BOOST_PREDEF_MAKE_YYYY(V) BOOST_PREDEF_MAKE_DATE(V,1,1)
/*` `BOOST_PREDEF_MAKE_YYYYMM(V)` */
#define BOOST_PREDEF_MAKE_YYYYMM(V) BOOST_PREDEF_MAKE_DATE((V)/100,(V)%100,1)

#endif


code:
/*==============================================================================
    Copyright (c) 2005-2010 Joel de Guzman
    Copyright (c) 2010-2011 Thomas Heller

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef BOOST_PHOENIX_CORE_ENVIRONMENT_HPP
#define BOOST_PHOENIX_CORE_ENVIRONMENT_HPP

#include <boost/phoenix/core/limits.hpp>
#include <boost/fusion/sequence/intrinsic/at.hpp>
#include <boost/fusion/support/is_sequence.hpp>
#include <boost/phoenix/support/vector.hpp>
#include <boost/proto/transform/impl.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/utility/result_of.hpp>

#include <typeinfo>

namespace boost { namespace phoenix
{
    struct unused {};

    namespace result_of
    {
        template <typename Env, typename Actions>
        struct context
        {
            typedef vector2<Env, Actions> type;
        };

        template <typename Env, typename Actions>
        struct make_context
            : context<Env, Actions>
        {};

        template <typename Context>
        struct env
        {
            typedef
                typename fusion::result_of::at_c<
                    typename boost::remove_reference<Context>::type
                  , 0
                >::type
                type;
        };

        template <typename Context>
        struct actions
        {
            typedef
                typename fusion::result_of::at_c<
                    typename boost::remove_reference<Context>::type
                  , 1
                >::type
                type;
        };
    }

    namespace functional
    {
        struct context
        {
            BOOST_PROTO_CALLABLE()

            template <typename Sig>
            struct result;

            template <typename This, typename Env, typename Actions>
            struct result<This(Env, Actions)>
                : result<This(Env const &, Actions const &)>
            {};

            template <typename This, typename Env, typename Actions>
            struct result<This(Env &, Actions)>
                : result<This(Env &, Actions const &)>
            {};

            template <typename This, typename Env, typename Actions>
            struct result<This(Env, Actions &)>
                : result<This(Env const &, Actions &)>
            {};

            template <typename This, typename Env, typename Actions>
            struct result<This(Env &, Actions &)>
                : result_of::context<Env &, Actions &>
            {};

            template <typename Env, typename Actions>
            typename result_of::context<Env &, Actions &>::type
            operator()(Env & env, Actions & actions) const
            {
                vector2<Env &, Actions &> e = {env, actions};
                return e;
            }

            template <typename Env, typename Actions>
            typename result_of::context<Env const &, Actions &>::type
            operator()(Env const & env, Actions & actions) const
            {
                vector2<Env const &, Actions &> e = {env, actions};
                return e;
            }

            template <typename Env, typename Actions>
            typename result_of::context<Env &, Actions const &>::type
            operator()(Env & env, Actions const & actions) const
            {
                vector2<Env &, Actions const &> e = {env, actions};
                return e;
            }

            template <typename Env, typename Actions>
            typename result_of::context<Env const &, Actions const &>::type
            operator()(Env const & env, Actions const & actions) const
            {
                vector2<Env const&, Actions const &> e = {env, actions};
                return e;
            }
        };

        struct make_context
            : context
        {};

        struct env
        {
            BOOST_PROTO_CALLABLE()

            template <typename Sig>
            struct result;

            template <typename This, typename Context>
            struct result<This(Context)>
                : result<This(Context const &)>
            {};

            template <typename This, typename Context>
            struct result<This(Context &)>
                : result_of::env<Context>
            {};

            template <typename Context>
            typename result_of::env<Context const>::type
            operator()(Context const & ctx) const
            {
                return fusion::at_c<0>(ctx);
            }

            template <typename Context>
            typename result_of::env<Context>::type
            operator()(Context & ctx) const
            {
                return fusion::at_c<0>(ctx);
            }
        };

        struct actions
        {
            BOOST_PROTO_CALLABLE()

            template <typename Sig>
            struct result;

            template <typename This, typename Context>
            struct result<This(Context)>
                : result<This(Context const &)>
            {};

            template <typename This, typename Context>
            struct result<This(Context &)>
                : result_of::actions<Context>
            {};

            template <typename Context>
            typename result_of::actions<Context const>::type
            operator()(Context const & ctx) const
            {
                return fusion::at_c<1>(ctx);
            }

            template <typename Context>
            typename result_of::actions<Context>::type
            operator()(Context & ctx) const
            {
                return fusion::at_c<1>(ctx);
            }
        };

    }

    struct _context
        : proto::transform<_context>
    {
        template <typename Expr, typename State, typename Data>
        struct impl
            : proto::transform_impl<Expr, State, Data>
        {
            typedef vector2<State, Data> result_type;

            result_type operator()(
                typename impl::expr_param
              , typename impl::state_param s
              , typename impl::data_param d
            ) const
            {
                vector2<State, Data> e = {s, d};
                return e;
            }
        };
    };

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env const &, Actions const&>::type const
    context(Env const& env, Actions const& actions)
    {
        vector2<Env const&, Actions const &> e = {env, actions};
        return e;
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env const &, Actions const&>::type const
    make_context(Env const& env, Actions const& actions)
    {
        return context(env, actions);
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env &, Actions const&>::type const
    context(Env & env, Actions const& actions)
    {
        vector2<Env &, Actions const &> e = {env, actions};
        return e;
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env &, Actions const&>::type const
    make_context(Env & env, Actions const& actions)
    {
        return context(env, actions);
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env const &, Actions &>::type const
    context(Env const& env, Actions & actions)
    {
        vector2<Env const&, Actions &> e = {env, actions};
        return e;
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env const &, Actions &>::type const
    make_context(Env const& env, Actions & actions)
    {
        return context(env, actions);
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env &, Actions &>::type const
    context(Env & env, Actions & actions)
    {
        vector2<Env &, Actions &> e = {env, actions};
        return e;
    }

    template <typename Env, typename Actions>
    inline
    typename result_of::context<Env &, Actions &>::type const
    make_context(Env & env, Actions & actions)
    {
        return context(env, actions);
    }

    struct _env
        : proto::transform<_env>
    {
        template <typename Expr, typename State, typename Data>
        struct impl
            : proto::transform_impl<Expr, State, Data>
        {
            typedef State result_type;

            result_type operator()(
                typename impl::expr_param
              , typename impl::state_param s
              , typename impl::data_param
            ) const
            {
                return s;
            }
        };
    };

    template <typename Expr, typename State>
    struct _env::impl<Expr, State, proto::empty_env>
        : proto::transform_impl<Expr, State, proto::empty_env>
    {
            typedef
                typename fusion::result_of::at_c<
                    typename boost::remove_reference<State>::type
                  , 0
                >::type
                result_type;

            result_type operator()(
                typename impl::expr_param
              , typename impl::state_param s
              , typename impl::data_param
            ) const
            {
                return fusion::at_c<0>(s);
            }
    };

    template <typename Expr, typename State>
    struct _env::impl<Expr, State, unused>
        : _env::impl<Expr, State, proto::empty_env>
    {};

    template <typename Context>
    inline
    typename fusion::result_of::at_c<Context, 0>::type
    env(Context & ctx)
    {
        return fusion::at_c<0>(ctx);
    }

    template <typename Context>
    inline
    typename fusion::result_of::at_c<Context const, 0>::type
    env(Context const & ctx)
    {
        return fusion::at_c<0>(ctx);
    }

    struct _actions
        : proto::transform<_actions>
    {
        template <typename Expr, typename State, typename Data>
        struct impl
            : proto::transform_impl<Expr, State, Data>
        {
            typedef Data result_type;

            result_type operator()(
                typename impl::expr_param
              , typename impl::state_param
              , typename impl::data_param d
            ) const
            {
                return d;
            }
        };
    };

    template <typename Expr, typename State>
    struct _actions::impl<Expr, State, proto::empty_env>
        : proto::transform_impl<Expr, State, proto::empty_env>
    {
            typedef
                typename fusion::result_of::at_c<
                    typename boost::remove_reference<State>::type
                  , 1
                >::type
                result_type;

            result_type operator()(
                typename impl::expr_param
              , typename impl::state_param s
              , typename impl::data_param
            ) const
            {
                return fusion::at_c<1>(s);
            }
    };

    template <typename Expr, typename State>
    struct _actions::impl<Expr, State, unused>
        : _actions::impl<Expr, State, proto::empty_env>
    {};

    template <typename Context>
    inline
    typename fusion::result_of::at_c<Context, 1>::type
    actions(Context & ctx)
    {
        return fusion::at_c<1>(ctx);
    }

    template <typename Context>
    inline
    typename fusion::result_of::at_c<Context const, 1>::type
    actions(Context const & ctx)
    {
        return fusion::at_c<1>(ctx);
    }

    namespace result_of
    {
        template <
            BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
                BOOST_PHOENIX_LIMIT
              , typename A
              , mpl::void_
            )
          , typename Dummy = void
        >
        struct make_env;

    #define M0(Z, N, D)                                                         \
        template <BOOST_PHOENIX_typename_A(N)>                                  \
        struct make_env<BOOST_PHOENIX_A(N)>                                     \
        {                                                                       \
            typedef BOOST_PP_CAT(vector, N)<BOOST_PHOENIX_A(N)> type;           \
        };                                                                      \
    /**/
        BOOST_PP_REPEAT_FROM_TO(1, BOOST_PHOENIX_LIMIT, M0, _)
    #undef M0
    }

    inline
    result_of::make_env<>::type
    make_env()
    {
        return result_of::make_env<>::type();
    }
#define M0(Z, N, D)                                                             \
    template <BOOST_PHOENIX_typename_A(N)>                                      \
    inline                                                                      \
    typename result_of::make_env<BOOST_PHOENIX_A_ref(N)>::type                  \
    make_env(BOOST_PHOENIX_A_ref_a(N))                                          \
    {                                                                           \
        typename result_of::make_env<BOOST_PHOENIX_A_ref(N)>::type              \
            env =                                                               \
            {                                                                   \
                BOOST_PHOENIX_a(N)                                              \
            };                                                                  \
        return env;                                                             \
    }                                                                           \
    template <BOOST_PHOENIX_typename_A(N)>                                      \
    inline                                                                      \
    typename result_of::make_env<BOOST_PHOENIX_A_const_ref(N)>::type            \
    make_env(BOOST_PHOENIX_A_const_ref_a(N))                                    \
    {                                                                           \
        typename result_of::make_env<BOOST_PHOENIX_A_const_ref(N)>::type        \
            env =                                                               \
            {                                                                   \
                BOOST_PHOENIX_a(N)                                              \
            };                                                                  \
        return env;                                                             \
    }                                                                           \
    /**/
        BOOST_PP_REPEAT_FROM_TO(1, BOOST_PHOENIX_LIMIT, M0, _)
    #undef M0

    template <typename T, typename Enable = void>
    struct is_environment : fusion::traits::is_sequence<T> {};
}}

#endif


code:
// Boost.Range library
//
//  Copyright Thorsten Ottosen 2003-2004. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/range/
//

#ifndef BOOST_RANGE_SIZE_HPP
#define BOOST_RANGE_SIZE_HPP

#if defined(_MSC_VER)
# pragma once
#endif

#include <boost/range/config.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/size_type.hpp>
#include <boost/range/detail/has_member_size.hpp>
#include <boost/assert.hpp>
#include <boost/cstdint.hpp>
#include <boost/utility.hpp>

namespace boost
{
    namespace range_detail
    {

        template<class SinglePassRange>
        inline typename ::boost::enable_if<
            has_member_size<SinglePassRange>,
            typename range_size<const SinglePassRange>::type
        >::type
        range_calculate_size(const SinglePassRange& rng)
        {
            return rng.size();
        }

        template<class SinglePassRange>
        inline typename disable_if<
            has_member_size<SinglePassRange>,
            typename range_size<const SinglePassRange>::type
        >::type
        range_calculate_size(const SinglePassRange& rng)
        {
            return std::distance(boost::begin(rng), boost::end(rng));
        }
    }

    template<class SinglePassRange>
    inline typename range_size<const SinglePassRange>::type
    size(const SinglePassRange& rng)
    {
// Very strange things happen on some compilers that have the range concept
// asserts disabled. This preprocessor condition is clearly redundant on a
// working compiler but is vital for at least some compilers such as clang 4.2
// but only on the Mac!
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT == 1
        BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<SinglePassRange>));
#endif

#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) && \
    !BOOST_WORKAROUND(__GNUC__, < 3) \
    /**/
        using namespace range_detail;
#endif

        return range_calculate_size(rng);
    }

} // namespace 'boost'

#endif