<commit_before>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// Main
//==============================================================================

#include "checkforupdateswindow.h"
#include "cliutils.h"
#include "coresettings.h"
#include "guiutils.h"
#include "mainwindow.h"
#include "settings.h"
#include "splashscreenwindow.h"

//==============================================================================

#include <QDir>
#include <QLocale>
#include <QProcess>
#include <QSettings>
#include <QVariant>

#ifdef Q_OS_WIN
    #include <QWebSettings>
#endif

//==============================================================================

#include <QtSingleApplication>

//==============================================================================

int main(int pArgC, char *pArgV[])
{
    // Initialise Qt's message pattern

    OpenCOR::initQtMessagePattern();

    // Determine whether we should try the CLI version of OpenCOR:
    //  - Windows: we never try the CLI version of OpenCOR. We go straight for
    //             its GUI version.
    //  - Linux: we always try the CLI version of OpenCOR and then go for its
    //           GUI version, if needed.
    //  - OS X: we try the CLI version of OpenCOR unless the user double clicks
    //          on the OpenCOR bundle or opens it from the command line by
    //          entering something like:
    //              open OpenCOR.app
    //          in which case we go for its GUI version.
    // Note #1: on Windows, we have two binaries (.com and .exe that are for the
    //          CLI and GUI versions of OpenCOR, respectively). This means that
    //          when a console window is open, to enter something like:
    //              C:\>OpenCOR
    //          will effectively call OpenCOR.com. From there, should there be
    //          no argument that requires CLI treatment, then the GUI version of
    //          OpenCOR will be run. This is, unfortunately, the only way to
    //          have OpenCOR to behave as both a CLI and a GUI application on
    //          Windows, hence the [OpenCOR]/windows/main.cpp file, which is
    //          used to generate the CLI version of OpenCOR...
    // Note #2: on OS X, if we were to try to open the OpenCOR bundle from the
    //          command line, then we would get an error message similar to:
    //              LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app.
    //          Fortunately, when double clicking on the OpenCOR bundle or
    //          opening it from the command line, a special argument in the form
    //          of -psn_0_1234567 is passed to OpenCOR, so we can use that to
    //          determine whether we need to force OpenCOR to be run in GUI mode
    //          or whether we first try the CLI version of OpenCOR, and then its
    //          GUI version, if needed...

#if defined(Q_OS_WIN)
    bool tryCliVersion = false;
#elif defined(Q_OS_LINUX)
    bool tryCliVersion = true;
#elif defined(Q_OS_MAC)
    bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5);
#else
    #error Unsupported platform
#endif

    // Run the CLI version of OpenCOR, if possible/needed

    if (tryCliVersion) {
        // Initialise the plugins path

        OpenCOR::initPluginsPath(pArgV[0]);

        // Create and initialise the CLI version of OpenCOR

        QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV);

        OpenCOR::initApplication(cliApp);

        // Try to run the CLI version of OpenCOR

        int res;

        bool runCliApplication = OpenCOR::cliApplication(cliApp, &res);

        OpenCOR::removeGlobalInstances();

        delete cliApp;

        if (runCliApplication)
            // OpenCOR was run as a CLI application, so leave

            return res;

        // Note: at this stage, we tried the CLI version of OpenCOR, but in the
        //       end we need to go for its GUI version, so start over but with
        //       the GUI version of OpenCOR this time...
    }

    // Make sure that we always use indirect rendering on Linux
    // Note: indeed, depending on which plugins are selected, OpenCOR may need
    //       LLVM. If that's the case, and in case the user's video card uses a
    //       driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there
    //       may be a conflict between the version of LLVM used by OpenCOR and
    //       the one used by the video card. One way to address this issue is by
    //       using indirect rendering...

#ifdef Q_OS_LINUX
    qputenv("LIBGL_ALWAYS_INDIRECT", "1");
#endif

    // Initialise the plugins path

    OpenCOR::initPluginsPath(pArgV[0]);

    // Create the GUI version of OpenCOR

    SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(),
                                                                                pArgC, pArgV);

    // Send a message (containing the arguments that were passed to this
    // instance of OpenCOR minus the first one since it corresponds to the full
    // path to our executable, which we are not interested in) to our 'official'
    // instance of OpenCOR, should there be one. If there is none, then just
    // carry on as normal, otherwise exit since we want only one instance of
    // OpenCOR at any given time

    QStringList appArguments = guiApp->arguments();

    appArguments.removeFirst();

    QString arguments = appArguments.join("|");

    if (guiApp->isRunning()) {
        guiApp->sendMessage(arguments);

        delete guiApp;

        return 0;
    }

    // Initialise the GUI version of OpenCOR

    QString appDate = QString();

    OpenCOR::initApplication(guiApp, &appDate);

    // Check whether we want to check for new versions at startup

    QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication);

#ifndef QT_DEBUG
    settings.beginGroup("CheckForUpdatesWindow");
        bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool();
        bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool();
    settings.endGroup();
#endif

    // Check whether a new version of OpenCOR is available

#ifndef QT_DEBUG
    if (checkForUpdatesAtStartup) {
        OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate);

        checkForUpdatesEngine->check();

        if (   ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion())
            || (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) {
            // Retrieve the language to be used to show the check for updates
            // window

            const QString systemLocale = QLocale::system().name().left(2);

            QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString();

            if (locale.isEmpty())
                locale = systemLocale;

            QLocale::setDefault(QLocale(locale));

            QTranslator qtTranslator;
            QTranslator appTranslator;

            qtTranslator.load(":qt_"+locale);
            qApp->installTranslator(&qtTranslator);

            appTranslator.load(":app_"+locale);
            qApp->installTranslator(&appTranslator);

            // Show the check for updates window
            // Note: checkForUpdatesEngine gets deleted by
            //       checkForUpdatesWindow...

            OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine);

            settings.beginGroup(checkForUpdatesWindow.objectName());
                checkForUpdatesWindow.loadSettings(&settings);
            settings.endGroup();

            checkForUpdatesWindow.exec();

            settings.beginGroup(checkForUpdatesWindow.objectName());
                checkForUpdatesWindow.saveSettings(&settings);
            settings.endGroup();
        } else {
            delete checkForUpdatesEngine;
        }
    }
#endif

    // Initialise our colours by 'updating' them

    OpenCOR::updateColors();

    // Create and show our splash screen, if we are not in debug mode

#ifndef QT_DEBUG
    OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow();

    splashScreen->show();
#endif

    // Create our main window

    OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate);

    // Keep track of our main window (required by QtSingleApplication so that it
    // can do what it's supposed to be doing)

    guiApp->setActivationWindow(win);

    // Handle our arguments

    win->handleArguments(arguments);

    // Show our main window

    win->show();

    // By default, we can and should execute our application

    bool canExecuteAplication = true;

    // Close and delete our splash screen once our main window is visible, if we
    // are not in debug mode

#ifndef QT_DEBUG
    splashScreen->closeAndDeleteAfter(win);

    // Make sure that our main window is in the foreground, unless the user
    // decided to close our main window while we were showing our splash screen
    // Note: indeed, on Linux, to show our splash screen may result in our main
    //       window being shown in the background...

    if (!win->shuttingDown())
        win->showSelf();
    else
        canExecuteAplication = false;
#endif

    // Execute our application, if possible

    int res;

    if (canExecuteAplication)
        res = guiApp->exec();
    else
        res = 0;

    // Keep track of our application file and directory paths (in case we need
    // to restart OpenCOR)

    QString appFilePath = guiApp->applicationFilePath();
    QString appDirPath  = guiApp->applicationDirPath();

    // Delete our main window

    delete win;

    // We use QtWebKit, and QWebPage in particular, which results in some leak
    // messages being generated on Windows when leaving OpenCOR. This is because
    // an object cache is shared between all QWebPage instances. So to destroy a
    // QWebPage instance doesn't clear the cache, hence the leak messages.
    // However, those messages are 'only' warnings, so we can safely live with
    // them. Still, it doesn't look 'good', so we clear the memory caches, thus
    // avoiding those leak messages...
    // Note: the below must absolutely be done after calling guiApp->exec() and
    //       before deleting guiApp...

#ifdef Q_OS_WIN
    QWebSettings::clearMemoryCaches();
#endif

    // Remove all 'global' instances that were created and used during this
    // session

    OpenCOR::removeGlobalInstances();

    // Delete our application

    delete guiApp;

    // We are done with the execution of our application, so now the question is
    // whether we need to restart
    // Note: we do this here rather than 'within' the GUI because once we have
    //       launched a new instance of OpenCOR, we want this instance of
    //       OpenCOR to finish as soon as possible, which will be the case here
    //       since all that remains to be done is to return the result of the
    //       execution of our application...

    if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) {
        // We want to restart, so the question is whether we want a normal
        // restart or a clean one

        if (res == OpenCOR::CleanRestart)
            // We want a clean restart, so clear all the user settings (indeed,
            // this will ensure that the various windows are, for instance,
            // properly reset with regards to their dimensions)

            settings.clear();

        // Restart OpenCOR, but without providing any of the arguments that were
        // originally passed to us since we want to reset everything

        QProcess::startDetached(appFilePath, QStringList(), appDirPath);
    }

    // We are done running the GUI version of OpenCOR, so leave

    return res;
}

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// Main
//==============================================================================

#include "checkforupdateswindow.h"
#include "cliutils.h"
#include "coresettings.h"
#include "guiutils.h"
#include "mainwindow.h"
#include "settings.h"
#include "splashscreenwindow.h"

//==============================================================================

#include <QDir>
#include <QLocale>
#include <QProcess>
#include <QSettings>
#include <QVariant>

#ifdef Q_OS_WIN
    #include <QWebSettings>
#endif

//==============================================================================

#include <QtSingleApplication>

//==============================================================================

int main(int pArgC, char *pArgV[])
{
    // Initialise Qt's message pattern

    OpenCOR::initQtMessagePattern();

    // Determine whether we should try the CLI version of OpenCOR:
    //  - Windows: we never try the CLI version of OpenCOR. We go straight for
    //             its GUI version.
    //  - Linux: we always try the CLI version of OpenCOR and then go for its
    //           GUI version, if needed.
    //  - OS X: we try the CLI version of OpenCOR unless the user double clicks
    //          on the OpenCOR bundle or opens it from the command line by
    //          entering something like:
    //              open OpenCOR.app
    //          in which case we go for its GUI version.
    // Note #1: on Windows, we have two binaries (.com and .exe that are for the
    //          CLI and GUI versions of OpenCOR, respectively). This means that
    //          when a console window is open, to enter something like:
    //              C:\>OpenCOR
    //          will effectively call OpenCOR.com. From there, should there be
    //          no argument that requires CLI treatment, then the GUI version of
    //          OpenCOR will be run. This is, unfortunately, the only way to
    //          have OpenCOR to behave as both a CLI and a GUI application on
    //          Windows, hence the [OpenCOR]/windows/main.cpp file, which is
    //          used to generate the CLI version of OpenCOR...
    // Note #2: on OS X, if we were to try to open the OpenCOR bundle from the
    //          command line, then we would get an error message similar to:
    //              LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app.
    //          Fortunately, when double clicking on the OpenCOR bundle or
    //          opening it from the command line, a special argument in the form
    //          of -psn_0_1234567 is passed to OpenCOR, so we can use that to
    //          determine whether we need to force OpenCOR to be run in GUI mode
    //          or whether we first try the CLI version of OpenCOR, and then its
    //          GUI version, if needed...

#if defined(Q_OS_WIN)
    bool tryCliVersion = false;
#elif defined(Q_OS_LINUX)
    bool tryCliVersion = true;
#elif defined(Q_OS_MAC)
    bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5);
#else
    #error Unsupported platform
#endif

    // Run the CLI version of OpenCOR, if possible/needed

    if (tryCliVersion) {
        // Initialise the plugins path

        OpenCOR::initPluginsPath(pArgV[0]);

        // Create and initialise the CLI version of OpenCOR

        QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV);

        OpenCOR::initApplication(cliApp);

        // Try to run the CLI version of OpenCOR

        int res;

        bool runCliApplication = OpenCOR::cliApplication(cliApp, &res);

        OpenCOR::removeGlobalInstances();

        delete cliApp;

        if (runCliApplication)
            // OpenCOR was run as a CLI application, so leave

            return res;

        // Note: at this stage, we tried the CLI version of OpenCOR, but in the
        //       end we need to go for its GUI version, so start over but with
        //       the GUI version of OpenCOR this time...
    }

    // Make sure that we always use indirect rendering on Linux
    // Note: indeed, depending on which plugins are selected, OpenCOR may need
    //       LLVM. If that's the case, and in case the user's video card uses a
    //       driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there
    //       may be a conflict between the version of LLVM used by OpenCOR and
    //       the one used by the video card. One way to address this issue is by
    //       using indirect rendering...

#ifdef Q_OS_LINUX
    qputenv("LIBGL_ALWAYS_INDIRECT", "1");
#endif

    // Initialise the plugins path

    OpenCOR::initPluginsPath(pArgV[0]);

    // Create the GUI version of OpenCOR

    SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(),
                                                                                pArgC, pArgV);

    // Send a message (containing the arguments that were passed to this
    // instance of OpenCOR minus the first one since it corresponds to the full
    // path to our executable, which we are not interested in) to our 'official'
    // instance of OpenCOR, should there be one. If there is none, then just
    // carry on as normal, otherwise exit since we want only one instance of
    // OpenCOR at any given time

    QStringList appArguments = guiApp->arguments();

    appArguments.removeFirst();

    QString arguments = appArguments.join("|");

    if (guiApp->isRunning()) {
        guiApp->sendMessage(arguments);

        delete guiApp;

        return 0;
    }

    // Initialise the GUI version of OpenCOR

    QString appDate = QString();

    OpenCOR::initApplication(guiApp, &appDate);

    // Check whether we want to check for new versions at startup and, if so,
    // whether a new version of OpenCOR is available

    QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication);

#ifndef QT_DEBUG
    settings.beginGroup("CheckForUpdatesWindow");
        bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool();
        bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool();
    settings.endGroup();

    if (checkForUpdatesAtStartup) {
        OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate);

        checkForUpdatesEngine->check();

        if (   ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion())
            || (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) {
            // Retrieve the language to be used to show the check for updates
            // window

            const QString systemLocale = QLocale::system().name().left(2);

            QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString();

            if (locale.isEmpty())
                locale = systemLocale;

            QLocale::setDefault(QLocale(locale));

            QTranslator qtTranslator;
            QTranslator appTranslator;

            qtTranslator.load(":qt_"+locale);
            qApp->installTranslator(&qtTranslator);

            appTranslator.load(":app_"+locale);
            qApp->installTranslator(&appTranslator);

            // Show the check for updates window
            // Note: checkForUpdatesEngine gets deleted by
            //       checkForUpdatesWindow...

            OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine);

            settings.beginGroup(checkForUpdatesWindow.objectName());
                checkForUpdatesWindow.loadSettings(&settings);
            settings.endGroup();

            checkForUpdatesWindow.exec();

            settings.beginGroup(checkForUpdatesWindow.objectName());
                checkForUpdatesWindow.saveSettings(&settings);
            settings.endGroup();
        } else {
            delete checkForUpdatesEngine;
        }
    }
#endif

    // Initialise our colours by 'updating' them

    OpenCOR::updateColors();

    // Create and show our splash screen, if we are not in debug mode

#ifndef QT_DEBUG
    OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow();

    splashScreen->show();
#endif

    // Create our main window

    OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate);

    // Keep track of our main window (required by QtSingleApplication so that it
    // can do what it's supposed to be doing)

    guiApp->setActivationWindow(win);

    // Handle our arguments

    win->handleArguments(arguments);

    // Show our main window

    win->show();

    // By default, we can and should execute our application

    bool canExecuteAplication = true;

    // Close and delete our splash screen once our main window is visible, if we
    // are not in debug mode

#ifndef QT_DEBUG
    splashScreen->closeAndDeleteAfter(win);

    // Make sure that our main window is in the foreground, unless the user
    // decided to close our main window while we were showing our splash screen
    // Note: indeed, on Linux, to show our splash screen may result in our main
    //       window being shown in the background...

    if (!win->shuttingDown())
        win->showSelf();
    else
        canExecuteAplication = false;
#endif

    // Execute our application, if possible

    int res;

    if (canExecuteAplication)
        res = guiApp->exec();
    else
        res = 0;

    // Keep track of our application file and directory paths (in case we need
    // to restart OpenCOR)

    QString appFilePath = guiApp->applicationFilePath();
    QString appDirPath  = guiApp->applicationDirPath();

    // Delete our main window

    delete win;

    // We use QtWebKit, and QWebPage in particular, which results in some leak
    // messages being generated on Windows when leaving OpenCOR. This is because
    // an object cache is shared between all QWebPage instances. So to destroy a
    // QWebPage instance doesn't clear the cache, hence the leak messages.
    // However, those messages are 'only' warnings, so we can safely live with
    // them. Still, it doesn't look 'good', so we clear the memory caches, thus
    // avoiding those leak messages...
    // Note: the below must absolutely be done after calling guiApp->exec() and
    //       before deleting guiApp...

#ifdef Q_OS_WIN
    QWebSettings::clearMemoryCaches();
#endif

    // Remove all 'global' instances that were created and used during this
    // session

    OpenCOR::removeGlobalInstances();

    // Delete our application

    delete guiApp;

    // We are done with the execution of our application, so now the question is
    // whether we need to restart
    // Note: we do this here rather than 'within' the GUI because once we have
    //       launched a new instance of OpenCOR, we want this instance of
    //       OpenCOR to finish as soon as possible, which will be the case here
    //       since all that remains to be done is to return the result of the
    //       execution of our application...

    if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) {
        // We want to restart, so the question is whether we want a normal
        // restart or a clean one

        if (res == OpenCOR::CleanRestart)
            // We want a clean restart, so clear all the user settings (indeed,
            // this will ensure that the various windows are, for instance,
            // properly reset with regards to their dimensions)

            settings.clear();

        // Restart OpenCOR, but without providing any of the arguments that were
        // originally passed to us since we want to reset everything

        QProcess::startDetached(appFilePath, QStringList(), appDirPath);
    }

    // We are done running the GUI version of OpenCOR, so leave

    return res;
}

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>#include "EBSDMesh.h"

template<>
InputParameters validParams<EBSDMesh>()
{
  InputParameters params = validParams<GeneratedMesh>();
  params.addRequiredParam<FileName>("filename", "The name of the file containing the EBSD data");
  params.addParam<unsigned int>("uniform_refine", 0, "Number of coarsening levels available in adaptive mesh refinement.");

  // suppress parameters
  params.suppressParameter<MooseEnum>("dim");
  params.set<MooseEnum>("dim") = MooseEnum("1=1 2 3", "1");
  params.suppressParameter<int>("nx");
  params.suppressParameter<int>("ny");
  params.suppressParameter<int>("nz");
  params.suppressParameter<int>("xmin");
  params.suppressParameter<int>("ymin");
  params.suppressParameter<int>("zmin");
  params.suppressParameter<int>("xmax");
  params.suppressParameter<int>("ymax");
  params.suppressParameter<int>("zmax");

  return params;
}

EBSDMesh::EBSDMesh(const std::string & name, InputParameters parameters) :
    GeneratedMesh(name, parameters),
    _filename(getParam<FileName>("filename"))
{
  if (isParamValid("nx") || isParamValid("ny") || isParamValid("nz") ||
      isParamValid("xmin") || isParamValid("ymin") || isParamValid("zmin") ||
      isParamValid("xmax") || isParamValid("ymax") || isParamValid("zmax"))
    mooseWarning("Do not specify mesh geometry information, it is read from the EBSD file.");
}

EBSDMesh::~EBSDMesh()
{
}

void
EBSDMesh::readEBSDHeader()
{
  std::ifstream stream_in(_filename.c_str());

  if (!stream_in)
    mooseError("Can't open EBSD file: " << _filename);

  // Labels to look for in the header
  std::vector<std::string> labels;
  labels.push_back("X_step");
  labels.push_back("X_Dim");
  labels.push_back("Y_step");
  labels.push_back("Y_Dim");
  labels.push_back("Z_step");
  labels.push_back("Z_Dim");

  // Dimension variables to store once they are found in the header
  // X_step, X_Dim, Y_step, Y_Dim, Z_step, Z_Dim
  // We use Reals even though the Dim values should all be integers...
  std::vector<Real> label_vals(labels.size());

  std::string line;
  while (true)
  {
    // Try to a line form teh EBSD file
    std::getline(stream_in, line);

    if (stream_in)
    {
      // We need to process the comment lines that have:
      // X_step, X_Dim
      // Y_step, Y_Dim
      // Z_step, Z_Dim
      // in them.
      if (line.find("#") == 0)
      {
        // Process lines that start with a comment character (comments and meta data)

        for (unsigned i=0; i<labels.size(); ++i)
          if (line.find(labels[i]) != std::string::npos)
          {
            // Moose::out << "Found label " << labels[i] << ": " << line << std::endl;
            std::string dummy;
            std::istringstream iss(line);
            iss >> dummy >> dummy >> label_vals[i];

            // One label per line, break out of for loop over labels
            break;
          }
      }
      else
        break;
    }
    else
      mooseError("Error reading EBSD file header in EBSDMesh.");
  }

  // Copy stuff out of the label_vars array into class variables
  _geometry.d[0] = label_vals[0];
  _geometry.n[0] = label_vals[1];

  _geometry.d[1] = label_vals[2];
  _geometry.n[1] = label_vals[3];

  _geometry.d[2] = label_vals[4];
  _geometry.n[2] = label_vals[5];

  unsigned int dim;

  // determine mesh dimension
  for (dim = 3; dim > 0 && _geometry.n[dim-1] == 0; --dim);

  // check if the data has nonzero stepsizes
  for (unsigned i = 0; i < dim; ++i)
    if (_geometry.d[i] == 0.0)
      mooseError("Error reading header, EBSD data step size is zero.");

  if (dim == 0)
    mooseError("Error reading header, EBSD data is zero dimensional.");

  _geometry.dim = dim;
}

void
EBSDMesh::buildMesh()
{
  readEBSDHeader();

  unsigned int uniform_refine = getParam<unsigned int>("uniform_refine");
  _dim = (_geometry.dim == 1 ? "1" : (_geometry.dim == 2 ? "2" : "3"));

  unsigned int nr[3];
  nr[0] = _geometry.n[0];
  nr[1] = _geometry.n[1];
  nr[2] = _geometry.n[2];

  // set min/max box length
  InputParameters & params = parameters();
  params.set<Real>("xmin") = 0.0;
  params.set<Real>("xmax") = nr[0] * _geometry.d[0];
  params.set<Real>("ymin") = 0.0;
  params.set<Real>("ymax") = nr[1] * _geometry.d[1];
  params.set<Real>("zmin") = 0.0;
  params.set<Real>("zmax") = nr[2] * _geometry.d[2];

  // check if the requested uniform refine level is possible and determine initial grid size
  for (unsigned int i = 0; i < uniform_refine; ++i)
    for (unsigned int j = 0; j < _geometry.dim; ++j)
    {
      if (nr[j] % 2 != 0)
        mooseError("EBSDMesh error. Requested uniform_refine levels not possible.");
      nr[j] /= 2;
    }

  _nx = nr[0];
  _ny = nr[1];
  _nz = nr[2];

  GeneratedMesh::buildMesh();
}
<commit_msg>Simplify EBSD header read for unit test (#27)<commit_after>#include "EBSDMesh.h"

template<>
InputParameters validParams<EBSDMesh>()
{
  InputParameters params = validParams<GeneratedMesh>();
  params.addRequiredParam<FileName>("filename", "The name of the file containing the EBSD data");
  params.addParam<unsigned int>("uniform_refine", 0, "Number of coarsening levels available in adaptive mesh refinement.");

  // suppress parameters
  params.suppressParameter<MooseEnum>("dim");
  params.set<MooseEnum>("dim") = MooseEnum("1=1 2 3", "1");
  params.suppressParameter<int>("nx");
  params.suppressParameter<int>("ny");
  params.suppressParameter<int>("nz");
  params.suppressParameter<int>("xmin");
  params.suppressParameter<int>("ymin");
  params.suppressParameter<int>("zmin");
  params.suppressParameter<int>("xmax");
  params.suppressParameter<int>("ymax");
  params.suppressParameter<int>("zmax");

  return params;
}

EBSDMesh::EBSDMesh(const std::string & name, InputParameters parameters) :
    GeneratedMesh(name, parameters),
    _filename(getParam<FileName>("filename"))
{
  if (isParamValid("nx") || isParamValid("ny") || isParamValid("nz") ||
      isParamValid("xmin") || isParamValid("ymin") || isParamValid("zmin") ||
      isParamValid("xmax") || isParamValid("ymax") || isParamValid("zmax"))
    mooseWarning("Do not specify mesh geometry information, it is read from the EBSD file.");
}

EBSDMesh::~EBSDMesh()
{
}

void
EBSDMesh::readEBSDHeader()
{
  std::ifstream stream_in(_filename.c_str());

  if (!stream_in)
    mooseError("Can't open EBSD file: " << _filename);

  // Labels to look for in the header
  std::vector<std::string> labels;
  labels.push_back("X_step");
  labels.push_back("X_Dim");
  labels.push_back("Y_step");
  labels.push_back("Y_Dim");
  labels.push_back("Z_step");
  labels.push_back("Z_Dim");

  // Dimension variables to store once they are found in the header
  // X_step, X_Dim, Y_step, Y_Dim, Z_step, Z_Dim
  // We use Reals even though the Dim values should all be integers...
  std::vector<Real> label_vals(labels.size());

  std::string line;
  while (std::getline(stream_in, line))
  {
    // We need to process the comment lines that have:
    // X_step, X_Dim
    // Y_step, Y_Dim
    // Z_step, Z_Dim
    // in them.
    if (line.find("#") == 0)
    {
      // Process lines that start with a comment character (comments and meta data)

      for (unsigned i=0; i<labels.size(); ++i)
        if (line.find(labels[i]) != std::string::npos)
        {
          // Moose::out << "Found label " << labels[i] << ": " << line << std::endl;
          std::string dummy;
          std::istringstream iss(line);
          iss >> dummy >> dummy >> label_vals[i];

          // One label per line, break out of for loop over labels
          break;
        }
    }
    else
      // first non comment line marks the end of the header
      break;
  }

  // Copy stuff out of the label_vars array into class variables
  _geometry.d[0] = label_vals[0];
  _geometry.n[0] = label_vals[1];

  _geometry.d[1] = label_vals[2];
  _geometry.n[1] = label_vals[3];

  _geometry.d[2] = label_vals[4];
  _geometry.n[2] = label_vals[5];

  unsigned int dim;

  // determine mesh dimension
  for (dim = 3; dim > 0 && _geometry.n[dim-1] == 0; --dim);

  // check if the data has nonzero stepsizes
  for (unsigned i = 0; i < dim; ++i)
    if (_geometry.d[i] == 0.0)
      mooseError("Error reading header, EBSD data step size is zero.");

  if (dim == 0)
    mooseError("Error reading header, EBSD data is zero dimensional.");

  _geometry.dim = dim;
}

void
EBSDMesh::buildMesh()
{
  readEBSDHeader();

  unsigned int uniform_refine = getParam<unsigned int>("uniform_refine");
  _dim = (_geometry.dim == 1 ? "1" : (_geometry.dim == 2 ? "2" : "3"));

  unsigned int nr[3];
  nr[0] = _geometry.n[0];
  nr[1] = _geometry.n[1];
  nr[2] = _geometry.n[2];

  // set min/max box length
  InputParameters & params = parameters();
  params.set<Real>("xmin") = 0.0;
  params.set<Real>("xmax") = nr[0] * _geometry.d[0];
  params.set<Real>("ymin") = 0.0;
  params.set<Real>("ymax") = nr[1] * _geometry.d[1];
  params.set<Real>("zmin") = 0.0;
  params.set<Real>("zmax") = nr[2] * _geometry.d[2];

  // check if the requested uniform refine level is possible and determine initial grid size
  for (unsigned int i = 0; i < uniform_refine; ++i)
    for (unsigned int j = 0; j < _geometry.dim; ++j)
    {
      if (nr[j] % 2 != 0)
        mooseError("EBSDMesh error. Requested uniform_refine levels not possible.");
      nr[j] /= 2;
    }

  _nx = nr[0];
  _ny = nr[1];
  _nz = nr[2];

  GeneratedMesh::buildMesh();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <curses.h>
#include <cmath>
#include <algorithm>

#include "Connection.h"
#include "Configuration.h"

static std::vector<Connection> connections;

void offending() {
  std::vector<Process> processes;
  for (Connection& conn : connections) {
    if (!conn)
      break;

    std::vector<Process> process = conn.getOS()->getProcesses();
    for (Process& p : process)
      processes.push_back(p);
  }
  std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool {
    return a.time > b.time;
  });

  clear();
  refresh();

  int maxx, maxy;
  getmaxyx(stdscr, maxy, maxx);
  char action;
  do {
    clear();
    mvaddstr(0,0, "Host");
    mvaddstr(0,20, "Program");
    mvaddstr(0,40, "User");
    mvaddstr(0,50, "PID");
    mvaddstr(0,60, "CPU");
    mvaddstr(0,66, "MEM");
    mvaddstr(0,72, "Time");
    int row = 1;
    for (Process& p : processes) {
      mvaddnstr(row, 0, p.connection->getHostname().c_str(), 19);
      mvaddnstr(row, 20, p.command.c_str(), 19);
      mvaddnstr(row, 40, p.user.c_str(), 10);
      mvaddnstr(row, 50, std::to_string(p.pid).c_str(), 10);
      mvaddnstr(row, 60, std::to_string(p.cpu).c_str(), 5);
      mvaddnstr(row, 66, std::to_string(p.mem).c_str(), 5);
      mvaddnstr(row, 72, std::to_string(p.time / 60.0 / 60.0).c_str(), 8);

      row++;
      if (row == maxy)
        break;
    }
    refresh();
    action = getchar();
    if (action == 'c') {
      std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool {
        return a.cpu > b.cpu;
      });
    } else if (action == 'm') {
      std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool {
        return a.mem > b.mem;
      });
    }
  } while (action != 'q');

}

int main(int argc, char** argv) {
  Configuration conf;

  connections.reserve(conf.getHosts().size());

  for (std::string hostname : conf.getHosts()) {
    std::cout << hostname << std::endl;
    connections.emplace_back( hostname );
  }

  for (Connection& conn : connections) {
    if (!conn) {
      std::cerr << "Error!" << std::endl;
      continue;
    }
    OperatingSystem * os = conn.getOS();
    auto loads = os->getLoad();
    for (double load : loads) {
      std::cout << load << " ";
    }
    std::cout << std::endl;
  }

  setlocale(LC_ALL, "en_US.UTF-8");

  initscr();
  timeout(1000);
  char action;
  do {
    int row = 1;
    attron(A_DIM);
    mvaddstr(0, 0, "Hostname");
    mvaddstr(0,40, "| Load");
    mvaddstr(0,47, "| #usr");
    attroff(A_DIM);
    start_color();
    init_pair(1, COLOR_RED, COLOR_BLACK);
    std::string progress = "|/-\\";
    int prog = 0;

    attron(A_STANDOUT);
    mvaddch(0, 79, progress[prog]);
    attroff(A_STANDOUT);
    for (Connection & conn : connections) {
      mvaddstr(row, 1, conn.getHostname().c_str());

      mvaddch(row, 40, '|');
      if (!conn) {
        attron(A_BLINK | COLOR_PAIR(1));
        addstr(" OFFLINE ");
        attroff(A_BLINK | COLOR_PAIR(1));
        continue;
      }

      std::array<double,3> load = conn.getOS()->getLoad();
      std::array<double,5> interp;
      interp[0] = load[0];
      interp[1] = (load[0] + load[1])/2;
      interp[2] = load[1];
      interp[3] = (load[1] + load[2])/2;
      interp[4] = load[2];
      cchar_t t;
      t.attr = 0;
      t.chars[1] = L'\0';
      for (double load : interp) {
        int loadScaled = (int)( std::log(load)/std::log(10) * 4 + 6 );
        loadScaled = loadScaled > 7 ? 7 : loadScaled;
        loadScaled = loadScaled < 0 ? 0 : loadScaled;
        t.chars[0] = L'\u2581'+ loadScaled ;
        add_wch( &t );
      }

      mvaddstr(row, 47, "| ");
      addstr( std::to_string( conn.getOS()->getNUsers() ).c_str() );

      row++;
    }
    refresh();
    row = 1;

    prog++;
    if (prog == 4)
      prog = 0;

    action = getch();
    if (action == 'o') {
      offending();
      clear();
    }
  } while (action != 'q');

  endwin();

  return 0;
}<commit_msg>Changed to days.<commit_after>#include <iostream>
#include <curses.h>
#include <cmath>
#include <algorithm>

#include "Connection.h"
#include "Configuration.h"

static std::vector<Connection> connections;

void offending() {
  std::vector<Process> processes;
  for (Connection& conn : connections) {
    if (!conn)
      break;

    std::vector<Process> process = conn.getOS()->getProcesses();
    for (Process& p : process)
      processes.push_back(p);
  }
  std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool {
    return a.time > b.time;
  });

  clear();
  refresh();

  int maxx, maxy;
  getmaxyx(stdscr, maxy, maxx);
  char action;
  do {
    clear();
    mvaddstr(0,0, "Host");
    mvaddstr(0,20, "Program");
    mvaddstr(0,40, "User");
    mvaddstr(0,50, "PID");
    mvaddstr(0,60, "CPU");
    mvaddstr(0,66, "MEM");
    mvaddstr(0,72, "Time");
    int row = 1;
    for (Process& p : processes) {
      mvaddnstr(row, 0, p.connection->getHostname().c_str(), 19);
      mvaddnstr(row, 20, p.command.c_str(), 19);
      mvaddnstr(row, 40, p.user.c_str(), 10);
      mvaddnstr(row, 50, std::to_string(p.pid).c_str(), 10);
      mvaddnstr(row, 60, std::to_string(p.cpu).c_str(), 5);
      mvaddnstr(row, 66, std::to_string(p.mem).c_str(), 5);
      mvaddnstr(row, 72, std::to_string(p.time / (60.0 * 60.0 * 24.0)).c_str(), 8);

      row++;
      if (row == maxy)
        break;
    }
    refresh();
    action = getchar();
    if (action == 'c') {
      std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool {
        return a.cpu > b.cpu;
      });
    } else if (action == 'm') {
      std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool {
        return a.mem > b.mem;
      });
    }
  } while (action != 'q');

}

int main(int argc, char** argv) {
  Configuration conf;

  connections.reserve(conf.getHosts().size());

  for (std::string hostname : conf.getHosts()) {
    std::cout << hostname << std::endl;
    connections.emplace_back( hostname );
  }

  for (Connection& conn : connections) {
    if (!conn) {
      std::cerr << "Error!" << std::endl;
      continue;
    }
    OperatingSystem * os = conn.getOS();
    auto loads = os->getLoad();
    for (double load : loads) {
      std::cout << load << " ";
    }
    std::cout << std::endl;
  }

  setlocale(LC_ALL, "en_US.UTF-8");

  initscr();
  timeout(1000);
  char action;
  do {
    int row = 1;
    attron(A_DIM);
    mvaddstr(0, 0, "Hostname");
    mvaddstr(0,40, "| Load");
    mvaddstr(0,47, "| #usr");
    attroff(A_DIM);
    start_color();
    init_pair(1, COLOR_RED, COLOR_BLACK);
    std::string progress = "|/-\\";
    int prog = 0;

    attron(A_STANDOUT);
    mvaddch(0, 79, progress[prog]);
    attroff(A_STANDOUT);
    for (Connection & conn : connections) {
      mvaddstr(row, 1, conn.getHostname().c_str());

      mvaddch(row, 40, '|');
      if (!conn) {
        attron(A_BLINK | COLOR_PAIR(1));
        addstr(" OFFLINE ");
        attroff(A_BLINK | COLOR_PAIR(1));
        continue;
      }

      std::array<double,3> load = conn.getOS()->getLoad();
      std::array<double,5> interp;
      interp[0] = load[0];
      interp[1] = (load[0] + load[1])/2;
      interp[2] = load[1];
      interp[3] = (load[1] + load[2])/2;
      interp[4] = load[2];
      cchar_t t;
      t.attr = 0;
      t.chars[1] = L'\0';
      for (double load : interp) {
        int loadScaled = (int)( std::log(load)/std::log(10) * 4 + 6 );
        loadScaled = loadScaled > 7 ? 7 : loadScaled;
        loadScaled = loadScaled < 0 ? 0 : loadScaled;
        t.chars[0] = L'\u2581'+ loadScaled ;
        add_wch( &t );
      }

      mvaddstr(row, 47, "| ");
      addstr( std::to_string( conn.getOS()->getNUsers() ).c_str() );

      row++;
    }
    refresh();
    row = 1;

    prog++;
    if (prog == 4)
      prog = 0;

    action = getch();
    if (action == 'o') {
      offending();
      clear();
    }
  } while (action != 'q');

  endwin();

  return 0;
}<|endoftext|>


<commit_before>#include "project.h"
#include "main_window.h"

#include <QDebug>

#include <QApplication>
#include <QFileInfo>
#include <QDir>
#include <QVideoWidget>
#include <QMediaPlayer>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName(APP_NAME);
    a.setApplicationDisplayName(APP_NAME);
    a.setOrganizationName(COPYRIGHT_HOLDER);
    a.setOrganizationDomain(COPYRIGHT_DOMAIN);

    a.setWindowIcon(QIcon(":/logo/images/logo_512.png"));

    MainWindow w;

    QString path;
    if(argc<2) {
        QTextStream(stdout) << "Usage: "
                  << QFileInfo( QCoreApplication::applicationFilePath() ).fileName()
                  << " path_to_dir_or_file"
                  << endl;
    }
    else {
        path = QString(argv[1]);
        QFileInfo fileinfo(path);
        if(!fileinfo.exists())
        {
            qDebug() << "File does not exist: " << path;
            return 1;
        }

        qDebug() << path;
        if(fileinfo.isDir())
            w.loadFolder(fileinfo.filePath());
        else
            w.loadFolder(fileinfo.absoluteDir().absolutePath(), fileinfo.fileName());
    }
    w.show();
    return a.exec();
}
<commit_msg>Made window show centered in primary monitor<commit_after>#include "project.h"
#include "main_window.h"

#include <QDebug>

#include <QApplication>
#include <QFileInfo>
#include <QDir>
#include <QVideoWidget>
#include <QMediaPlayer>
#include <QDesktopWidget>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName(APP_NAME);
    a.setApplicationDisplayName(APP_NAME);
    a.setOrganizationName(COPYRIGHT_HOLDER);
    a.setOrganizationDomain(COPYRIGHT_DOMAIN);

    a.setWindowIcon(QIcon(":/logo/images/logo_512.png"));

    MainWindow w;

    QString path;
    if(argc<2) {
        QTextStream(stdout) << "Usage: "
                  << QFileInfo( QCoreApplication::applicationFilePath() ).fileName()
                  << " path_to_dir_or_file"
                  << endl;
    }
    else {
        path = QString(argv[1]);
        QFileInfo fileinfo(path);
        if(!fileinfo.exists())
        {
            qDebug() << "File does not exist: " << path;
            return 1;
        }

        qDebug() << path;
        if(fileinfo.isDir())
            w.loadFolder(fileinfo.filePath());
        else
            w.loadFolder(fileinfo.absoluteDir().absolutePath(), fileinfo.fileName());
    }
    w.move(QApplication::desktop()->screenGeometry().center() - w.rect().center());
    w.show();
    return a.exec();
}
<|endoftext|>


<commit_before>#include "image_writer.h"
#include "heatmap_writer.h"
#include "json_writer.h"
#include "logger.h"
#include "parser.h"
#include "logger.h"

#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>

#include <float.h>

using namespace wotreplay;
namespace po = boost::program_options;

void show_help(int argc, const char *argv[], po::options_description &desc) {
    std::stringstream help_message;
    help_message << desc << "\n";
    logger.write(help_message.str());
}

float distance(const std::tuple<float, float, float> &left, const std::tuple<float, float, float> &right) {
    float delta_x = std::get<0>(left) - std::get<0>(right);
    float delta_y = std::get<1>(left) - std::get<1>(right);
    float delta_z = std::get<2>(left) - std::get<2>(right);
    // distance in xy plane
    float dist1 = std::sqrt(delta_x*delta_x + delta_y*delta_y);
    return std::sqrt(dist1*dist1 + delta_z*delta_z);
}

static bool is_not_empty(const packet_t &packet) {
    // list of default properties with no special meaning
    std::set<property_t> standard_properties = { property_t::clock, property_t::player_id, property_t::type, property_t::sub_type };
    auto properties = packet.get_properties();
    for (int i = 0; i < properties.size(); ++i) {
        property_t property = static_cast<property_t>(i);
        // packet has property, but can not be found in default properties
        if (properties[i] &&
            standard_properties.find(property) == standard_properties.end()) {
            return true;
        }
    }
    return false;
}

int create_minimaps(const po::variables_map &vm, const std::string &output, bool debug) {
    if ( vm.count("output") == 0 ) {
        logger.write(wotreplay::log_level_t::error, "parameter output is required to use this mode");
        return -EXIT_FAILURE;
    }

    boost::format file_name_format("%1%/%2%_%3%_%4%.png");

    image_writer_t writer;
    for (const auto &arena_entry : get_arenas()) {
        const arena_t &arena = arena_entry.second;
        for (const auto &configuration_entry : arena.configurations) {
            for (int team_id : { 0, 1 }) {
                const std::string game_mode = configuration_entry.first;
                writer.init(arena, game_mode);
                writer.set_recorder_team(team_id);
                writer.set_use_fixed_teamcolors(false);
                std::string file_name = (file_name_format % output % arena.name % game_mode % team_id).str();
                std::ofstream os(file_name, std::ios::binary);
                writer.finish();
                writer.write(os);
            }
        }
    }

    return EXIT_SUCCESS;
}

int parse_replay(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) {
    if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) {
        logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n");
        return -EXIT_FAILURE;
    }

    std::ifstream in(input, std::ios::binary);
    if (!in) {
        logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input);
        std::exit(0);
    }

    parser_t parser;
    game_t game;

    parser.set_debug(debug);
    parser.load_data();
    parser.parse(in, game);

    std::unique_ptr<writer_t> writer;

    if (type == "png") {
        writer = std::unique_ptr<writer_t>(new image_writer_t());
        auto &image_writer = dynamic_cast<image_writer_t&>(*writer);
        image_writer.set_show_self(true);
        image_writer.set_use_fixed_teamcolors(false);
    } else if (type == "json") {
        writer = std::unique_ptr<writer_t>(new json_writer_t());
        if (vm.count("supress-empty")) {
            writer->set_filter(&is_not_empty);
        }
    } else if (type == "heatmap") {
        writer = std::unique_ptr<writer_t>(new heatmap_writer_t());
    } else {
        logger.writef(log_level_t::error, "Invalid output type (%1%), supported types: png and json.\n", type);
        return -EXIT_FAILURE;
    }

    writer->init(game.get_arena(), game.get_game_mode());
    writer->update(game);
    writer->finish();

    std::ostream *out;

    if (vm.count("output") > 0) {
        out = new std::ofstream(output, std::ios::binary);
        if (!out) {
            logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input);
            std::exit(0);
        }
    } else {
        out = &std::cout;
    }

    writer->write(*out);

    if (dynamic_cast<std::ofstream*>(out)) {
        dynamic_cast<std::ofstream*>(out)->close();
        delete out;
    }

    return EXIT_SUCCESS;
}

int main(int argc, const char * argv[]) {
    po::options_description desc("Allowed options");

    std::string type, output, input, root;

    desc.add_options()
        ("type"  , po::value(&type), "select output type")
        ("output", po::value(&output), "target file")
        ("input" , po::value(&input), "input file")
        ("root"  , po::value(&root), "set root directory")
        ("help"  , "produce help message")
        ("debug"   , "enable parser debugging")
        ("supress-empty", "supress empty packets from json output")
        ("create-minimaps", "create all empty minimaps in output directory")
        ("parse", "parse a replay file")
        ("quiet", "supress diagnostic messages");

    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    } catch (std::exception &e) {
        show_help(argc, argv, desc);
        std::exit(-1);
    } catch (...) {
        logger.write(log_level_t::error, "Unknown error.\n");
        std::exit(-1);
    }

    if (vm.count("help") > 0) {
        show_help(argc, argv, desc);
        std::exit(0);
    }

    if (vm.count("root") >  0
            && chdir(root.c_str()) != 0) {
        logger.writef(log_level_t::error, "Cannot change working directory to: %1%\n", root);
        std::exit(0);
    }

    bool debug = vm.count("debug") > 0;
    if (debug) {
        logger.set_log_level(log_level_t::debug);
    } else if (vm.count("quiet") > 0) {
        logger.set_log_level(log_level_t::none);
    } else {
        logger.set_log_level(log_level_t::warning);
    }

    int exit_code;
    if (vm.count("parse") > 0) {
        // parse
        exit_code = parse_replay(vm, input, output, type, debug);
    } else if (vm.count("create-minimaps") > 0) {
        // create all minimaps
        exit_code =  create_minimaps(vm, output, debug);
    } else {
        logger.write(wotreplay::log_level_t::error, "Error: no mode specified\n");
        exit_code = -EXIT_FAILURE;
    }

    if (exit_code < 0) {
        show_help(argc, argv, desc);
    }

    return exit_code;
}<commit_msg>Improve error message for failing to open input file<commit_after>#include "image_writer.h"
#include "heatmap_writer.h"
#include "json_writer.h"
#include "logger.h"
#include "parser.h"
#include "logger.h"

#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>

#include <float.h>

using namespace wotreplay;
namespace po = boost::program_options;

void show_help(int argc, const char *argv[], po::options_description &desc) {
    std::stringstream help_message;
    help_message << desc << "\n";
    logger.write(help_message.str());
}

float distance(const std::tuple<float, float, float> &left, const std::tuple<float, float, float> &right) {
    float delta_x = std::get<0>(left) - std::get<0>(right);
    float delta_y = std::get<1>(left) - std::get<1>(right);
    float delta_z = std::get<2>(left) - std::get<2>(right);
    // distance in xy plane
    float dist1 = std::sqrt(delta_x*delta_x + delta_y*delta_y);
    return std::sqrt(dist1*dist1 + delta_z*delta_z);
}

static bool is_not_empty(const packet_t &packet) {
    // list of default properties with no special meaning
    std::set<property_t> standard_properties = { property_t::clock, property_t::player_id, property_t::type, property_t::sub_type };
    auto properties = packet.get_properties();
    for (int i = 0; i < properties.size(); ++i) {
        property_t property = static_cast<property_t>(i);
        // packet has property, but can not be found in default properties
        if (properties[i] &&
            standard_properties.find(property) == standard_properties.end()) {
            return true;
        }
    }
    return false;
}

int create_minimaps(const po::variables_map &vm, const std::string &output, bool debug) {
    if ( vm.count("output") == 0 ) {
        logger.write(wotreplay::log_level_t::error, "parameter output is required to use this mode");
        return -EXIT_FAILURE;
    }

    boost::format file_name_format("%1%/%2%_%3%_%4%.png");

    image_writer_t writer;
    for (const auto &arena_entry : get_arenas()) {
        const arena_t &arena = arena_entry.second;
        for (const auto &configuration_entry : arena.configurations) {
            for (int team_id : { 0, 1 }) {
                const std::string game_mode = configuration_entry.first;
                writer.init(arena, game_mode);
                writer.set_recorder_team(team_id);
                writer.set_use_fixed_teamcolors(false);
                std::string file_name = (file_name_format % output % arena.name % game_mode % team_id).str();
                std::ofstream os(file_name, std::ios::binary);
                writer.finish();
                writer.write(os);
            }
        }
    }

    return EXIT_SUCCESS;
}

int parse_replay(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) {
    if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) {
        logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n");
        return -EXIT_FAILURE;
    }

    std::ifstream in(input, std::ios::binary);
    if (!in) {
        logger.writef(log_level_t::error, "Failed to open file: %1%\n", input);
        std::exit(0);
    }

    parser_t parser;
    game_t game;

    parser.set_debug(debug);
    parser.load_data();
    parser.parse(in, game);

    std::unique_ptr<writer_t> writer;

    if (type == "png") {
        writer = std::unique_ptr<writer_t>(new image_writer_t());
        auto &image_writer = dynamic_cast<image_writer_t&>(*writer);
        image_writer.set_show_self(true);
        image_writer.set_use_fixed_teamcolors(false);
    } else if (type == "json") {
        writer = std::unique_ptr<writer_t>(new json_writer_t());
        if (vm.count("supress-empty")) {
            writer->set_filter(&is_not_empty);
        }
    } else if (type == "heatmap") {
        writer = std::unique_ptr<writer_t>(new heatmap_writer_t());
    } else {
        logger.writef(log_level_t::error, "Invalid output type (%1%), supported types: png and json.\n", type);
        return -EXIT_FAILURE;
    }

    writer->init(game.get_arena(), game.get_game_mode());
    writer->update(game);
    writer->finish();

    std::ostream *out;

    if (vm.count("output") > 0) {
        out = new std::ofstream(output, std::ios::binary);
        if (!out) {
            logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input);
            std::exit(0);
        }
    } else {
        out = &std::cout;
    }

    writer->write(*out);

    if (dynamic_cast<std::ofstream*>(out)) {
        dynamic_cast<std::ofstream*>(out)->close();
        delete out;
    }

    return EXIT_SUCCESS;
}

int main(int argc, const char * argv[]) {
    po::options_description desc("Allowed options");

    std::string type, output, input, root;

    desc.add_options()
        ("type"  , po::value(&type), "select output type")
        ("output", po::value(&output), "target file")
        ("input" , po::value(&input), "input file")
        ("root"  , po::value(&root), "set root directory")
        ("help"  , "produce help message")
        ("debug"   , "enable parser debugging")
        ("supress-empty", "supress empty packets from json output")
        ("create-minimaps", "create all empty minimaps in output directory")
        ("parse", "parse a replay file")
        ("quiet", "supress diagnostic messages");

    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    } catch (std::exception &e) {
        show_help(argc, argv, desc);
        std::exit(-1);
    } catch (...) {
        logger.write(log_level_t::error, "Unknown error.\n");
        std::exit(-1);
    }

    if (vm.count("help") > 0) {
        show_help(argc, argv, desc);
        std::exit(0);
    }

    if (vm.count("root") >  0
            && chdir(root.c_str()) != 0) {
        logger.writef(log_level_t::error, "Cannot change working directory to: %1%\n", root);
        std::exit(0);
    }

    bool debug = vm.count("debug") > 0;
    if (debug) {
        logger.set_log_level(log_level_t::debug);
    } else if (vm.count("quiet") > 0) {
        logger.set_log_level(log_level_t::none);
    } else {
        logger.set_log_level(log_level_t::warning);
    }

    int exit_code;
    if (vm.count("parse") > 0) {
        // parse
        exit_code = parse_replay(vm, input, output, type, debug);
    } else if (vm.count("create-minimaps") > 0) {
        // create all minimaps
        exit_code =  create_minimaps(vm, output, debug);
    } else {
        logger.write(wotreplay::log_level_t::error, "Error: no mode specified\n");
        exit_code = -EXIT_FAILURE;
    }

    if (exit_code < 0) {
        show_help(argc, argv, desc);
    }

    return exit_code;
}<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <memory>
#include <sstream>
#include <thread>

#include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "geom/point.h"
#include "geom/rectangle.h"
#include "geom/vector.h"
#include "image/image.h"
#include "model/obj.h"
#include "node/group/simple.h"
#include "node/instance.h"
#include "node/solid/disc.h"
#include "node/solid/infinite_plane.h"
#include "node/solid/sphere.h"
#include "node/solid/triangle.h"
#include "renderer/parallel/parallel.h"
#include "renderer/serial/serial.h"
#include "renderer/settings.h"
#include "supersampling/random.h"
#include "world/world.h"

using namespace Svit;

int
main (void)
{
	Settings settings;
	settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.max_thread_count = std::thread::hardware_concurrency();
	settings.tile_size = Vector2i(10, 10);
	settings.max_sample_count = 1;
	settings.adaptive_sample_step = 10;

	CosineDebuggerEngine engine;
	SerialRenderer renderer;
	RandomSuperSampling super_sampling(true);

	SimpleGroup scene;
	Sphere sphere(Point3(0.0, 0.0, 0.0), 1.0);
	PerspectiveCamera camera(
		Point3(0.0, 0.75, -5.5),
		Vector3(0.0, 0.0, 1.0),
		Vector3(0.0, 1.0, 0.0),
		Rectangle(Point2i(0, 0), Vector2i(128, 72)).get_aspect_ratio(),
		M_PI/2.0f);

	ObjModel cow;
	cow.load("cow.obj");

	SimpleGroup cow_group;
	cow.add_to_group(cow_group);

	scene.add(&sphere);
	scene.add(&cow_group);

	World world;
	world.scene = &scene;
	world.camera = &camera;

	Image image = renderer.render(world, settings, engine, super_sampling);
	image.write_png(std::string("cow.png"));

	return 0;
}

<commit_msg>WIP main.cpp<commit_after>#include <cmath>
#include <iostream>
#include <memory>
#include <sstream>
#include <thread>

#include "camera/perspective.h"
#include "engine/cosine_debugger.h"
#include "geom/point.h"
#include "geom/rectangle.h"
#include "geom/vector.h"
#include "image/image.h"
#include "model/obj.h"
#include "node/group/simple.h"
#include "node/group/kdtree/kdtree.h"
#include "node/group/kdtree/axis_selector/round_robin.h"
#include "node/group/kdtree/split_strategy/centre.h"
#include "node/group/kdtree/kdtree.h"
#include "node/instance.h"
#include "node/solid/disc.h"
#include "node/solid/infinite_plane.h"
#include "node/solid/sphere.h"
#include "node/solid/triangle.h"
#include "renderer/parallel/parallel.h"
#include "renderer/serial/serial.h"
#include "renderer/settings.h"
#include "supersampling/random.h"
#include "world/world.h"

using namespace Svit;

int
main (void)
{
	Settings settings;
	settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720));
	settings.max_thread_count = std::thread::hardware_concurrency();
	settings.tile_size = Vector2i(10, 10);
	settings.max_sample_count = 1;
	settings.adaptive_sample_step = 10;

	CosineDebuggerEngine engine;
	SerialRenderer renderer;
	RandomSuperSampling super_sampling(true);

	SimpleGroup scene;
	Sphere sphere(Point3(0.0, 0.0, 0.0), 1.0);
	PerspectiveCamera camera(
		Point3(0.0, 0.75, -5.5),
		Vector3(0.0, 0.0, 1.0),
		Vector3(0.0, 1.0, 0.0),
		Rectangle(Point2i(0, 0), Vector2i(128, 72)).get_aspect_ratio(),
		M_PI/2.0f);

	ObjModel cow_model;
	cow_model.load("simplecow.obj");

	KDTree cow(new RoundRobinAxisSelector(), new CentreSplitStrategy(), 20, 3);
	cow_model.add_to_group(cow);
	cow.finish();

	cow.root.bounding_box.max.dump("cow bb min");
	cow.root.bounding_box.min.dump("cow bb max");

	/* KDTree spheres(new RoundRobinAxisSelector(), new CentreSplitStrategy(), 20, 100); */
	/* for (unsigned int i = 0; i < 6; i++) */
	/* 	spheres.add(new Sphere(Point3((float)i/5.0f*10.0f, 0.0f, 0.0f), 1.0f)); */

	/* spheres.finish(); */
	/* scene.add(&spheres); */

	scene.add(&cow);
	/* scene.add(&sphere); */

	World world;
	world.scene = &scene;
	world.camera = &camera;

	Image image = renderer.render(world, settings, engine, super_sampling);
	image.write_png(std::string("coww.png"));

	return 0;
}

<|endoftext|>


<commit_before>#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "plugins/pluginmanager.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "tools/logger.h"
#include "widgets/querytextedit.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QSplashScreen>

int main(int argc, char *argv[]) {
  QApplication::setApplicationName("dbmaster");
  QApplication::setApplicationVersion("0.10.0");
  QApplication::setOrganizationDomain("dbmaster.org");
  QApplication a(argc, argv);
  a.setWindowIcon(QIcon(":/img/dbmaster.png"));

  QSplashScreen splash(QPixmap(":/img/splash.png"));
  splash.show();

  Logger *logger = new Logger;

  // Loading translations
  splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);

  QTranslator translator;
  // getting the current locale
  QString lang = QLocale::system().name().left(2);
  QString transdir = ".";
#if defined(Q_WS_X11)
  // for *nix
  transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif

#if defined(Q_OS_MAC)
  transdir = "DbMaster.app/Contents/MacOS";
#endif

  QString path;
  /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
   * dev, on le charge, sinon il est dans le répertoire d'installation. */
  path = QString("../../dbmaster/tr/%1.qm").arg(lang);
  if (!QFile::exists(path))
    path = transdir.append("/%1.qm").arg(lang);
  qDebug() << QString("Loaded %1 translation file").arg(path);
  translator.load(path);
  a.installTranslator(&translator);

  path = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#if defined (Q_WS_WIN)
  path = QDir::currentPath();
#endif

  QTranslator qtTranslator;
  qtTranslator.load("qt_" + lang, path);
  a.installTranslator(&qtTranslator);

  // Ajout des plugins
  splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom);
  PluginManager::init();

  splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);

  IconManager::init();
  DbManager::init();
  Config::init();
  QueryTextEdit::reloadCompleter();

  MainWindow *w = new MainWindow();
  w->show();
  splash.finish(w);

  if (a.arguments().size() >= 2) {
    for (int i=1; i<a.arguments().size(); i++) {
      w->openQuery(a.arguments()[i]);
    }
  }

  return a.exec();
}
<commit_msg>Version number<commit_after>#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "plugins/pluginmanager.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "tools/logger.h"
#include "widgets/querytextedit.h"

#include <QtWidgets/QApplication>
#include <QtWidgets/QSplashScreen>

int main(int argc, char *argv[]) {
  QApplication::setApplicationName("dbmaster");
  QApplication::setApplicationVersion("0.11.0");
  QApplication::setOrganizationDomain("dbmaster.org");
  QApplication a(argc, argv);
  a.setWindowIcon(QIcon(":/img/dbmaster.png"));

  QSplashScreen splash(QPixmap(":/img/splash.png"));
  splash.show();

  Logger *logger = new Logger;

  // Loading translations
  splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);

  QTranslator translator;
  // getting the current locale
  QString lang = QLocale::system().name().left(2);
  QString transdir = ".";
#if defined(Q_WS_X11)
  // for *nix
  transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif

#if defined(Q_OS_MAC)
  transdir = "DbMaster.app/Contents/MacOS";
#endif

  QString path;
  /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
   * dev, on le charge, sinon il est dans le répertoire d'installation. */
  path = QString("../../dbmaster/tr/%1.qm").arg(lang);
  if (!QFile::exists(path))
    path = transdir.append("/%1.qm").arg(lang);
  qDebug() << QString("Loaded %1 translation file").arg(path);
  translator.load(path);
  a.installTranslator(&translator);

  path = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#if defined (Q_WS_WIN)
  path = QDir::currentPath();
#endif

  QTranslator qtTranslator;
  qtTranslator.load("qt_" + lang, path);
  a.installTranslator(&qtTranslator);

  // Ajout des plugins
  splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom);
  PluginManager::init();

  splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);

  IconManager::init();
  DbManager::init();
  Config::init();
  QueryTextEdit::reloadCompleter();

  MainWindow *w = new MainWindow();
  w->show();
  splash.finish(w);

  if (a.arguments().size() >= 2) {
    for (int i=1; i<a.arguments().size(); i++) {
      w->openQuery(a.arguments()[i]);
    }
  }

  return a.exec();
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <em_chip.h>
#include <em_cmu.h>
#include <em_dbg.h>
#include <em_device.h>
#include <em_emu.h>
#include <em_gpio.h>
#include <gsl/span>
#include <em_system.h>

#include <FreeRTOS.h>
#include <FreeRTOSConfig.h>
#include <task.h>

#include "SwoEndpoint/SwoEndpoint.h"
#include "adcs/adcs.h"
#include "base/ecc.h"
#include "base/os.h"
#include "dmadrv.h"
#include "eps/eps.h"
#include "fs/fs.h"
#include "i2c/i2c.h"
#include "io_map.h"
#include "leuart/leuart.h"
#include "logger/logger.h"
#include "mission.h"
#include "obc.h"
#include "storage/nand.h"
#include "storage/nand_driver.h"
#include "storage/storage.h"
#include "swo/swo.h"
#include "system.h"
#include "terminal.h"

#include "gpio/gpio.h"
#include "leuart/leuart.h"
#include "power_eps/power_eps.h"

using services::time::TimeProvider;
using namespace std::chrono_literals;

OBC Main;
mission::ObcMission Mission(Main.timeProvider, Main.antennaDriver, false);

const int __attribute__((used)) uxTopUsedPriority = configMAX_PRIORITIES;

extern "C" void vApplicationStackOverflowHook(xTaskHandle* pxTask, signed char* pcTaskName)
{
    UNREFERENCED_PARAMETER(pxTask);
    UNREFERENCED_PARAMETER(pcTaskName);
}

extern "C" void vApplicationIdleHook(void)
{
    EMU_EnterEM1();
}

void I2C0_IRQHandler(void)
{
    Main.Hardware.I2C.Peripherals[0].Driver.IRQHandler();
}

void I2C1_IRQHandler(void)
{
    Main.Hardware.I2C.Peripherals[1].Driver.IRQHandler();
}

static void BlinkLed0(void* param)
{
    UNREFERENCED_PARAMETER(param);

    while (1)
    {
        Main.Hardware.Pins.Led0.Toggle();
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

static void SmartWaitTask(void* param)
{
    UNREFERENCED_PARAMETER(param);

    LOG(LOG_LEVEL_DEBUG, "Wait start");

    while (1)
    {
        Main.timeProvider.LongDelay(10min);
        LOG(LOG_LEVEL_DEBUG, "After wait");
    }
}

static void InitSwoEndpoint(void)
{
    void* swoEndpointHandle = SwoEndpointInit();
    const bool result = LogAddEndpoint(SwoGetEndpoint(swoEndpointHandle), swoEndpointHandle, LOG_LEVEL_TRACE);
    if (!result)
    {
        SwoPutsOnChannel(0, "Unable to attach swo endpoint to logger. ");
    }
}

static void ClearState(OBC* obc)
{
    if (obc->Hardware.Pins.SysClear.Input() == false)
    {
        LOG(LOG_LEVEL_WARNING, "Clearing state on startup");

        if (OS_RESULT_FAILED(obc->Storage.ClearStorage()))
        {
            LOG(LOG_LEVEL_ERROR, "Clearing state failed");
        }

        LOG(LOG_LEVEL_INFO, "All files removed");
    }
}

static void SetupAntennas(void)
{
    AntennaMiniportInitialize(&Main.antennaMiniport);
    AntennaDriverInitialize(&Main.antennaDriver, &Main.antennaMiniport, &Main.Hardware.I2C.Buses.Bus, &Main.Hardware.I2C.Buses.Payload);
}

static void ObcInitTask(void* param)
{
    auto obc = static_cast<OBC*>(param);

    obc->PostStartInitialization();

    ClearState(obc);

    if (!obc->timeProvider.Initialize(nullptr, nullptr))
    {
        LOG(LOG_LEVEL_ERROR, "Unable to initialize persistent timer. ");
    }

    if (OS_RESULT_FAILED(Main.antennaDriver.HardReset(&Main.antennaDriver)))
    {
        LOG(LOG_LEVEL_ERROR, "Unable to reset both antenna controllers. ");
    }

    if (!obc->Communication.CommDriver.Restart())
    {
        LOG(LOG_LEVEL_ERROR, "Unable to restart comm");
    }

    InitializeADCS(&obc->adcs);

    Mission.Initialize();

    System::CreateTask(SmartWaitTask, "SmartWait", 512, NULL, TaskPriority::P1, NULL);

    LOG(LOG_LEVEL_INFO, "Intialized");
    Main.initialized = true;

    System::SuspendTask(NULL);
}

void SetupHardware(void)
{
    CMU_ClockEnable(cmuClock_GPIO, true);
    CMU_ClockEnable(cmuClock_DMA, true);

    CMU_ClockSelectSet(cmuClock_LFA, cmuSelect_HFCLKLE);
    CMU_ClockSelectSet(cmuClock_LFB, cmuSelect_HFCLKLE);
}

extern "C" void __libc_init_array(void);

int main(void)
{
    memset(&Main, 0, sizeof(Main));

    __libc_init_array();

    CHIP_Init();

    SetupHardware();

    SwoEnable();

    LogInit(LOG_LEVEL_DEBUG);
    InitSwoEndpoint();

    DMADRV_Init();

    LeuartLineIOInit(&Main.IO);

    EpsInit(&Main.Hardware.I2C.Fallback);

    EPSPowerControlInitialize(&Main.PowerControlInterface);

    Main.Initialize();

    InitializeTerminal();

    SwoPutsOnChannel(0, "Hello I'm PW-SAT2 OBC\n");

    SetupAntennas();

    Main.Hardware.Pins.Led0.High();
    Main.Hardware.Pins.Led1.High();

    System::CreateTask(BlinkLed0, "Blink0", 512, NULL, TaskPriority::P1, NULL);
    System::CreateTask(ObcInitTask, "Init", 3_KB, &Main, TaskPriority::Highest, &Main.initTask);

    System::RunScheduler();

    Main.Hardware.Pins.Led0.Toggle();

    return 0;
}
<commit_msg>Implementing BURTC Interrupt Handler<commit_after>#include <cstdio>
#include <cstring>
#include <em_chip.h>
#include <em_cmu.h>
#include <em_dbg.h>
#include <em_device.h>
#include <em_emu.h>
#include <em_gpio.h>
#include <gsl/span>
#include <em_system.h>

#include <FreeRTOS.h>
#include <FreeRTOSConfig.h>
#include <task.h>

#include "SwoEndpoint/SwoEndpoint.h"
#include "adcs/adcs.h"
#include "base/ecc.h"
#include "base/os.h"
#include "dmadrv.h"
#include "em_burtc.h"
#include "eps/eps.h"
#include "fs/fs.h"
#include "gpio/gpio.h"
#include "i2c/i2c.h"
#include "io_map.h"
#include "leuart/leuart.h"
#include "leuart/leuart.h"
#include "logger/logger.h"
#include "mission.h"
#include "obc.h"
#include "power_eps/power_eps.h"
#include "storage/nand.h"
#include "storage/nand_driver.h"
#include "storage/storage.h"
#include "swo/swo.h"
#include "system.h"
#include "terminal.h"

using services::time::TimeProvider;
using namespace std::chrono_literals;

OBC Main;
mission::ObcMission Mission(Main.timeProvider, Main.antennaDriver, false);

const int __attribute__((used)) uxTopUsedPriority = configMAX_PRIORITIES;

extern "C" void vApplicationStackOverflowHook(xTaskHandle* pxTask, signed char* pcTaskName)
{
    UNREFERENCED_PARAMETER(pxTask);
    UNREFERENCED_PARAMETER(pcTaskName);
}

extern "C" void vApplicationIdleHook(void)
{
    EMU_EnterEM1();
}

void I2C0_IRQHandler(void)
{
    Main.Hardware.I2C.Peripherals[0].Driver.IRQHandler();
}

void I2C1_IRQHandler(void)
{
    Main.Hardware.I2C.Peripherals[1].Driver.IRQHandler();
}

OSSemaphoreHandle timerSemaphore;
void BURTC_IRQHandler(void)
{
    System::GiveSemaphore(timerSemaphore);
}

void configBURTC(void)
{
    BURTC_Init_TypeDef burtcInit = BURTC_INIT_DEFAULT;

    burtcInit.mode = burtcModeEM4;
    burtcInit.clkSel = burtcClkSelLFRCO;
    burtcInit.clkDiv = 3;

    BURTC_CompareSet(0, 205);        /* Set top value for comparator */
    BURTC_IntEnable(BURTC_IF_COMP0); /* Enable compare interrupt flag */
    NVIC_EnableIRQ(BURTC_IRQn);
    BURTC_Init(&burtcInit);
}

static void UpdateTimeProvider(void* param)
{
    UNREFERENCED_PARAMETER(param);

    while (1)
    {
        System::TakeSemaphore(timerSemaphore, 50ms);
        Main.timeProvider.AdvanceTime(50ms);
    }
}

void configTimer(void)
{
    configBURTC();

    timerSemaphore = System::CreateBinarySemaphore();
    System::CreateTask(UpdateTimeProvider, "UpdateTimeProvider", 512, NULL, TaskPriority::P1, NULL);
}

static void BlinkLed0(void* param)
{
    UNREFERENCED_PARAMETER(param);

    while (1)
    {
        Main.Hardware.Pins.Led0.Toggle();
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

static void SmartWaitTask(void* param)
{
    UNREFERENCED_PARAMETER(param);

    LOG(LOG_LEVEL_DEBUG, "Wait start");

    while (1)
    {
        Main.timeProvider.LongDelay(10min);
        LOG(LOG_LEVEL_DEBUG, "After wait");
    }
}

static void InitSwoEndpoint(void)
{
    void* swoEndpointHandle = SwoEndpointInit();
    const bool result = LogAddEndpoint(SwoGetEndpoint(swoEndpointHandle), swoEndpointHandle, LOG_LEVEL_TRACE);
    if (!result)
    {
        SwoPutsOnChannel(0, "Unable to attach swo endpoint to logger. ");
    }
}

static void ClearState(OBC* obc)
{
    if (obc->Hardware.Pins.SysClear.Input() == false)
    {
        LOG(LOG_LEVEL_WARNING, "Clearing state on startup");

        if (OS_RESULT_FAILED(obc->Storage.ClearStorage()))
        {
            LOG(LOG_LEVEL_ERROR, "Clearing state failed");
        }

        LOG(LOG_LEVEL_INFO, "All files removed");
    }
}

static void SetupAntennas(void)
{
    AntennaMiniportInitialize(&Main.antennaMiniport);
    AntennaDriverInitialize(&Main.antennaDriver, &Main.antennaMiniport, &Main.Hardware.I2C.Buses.Bus, &Main.Hardware.I2C.Buses.Payload);
}

static void ObcInitTask(void* param)
{
    auto obc = static_cast<OBC*>(param);

    obc->PostStartInitialization();

    ClearState(obc);

    if (!obc->timeProvider.Initialize(nullptr, nullptr))
    {
        LOG(LOG_LEVEL_ERROR, "Unable to initialize persistent timer. ");
    }

    if (OS_RESULT_FAILED(Main.antennaDriver.HardReset(&Main.antennaDriver)))
    {
        LOG(LOG_LEVEL_ERROR, "Unable to reset both antenna controllers. ");
    }

    if (!obc->Communication.CommDriver.Restart())
    {
        LOG(LOG_LEVEL_ERROR, "Unable to restart comm");
    }

    InitializeADCS(&obc->adcs);

    Mission.Initialize();

    System::CreateTask(SmartWaitTask, "SmartWait", 512, NULL, TaskPriority::P1, NULL);

    LOG(LOG_LEVEL_INFO, "Intialized");
    Main.initialized = true;

    System::SuspendTask(NULL);
}

void SetupHardware(void)
{
    CMU_ClockEnable(cmuClock_GPIO, true);
    CMU_ClockEnable(cmuClock_DMA, true);

    CMU_ClockSelectSet(cmuClock_LFA, cmuSelect_HFCLKLE);
    CMU_ClockSelectSet(cmuClock_LFB, cmuSelect_HFCLKLE);
}

extern "C" void __libc_init_array(void);

int main(void)
{
    memset(&Main, 0, sizeof(Main));

    __libc_init_array();

    CHIP_Init();

    SetupHardware();

    SwoEnable();

    LogInit(LOG_LEVEL_DEBUG);
    InitSwoEndpoint();

    DMADRV_Init();

    LeuartLineIOInit(&Main.IO);

    EpsInit(&Main.Hardware.I2C.Fallback);

    EPSPowerControlInitialize(&Main.PowerControlInterface);

    Main.Initialize();

    InitializeTerminal();

    SwoPutsOnChannel(0, "Hello I'm PW-SAT2 OBC\n");

    SetupAntennas();

    Main.Hardware.Pins.Led0.High();
    Main.Hardware.Pins.Led1.High();

    configTimer();

    System::CreateTask(BlinkLed0, "Blink0", 512, NULL, TaskPriority::P1, NULL);
    System::CreateTask(ObcInitTask, "Init", 3_KB, &Main, TaskPriority::Highest, &Main.initTask);

    System::RunScheduler();

    Main.Hardware.Pins.Led0.Toggle();

    return 0;
}
<|endoftext|>


<commit_before>/*

This file is part of VROOM.

Copyright (c) 2015-2021, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include <fstream>
#include <iostream>
#include <sstream>
#ifndef _WIN32
#include <unistd.h>
#endif

#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif

#include "../include/cxxopts/include/cxxopts.hpp"
#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "utils/helpers.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"

int main(int argc, char** argv) {
  vroom::io::CLArgs cl_args;
  std::string host_arg;
  std::string port_arg;
  std::string router_arg;
  std::string limit_arg;
  std::string nb_threads_arg;
  std::vector<std::string> heuristic_params_arg;

  // clang-format off
  cxxopts::Options options(
    "vroom",
    "VROOM Copyright (C) 2015-2021, Julien Coupey\n"
    "Version: " + vroom::get_version() + "\n"
    "A command-line utility to solve complex vehicle routing problems."
    );

  options
    .set_width(80)
    .set_tab_expansion()
    .add_options("main_group")
    ("h,help", "Print this help message.")
    ("v,version", "Print the version of this software.")
    ("a,host", "The host for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":0.0.0.0'", cxxopts::value<std::string>(host_arg)->default_value("car:0.0.0.0"))
    ("c,choose-eta", "Choose ETA for custom routes and report violations.", cxxopts::value<bool>(cl_args.check)->default_value("false"))
    ("g,geometry", "Add detailed route geometry and indicators", cxxopts::value<bool>(cl_args.geometry)->default_value("false"))
    ("i,input-file", "Read input from 'input-file' rather than from stdin", cxxopts::value<std::string>(cl_args.input_file))
    ("l,limit", "Stop solving process after 'limit' seconds", cxxopts::value<std::string>(limit_arg)->default_value(""))
    ("o,output", "Output file name", cxxopts::value<std::string>(cl_args.output_file))
    ("p,port", "The host port for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":5000'", cxxopts::value<std::string>(port_arg)->default_value("car:5000"))
    ("r,router", "osrm, libosrm, ors or valhalla", cxxopts::value<std::string>(router_arg)->default_value("osrm"))
    ("t,threads", "Number of threads to use", cxxopts::value<unsigned>(cl_args.nb_threads)->default_value("4"))
    ("x,explore", "Exploration level to use (0..5)", cxxopts::value<unsigned>(cl_args.exploration_level)->default_value("5"));

  // we don't want to print debug args on --help
  options.add_options("debug_group")
    ("e,heuristic-param", "Heuristic parameter, useful for debugging", cxxopts::value<std::vector<std::string>>(heuristic_params_arg));
  // clang-format on

  auto parsed_args = options.parse(argc, argv);

  if (parsed_args.count("help")) {
    std::cout << options.help({"main_group"}) << "\n";
    exit(0);
  }

  if (parsed_args.count("version")) {
    std::cout << "vroom " << vroom::get_version() << "\n";
    exit(0);
  }

  // parse and update some params
  vroom::io::update_host(cl_args.servers, host_arg);
  vroom::io::update_port(cl_args.servers, port_arg);
  if (!limit_arg.empty()) {
    // Internally timeout is in milliseconds.
    cl_args.timeout = 1000 * std::stof(limit_arg);
  }
  cl_args.exploration_level =
    std::min(cl_args.exploration_level, cl_args.max_exploration_level);

  // Determine routing engine (defaults to ROUTER::OSRM).
  if (router_arg == "libosrm") {
    cl_args.router = vroom::ROUTER::LIBOSRM;
  } else if (router_arg == "ors") {
    cl_args.router = vroom::ROUTER::ORS;
  } else if (router_arg == "valhalla") {
    cl_args.router = vroom::ROUTER::VALHALLA;
  } else if (!router_arg.empty() and router_arg != "osrm") {
    auto error_code = vroom::utils::get_code(vroom::ERROR::INPUT);
    std::string message = "Invalid routing engine: " + router_arg + ".";
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }

  try {
    // Force heuristic parameters from the command-line, useful for
    // debugging.
    std::transform(heuristic_params_arg.begin(),
                   heuristic_params_arg.end(),
                   std::back_inserter(cl_args.h_params),
                   [](const auto& str_param) {
                     return vroom::utils::str_to_heuristic_param(str_param);
                   });
  } catch (const vroom::Exception& e) {
    auto error_code = vroom::utils::get_code(e.error);
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }

  // Read input problem
  if (optind == argc) {
    std::stringstream buffer;
    if (cl_args.input_file.empty()) {
      // Getting input from stdin.
      buffer << std::cin.rdbuf();
    } else {
      // Getting input from provided file.
      std::ifstream ifs(cl_args.input_file);
      buffer << ifs.rdbuf();
    }
    cl_args.input = buffer.str();
  } else {
    // Getting input from command-line.
    cl_args.input = argv[optind];
  }

  try {
    // Build problem.
    vroom::Input problem_instance = vroom::io::parse(cl_args);

    vroom::Solution sol = (cl_args.check)
                            ? problem_instance.check(cl_args.nb_threads)
                            : problem_instance.solve(cl_args.exploration_level,
                                                     cl_args.nb_threads,
                                                     cl_args.timeout,
                                                     cl_args.h_params);

    // Write solution.
    vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
  } catch (const vroom::Exception& e) {
    auto error_code = vroom::utils::get_code(e.error);
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }
#if USE_LIBOSRM
  catch (const osrm::exception& e) {
    // In case of an unhandled routing error.
    auto error_code = vroom::utils::get_code(vroom::ERROR::ROUTING);
    auto message = "Routing problem: " + std::string(e.what());
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }
#endif
  catch (const std::exception& e) {
    // In case of an unhandled internal error.
    auto error_code = vroom::utils::get_code(vroom::ERROR::INTERNAL);
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({error_code, e.what()},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }

  return 0;
}
<commit_msg>add positional arg; parse stdin, from file or from inline json; hide debug arg(s) from help output<commit_after>/*

This file is part of VROOM.

Copyright (c) 2015-2021, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include <fstream>
#include <iostream>
#include <sstream>
#ifndef _WIN32
#include <unistd.h>
#endif

#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif

#include "../include/cxxopts/include/cxxopts.hpp"
#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "utils/helpers.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"

int main(int argc, char** argv) {
  vroom::io::CLArgs cl_args;
  std::string host_arg;
  std::string port_arg;
  std::string router_arg;
  std::string limit_arg;
  std::string nb_threads_arg;
  std::vector<std::string> heuristic_params_arg;

  // clang-format off
  cxxopts::Options options(
    "vroom",
    "VROOM Copyright (C) 2015-2021, Julien Coupey\n"
    "Version: " + vroom::get_version() + "\n\n"
    "A command-line utility to solve complex vehicle routing problems.\n"
    );

  options
    .set_width(80)
    .set_tab_expansion()
    .add_options("main_group")
    ("h,help", "Print this help message.")
    ("v,version", "Print the version of this software.")
    ("a,host", "The host for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":0.0.0.0'", cxxopts::value<std::string>(host_arg)->default_value("car:0.0.0.0"))
    ("c,choose-eta", "Choose ETA for custom routes and report violations.", cxxopts::value<bool>(cl_args.check)->default_value("false"))
    ("g,geometry", "Add detailed route geometry and indicators", cxxopts::value<bool>(cl_args.geometry)->default_value("false"))
    ("i,input-file", "Read input from 'input-file' rather than from stdin", cxxopts::value<std::string>(cl_args.input_file))
    ("l,limit", "Stop solving process after 'limit' seconds", cxxopts::value<std::string>(limit_arg)->default_value(""))
    ("o,output", "Output file name", cxxopts::value<std::string>(cl_args.output_file))
    ("p,port", "The host port for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":5000'", cxxopts::value<std::string>(port_arg)->default_value("car:5000"))
    ("r,router", "osrm, libosrm, ors or valhalla", cxxopts::value<std::string>(router_arg)->default_value("osrm"))
    ("t,threads", "Number of threads to use", cxxopts::value<unsigned>(cl_args.nb_threads)->default_value("4"))
    ("x,explore", "Exploration level to use (0..5)", cxxopts::value<unsigned>(cl_args.exploration_level)->default_value("5"))
    ("input", "optional input positional arg", cxxopts::value<std::string>(cl_args.input));

  // we don't want to print debug args on --help
  options.add_options("debug_group")
    ("e,heuristic-param", "Heuristic parameter", cxxopts::value<std::vector<std::string>>(heuristic_params_arg));
  // clang-format on

  options.parse_positional({"input"});
  options.positional_help("OPTIONAL INLINE JSON");
  auto parsed_args = options.parse(argc, argv);

  if (parsed_args.count("help")) {
    std::cout << options.help({"main_group"}) << "\n";
    exit(0);
  }

  if (parsed_args.count("version")) {
    std::cout << "vroom " << vroom::get_version() << "\n";
    exit(0);
  }

  // parse and update some params
  vroom::io::update_host(cl_args.servers, host_arg);
  vroom::io::update_port(cl_args.servers, port_arg);
  if (!limit_arg.empty()) {
    // Internally timeout is in milliseconds.
    cl_args.timeout = 1000 * std::stof(limit_arg);
  }
  cl_args.exploration_level =
    std::min(cl_args.exploration_level, cl_args.max_exploration_level);

  // Determine routing engine (defaults to ROUTER::OSRM).
  if (router_arg == "libosrm") {
    cl_args.router = vroom::ROUTER::LIBOSRM;
  } else if (router_arg == "ors") {
    cl_args.router = vroom::ROUTER::ORS;
  } else if (router_arg == "valhalla") {
    cl_args.router = vroom::ROUTER::VALHALLA;
  } else if (!router_arg.empty() and router_arg != "osrm") {
    auto error_code = vroom::utils::get_code(vroom::ERROR::INPUT);
    std::string message = "Invalid routing engine: " + router_arg + ".";
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }

  try {
    // Force heuristic parameters from the command-line, useful for
    // debugging.
    std::transform(heuristic_params_arg.begin(),
                   heuristic_params_arg.end(),
                   std::back_inserter(cl_args.h_params),
                   [](const auto& str_param) {
                     return vroom::utils::str_to_heuristic_param(str_param);
                   });
  } catch (const vroom::Exception& e) {
    auto error_code = vroom::utils::get_code(e.error);
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }

  // Read input problem
  if (cl_args.input.empty()) {
    std::stringstream buffer;
    if (!cl_args.input_file.empty()) {
      std::ifstream ifs(cl_args.input_file);
      buffer << ifs.rdbuf();
    } else {
      buffer << std::cin.rdbuf();
    }
    cl_args.input = buffer.str();
  }

  try {
    // Build problem.
    vroom::Input problem_instance = vroom::io::parse(cl_args);

    vroom::Solution sol = (cl_args.check)
                            ? problem_instance.check(cl_args.nb_threads)
                            : problem_instance.solve(cl_args.exploration_level,
                                                     cl_args.nb_threads,
                                                     cl_args.timeout,
                                                     cl_args.h_params);

    // Write solution.
    vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
  } catch (const vroom::Exception& e) {
    auto error_code = vroom::utils::get_code(e.error);
    std::cerr << "[Error] " << e.message << std::endl;
    vroom::io::write_to_json({error_code, e.message},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }
#if USE_LIBOSRM
  catch (const osrm::exception& e) {
    // In case of an unhandled routing error.
    auto error_code = vroom::utils::get_code(vroom::ERROR::ROUTING);
    auto message = "Routing problem: " + std::string(e.what());
    std::cerr << "[Error] " << message << std::endl;
    vroom::io::write_to_json({error_code, message}, false, cl_args.output_file);
    exit(error_code);
  }
#endif
  catch (const std::exception& e) {
    // In case of an unhandled internal error.
    auto error_code = vroom::utils::get_code(vroom::ERROR::INTERNAL);
    std::cerr << "[Error] " << e.what() << std::endl;
    vroom::io::write_to_json({error_code, e.what()},
                             false,
                             cl_args.output_file);
    exit(error_code);
  }

  return 0;
}
<|endoftext|>


<commit_before>void asignacion1() { // OMIT
  int a,b;   // a:?,  b:?
  a = 10;    // a:10, b:?
  b = 4;     // a:10, b:4
  a = b;     // a:4,  b:4
  b = 7;     // a:4,  b:7
  printf("a:%d\tb:%d\n",a,b);
} // OMIT

void asignacion2() { // OMIT
  int m,n,p;    // m:?, n:?, p:?
  // p = 5;     // m:?, n:?, p:5
  // n = p;     // m:?, n:5, p:5
  // m = n;     // m:5, n:5, p:5
  m = n = p = 5;
} // OMIT

void asignacion3() { // OMIT
} // OMIT
<commit_msg>c++ operators/asignacion.cpp - tercer ejemplo<commit_after>void asignacion1() { // OMIT
  int a,b;   // a:?,  b:?
  a = 10;    // a:10, b:?
  b = 4;     // a:10, b:4
  a = b;     // a:4,  b:4
  b = 7;     // a:4,  b:7
  printf("a:%d\tb:%d\n",a,b);
} // OMIT

void asignacion2() { // OMIT
  int m,n,p;    // m:?, n:?, p:?
  // p = 5;     // m:?, n:?, p:5
  // n = p;     // m:?, n:5, p:5
  // m = n;     // m:5, n:5, p:5
  m = n = p = 5;
  printf("m:%d\tn:%d\tp:%d\n",m,n,p);
} // OMIT

void asignacion3() { // OMIT
  int x,y;        // x:?, y:?
  // x = 5;       // x:5, y:?
  // y = 2 + x;   // x:5, y:7
  y = 2 + (x = 5);
  printf("x:%d\ty:%d\n",x,y);
} // OMIT
<|endoftext|>