<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "inout.hh"
#include "utilities.hh"
#include "strings.hh"
#include "thread.hh"
#include <unistd.h>
#include <cstring>

namespace Rapicorn {

// export debug_handler() symbol for debugging stacktraces and gdb
extern void debug_handler (const char, const String&, const String&, const char *key = NULL) __attribute__ ((noinline));

void
debug_assert (const char *file_path, const int line, const char *message)
{
  debug_handler ('C', string_printf ("%s:%d", file_path, line), string_printf ("assertion failed: %s", message));
}

void
debug_fassert (const char *file_path, const int line, const char *message)
{
  debug_handler ('F', string_printf ("%s:%d", file_path, line), string_printf ("assertion failed: %s", message));
  ::abort();
}

void
debug_fatal (const char *file_path, const int line, const char *format, ...)
{
  va_list vargs;
  va_start (vargs, format);
  String msg = string_vprintf (format, vargs);
  va_end (vargs);
  debug_handler ('F', string_printf ("%s:%d", file_path, line), msg);
  ::abort();
}

void
debug_critical (const char *file_path, const int line, const char *format, ...)
{
  va_list vargs;
  va_start (vargs, format);
  String msg = string_vprintf (format, vargs);
  va_end (vargs);
  debug_handler ('C', string_printf ("%s:%d", file_path, line), msg);
}

void
debug_fixit (const char *file_path, const int line, const char *format, ...)
{
  va_list vargs;
  va_start (vargs, format);
  String msg = string_vprintf (format, vargs);
  va_end (vargs);
  debug_handler ('X', string_printf ("%s:%d", file_path, line), msg);
}

// == envkey_ functions ==
static int
cstring_option_sense (const char *option_string, const char *option, char *value, const int offset = 0)
{
  const char *haystack = option_string + offset;
  const char *p = strstr (haystack, option);
  if (p)                                // found possible match
    {
      const int l = strlen (option);
      if (p == haystack || (p > haystack && (p[-1] == ':' || p[-1] == ';')))
        {                               // start matches (word boundary)
          const char *d1 = strchr (p + l, ':'), *d2 = strchr (p + l, ';'), *d = MAX (d1, d2);
          d = d ? d : p + l + strlen (p + l);
          bool match = true;
          if (p[l] == '=')              // found value
            {
              const char *v = p + l + 1;
              strncpy (value, v, d - v);
            }
          else if (p[l] == 0 || p[l] == ':' || p[l] == ';')
            {                           // option present
              strcpy (value, "1");
            }
          else
            match = false;              // no match
          if (match)
            {
              const int pos = d - option_string;
              if (d[0])
                {
                  const int next = cstring_option_sense (option_string, option, value, pos);
                  if (next >= 0)        // found overriding match
                    return next;
                }
              return pos;               // this match is last match
            }
        }                               // unmatched, keep searching
      return cstring_option_sense (option_string, option, value, p + l - option_string);
    }
  return -1;                            // not present in haystack
}

static bool
fast_envkey_check (const char *option_string, const char *key)
{
  const int l = max (size_t (64), strlen (option_string) + 1);
  char kvalue[l];
  strcpy (kvalue, "0");
  const int keypos = !key ? -1 : cstring_option_sense (option_string, key, kvalue);
  char avalue[l];
  strcpy (avalue, "0");
  const int allpos = cstring_option_sense (option_string, "all", avalue);
  if (keypos > allpos)
    return cstring_to_bool (kvalue, false);
  else if (allpos > keypos)
    return cstring_to_bool (avalue, false);
  else
    return false;       // neither key nor "all" found
}

/** Check whether a flipper (feature toggle) is enabled.
 * This function first checks the environment variable @a env_var for @a key, if it is present or if
 * @a with_all_toggle is true and 'all' is present, the function returns @a true, otherwise @a false.
 * The @a cachep argument may point to a caching variable which is reset to 0 if @a env_var is
 * empty (i.e. no features can be enabled), so the caching variable can be used to prevent
 * unneccessary future envkey_flipper_check() calls.
 */
bool
envkey_flipper_check (const char *env_var, const char *key, bool with_all_toggle, volatile bool *cachep)
{
  if (env_var)          // require explicit activation
    {
      const char *val = getenv (env_var);
      if (!val || val[0] == 0)
        {
          if (cachep)
            *cachep = 0;
        }
      else if (key && fast_envkey_check (val, key))
        return true;
    }
  return false;
}

/** Check whether to print debugging message.
 * This function first checks the environment variable @a env_var for @a key, if the key is present,
 * 'all' is present or if @a env_var is NULL, the debugging message will be printed.
 * A NULL @a key checks for general debugging, it's equivalent to passing "debug" as @a key.
 * The @a cachep argument may point to a caching variable which is reset to 0 if @a env_var is
 * empty (so no debugging is enabled), so the caching variable can be used to prevent unneccessary
 * future debugging calls, e.g. to envkey_debug_message().
 */
bool
envkey_debug_check (const char *env_var, const char *key, volatile bool *cachep)
{
  if (!env_var)
    return true;        // unconditional debugging
  return envkey_flipper_check (env_var, key ? key : "debug", true, cachep);
}

/** Conditionally print debugging message.
 * This function first checks whether debugging is enabled via envkey_debug_check() and returns if not.
 * The arguments @a file_path and @a line are used to denote the debugging message source location,
 * @a format and @a va_args are formatting the message analogously to vprintf().
 */
void
envkey_debug_message (const char *env_var, const char *key, const char *file_path, const int line,
                      const char *format, va_list va_args, volatile bool *cachep)
{
  if (!envkey_debug_check (env_var, key, cachep))
    return;
  String msg = string_vprintf (format, va_args);
  debug_handler ('D', string_printf ("%s:%d", file_path, line), msg, key);
}

// == AnsiColors ==
namespace AnsiColors {

const char*
color_code (Colors acolor)
{
  switch (acolor)
    {
    default: ;
    case NONE:             return "";
    case RESET:            return "\033[0m";
    case BOLD:             return "\033[1m";
    case BOLD_OFF:         return "\033[22m";
    case ITALICS:          return "\033[3m";
    case ITALICS_OFF:      return "\033[23m";
    case UNDERLINE:        return "\033[4m";
    case UNDERLINE_OFF:    return "\033[24m";
    case INVERSE:          return "\033[7m";
    case INVERSE_OFF:      return "\033[27m";
    case STRIKETHROUGH:    return "\033[9m";
    case STRIKETHROUGH_OFF:return "\033[29m";
    case FG_BLACK:         return "\033[30m";
    case FG_RED:           return "\033[31m";
    case FG_GREEN:         return "\033[32m";
    case FG_YELLOW:        return "\033[33m";
    case FG_BLUE:          return "\033[34m";
    case FG_MAGENTA:       return "\033[35m";
    case FG_CYAN:          return "\033[36m";
    case FG_WHITE:         return "\033[37m";
    case FG_DEFAULT:       return "\033[39m";
    case BG_BLACK:         return "\033[40m";
    case BG_RED:           return "\033[41m";
    case BG_GREEN:         return "\033[42m";
    case BG_YELLOW:        return "\033[43m";
    case BG_BLUE:          return "\033[44m";
    case BG_MAGENTA:       return "\033[45m";
    case BG_CYAN:          return "\033[46m";
    case BG_WHITE:         return "\033[47m";
    case BG_DEFAULT:       return "\033[49m";
    }
}

struct EnvKey {
  String var, key;
  EnvKey() : var (""), key ("") {}
};

static constexpr int     UNCHECKED = 2;
static Atomic<int>       colorize_stdout = UNCHECKED;   // cache stdout colorization check
static Exclusive<EnvKey> env_key;

void
color_envkey (const String &env_var, const String &key)
{
  EnvKey ekey;
  ekey.var = env_var;
  ekey.key = key;
  env_key = ekey; // Atomic access
  colorize_stdout = UNCHECKED; // Atomic access
}

bool
colorize_tty (int fd)
{
  EnvKey ekey = env_key;
  const char *ev = getenv (ekey.var.c_str());
  if (ev)
    {
      if (ekey.key.empty() == false)
        {
          const int l = max (size_t (64), strlen (ev) + 1);
          char value[l];
          strcpy (value, "auto");
          cstring_option_sense (ev, ekey.key.c_str(), value);
          if (strncasecmp (value, "always", 6) == 0)
            return true;
          else if (strncasecmp (value, "never", 5) == 0)
            return false;
          else if (strncasecmp (value, "auto", 4) != 0)
            return string_to_bool (value, 0);
        }
      else if (strncasecmp (ev, "always", 6) == 0)
        return true;
      else if (strncasecmp (ev, "never", 5) == 0)
        return false;
      else if (strncasecmp (ev, "auto", 4) != 0)
        return string_to_bool (ev, 0);
    }
  // found 'auto', sense arbitrary fd
  if (fd >= 3)
    return isatty (fd);
  // sense stdin/stdout/stderr
  if (isatty (1) && isatty (2))
    {
      char *term = getenv ("TERM");
      if (term && strcmp (term, "dumb") != 0)
        return true;
    }
  return false;
}

const char*
color (Colors acolor)
{
  if (colorize_stdout == UNCHECKED)
    colorize_stdout = colorize_tty();
  if (!colorize_stdout)
    return "";
  return color_code (acolor);
}

} // AnsiColors

} // Rapicorn
<commit_msg>RCORE: inout.cc: slight reformatting<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "inout.hh"
#include "utilities.hh"
#include "strings.hh"
#include "thread.hh"
#include <unistd.h>
#include <cstring>

namespace Rapicorn {

// FIXME: remove // export debug_handler() symbol for debugging stacktraces and gdb
extern void debug_handler (const char, const String&, const String&, const char *key = NULL) __attribute__ ((noinline));

// == envkey_ functions ==
static int
cstring_option_sense (const char *option_string, const char *option, char *value, const int offset = 0)
{
  const char *haystack = option_string + offset;
  const char *p = strstr (haystack, option);
  if (p)                                // found possible match
    {
      const int l = strlen (option);
      if (p == haystack || (p > haystack && (p[-1] == ':' || p[-1] == ';')))
        {                               // start matches (word boundary)
          const char *d1 = strchr (p + l, ':'), *d2 = strchr (p + l, ';'), *d = MAX (d1, d2);
          d = d ? d : p + l + strlen (p + l);
          bool match = true;
          if (p[l] == '=')              // found value
            {
              const char *v = p + l + 1;
              strncpy (value, v, d - v);
            }
          else if (p[l] == 0 || p[l] == ':' || p[l] == ';')
            {                           // option present
              strcpy (value, "1");
            }
          else
            match = false;              // no match
          if (match)
            {
              const int pos = d - option_string;
              if (d[0])
                {
                  const int next = cstring_option_sense (option_string, option, value, pos);
                  if (next >= 0)        // found overriding match
                    return next;
                }
              return pos;               // this match is last match
            }
        }                               // unmatched, keep searching
      return cstring_option_sense (option_string, option, value, p + l - option_string);
    }
  return -1;                            // not present in haystack
}

static bool
fast_envkey_check (const char *option_string, const char *key)
{
  const int l = max (size_t (64), strlen (option_string) + 1);
  char kvalue[l];
  strcpy (kvalue, "0");
  const int keypos = !key ? -1 : cstring_option_sense (option_string, key, kvalue);
  char avalue[l];
  strcpy (avalue, "0");
  const int allpos = cstring_option_sense (option_string, "all", avalue);
  if (keypos > allpos)
    return cstring_to_bool (kvalue, false);
  else if (allpos > keypos)
    return cstring_to_bool (avalue, false);
  else
    return false;       // neither key nor "all" found
}

/** Check whether a flipper (feature toggle) is enabled.
 * This function first checks the environment variable @a env_var for @a key, if it is present or if
 * @a with_all_toggle is true and 'all' is present, the function returns @a true, otherwise @a false.
 * The @a cachep argument may point to a caching variable which is reset to 0 if @a env_var is
 * empty (i.e. no features can be enabled), so the caching variable can be used to prevent
 * unneccessary future envkey_flipper_check() calls.
 */
bool
envkey_flipper_check (const char *env_var, const char *key, bool with_all_toggle, volatile bool *cachep)
{
  if (env_var)          // require explicit activation
    {
      const char *val = getenv (env_var);
      if (!val || val[0] == 0)
        {
          if (cachep)
            *cachep = 0;
        }
      else if (key && fast_envkey_check (val, key))
        return true;
    }
  return false;
}

/** Check whether to print debugging message.
 * This function first checks the environment variable @a env_var for @a key, if the key is present,
 * 'all' is present or if @a env_var is NULL, the debugging message will be printed.
 * A NULL @a key checks for general debugging, it's equivalent to passing "debug" as @a key.
 * The @a cachep argument may point to a caching variable which is reset to 0 if @a env_var is
 * empty (so no debugging is enabled), so the caching variable can be used to prevent unneccessary
 * future debugging calls, e.g. to envkey_debug_message().
 */
bool
envkey_debug_check (const char *env_var, const char *key, volatile bool *cachep)
{
  if (!env_var)
    return true;        // unconditional debugging
  return envkey_flipper_check (env_var, key ? key : "debug", true, cachep);
}

/** Conditionally print debugging message.
 * This function first checks whether debugging is enabled via envkey_debug_check() and returns if not.
 * The arguments @a file_path and @a line are used to denote the debugging message source location,
 * @a format and @a va_args are formatting the message analogously to vprintf().
 */
void
envkey_debug_message (const char *env_var, const char *key, const char *file_path, const int line,
                      const char *format, va_list va_args, volatile bool *cachep)
{
  if (!envkey_debug_check (env_var, key, cachep))
    return;
  String msg = string_vprintf (format, va_args);
  debug_handler ('D', string_printf ("%s:%d", file_path, line), msg, key);
}

// == debug_* functions ==
void
debug_assert (const char *file_path, const int line, const char *message)
{
  debug_handler ('C', string_printf ("%s:%d", file_path, line), string_printf ("assertion failed: %s", message));
}

void
debug_fassert (const char *file_path, const int line, const char *message)
{
  debug_handler ('F', string_printf ("%s:%d", file_path, line), string_printf ("assertion failed: %s", message));
  ::abort();
}

void
debug_fatal (const char *file_path, const int line, const char *format, ...)
{
  va_list vargs;
  va_start (vargs, format);
  String msg = string_vprintf (format, vargs);
  va_end (vargs);
  debug_handler ('F', string_printf ("%s:%d", file_path, line), msg);
  ::abort();
}

void
debug_critical (const char *file_path, const int line, const char *format, ...)
{
  va_list vargs;
  va_start (vargs, format);
  String msg = string_vprintf (format, vargs);
  va_end (vargs);
  debug_handler ('C', string_printf ("%s:%d", file_path, line), msg);
}

void
debug_fixit (const char *file_path, const int line, const char *format, ...)
{
  va_list vargs;
  va_start (vargs, format);
  String msg = string_vprintf (format, vargs);
  va_end (vargs);
  debug_handler ('X', string_printf ("%s:%d", file_path, line), msg);
}

// == AnsiColors ==
namespace AnsiColors {

const char*
color_code (Colors acolor)
{
  switch (acolor)
    {
    default: ;
    case NONE:             return "";
    case RESET:            return "\033[0m";
    case BOLD:             return "\033[1m";
    case BOLD_OFF:         return "\033[22m";
    case ITALICS:          return "\033[3m";
    case ITALICS_OFF:      return "\033[23m";
    case UNDERLINE:        return "\033[4m";
    case UNDERLINE_OFF:    return "\033[24m";
    case INVERSE:          return "\033[7m";
    case INVERSE_OFF:      return "\033[27m";
    case STRIKETHROUGH:    return "\033[9m";
    case STRIKETHROUGH_OFF:return "\033[29m";
    case FG_BLACK:         return "\033[30m";
    case FG_RED:           return "\033[31m";
    case FG_GREEN:         return "\033[32m";
    case FG_YELLOW:        return "\033[33m";
    case FG_BLUE:          return "\033[34m";
    case FG_MAGENTA:       return "\033[35m";
    case FG_CYAN:          return "\033[36m";
    case FG_WHITE:         return "\033[37m";
    case FG_DEFAULT:       return "\033[39m";
    case BG_BLACK:         return "\033[40m";
    case BG_RED:           return "\033[41m";
    case BG_GREEN:         return "\033[42m";
    case BG_YELLOW:        return "\033[43m";
    case BG_BLUE:          return "\033[44m";
    case BG_MAGENTA:       return "\033[45m";
    case BG_CYAN:          return "\033[46m";
    case BG_WHITE:         return "\033[47m";
    case BG_DEFAULT:       return "\033[49m";
    }
}

struct EnvKey {
  String var, key;
  EnvKey() : var (""), key ("") {}
};

static constexpr int     UNCHECKED = 2;
static Atomic<int>       colorize_stdout = UNCHECKED;   // cache stdout colorization check
static Exclusive<EnvKey> env_key;

void
color_envkey (const String &env_var, const String &key)
{
  EnvKey ekey;
  ekey.var = env_var;
  ekey.key = key;
  env_key = ekey; // Atomic access
  colorize_stdout = UNCHECKED; // Atomic access
}

bool
colorize_tty (int fd)
{
  EnvKey ekey = env_key;
  const char *ev = getenv (ekey.var.c_str());
  if (ev)
    {
      if (ekey.key.empty() == false)
        {
          const int l = max (size_t (64), strlen (ev) + 1);
          char value[l];
          strcpy (value, "auto");
          cstring_option_sense (ev, ekey.key.c_str(), value);
          if (strncasecmp (value, "always", 6) == 0)
            return true;
          else if (strncasecmp (value, "never", 5) == 0)
            return false;
          else if (strncasecmp (value, "auto", 4) != 0)
            return string_to_bool (value, 0);
        }
      else if (strncasecmp (ev, "always", 6) == 0)
        return true;
      else if (strncasecmp (ev, "never", 5) == 0)
        return false;
      else if (strncasecmp (ev, "auto", 4) != 0)
        return string_to_bool (ev, 0);
    }
  // found 'auto', sense arbitrary fd
  if (fd >= 3)
    return isatty (fd);
  // sense stdin/stdout/stderr
  if (isatty (1) && isatty (2))
    {
      char *term = getenv ("TERM");
      if (term && strcmp (term, "dumb") != 0)
        return true;
    }
  return false;
}

const char*
color (Colors acolor)
{
  if (colorize_stdout == UNCHECKED)
    colorize_stdout = colorize_tty();
  if (!colorize_stdout)
    return "";
  return color_code (acolor);
}

} // AnsiColors

} // Rapicorn
<|endoftext|>


<commit_before>#include "plugin.h"
#include "plugininterface.h"
#include "pluginmanager.h"

#include <QApplication>
#include <QDir>
#include <QPluginLoader>
#include <QSettings>

#include <QMessageBox>

namespace OpenCOR {

PluginManager::PluginManager(QSettings *pSettings) :
    mSettings(pSettings)
{
#ifndef Q_WS_MAC
    const QString pluginsDir = "plugins";
#else
    const QString pluginsDir = "PlugIns";
#endif

    mPluginsDir =  QDir(qApp->applicationDirPath()).canonicalPath()
                  +QDir::separator()+QString("..")
                  +QDir::separator()+pluginsDir
                  +QDir::separator()+qApp->applicationName();

#ifndef Q_WS_MAC
    // The plugins directory should be correct, but in case we try to run
    // OpenCOR on Windows or Linux AND from within Qt Creator, then the binary
    // will be running [OpenCOR]/build/OpenCOR[.exe] rather than
    // [OpenCOR]/build/bin/OpenCOR[.exe] as we should if we were to mimic the
    // case where OpenCOR has been deployed. Then, because the plugins are in
    // [OpenCOR]/build/plugins/OpenCOR, we must skip the "../" bit. Yes, it's
    // not neat, but... is there another solution?...

    if (!QDir(mPluginsDir).exists())
        mPluginsDir =  QDir(qApp->applicationDirPath()).canonicalPath()
                      +QDir::separator()+pluginsDir
                      +QDir::separator()+qApp->applicationName();
#endif
}

PluginManager::~PluginManager()
{
    // Remove all the plugins

    foreach (Plugin *plugin, mPlugins)
        delete plugin;
}

void PluginManager::loadPlugin(const QString &pPluginFileName)
{
    // Check what type of plugin we are dealing with and what its dependencies
    // are, if any

    typedef PluginInfo (*PluginInfoFunc)();
    const QString pluginName = QFileInfo(pPluginFileName).baseName();

    PluginInfoFunc pluginInfoFunc = (PluginInfoFunc) QLibrary::resolve(pPluginFileName,
                                                                       QString(pluginName+"PluginInfo").toLatin1().constData());
    if (pluginInfoFunc) {
        // The plugin information function was found, so extract the information
        // we are after

        PluginInfo pluginInfo = pluginInfoFunc();

        QString type;
        QString dependencies;

        switch (pluginInfo.type) {
        case Console:
            type = "console";

            break;
        case Gui:
            type = "GUI";

            break;
        default:
            type = "both console and GUI";

            break;
        }

        if (!pluginInfo.dependencies.count()) {
            dependencies = "none";
        } else {
            foreach (QString dependency, pluginInfo.dependencies)
                dependencies += dependency+" | ";

            dependencies.chop(3);
        }

        QMessageBox::information(0, "Plugin info",
                                 QString("Plugin name: %1\nType: %2\nDependencies: %3").arg(pluginName,
                                                                                type,
                                                                                dependencies));
    } else {
        QMessageBox::information(0, "Plugin info",
                                 QString("The %1 plugin CANNOT be loaded").arg(pluginName));
    }
}

void PluginManager::loadPlugins()
{
    // Try to load all the plugins

#ifdef Q_WS_WIN
    const QString extension = ".dll";
#elif defined(Q_WS_MAC)
    const QString extension = ".dylib";
#else
    const QString extension = ".so";
#endif

    QFileInfoList files = QDir(mPluginsDir).entryInfoList(QStringList("*"+extension), QDir::Files);

    foreach (const QFileInfo &file, files)
        loadPlugin(file.canonicalFilePath());
}

}
<commit_msg>Fixed a small issue with loading plugins on Linux and Mac OS X.<commit_after>#include "plugin.h"
#include "plugininterface.h"
#include "pluginmanager.h"

#include <QApplication>
#include <QDir>
#include <QPluginLoader>
#include <QSettings>

#include <QMessageBox>

namespace OpenCOR {

PluginManager::PluginManager(QSettings *pSettings) :
    mSettings(pSettings)
{
#ifndef Q_WS_MAC
    const QString pluginsDir = "plugins";
#else
    const QString pluginsDir = "PlugIns";
#endif

    mPluginsDir =  QDir(qApp->applicationDirPath()).canonicalPath()
                  +QDir::separator()+QString("..")
                  +QDir::separator()+pluginsDir
                  +QDir::separator()+qApp->applicationName();

#ifndef Q_WS_MAC
    // The plugins directory should be correct, but in case we try to run
    // OpenCOR on Windows or Linux AND from within Qt Creator, then the binary
    // will be running [OpenCOR]/build/OpenCOR[.exe] rather than
    // [OpenCOR]/build/bin/OpenCOR[.exe] as we should if we were to mimic the
    // case where OpenCOR has been deployed. Then, because the plugins are in
    // [OpenCOR]/build/plugins/OpenCOR, we must skip the "../" bit. Yes, it's
    // not neat, but... is there another solution?...

    if (!QDir(mPluginsDir).exists())
        mPluginsDir =  QDir(qApp->applicationDirPath()).canonicalPath()
                      +QDir::separator()+pluginsDir
                      +QDir::separator()+qApp->applicationName();
#endif
}

PluginManager::~PluginManager()
{
    // Remove all the plugins

    foreach (Plugin *plugin, mPlugins)
        delete plugin;
}

void PluginManager::loadPlugin(const QString &pPluginFileName)
{
    // Check what type of plugin we are dealing with and what its dependencies
    // are, if any

    typedef PluginInfo (*PluginInfoFunc)();

#ifndef Q_WS_WIN
    const QString pluginName = QFileInfo(pPluginFileName).baseName().remove(0, 3);
    // Note: remove the "lib" part of the plugin file name...
#else
    const QString pluginName = QFileInfo(pPluginFileName).baseName();
#endif

    PluginInfoFunc pluginInfoFunc = (PluginInfoFunc) QLibrary::resolve(pPluginFileName,
                                                                       QString(pluginName+"PluginInfo").toLatin1().constData());
    if (pluginInfoFunc) {
        // The plugin information function was found, so extract the information
        // we are after

        PluginInfo pluginInfo = pluginInfoFunc();

        QString type;
        QString dependencies;

        switch (pluginInfo.type) {
        case Console:
            type = "console";

            break;
        case Gui:
            type = "GUI";

            break;
        default:
            type = "both console and GUI";

            break;
        }

        if (!pluginInfo.dependencies.count()) {
            dependencies = "none";
        } else {
            foreach (QString dependency, pluginInfo.dependencies)
                dependencies += dependency+" | ";

            dependencies.chop(3);
        }

        QMessageBox::information(0, "Plugin info",
                                 QString("Plugin name: %1\nType: %2\nDependencies: %3").arg(pluginName,
                                                                                type,
                                                                                dependencies));
    } else {
        QMessageBox::information(0, "Plugin info",
                                 QString("The %1 plugin CANNOT be loaded").arg(pluginName));
    }
}

void PluginManager::loadPlugins()
{
    // Try to load all the plugins

#ifdef Q_WS_WIN
    const QString extension = ".dll";
#elif defined(Q_WS_MAC)
    const QString extension = ".dylib";
#else
    const QString extension = ".so";
#endif

    QFileInfoList files = QDir(mPluginsDir).entryInfoList(QStringList("*"+extension), QDir::Files);

    foreach (const QFileInfo &file, files)
        loadPlugin(file.canonicalFilePath());
}

}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief arango exceptions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Exception.h"
#include "Basics/StringUtils.h"

using namespace std;
using namespace triagens::arango;

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor, without format string
////////////////////////////////////////////////////////////////////////////////

Exception::Exception (int code,
                      char const* file,
                      int line)
  : _errorMessage(TRI_errno_string(code)),
    _file(file),
    _line(line),
    _code(code) {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor, for creating an exception with an already created
/// error message (normally based on error templates containing %s, %d etc.)
////////////////////////////////////////////////////////////////////////////////

Exception::Exception (int code,
                      string const& errorMessage,
                      char const* file,
                      int line)
  : _errorMessage(errorMessage),
    _file(file),
    _line(line),
    _code(code) {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

Exception::~Exception () throw () {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return exception message
////////////////////////////////////////////////////////////////////////////////

char const* Exception::what () const throw () {
  // we have to use an instance member here because we should not return a
  // pointer (c_str()) to the internals of a stack object (stack object will
  // be destroyed when function is left...)
  // additionally, we should not create new string values here as this might
  // throw exceptions - but this function is marked to throw no exceptions!
  /*
  std::string message = "exception in '";
  message.append(_file);
  message.append("' at line ");
  message.append(basics::StringUtils::itoa(_line));
  message.append(": ");
  message += this->message();

  return message.c_str();
  */

  return _errorMessage.c_str();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief construct an error message from a template string
////////////////////////////////////////////////////////////////////////////////

std::string Exception::FillExceptionString (int code,
                                            ...) {
  char const* format = TRI_errno_string(code);
  TRI_ASSERT(format != nullptr);

  char buffer[1024];
  va_list ap;
  va_start(ap, code);
  vsnprintf(buffer, sizeof(buffer) - 1, format, ap);
  va_end(ap);
  buffer[sizeof(buffer) - 1] = '\0'; // Windows

  return std::string(buffer);
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>When compiled in maintainer mode, print c-backtraces on Arango Exceptions too.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief arango exceptions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Exception.h"
#include "Basics/StringUtils.h"

using namespace std;
using namespace triagens::arango;

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor, without format string
////////////////////////////////////////////////////////////////////////////////

Exception::Exception (int code,
                      char const* file,
                      int line)
  : _errorMessage(TRI_errno_string(code)),
    _file(file),
    _line(line),
    _code(code) {
#ifdef TRI_ENABLE_MAINTAINER_MODE
#if HAVE_BACKTRACE
  _backtrace();
#endif
#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor, for creating an exception with an already created
/// error message (normally based on error templates containing %s, %d etc.)
////////////////////////////////////////////////////////////////////////////////

Exception::Exception (int code,
                      string const& errorMessage,
                      char const* file,
                      int line)
  : _errorMessage(errorMessage),
    _file(file),
    _line(line),
    _code(code) {
#ifdef TRI_ENABLE_MAINTAINER_MODE
#if HAVE_BACKTRACE
  _backtrace();
#endif
#endif
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

Exception::~Exception () throw () {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return exception message
////////////////////////////////////////////////////////////////////////////////

char const* Exception::what () const throw () {
  // we have to use an instance member here because we should not return a
  // pointer (c_str()) to the internals of a stack object (stack object will
  // be destroyed when function is left...)
  // additionally, we should not create new string values here as this might
  // throw exceptions - but this function is marked to throw no exceptions!
  /*
  std::string message = "exception in '";
  message.append(_file);
  message.append("' at line ");
  message.append(basics::StringUtils::itoa(_line));
  message.append(": ");
  message += this->message();

  return message.c_str();
  */

  return _errorMessage.c_str();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief construct an error message from a template string
////////////////////////////////////////////////////////////////////////////////

std::string Exception::FillExceptionString (int code,
                                            ...) {
  char const* format = TRI_errno_string(code);
  TRI_ASSERT(format != nullptr);

  char buffer[1024];
  va_list ap;
  va_start(ap, code);
  vsnprintf(buffer, sizeof(buffer) - 1, format, ap);
  va_end(ap);
  buffer[sizeof(buffer) - 1] = '\0'; // Windows

  return std::string(buffer);
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// A very simple commandline tool for decompressing woff2 format files to true
// type font files.

#include <string>

#include "./file.h"
#include "./woff2_dec.h"

int main(int argc, char **argv) {
  using std::string;

  if (argc != 2) {
    fprintf(stderr, "One argument, the input filename, must be provided.\n");
    return 1;
  }

  string filename(argv[1]);
  string outfilename = filename.substr(0, filename.find_last_of(".")) + ".ttf";

  string input = woff2::GetFileContent(filename);
  const uint8_t* raw_input = reinterpret_cast<const uint8_t*>(input.data());
  string output(std::min(woff2::ComputeWOFF2FinalSize(raw_input, input.size()),
                         woff2::kDefaultMaxSize), 0);
  woff2::WOFF2StringOut out(&output);

  const bool ok = woff2::ConvertWOFF2ToTTF(raw_input, input.size(), &out);

  if (ok) {
    woff2::SetFileContents(outfilename, output.begin(),
        output.begin() + out.Size());
  }
  return ok ? 0 : 1;
}
<commit_msg>reminder to update fuzzer on change<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// A very simple commandline tool for decompressing woff2 format files to true
// type font files.

#include <string>

#include "./file.h"
#include "./woff2_dec.h"

int main(int argc, char **argv) {
  using std::string;

  if (argc != 2) {
    fprintf(stderr, "One argument, the input filename, must be provided.\n");
    return 1;
  }

  string filename(argv[1]);
  string outfilename = filename.substr(0, filename.find_last_of(".")) + ".ttf";

  // Note: update woff2_dec_fuzzer_new_entry.cc if this pattern changes.
  string input = woff2::GetFileContent(filename);
  const uint8_t* raw_input = reinterpret_cast<const uint8_t*>(input.data());
  string output(std::min(woff2::ComputeWOFF2FinalSize(raw_input, input.size()),
                         woff2::kDefaultMaxSize), 0);
  woff2::WOFF2StringOut out(&output);

  const bool ok = woff2::ConvertWOFF2ToTTF(raw_input, input.size(), &out);

  if (ok) {
    woff2::SetFileContents(outfilename, output.begin(),
        output.begin() + out.Size());
  }
  return ok ? 0 : 1;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/private/SkMalloc.h"

#include <cstdlib>

#if defined(SK_DEBUG) && defined(SK_BUILD_FOR_WIN)
#include <intrin.h>
// This is a super stable value and setting it here avoids pulling in all of windows.h.
#ifndef FAST_FAIL_FATAL_APP_EXIT
#define FAST_FAIL_FATAL_APP_EXIT              7
#endif
#endif

#define SK_DEBUGFAILF(fmt, ...) \
    SkASSERT((SkDebugf(fmt"\n", __VA_ARGS__), false))

static inline void sk_out_of_memory(size_t size) {
    SK_DEBUGFAILF("sk_out_of_memory (asked for %zu bytes)",
                  size);
#if defined(SK_BUILD_FOR_AFL_FUZZ)
    exit(1);
#else
    abort();
#endif
}

static inline void* throw_on_failure(size_t size, void* p) {
    if (size > 0 && p == nullptr) {
        // If we've got a nullptr here, the only reason we should have failed is running out of RAM.
        sk_out_of_memory(size);
    }
    return p;
}

void sk_abort_no_print() {
#if defined(SK_BUILD_FOR_WIN) && defined(SK_IS_BOT)
    // do not display a system dialog before aborting the process
    _set_abort_behavior(0, _WRITE_ABORT_MSG);
#endif
#if defined(SK_DEBUG) && defined(SK_BUILD_FOR_WIN)
    __fastfail(FAST_FAIL_FATAL_APP_EXIT);
#elif defined(__clang__)
    __builtin_trap();
#else
    abort();
#endif
}

void sk_out_of_memory(void) {
    SkDEBUGFAIL("sk_out_of_memory");
#if defined(SK_BUILD_FOR_AFL_FUZZ)
    exit(1);
#else
    abort();
#endif
}

void* sk_realloc_throw(void* addr, size_t size) {
    return throw_on_failure(size, realloc(addr, size));
}

void sk_free(void* p) {
    if (p) {
        free(p);
    }
}

void* sk_malloc_flags(size_t size, unsigned flags) {
    void* p;
    if (flags & SK_MALLOC_ZERO_INITIALIZE) {
        p = calloc(size, 1);
    } else {
        p = malloc(size);
    }
    if (flags & SK_MALLOC_THROW) {
        return throw_on_failure(size, p);
    } else {
        return p;
    }
}
<commit_msg>Avoid heap initialization for skia allocations.<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/private/SkMalloc.h"

#include <cstdlib>

#if defined(SK_DEBUG) && defined(SK_BUILD_FOR_WIN)
#include <intrin.h>
// This is a super stable value and setting it here avoids pulling in all of windows.h.
#ifndef FAST_FAIL_FATAL_APP_EXIT
#define FAST_FAIL_FATAL_APP_EXIT              7
#endif
#endif

#define SK_DEBUGFAILF(fmt, ...) \
    SkASSERT((SkDebugf(fmt"\n", __VA_ARGS__), false))

static inline void sk_out_of_memory(size_t size) {
    SK_DEBUGFAILF("sk_out_of_memory (asked for %zu bytes)",
                  size);
#if defined(SK_BUILD_FOR_AFL_FUZZ)
    exit(1);
#else
    abort();
#endif
}

static inline void* throw_on_failure(size_t size, void* p) {
    if (size > 0 && p == nullptr) {
        // If we've got a nullptr here, the only reason we should have failed is running out of RAM.
        sk_out_of_memory(size);
    }
    return p;
}

void sk_abort_no_print() {
#if defined(SK_BUILD_FOR_WIN) && defined(SK_IS_BOT)
    // do not display a system dialog before aborting the process
    _set_abort_behavior(0, _WRITE_ABORT_MSG);
#endif
#if defined(SK_DEBUG) && defined(SK_BUILD_FOR_WIN)
    __fastfail(FAST_FAIL_FATAL_APP_EXIT);
#elif defined(__clang__)
    __builtin_trap();
#else
    abort();
#endif
}

void sk_out_of_memory(void) {
    SkDEBUGFAIL("sk_out_of_memory");
#if defined(SK_BUILD_FOR_AFL_FUZZ)
    exit(1);
#else
    abort();
#endif
}

void* sk_realloc_throw(void* addr, size_t size) {
    return throw_on_failure(size, realloc(addr, size));
}

void sk_free(void* p) {
    if (p) {
        free(p);
    }
}

void* sk_malloc_flags(size_t size, unsigned flags) {
    void* p;
    if (flags & SK_MALLOC_ZERO_INITIALIZE) {
        p = calloc(size, 1);
    } else {
#if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) && defined(__BIONIC__)
        /* TODO: After b/169449588 is fixed, we will want to change this to restore
         *       original behavior instead of always disabling the flag.
         * TODO: After b/158870657 is fixed and scudo is used globally, we can assert when an
         *       an error is returned.
         */
        // malloc() generally doesn't initialize its memory and that's a huge security hole,
        // so Android has replaced its malloc() with one that zeros memory,
        // but that's a huge performance hit for HWUI, so turn it back off again.
        (void)mallopt(M_THREAD_DISABLE_MEM_INIT, 1);
#endif
        p = malloc(size);
#if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) && defined(__BIONIC__)
        (void)mallopt(M_THREAD_DISABLE_MEM_INIT, 0);
#endif
    }
    if (flags & SK_MALLOC_THROW) {
        return throw_on_failure(size, p);
    } else {
        return p;
    }
}
<|endoftext|>


<commit_before>/*
  C code wrapper around Dehnen/McMillan Torus code for actionAngle calculations
*/
#include <new>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <ctime>
#include "Torus.h"
#include "LogPot.h"

extern "C"
{
  void actionAngleTorus_xv(double jr, double jphi, double jz,
			   int na,
			   double * angler, double * anglephi, double * anglez,
			   double * R, double * vR, double * vT,
			   double * z, double * vz, double * phi)
  {
    // set up Torus
    Torus *T;
    T= new(std::nothrow) Torus;

    // set up GalaxyPotential
    Potential *Phi;
    Phi = new(std::nothrow) LogPotential(1.,0.8,0.,0.);

    // Load actions and fit Torus
    Actions J;
    J[0]= jr;
    J[1]= jz;
    J[2]= jphi;
    double dJ= 0.003;
    int flag;
    flag = T->AutoFit(J,Phi,dJ);

    Phi->set_Lz(J(2));

    // Load angles and get (x,v)
    Angles A;
    PSPT Q;
    int ii;
    for (ii=0; ii < na; ii++) {
      // Load angles
      A[0]= *(angler+ii);
      A[1]= *(anglez+ii);
      A[2]= *(anglephi+ii);
      // get phase-space point
      Q= T->Map3D(A);
      *(R+ii)= Q(0);
      *(z+ii)= Q(1);
      *(phi+ii)= Q(2);
      *(vR+ii)= Q(3);
      *(vz+ii)= Q(4);
      *(vT+ii)= Q(5);
    }
  }
}
<commit_msg>example of running Torus code with galpy log potential; agrees with Torus log potential<commit_after>/*
  C code wrapper around Dehnen/McMillan Torus code for actionAngle calculations
*/
#include <new>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <ctime>
#include "Torus.h"
#include "LogPot.h"
#include "galpyPot.h"
#include <actionAngle.h>
#include <integrateFullOrbit.h>
#include <galpy_potentials.h>

extern "C"
{
  void actionAngleTorus_xv(double jr, double jphi, double jz,
			   int na,
			   double * angler, double * anglephi, double * anglez,
			   double * R, double * vR, double * vT,
			   double * z, double * vz, double * phi)
  {
    // set up Torus
    Torus *T;
    T= new(std::nothrow) Torus;

    // set up potential
    Potential *Phi;
    //Phi = new(std::nothrow) LogPotential(1.,0.8,0.,0.);
    int npot= 1;
    struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
    double * pot_args;
    pot_args= (double *) malloc ( 3 * sizeof ( double ) );
    *pot_args= 1.;
    *(pot_args+1)= 0.8;
    *(pot_args+2)= 0.;
    int pot_type= 0;
    parse_actionAngleArgs(npot,potentialArgs,&pot_type,pot_args);
    parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,pot_args);
    Phi = new(std::nothrow) galpyPotential(npot,potentialArgs);

    // Load actions and fit Torus
    Actions J;
    J[0]= jr;
    J[1]= jz;
    J[2]= jphi;
    double dJ= 0.003;
    int flag;
    flag = T->AutoFit(J,Phi,dJ);

    Phi->set_Lz(J(2));

    // Load angles and get (x,v)
    Angles A;
    PSPT Q;
    int ii;
    for (ii=0; ii < na; ii++) {
      // Load angles
      A[0]= *(angler+ii);
      A[1]= *(anglez+ii);
      A[2]= *(anglephi+ii);
      // get phase-space point
      Q= T->Map3D(A);
      *(R+ii)= Q(0);
      *(z+ii)= Q(1);
      *(phi+ii)= Q(2);
      *(vR+ii)= Q(3);
      *(vz+ii)= Q(4);
      *(vT+ii)= Q(5);
    }
  }
}
<|endoftext|>


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

 Module:       FGGain.cpp
 Author:       Jon S. Berndt
 Date started: 4/2000

 ------------- Copyright (C) 2000 -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES,  and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGGain.h"
#include "input_output/FGXMLElement.h"
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

namespace JSBSim {

static const char *IdSrc = "$Id: FGGain.cpp,v 1.21 2010/08/21 22:56:11 jberndt Exp $";
static const char *IdHdr = ID_GAIN;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGGain::FGGain(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element)
{
  Element *scale_element, *zero_centered;
  string strScheduledBy, gain_string, sZeroCentered;

  GainPropertyNode = 0;
  GainPropertySign = 1.0;
  Gain = 1.000;
  Rows = 0;
  Table = 0;
  InMin = -1.0;
  InMax =  1.0;
  OutMin = OutMax = 0.0;

  if (Type == "PURE_GAIN") {
    if ( !element->FindElement("gain") ) {
      cout << highint << "      No GAIN specified (default: 1.0)" << normint << endl;
    }
  }

  if ( element->FindElement("gain") ) {
    gain_string = element->FindElementValue("gain");
    if (!is_number(gain_string)) { // property
      if (gain_string[0] == '-') {
       GainPropertySign = -1.0;
       gain_string.erase(0,1);
      }
      GainPropertyNode = PropertyManager->GetNode(gain_string);
    } else {
      Gain = element->FindElementValueAsNumber("gain");
    }
  }

  if (Type == "AEROSURFACE_SCALE") {
    scale_element = element->FindElement("domain");
    if (scale_element) {
      if (scale_element->FindElement("max") && scale_element->FindElement("min") )
      {
        InMax = scale_element->FindElementValueAsNumber("max");
        InMin = scale_element->FindElementValueAsNumber("min");
      }
    }
    scale_element = element->FindElement("range");
    if (!scale_element) throw(string("No range supplied for aerosurface scale component"));
    if (scale_element->FindElement("max") && scale_element->FindElement("min") )
    {
      OutMax = scale_element->FindElementValueAsNumber("max");
      OutMin = scale_element->FindElementValueAsNumber("min");
    } else {
      cerr << "Maximum and minimum output values must be supplied for the "
              "aerosurface scale component" << endl;
      exit(-1);
    }
    ZeroCentered = true;
    zero_centered = element->FindElement("zero_centered");
    //ToDo if zero centered, then mins must be <0 and max's must be >0
    if (zero_centered) {
      sZeroCentered = element->FindElementValue("zero_centered");
      if (sZeroCentered == string("0") || sZeroCentered == string("false")) {
        ZeroCentered = false;
      }
    }
  }

  if (Type == "SCHEDULED_GAIN") {
    if (element->FindElement("table")) {
      Table = new FGTable(PropertyManager, element->FindElement("table"));
    } else {
      cerr << "A table must be provided for the scheduled gain component" << endl;
      exit(-1);
    }
  }

  FGFCSComponent::bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGGain::~FGGain()
{
  delete Table;

  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGain::Run(void )
{
  double SchedGain = 1.0;

  Input = InputNodes[0]->getDoubleValue() * InputSigns[0];

  if (GainPropertyNode != 0) Gain = GainPropertyNode->getDoubleValue() * GainPropertySign;

  if (Type == "PURE_GAIN") {                       // PURE_GAIN

    Output = Gain * Input;

  } else if (Type == "SCHEDULED_GAIN") {           // SCHEDULED_GAIN

    SchedGain = Table->GetValue();
    Output = Gain * SchedGain * Input;

  } else if (Type == "AEROSURFACE_SCALE") {        // AEROSURFACE_SCALE

    if (ZeroCentered) {
      if (Input == 0.0) {
        Output = 0.0;
      } else if (Input > 0) {
        Output = (Input / InMax) * OutMax;
      } else {
        Output = (Input / InMin) * OutMin;
      }
    } else {
      Output = OutMin + ((Input - InMin) / (InMax - InMin)) * (OutMax - OutMin);
    }

    Output *= Gain;
  }

  Clip();
  if (IsOutput) SetOutput();

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGGain::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor
      if (InputSigns[0] < 0)
        cout << "      INPUT: -" << InputNames[0] << endl;
      else
        cout << "      INPUT: " << InputNames[0] << endl;

      if (GainPropertyNode != 0) {
        cout << "      GAIN: " << GainPropertyNode->GetName() << endl;
      } else {
        cout << "      GAIN: " << Gain << endl;
      }
      if (IsOutput) {
        for (unsigned int i=0; i<OutputNodes.size(); i++)
          cout << "      OUTPUT: " << OutputNodes[i]->getName() << endl;
      }
      if (Type == "AEROSURFACE_SCALE") {
        cout << "      In/Out Mapping:" << endl;
        cout << "        Input MIN: " << InMin << endl;
        cout << "        Input MAX: " << InMax << endl;
        cout << "        Output MIN: " << OutMin << endl;
        cout << "        Output MAX: " << OutMax << endl;
      }
      if (Table != 0) {
        cout << "      Scheduled by table: " << endl;
        Table->Print();
      }
    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGGain" << endl;
    if (from == 1) cout << "Destroyed:    FGGain" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<commit_msg>Fixed a logging destination in FGGain<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGGain.cpp
 Author:       Jon S. Berndt
 Date started: 4/2000

 ------------- Copyright (C) 2000 -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES,  and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGGain.h"
#include "input_output/FGXMLElement.h"
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

namespace JSBSim {

static const char *IdSrc = "$Id: FGGain.cpp,v 1.22 2010/08/24 10:37:17 jberndt Exp $";
static const char *IdHdr = ID_GAIN;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGGain::FGGain(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element)
{
  Element *scale_element, *zero_centered;
  string strScheduledBy, gain_string, sZeroCentered;

  GainPropertyNode = 0;
  GainPropertySign = 1.0;
  Gain = 1.000;
  Rows = 0;
  Table = 0;
  InMin = -1.0;
  InMax =  1.0;
  OutMin = OutMax = 0.0;

  if (Type == "PURE_GAIN") {
    if ( !element->FindElement("gain") ) {
      cerr << highint << "      No GAIN specified (default: 1.0)" << normint << endl;
    }
  }

  if ( element->FindElement("gain") ) {
    gain_string = element->FindElementValue("gain");
    if (!is_number(gain_string)) { // property
      if (gain_string[0] == '-') {
       GainPropertySign = -1.0;
       gain_string.erase(0,1);
      }
      GainPropertyNode = PropertyManager->GetNode(gain_string);
    } else {
      Gain = element->FindElementValueAsNumber("gain");
    }
  }

  if (Type == "AEROSURFACE_SCALE") {
    scale_element = element->FindElement("domain");
    if (scale_element) {
      if (scale_element->FindElement("max") && scale_element->FindElement("min") )
      {
        InMax = scale_element->FindElementValueAsNumber("max");
        InMin = scale_element->FindElementValueAsNumber("min");
      }
    }
    scale_element = element->FindElement("range");
    if (!scale_element) throw(string("No range supplied for aerosurface scale component"));
    if (scale_element->FindElement("max") && scale_element->FindElement("min") )
    {
      OutMax = scale_element->FindElementValueAsNumber("max");
      OutMin = scale_element->FindElementValueAsNumber("min");
    } else {
      cerr << "Maximum and minimum output values must be supplied for the "
              "aerosurface scale component" << endl;
      exit(-1);
    }
    ZeroCentered = true;
    zero_centered = element->FindElement("zero_centered");
    //ToDo if zero centered, then mins must be <0 and max's must be >0
    if (zero_centered) {
      sZeroCentered = element->FindElementValue("zero_centered");
      if (sZeroCentered == string("0") || sZeroCentered == string("false")) {
        ZeroCentered = false;
      }
    }
  }

  if (Type == "SCHEDULED_GAIN") {
    if (element->FindElement("table")) {
      Table = new FGTable(PropertyManager, element->FindElement("table"));
    } else {
      cerr << "A table must be provided for the scheduled gain component" << endl;
      exit(-1);
    }
  }

  FGFCSComponent::bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGGain::~FGGain()
{
  delete Table;

  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGain::Run(void )
{
  double SchedGain = 1.0;

  Input = InputNodes[0]->getDoubleValue() * InputSigns[0];

  if (GainPropertyNode != 0) Gain = GainPropertyNode->getDoubleValue() * GainPropertySign;

  if (Type == "PURE_GAIN") {                       // PURE_GAIN

    Output = Gain * Input;

  } else if (Type == "SCHEDULED_GAIN") {           // SCHEDULED_GAIN

    SchedGain = Table->GetValue();
    Output = Gain * SchedGain * Input;

  } else if (Type == "AEROSURFACE_SCALE") {        // AEROSURFACE_SCALE

    if (ZeroCentered) {
      if (Input == 0.0) {
        Output = 0.0;
      } else if (Input > 0) {
        Output = (Input / InMax) * OutMax;
      } else {
        Output = (Input / InMin) * OutMin;
      }
    } else {
      Output = OutMin + ((Input - InMin) / (InMax - InMin)) * (OutMax - OutMin);
    }

    Output *= Gain;
  }

  Clip();
  if (IsOutput) SetOutput();

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGGain::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor
      if (InputSigns[0] < 0)
        cout << "      INPUT: -" << InputNames[0] << endl;
      else
        cout << "      INPUT: " << InputNames[0] << endl;

      if (GainPropertyNode != 0) {
        cout << "      GAIN: " << GainPropertyNode->GetName() << endl;
      } else {
        cout << "      GAIN: " << Gain << endl;
      }
      if (IsOutput) {
        for (unsigned int i=0; i<OutputNodes.size(); i++)
          cout << "      OUTPUT: " << OutputNodes[i]->getName() << endl;
      }
      if (Type == "AEROSURFACE_SCALE") {
        cout << "      In/Out Mapping:" << endl;
        cout << "        Input MIN: " << InMin << endl;
        cout << "        Input MAX: " << InMax << endl;
        cout << "        Output MIN: " << OutMin << endl;
        cout << "        Output MAX: " << OutMax << endl;
      }
      if (Table != 0) {
        cout << "      Scheduled by table: " << endl;
        Table->Print();
      }
    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGGain" << endl;
    if (from == 1) cout << "Destroyed:    FGGain" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EnhancedCustomShapeFontWork.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:26:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _ENHANCEDCUSTOMSHAPEFONTWORK_HXX
#define _ENHANCEDCUSTOMSHAPEFONTWORK_HXX

class SdrObject;
class EnhancedCustomShapeFontWork
{

    public :

        static SdrObject* CreateFontWork( const SdrObject* pShape2d, const SdrObject* pCustomShape );
};

#endif

<commit_msg>INTEGRATION: CWS sj29 (1.3.100); FILE MERGED 2005/10/25 17:48:15 sj 1.3.100.1: #i55538# now using the correct font by supporting the script type<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EnhancedCustomShapeFontWork.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-11-02 09:57:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _ENHANCEDCUSTOMSHAPEFONTWORK_HXX
#define _ENHANCEDCUSTOMSHAPEFONTWORK_HXX

#ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif

class SdrObject;
class EnhancedCustomShapeFontWork
{
        static ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > mxBreakIterator;

    public :

        static com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > GetBreakIterator();
        static SdrObject* CreateFontWork( const SdrObject* pShape2d, const SdrObject* pCustomShape );
};

#endif

<|endoftext|>


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

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

namespace Loki {

///
Config::Config() {}

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

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

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

    try {
      ReadoutConstDelayNS = root["ReadoutConstDelayNS"].get<unsigned int>();
    } catch (...) {
      // Use default value
    }
    LOG(INIT, Sev::Info, "ReadoutConstDelayNS: {}", ReadoutConstDelayNS);

    try {
      MaxPulseTimeNS = root["MaxPulseTimeNS"].get<unsigned int>();
    } catch (...) {
      // Use default value
    }
    LOG(INIT, Sev::Info, "MaxPulseTimeNS: {}", MaxPulseTimeNS);

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

      NTubesTotal += TubesZ * TubesN;
      LOG(INIT, Sev::Info, "NTubesTotal: {}", NTubesTotal);

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

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

    Pixels = NTubesTotal * PanelGeometry::NStraws * Resolution;
    Geometry = new ESSGeometry(Resolution, NTubesTotal * 7, 1, 1);
    LOG(INIT, Sev::Info, "Total pixels: {}", Pixels);

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

} // namespace Loki
<commit_msg>Minor refactoring, removing unnecessary constant, and added comment (#452)<commit_after>/* Copyright (C) 2019 European Spallation Source, ERIC. See LICENSE file */
//===----------------------------------------------------------------------===//
///
/// \file
///
/// \brief using nlohmann json parser to read configurations from file
//===----------------------------------------------------------------------===//

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

namespace Loki {

///
Config::Config() {}

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

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

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

    try {
      ReadoutConstDelayNS = root["ReadoutConstDelayNS"].get<unsigned int>();
    } catch (...) {
      // Use default value
    }
    LOG(INIT, Sev::Info, "ReadoutConstDelayNS: {}", ReadoutConstDelayNS);

    try {
      MaxPulseTimeNS = root["MaxPulseTimeNS"].get<unsigned int>();
    } catch (...) {
      // Use default value
    }
    LOG(INIT, Sev::Info, "MaxPulseTimeNS: {}", MaxPulseTimeNS);

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

      NTubesTotal += TubesZ * TubesN;
      LOG(INIT, Sev::Info, "NTubesTotal: {}", NTubesTotal);

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

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

    Pixels = NTubesTotal * PanelGeometry::NStraws * Resolution;
    // This detector is made of individual 2D banks, so final 2 dimensions are 1
    Geometry = new ESSGeometry(Resolution, NTubesTotal * PanelGeometry::NStraws, 1, 1);
    LOG(INIT, Sev::Info, "Total pixels: {}", Pixels);

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

} // namespace Loki
<|endoftext|>


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee Modules --- EngineShutdown
 *
 * @author Sam Baskinger <sbaskinger@qualys.com>
 */
#ifndef __MODULES__ENGINE_SHUTDOWN_HPP__
#define __MODULES__ENGINE_SHUTDOWN_HPP__

#endif // __MODULES__ENGINE_SHUTDOWN_HPP__
<commit_msg>Removing obsolete file engine_shutdown.hpp. The engine_shutdown module will not share any interface beyond registering for hooks.<commit_after><|endoftext|>


<commit_before>/*
 *
 * Copyright (c) 2016 Nest Labs, Inc.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#if HAVE_CONFIG_H
#include <config.h>
#endif

#include "assert-macros.h"
#include <syslog.h>
#include <errno.h>
#include "SpinelNCPTaskScan.h"
#include "SpinelNCPInstance.h"
#include "spinel-extra.h"

using namespace nl;
using namespace nl::wpantund;

nl::wpantund::SpinelNCPTaskScan::SpinelNCPTaskScan(
	SpinelNCPInstance* instance,
	CallbackWithStatusArg1 cb,
	uint32_t channel_mask,
	uint16_t scan_period,
	ScanType scan_type,
	bool joiner_flag,
	bool enable_filtering,
	uint16_t pan_id
):	SpinelNCPTask(instance, cb), mChannelMaskLen(0), mScanPeriod(scan_period), mScanType(scan_type),
	mJoinerFlag(joiner_flag), mEnablerFiltering(enable_filtering), mPanId(pan_id), mShouldInterfaceDown(false)
{
	uint8_t i;

	for (i = 0; i < 32; i++) {
		if (channel_mask & (1<<i)) {
			mChannelMaskData[mChannelMaskLen++] = i;
		}
	}
}

void
nl::wpantund::SpinelNCPTaskScan::finish(int status, const boost::any& value)
{
	SpinelNCPTask::finish(status, value);
}

int
nl::wpantund::SpinelNCPTaskScan::vprocess_event(int event, va_list args)
{
	int ret = 0;

	EH_BEGIN();

	if (!mInstance->mEnabled) {
		ret = kWPANTUNDStatus_InvalidWhenDisabled;
		finish(ret);
		EH_EXIT();
	}

	if (mInstance->get_ncp_state() == UPGRADING) {
		ret = kWPANTUNDStatus_InvalidForCurrentState;
		finish(ret);
		EH_EXIT();
	}

	// Wait for a bit to see if the NCP will enter the right state.
	EH_REQUIRE_WITHIN(
		NCP_DEFAULT_COMMAND_RESPONSE_TIMEOUT,
		!ncp_state_is_initializing(mInstance->get_ncp_state())
		&& (mInstance->get_ncp_state() != ASSOCIATING)
		&& (mInstance->get_ncp_state() != CREDENTIALS_NEEDED)
		&& !mInstance->is_initializing_ncp(),
		on_error
	);

	// The first event to a task is EVENT_STARTING_TASK. The following
	// line makes sure that we don't start processing this task
	// until it is properly scheduled. All tasks immediately receive
	// the initial `EVENT_STARTING_TASK` event, but further events
	// will only be received by that task once it is that task's turn
	// to execute.
	EH_WAIT_UNTIL(EVENT_STARTING_TASK != event);

	mShouldInterfaceDown = false;

	// Set channel mask
	mNextCommand = SpinelPackData(
		SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_DATA_S),
		SPINEL_PROP_MAC_SCAN_MASK,
		mChannelMaskData,
		mChannelMaskLen
	);
	EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
	ret = mNextCommandRet;
	require_noerr(ret, on_error);

	if (mScanType == kScanTypeDiscover) {

		// Set `discovery joiner flag`
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_THREAD_DISCOVERY_SCAN_JOINER_FLAG,
			mJoinerFlag
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);

		// Set the `enable-filtering` property
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_THREAD_DISCOVERY_SCAN_ENABLE_FILTERING,
			mEnablerFiltering
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);

		// Set PANID used in Discovery scan for PANID filtering.
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_UINT16_S),
			SPINEL_PROP_THREAD_DISCOVERY_SCAN_PANID,
			mPanId
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);

		// For discovery scan, interface should be up
		if (mInstance->get_ncp_state() == OFFLINE) {
			mNextCommand = SpinelPackData(
				SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
				SPINEL_PROP_NET_IF_UP,
				true
			);
			EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
			ret = mNextCommandRet;
			require(ret == kWPANTUNDStatus_Ok || ret == kWPANTUNDStatus_Already, on_error);
			mShouldInterfaceDown = true;
		}
	}

	// Set delay period
	mNextCommand = SpinelPackData(
		SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_UINT16_S),
		SPINEL_PROP_MAC_SCAN_PERIOD,
		mScanPeriod
	);
	EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
	ret = mNextCommandRet;
	require_noerr(ret, on_error);

	// Start the scan.
	{
		spinel_scan_state_t scanState;

		if (mScanType == kScanTypeEnergy) {
			scanState = SPINEL_SCAN_STATE_ENERGY;
		} else if (mScanType == kScanTypeDiscover) {
			scanState = SPINEL_SCAN_STATE_DISCOVER;
		} else if (mScanType == kScanTypeNet) {
			scanState = SPINEL_SCAN_STATE_BEACON;
		} else {
			ret = kWPANTUNDStatus_InvalidArgument;
			goto on_error;
		}

		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_UINT8_S),
			SPINEL_PROP_MAC_SCAN_STATE,
			scanState
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);
	}

	do {
		EH_REQUIRE_WITHIN(
			15,
			event == EVENT_NCP_PROP_VALUE_IS
			|| event == EVENT_NCP_PROP_VALUE_INSERTED,
			on_error
		);

		spinel_prop_key_t prop_key = va_arg_small(args, spinel_prop_key_t);
		const uint8_t* data_ptr = va_arg(args, const uint8_t*);
		spinel_size_t data_len = va_arg(args, spinel_size_t);

		if ((prop_key == SPINEL_PROP_MAC_SCAN_BEACON)
		    && ((mScanType == kScanTypeNet) || (mScanType == kScanTypeDiscover))) {
			const spinel_eui64_t* laddr = NULL;
			const char* networkid = "";
			const uint8_t* xpanid = NULL;
			unsigned int xpanid_len = 0;
			unsigned int proto = 0;
			uint16_t panid = 0xFFFF;
			uint16_t saddr = 0xFFFF;
			uint8_t chan = 0;
			uint8_t lqi = 0x00;
			int8_t rssi = 0x00;
			uint8_t flags = 0x00;

			syslog(LOG_DEBUG, "Got a beacon");

			spinel_datatype_unpack(
				data_ptr,
				data_len,
				"Cct(ESSC)t(iCUd)",
				&chan,
				&rssi,

				&laddr,
				&saddr,
				&panid,
				&lqi,

				&proto,
				&flags,
				&networkid,
				&xpanid, &xpanid_len
			);

			if ((xpanid_len != 8) && (xpanid_len != 0)) {
				break;
			}

			WPAN::NetworkInstance network(
				networkid,
				xpanid,
				panid,
				chan,
				(flags & SPINEL_BEACON_THREAD_FLAG_JOINABLE)
			);
			network.rssi = rssi;
			network.type = proto;
			network.lqi = lqi;
			network.saddr = saddr;

			if (laddr) {
				memcpy(network.hwaddr, laddr, sizeof(network.hwaddr));
			}

			mInstance->get_control_interface().mOnNetScanBeacon(network);

		} else if ((prop_key == SPINEL_PROP_MAC_ENERGY_SCAN_RESULT) && (mScanType == kScanTypeEnergy)) {
			EnergyScanResultEntry result;

			syslog(LOG_DEBUG, "Got an Energy Scan result");

			spinel_datatype_unpack(
				data_ptr,
				data_len,
				"Cc",
				&result.mChannel,
				&result.mMaxRssi
			);

			mInstance->get_control_interface().mOnEnergyScanResult(result);

		} else if (prop_key == SPINEL_PROP_MAC_SCAN_STATE) {
			int scan_state;
			spinel_datatype_unpack(data_ptr, data_len, "i", &scan_state);

			if (scan_state == SPINEL_SCAN_STATE_IDLE) {
				break;
			}
		}

		// Change the event type to 'IDLE' so that we
		// don't try to process this event once than once.
		event = EVENT_IDLE;
	} while(true);

	if (mShouldInterfaceDown)
	{
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_NET_IF_UP,
			false
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require(ret == kWPANTUNDStatus_Ok || ret == kWPANTUNDStatus_Already, on_error);
		mShouldInterfaceDown = false;
	}

	finish(ret);

	EH_EXIT();

on_error:

	if (ret == kWPANTUNDStatus_Ok) {
		ret = kWPANTUNDStatus_Failure;
	}

	if (mShouldInterfaceDown)
	{
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_NET_IF_UP,
			false
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		mShouldInterfaceDown = false;
	}

	syslog(LOG_ERR, "Scan failed: %d", ret);

	finish(ret);

	EH_END();
}
<commit_msg>Relax the "discover scan" check for bringing NCP interface up<commit_after>/*
 *
 * Copyright (c) 2016 Nest Labs, Inc.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#if HAVE_CONFIG_H
#include <config.h>
#endif

#include "assert-macros.h"
#include <syslog.h>
#include <errno.h>
#include "SpinelNCPTaskScan.h"
#include "SpinelNCPInstance.h"
#include "spinel-extra.h"

using namespace nl;
using namespace nl::wpantund;

nl::wpantund::SpinelNCPTaskScan::SpinelNCPTaskScan(
	SpinelNCPInstance* instance,
	CallbackWithStatusArg1 cb,
	uint32_t channel_mask,
	uint16_t scan_period,
	ScanType scan_type,
	bool joiner_flag,
	bool enable_filtering,
	uint16_t pan_id
):	SpinelNCPTask(instance, cb), mChannelMaskLen(0), mScanPeriod(scan_period), mScanType(scan_type),
	mJoinerFlag(joiner_flag), mEnablerFiltering(enable_filtering), mPanId(pan_id), mShouldInterfaceDown(false)
{
	uint8_t i;

	for (i = 0; i < 32; i++) {
		if (channel_mask & (1<<i)) {
			mChannelMaskData[mChannelMaskLen++] = i;
		}
	}
}

void
nl::wpantund::SpinelNCPTaskScan::finish(int status, const boost::any& value)
{
	SpinelNCPTask::finish(status, value);
}

int
nl::wpantund::SpinelNCPTaskScan::vprocess_event(int event, va_list args)
{
	int ret = 0;

	EH_BEGIN();

	if (!mInstance->mEnabled) {
		ret = kWPANTUNDStatus_InvalidWhenDisabled;
		finish(ret);
		EH_EXIT();
	}

	if (mInstance->get_ncp_state() == UPGRADING) {
		ret = kWPANTUNDStatus_InvalidForCurrentState;
		finish(ret);
		EH_EXIT();
	}

	// Wait for a bit to see if the NCP will enter the right state.
	EH_REQUIRE_WITHIN(
		NCP_DEFAULT_COMMAND_RESPONSE_TIMEOUT,
		!ncp_state_is_initializing(mInstance->get_ncp_state())
		&& (mInstance->get_ncp_state() != ASSOCIATING)
		&& (mInstance->get_ncp_state() != CREDENTIALS_NEEDED)
		&& !mInstance->is_initializing_ncp(),
		on_error
	);

	// The first event to a task is EVENT_STARTING_TASK. The following
	// line makes sure that we don't start processing this task
	// until it is properly scheduled. All tasks immediately receive
	// the initial `EVENT_STARTING_TASK` event, but further events
	// will only be received by that task once it is that task's turn
	// to execute.
	EH_WAIT_UNTIL(EVENT_STARTING_TASK != event);

	mShouldInterfaceDown = false;

	// Set channel mask
	mNextCommand = SpinelPackData(
		SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_DATA_S),
		SPINEL_PROP_MAC_SCAN_MASK,
		mChannelMaskData,
		mChannelMaskLen
	);
	EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
	ret = mNextCommandRet;
	require_noerr(ret, on_error);

	if (mScanType == kScanTypeDiscover) {

		// Set `discovery joiner flag`
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_THREAD_DISCOVERY_SCAN_JOINER_FLAG,
			mJoinerFlag
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);

		// Set the `enable-filtering` property
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_THREAD_DISCOVERY_SCAN_ENABLE_FILTERING,
			mEnablerFiltering
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);

		// Set PANID used in Discovery scan for PANID filtering.
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_UINT16_S),
			SPINEL_PROP_THREAD_DISCOVERY_SCAN_PANID,
			mPanId
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);

		// For discovery scan, interface should be up
		if (!ncp_state_is_interface_up(mInstance->get_ncp_state())) {
			mNextCommand = SpinelPackData(
				SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
				SPINEL_PROP_NET_IF_UP,
				true
			);
			EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
			ret = mNextCommandRet;
			require(ret == kWPANTUNDStatus_Ok || ret == kWPANTUNDStatus_Already, on_error);
			mShouldInterfaceDown = true;
		}
	}

	// Set delay period
	mNextCommand = SpinelPackData(
		SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_UINT16_S),
		SPINEL_PROP_MAC_SCAN_PERIOD,
		mScanPeriod
	);
	EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
	ret = mNextCommandRet;
	require_noerr(ret, on_error);

	// Start the scan.
	{
		spinel_scan_state_t scanState;

		if (mScanType == kScanTypeEnergy) {
			scanState = SPINEL_SCAN_STATE_ENERGY;
		} else if (mScanType == kScanTypeDiscover) {
			scanState = SPINEL_SCAN_STATE_DISCOVER;
		} else if (mScanType == kScanTypeNet) {
			scanState = SPINEL_SCAN_STATE_BEACON;
		} else {
			ret = kWPANTUNDStatus_InvalidArgument;
			goto on_error;
		}

		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_UINT8_S),
			SPINEL_PROP_MAC_SCAN_STATE,
			scanState
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require_noerr(ret, on_error);
	}

	do {
		EH_REQUIRE_WITHIN(
			15,
			event == EVENT_NCP_PROP_VALUE_IS
			|| event == EVENT_NCP_PROP_VALUE_INSERTED,
			on_error
		);

		spinel_prop_key_t prop_key = va_arg_small(args, spinel_prop_key_t);
		const uint8_t* data_ptr = va_arg(args, const uint8_t*);
		spinel_size_t data_len = va_arg(args, spinel_size_t);

		if ((prop_key == SPINEL_PROP_MAC_SCAN_BEACON)
		    && ((mScanType == kScanTypeNet) || (mScanType == kScanTypeDiscover))) {
			const spinel_eui64_t* laddr = NULL;
			const char* networkid = "";
			const uint8_t* xpanid = NULL;
			unsigned int xpanid_len = 0;
			unsigned int proto = 0;
			uint16_t panid = 0xFFFF;
			uint16_t saddr = 0xFFFF;
			uint8_t chan = 0;
			uint8_t lqi = 0x00;
			int8_t rssi = 0x00;
			uint8_t flags = 0x00;

			syslog(LOG_DEBUG, "Got a beacon");

			spinel_datatype_unpack(
				data_ptr,
				data_len,
				"Cct(ESSC)t(iCUd)",
				&chan,
				&rssi,

				&laddr,
				&saddr,
				&panid,
				&lqi,

				&proto,
				&flags,
				&networkid,
				&xpanid, &xpanid_len
			);

			if ((xpanid_len != 8) && (xpanid_len != 0)) {
				break;
			}

			WPAN::NetworkInstance network(
				networkid,
				xpanid,
				panid,
				chan,
				(flags & SPINEL_BEACON_THREAD_FLAG_JOINABLE)
			);
			network.rssi = rssi;
			network.type = proto;
			network.lqi = lqi;
			network.saddr = saddr;

			if (laddr) {
				memcpy(network.hwaddr, laddr, sizeof(network.hwaddr));
			}

			mInstance->get_control_interface().mOnNetScanBeacon(network);

		} else if ((prop_key == SPINEL_PROP_MAC_ENERGY_SCAN_RESULT) && (mScanType == kScanTypeEnergy)) {
			EnergyScanResultEntry result;

			syslog(LOG_DEBUG, "Got an Energy Scan result");

			spinel_datatype_unpack(
				data_ptr,
				data_len,
				"Cc",
				&result.mChannel,
				&result.mMaxRssi
			);

			mInstance->get_control_interface().mOnEnergyScanResult(result);

		} else if (prop_key == SPINEL_PROP_MAC_SCAN_STATE) {
			int scan_state;
			spinel_datatype_unpack(data_ptr, data_len, "i", &scan_state);

			if (scan_state == SPINEL_SCAN_STATE_IDLE) {
				break;
			}
		}

		// Change the event type to 'IDLE' so that we
		// don't try to process this event once than once.
		event = EVENT_IDLE;
	} while(true);

	if (mShouldInterfaceDown)
	{
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_NET_IF_UP,
			false
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		ret = mNextCommandRet;
		require(ret == kWPANTUNDStatus_Ok || ret == kWPANTUNDStatus_Already, on_error);
		mShouldInterfaceDown = false;
	}

	finish(ret);

	EH_EXIT();

on_error:

	if (ret == kWPANTUNDStatus_Ok) {
		ret = kWPANTUNDStatus_Failure;
	}

	if (mShouldInterfaceDown)
	{
		mNextCommand = SpinelPackData(
			SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
			SPINEL_PROP_NET_IF_UP,
			false
		);
		EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
		mShouldInterfaceDown = false;
	}

	syslog(LOG_ERR, "Scan failed: %d", ret);

	finish(ret);

	EH_END();
}
<|endoftext|>


<commit_before>// This file is part of RBDyn.
//
// RBDyn is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// RBDyn is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with RBDyn.  If not, see <http://www.gnu.org/licenses/>.

// includes
// std
#include <iostream>

// boost
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JacobianBench
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/timer/timer.hpp>

// RBDyn
#include "FK.h"
#include "FV.h"
#include "Jacobian.h"
#include "MultiBody.h"
#include "MultiBodyConfig.h"
#include "MultiBodyGraph.h"

// Arm
#include "Tree30Dof.h"

BOOST_AUTO_TEST_CASE(Jacobian)
{
	const std::size_t nrIteration = 100000;

	rbd::MultiBody mb;
	rbd::MultiBodyConfig mbc;
	rbd::MultiBodyGraph mbg;
	std::tie(mb, mbc, mbg) = makeTree30Dof(false);

	rbd::Jacobian jac(mb, mbg.bodyIdByName("LARM6"));

	rbd::forwardKinematics(mb, mbc);
	rbd::forwardVelocity(mb, mbc);

	std::cout << "Jacobian::jacobian" << std::endl;
	{
		boost::timer::auto_cpu_timer t;
		for(std::size_t i = 0; i < nrIteration; ++i)
		{
			jac.jacobian(mb, mbc);
		}
	}
	std::cout << std::endl;
}

BOOST_AUTO_TEST_CASE(BodyJacobian)
{
	const std::size_t nrIteration = 100000;

	rbd::MultiBody mb;
	rbd::MultiBodyConfig mbc;
	rbd::MultiBodyGraph mbg;
	std::tie(mb, mbc, mbg) = makeTree30Dof(false);

	rbd::Jacobian jac(mb, mbg.bodyIdByName("LARM6"));

	rbd::forwardKinematics(mb, mbc);
	rbd::forwardVelocity(mb, mbc);

	std::cout << "Jacobian::bodyJacobian" << std::endl;
	{
		boost::timer::auto_cpu_timer t;
		for(std::size_t i = 0; i < nrIteration; ++i)
		{
			jac.bodyJacobian(mb, mbc);
		}
	}
	std::cout << std::endl;
}
<commit_msg>Add a bench to Jacobian::vectorBodyJacobian.<commit_after>// This file is part of RBDyn.
//
// RBDyn is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// RBDyn is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with RBDyn.  If not, see <http://www.gnu.org/licenses/>.

// includes
// std
#include <iostream>

// boost
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JacobianBench
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/timer/timer.hpp>

// RBDyn
#include "FK.h"
#include "FV.h"
#include "Jacobian.h"
#include "MultiBody.h"
#include "MultiBodyConfig.h"
#include "MultiBodyGraph.h"

// Arm
#include "Tree30Dof.h"

BOOST_AUTO_TEST_CASE(Jacobian)
{
	const std::size_t nrIteration = 100000;

	rbd::MultiBody mb;
	rbd::MultiBodyConfig mbc;
	rbd::MultiBodyGraph mbg;
	std::tie(mb, mbc, mbg) = makeTree30Dof(false);

	rbd::Jacobian jac(mb, mbg.bodyIdByName("LARM6"));

	rbd::forwardKinematics(mb, mbc);
	rbd::forwardVelocity(mb, mbc);

	std::cout << "Jacobian::jacobian" << std::endl;
	{
		boost::timer::auto_cpu_timer t;
		for(std::size_t i = 0; i < nrIteration; ++i)
		{
			jac.jacobian(mb, mbc);
		}
	}
	std::cout << std::endl;
}

BOOST_AUTO_TEST_CASE(BodyJacobian)
{
	const std::size_t nrIteration = 100000;

	rbd::MultiBody mb;
	rbd::MultiBodyConfig mbc;
	rbd::MultiBodyGraph mbg;
	std::tie(mb, mbc, mbg) = makeTree30Dof(false);

	rbd::Jacobian jac(mb, mbg.bodyIdByName("LARM6"));

	rbd::forwardKinematics(mb, mbc);
	rbd::forwardVelocity(mb, mbc);

	std::cout << "Jacobian::bodyJacobian" << std::endl;
	{
		boost::timer::auto_cpu_timer t;
		for(std::size_t i = 0; i < nrIteration; ++i)
		{
			jac.bodyJacobian(mb, mbc);
		}
	}
	std::cout << std::endl;
}

BOOST_AUTO_TEST_CASE(VectorBodyJacobian)
{
	const std::size_t nrIteration = 100000;

	rbd::MultiBody mb;
	rbd::MultiBodyConfig mbc;
	rbd::MultiBodyGraph mbg;
	std::tie(mb, mbc, mbg) = makeTree30Dof(false);

	rbd::Jacobian jac(mb, mbg.bodyIdByName("LARM6"));

	rbd::forwardKinematics(mb, mbc);
	rbd::forwardVelocity(mb, mbc);

	std::cout << "Jacobian::vectorBodyJacobian" << std::endl;
	{
		boost::timer::auto_cpu_timer t;
		for(std::size_t i = 0; i < nrIteration; ++i)
		{
			jac.vectorBodyJacobian(mb, mbc, Eigen::Vector3d(1., 0., 0.));
		}
	}
	std::cout << std::endl;
}
<|endoftext|>