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

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  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.commontk.org/LICENSE

  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.

=========================================================================*/
/*=========================================================================

   Program: ParaView
   Module:    $RCSfile$

   Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
   All rights reserved.

   ParaView is a free software; you can redistribute it and/or modify it
   under the terms of the ParaView license version 1.2.

   See License_v1.2.txt for the full ParaView license.
   A copy of this license can be obtained by contacting
   Kitware Inc.
   28 Corporate Drive
   Clifton Park, NY 12065
   USA

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

//#include <vtkPython.h> // python first

// Qt includes
#include <QCoreApplication>
#include <QResizeEvent>
#include <QScrollBar>
#include <QStringListModel>
#include <QTextCharFormat>
#include <QVBoxLayout>

// PythonQt includes
#include <PythonQt.h>
#include <PythonQtObjectPtr.h>

// CTK includes
#include <ctkConsoleWidget.h>
#include <ctkAbstractPythonManager.h>
#include "ctkPythonShell.h"

//----------------------------------------------------------------------------
class ctkPythonShellCompleter : public ctkConsoleWidgetCompleter
{
public:
  ctkPythonShellCompleter(ctkPythonShell& p) : Parent(p)
    {
    this->setParent(&p);
    }

  virtual void updateCompletionModel(const QString& completion)
    {
    // Start by clearing the model
    this->setModel(0);

    // Don't try to complete the empty string
    if (completion.isEmpty())
      {
      return;
      }

    // Search backward through the string for usable characters
    QString textToComplete;
    for (int i = completion.length()-1; i >= 0; --i)
      {
      QChar c = completion.at(i);
      if (c.isLetterOrNumber() || c == '.' || c == '_')
        {
        textToComplete.prepend(c);
        }
      else
        {
        break;
        }
      }

    // Split the string at the last dot, if one exists
    QString lookup;
    QString compareText = textToComplete;
    int dot = compareText.lastIndexOf('.');
    if (dot != -1)
      {
      lookup = compareText.mid(0, dot);
      compareText = compareText.mid(dot+1);
      }

    // Lookup python names
    QStringList attrs;
    if (!lookup.isEmpty() || !compareText.isEmpty())
      {
      attrs = Parent.getPythonAttributes(lookup);
      }

    // Initialize the completion model
    if (!attrs.isEmpty())
      {
      this->setCompletionMode(QCompleter::PopupCompletion);
      this->setModel(new QStringListModel(attrs, this));
      this->setCaseSensitivity(Qt::CaseInsensitive);
      this->setCompletionPrefix(compareText.toLower());
      this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));
      }
    }
  ctkPythonShell& Parent;
};

/////////////////////////////////////////////////////////////////////////
// ctkPythonShell::pqImplementation

struct ctkPythonShell::pqImplementation
{
  pqImplementation(QWidget* _parent, ctkAbstractPythonManager* pythonManager)
    : Console(_parent), PythonManager(pythonManager)
  {
  }

//----------------------------------------------------------------------------
//   void initialize(int argc, char* argv[])
//   {
//     // Setup Python's interactive prompts
//     PyObject* ps1 = PySys_GetObject(const_cast<char*>("ps1"));
//     if(!ps1)
//       {
//       PySys_SetObject(const_cast<char*>("ps1"), ps1 = PyString_FromString(">>> "));
//       Py_XDECREF(ps1);
//       }
//
//     PyObject* ps2 = PySys_GetObject(const_cast<char*>("ps2"));
//     if(!ps2)
//       {
//       PySys_SetObject(const_cast<char*>("ps2"), ps2 = PyString_FromString("... "));
//       Py_XDECREF(ps2);
//       }
//     this->MultilineStatement = false;
//   }

//----------------------------------------------------------------------------
  ~pqImplementation()
  {
//     this->destroyInterpretor();
  }

//----------------------------------------------------------------------------
//   void destroyInterpretor()
//     {
//     if (this->Interpreter)
//       {
//       QTextCharFormat format = this->Console.getFormat();
//       format.setForeground(QColor(255, 0, 0));
//       this->Console.setFormat(format);
//       this->Console.printString("\n... restarting ...\n");
//       format.setForeground(QColor(0, 0, 0));
//       this->Console.setFormat(format);
//
//       this->Interpreter->MakeCurrent();
//
//       // Restore Python's original stdout and stderr
//       PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));
//       PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));
//       this->Interpreter->ReleaseControl();
//       this->Interpreter->Delete();
//       }
//     this->Interpreter = 0;
//     }

//----------------------------------------------------------------------------
  void executeCommand(const QString& command)
  {
//     this->MultilineStatement =
//       this->Interpreter->Push(Command.toAscii().data());
    if (command.length())
      {
      Q_ASSERT(this->PythonManager);
      this->PythonManager->executeString(command);
      }
  }

//----------------------------------------------------------------------------
  void promptForInput(const QString& indent=QString())
  {
    QTextCharFormat format = this->Console.getFormat();
    format.setForeground(QColor(0, 0, 0));
    this->Console.setFormat(format);

//     this->Interpreter->MakeCurrent();
    if(!this->MultilineStatement)
      {
      this->Console.prompt(">>> ");
      //this->Console.prompt(
      //  PyString_AsString(PySys_GetObject(const_cast<char*>("ps1"))));
      }
    else
      {
      this->Console.prompt("... ");
      //this->Console.prompt(
      //  PyString_AsString(PySys_GetObject(const_cast<char*>("ps2"))));
      }
    this->Console.printCommand(indent);
//     this->Interpreter->ReleaseControl();
  }

  /// Provides a console for gathering user input and displaying
  /// Python output
  ctkConsoleWidget Console;

  ctkAbstractPythonManager* PythonManager;

  /// Indicates if the last statement processes was incomplete.
  bool MultilineStatement;
};

/////////////////////////////////////////////////////////////////////////
// ctkPythonShell

//----------------------------------------------------------------------------
ctkPythonShell::ctkPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent):
  Superclass(_parent),
  Implementation(new pqImplementation(this, pythonManager))
{
  // Layout UI
  QVBoxLayout* const boxLayout = new QVBoxLayout(this);
  boxLayout->setMargin(0);
  boxLayout->addWidget(&this->Implementation->Console);

  this->setObjectName("pythonShell");

  ctkPythonShellCompleter* completer = new ctkPythonShellCompleter(*this);
  this->Implementation->Console.setCompleter(completer);

  QObject::connect(
    &this->Implementation->Console, SIGNAL(executeCommand(const QString&)),
    this, SLOT(onExecuteCommand(const QString&)));

  // The call to mainContext() ensures that python has been initialized.
  Q_ASSERT(this->Implementation->PythonManager);
  this->Implementation->PythonManager->mainContext();

  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(0, 0, 255));
  this->Implementation->Console.setFormat(format);
  this->Implementation->Console.printString(
    QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()));
  this->promptForInput();

  Q_ASSERT(PythonQt::self());

  this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
                SLOT(printStdout(const QString&)));
  this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
                SLOT(printStderr(const QString&)));
}

//----------------------------------------------------------------------------
ctkPythonShell::~ctkPythonShell()
{
  delete this->Implementation;
}

//----------------------------------------------------------------------------
void ctkPythonShell::clear()
{
  this->Implementation->Console.clear();
  this->Implementation->promptForInput();
}

// //----------------------------------------------------------------------------
// void ctkPythonShell::makeCurrent()
// {
//   this->Implementation->Interpreter->MakeCurrent();
// }
//
// //----------------------------------------------------------------------------
// void ctkPythonShell::releaseControl()
// {
//   this->Implementation->Interpreter->ReleaseControl();
// }

//----------------------------------------------------------------------------
void ctkPythonShell::executeScript(const QString& script)
{
  Q_UNUSED(script);

  this->printStdout("\n");
  emit this->executing(true);
//   this->Implementation->Interpreter->RunSimpleString(
//     script.toAscii().data());
  emit this->executing(false);
  this->Implementation->promptForInput();
}

//----------------------------------------------------------------------------
QStringList ctkPythonShell::getPythonAttributes(const QString& pythonVariableName)
{
//   this->makeCurrent();

  Q_ASSERT(PyThreadState_GET()->interp);
  PyObject* dict = PyImport_GetModuleDict();
  PyObject* object = PyDict_GetItemString(dict, "__main__");
  Py_INCREF(object);

  if (!pythonVariableName.isEmpty())
    {
    QStringList tmpNames = pythonVariableName.split('.');
    for (int i = 0; i < tmpNames.size() && object; ++i)
      {
      QByteArray tmpName = tmpNames.at(i).toLatin1();
      PyObject* prevObj = object;
      if (PyDict_Check(object))
        {
        object = PyDict_GetItemString(object, tmpName.data());
        Py_XINCREF(object);
        }
      else
        {
        object = PyObject_GetAttrString(object, tmpName.data());
        }
      Py_DECREF(prevObj);
      }
    PyErr_Clear();
    }

  QStringList results;
  if (object)
    {
    PyObject* keys = PyObject_Dir(object);
    if (keys)
      {
      PyObject* key;
      PyObject* value;
      QString keystr;
      int nKeys = PyList_Size(keys);
      for (int i = 0; i < nKeys; ++i)
        {
        key = PyList_GetItem(keys, i);
        value = PyObject_GetAttr(object, key);
        if (!value)
          {
          continue;
          }

        results << PyString_AsString(key);
        Py_DECREF(value);
        }
      Py_DECREF(keys);
      }
    Py_DECREF(object);
    }

//   this->releaseControl();
  return results;
}

//----------------------------------------------------------------------------
void ctkPythonShell::printStdout(const QString& text)
{
  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(0, 150, 0));
  this->Implementation->Console.setFormat(format);

  this->Implementation->Console.printString(text);

  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}

//----------------------------------------------------------------------------
void ctkPythonShell::printMessage(const QString& text)
{
  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(0, 0, 150));
  this->Implementation->Console.setFormat(format);

  this->Implementation->Console.printString(text);
}

//----------------------------------------------------------------------------
void ctkPythonShell::printStderr(const QString& text)
{
  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(255, 0, 0));
  this->Implementation->Console.setFormat(format);

  this->Implementation->Console.printString(text);

  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}

//----------------------------------------------------------------------------
void ctkPythonShell::onExecuteCommand(const QString& Command)
{
  QString command = Command;
  command.replace(QRegExp("\\s*$"), "");
  this->internalExecuteCommand(command);

  // Find the indent for the command.
  QRegExp regExp("^(\\s+)");
  QString indent;
  if (regExp.indexIn(command) != -1)
    {
    indent = regExp.cap(1);
    }
  this->Implementation->promptForInput(indent);
}

//----------------------------------------------------------------------------
void ctkPythonShell::promptForInput()
{
  this->Implementation->promptForInput();
}

//----------------------------------------------------------------------------
void ctkPythonShell::internalExecuteCommand(const QString& command)
{
  emit this->executing(true);
  this->Implementation->executeCommand(command);
  emit this->executing(false);
}
<commit_msg>COMP: Use "pragma GCC diagnostic ignored" trick to shut up python old-style-cast warnings<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  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.commontk.org/LICENSE

  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.

=========================================================================*/
/*=========================================================================

   Program: ParaView
   Module:    $RCSfile$

   Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
   All rights reserved.

   ParaView is a free software; you can redistribute it and/or modify it
   under the terms of the ParaView license version 1.2.

   See License_v1.2.txt for the full ParaView license.
   A copy of this license can be obtained by contacting
   Kitware Inc.
   28 Corporate Drive
   Clifton Park, NY 12065
   USA

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

//#include <vtkPython.h> // python first

// Qt includes
#include <QCoreApplication>
#include <QResizeEvent>
#include <QScrollBar>
#include <QStringListModel>
#include <QTextCharFormat>
#include <QVBoxLayout>

// PythonQt includes
#include <PythonQt.h>
#include <PythonQtObjectPtr.h>

// CTK includes
#include <ctkConsoleWidget.h>
#include <ctkAbstractPythonManager.h>
#include "ctkPythonShell.h"

// Disable warnings related to Python macros and functions
// See http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
// Note: Ideally the incriminated functions and macros should be fixed upstream ...
#pragma GCC diagnostic ignored "-Wold-style-cast"

//----------------------------------------------------------------------------
class ctkPythonShellCompleter : public ctkConsoleWidgetCompleter
{
public:
  ctkPythonShellCompleter(ctkPythonShell& p) : Parent(p)
    {
    this->setParent(&p);
    }

  virtual void updateCompletionModel(const QString& completion)
    {
    // Start by clearing the model
    this->setModel(0);

    // Don't try to complete the empty string
    if (completion.isEmpty())
      {
      return;
      }

    // Search backward through the string for usable characters
    QString textToComplete;
    for (int i = completion.length()-1; i >= 0; --i)
      {
      QChar c = completion.at(i);
      if (c.isLetterOrNumber() || c == '.' || c == '_')
        {
        textToComplete.prepend(c);
        }
      else
        {
        break;
        }
      }

    // Split the string at the last dot, if one exists
    QString lookup;
    QString compareText = textToComplete;
    int dot = compareText.lastIndexOf('.');
    if (dot != -1)
      {
      lookup = compareText.mid(0, dot);
      compareText = compareText.mid(dot+1);
      }

    // Lookup python names
    QStringList attrs;
    if (!lookup.isEmpty() || !compareText.isEmpty())
      {
      attrs = Parent.getPythonAttributes(lookup);
      }

    // Initialize the completion model
    if (!attrs.isEmpty())
      {
      this->setCompletionMode(QCompleter::PopupCompletion);
      this->setModel(new QStringListModel(attrs, this));
      this->setCaseSensitivity(Qt::CaseInsensitive);
      this->setCompletionPrefix(compareText.toLower());
      this->popup()->setCurrentIndex(this->completionModel()->index(0, 0));
      }
    }
  ctkPythonShell& Parent;
};

/////////////////////////////////////////////////////////////////////////
// ctkPythonShell::pqImplementation

struct ctkPythonShell::pqImplementation
{
  pqImplementation(QWidget* _parent, ctkAbstractPythonManager* pythonManager)
    : Console(_parent), PythonManager(pythonManager)
  {
  }

//----------------------------------------------------------------------------
//   void initialize(int argc, char* argv[])
//   {
//     // Setup Python's interactive prompts
//     PyObject* ps1 = PySys_GetObject(const_cast<char*>("ps1"));
//     if(!ps1)
//       {
//       PySys_SetObject(const_cast<char*>("ps1"), ps1 = PyString_FromString(">>> "));
//       Py_XDECREF(ps1);
//       }
//
//     PyObject* ps2 = PySys_GetObject(const_cast<char*>("ps2"));
//     if(!ps2)
//       {
//       PySys_SetObject(const_cast<char*>("ps2"), ps2 = PyString_FromString("... "));
//       Py_XDECREF(ps2);
//       }
//     this->MultilineStatement = false;
//   }

//----------------------------------------------------------------------------
  ~pqImplementation()
  {
//     this->destroyInterpretor();
  }

//----------------------------------------------------------------------------
//   void destroyInterpretor()
//     {
//     if (this->Interpreter)
//       {
//       QTextCharFormat format = this->Console.getFormat();
//       format.setForeground(QColor(255, 0, 0));
//       this->Console.setFormat(format);
//       this->Console.printString("\n... restarting ...\n");
//       format.setForeground(QColor(0, 0, 0));
//       this->Console.setFormat(format);
//
//       this->Interpreter->MakeCurrent();
//
//       // Restore Python's original stdout and stderr
//       PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));
//       PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));
//       this->Interpreter->ReleaseControl();
//       this->Interpreter->Delete();
//       }
//     this->Interpreter = 0;
//     }

//----------------------------------------------------------------------------
  void executeCommand(const QString& command)
  {
//     this->MultilineStatement =
//       this->Interpreter->Push(Command.toAscii().data());
    if (command.length())
      {
      Q_ASSERT(this->PythonManager);
      this->PythonManager->executeString(command);
      }
  }

//----------------------------------------------------------------------------
  void promptForInput(const QString& indent=QString())
  {
    QTextCharFormat format = this->Console.getFormat();
    format.setForeground(QColor(0, 0, 0));
    this->Console.setFormat(format);

//     this->Interpreter->MakeCurrent();
    if(!this->MultilineStatement)
      {
      this->Console.prompt(">>> ");
      //this->Console.prompt(
      //  PyString_AsString(PySys_GetObject(const_cast<char*>("ps1"))));
      }
    else
      {
      this->Console.prompt("... ");
      //this->Console.prompt(
      //  PyString_AsString(PySys_GetObject(const_cast<char*>("ps2"))));
      }
    this->Console.printCommand(indent);
//     this->Interpreter->ReleaseControl();
  }

  /// Provides a console for gathering user input and displaying
  /// Python output
  ctkConsoleWidget Console;

  ctkAbstractPythonManager* PythonManager;

  /// Indicates if the last statement processes was incomplete.
  bool MultilineStatement;
};

/////////////////////////////////////////////////////////////////////////
// ctkPythonShell

//----------------------------------------------------------------------------
ctkPythonShell::ctkPythonShell(ctkAbstractPythonManager* pythonManager, QWidget* _parent):
  Superclass(_parent),
  Implementation(new pqImplementation(this, pythonManager))
{
  // Layout UI
  QVBoxLayout* const boxLayout = new QVBoxLayout(this);
  boxLayout->setMargin(0);
  boxLayout->addWidget(&this->Implementation->Console);

  this->setObjectName("pythonShell");

  ctkPythonShellCompleter* completer = new ctkPythonShellCompleter(*this);
  this->Implementation->Console.setCompleter(completer);

  QObject::connect(
    &this->Implementation->Console, SIGNAL(executeCommand(const QString&)),
    this, SLOT(onExecuteCommand(const QString&)));

  // The call to mainContext() ensures that python has been initialized.
  Q_ASSERT(this->Implementation->PythonManager);
  this->Implementation->PythonManager->mainContext();

  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(0, 0, 255));
  this->Implementation->Console.setFormat(format);
  this->Implementation->Console.printString(
    QString("Python %1 on %2\n").arg(Py_GetVersion()).arg(Py_GetPlatform()));
  this->promptForInput();

  Q_ASSERT(PythonQt::self());

  this->connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)),
                SLOT(printStdout(const QString&)));
  this->connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString&)),
                SLOT(printStderr(const QString&)));
}

//----------------------------------------------------------------------------
ctkPythonShell::~ctkPythonShell()
{
  delete this->Implementation;
}

//----------------------------------------------------------------------------
void ctkPythonShell::clear()
{
  this->Implementation->Console.clear();
  this->Implementation->promptForInput();
}

// //----------------------------------------------------------------------------
// void ctkPythonShell::makeCurrent()
// {
//   this->Implementation->Interpreter->MakeCurrent();
// }
//
// //----------------------------------------------------------------------------
// void ctkPythonShell::releaseControl()
// {
//   this->Implementation->Interpreter->ReleaseControl();
// }

//----------------------------------------------------------------------------
void ctkPythonShell::executeScript(const QString& script)
{
  Q_UNUSED(script);

  this->printStdout("\n");
  emit this->executing(true);
//   this->Implementation->Interpreter->RunSimpleString(
//     script.toAscii().data());
  emit this->executing(false);
  this->Implementation->promptForInput();
}

//----------------------------------------------------------------------------
QStringList ctkPythonShell::getPythonAttributes(const QString& pythonVariableName)
{
//   this->makeCurrent();

  Q_ASSERT(PyThreadState_GET()->interp);
  PyObject* dict = PyImport_GetModuleDict();
  PyObject* object = PyDict_GetItemString(dict, "__main__");
  Py_INCREF(object);

  if (!pythonVariableName.isEmpty())
    {
    QStringList tmpNames = pythonVariableName.split('.');
    for (int i = 0; i < tmpNames.size() && object; ++i)
      {
      QByteArray tmpName = tmpNames.at(i).toLatin1();
      PyObject* prevObj = object;
      if (PyDict_Check(object))
        {
        object = PyDict_GetItemString(object, tmpName.data());
        Py_XINCREF(object);
        }
      else
        {
        object = PyObject_GetAttrString(object, tmpName.data());
        }
      Py_DECREF(prevObj);
      }
    PyErr_Clear();
    }

  QStringList results;
  if (object)
    {
    PyObject* keys = PyObject_Dir(object);
    if (keys)
      {
      PyObject* key;
      PyObject* value;
      QString keystr;
      int nKeys = PyList_Size(keys);
      for (int i = 0; i < nKeys; ++i)
        {
        key = PyList_GetItem(keys, i);
        value = PyObject_GetAttr(object, key);
        if (!value)
          {
          continue;
          }

        results << PyString_AsString(key);
        Py_DECREF(value);
        }
      Py_DECREF(keys);
      }
    Py_DECREF(object);
    }

//   this->releaseControl();
  return results;
}

//----------------------------------------------------------------------------
void ctkPythonShell::printStdout(const QString& text)
{
  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(0, 150, 0));
  this->Implementation->Console.setFormat(format);

  this->Implementation->Console.printString(text);

  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}

//----------------------------------------------------------------------------
void ctkPythonShell::printMessage(const QString& text)
{
  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(0, 0, 150));
  this->Implementation->Console.setFormat(format);

  this->Implementation->Console.printString(text);
}

//----------------------------------------------------------------------------
void ctkPythonShell::printStderr(const QString& text)
{
  QTextCharFormat format = this->Implementation->Console.getFormat();
  format.setForeground(QColor(255, 0, 0));
  this->Implementation->Console.setFormat(format);

  this->Implementation->Console.printString(text);

  QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}

//----------------------------------------------------------------------------
void ctkPythonShell::onExecuteCommand(const QString& Command)
{
  QString command = Command;
  command.replace(QRegExp("\\s*$"), "");
  this->internalExecuteCommand(command);

  // Find the indent for the command.
  QRegExp regExp("^(\\s+)");
  QString indent;
  if (regExp.indexIn(command) != -1)
    {
    indent = regExp.cap(1);
    }
  this->Implementation->promptForInput(indent);
}

//----------------------------------------------------------------------------
void ctkPythonShell::promptForInput()
{
  this->Implementation->promptForInput();
}

//----------------------------------------------------------------------------
void ctkPythonShell::internalExecuteCommand(const QString& command)
{
  emit this->executing(true);
  this->Implementation->executeCommand(command);
  emit this->executing(false);
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkResourceProbe_hxx
#define itkResourceProbe_hxx

#include <numeric>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <functional>

#include "itkResourceProbe.h"
#include "itkNumericTraits.h"
#include "itkMultiThreader.h"
#include "itksys/SystemInformation.hxx"

namespace itk
{

template< typename ValueType, typename MeanType >
ResourceProbe< ValueType, MeanType >
::ResourceProbe(const std::string & type, const std::string & unit):
  m_TypeString(type), m_UnitString(unit)
{
  this->GetSystemInformation();
  this->Reset();
}

template< typename ValueType, typename MeanType >
ResourceProbe< ValueType, MeanType >
::~ResourceProbe()
{}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Reset(void)
{
  this->m_TotalValue        = NumericTraits< ValueType >::ZeroValue();
  this->m_StartValue        = NumericTraits< ValueType >::ZeroValue();
  this->m_MinimumValue      = NumericTraits< ValueType >::max();
  this->m_MaximumValue      = NumericTraits< ValueType >::min();
  this->m_MeanValue         = NumericTraits< ValueType >::ZeroValue();
  this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();

  this->m_NumberOfStarts    = NumericTraits< CountType >::ZeroValue();
  this->m_NumberOfStops     = NumericTraits< CountType >::ZeroValue();
  this->m_NumberOfIteration = NumericTraits< CountType >::ZeroValue();

  this->m_ProbeValueList.clear();
}

template< typename ValueType, typename MeanType >
std::string
ResourceProbe< ValueType, MeanType >
::GetType(void) const
{
  return this->m_TypeString;
}

template< typename ValueType, typename MeanType >
std::string
ResourceProbe< ValueType, MeanType >
::GetUnit(void) const
{
  return this->m_UnitString;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Start(void)
{
  this->m_NumberOfStarts++;
  this->m_StartValue = this->GetInstantValue();
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Stop(void)
{
  ValueType probevalue = this->GetInstantValue() - this->m_StartValue;
  if ( this->m_NumberOfStops == this->m_NumberOfStarts )
    {
    return;
    }

  this->UpdateMinimumMaximumMeasuredValue(probevalue);
  this->m_TotalValue += probevalue;
  this->m_ProbeValueList.push_back(probevalue);
  this->m_NumberOfStops++;
  this->m_NumberOfIteration = static_cast<CountType>(this->m_ProbeValueList.size());
}

template< typename ValueType, typename MeanType >
typename ResourceProbe< ValueType, MeanType >::CountType
ResourceProbe< ValueType, MeanType >
::GetNumberOfStarts(void) const
{
  return this->m_NumberOfStarts;
}

template< typename ValueType, typename MeanType >
typename ResourceProbe< ValueType, MeanType >::CountType
ResourceProbe< ValueType, MeanType >
::GetNumberOfStops(void) const
{
  return this->m_NumberOfStops;
}

template< typename ValueType, typename MeanType >
typename ResourceProbe< ValueType, MeanType >::CountType
ResourceProbe< ValueType, MeanType >
::GetNumberOfIteration(void) const
{
  return this->m_NumberOfIteration;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetTotal(void) const
{
  return this->m_TotalValue;
}

template< typename ValueType, typename MeanType >
MeanType
ResourceProbe< ValueType, MeanType >
::GetMean(void) const
{
  MeanType meanValue = NumericTraits< MeanType >::ZeroValue();

  if ( this->m_NumberOfStops )
    {
    meanValue = static_cast< MeanType >( this->m_TotalValue ) / static_cast< MeanType >( this->m_NumberOfStops );
    }

  return meanValue;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetMinimum() const
{
  return this->m_MinimumValue;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetMaximum() const
{
  return this->m_MaximumValue;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetStandardDeviation()
{
  this->m_MeanValue = this->GetMean();
  std::vector<ValueType> diff(this->m_ProbeValueList.size());
  std::transform(this->m_ProbeValueList.begin(),
                 this->m_ProbeValueList.end(),
                 diff.begin(),
                 std::bind2nd(std::minus<ValueType>(),
                              this->m_MeanValue ));
  ValueType sq_sum =
    std::inner_product(diff.begin(),diff.end(),
                       diff.begin(),
                       0.0);

  int sz = this->m_ProbeValueList.size()-1;
  if (sz <=0)
    {
    this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();
    }
  else
    {
    this->m_StandardDeviation =
      std::sqrt(sq_sum /
               (static_cast<ValueType>(sz)));
    }
  return this->m_StandardDeviation;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::SetNameOfProbe(const char* nameOfProbe)
{
  this->m_NameOfProbe = nameOfProbe;
}

template< typename ValueType, typename MeanType >
std::string
ResourceProbe< ValueType, MeanType >
::GetNameOfProbe() const
{
  return this->m_NameOfProbe;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::PrintSystemInformation(std::ostream & os)
{
  os << "System:              " << m_SystemName << std::endl;
  os << "Processor:           " << m_ProcessorName << std::endl;
  os << "    Cache:           " << m_ProcessorCacheSize << std::endl;
  os << "    Clock:           " << m_ProcessorClockFrequency << std::endl;
  os << "    Cores:           " << m_NumberOfPhysicalCPU
     << " cpus x " << m_NumberOfLogicalCPU
     << " Cores = "<< m_NumberOfAvailableCore << std::endl;
  // Retrieve memory information in megabyte.
  os << "    Virtual Memory:  Total: "
     << m_TotalVirtualMemory
     <<" Available: "<< m_AvailableVirtualMemory << std::endl;
  os << "    Physical Memory: Total:"
     << m_TotalPhysicalMemory
     <<" Available: "<< m_AvailablePhysicalMemory << std::endl;

  os << "OSName:              "<< m_OSName << std::endl;
  os << "    Release:         "<< m_OSRelease << std::endl;
  os << "    Version:         "<< m_OSVersion << std::endl;
  os << "    Platform:        "<< m_OSPlatform << std::endl;

  os << "    Operating System is "
     << (m_Is64Bits?"64 bit":"32 bit") << std::endl;

  os << "ITK Version: "
     << m_ITKVersion << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Report(std::ostream & os, bool printSystemInfo, bool printReportHead )
{
  if(printSystemInfo)
    {
    this->PrintSystemInformation(os);
    }

  if(printReportHead)
    {
    this->PrintReportHead(os);
    }

  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe
     << std::left << std::setw( tabwidth    ) << this->m_NumberOfIteration
     << std::left << std::setw( tabwidth    ) << this->GetTotal()
     << std::left << std::setw( tabwidth    ) << this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << this->GetMean()
     << std::left << std::setw( tabwidth    ) << this->GetMaximum()
     << std::left << std::setw( tabwidth    ) << this->GetStandardDeviation();
  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::ExpandedReport(std::ostream & os, bool printSystemInfo, bool printReportHead )
{
  if(printSystemInfo)
    {
    this->PrintSystemInformation(os);
    }

  if(printReportHead)
    {
    this->PrintExpandedReportHead(os);
    }

  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe
     << std::left << std::setw( tabwidth    ) << this->m_NumberOfIteration
     << std::left << std::setw( tabwidth    ) << this->GetTotal()
     << std::left << std::setw( tabwidth    ) << this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << this->GetMean() - this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << (this->GetMean()/this->GetMinimum())*100
     << std::left << std::setw( tabwidth    ) << this->GetMean()
     << std::left << std::setw( tabwidth    ) << this->GetMaximum() - this->GetMean()
     << std::left << std::setw( tabwidth    ) << (this->GetMaximum()/this->GetMean())*100
     << std::left << std::setw( tabwidth    ) << this->GetMaximum()
     << std::left << std::setw( tabwidth    ) << this->GetMaximum() - this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << this->GetStandardDeviation();
  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::UpdateMinimumMaximumMeasuredValue(ValueType value)
{
  if(this->m_MinimumValue > value)
    {
    this->m_MinimumValue = value;
    }

  if(this->m_MaximumValue < value)
    {
    this->m_MaximumValue = value;
    }
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::PrintReportHead(std::ostream & os)
{
  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << std::string("Name Of Probe(")+this->m_TypeString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Iteration"
     << std::left << std::setw( tabwidth    ) << std::string("Total(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Min(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Mean(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Max(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Std(") + this->m_UnitString + std::string(")");

  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::PrintExpandedReportHead(std::ostream & os)
{
  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << std::string("Name Of Probe(") + this->m_TypeString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Iteration"
     << std::left << std::setw( tabwidth    ) << std::string("Total(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Min(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Mean-Min(diff)"
     << std::left << std::setw( tabwidth    ) << "Mean/Min(%)"
     << std::left << std::setw( tabwidth    ) << std::string("Mean(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Max-Mean(diff)"
     << std::left << std::setw( tabwidth    ) << "Max/Mean(%)"
     << std::left << std::setw( tabwidth    ) << std::string("Max(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Total Diff(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Std(") + this->m_UnitString + std::string(")");

  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::GetSystemInformation()
{
  itksys::SystemInformation systeminfo;
  systeminfo.RunCPUCheck();
  systeminfo.RunMemoryCheck();
  systeminfo.RunOSCheck();

  m_SystemName              = systeminfo.GetHostname();
  m_ProcessorName           = systeminfo.GetExtendedProcessorName();
  m_ProcessorCacheSize      = systeminfo.GetProcessorCacheSize();
  m_ProcessorClockFrequency = systeminfo.GetProcessorClockFrequency();
  m_NumberOfPhysicalCPU     = systeminfo.GetNumberOfPhysicalCPU();
  m_NumberOfLogicalCPU      = systeminfo.GetNumberOfLogicalCPU();
  m_NumberOfAvailableCore   = m_NumberOfPhysicalCPU*m_NumberOfLogicalCPU;

  m_OSName                  = systeminfo.GetOSName();
  m_OSRelease               = systeminfo.GetOSRelease();
  m_OSVersion               = systeminfo.GetOSVersion();
  m_OSPlatform              = systeminfo.GetOSPlatform();

  m_Is64Bits                = systeminfo.Is64Bits();
  std::ostringstream        itkversion;
  itkversion << ITK_VERSION_MAJOR << "." << ITK_VERSION_MINOR << "." << ITK_VERSION_PATCH;
  m_ITKVersion              = itkversion.str();

 // Retrieve memory information in megabyte.
  m_TotalVirtualMemory      = systeminfo.GetTotalVirtualMemory();
  m_AvailableVirtualMemory  = systeminfo.GetAvailableVirtualMemory();
  m_TotalPhysicalMemory     = systeminfo.GetTotalPhysicalMemory();
  m_AvailablePhysicalMemory = systeminfo.GetAvailablePhysicalMemory();
}

} // end namespace itk

#endif
<commit_msg>COMP: Fixed 'std::sqrt' : ambiguous call to overloaded function<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkResourceProbe_hxx
#define itkResourceProbe_hxx

#include <numeric>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <functional>

#include "itkResourceProbe.h"
#include "itkNumericTraits.h"
#include "itkMultiThreader.h"
#include "itksys/SystemInformation.hxx"

namespace itk
{

template< typename ValueType, typename MeanType >
ResourceProbe< ValueType, MeanType >
::ResourceProbe(const std::string & type, const std::string & unit):
  m_TypeString(type), m_UnitString(unit)
{
  this->GetSystemInformation();
  this->Reset();
}

template< typename ValueType, typename MeanType >
ResourceProbe< ValueType, MeanType >
::~ResourceProbe()
{}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Reset(void)
{
  this->m_TotalValue        = NumericTraits< ValueType >::ZeroValue();
  this->m_StartValue        = NumericTraits< ValueType >::ZeroValue();
  this->m_MinimumValue      = NumericTraits< ValueType >::max();
  this->m_MaximumValue      = NumericTraits< ValueType >::min();
  this->m_MeanValue         = NumericTraits< ValueType >::ZeroValue();
  this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();

  this->m_NumberOfStarts    = NumericTraits< CountType >::ZeroValue();
  this->m_NumberOfStops     = NumericTraits< CountType >::ZeroValue();
  this->m_NumberOfIteration = NumericTraits< CountType >::ZeroValue();

  this->m_ProbeValueList.clear();
}

template< typename ValueType, typename MeanType >
std::string
ResourceProbe< ValueType, MeanType >
::GetType(void) const
{
  return this->m_TypeString;
}

template< typename ValueType, typename MeanType >
std::string
ResourceProbe< ValueType, MeanType >
::GetUnit(void) const
{
  return this->m_UnitString;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Start(void)
{
  this->m_NumberOfStarts++;
  this->m_StartValue = this->GetInstantValue();
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Stop(void)
{
  ValueType probevalue = this->GetInstantValue() - this->m_StartValue;
  if ( this->m_NumberOfStops == this->m_NumberOfStarts )
    {
    return;
    }

  this->UpdateMinimumMaximumMeasuredValue(probevalue);
  this->m_TotalValue += probevalue;
  this->m_ProbeValueList.push_back(probevalue);
  this->m_NumberOfStops++;
  this->m_NumberOfIteration = static_cast<CountType>(this->m_ProbeValueList.size());
}

template< typename ValueType, typename MeanType >
typename ResourceProbe< ValueType, MeanType >::CountType
ResourceProbe< ValueType, MeanType >
::GetNumberOfStarts(void) const
{
  return this->m_NumberOfStarts;
}

template< typename ValueType, typename MeanType >
typename ResourceProbe< ValueType, MeanType >::CountType
ResourceProbe< ValueType, MeanType >
::GetNumberOfStops(void) const
{
  return this->m_NumberOfStops;
}

template< typename ValueType, typename MeanType >
typename ResourceProbe< ValueType, MeanType >::CountType
ResourceProbe< ValueType, MeanType >
::GetNumberOfIteration(void) const
{
  return this->m_NumberOfIteration;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetTotal(void) const
{
  return this->m_TotalValue;
}

template< typename ValueType, typename MeanType >
MeanType
ResourceProbe< ValueType, MeanType >
::GetMean(void) const
{
  MeanType meanValue = NumericTraits< MeanType >::ZeroValue();

  if ( this->m_NumberOfStops )
    {
    meanValue = static_cast< MeanType >( this->m_TotalValue ) / static_cast< MeanType >( this->m_NumberOfStops );
    }

  return meanValue;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetMinimum() const
{
  return this->m_MinimumValue;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetMaximum() const
{
  return this->m_MaximumValue;
}

template< typename ValueType, typename MeanType >
ValueType
ResourceProbe< ValueType, MeanType >
::GetStandardDeviation()
{
  this->m_MeanValue = this->GetMean();
  std::vector<ValueType> diff(this->m_ProbeValueList.size());
  std::transform(this->m_ProbeValueList.begin(),
                 this->m_ProbeValueList.end(),
                 diff.begin(),
                 std::bind2nd(std::minus<ValueType>(),
                              this->m_MeanValue ));
  ValueType sqsum =
    std::inner_product(diff.begin(),diff.end(),
                       diff.begin(),
                       0.0);

  int sz = this->m_ProbeValueList.size()-1;
  if (sz <=0)
    {
    this->m_StandardDeviation = NumericTraits< ValueType >::ZeroValue();
    }
  else
    {
    this->m_StandardDeviation =
      static_cast<ValueType>(std::sqrt(static_cast<double>(sqsum /(static_cast<ValueType>(sz)))));
    }
  return this->m_StandardDeviation;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::SetNameOfProbe(const char* nameOfProbe)
{
  this->m_NameOfProbe = nameOfProbe;
}

template< typename ValueType, typename MeanType >
std::string
ResourceProbe< ValueType, MeanType >
::GetNameOfProbe() const
{
  return this->m_NameOfProbe;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::PrintSystemInformation(std::ostream & os)
{
  os << "System:              " << m_SystemName << std::endl;
  os << "Processor:           " << m_ProcessorName << std::endl;
  os << "    Cache:           " << m_ProcessorCacheSize << std::endl;
  os << "    Clock:           " << m_ProcessorClockFrequency << std::endl;
  os << "    Cores:           " << m_NumberOfPhysicalCPU
     << " cpus x " << m_NumberOfLogicalCPU
     << " Cores = "<< m_NumberOfAvailableCore << std::endl;
  // Retrieve memory information in megabyte.
  os << "    Virtual Memory:  Total: "
     << m_TotalVirtualMemory
     <<" Available: "<< m_AvailableVirtualMemory << std::endl;
  os << "    Physical Memory: Total:"
     << m_TotalPhysicalMemory
     <<" Available: "<< m_AvailablePhysicalMemory << std::endl;

  os << "OSName:              "<< m_OSName << std::endl;
  os << "    Release:         "<< m_OSRelease << std::endl;
  os << "    Version:         "<< m_OSVersion << std::endl;
  os << "    Platform:        "<< m_OSPlatform << std::endl;

  os << "    Operating System is "
     << (m_Is64Bits?"64 bit":"32 bit") << std::endl;

  os << "ITK Version: "
     << m_ITKVersion << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::Report(std::ostream & os, bool printSystemInfo, bool printReportHead )
{
  if(printSystemInfo)
    {
    this->PrintSystemInformation(os);
    }

  if(printReportHead)
    {
    this->PrintReportHead(os);
    }

  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe
     << std::left << std::setw( tabwidth    ) << this->m_NumberOfIteration
     << std::left << std::setw( tabwidth    ) << this->GetTotal()
     << std::left << std::setw( tabwidth    ) << this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << this->GetMean()
     << std::left << std::setw( tabwidth    ) << this->GetMaximum()
     << std::left << std::setw( tabwidth    ) << this->GetStandardDeviation();
  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::ExpandedReport(std::ostream & os, bool printSystemInfo, bool printReportHead )
{
  if(printSystemInfo)
    {
    this->PrintSystemInformation(os);
    }

  if(printReportHead)
    {
    this->PrintExpandedReportHead(os);
    }

  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << this->m_NameOfProbe
     << std::left << std::setw( tabwidth    ) << this->m_NumberOfIteration
     << std::left << std::setw( tabwidth    ) << this->GetTotal()
     << std::left << std::setw( tabwidth    ) << this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << this->GetMean() - this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << (this->GetMean()/this->GetMinimum())*100
     << std::left << std::setw( tabwidth    ) << this->GetMean()
     << std::left << std::setw( tabwidth    ) << this->GetMaximum() - this->GetMean()
     << std::left << std::setw( tabwidth    ) << (this->GetMaximum()/this->GetMean())*100
     << std::left << std::setw( tabwidth    ) << this->GetMaximum()
     << std::left << std::setw( tabwidth    ) << this->GetMaximum() - this->GetMinimum()
     << std::left << std::setw( tabwidth    ) << this->GetStandardDeviation();
  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::UpdateMinimumMaximumMeasuredValue(ValueType value)
{
  if(this->m_MinimumValue > value)
    {
    this->m_MinimumValue = value;
    }

  if(this->m_MaximumValue < value)
    {
    this->m_MaximumValue = value;
    }
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::PrintReportHead(std::ostream & os)
{
  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << std::string("Name Of Probe(")+this->m_TypeString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Iteration"
     << std::left << std::setw( tabwidth    ) << std::string("Total(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Min(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Mean(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Max(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Std(") + this->m_UnitString + std::string(")");

  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::PrintExpandedReportHead(std::ostream & os)
{
  std::stringstream ss;
  ss << std::left << std::setw( tabwidth *2 ) << std::string("Name Of Probe(") + this->m_TypeString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Iteration"
     << std::left << std::setw( tabwidth    ) << std::string("Total(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Min(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Mean-Min(diff)"
     << std::left << std::setw( tabwidth    ) << "Mean/Min(%)"
     << std::left << std::setw( tabwidth    ) << std::string("Mean(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << "Max-Mean(diff)"
     << std::left << std::setw( tabwidth    ) << "Max/Mean(%)"
     << std::left << std::setw( tabwidth    ) << std::string("Max(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Total Diff(") + this->m_UnitString + std::string(")")
     << std::left << std::setw( tabwidth    ) << std::string("Std(") + this->m_UnitString + std::string(")");

  os << ss.str() << std::endl;
}

template< typename ValueType, typename MeanType >
void
ResourceProbe< ValueType, MeanType >
::GetSystemInformation()
{
  itksys::SystemInformation systeminfo;
  systeminfo.RunCPUCheck();
  systeminfo.RunMemoryCheck();
  systeminfo.RunOSCheck();

  m_SystemName              = systeminfo.GetHostname();
  m_ProcessorName           = systeminfo.GetExtendedProcessorName();
  m_ProcessorCacheSize      = systeminfo.GetProcessorCacheSize();
  m_ProcessorClockFrequency = systeminfo.GetProcessorClockFrequency();
  m_NumberOfPhysicalCPU     = systeminfo.GetNumberOfPhysicalCPU();
  m_NumberOfLogicalCPU      = systeminfo.GetNumberOfLogicalCPU();
  m_NumberOfAvailableCore   = m_NumberOfPhysicalCPU*m_NumberOfLogicalCPU;

  m_OSName                  = systeminfo.GetOSName();
  m_OSRelease               = systeminfo.GetOSRelease();
  m_OSVersion               = systeminfo.GetOSVersion();
  m_OSPlatform              = systeminfo.GetOSPlatform();

  m_Is64Bits                = systeminfo.Is64Bits();
  std::ostringstream        itkversion;
  itkversion << ITK_VERSION_MAJOR << "." << ITK_VERSION_MINOR << "." << ITK_VERSION_PATCH;
  m_ITKVersion              = itkversion.str();

 // Retrieve memory information in megabyte.
  m_TotalVirtualMemory      = systeminfo.GetTotalVirtualMemory();
  m_AvailableVirtualMemory  = systeminfo.GetAvailableVirtualMemory();
  m_TotalPhysicalMemory     = systeminfo.GetTotalPhysicalMemory();
  m_AvailablePhysicalMemory = systeminfo.GetAvailablePhysicalMemory();
}

} // end namespace itk

#endif
<|endoftext|>


<commit_before>#include "audio/player.h"

namespace loftili {

namespace audio {

void Player::Stop() {
  m_state = PLAYER_STATE_STOPPED;
}

bool Player::Play(std::string url) {
  Startup();
  loftili::net::HttpClient client;
  loftili::net::HttpRequest req(loftili::net::Url(url.c_str()));

  mpg123_handle* m_handle;
  m_handle = mpg123_new(NULL, NULL);

  spdlog::get(LOFTILI_SPDLOG_ID)->info("attempting to download track...");
  if(client.Send(req)) {
    std::shared_ptr<loftili::net::HttpResponse> res = client.Latest();
    if(res->Status() != 200) {
      spdlog::get(LOFTILI_SPDLOG_ID)->critical("download {0} failed", url.c_str());
      return false;
    }

    spdlog::get(LOFTILI_SPDLOG_ID)->info("download complete, temporarily saving to file system");
    remove("current.mp3");
    std::ofstream download;
    download.open("current.mp3", std::ios::binary | std::ios::out);
    download.write(res->Body(), res->ContentLength());
    download.close();
    int err = mpg123_open(m_handle, "current.mp3");

    if(err != MPG123_OK) {
      mpg123_close(m_handle);
      mpg123_delete(m_handle);
      Shutdown();
      return false;
    }

    off_t frame_offset;
    unsigned char* audio;
    size_t done;
    int channels, encoding;
    long rate;

    err = mpg123_getformat(m_handle, &rate, &channels, &encoding);
    if(err != MPG123_OK) {
      mpg123_close(m_handle);
      mpg123_delete(m_handle);
      Shutdown();
    }

    ao_sample_format format;
    format.bits = mpg123_encsize(encoding) * 8;
    format.rate = rate;
    format.channels = channels;
    format.byte_format = AO_FMT_NATIVE;
    format.matrix = 0;

    ao_device* dev = ao_open_live(ao_default_driver_id(), &format, NULL);
    m_state = PLAYER_STATE_PLAYING;

    do {
      err = mpg123_decode_frame(m_handle, &frame_offset, &audio, &done);
      switch(err) {
        case MPG123_OK:
          ao_play(dev, (char*)audio, done);
          break;
        default:
          break;
      }
    } while(done > 0 && m_state == PLAYER_STATE_PLAYING);

    ao_close(dev);
  }

  mpg123_close(m_handle);
  mpg123_delete(m_handle);
  Shutdown();
  return true;
}

Player::operator bool() {
  return m_state == PLAYER_STATE_PLAYING;
}

void Player::Startup() {
  ao_initialize();
  mpg123_init();
}

void Player::Shutdown() {
  ao_shutdown();
  mpg123_exit();
}

}

}
<commit_msg>[LFTCE-31] detecting libao inability to open audio device and exiting out of playback<commit_after>#include "audio/player.h"

namespace loftili {

namespace audio {

void Player::Stop() {
  m_state = PLAYER_STATE_STOPPED;
}

bool Player::Play(std::string url) {
  Startup();
  loftili::net::HttpClient client;
  loftili::net::HttpRequest req(loftili::net::Url(url.c_str()));

  mpg123_handle* m_handle;
  m_handle = mpg123_new(NULL, NULL);

  spdlog::get(LOFTILI_SPDLOG_ID)->info("attempting to download track...");
  if(client.Send(req)) {
    std::shared_ptr<loftili::net::HttpResponse> res = client.Latest();
    if(res->Status() != 200) {
      spdlog::get(LOFTILI_SPDLOG_ID)->critical("download {0} failed", url.c_str());
      return false;
    }

    spdlog::get(LOFTILI_SPDLOG_ID)->info("download complete, temporarily saving to file system");
    remove("current.mp3");
    std::ofstream download;
    download.open("current.mp3", std::ios::binary | std::ios::out);
    download.write(res->Body(), res->ContentLength());
    download.close();
    int err = mpg123_open(m_handle, "current.mp3");

    if(err != MPG123_OK) {
      mpg123_close(m_handle);
      mpg123_delete(m_handle);
      Shutdown();
      return false;
    }

    off_t frame_offset;
    unsigned char* audio;
    size_t done;
    int channels, encoding;
    long rate;

    err = mpg123_getformat(m_handle, &rate, &channels, &encoding);
    if(err != MPG123_OK) {
      mpg123_close(m_handle);
      mpg123_delete(m_handle);
      Shutdown();
    }

    ao_sample_format format;
    format.bits = mpg123_encsize(encoding) * 8;
    format.rate = rate;
    format.channels = channels;
    format.byte_format = AO_FMT_NATIVE;
    format.matrix = 0;

    ao_device* dev = ao_open_live(ao_default_driver_id(), &format, NULL);
    if(dev == NULL) {
      spdlog::get(LOFTILI_SPDLOG_ID)->critical("failed opening libao device, unable to play audio");
      mpg123_close(m_handle);
      mpg123_delete(m_handle);
      Shutdown();
      return false;
    }

    m_state = PLAYER_STATE_PLAYING;

    do {
      err = mpg123_decode_frame(m_handle, &frame_offset, &audio, &done);
      switch(err) {
        case MPG123_OK:
          ao_play(dev, (char*)audio, done);
          break;
        default:
          break;
      }
    } while(done > 0 && m_state == PLAYER_STATE_PLAYING);

    ao_close(dev);
  }

  mpg123_close(m_handle);
  mpg123_delete(m_handle);
  Shutdown();
  return true;
}

Player::operator bool() {
  return m_state == PLAYER_STATE_PLAYING;
}

void Player::Startup() {
  ao_initialize();
  mpg123_init();
}

void Player::Shutdown() {
  ao_shutdown();
  mpg123_exit();
}

}

}
<|endoftext|>


<commit_before>#include "DanpheApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "ModulesApp.h"

//Kernels
#include "ElectricPotential.h"
//Auxkernels
#include "CurrentDensity.h"
//Materials
#include "TinSheet.h"

template<>
InputParameters validParams<DanpheApp>()
{
  InputParameters params = validParams<MooseApp>();
  return params;
}

DanpheApp::DanpheApp(const std::string & name, InputParameters parameters) :
    MooseApp(name, parameters)
{
  srand(processor_id());

  Moose::registerObjects(_factory);
  ModulesApp::registerObjects(_factory);
  DanpheApp::registerObjects(_factory);

  Moose::associateSyntax(_syntax, _action_factory);
  ModulesApp::associateSyntax(_syntax, _action_factory);
  DanpheApp::associateSyntax(_syntax, _action_factory);
}

DanpheApp::~DanpheApp()
{
}

void
DanpheApp::registerApps()
{
  registerApp(DanpheApp);
}

void
DanpheApp::registerObjects(Factory & factory)
{
  registerKernel(ElectricPotential);
  registerAux(CurrentDensity);
  registerMaterial(TinSheet);
}

void
DanpheApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
}
<commit_msg>Update DanpheApp.C<commit_after>#include "DanpheApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "ModulesApp.h"

//Kernels
#include "ElectricPotential.h"
#include "CoupledPotential.h"
//Auxkernels
#include "CurrentDensity.h"
//Materials
#include "TinSheet.h"

template<>
InputParameters validParams<DanpheApp>()
{
  InputParameters params = validParams<MooseApp>();
  return params;
}

DanpheApp::DanpheApp(const std::string & name, InputParameters parameters) :
    MooseApp(name, parameters)
{
  srand(processor_id());

  Moose::registerObjects(_factory);
  ModulesApp::registerObjects(_factory);
  DanpheApp::registerObjects(_factory);

  Moose::associateSyntax(_syntax, _action_factory);
  ModulesApp::associateSyntax(_syntax, _action_factory);
  DanpheApp::associateSyntax(_syntax, _action_factory);
}

DanpheApp::~DanpheApp()
{
}

void
DanpheApp::registerApps()
{
  registerApp(DanpheApp);
}

void
DanpheApp::registerObjects(Factory & factory)
{
  registerKernel(ElectricPotential);
  registerKernel(CoupledPotential);
  registerAux(CurrentDensity);
  registerMaterial(TinSheet);
}

void
DanpheApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
}
<|endoftext|>


<commit_before>/**
 * @file ct2ctml.cpp
 * Driver for the system call to the python executable that converts
 * cti files to ctml files (see \ref inputfiles).
 */
// Copyright 2001-2005  California Institute of Technology

#include "cantera/base/ctml.h"
#include "cantera/base/stringUtils.h"
#include "../../ext/libexecstream/exec-stream.h"

#include <fstream>
#include <sstream>

#ifdef _WIN32
#include <windows.h>
#endif

using namespace Cantera;
using namespace std;

namespace ctml
{

//! return the full path to the Python interpreter.
/*!
 * Use the environment variable PYTHON_CMD if it is set. If not, return
 * the string 'python'.
 *
 * Note, there are hidden problems here that really direct us to use
 * a full pathname for the location of python. Basically the system
 * call will use the shell /bin/sh, in order to launch python.
 * This default shell may not be the shell that the user is employing.
 * Therefore, the default path to python may be different during
 * a system call than during the default user shell environment.
 * This is quite a headache. The answer is to always set the
 * PYTHON_CMD environmental variable in the user environment to
 * an absolute path to locate the python executable. Then this
 * issue goes away.
 */
static string pypath()
{
    string s = "python";
    const char* py = getenv("PYTHON_CMD");

    if (py) {
        string sp = stripws(string(py));
        if (sp.size() > 0) {
            s = sp;
        }
    }
    return s;
}

void ct2ctml(const char* file, const int debug)
{
    string xml = ct2ctml_string(file);
    string out_name = file;
#ifdef _WIN32
    // For Windows, make the path POSIX compliant so code looking for directory
    // separators is simpler.  Just look for '/' not both '/' and '\\'
    std::replace_if(out_name.begin(), out_name.end(),
                    std::bind2nd(std::equal_to<char>(), '\\'), '/') ;
#endif
    size_t idir = out_name.rfind('/');
    if (idir != npos) {
        out_name = out_name.substr(idir+1, out_name.size());
    }
    size_t idot = out_name.rfind('.');
    if (idot != npos) {
        out_name = out_name.substr(0, idot) + ".xml";
    } else {
        out_name += ".xml";
    }
    std::ofstream out(out_name.c_str());
    out << xml;
}

static std::string call_ctml_writer(const std::string& text, bool isfile)
{
    std::string file, arg;
    if (isfile) {
        file = text;
        arg = "r'" + text + "'";
    } else {
        file = "<string>";
        arg = "text=r'''" + text + "'''";
    }

#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    throw CanteraError("ct2ctml",
                       "python cti to ctml conversion requested for file, " + file +
                       ", but not available in this computational environment");
#endif

    string python_output, error_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        stringstream output_stream, error_stream;
        std::vector<string> args;
        args.push_back("-c");

        args.push_back(
                    "from __future__ import print_function\n"
                    "import sys\n"
                    "try:\n"
                    "    from cantera import ctml_writer\n"
                    "except ImportError:\n"
                    "    print('sys.path: ' + repr(sys.path) + '\\n', file=sys.stderr)\n"
                    "    raise\n"
                    "ctml_writer.convert(" + arg + ", outName='STDOUT')\n"
                    "sys.exit(0)\n");

        python.start(pypath(), args.begin(), args.end());
        std::string line;

        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;
        }

#ifdef _WIN32
        // Sleeping for 1 ms prevents a (somewhat inexplicable) deadlock while
        // reading from the stream.
        Sleep(1);
#endif
        while (python.err().good()) {
            std::getline(python.err(), line);
            error_stream << line << std::endl;
        }
        python.close();
        python_exit_code = python.exit_code();
        error_output = stripws(error_stream.str());
        python_output = output_stream.str();
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml_string", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << file << "\" to CTML.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (error_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << error_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ct2ctml_string", message.str());
    }

    if (error_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << error_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
    return python_output;
}

std::string ct2ctml_string(const std::string& file)
{
    return call_ctml_writer(file, true);
}

std::string ct_string2ctml_string(const std::string& cti)
{
    return call_ctml_writer(cti, false);
}

void ck2cti(const std::string& in_file, const std::string& thermo_file,
            const std::string& transport_file, const std::string& id_tag)
{
#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = in_file;
    throw CanteraError("ct2ctml",
                       "python ck to cti conversion requested for file, " + ppath +
                       ", but not available in this computational environment");
#endif

    string python_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        python.start(pypath(), "-i");
        stringstream output_stream;

        ostream& pyin = python.in();
        pyin << "if True:\n" << // Use this so that the rest is a single block
                "    import sys\n" <<
                "    sys.stderr = sys.stdout\n" <<
                "    try:\n" <<
                "        from cantera import ck2cti\n" <<
                "    except ImportError:\n" <<
                "        print('sys.path: ' + repr(sys.path))\n" <<
                "        raise\n"
                "    ck2cti.Parser().convertMech(r'" << in_file << "',";
        if (thermo_file != "" && thermo_file != "-") {
            pyin << " thermoFile=r'" << thermo_file << "',";
        }
        if (transport_file != "" && transport_file != "-") {
            pyin << " transportFile=r'" << transport_file << "',";
        }
        pyin << " phaseName='" << id_tag << "',";
        pyin << " permissive=True,";
        pyin << " quiet=True)\n";
        pyin << "    sys.exit(0)\n\n";
        pyin << "sys.exit(7)\n";
        python.close_in();

        std::string line;
        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;;
        }
        python.close();
        python_exit_code = python.exit_code();
        python_output = stripws(output_stream.str());
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << in_file << "\" to CTI.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (python_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << python_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ck2cti", message.str());
    }

    if (python_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << python_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
}

void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string& file, const int debug)
{
    warn_deprecated("get_CTML_Tree", "To be removed after Cantera 2.2. "
            "Use get_XML_File instead.");
    XML_Node* src = get_XML_File(file);
    src->copy(rootPtr);
}

Cantera::XML_Node getCtmlTree(const std::string& file)
{
    warn_deprecated("getCtmlTree", "To be removed after Cantera 2.2. "
            "Use get_XML_File instead.");
    XML_Node root;
    XML_Node* src = get_XML_File(file);
    src->copy(&root);
    return root;
}

}
<commit_msg>Fix compilation with Visual Studio 2013<commit_after>/**
 * @file ct2ctml.cpp
 * Driver for the system call to the python executable that converts
 * cti files to ctml files (see \ref inputfiles).
 */
// Copyright 2001-2005  California Institute of Technology

#include "cantera/base/ctml.h"
#include "cantera/base/stringUtils.h"
#include "../../ext/libexecstream/exec-stream.h"

#include <fstream>
#include <sstream>
#include <functional>

#ifdef _WIN32
#include <windows.h>
#endif

using namespace Cantera;
using namespace std;

namespace ctml
{

//! return the full path to the Python interpreter.
/*!
 * Use the environment variable PYTHON_CMD if it is set. If not, return
 * the string 'python'.
 *
 * Note, there are hidden problems here that really direct us to use
 * a full pathname for the location of python. Basically the system
 * call will use the shell /bin/sh, in order to launch python.
 * This default shell may not be the shell that the user is employing.
 * Therefore, the default path to python may be different during
 * a system call than during the default user shell environment.
 * This is quite a headache. The answer is to always set the
 * PYTHON_CMD environmental variable in the user environment to
 * an absolute path to locate the python executable. Then this
 * issue goes away.
 */
static string pypath()
{
    string s = "python";
    const char* py = getenv("PYTHON_CMD");

    if (py) {
        string sp = stripws(string(py));
        if (sp.size() > 0) {
            s = sp;
        }
    }
    return s;
}

void ct2ctml(const char* file, const int debug)
{
    string xml = ct2ctml_string(file);
    string out_name = file;
#ifdef _WIN32
    // For Windows, make the path POSIX compliant so code looking for directory
    // separators is simpler.  Just look for '/' not both '/' and '\\'
    std::replace_if(out_name.begin(), out_name.end(),
                    std::bind2nd(std::equal_to<char>(), '\\'), '/') ;
#endif
    size_t idir = out_name.rfind('/');
    if (idir != npos) {
        out_name = out_name.substr(idir+1, out_name.size());
    }
    size_t idot = out_name.rfind('.');
    if (idot != npos) {
        out_name = out_name.substr(0, idot) + ".xml";
    } else {
        out_name += ".xml";
    }
    std::ofstream out(out_name.c_str());
    out << xml;
}

static std::string call_ctml_writer(const std::string& text, bool isfile)
{
    std::string file, arg;
    if (isfile) {
        file = text;
        arg = "r'" + text + "'";
    } else {
        file = "<string>";
        arg = "text=r'''" + text + "'''";
    }

#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    throw CanteraError("ct2ctml",
                       "python cti to ctml conversion requested for file, " + file +
                       ", but not available in this computational environment");
#endif

    string python_output, error_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        stringstream output_stream, error_stream;
        std::vector<string> args;
        args.push_back("-c");

        args.push_back(
                    "from __future__ import print_function\n"
                    "import sys\n"
                    "try:\n"
                    "    from cantera import ctml_writer\n"
                    "except ImportError:\n"
                    "    print('sys.path: ' + repr(sys.path) + '\\n', file=sys.stderr)\n"
                    "    raise\n"
                    "ctml_writer.convert(" + arg + ", outName='STDOUT')\n"
                    "sys.exit(0)\n");

        python.start(pypath(), args.begin(), args.end());
        std::string line;

        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;
        }

#ifdef _WIN32
        // Sleeping for 1 ms prevents a (somewhat inexplicable) deadlock while
        // reading from the stream.
        Sleep(1);
#endif
        while (python.err().good()) {
            std::getline(python.err(), line);
            error_stream << line << std::endl;
        }
        python.close();
        python_exit_code = python.exit_code();
        error_output = stripws(error_stream.str());
        python_output = output_stream.str();
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml_string", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << file << "\" to CTML.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (error_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << error_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ct2ctml_string", message.str());
    }

    if (error_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << error_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
    return python_output;
}

std::string ct2ctml_string(const std::string& file)
{
    return call_ctml_writer(file, true);
}

std::string ct_string2ctml_string(const std::string& cti)
{
    return call_ctml_writer(cti, false);
}

void ck2cti(const std::string& in_file, const std::string& thermo_file,
            const std::string& transport_file, const std::string& id_tag)
{
#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = in_file;
    throw CanteraError("ct2ctml",
                       "python ck to cti conversion requested for file, " + ppath +
                       ", but not available in this computational environment");
#endif

    string python_output;
    int python_exit_code;
    try {
        exec_stream_t python;
        python.set_wait_timeout(exec_stream_t::s_all, 1800000); // 30 minutes
        python.start(pypath(), "-i");
        stringstream output_stream;

        ostream& pyin = python.in();
        pyin << "if True:\n" << // Use this so that the rest is a single block
                "    import sys\n" <<
                "    sys.stderr = sys.stdout\n" <<
                "    try:\n" <<
                "        from cantera import ck2cti\n" <<
                "    except ImportError:\n" <<
                "        print('sys.path: ' + repr(sys.path))\n" <<
                "        raise\n"
                "    ck2cti.Parser().convertMech(r'" << in_file << "',";
        if (thermo_file != "" && thermo_file != "-") {
            pyin << " thermoFile=r'" << thermo_file << "',";
        }
        if (transport_file != "" && transport_file != "-") {
            pyin << " transportFile=r'" << transport_file << "',";
        }
        pyin << " phaseName='" << id_tag << "',";
        pyin << " permissive=True,";
        pyin << " quiet=True)\n";
        pyin << "    sys.exit(0)\n\n";
        pyin << "sys.exit(7)\n";
        python.close_in();

        std::string line;
        while (python.out().good()) {
            std::getline(python.out(), line);
            output_stream << line << std::endl;;
        }
        python.close();
        python_exit_code = python.exit_code();
        python_output = stripws(output_stream.str());
    } catch (std::exception& err) {
        // Report failure to execute Python
        stringstream message;
        message << "Error executing python while converting input file:\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << err.what() << std::endl;
        throw CanteraError("ct2ctml", message.str());
    }

    if (python_exit_code != 0) {
        // Report a failure in the conversion process
        stringstream message;
        message << "Error converting input file \"" << in_file << "\" to CTI.\n";
        message << "Python command was: '" << pypath() << "'\n";
        message << "The exit code was: " << python_exit_code << "\n";
        if (python_output.size() > 0) {
            message << "-------------- start of converter log --------------\n";
            message << python_output << std::endl;
            message << "--------------- end of converter log ---------------";
        } else {
            message << "The command did not produce any output." << endl;
        }
        throw CanteraError("ck2cti", message.str());
    }

    if (python_output.size() > 0) {
        // Warn if there was any output from the conversion process
        stringstream message;
        message << "Warning: Unexpected output from CTI converter\n";
        message << "-------------- start of converter log --------------\n";
        message << python_output << std::endl;
        message << "--------------- end of converter log ---------------\n";
        writelog(message.str());
    }
}

void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string& file, const int debug)
{
    warn_deprecated("get_CTML_Tree", "To be removed after Cantera 2.2. "
            "Use get_XML_File instead.");
    XML_Node* src = get_XML_File(file);
    src->copy(rootPtr);
}

Cantera::XML_Node getCtmlTree(const std::string& file)
{
    warn_deprecated("getCtmlTree", "To be removed after Cantera 2.2. "
            "Use get_XML_File instead.");
    XML_Node root;
    XML_Node* src = get_XML_File(file);
    src->copy(&root);
    return root;
}

}
<|endoftext|>