<commit_before>/*
fileview.cpp

ᬮ 䠩 - ன  viewer.cpp

*/

/* Revision: 1.04 15.07.2000 $ */

/*
Modify:
  15.07.2000 tran
    + CtrlB 몫砥/砥 keybar
  04.07.2000 tran
    +  뢠 ᠣ     䠩
  29.06.2000 tran
    +   㭪樮
  28.06.2000 tran
    - NT Console resize
      adding SetScreenPosition
  25.06.2000 SVS
    ! ⮢ Master Copy
    ! 뤥  ⢥ ᠬ⥫쭮
*/

#include "headers.hpp"
#pragma hdrstop

/* $ 30.06.2000 IS
   ⠭
*/
#include "internalheaders.hpp"
/* IS $ */

FileViewer::FileViewer(char *Name,int EnableSwitch,int DisableHistory,
                       int DisableEdit,long ViewStartPos,char *PluginData,
                       NamesList *ViewNamesList)
{
  FileViewer::DisableEdit=DisableEdit;
  SetPosition(0,0,ScrX,ScrY);
  FullScreen=TRUE;
  Init(Name,EnableSwitch,DisableHistory,ViewStartPos,PluginData,ViewNamesList);
}

FileViewer::FileViewer(char *Name,int EnableSwitch,char *Title,
                       int X1,int Y1,int X2,int Y2)
{
  DisableEdit=TRUE;
  SetPosition(X1,Y1,X2,Y2);
  FullScreen=(X1==0 && Y1==0 && X2==ScrX && Y2==ScrY);
  View.SetTitle(Title);
  Init(Name,EnableSwitch,TRUE,-1,"",NULL);
}

void FileViewer::Init(char *Name,int EnableSwitch,int DisableHistory,
                      long ViewStartPos,char *PluginData,
                      NamesList *ViewNamesList)
{
  ViewKeyBar.SetOwner(this);
  ViewKeyBar.SetPosition(X1,Y2,X2,Y2);
  View.SetPluginData(PluginData);

  SetEnableSwitch(EnableSwitch);

  /* $ 29.06.2000 tran
        㭪樮  */
  char *FViewKeys[]={MSG(MViewF1),MSG(MViewF2),MSG(MViewF3),MSG(MViewF4),MSG(MViewF5),DisableEdit ? "":MSG(MViewF6),MSG(MViewF7),MSG(MViewF8),"",MSG(MViewF10),MSG(MViewF11),MSG(MViewF12)};
  char *FViewShiftKeys[]={MSG(MViewShiftF1),MSG(MViewShiftF2),MSG(MViewShiftF3),MSG(MViewShiftF4),MSG(MViewShiftF5),MSG(MViewShiftF6),MSG(MViewShiftF7),MSG(MViewShiftF8),MSG(MViewShiftF9),MSG(MViewShiftF10),MSG(MViewShiftF11),MSG(MViewShiftF12)};
  char *FViewAltKeys[]={MSG(MViewAltF1),MSG(MViewAltF2),MSG(MViewAltF3),MSG(MViewAltF4),MSG(MViewAltF5),MSG(MViewAltF6),MSG(MViewAltF7),MSG(MViewAltF8),MSG(MViewAltF9),MSG(MViewAltF10),MSG(MViewAltF11),MSG(MViewAltF12)};
  char *FViewCtrlKeys[]={MSG(MViewCtrlF1),MSG(MViewCtrlF2),MSG(MViewCtrlF3),MSG(MViewCtrlF4),MSG(MViewCtrlF5),MSG(MViewCtrlF6),MSG(MViewCtrlF7),MSG(MViewCtrlF8),MSG(MViewCtrlF9),MSG(MViewCtrlF10),MSG(MViewCtrlF11),MSG(MViewCtrlF12)};

  ViewKeyBar.Set(FViewKeys,sizeof(FViewKeys)/sizeof(FViewKeys[0]));
  ViewKeyBar.SetShift(FViewShiftKeys,sizeof(FViewShiftKeys)/sizeof(FViewShiftKeys[0]));
  ViewKeyBar.SetAlt(FViewAltKeys,sizeof(FViewAltKeys)/sizeof(FViewAltKeys[0]));
  ViewKeyBar.SetCtrl(FViewCtrlKeys,sizeof(FViewCtrlKeys)/sizeof(FViewCtrlKeys[0]));
  /* tran $ */
  SetKeyBar(&ViewKeyBar);
  /* $ 15.07.2000 tran
     ShowKeyBarViewer support*/
  View.SetPosition(X1,Y1,X2,Y2-(Opt.ShowKeyBarViewer?1:0));
  /* tran 15.07.2000 $ */

  View.SetViewKeyBar(&ViewKeyBar);
  /* $ 04.07.2000 tran
     + add TRUE as 'warning' parameter */
  if (!View.OpenFile(Name,TRUE))
  /* tran 04.07.2000 $ */
  {
    ExitCode=FALSE;
    return;
  }

  if (ViewStartPos!=-1)
    View.SetFilePos(ViewStartPos);
  if (ViewNamesList)
    View.SetNamesList(ViewNamesList);
  ExitCode=TRUE;
  ViewKeyBar.Show();
  /* $ 15.07.2000 tran
     dirty trick :( */
  if ( Opt.ShowKeyBarViewer==0 )
    ViewKeyBar.Hide0();
  /* tran 15.07.2000 $ */

  sprintf(NewTitle,MSG(MInViewer),PointToName(Name));
  SetFarTitle(NewTitle);
  ShowConsoleTitle();
  F3KeyOnly=TRUE;
  Process();
  if (!DisableHistory && (CtrlObject->ActivePanel!=NULL || strcmp(Name,"-")!=0))
  {
    char FullFileName[NM];
    ConvertNameToFull(Name,FullFileName);
    CtrlObject->ViewHistory->AddToHistory(FullFileName,MSG(MHistoryView),0);
  }
}

void FileViewer::Process()
{
  ChangeMacroMode MacroMode(MACRO_VIEWER);
  Modal::Process();
}

void FileViewer::Show()
{
  if (FullScreen)
  {
    /* $ 15.07.2000 tran
       + keybar hide/show support */
    if ( Opt.ShowKeyBarViewer )
    {
        ViewKeyBar.SetPosition(0,ScrY,ScrX,ScrY);
        ViewKeyBar.Redraw();
    }
    SetPosition(0,0,ScrX,ScrY-(Opt.ShowKeyBarViewer?1:0));
    View.SetPosition(0,0,ScrX,ScrY-(Opt.ShowKeyBarViewer?1:0));
    /* tran 15.07.2000 $ */
  }
  ScreenObject::Show();
}

void FileViewer::DisplayObject()
{
  View.Show();
}

int FileViewer::ProcessKey(int Key)
{
  if (Key!=KEY_F3 && Key!=KEY_NUMPAD5)
    F3KeyOnly=FALSE;
  switch(Key)
  {
    /* $ 15.07.2000 tran
       + CtrlB switch KeyBar*/
    case KEY_CTRLB:
      Opt.ShowKeyBarViewer=!Opt.ShowKeyBarViewer;
      if ( Opt.ShowKeyBarViewer )
        ViewKeyBar.Show();
      else
        ViewKeyBar.Hide0(); // 0 mean - Don't purge saved screen
      Show();
      return (TRUE);
    /* tran 15.07.2000 $ */
    case KEY_CTRLO:
      Hide();
      if (CtrlObject->LeftPanel!=CtrlObject->RightPanel)
        CtrlObject->ModalManager.ShowBackground();
      else
      {
        ViewKeyBar.Hide();
        WaitKey();
      }
      ViewKeyBar.Show();
      Show();
      return(TRUE);
    case KEY_CTRLTAB:
    case KEY_CTRLSHIFTTAB:
    case KEY_F12:
      if (GetEnableSwitch())
      {
        View.KeepInitParameters();
        if (Key==KEY_CTRLSHIFTTAB)
          SetExitCode(3);
        else
          SetExitCode(Key==KEY_CTRLTAB ? 1:2);
      }
      return(TRUE);
    case KEY_F3:
    case KEY_NUMPAD5:
      if (F3KeyOnly)
        return(TRUE);
    case KEY_ESC:
    case KEY_F10:
      SetExitCode(0);
      return(TRUE);
    case KEY_F6:
      if (!DisableEdit)
      {
        SetExitCode(0);
        char ViewFileName[NM];
        View.GetFileName(ViewFileName);
        long FilePos=View.GetFilePos();
        CtrlObject->ModalManager.SetNextWindow(FALSE,ViewFileName,FilePos);
        ShowTime(2);
      }
      return(TRUE);
    default:
      return(View.ProcessKey(Key));
  }
}

int FileViewer::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
  F3KeyOnly=FALSE;
  if (!View.ProcessMouse(MouseEvent))
    if (!ViewKeyBar.ProcessMouse(MouseEvent))
      return(FALSE);
  return(TRUE);
}

int FileViewer::GetTypeAndName(char *Type,char *Name)
{
  strcpy(Type,MSG(MScreensView));
  View.GetFileName(Name);
  return(MODALTYPE_VIEWER);
}

void FileViewer::ShowConsoleTitle()
{
  View.ShowConsoleTitle();
}

void FileViewer::SetTempViewName(char *Name)
{
  View.SetTempViewName(Name);
}

int FileViewer::GetExitCode()
{
  return(ExitCode);
}

/* $ 28.06.2000 tran
 (NT Console resize)
 resize viewer */
void FileViewer::SetScreenPosition()
{
  if (FullScreen)
  {
    SetPosition(0,0,ScrX,ScrY);
    Show();
  }
}
/* tran $ */
<commit_msg>FAR patch 00080.fileview_ctrlo Дата              : 21.07.2000 Сделал            : andrey tretjakov Описание          : убирает глюк во Viewer при CtrlO с выключенным кейбаром Измененные файлы  : fileview.cpp Состав            : 00080.fileview_ctrlo.txt                     fileview.cpp.80.diff Основан на патче  : 79 Дополнение        :<commit_after>/*
fileview.cpp

ᬮ 䠩 - ன  viewer.cpp

*/

/* Revision: 1.05 21.07.2000 $ */

/*
Modify:
  21.07.2000 tran 1.05
      - 䠪  CtrlO  몫祭
  15.07.2000 tran
      + CtrlB 몫砥/砥 keybar
  04.07.2000 tran
    +  뢠 ᠣ     䠩
  29.06.2000 tran
    +   㭪樮
  28.06.2000 tran
    - NT Console resize
      adding SetScreenPosition
  25.06.2000 SVS
    ! ⮢ Master Copy
    ! 뤥  ⢥ ᠬ⥫쭮
*/

#include "headers.hpp"
#pragma hdrstop

/* $ 30.06.2000 IS
   ⠭
*/
#include "internalheaders.hpp"
/* IS $ */

FileViewer::FileViewer(char *Name,int EnableSwitch,int DisableHistory,
                       int DisableEdit,long ViewStartPos,char *PluginData,
                       NamesList *ViewNamesList)
{
  FileViewer::DisableEdit=DisableEdit;
  SetPosition(0,0,ScrX,ScrY);
  FullScreen=TRUE;
  Init(Name,EnableSwitch,DisableHistory,ViewStartPos,PluginData,ViewNamesList);
}

FileViewer::FileViewer(char *Name,int EnableSwitch,char *Title,
                       int X1,int Y1,int X2,int Y2)
{
  DisableEdit=TRUE;
  SetPosition(X1,Y1,X2,Y2);
  FullScreen=(X1==0 && Y1==0 && X2==ScrX && Y2==ScrY);
  View.SetTitle(Title);
  Init(Name,EnableSwitch,TRUE,-1,"",NULL);
}

void FileViewer::Init(char *Name,int EnableSwitch,int DisableHistory,
                      long ViewStartPos,char *PluginData,
                      NamesList *ViewNamesList)
{
  ViewKeyBar.SetOwner(this);
  ViewKeyBar.SetPosition(X1,Y2,X2,Y2);
  View.SetPluginData(PluginData);

  SetEnableSwitch(EnableSwitch);

  /* $ 29.06.2000 tran
        㭪樮  */
  char *FViewKeys[]={MSG(MViewF1),MSG(MViewF2),MSG(MViewF3),MSG(MViewF4),MSG(MViewF5),DisableEdit ? "":MSG(MViewF6),MSG(MViewF7),MSG(MViewF8),"",MSG(MViewF10),MSG(MViewF11),MSG(MViewF12)};
  char *FViewShiftKeys[]={MSG(MViewShiftF1),MSG(MViewShiftF2),MSG(MViewShiftF3),MSG(MViewShiftF4),MSG(MViewShiftF5),MSG(MViewShiftF6),MSG(MViewShiftF7),MSG(MViewShiftF8),MSG(MViewShiftF9),MSG(MViewShiftF10),MSG(MViewShiftF11),MSG(MViewShiftF12)};
  char *FViewAltKeys[]={MSG(MViewAltF1),MSG(MViewAltF2),MSG(MViewAltF3),MSG(MViewAltF4),MSG(MViewAltF5),MSG(MViewAltF6),MSG(MViewAltF7),MSG(MViewAltF8),MSG(MViewAltF9),MSG(MViewAltF10),MSG(MViewAltF11),MSG(MViewAltF12)};
  char *FViewCtrlKeys[]={MSG(MViewCtrlF1),MSG(MViewCtrlF2),MSG(MViewCtrlF3),MSG(MViewCtrlF4),MSG(MViewCtrlF5),MSG(MViewCtrlF6),MSG(MViewCtrlF7),MSG(MViewCtrlF8),MSG(MViewCtrlF9),MSG(MViewCtrlF10),MSG(MViewCtrlF11),MSG(MViewCtrlF12)};

  ViewKeyBar.Set(FViewKeys,sizeof(FViewKeys)/sizeof(FViewKeys[0]));
  ViewKeyBar.SetShift(FViewShiftKeys,sizeof(FViewShiftKeys)/sizeof(FViewShiftKeys[0]));
  ViewKeyBar.SetAlt(FViewAltKeys,sizeof(FViewAltKeys)/sizeof(FViewAltKeys[0]));
  ViewKeyBar.SetCtrl(FViewCtrlKeys,sizeof(FViewCtrlKeys)/sizeof(FViewCtrlKeys[0]));
  /* tran $ */
  SetKeyBar(&ViewKeyBar);
  /* $ 15.07.2000 tran
     ShowKeyBarViewer support*/
  View.SetPosition(X1,Y1,X2,Y2-(Opt.ShowKeyBarViewer?1:0));
  /* tran 15.07.2000 $ */

  View.SetViewKeyBar(&ViewKeyBar);
  /* $ 04.07.2000 tran
     + add TRUE as 'warning' parameter */
  if (!View.OpenFile(Name,TRUE))
  /* tran 04.07.2000 $ */
  {
    ExitCode=FALSE;
    return;
  }

  if (ViewStartPos!=-1)
    View.SetFilePos(ViewStartPos);
  if (ViewNamesList)
    View.SetNamesList(ViewNamesList);
  ExitCode=TRUE;
  ViewKeyBar.Show();
  /* $ 15.07.2000 tran
     dirty trick :( */
  if ( Opt.ShowKeyBarViewer==0 )
    ViewKeyBar.Hide0();
  /* tran 15.07.2000 $ */

  sprintf(NewTitle,MSG(MInViewer),PointToName(Name));
  SetFarTitle(NewTitle);
  ShowConsoleTitle();
  F3KeyOnly=TRUE;
  Process();
  if (!DisableHistory && (CtrlObject->ActivePanel!=NULL || strcmp(Name,"-")!=0))
  {
    char FullFileName[NM];
    ConvertNameToFull(Name,FullFileName);
    CtrlObject->ViewHistory->AddToHistory(FullFileName,MSG(MHistoryView),0);
  }
}

void FileViewer::Process()
{
  ChangeMacroMode MacroMode(MACRO_VIEWER);
  Modal::Process();
}

void FileViewer::Show()
{
  if (FullScreen)
  {
    /* $ 15.07.2000 tran
       + keybar hide/show support */
    if ( Opt.ShowKeyBarViewer )
    {
        ViewKeyBar.SetPosition(0,ScrY,ScrX,ScrY);
        ViewKeyBar.Redraw();
    }
    SetPosition(0,0,ScrX,ScrY-(Opt.ShowKeyBarViewer?1:0));
    View.SetPosition(0,0,ScrX,ScrY-(Opt.ShowKeyBarViewer?1:0));
    /* tran 15.07.2000 $ */
  }
  ScreenObject::Show();
}

void FileViewer::DisplayObject()
{
  View.Show();
}

int FileViewer::ProcessKey(int Key)
{
  if (Key!=KEY_F3 && Key!=KEY_NUMPAD5)
    F3KeyOnly=FALSE;
  switch(Key)
  {
    /* $ 15.07.2000 tran
       + CtrlB switch KeyBar*/
    case KEY_CTRLB:
      Opt.ShowKeyBarViewer=!Opt.ShowKeyBarViewer;
      if ( Opt.ShowKeyBarViewer )
        ViewKeyBar.Show();
      else
        ViewKeyBar.Hide0(); // 0 mean - Don't purge saved screen
      Show();
      return (TRUE);
    /* tran 15.07.2000 $ */
    case KEY_CTRLO:
      Hide();
      if (CtrlObject->LeftPanel!=CtrlObject->RightPanel)
        CtrlObject->ModalManager.ShowBackground();
      else
      {
        ViewKeyBar.Hide();
        WaitKey();
      }
      /* $ 21.07.2000 tran
         - 䠪  Ctrl-O*/
      if ( Opt.ShowKeyBarViewer )
        ViewKeyBar.Show();
      else
        ViewKeyBar.Hide0(); // 0 mean - Don't purge saved screen
      /* tran 21.07.2000 $ */
      Show();
      return(TRUE);
    case KEY_CTRLTAB:
    case KEY_CTRLSHIFTTAB:
    case KEY_F12:
      if (GetEnableSwitch())
      {
        View.KeepInitParameters();
        if (Key==KEY_CTRLSHIFTTAB)
          SetExitCode(3);
        else
          SetExitCode(Key==KEY_CTRLTAB ? 1:2);
      }
      return(TRUE);
    case KEY_F3:
    case KEY_NUMPAD5:
      if (F3KeyOnly)
        return(TRUE);
    case KEY_ESC:
    case KEY_F10:
      SetExitCode(0);
      return(TRUE);
    case KEY_F6:
      if (!DisableEdit)
      {
        SetExitCode(0);
        char ViewFileName[NM];
        View.GetFileName(ViewFileName);
        long FilePos=View.GetFilePos();
        CtrlObject->ModalManager.SetNextWindow(FALSE,ViewFileName,FilePos);
        ShowTime(2);
      }
      return(TRUE);
    default:
      return(View.ProcessKey(Key));
  }
}

int FileViewer::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
  F3KeyOnly=FALSE;
  if (!View.ProcessMouse(MouseEvent))
    if (!ViewKeyBar.ProcessMouse(MouseEvent))
      return(FALSE);
  return(TRUE);
}

int FileViewer::GetTypeAndName(char *Type,char *Name)
{
  strcpy(Type,MSG(MScreensView));
  View.GetFileName(Name);
  return(MODALTYPE_VIEWER);
}

void FileViewer::ShowConsoleTitle()
{
  View.ShowConsoleTitle();
}

void FileViewer::SetTempViewName(char *Name)
{
  View.SetTempViewName(Name);
}

int FileViewer::GetExitCode()
{
  return(ExitCode);
}

/* $ 28.06.2000 tran
 (NT Console resize)
 resize viewer */
void FileViewer::SetScreenPosition()
{
  if (FullScreen)
  {
    SetPosition(0,0,ScrX,ScrY);
    Show();
  }
}
/* tran $ */
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

#include <termios.h>
#include <unistd.h>

int main(void) {
  const std::string PASSWORD{"password"};

  { // hide password
    termios orgstt;
    tcgetattr(STDIN_FILENO, &orgstt);
    auto newstt = orgstt;
    newstt.c_lflag &= ~ECHO;

    tcsetattr(STDIN_FILENO, TCSANOW, &newstt);
    std::string fst_try, snd_try;
    std::cout << "password: ";
    std::getline(std::cin, fst_try);

    std::cout << "\nretype password: ";
    std::getline(std::cin, snd_try);

    if (fst_try != snd_try or snd_try != PASSWORD) {
      std::cout << "\nwrong password!\n";
      exit(EXIT_FAILURE);
    }

    tcsetattr(STDIN_FILENO, TCSANOW, &orgstt);
  }

  std::vector<std::vector<float>> marks;
  {
    int groups;
    std::cout << "\nEnter number of groups: ";
    std::cin >> groups;
    marks.resize(groups);
  }

  int student_count;
  for (auto& group : marks) {
    std::cout << "Enter student number: ";
    std::cin >> student_count;
    group.resize(student_count);

    for (auto& mark : group) {
      std::cout << "Enter mark (0~100): ";
      std::cin >> mark;
    }

    std::sort(std::begin(group), std::end(group));

    std::cout << "\nReport:\n"
              <<   "=======\n";

    std::cout << "marks:\n";
    std::copy(std::begin(group), std::end(group),
              std::ostream_iterator<float>{std::cout, ", "});

    std::cout << "\n"
              << "min mark: " << *std::rbegin(group) << "\n"
              << "max mark: " << *std::begin(group)  << "\n";

    auto mid = std::lower_bound(std::begin(group), std::end(group), 50.0);
    std::cout << "failed: "    << std::distance(std::begin(group), mid)   << "\n"
              << "succeeded: " << std::distance(mid - 1, std::end(group)) << "\n";
  }
}
<commit_msg>fixed typos<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

#include <termios.h>
#include <unistd.h>

int main(void) {
  const std::string PASSWORD{"password"};

  { // hide password
    termios orgstt;
    tcgetattr(STDIN_FILENO, &orgstt);
    auto newstt = orgstt;
    newstt.c_lflag &= ~ECHO;

    tcsetattr(STDIN_FILENO, TCSANOW, &newstt);
    std::string fst_try, snd_try;
    std::cout << "password: ";
    std::getline(std::cin, fst_try);

    std::cout << "\nretype password: ";
    std::getline(std::cin, snd_try);

    if (fst_try != snd_try or snd_try != PASSWORD) {
      std::cout << "\nwrong password!\n";
      exit(EXIT_FAILURE);
    }

    tcsetattr(STDIN_FILENO, TCSANOW, &orgstt);
  }

  std::vector<std::vector<float>> marks;
  {
    int groups;
    std::cout << "\nEnter number of groups: ";
    std::cin >> groups;
    marks.resize(groups);
  }

  int student_count;
  for (auto& group : marks) {
    std::cout << "Enter student number: ";
    std::cin >> student_count;
    group.resize(student_count);

    for (auto& mark : group) {
      std::cout << "Enter mark (0~100): ";
      std::cin >> mark;
    }

    std::sort(std::begin(group), std::end(group));

    std::cout << "\nReport:\n"
              <<   "=======\n";

    std::cout << "marks:\n";
    std::copy(std::begin(group), std::end(group),
              std::ostream_iterator<float>{std::cout, ", "});

    std::cout << "\n"
              << "min mark: " << *std::begin(group) << "\n"
              << "max mark: " << *std::rbegin(group)  << "\n";

    auto mid = std::lower_bound(std::begin(group), std::end(group), 50.0);
    std::cout << "failed: "    << std::distance(std::begin(group), mid)   << "\n"
              << "succeeded: " << std::distance(mid, std::end(group)) << "\n";
  }
}
<|endoftext|>


<commit_before>#ifndef TIMEAWAREDATAWRITER_HH
#define TIMEAWAREDATAWRITER_HH

#include <dune/fem/io/file/datawriter.hh>

namespace Dune {

	//! TimeproviderType can only be FractionalTimeProvider atm
	template < class TimeproviderType, class GridType, class OutputTupleType >
	class TimeAwareDataWriter : public DataWriter< GridType, OutputTupleType >{
		protected:
			typedef DataWriter< GridType, OutputTupleType >
					BaseType;
			using BaseType::grape;
			using BaseType::grid_;
			using BaseType::path_;
			using BaseType::datapref_;
			using BaseType::writeStep_;
			using BaseType::outputFormat_;
			using BaseType::vtk;
			using BaseType::vtkvtx;
			using BaseType::gnuplot;
			using BaseType::data_;
			using BaseType::saveTime_;
			using BaseType::myRank_;
			using BaseType::saveStep_;

	   public:
			TimeAwareDataWriter( const TimeproviderType& timeprovider,
								 const GridType& grid,
								 OutputTupleType& tuple )
				: BaseType( grid, grid.name(), tuple, timeprovider.startTime(), timeprovider.endTime() ),
				timeprovider_( timeprovider )
			{

			}

			void write() const
			{
				write( timeprovider_.time() , timeprovider_.timeStep()  );
			}

			/** \brief write given data to disc
			   \param[in] time actual time of computation
			   \param[in] timestep current number of time step
			   \param[in] data data to write (template type, should be a tuple)
			*/
			void write(double time, int timestep ) const
			{
				if( BaseType::willWrite( time, timestep ) )
				{
					{
						// check online display
						BaseType::display();
					}

					if( BaseType::outputFormat_ == grape )
					{
						// create new path for time step output
						std::string timeStepPath = IOInterface::createPath ( grid_.comm(),
																			 path_, datapref_ , writeStep_ );

						// for structured grids copy grid
						IOInterface::copyMacroGrid(grid_,path_,timeStepPath,datapref_);

						GrapeDataIO<GridType> dataio;
						// call output of IOTuple
						IOTuple<OutputTupleType>::output(dataio,
														 grid_ ,time, writeStep_, timeStepPath , datapref_, data_ );
					}
	#if USE_VTKWRITER
					else if ( outputFormat_ == vtk || outputFormat_ == vtkvtx )
					{
						// write data in vtk output format
						writeVTKOutput( Element<0>::get(data_) );
					}
	#endif
					else if ( outputFormat_ == gnuplot )
					{
						writeGnuPlotOutput( Element<0>::get(data_), time );
					}
					else
					{
						DUNE_THROW(NotImplemented,"DataWriter::write: wrong output format");
					}

					// only write info for proc 0, otherwise on large number of procs
					// this is to much output
					if(myRank_ <= 0)
					{
						std::cout << "DataWriter["<<myRank_<<"]::write:  time = "<< time << "  writeData: step number " << writeStep_ << std::endl;
					}
					saveTime_ += saveStep_;
					++writeStep_;
				}
				return;
			}

		protected:
			const TimeproviderType& timeprovider_;

			template <class VTKOut>
			class VTKOutputter {
					const std::string path_;
					const bool parallel_;
					const int step_;
				public:
				//! Constructor
					VTKOutputter(VTKOut& vtkOut,std::string path, bool parallel,int step)
					   : vtkOut_(vtkOut),
					   path_(path),
					   parallel_(parallel),
					   step_(step)
					{}

				//! Applies the setting on every DiscreteFunction/LocalFunction pair.
					template <class DFType>
					void visit(DFType* f)
					{
						std::string name = genFilename( (parallel_) ? "" : path_, f->name(), step_ );
						if ( DFType::FunctionSpaceType::DimRange > 1 ) {
							vtkOut_.addVectorVertexData( *f );
							vtkOut_.addVectorCellData( *f );
						}
						else {
							vtkOut_.addVertexData( *f );
							vtkOut_.addCellData( *f );
						}

						if( parallel_ )
						{
							// write all data for parallel runs
							vtkOut_.pwrite( name.c_str(), path_.c_str(), "." , Dune::VTKOptions::binaryappended );
						}
						else
						{
							// write all data serial
							vtkOut_.write( name.c_str(), Dune::VTKOptions::binaryappended );
						}

						vtkOut_.clear();
					}
					static inline std::string genFilename(const std::string& path,
												   const std::string& fn,
												   int ntime,
												   int precision = 6)
					{
						std::ostringstream name;

						if(path.size() > 0)
						{
							name << path;
							name << "/";
						}
						name << fn;

						char cp[256];
						switch(precision)
						{
							case 2  : { sprintf(cp, "%02d", ntime); break; }
							case 3  : { sprintf(cp, "%03d", ntime); break; }
							case 4  : { sprintf(cp, "%04d", ntime); break; }
							case 5  : { sprintf(cp, "%05d", ntime); break; }
							case 6  : { sprintf(cp, "%06d", ntime); break; }
							case 7  : { sprintf(cp, "%07d", ntime); break; }
							case 8  : { sprintf(cp, "%08d", ntime); break; }
							case 9  : { sprintf(cp, "%09d", ntime); break; }
							case 10 : { sprintf(cp, "%010d", ntime); break; }
							default:
								{
									DUNE_THROW(Exception, "Couldn't gernerate filename with precision = "<<precision);
								}
						}
						name << cp;

						// here implicitly a string is generated
						return name.str();
					}

				private:
					VTKOut & vtkOut_;
			};

	#if USE_VTKWRITER
			template <class DFType>
			void writeVTKOutput(const DFType* func) const
			{

				// check whether we have parallel run
				const bool parallel = (grid_.comm().size() > 1);

				// generate filename, with path only for serial run

				{
					// get grid part
					typedef typename DFType :: DiscreteFunctionSpaceType :: GridPartType GridPartType;
					const GridPartType& gridPart = func->space().gridPart();

					{
						// create vtk output handler
						typedef VTKIO < GridPartType > VTKIOType;
						VTKIOType vtkio ( gridPart, VTKOptions::nonconforming );

						// add all functions
						ForEachValue<OutputTupleType> forEach(data_);
						VTKOutputter< VTKIOType > io( vtkio, path_, parallel, timeprovider_.timeStep() );
						forEach.apply( io );

						// write all data

					}
				}
			}
	#endif

	};

} // end namespace Dune
#endif // DATAWRITER_HH
<commit_msg>inti order fixed<commit_after>#ifndef TIMEAWAREDATAWRITER_HH
#define TIMEAWAREDATAWRITER_HH

#include <dune/fem/io/file/datawriter.hh>

namespace Dune {

	//! TimeproviderType can only be FractionalTimeProvider atm
	template < class TimeproviderType, class GridType, class OutputTupleType >
	class TimeAwareDataWriter : public DataWriter< GridType, OutputTupleType >{
		protected:
			typedef DataWriter< GridType, OutputTupleType >
					BaseType;
			using BaseType::grape;
			using BaseType::grid_;
			using BaseType::path_;
			using BaseType::datapref_;
			using BaseType::writeStep_;
			using BaseType::outputFormat_;
			using BaseType::vtk;
			using BaseType::vtkvtx;
			using BaseType::gnuplot;
			using BaseType::data_;
			using BaseType::saveTime_;
			using BaseType::myRank_;
			using BaseType::saveStep_;

	   public:
			TimeAwareDataWriter( const TimeproviderType& timeprovider,
								 const GridType& grid,
								 OutputTupleType& tuple )
				: BaseType( grid, grid.name(), tuple, timeprovider.startTime(), timeprovider.endTime() ),
				timeprovider_( timeprovider )
			{

			}

			void write() const
			{
				write( timeprovider_.time() , timeprovider_.timeStep()  );
			}

			/** \brief write given data to disc
			   \param[in] time actual time of computation
			   \param[in] timestep current number of time step
			   \param[in] data data to write (template type, should be a tuple)
			*/
			void write(double time, int timestep ) const
			{
				if( BaseType::willWrite( time, timestep ) )
				{
					{
						// check online display
						BaseType::display();
					}

					if( BaseType::outputFormat_ == grape )
					{
						// create new path for time step output
						std::string timeStepPath = IOInterface::createPath ( grid_.comm(),
																			 path_, datapref_ , writeStep_ );

						// for structured grids copy grid
						IOInterface::copyMacroGrid(grid_,path_,timeStepPath,datapref_);

						GrapeDataIO<GridType> dataio;
						// call output of IOTuple
						IOTuple<OutputTupleType>::output(dataio,
														 grid_ ,time, writeStep_, timeStepPath , datapref_, data_ );
					}
	#if USE_VTKWRITER
					else if ( outputFormat_ == vtk || outputFormat_ == vtkvtx )
					{
						// write data in vtk output format
						writeVTKOutput( Element<0>::get(data_) );
					}
	#endif
					else if ( outputFormat_ == gnuplot )
					{
						writeGnuPlotOutput( Element<0>::get(data_), time );
					}
					else
					{
						DUNE_THROW(NotImplemented,"DataWriter::write: wrong output format");
					}

					// only write info for proc 0, otherwise on large number of procs
					// this is to much output
					if(myRank_ <= 0)
					{
						std::cout << "DataWriter["<<myRank_<<"]::write:  time = "<< time << "  writeData: step number " << writeStep_ << std::endl;
					}
					saveTime_ += saveStep_;
					++writeStep_;
				}
				return;
			}

		protected:
			const TimeproviderType& timeprovider_;

			template <class VTKOut>
			class VTKOutputter {
				public:
				//! Constructor
					VTKOutputter(VTKOut& vtkOut,std::string path, bool parallel,int step)
					   : vtkOut_(vtkOut),
					   path_(path),
					   parallel_(parallel),
					   step_(step)
					{}

				//! Applies the setting on every DiscreteFunction/LocalFunction pair.
					template <class DFType>
					void visit(DFType* f)
					{
						std::string name = genFilename( (parallel_) ? "" : path_, f->name(), step_ );
						if ( DFType::FunctionSpaceType::DimRange > 1 ) {
							vtkOut_.addVectorVertexData( *f );
							vtkOut_.addVectorCellData( *f );
						}
						else {
							vtkOut_.addVertexData( *f );
							vtkOut_.addCellData( *f );
						}

						if( parallel_ )
						{
							// write all data for parallel runs
							vtkOut_.pwrite( name.c_str(), path_.c_str(), "." , Dune::VTKOptions::binaryappended );
						}
						else
						{
							// write all data serial
							vtkOut_.write( name.c_str(), Dune::VTKOptions::binaryappended );
						}

						vtkOut_.clear();
					}
					static inline std::string genFilename(const std::string& path,
												   const std::string& fn,
												   int ntime,
												   int precision = 6)
					{
						std::ostringstream name;

						if(path.size() > 0)
						{
							name << path;
							name << "/";
						}
						name << fn;

						char cp[256];
						switch(precision)
						{
							case 2  : { sprintf(cp, "%02d", ntime); break; }
							case 3  : { sprintf(cp, "%03d", ntime); break; }
							case 4  : { sprintf(cp, "%04d", ntime); break; }
							case 5  : { sprintf(cp, "%05d", ntime); break; }
							case 6  : { sprintf(cp, "%06d", ntime); break; }
							case 7  : { sprintf(cp, "%07d", ntime); break; }
							case 8  : { sprintf(cp, "%08d", ntime); break; }
							case 9  : { sprintf(cp, "%09d", ntime); break; }
							case 10 : { sprintf(cp, "%010d", ntime); break; }
							default:
								{
									DUNE_THROW(Exception, "Couldn't gernerate filename with precision = "<<precision);
								}
						}
						name << cp;

						// here implicitly a string is generated
						return name.str();
					}

				private:
					VTKOut & vtkOut_;
					const std::string path_;
					const bool parallel_;
					const int step_;
			};

	#if USE_VTKWRITER
			template <class DFType>
			void writeVTKOutput(const DFType* func) const
			{

				// check whether we have parallel run
				const bool parallel = (grid_.comm().size() > 1);

				// generate filename, with path only for serial run

				{
					// get grid part
					typedef typename DFType :: DiscreteFunctionSpaceType :: GridPartType GridPartType;
					const GridPartType& gridPart = func->space().gridPart();

					{
						// create vtk output handler
						typedef VTKIO < GridPartType > VTKIOType;
						VTKIOType vtkio ( gridPart, VTKOptions::nonconforming );

						// add all functions
						ForEachValue<OutputTupleType> forEach(data_);
						VTKOutputter< VTKIOType > io( vtkio, path_, parallel, timeprovider_.timeStep() );
						forEach.apply( io );

						// write all data

					}
				}
			}
	#endif

	};

} // end namespace Dune
#endif // DATAWRITER_HH
<|endoftext|>


<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#pragma once

#include <backendsCommon/DynamicBackend.hpp>
#include <backendsCommon/DynamicBackendUtils.hpp>

#include <string>
#include <memory>

#include <string>

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>

static std::string g_TestSharedObjectSubDir                 = "src/backends/backendsCommon/test/";
static std::string g_TestSharedObjectFileName               = "libarmnnTestSharedObject.so";
static std::string g_TestValidTestDynamicBackendFileName    = "libarmnnValidTestDynamicBackend.so";
static std::string g_TestInvalidTestDynamicBackend1FileName = "libarmnnInvalidTestDynamicBackend1.so";
static std::string g_TestInvalidTestDynamicBackend2FileName = "libarmnnInvalidTestDynamicBackend2.so";
static std::string g_TestInvalidTestDynamicBackend3FileName = "libarmnnInvalidTestDynamicBackend3.so";
static std::string g_TestInvalidTestDynamicBackend4FileName = "libarmnnInvalidTestDynamicBackend4.so";
static std::string g_TestInvalidTestDynamicBackend5FileName = "libarmnnInvalidTestDynamicBackend5.so";
static std::string g_TestInvalidTestDynamicBackend6FileName = "libarmnnInvalidTestDynamicBackend6.so";
static std::string g_TestInvalidTestDynamicBackend7FileName = "libarmnnInvalidTestDynamicBackend7.so";

std::string GetTestFilePath(const std::string& fileName)
{
    using namespace boost::filesystem;

    path currentPath(current_path());
    path sharedObjectPath = currentPath.append(g_TestSharedObjectSubDir);
    path sharedObjectFile = sharedObjectPath.append(fileName);
    BOOST_TEST(exists(sharedObjectFile));

    return sharedObjectFile.string();
}

void OpenCloseHandleTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void CloseInvalidHandleTestImpl()
{
    using namespace armnn;

    // This calls must silently handle invalid handles and complete successfully (no segfaults, etc.)
    DynamicBackendUtils::CloseHandle(nullptr);
}

void OpenEmptyFileNameTestImpl()
{
    using namespace armnn;

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(""), RuntimeException);
    BOOST_TEST((sharedObjectHandle == nullptr));
}

void OpenNotExistingFileTestImpl()
{
    using namespace armnn;

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle("NotExistingFileName"), RuntimeException);
    BOOST_TEST((sharedObjectHandle == nullptr));
}

void OpenNotSharedObjectTestImpl()
{
    using namespace armnn;

    std::string notSharedObjectFilePath = GetTestFilePath("libarmnnNoSharedObject.txt");

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(notSharedObjectFilePath), RuntimeException);
    BOOST_TEST((sharedObjectHandle == nullptr));
}

void GetValidEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_NO_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction1"));
    BOOST_TEST((testFunctionPointer != nullptr));
    BOOST_TEST(testFunctionPointer(7) == 7);

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void GetNameMangledEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction2"),
                      RuntimeException);
    BOOST_TEST((testFunctionPointer == nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void GetNoExternEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction3"),
                      RuntimeException);
    BOOST_TEST((testFunctionPointer == nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void GetNotExistingEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction4"),
                      RuntimeException);
    BOOST_TEST((testFunctionPointer == nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void BackendVersioningTestImpl()
{
    using namespace armnn;

    class TestDynamicBackendUtils : public DynamicBackendUtils
    {
    public:
        static bool IsBackendCompatibleTest(const BackendVersion& backendApiVersion,
                                            const BackendVersion& backendVersion)
        {
            return IsBackendCompatibleImpl(backendApiVersion, backendVersion);
        }
    };

    // The backend API version used for the tests
    BackendVersion backendApiVersion{ 2, 4 };

    // Same backend and backend API versions are compatible with the backend API
    BackendVersion sameBackendVersion{ 2, 4 };
    BOOST_TEST(sameBackendVersion == backendApiVersion);
    BOOST_TEST(sameBackendVersion <= backendApiVersion);
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, sameBackendVersion) == true);

    // Backend versions that differ from the backend API version by major revision are not compatible
    // with the backend API
    BackendVersion laterMajorBackendVersion{ 3, 4 };
    BOOST_TEST(!(laterMajorBackendVersion == backendApiVersion));
    BOOST_TEST(!(laterMajorBackendVersion <= backendApiVersion));
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, laterMajorBackendVersion) == false);

    BackendVersion earlierMajorBackendVersion{ 1, 4 };
    BOOST_TEST(!(earlierMajorBackendVersion == backendApiVersion));
    BOOST_TEST(earlierMajorBackendVersion <= backendApiVersion);
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion,
                                                                earlierMajorBackendVersion) == false);

    // Backend versions with the same major revision but later minor revision than
    // the backend API version are not compatible with the backend API
    BackendVersion laterMinorBackendVersion{ 2, 5 };
    BOOST_TEST(!(laterMinorBackendVersion == backendApiVersion));
    BOOST_TEST(!(laterMinorBackendVersion <= backendApiVersion));
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, laterMinorBackendVersion) == false);

    // Backend versions with the same major revision but earlier minor revision than
    // the backend API version are compatible with the backend API
    BackendVersion earlierMinorBackendVersion{ 2, 3 };
    BOOST_TEST(!(earlierMinorBackendVersion == backendApiVersion));
    BOOST_TEST(earlierMinorBackendVersion <= backendApiVersion);
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, earlierMinorBackendVersion) == true);
}

void CreateValidDynamicBackendObjectTestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Correct backend implementation

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestValidTestDynamicBackendFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_NO_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)));
    BOOST_TEST((dynamicBackend != nullptr));

    BackendId dynamicBackendId;
    BOOST_CHECK_NO_THROW(dynamicBackendId = dynamicBackend->GetBackendId());
    BOOST_TEST((dynamicBackendId == "ValidTestDynamicBackend"));

    BackendVersion dynamicBackendVersion;
    BOOST_CHECK_NO_THROW(dynamicBackendVersion = dynamicBackend->GetBackendVersion());
    BOOST_TEST((dynamicBackendVersion == BackendVersion({ 1, 0 })));

    IBackendInternalUniquePtr dynamicBackendInstance;
    BOOST_CHECK_NO_THROW(dynamicBackendInstance = dynamicBackend->GetBackend());
    BOOST_TEST((dynamicBackendInstance != nullptr));

    BOOST_TEST((dynamicBackendInstance->GetId() == "ValidTestDynamicBackend"));
}

void CreateDynamicBackendObjectInvalidHandleTestImpl()
{
    // Invalid (null) shared object handle

    using namespace armnn;

    void* sharedObjectHandle = nullptr;
    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), InvalidArgumentException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface1TestImpl()
{
    // Valid shared object handle
    // Wrong (not C-style) name mangling

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend1FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface2TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Wrong interface (missing GetBackendId())

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend2FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface3TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Wrong interface (missing GetVersion())

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend3FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface4TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Wrong interface (missing BackendFactory())

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend4FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface5TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Invalid (null) backend id returned by GetBackendId()

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend5FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface6TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Invalid (null) backend instance returned by BackendFactory()

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend6FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_NO_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)));
    BOOST_TEST((dynamicBackend != nullptr));

    BackendId dynamicBackendId;
    BOOST_CHECK_NO_THROW(dynamicBackendId = dynamicBackend->GetBackendId());
    BOOST_TEST((dynamicBackendId == "InvalidTestDynamicBackend"));

    BackendVersion dynamicBackendVersion;
    BOOST_CHECK_NO_THROW(dynamicBackendVersion = dynamicBackend->GetBackendVersion());
    BOOST_TEST((dynamicBackendVersion == BackendVersion({ 1, 0 })));

    IBackendInternalUniquePtr dynamicBackendInstance;
    BOOST_CHECK_THROW(dynamicBackendInstance = dynamicBackend->GetBackend(), RuntimeException);
    BOOST_TEST((dynamicBackendInstance == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface7TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Invalid (incompatible backend API version) backend instance returned by BackendFactory()

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend7FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}
<commit_msg>IVGCVSW-3561 Use absolute path of unit tests<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#pragma once

#include <backendsCommon/DynamicBackend.hpp>
#include <backendsCommon/DynamicBackendUtils.hpp>

#include <string>
#include <memory>

#include <string>

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/dll.hpp>

static std::string g_TestSharedObjectSubDir                 = "src/backends/backendsCommon/test/";
static std::string g_TestSharedObjectFileName               = "libarmnnTestSharedObject.so";
static std::string g_TestValidTestDynamicBackendFileName    = "libarmnnValidTestDynamicBackend.so";
static std::string g_TestInvalidTestDynamicBackend1FileName = "libarmnnInvalidTestDynamicBackend1.so";
static std::string g_TestInvalidTestDynamicBackend2FileName = "libarmnnInvalidTestDynamicBackend2.so";
static std::string g_TestInvalidTestDynamicBackend3FileName = "libarmnnInvalidTestDynamicBackend3.so";
static std::string g_TestInvalidTestDynamicBackend4FileName = "libarmnnInvalidTestDynamicBackend4.so";
static std::string g_TestInvalidTestDynamicBackend5FileName = "libarmnnInvalidTestDynamicBackend5.so";
static std::string g_TestInvalidTestDynamicBackend6FileName = "libarmnnInvalidTestDynamicBackend6.so";
static std::string g_TestInvalidTestDynamicBackend7FileName = "libarmnnInvalidTestDynamicBackend7.so";

std::string GetTestFilePath(const std::string& fileName)
{
    using namespace boost::filesystem;

    path programLocation = boost::dll::program_location().parent_path();
    path sharedObjectPath = programLocation.append(g_TestSharedObjectSubDir);
    path sharedObjectFile = sharedObjectPath.append(fileName);
    BOOST_TEST(exists(sharedObjectFile));

    return sharedObjectFile.string();
}

void OpenCloseHandleTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void CloseInvalidHandleTestImpl()
{
    using namespace armnn;

    // This calls must silently handle invalid handles and complete successfully (no segfaults, etc.)
    DynamicBackendUtils::CloseHandle(nullptr);
}

void OpenEmptyFileNameTestImpl()
{
    using namespace armnn;

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(""), RuntimeException);
    BOOST_TEST((sharedObjectHandle == nullptr));
}

void OpenNotExistingFileTestImpl()
{
    using namespace armnn;

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle("NotExistingFileName"), RuntimeException);
    BOOST_TEST((sharedObjectHandle == nullptr));
}

void OpenNotSharedObjectTestImpl()
{
    using namespace armnn;

    std::string notSharedObjectFilePath = GetTestFilePath("libarmnnNoSharedObject.txt");

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(notSharedObjectFilePath), RuntimeException);
    BOOST_TEST((sharedObjectHandle == nullptr));
}

void GetValidEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_NO_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction1"));
    BOOST_TEST((testFunctionPointer != nullptr));
    BOOST_TEST(testFunctionPointer(7) == 7);

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void GetNameMangledEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction2"),
                      RuntimeException);
    BOOST_TEST((testFunctionPointer == nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void GetNoExternEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction3"),
                      RuntimeException);
    BOOST_TEST((testFunctionPointer == nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void GetNotExistingEntryPointTestImpl()
{
    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestSharedObjectFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    using TestFunctionType = int(*)(int);
    TestFunctionType testFunctionPointer = nullptr;
    BOOST_CHECK_THROW(testFunctionPointer = DynamicBackendUtils::GetEntryPoint<TestFunctionType>(sharedObjectHandle,
                                                                                "TestFunction4"),
                      RuntimeException);
    BOOST_TEST((testFunctionPointer == nullptr));

    DynamicBackendUtils::CloseHandle(sharedObjectHandle);
}

void BackendVersioningTestImpl()
{
    using namespace armnn;

    class TestDynamicBackendUtils : public DynamicBackendUtils
    {
    public:
        static bool IsBackendCompatibleTest(const BackendVersion& backendApiVersion,
                                            const BackendVersion& backendVersion)
        {
            return IsBackendCompatibleImpl(backendApiVersion, backendVersion);
        }
    };

    // The backend API version used for the tests
    BackendVersion backendApiVersion{ 2, 4 };

    // Same backend and backend API versions are compatible with the backend API
    BackendVersion sameBackendVersion{ 2, 4 };
    BOOST_TEST(sameBackendVersion == backendApiVersion);
    BOOST_TEST(sameBackendVersion <= backendApiVersion);
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, sameBackendVersion) == true);

    // Backend versions that differ from the backend API version by major revision are not compatible
    // with the backend API
    BackendVersion laterMajorBackendVersion{ 3, 4 };
    BOOST_TEST(!(laterMajorBackendVersion == backendApiVersion));
    BOOST_TEST(!(laterMajorBackendVersion <= backendApiVersion));
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, laterMajorBackendVersion) == false);

    BackendVersion earlierMajorBackendVersion{ 1, 4 };
    BOOST_TEST(!(earlierMajorBackendVersion == backendApiVersion));
    BOOST_TEST(earlierMajorBackendVersion <= backendApiVersion);
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion,
                                                                earlierMajorBackendVersion) == false);

    // Backend versions with the same major revision but later minor revision than
    // the backend API version are not compatible with the backend API
    BackendVersion laterMinorBackendVersion{ 2, 5 };
    BOOST_TEST(!(laterMinorBackendVersion == backendApiVersion));
    BOOST_TEST(!(laterMinorBackendVersion <= backendApiVersion));
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, laterMinorBackendVersion) == false);

    // Backend versions with the same major revision but earlier minor revision than
    // the backend API version are compatible with the backend API
    BackendVersion earlierMinorBackendVersion{ 2, 3 };
    BOOST_TEST(!(earlierMinorBackendVersion == backendApiVersion));
    BOOST_TEST(earlierMinorBackendVersion <= backendApiVersion);
    BOOST_TEST(TestDynamicBackendUtils::IsBackendCompatibleTest(backendApiVersion, earlierMinorBackendVersion) == true);
}

void CreateValidDynamicBackendObjectTestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Correct backend implementation

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestValidTestDynamicBackendFileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_NO_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)));
    BOOST_TEST((dynamicBackend != nullptr));

    BackendId dynamicBackendId;
    BOOST_CHECK_NO_THROW(dynamicBackendId = dynamicBackend->GetBackendId());
    BOOST_TEST((dynamicBackendId == "ValidTestDynamicBackend"));

    BackendVersion dynamicBackendVersion;
    BOOST_CHECK_NO_THROW(dynamicBackendVersion = dynamicBackend->GetBackendVersion());
    BOOST_TEST((dynamicBackendVersion == BackendVersion({ 1, 0 })));

    IBackendInternalUniquePtr dynamicBackendInstance;
    BOOST_CHECK_NO_THROW(dynamicBackendInstance = dynamicBackend->GetBackend());
    BOOST_TEST((dynamicBackendInstance != nullptr));

    BOOST_TEST((dynamicBackendInstance->GetId() == "ValidTestDynamicBackend"));
}

void CreateDynamicBackendObjectInvalidHandleTestImpl()
{
    // Invalid (null) shared object handle

    using namespace armnn;

    void* sharedObjectHandle = nullptr;
    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), InvalidArgumentException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface1TestImpl()
{
    // Valid shared object handle
    // Wrong (not C-style) name mangling

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend1FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface2TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Wrong interface (missing GetBackendId())

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend2FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface3TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Wrong interface (missing GetVersion())

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend3FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface4TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Wrong interface (missing BackendFactory())

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend4FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface5TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Invalid (null) backend id returned by GetBackendId()

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend5FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface6TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Invalid (null) backend instance returned by BackendFactory()

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend6FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_NO_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)));
    BOOST_TEST((dynamicBackend != nullptr));

    BackendId dynamicBackendId;
    BOOST_CHECK_NO_THROW(dynamicBackendId = dynamicBackend->GetBackendId());
    BOOST_TEST((dynamicBackendId == "InvalidTestDynamicBackend"));

    BackendVersion dynamicBackendVersion;
    BOOST_CHECK_NO_THROW(dynamicBackendVersion = dynamicBackend->GetBackendVersion());
    BOOST_TEST((dynamicBackendVersion == BackendVersion({ 1, 0 })));

    IBackendInternalUniquePtr dynamicBackendInstance;
    BOOST_CHECK_THROW(dynamicBackendInstance = dynamicBackend->GetBackend(), RuntimeException);
    BOOST_TEST((dynamicBackendInstance == nullptr));
}

void CreateDynamicBackendObjectInvalidInterface7TestImpl()
{
    // Valid shared object handle
    // Correct name mangling
    // Correct interface
    // Invalid (incompatible backend API version) backend instance returned by BackendFactory()

    using namespace armnn;

    std::string sharedObjectFilePath = GetTestFilePath(g_TestInvalidTestDynamicBackend7FileName);

    void* sharedObjectHandle = nullptr;
    BOOST_CHECK_NO_THROW(sharedObjectHandle = DynamicBackendUtils::OpenHandle(sharedObjectFilePath));
    BOOST_TEST((sharedObjectHandle != nullptr));

    std::unique_ptr<DynamicBackend> dynamicBackend;
    BOOST_CHECK_THROW(dynamicBackend.reset(new DynamicBackend(sharedObjectHandle)), RuntimeException);
    BOOST_TEST((dynamicBackend == nullptr));
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/neteq4/tools/input_audio_file.h"

namespace webrtc {
namespace test {

InputAudioFile::InputAudioFile(const std::string file_name) {
  fp_ = fopen(file_name.c_str(), "rb");
}

InputAudioFile::~InputAudioFile() { fclose(fp_); }

bool InputAudioFile::Read(size_t samples, int16_t* destination) {
  if (!fp_) {
    return false;
  }
  size_t bytes_read = fread(destination, sizeof(int16_t), samples, fp_);
  if (bytes_read < samples) {
    // Rewind and read the missing sampels.
    rewind(fp_);
    size_t missing_samples = samples - bytes_read;
    if (fread(destination, sizeof(int16_t), missing_samples, fp_) <
        missing_samples) {
      // Could not read enough even after rewinding the file.
      return false;
    }
  }
  return true;
}

void InputAudioFile::DuplicateInterleaved(const int16_t* source, size_t samples,
                                          size_t channels,
                                          int16_t* destination) {
  for (size_t i = 0; i < samples; ++i) {
    for (size_t j = 0; j < channels; ++j) {
      destination[i * channels + j] = source[i];
    }
  }
}

}  // namespace test
}  // namespace webrtc
<commit_msg>Correcting two nits in InputAudioFile<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/audio_coding/neteq4/tools/input_audio_file.h"

namespace webrtc {
namespace test {

InputAudioFile::InputAudioFile(const std::string file_name) {
  fp_ = fopen(file_name.c_str(), "rb");
}

InputAudioFile::~InputAudioFile() { fclose(fp_); }

bool InputAudioFile::Read(size_t samples, int16_t* destination) {
  if (!fp_) {
    return false;
  }
  size_t samples_read = fread(destination, sizeof(int16_t), samples, fp_);
  if (samples_read < samples) {
    // Rewind and read the missing samples.
    rewind(fp_);
    size_t missing_samples = samples - samples_read;
    if (fread(destination, sizeof(int16_t), missing_samples, fp_) <
        missing_samples) {
      // Could not read enough even after rewinding the file.
      return false;
    }
  }
  return true;
}

void InputAudioFile::DuplicateInterleaved(const int16_t* source, size_t samples,
                                          size_t channels,
                                          int16_t* destination) {
  for (size_t i = 0; i < samples; ++i) {
    for (size_t j = 0; j < channels; ++j) {
      destination[i * channels + j] = source[i];
    }
  }
}

}  // namespace test
}  // namespace webrtc
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QCoreApplication>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>

#include "dbusthread.h"

class DBusThreadManager : public QObject
{
  public:
    static DBusThreadManager *self();

  protected:
    virtual void customEvent( QEvent *event );

  private:
    DBusThreadManager();

    static DBusThreadManager* mSelf;
    static QMutex mMutex;
};

class DBusThreadEvent : public QEvent
{
  public:
    DBusThreadEvent( DBusThread *thread, const QString &service, const QString &path,
                     const QString &inteface, const QString &method,
                     const QList<QVariant> &arguments )
      : QEvent( QEvent::User ),
        mThread( thread ), mService( service ), mPath( path ), mInterface( inteface ),
        mMethod( method ), mArguments( arguments )
    {
    }

    DBusThread *mThread;
    QString mService;
    QString mPath;
    QString mInterface;
    QString mMethod;
    QList<QVariant> mArguments;
};

DBusThread::DBusThread( QObject *parent )
  : QThread( parent )
{
}

QList<QVariant> DBusThread::callDBus( const QString &service, const QString &path,
                                      const QString &interface, const QString &method,
                                      const QList<QVariant> &arguments )
{
  mData.clear();

  DBusThreadEvent *event = new DBusThreadEvent( this, service, path, interface,
                                                method, arguments );

  DBusThreadManager *manager = DBusThreadManager::self();

  QCoreApplication::instance()->postEvent( manager, event );

  mMutex.lock();
  mCondition.wait( &mMutex );
  mMutex.unlock();

  return mData;
}

void DBusThread::wakeup( const QList<QVariant> &result )
{
  mData = result;

  mCondition.wakeAll();
}

DBusThreadManager* DBusThreadManager::mSelf = 0;
QMutex DBusThreadManager::mMutex;

DBusThreadManager::DBusThreadManager()
  : QObject( 0 )
{
}

DBusThreadManager *DBusThreadManager::self()
{
  mMutex.lock();

  if ( !mSelf ) {
      mSelf = new DBusThreadManager();

      /**
       * Move the proxy to the main (gui) thread, only this thread
       * can handle dbus calls.
       */
      mSelf->moveToThread( QCoreApplication::instance()->thread() );
  }

  mMutex.unlock();

  return mSelf;
}

void DBusThreadManager::customEvent( QEvent *_event )
{
  DBusThreadEvent *event = static_cast<DBusThreadEvent*>( _event );

  QDBusMessage message = QDBusMessage::createMethodCall( event->mService,
                                                         event->mPath,
                                                         event->mInterface,
                                                         event->mMethod );
  message.setArguments( event->mArguments );

  new DBusThreadProxy( event->mThread, message );
}

DBusThreadProxy::DBusThreadProxy( DBusThread *thread, const QDBusMessage &message )
  : mThread( thread )
{
  QDBusConnection::sessionBus().callWithCallback( message, this, SLOT( dbusReply( const QDBusMessage& ) ) );
}

void DBusThreadProxy::dbusReply( const QDBusMessage &message )
{
  if ( mThread )
    mThread->wakeup( message.arguments() );
  else
    qDebug( "DBusThreadProxy: thread was deleted during dbus call!" );

  deleteLater();
}

#include "dbusthread.moc"

<commit_msg>Prevent waking up threads that haven't gone to sleep yet.<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>

#include "dbusthread.h"

class DBusThreadManager : public QObject
{
  public:
    static DBusThreadManager *self();

  protected:
    virtual void customEvent( QEvent *event );

  private:
    DBusThreadManager();

    static DBusThreadManager* mSelf;
    static QMutex mMutex;
};

class DBusThreadEvent : public QEvent
{
  public:
    DBusThreadEvent( DBusThread *thread, const QString &service, const QString &path,
                     const QString &inteface, const QString &method,
                     const QList<QVariant> &arguments )
      : QEvent( QEvent::User ),
        mThread( thread ), mService( service ), mPath( path ), mInterface( inteface ),
        mMethod( method ), mArguments( arguments )
    {
    }

    DBusThread *mThread;
    QString mService;
    QString mPath;
    QString mInterface;
    QString mMethod;
    QList<QVariant> mArguments;
};

DBusThread::DBusThread( QObject *parent )
  : QThread( parent )
{
}

QList<QVariant> DBusThread::callDBus( const QString &service, const QString &path,
                                      const QString &interface, const QString &method,
                                      const QList<QVariant> &arguments )
{
  mData.clear();

  DBusThreadEvent *event = new DBusThreadEvent( this, service, path, interface,
                                                method, arguments );

  DBusThreadManager *manager = DBusThreadManager::self();

  mMutex.lock();

  QCoreApplication::instance()->postEvent( manager, event );

  mCondition.wait( &mMutex );
  mMutex.unlock();

  return mData;
}

void DBusThread::wakeup( const QList<QVariant> &result )
{
  mData = result;

  mMutex.lock();
  mCondition.wakeAll();
  mMutex.unlock();
}

DBusThreadManager* DBusThreadManager::mSelf = 0;
QMutex DBusThreadManager::mMutex;

DBusThreadManager::DBusThreadManager()
  : QObject( 0 )
{
}

DBusThreadManager *DBusThreadManager::self()
{
  mMutex.lock();

  if ( !mSelf ) {
      mSelf = new DBusThreadManager();

      /**
       * Move the proxy to the main (gui) thread, only this thread
       * can handle dbus calls.
       */
      mSelf->moveToThread( QCoreApplication::instance()->thread() );
  }

  mMutex.unlock();

  return mSelf;
}

void DBusThreadManager::customEvent( QEvent *_event )
{
  DBusThreadEvent *event = static_cast<DBusThreadEvent*>( _event );

  QDBusMessage message = QDBusMessage::createMethodCall( event->mService,
                                                         event->mPath,
                                                         event->mInterface,
                                                         event->mMethod );
  message.setArguments( event->mArguments );

  new DBusThreadProxy( event->mThread, message );
}

DBusThreadProxy::DBusThreadProxy( DBusThread *thread, const QDBusMessage &message )
  : mThread( thread )
{
  if ( !QDBusConnection::sessionBus().callWithCallback( message, this, SLOT( dbusReply( const QDBusMessage& ) ) ) )
    emit dbusReply( message.createError( QLatin1String("Call Error"), QLatin1String("callWithCallback() failed in DBusThreadProxy") ) );
}

void DBusThreadProxy::dbusReply( const QDBusMessage &message )
{
  if ( mThread )
    mThread->wakeup( message.arguments() );
  else
    qDebug( "DBusThreadProxy: thread was deleted during dbus call!" );

  deleteLater();
}

#include "dbusthread.moc"

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#pragma once

#include <array>
#include <cassert>
#include <cctype>
#include <fstream>
#include <string>
#include <vector>
#include <cstdint>
#include <algorithm>
#include <utility>
#include <uavcan_linux/exception.hpp>
#include <uavcan/data_type.hpp>

namespace uavcan_linux
{
/**
 * This class can find and read machine ID from a text file, represented as 32-char (16-byte) long hexadecimal string,
 * possibly with separators (like dashes or colons). If the available ID is more than 16 bytes, extra bytes will be
 * ignored. A shorter ID will not be accepted as valid.
 * In order to be read, the ID must be located on the first line of the file and must not contain any whitespace
 * characters.
 *
 * Examples of valid ID:
 *   0123456789abcdef0123456789abcdef
 *   20CE0b1E-8C03-07C8-13EC-00242C491652
 */
class MachineIDReader
{
public:
    static constexpr int MachineIDSize = 16;

    typedef std::array<std::uint8_t, MachineIDSize> MachineID;

    static std::vector<std::string> getDefaultSearchLocations()
    {
        return
        {
            "/etc/machine-id",
            "/var/lib/dbus/machine-id",
            "/sys/class/dmi/id/product_uuid"
        };
    }

private:
    const std::vector<std::string> search_locations_;

    static std::vector<std::string> mergeLists(const std::vector<std::string>& a, const std::vector<std::string>& b)
    {
        std::vector<std::string> ab;
        ab.reserve(a.size() + b.size());
        ab.insert(ab.end(), a.begin(), a.end());
        ab.insert(ab.end(), b.begin(), b.end());
        return ab;
    }

    bool tryRead(const std::string& location, MachineID& out_id) const
    {
        /*
         * Reading the file
         */
        std::string token;
        try
        {
            std::ifstream infile(location);
            infile >> token;
        }
        catch (std::exception&)
        {
            return false;
        }

        /*
         * Preprocessing the input string - convert to lowercase, remove all non-hex characters, limit to 32 chars
         */
        std::transform(token.begin(), token.end(), token.begin(), [](char x) { return std::tolower(x); });
        token.erase(std::remove_if(token.begin(), token.end(),
                                   [](char x){ return (x < 'a' || x > 'f') && !std::isdigit(x); }),
                    token.end());

        if (token.length() < (MachineIDSize * 2))
        {
            return false;
        }
        token.resize(MachineIDSize * 2);        // Truncating

        /*
         * Parsing the string as hex bytes
         */
        auto sym = std::begin(token);
        for (auto& byte : out_id)
        {
            assert(sym != std::end(token));
            byte = std::stoi(std::string{*sym++, *sym++}, nullptr, 16);
        }

        return true;
    }

public:
    /**
     * This class can use extra seach locations. If provided, they will be checked first, before default ones.
     */
    MachineIDReader(const std::vector<std::string>& extra_search_locations = {})
        : search_locations_(mergeLists(extra_search_locations, getDefaultSearchLocations()))
    { }

    /**
     * Just like @ref readAndGetLocation(), but this one doesn't return location where this ID was obtained from.
     */
    MachineID read() const { return readAndGetLocation().first; }

    /**
     * This function checks available search locations and reads the ID from the first valid location.
     * It returns std::pair<> with ID and the file path where it was read from.
     * In case if none of the search locations turned out to be valid, @ref uavcan_linux::Exception will be thrown.
     */
    std::pair<MachineID, std::string> readAndGetLocation() const
    {
        for (auto x : search_locations_)
        {
            auto out = MachineID();
            if (tryRead(x, out))
            {
                return {out, x};
            }
        }
        throw Exception("Failed to read machine ID");
    }
};

/**
 * This class computes unique ID for a UAVCAN node in a Linux application.
 * It takes the following inputs:
 *  - Unique machine ID
 *  - Node name string (e.g. "org.uavcan.linux_app.dynamic_node_id_server")
 *  - Instance ID byte, e.g. node ID
 */
std::array<std::uint8_t, 16> makeApplicationID(const MachineIDReader::MachineID& machine_id,
                                               const std::string& node_name,
                                               const std::uint8_t instance_id)
{
    union HalfID
    {
        std::uint64_t num;
        std::uint8_t bytes[8];

        HalfID(std::uint64_t arg_num) : num(arg_num) { }
    };

    std::array<std::uint8_t, 16> out;

    // First 8 bytes of the application ID are CRC64 of the machine ID in native byte order
    {
        uavcan::DataTypeSignatureCRC crc;
        crc.add(machine_id.data(), static_cast<unsigned>(machine_id.size()));
        HalfID half(crc.get());
        std::copy_n(half.bytes, 8, out.begin());
    }

    // Last 8 bytes of the application ID are CRC64 of the node name and optionally node ID
    {
        uavcan::DataTypeSignatureCRC crc;
        crc.add(reinterpret_cast<const std::uint8_t*>(node_name.c_str()), static_cast<unsigned>(node_name.length()));
        crc.add(instance_id);
        HalfID half(crc.get());
        std::copy_n(half.bytes, 8, out.begin() + 8);
    }

    return out;
}

}
<commit_msg>uavcan_linux::makeApplicationID() - instance_id made optional<commit_after>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#pragma once

#include <array>
#include <cassert>
#include <cctype>
#include <fstream>
#include <string>
#include <vector>
#include <cstdint>
#include <algorithm>
#include <utility>
#include <uavcan_linux/exception.hpp>
#include <uavcan/data_type.hpp>

namespace uavcan_linux
{
/**
 * This class can find and read machine ID from a text file, represented as 32-char (16-byte) long hexadecimal string,
 * possibly with separators (like dashes or colons). If the available ID is more than 16 bytes, extra bytes will be
 * ignored. A shorter ID will not be accepted as valid.
 * In order to be read, the ID must be located on the first line of the file and must not contain any whitespace
 * characters.
 *
 * Examples of valid ID:
 *   0123456789abcdef0123456789abcdef
 *   20CE0b1E-8C03-07C8-13EC-00242C491652
 */
class MachineIDReader
{
public:
    static constexpr int MachineIDSize = 16;

    typedef std::array<std::uint8_t, MachineIDSize> MachineID;

    static std::vector<std::string> getDefaultSearchLocations()
    {
        return
        {
            "/etc/machine-id",
            "/var/lib/dbus/machine-id",
            "/sys/class/dmi/id/product_uuid"
        };
    }

private:
    const std::vector<std::string> search_locations_;

    static std::vector<std::string> mergeLists(const std::vector<std::string>& a, const std::vector<std::string>& b)
    {
        std::vector<std::string> ab;
        ab.reserve(a.size() + b.size());
        ab.insert(ab.end(), a.begin(), a.end());
        ab.insert(ab.end(), b.begin(), b.end());
        return ab;
    }

    bool tryRead(const std::string& location, MachineID& out_id) const
    {
        /*
         * Reading the file
         */
        std::string token;
        try
        {
            std::ifstream infile(location);
            infile >> token;
        }
        catch (std::exception&)
        {
            return false;
        }

        /*
         * Preprocessing the input string - convert to lowercase, remove all non-hex characters, limit to 32 chars
         */
        std::transform(token.begin(), token.end(), token.begin(), [](char x) { return std::tolower(x); });
        token.erase(std::remove_if(token.begin(), token.end(),
                                   [](char x){ return (x < 'a' || x > 'f') && !std::isdigit(x); }),
                    token.end());

        if (token.length() < (MachineIDSize * 2))
        {
            return false;
        }
        token.resize(MachineIDSize * 2);        // Truncating

        /*
         * Parsing the string as hex bytes
         */
        auto sym = std::begin(token);
        for (auto& byte : out_id)
        {
            assert(sym != std::end(token));
            byte = std::stoi(std::string{*sym++, *sym++}, nullptr, 16);
        }

        return true;
    }

public:
    /**
     * This class can use extra seach locations. If provided, they will be checked first, before default ones.
     */
    MachineIDReader(const std::vector<std::string>& extra_search_locations = {})
        : search_locations_(mergeLists(extra_search_locations, getDefaultSearchLocations()))
    { }

    /**
     * Just like @ref readAndGetLocation(), but this one doesn't return location where this ID was obtained from.
     */
    MachineID read() const { return readAndGetLocation().first; }

    /**
     * This function checks available search locations and reads the ID from the first valid location.
     * It returns std::pair<> with ID and the file path where it was read from.
     * In case if none of the search locations turned out to be valid, @ref uavcan_linux::Exception will be thrown.
     */
    std::pair<MachineID, std::string> readAndGetLocation() const
    {
        for (auto x : search_locations_)
        {
            auto out = MachineID();
            if (tryRead(x, out))
            {
                return {out, x};
            }
        }
        throw Exception("Failed to read machine ID");
    }
};

/**
 * This class computes unique ID for a UAVCAN node in a Linux application.
 * It takes the following inputs:
 *  - Unique machine ID
 *  - Node name string (e.g. "org.uavcan.linux_app.dynamic_node_id_server")
 *  - Instance ID byte, e.g. node ID (optional)
 */
std::array<std::uint8_t, 16> makeApplicationID(const MachineIDReader::MachineID& machine_id,
                                               const std::string& node_name,
                                               const std::uint8_t instance_id = 0)
{
    union HalfID
    {
        std::uint64_t num;
        std::uint8_t bytes[8];

        HalfID(std::uint64_t arg_num) : num(arg_num) { }
    };

    std::array<std::uint8_t, 16> out;

    // First 8 bytes of the application ID are CRC64 of the machine ID in native byte order
    {
        uavcan::DataTypeSignatureCRC crc;
        crc.add(machine_id.data(), static_cast<unsigned>(machine_id.size()));
        HalfID half(crc.get());
        std::copy_n(half.bytes, 8, out.begin());
    }

    // Last 8 bytes of the application ID are CRC64 of the node name and optionally node ID
    {
        uavcan::DataTypeSignatureCRC crc;
        crc.add(reinterpret_cast<const std::uint8_t*>(node_name.c_str()), static_cast<unsigned>(node_name.length()));
        crc.add(instance_id);
        HalfID half(crc.get());
        std::copy_n(half.bytes, 8, out.begin() + 8);
    }

    return out;
}

}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/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.
 *
 *=========================================================================*/

/**
printThetas
  Set hyperparameters for a N-D Gaussian Process Model Emulator

ACKNOWLEDGMENTS:
  This software was written in 2012-2013 by Hal Canary
  <cs.unc.edu/~hal>, based off of the MADAIEmulator program (Copyright
  2009-2012 Duke University) by C.Coleman-Smith <cec24@phy.duke.edu>
  in 2010-2012 while working for the MADAI project <http://madai.us/>.

USE:
  For details on how to use printThetas, consult the manpage via:
    $ nroff -man < [PATH_TO/]printThetas.1 | less
  or, if the manual is installed:
    $ man 1 printThetas
*/

const char useage [] =
  "Usage:\n"
  "    printThetas ModelSnapshotFile\n"
  "\n"
  "ModelSnapshotFile can be \"-\" or read from standard input.\n";

#include <iostream> // cout, cin
#include <fstream> // ifstream, ofstream

#include "GaussianProcessEmulator.h"

int main(int argc, char ** argv) {
  char const * inputFile = NULL;
  if (argc > 1) {
    inputFile = argv[1];
  } else {
    std::cerr << useage << '\n';
    return EXIT_FAILURE;
  }

  madai::GaussianProcessEmulator gpe;
  std::ostream & output = std::cout;

  std::istream * input = & std::cin;
  std::ifstream inputFileStream;

  if (0 != strcmp(inputFile, "-")) {
    inputFileStream.open(inputFile);
    if (! inputFileStream.good())
      std::cerr << "Error (1) loading file " << inputFile << '\n';
    input = & inputFileStream;
  }
  if (! gpe.Load(* input)) {
    std::cerr << "Error (2) loading file " << inputFile << '\n';
    return EXIT_FAILURE;
  }
  if (gpe.GetStatus() != madai::GaussianProcessEmulator::READY) {
    std::cerr << "Error (3) loading file " << inputFile << '\n';
    return EXIT_FAILURE;
  }
  if(! gpe.PrintThetas(output)) {
    std::cerr << "Error printing Thetas.\n";
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
<commit_msg>Now reads from the directory structure rather than the single file structure.<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/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.
 *
 *=========================================================================*/

/**
printThetas
  Set hyperparameters for a N-D Gaussian Process Model Emulator

ACKNOWLEDGMENTS:
  This software was written in 2012-2013 by Hal Canary
  <cs.unc.edu/~hal>, based off of the MADAIEmulator program (Copyright
  2009-2012 Duke University) by C.Coleman-Smith <cec24@phy.duke.edu>
  in 2010-2012 while working for the MADAI project <http://madai.us/>.

USE:
  For details on how to use printThetas, consult the manpage via:
    $ nroff -man < [PATH_TO/]printThetas.1 | less
  or, if the manual is installed:
    $ man 1 printThetas
*/

const char useage [] =
  "Usage:\n"
  "    printThetas TopDirectory\n"
  "\n"
  "TopDirectory is the directory containing the model_output/, experimental_results/\n"
  "and statistical_analysis/directories. It can also be \"-\" to read from standard input.\n";

#include <iostream> // cout, cin
#include <fstream> // ifstream, ofstream

#include "GaussianProcessEmulator.h"

int main(int argc, char ** argv) {
  char const * TopDirectory = NULL;
  if (argc > 1) {
    TopDirectory = argv[1];
  } else {
    std::cerr << useage << '\n';
    return EXIT_FAILURE;
  }

  madai::GaussianProcessEmulator gpe;
  std::ostream & output = std::cout;

  if (0 == strcmp(TopDirectory, "-")) {
    if (! gpe.Load( std::cin ) ){
      std::cerr << "Error (2) loading emulator from cin\n";
      return EXIT_FAILURE;
    }
  } else {
    std::string PCAFile(TopDirectory);
    PCAFile += "/statistical_analysis/PCADecomposition.dat";
    if ( gpe.LoadConfiguration() != madai::Model::NO_ERROR) {
      std::cerr << "Error (2) loading file " << PCAFile << '\n';
      return EXIT_FAILURE;
    }
  }

  if (gpe.GetStatus() != madai::GaussianProcessEmulator::READY) {
    std::cerr << "Error (3) loading file " << inputFile << '\n';
    return EXIT_FAILURE;
  }
  if(! gpe.PrintThetas(output)) {
    std::cerr << "Error printing Thetas.\n";
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
<|endoftext|>