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

  This file is part of the elastix software.

  Copyright (c) University Medical Center Utrecht. All rights reserved.
  See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
  details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE. See the above copyright notices for more information.

======================================================================*/
#include "elxElastixBase.h"
#include <sstream>
#include "itkMersenneTwisterRandomVariateGenerator.h"

namespace elastix
{

/**
 * ********************* Constructor ****************************
 */

ElastixBase::ElastixBase()
{
  /** Initialize. */
  this->m_Configuration = 0;
  this->m_ComponentDatabase = 0;
  this->m_DBIndex = 0;

  /** The default output precision of elxout is set to 6. */
  this->m_DefaultOutputPrecision = 6;

  /** Create the component containers. */
  this->m_FixedImagePyramidContainer = ObjectContainerType::New();
  this->m_MovingImagePyramidContainer = ObjectContainerType::New();
  this->m_InterpolatorContainer = ObjectContainerType::New();
  this->m_ImageSamplerContainer = ObjectContainerType::New();
  this->m_MetricContainer = ObjectContainerType::New();
  this->m_OptimizerContainer = ObjectContainerType::New();
  this->m_RegistrationContainer = ObjectContainerType::New();
  this->m_ResamplerContainer = ObjectContainerType::New();
  this->m_ResampleInterpolatorContainer = ObjectContainerType::New();
  this->m_TransformContainer = ObjectContainerType::New();

  /** Create image and mask containers. */
  this->m_FixedImageContainer = DataObjectContainerType::New();
  this->m_MovingImageContainer = DataObjectContainerType::New();
  this->m_FixedImageFileNameContainer = FileNameContainerType::New();
  this->m_MovingImageFileNameContainer = FileNameContainerType::New();

  this->m_FixedMaskContainer = DataObjectContainerType::New();
  this->m_MovingMaskContainer = DataObjectContainerType::New();
  this->m_FixedMaskFileNameContainer = FileNameContainerType::New();
  this->m_MovingMaskFileNameContainer = FileNameContainerType::New();

  /** Initialize initialTransform and final transform. */
  this->m_InitialTransform = 0;
  this->m_FinalTransform = 0;

  /** Ignore direction cosines by default, for backward compatability. */
  this->m_UseDirectionCosines = false;

} // end Constructor

/**
 * ********************* SetDBIndex ***********************
 */

void ElastixBase::SetDBIndex( DBIndexType _arg )
{
  /** If m_DBIndex is not set, set it. */
  if ( this->m_DBIndex != _arg )
  {
    this->m_DBIndex = _arg;

    itk::Object * thisasobject = dynamic_cast<itk::Object *>( this );
    if ( thisasobject )
    {
      thisasobject->Modified();
    }
  }

} // end SetDBIndex()

/**
 * ************************ BeforeAllBase ***************************
 */

int ElastixBase::BeforeAllBase( void )
{
  /** Declare the return value and initialize it. */
  int returndummy = 0;

  /** Set the default precision of floating values in the output. */
  this->m_Configuration->ReadParameter(
    this->m_DefaultOutputPrecision, "DefaultOutputPrecision", 0, false );
  elxout << std::setprecision( this->m_DefaultOutputPrecision );

  /** Print to log file. */
  elxout << std::fixed;
  elxout << std::showpoint;
  elxout << std::setprecision( 3 );
  elxout << "ELASTIX version: " << __ELASTIX_VERSION << std::endl;
  elxout << std::setprecision( this->GetDefaultOutputPrecision() );

  /** Check Command line options and print them to the logfile. */
  elxout << "Command line options from ElastixBase:" << std::endl;
  std::string check = "";

  /** Read the fixed and moving image filenames. These are obliged options,
   * so print an error if they are not present.
   * Print also some info (second boolean = true).
   */
  this->m_FixedImageFileNameContainer = this->GenerateFileNameContainer(
    "-f", returndummy, true, true );
  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(
    "-m", returndummy, true, true );

  /** Read the fixed and moving mask filenames. These are not obliged options,
   * so do not print any errors if they are not present.
   * Do print some info (second boolean = true).
   */
  int maskreturndummy = 0;
  this->m_FixedMaskFileNameContainer = this->GenerateFileNameContainer(
    "-fMask", maskreturndummy, false, true );
  if ( maskreturndummy != 0 )
  {
    elxout << "-fMask    unspecified, so no fixed mask used" << std::endl;
  }
  maskreturndummy = 0;
  this->m_MovingMaskFileNameContainer = this->GenerateFileNameContainer(
    "-mMask", maskreturndummy, false, true );
  if ( maskreturndummy != 0 )
  {
    elxout << "-mMask    unspecified, so no moving mask used" << std::endl;
  }

  /** Check for appearance of "-out".
   * This check has already been performed in elastix.cxx,
   * Here we do it again.
   */
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-out" );
  if ( check == "" )
  {
    xl::xout["error"] << "ERROR: No CommandLine option \"-out\" given!" << std::endl;
    returndummy |= 1;
  }
  else
  {
    /** Make sure that last character of -out equals a '/'. */
    std::string folder( check );
    if ( folder.find_last_of( "/" ) != folder.size() - 1 )
    {
      folder.append( "/" );
      this->GetConfiguration()->SetCommandLineArgument( "-out", folder.c_str() );
    }
    elxout << "-out      " << check << std::endl;
  }

  /** Print all "-p". */
  unsigned int i = 1;
  bool loop = true;
  while ( loop )
  {
    check = "";
    std::ostringstream tempPname("");
    tempPname << "-p(" << i << ")";
    check = this->GetConfiguration()->GetCommandLineArgument( tempPname.str().c_str() );
    if ( check == "" ) loop = false;
    else elxout << "-p        " << check << std::endl;
    ++i;
  }

  /** Check for appearance of "-priority", if this is a Windows station. */
#ifdef _WIN32
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-priority" );
  if ( check == "" )
  {
    elxout << "-priority unspecified, so NORMAL process priority" << std::endl;
  }
  else
  {
    elxout << "-priority " << check << std::endl;
  }
#endif

  /** Check for appearance of -threads, which specifies the maximum number of threads. */
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-threads" );
  if ( check == "" )
  {
    elxout << "-threads  unspecified, so all available threads are used" << std::endl;
  }
  else
  {
    elxout << "-threads  " << check << std::endl;
  }

  /** Check the very important UseDirectionCosines parameter. */
  this->m_UseDirectionCosines = false;
  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,
    "UseDirectionCosines", 0 );
  if ( !retudc )
  {
    xl::xout["warning"]
      << "\nWARNING: From elastix 4.3 it is highly recommended to add\n"
      << "the UseDirectionCosines option to your parameter file! See\n"
      << "http://elastix.isi.uu.nl/whatsnew_04_3.php for more information.\n"
      << std::endl;
  }

  /** Set the random seed. Use 121212 as a default, which is the same as
   * the default in the MersenneTwister code.
   * Use silent parameter file readout, to avoid annoying warning when
   * starting elastix */
  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
  typedef RandomGeneratorType::IntegerType SeedType;
  unsigned int randomSeed = 121212;
  this->GetConfiguration()->ReadParameter( randomSeed, "RandomSeed", 0, false );
  RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();
  randomGenerator->SetSeed( static_cast<SeedType>( randomSeed ) );

  /** Return a value. */
  return returndummy;

} // end BeforeAllBase()

/**
 * ************************ BeforeAllTransformixBase ***************************
 */

int ElastixBase::BeforeAllTransformixBase( void )
{
  /** Declare the return value and initialize it. */
  int returndummy = 0;

  /** Print to log file. */
  elxout << std::fixed;
  elxout << std::showpoint;
  elxout << std::setprecision( 3 );
  elxout << "ELASTIX version: " << __ELASTIX_VERSION << std::endl;
  elxout << std::setprecision( this->GetDefaultOutputPrecision() );

  /** Check Command line options and print them to the logfile. */
  elxout << "Command line options from ElastixBase:" << std::endl;
  std::string check = "";

  /** Read the input image filenames. These are not obliged options,
   * so do not print an error if they are not present.
   * Print also some info (second boolean = true)
   * Save the result in the moving image file name container.
   */
  int inreturndummy = 0;
  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(
    "-in", inreturndummy, false, true );
  if ( inreturndummy != 0 )
  {
    elxout << "-in       unspecified, so no input image specified" << std::endl;
  }

  /** Check for appearance of "-out". */
  check = this->GetConfiguration()->GetCommandLineArgument( "-out" );
  if ( check == "" )
  {
    xl::xout["error"] << "ERROR: No CommandLine option \"-out\" given!" << std::endl;
    returndummy |= 1;
  }
  else
  {
    /** Make sure that last character of -out equals a '/'. */
    std::string folder( check );
    if ( folder.find_last_of( "/" ) != folder.size() - 1 )
    {
      folder.append( "/" );
      this->GetConfiguration()->SetCommandLineArgument( "-out", folder.c_str() );
    }
    elxout << "-out      " << check << std::endl;
  }

  /** Check for appearance of -threads, which specifies the maximum number of threads. */
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-threads" );
  if ( check == "" )
  {
    elxout << "-threads  unspecified, so all available threads are used" << std::endl;
  }
  else
  {
    elxout << "-threads  " << check << std::endl;
  }

  /** Print "-tp". */
  check = this->GetConfiguration()->GetCommandLineArgument( "-tp" );
  elxout << "-tp       " << check << std::endl;

  /** Check the very important UseDirectionCosines parameter. */
  this->m_UseDirectionCosines = false;
  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,
    "UseDirectionCosines", 0 );
  if ( !retudc )
  {
    xl::xout["warning"]
      << "\nWARNING: From elastix 4.3 it is highly recommended to add\n"
      << "the UseDirectionCosines option to your parameter file! See\n"
      << "http://elastix.isi.uu.nl/whatsnew_04_3.php for more information.\n"
      << std::endl;
  }

  return returndummy;

} // end BeforeAllTransformixBase()

/**
 * ************************ BeforeRegistrationBase ******************
 */

void ElastixBase::BeforeRegistrationBase( void )
{
  using namespace xl;

  /** Set up the "iteration" writing field. */
  this->m_IterationInfo.SetOutputs( xout.GetCOutputs() );
  this->m_IterationInfo.SetOutputs( xout.GetXOutputs() );

  xout.AddTargetCell( "iteration", &this->m_IterationInfo );

} // end BeforeRegistrationBase()

/**
 * **************** AfterRegistrationBase ***********************
 */

void ElastixBase::AfterRegistrationBase( void )
{
  /** Remove the "iteration" writing field. */
  xl::xout.RemoveTargetCell( "iteration" );

} // end AfterRegistrationBase()

/**
 * ********************* GenerateFileNameContainer ******************
 */

ElastixBase::FileNameContainerPointer
ElastixBase::GenerateFileNameContainer(
  const std::string & optionkey, int & errorcode,
  bool printerrors, bool printinfo ) const
{
  FileNameContainerPointer fileNameContainer = FileNameContainerType::New();
  std::string check = "";
  std::string argused( "" );

  /** Try optionkey0. */
  std::ostringstream argusedss( "" );
  argusedss << optionkey << 0;
  argused = argusedss.str();
  check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );
  if ( check == "" )
  {
    /** Try optionkey. */
    std::ostringstream argusedss2( "" );
    argusedss2 << optionkey;
    argused = argusedss2.str();
    check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );
    if ( check == "" )
    {
      /** Both failed; return an error message, if desired. */
      if ( printerrors )
      {
        xl::xout["error"]
        << "ERROR: No CommandLine option \""
          << optionkey << "\" or \""
          << optionkey << 0 << "\" given!" << std::endl;
      }
      errorcode |= 1;

      return fileNameContainer;
    }
  }

  /** Optionkey or optionkey0 is found. */
  if ( check != "" )
  {
    /** Print info, if desired. */
    if ( printinfo )
    {
      /** Print the option, with some spaces, followed by the value. */
      int nrSpaces0 = 10 - argused.length();
      unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;
      std::string spaces = "";
      spaces.resize( nrSpaces, ' ' );
      elxout << argused << spaces << check << std::endl;
    }
    fileNameContainer->CreateElementAt( 0 ) = check;

    /** Loop over all optionkey<i> options given with i > 0. */
    unsigned int i = 1;
    bool readsuccess = true;
    while ( readsuccess )
    {
      std::ostringstream argusedss2( "" );
      argusedss2 << optionkey << i;
      argused = argusedss2.str();
      check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );
      if ( check == "" )
      {
        readsuccess = false;
      }
      else
      {
        if ( printinfo )
        {
          /** Print the option, with some spaces, followed by the value. */
          int nrSpaces0 = 10 - argused.length();
          unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;
          std::string spaces = "";
          spaces.resize( nrSpaces, ' ' );
          elxout << argused << spaces << check << std::endl;
        }
        fileNameContainer->CreateElementAt(i) = check;
        ++i;
      }
    } // end while
  } // end if

  return fileNameContainer;

} // end GenerateFileNameContainer()

/**
 * ******************** GetUseDirectionCosines ********************
 */

bool ElastixBase::GetUseDirectionCosines( void ) const
{
  return this->m_UseDirectionCosines;
}

/**
 * ******************** SetOriginalFixedImageDirectionFlat ********************
 */

void ElastixBase::SetOriginalFixedImageDirectionFlat(
  const FlatDirectionCosinesType & arg )
{
  this->m_OriginalFixedImageDirection = arg;
}

/**
 * ******************** GetOriginalFixedImageDirectionFlat ********************
 */

const ElastixBase::FlatDirectionCosinesType &
ElastixBase::GetOriginalFixedImageDirectionFlat( void ) const
{
  return this->m_OriginalFixedImageDirection;
}

} // end namespace elastix

<commit_msg>BUG: last slash of output dir should be \ under windows/cygwin<commit_after>/*======================================================================

  This file is part of the elastix software.

  Copyright (c) University Medical Center Utrecht. All rights reserved.
  See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
  details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE. See the above copyright notices for more information.

======================================================================*/
#include "elxElastixBase.h"
#include <sstream>
#include "itkMersenneTwisterRandomVariateGenerator.h"

namespace elastix
{

/**
 * ********************* Constructor ****************************
 */

ElastixBase::ElastixBase()
{
  /** Initialize. */
  this->m_Configuration = 0;
  this->m_ComponentDatabase = 0;
  this->m_DBIndex = 0;

  /** The default output precision of elxout is set to 6. */
  this->m_DefaultOutputPrecision = 6;

  /** Create the component containers. */
  this->m_FixedImagePyramidContainer = ObjectContainerType::New();
  this->m_MovingImagePyramidContainer = ObjectContainerType::New();
  this->m_InterpolatorContainer = ObjectContainerType::New();
  this->m_ImageSamplerContainer = ObjectContainerType::New();
  this->m_MetricContainer = ObjectContainerType::New();
  this->m_OptimizerContainer = ObjectContainerType::New();
  this->m_RegistrationContainer = ObjectContainerType::New();
  this->m_ResamplerContainer = ObjectContainerType::New();
  this->m_ResampleInterpolatorContainer = ObjectContainerType::New();
  this->m_TransformContainer = ObjectContainerType::New();

  /** Create image and mask containers. */
  this->m_FixedImageContainer = DataObjectContainerType::New();
  this->m_MovingImageContainer = DataObjectContainerType::New();
  this->m_FixedImageFileNameContainer = FileNameContainerType::New();
  this->m_MovingImageFileNameContainer = FileNameContainerType::New();

  this->m_FixedMaskContainer = DataObjectContainerType::New();
  this->m_MovingMaskContainer = DataObjectContainerType::New();
  this->m_FixedMaskFileNameContainer = FileNameContainerType::New();
  this->m_MovingMaskFileNameContainer = FileNameContainerType::New();

  /** Initialize initialTransform and final transform. */
  this->m_InitialTransform = 0;
  this->m_FinalTransform = 0;

  /** Ignore direction cosines by default, for backward compatability. */
  this->m_UseDirectionCosines = false;

} // end Constructor

/**
 * ********************* SetDBIndex ***********************
 */

void ElastixBase::SetDBIndex( DBIndexType _arg )
{
  /** If m_DBIndex is not set, set it. */
  if ( this->m_DBIndex != _arg )
  {
    this->m_DBIndex = _arg;

    itk::Object * thisasobject = dynamic_cast<itk::Object *>( this );
    if ( thisasobject )
    {
      thisasobject->Modified();
    }
  }

} // end SetDBIndex()

/**
 * ************************ BeforeAllBase ***************************
 */

int ElastixBase::BeforeAllBase( void )
{
  /** Declare the return value and initialize it. */
  int returndummy = 0;

  /** Set the default precision of floating values in the output. */
  this->m_Configuration->ReadParameter(
    this->m_DefaultOutputPrecision, "DefaultOutputPrecision", 0, false );
  elxout << std::setprecision( this->m_DefaultOutputPrecision );

  /** Print to log file. */
  elxout << std::fixed;
  elxout << std::showpoint;
  elxout << std::setprecision( 3 );
  elxout << "ELASTIX version: " << __ELASTIX_VERSION << std::endl;
  elxout << std::setprecision( this->GetDefaultOutputPrecision() );

  /** Check Command line options and print them to the logfile. */
  elxout << "Command line options from ElastixBase:" << std::endl;
  std::string check = "";

  /** Read the fixed and moving image filenames. These are obliged options,
   * so print an error if they are not present.
   * Print also some info (second boolean = true).
   */
  this->m_FixedImageFileNameContainer = this->GenerateFileNameContainer(
    "-f", returndummy, true, true );
  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(
    "-m", returndummy, true, true );

  /** Read the fixed and moving mask filenames. These are not obliged options,
   * so do not print any errors if they are not present.
   * Do print some info (second boolean = true).
   */
  int maskreturndummy = 0;
  this->m_FixedMaskFileNameContainer = this->GenerateFileNameContainer(
    "-fMask", maskreturndummy, false, true );
  if ( maskreturndummy != 0 )
  {
    elxout << "-fMask    unspecified, so no fixed mask used" << std::endl;
  }
  maskreturndummy = 0;
  this->m_MovingMaskFileNameContainer = this->GenerateFileNameContainer(
    "-mMask", maskreturndummy, false, true );
  if ( maskreturndummy != 0 )
  {
    elxout << "-mMask    unspecified, so no moving mask used" << std::endl;
  }

  /** Check for appearance of "-out".
   * This check has already been performed in elastix.cxx,
   * Here we do it again. MS: WHY?
   */
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-out" );
  if ( check == "" )
  {
    xl::xout["error"] << "ERROR: No CommandLine option \"-out\" given!" << std::endl;
    returndummy |= 1;
  }
  else
  {
    /** Make sure that last character of the output folder equals a '/' or '\'. */
    std::string folder( check );
    const char last = folder[ folder.size() - 1 ];
    if( last != '/' && last != '\\' )
    {
      folder.append( "/" );
      folder = itksys::SystemTools::ConvertToOutputPath( folder.c_str() );
      this->GetConfiguration()->SetCommandLineArgument( "-out", folder.c_str() );
    }
    elxout << "-out      " << check << std::endl;
  }

  /** Print all "-p". */
  unsigned int i = 1;
  bool loop = true;
  while ( loop )
  {
    check = "";
    std::ostringstream tempPname("");
    tempPname << "-p(" << i << ")";
    check = this->GetConfiguration()->GetCommandLineArgument( tempPname.str().c_str() );
    if ( check == "" ) loop = false;
    else elxout << "-p        " << check << std::endl;
    ++i;
  }

  /** Check for appearance of "-priority", if this is a Windows station. */
#ifdef _WIN32
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-priority" );
  if ( check == "" )
  {
    elxout << "-priority unspecified, so NORMAL process priority" << std::endl;
  }
  else
  {
    elxout << "-priority " << check << std::endl;
  }
#endif

  /** Check for appearance of -threads, which specifies the maximum number of threads. */
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-threads" );
  if ( check == "" )
  {
    elxout << "-threads  unspecified, so all available threads are used" << std::endl;
  }
  else
  {
    elxout << "-threads  " << check << std::endl;
  }

  /** Check the very important UseDirectionCosines parameter. */
  this->m_UseDirectionCosines = false;
  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,
    "UseDirectionCosines", 0 );
  if ( !retudc )
  {
    xl::xout["warning"]
      << "\nWARNING: From elastix 4.3 it is highly recommended to add\n"
      << "the UseDirectionCosines option to your parameter file! See\n"
      << "http://elastix.isi.uu.nl/whatsnew_04_3.php for more information.\n"
      << std::endl;
  }

  /** Set the random seed. Use 121212 as a default, which is the same as
   * the default in the MersenneTwister code.
   * Use silent parameter file readout, to avoid annoying warning when
   * starting elastix */
  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
  typedef RandomGeneratorType::IntegerType SeedType;
  unsigned int randomSeed = 121212;
  this->GetConfiguration()->ReadParameter( randomSeed, "RandomSeed", 0, false );
  RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();
  randomGenerator->SetSeed( static_cast<SeedType>( randomSeed ) );

  /** Return a value. */
  return returndummy;

} // end BeforeAllBase()

/**
 * ************************ BeforeAllTransformixBase ***************************
 */

int ElastixBase::BeforeAllTransformixBase( void )
{
  /** Declare the return value and initialize it. */
  int returndummy = 0;

  /** Print to log file. */
  elxout << std::fixed;
  elxout << std::showpoint;
  elxout << std::setprecision( 3 );
  elxout << "ELASTIX version: " << __ELASTIX_VERSION << std::endl;
  elxout << std::setprecision( this->GetDefaultOutputPrecision() );

  /** Check Command line options and print them to the logfile. */
  elxout << "Command line options from ElastixBase:" << std::endl;
  std::string check = "";

  /** Read the input image filenames. These are not obliged options,
   * so do not print an error if they are not present.
   * Print also some info (second boolean = true)
   * Save the result in the moving image file name container.
   */
  int inreturndummy = 0;
  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(
    "-in", inreturndummy, false, true );
  if ( inreturndummy != 0 )
  {
    elxout << "-in       unspecified, so no input image specified" << std::endl;
  }

  /** Check for appearance of "-out". */
  check = this->GetConfiguration()->GetCommandLineArgument( "-out" );
  if ( check == "" )
  {
    xl::xout["error"] << "ERROR: No CommandLine option \"-out\" given!" << std::endl;
    returndummy |= 1;
  }
  else
  {
    /** Make sure that last character of -out equals a '/'. */
    std::string folder( check );
    if ( folder.find_last_of( "/" ) != folder.size() - 1 )
    {
      folder.append( "/" );
      this->GetConfiguration()->SetCommandLineArgument( "-out", folder.c_str() );
    }
    elxout << "-out      " << check << std::endl;
  }

  /** Check for appearance of -threads, which specifies the maximum number of threads. */
  check = "";
  check = this->GetConfiguration()->GetCommandLineArgument( "-threads" );
  if ( check == "" )
  {
    elxout << "-threads  unspecified, so all available threads are used" << std::endl;
  }
  else
  {
    elxout << "-threads  " << check << std::endl;
  }

  /** Print "-tp". */
  check = this->GetConfiguration()->GetCommandLineArgument( "-tp" );
  elxout << "-tp       " << check << std::endl;

  /** Check the very important UseDirectionCosines parameter. */
  this->m_UseDirectionCosines = false;
  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,
    "UseDirectionCosines", 0 );
  if ( !retudc )
  {
    xl::xout["warning"]
      << "\nWARNING: From elastix 4.3 it is highly recommended to add\n"
      << "the UseDirectionCosines option to your parameter file! See\n"
      << "http://elastix.isi.uu.nl/whatsnew_04_3.php for more information.\n"
      << std::endl;
  }

  return returndummy;

} // end BeforeAllTransformixBase()

/**
 * ************************ BeforeRegistrationBase ******************
 */

void ElastixBase::BeforeRegistrationBase( void )
{
  using namespace xl;

  /** Set up the "iteration" writing field. */
  this->m_IterationInfo.SetOutputs( xout.GetCOutputs() );
  this->m_IterationInfo.SetOutputs( xout.GetXOutputs() );

  xout.AddTargetCell( "iteration", &this->m_IterationInfo );

} // end BeforeRegistrationBase()

/**
 * **************** AfterRegistrationBase ***********************
 */

void ElastixBase::AfterRegistrationBase( void )
{
  /** Remove the "iteration" writing field. */
  xl::xout.RemoveTargetCell( "iteration" );

} // end AfterRegistrationBase()

/**
 * ********************* GenerateFileNameContainer ******************
 */

ElastixBase::FileNameContainerPointer
ElastixBase::GenerateFileNameContainer(
  const std::string & optionkey, int & errorcode,
  bool printerrors, bool printinfo ) const
{
  FileNameContainerPointer fileNameContainer = FileNameContainerType::New();
  std::string check = "";
  std::string argused( "" );

  /** Try optionkey0. */
  std::ostringstream argusedss( "" );
  argusedss << optionkey << 0;
  argused = argusedss.str();
  check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );
  if ( check == "" )
  {
    /** Try optionkey. */
    std::ostringstream argusedss2( "" );
    argusedss2 << optionkey;
    argused = argusedss2.str();
    check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );
    if ( check == "" )
    {
      /** Both failed; return an error message, if desired. */
      if ( printerrors )
      {
        xl::xout["error"]
        << "ERROR: No CommandLine option \""
          << optionkey << "\" or \""
          << optionkey << 0 << "\" given!" << std::endl;
      }
      errorcode |= 1;

      return fileNameContainer;
    }
  }

  /** Optionkey or optionkey0 is found. */
  if ( check != "" )
  {
    /** Print info, if desired. */
    if ( printinfo )
    {
      /** Print the option, with some spaces, followed by the value. */
      int nrSpaces0 = 10 - argused.length();
      unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;
      std::string spaces = "";
      spaces.resize( nrSpaces, ' ' );
      elxout << argused << spaces << check << std::endl;
    }
    fileNameContainer->CreateElementAt( 0 ) = check;

    /** Loop over all optionkey<i> options given with i > 0. */
    unsigned int i = 1;
    bool readsuccess = true;
    while ( readsuccess )
    {
      std::ostringstream argusedss2( "" );
      argusedss2 << optionkey << i;
      argused = argusedss2.str();
      check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );
      if ( check == "" )
      {
        readsuccess = false;
      }
      else
      {
        if ( printinfo )
        {
          /** Print the option, with some spaces, followed by the value. */
          int nrSpaces0 = 10 - argused.length();
          unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;
          std::string spaces = "";
          spaces.resize( nrSpaces, ' ' );
          elxout << argused << spaces << check << std::endl;
        }
        fileNameContainer->CreateElementAt(i) = check;
        ++i;
      }
    } // end while
  } // end if

  return fileNameContainer;

} // end GenerateFileNameContainer()

/**
 * ******************** GetUseDirectionCosines ********************
 */

bool ElastixBase::GetUseDirectionCosines( void ) const
{
  return this->m_UseDirectionCosines;
}

/**
 * ******************** SetOriginalFixedImageDirectionFlat ********************
 */

void ElastixBase::SetOriginalFixedImageDirectionFlat(
  const FlatDirectionCosinesType & arg )
{
  this->m_OriginalFixedImageDirection = arg;
}

/**
 * ******************** GetOriginalFixedImageDirectionFlat ********************
 */

const ElastixBase::FlatDirectionCosinesType &
ElastixBase::GetOriginalFixedImageDirectionFlat( void ) const
{
  return this->m_OriginalFixedImageDirection;
}

} // end namespace elastix

<|endoftext|>


<commit_before>#include "BoyerMoore.hpp"

BoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const char* pattern)
    : pattern(pattern),
      patternLength(strlen(pattern)) {
    if(patternLength != 0) {
        initializeSkipTable();
    }
}

BoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const std::string& patternParam)
    : pattern(patternParam.c_str()),
      patternLength(patternParam.size()) {
    if(patternLength != 0) {
        initializeSkipTable();
    }
}

void BoyerMooreHorspoolSearcher::initializeSkipTable() {
    assert(pattern);
    //Initialize table to maximum skip length
    for (size_t i = 0;i < SKIPTABLE_LENGTH; i++) {
        skipTable[i] = patternLength;
    }
    //Calculate skip table for characters that exist in the pattern.
    for (size_t i = 0; i < patternLength - 1; i++) {
        skipTable[(uint8_t)pattern[i]] = patternLength - i - 1;
    }
}

const int BoyerMooreHorspoolSearcher::find(const char* corpus) {
    return find(corpus, strlen(corpus));
}

const int BoyerMooreHorspoolSearcher::find(const std::string& corpus) {
    return find(corpus.c_str(), corpus.size());
}

const int BoyerMooreHorspoolSearcher::find(const char* corpus, size_t corpusLength) {
    assert(corpus);
    //Shortcut if there's an empty pattern (--> we DEFINE that as not found)
    if(patternLength == 0) {
        return -1;
    }
    //Can't find pattern if its larger than corpus
    if (patternLength > corpusLength) {
        return -1;
    }
    for(int k = patternLength - 1 ; k < corpusLength ; ) {
        int j = patternLength - 1;
        int i = k;
        while (j >= 0 && corpus[i] == pattern[j]) {
            j--;
            i--;
        }
        if (j == -1) {
            return i + 1;
        }
        k += skipTable[(uint8_t)corpus[k]];
    }
    //Couldn't find it
    return -1;
}<commit_msg>Fix signed/unsigned compare warning<commit_after>#include "BoyerMoore.hpp"

BoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const char* pattern)
    : pattern(pattern),
      patternLength(strlen(pattern)) {
    if(patternLength != 0) {
        initializeSkipTable();
    }
}

BoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const std::string& patternParam)
    : pattern(patternParam.c_str()),
      patternLength(patternParam.size()) {
    if(patternLength != 0) {
        initializeSkipTable();
    }
}

void BoyerMooreHorspoolSearcher::initializeSkipTable() {
    assert(pattern);
    //Initialize table to maximum skip length
    for (size_t i = 0;i < SKIPTABLE_LENGTH; i++) {
        skipTable[i] = patternLength;
    }
    //Calculate skip table for characters that exist in the pattern.
    for (size_t i = 0; i < patternLength - 1; i++) {
        skipTable[(uint8_t)pattern[i]] = patternLength - i - 1;
    }
}

const int BoyerMooreHorspoolSearcher::find(const char* corpus) {
    return find(corpus, strlen(corpus));
}

const int BoyerMooreHorspoolSearcher::find(const std::string& corpus) {
    return find(corpus.c_str(), corpus.size());
}

const int BoyerMooreHorspoolSearcher::find(const char* corpus, size_t corpusLength) {
    assert(corpus);
    //Shortcut if there's an empty pattern (--> we DEFINE that as not found)
    if(patternLength == 0) {
        return -1;
    }
    //Can't find pattern if its larger than corpus
    if (patternLength > corpusLength) {
        return -1;
    }
    for(int k = patternLength - 1 ; k < (int)corpusLength ; ) {
        int j = patternLength - 1;
        int i = k;
        while (j >= 0 && corpus[i] == pattern[j]) {
            j--;
            i--;
        }
        if (j == -1) {
            return i + 1;
        }
        k += skipTable[(uint8_t)corpus[k]];
    }
    //Couldn't find it
    return -1;
}<|endoftext|>


<commit_before>#include "RedBlackTree.h"
#include <algorithm>
#include <cassert>
#include <utility>
#include <iostream>
#include <string>

#define RED 'R'
#define BLACK 'B'

RbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};

static RbNode *Next(RbNode *e) {
  if (is_nil(e->right)) {
    return &RBNIL;
  }
  RbNode *next = e->right;
  while (not_nil(next->left)) {
    next = next->left;
  }
  return next;
}

static RbNode *GrandFather(RbNode *e) {
  if (is_nil(e))
    return &RBNIL;
  if (is_nil(e->father))
    return &RBNIL;
  return e->father->father;
}

static RbNode *Uncle(RbNode *e) {
  if (is_nil(GrandFather(e)))
    return &RBNIL;
  if (GrandFather(e)->left == e)
    return GrandFather(e)->right;
  if (GrandFather(e)->right == e)
    return GrandFather(e)->left;
  return &RBNIL;
}

static bool IsLeft(RbNode *e) {
  if (is_nil(e->father))
    return false;
  return e->father->left == e;
}

static bool IsRight(RbNode *e) {
  if (is_nil(e->father))
    return false;
  return e->father->right == e;
}

static RbNode *Brother(RbNode *e) {
  if (is_nil(e))
    return &RBNIL;
  if (IsLeft(e)) {
    return e->father->right;
  }
  if (IsRight(e)) {
    return e->father->left;
  }
  return &RBNIL;
}

static void DumpNode(RbNode *e) {
  assert(e);
  if (is_nil(e)) {
    std::cout << " [nil B]" << std::endl;
  } else {
    std::cout << " [" << e->value << " "
      << (e->color == RED ? "R" : "B")
      << " l:" << (is_nil(e->left) ? "nil" : std::to_string(e->left->value))
      << " r:" << (is_nil(e->right) ? "nil" : std::to_string(e->right->value))
      << "]" << std::endl;
    DumpNode(e->left);
    DumpNode(e->right);
  }
}

static void DumpTree(RedBlackTree *t) {
  assert(t);
  std::cout << std::endl << std::endl << std::endl;
  DumpNode(t->root);
}

static void Free(RbNode *e) {
  if (is_nil(e))
    return;
  Free(e->left);
  Free(e->right);
  delete e;
}

static void LeftRotate(RbNode *&father, RbNode *&e) {
  RbNode *p_right = e->right;
  e->right = p_right->left;

  if (not_nil(e->right)) {
    e->right->father = e;
  }

  p_right->father = e->father;

  if (is_nil(e->father)) {
    father = p_right;
  } else if (e == e->father->left) {
    e->father->left = p_right;
  } else {
    e->father->right = p_right;
  }

  p_right->left = e;
  e->father = p_right;
}

static void RightRotate(RbNode *&father, RbNode *&e) {
  RbNode *p_left = e->left;
  e->left = p_left->right;

  if (not_nil(e->left)) {
    e->left->father = e;
  }

  p_left->father = e->father;

  if (is_nil(e->father)) {
    father = p_left;
  } else if (e == e->father->left) {
    e->father->left = p_left;
  } else {
    e->father->right = p_left;
  }

  p_left->right = e;
  e->father = p_left;
}

void FixInsert(RbNode *&root, RbNode *&e) {
  RbNode *e_father, *e_grand_father;
  set_nil(e_father);
  set_nil(e_grand_father);

  while ((e != root) && (e->color != BLACK) && (e->father->color == RED)) {
    e_father = e->father;
    e_grand_father = e->father->father;

    // case A
    if (e_father == e_grand_father->left) {
      RbNode *e_uncle = e_grand_father->right;

      // case 1: Red Uncle
      if (not_nil(e_uncle) && e_uncle->color == RED) {
        e_grand_father->color = RED;
        e_father->color = BLACK;
        e_uncle->color = BLACK;
        e = e_grand_father;
      } else {

        // case 2: Black Uncle, left-right-case
        if (e == e_father->right) {
          LeftRotate(root, e_father);
          e = e_father;
          e_father = e->father;
        }

        // case 3: Black Uncle, left-left-case
        RightRotate(root, e_grand_father);
        std::swap(e_father->color, e_grand_father->color);
        e = e_father;
      }
    }

    // case B
    else {
      RbNode *e_uncle = e_grand_father->right;

      // case 1: Red Uncle
      if (not_nil(e_uncle) && (e_uncle->color == RED)) {
        e_grand_father->color = RED;
        e_father->color = BLACK;
        e_uncle->color = BLACK;
        e = e_grand_father;
      } else {

        // case 4: Black Uncle, left-right-case
        if (e == e_father->left) {
          RightRotate(root, e_father);
          e = e_father;
          e_father = e->father;
        }

        // case 5: Black Uncle, right-right-case
        LeftRotate(root, e_grand_father);
        std::swap(e_father->color, e_grand_father->color);
        e = e_father;
      }
    }
  } // while

  root->color = BLACK;
}

static void FixErase(RbNode *&root, RbNode *&e) {
  // Reached root
  if (e == root) {
    return;
  }

  RbNode *e_brother = Brother(e);
  RbNode *e_father = e->father;

  if (is_nil(e_brother)) {
    // No sibiling, double black pushed up
    FixErase(root, e_father);
  } else {
    if (e_brother->color == RED) {
      // brother red
      e_father->color = RED;
      e_brother->color = BLACK;
      if (IsLeft(e_brother)) {
        // left case
        RightRotate(root, e_father);
      } else {
        // right case
        LeftRotate(root, e_father);
      }
      FixErase(root, e);
    } else {
      // brother black
      if (e_brother->left->color == RED || e_brother->right->color == RED) {
        // at least 1 red children
        if (not_nil(e_brother->left) && e_brother->left->color == RED) {
          if (IsLeft(e_brother)) {
            // left left
            e_brother->left->color = e_brother->color;
            e_brother->color = e_father->color;
            RightRotate(root, e_father);
          } else {
            // right left
            e_brother->left->color = e_father->color;
            RightRotate(root, e_brother);
            LeftRotate(root, e_father);
          }
        } else {
          if (IsLeft(e_brother)) {
            // left right
            e_brother->right->color = e_father->color;
            LeftRotate(root, e_brother);
            RightRotate(root, e_father);
          } else {
            // right right
            e_brother->right->color = e_brother->color;
            e_brother->color = e_father->color;
            LeftRotate(root, e_father);
          }
        }
        e_father->color = BLACK;
      } else {
        // 2 black children
        e_brother->color = RED;
        if (e_father->color == BLACK) {
          FixErase(root, e_father);
        } else {
          e_father->color = BLACK;
        }
      }
    }
  }
}

static void Erase(RbNode *&root, RbNode *&e) {

  // case 1: e has no child
  if (is_nil(e->left) && is_nil(e->right)) {
    if (e == root) {
      set_nil(root);
    } else {
      if (e->color == BLACK) {
        FixErase(root, e);
      } else {
        if (not_nil(Uncle(e))) {
          Uncle(e)->color = RED;
        }
      }
      if (IsLeft(e)) {
        set_nil(e->father->left);
      } else {
        set_nil(e->father->right);
      }
    }
    delete e;
    return;
  }

  // case 2: e has 1 child
  if (is_nil(e->left) || is_nil(e->right)) {
    RbNode *p = not_nil(e->left) ? e->left : e->right;
    if (e == root) {
      e->value = p->value;
      set_nil(e->left);
      set_nil(e->right);
      delete p;
    } else {
      if (IsLeft(e)) {
        e->father->left = p;
      } else {
        e->father->right = p;
      }
      delete e;
      p->father = e->father;
      if (e->color == BLACK && p->color == BLACK) {
        FixErase(root, e);
      } else {
        p->color = BLACK;
      }
    }
    return;
  }

  // case 3: e has 2 child
  RbNode *p = Next(e);
  std::swap(p->color, e->color);
  Erase(root, e);
}

static RbNode *Find(RbNode *e, int value) {
  if (is_nil(e)) {
    return &RBNIL;
  }
  //二分查找
  if (e->value == value) {
    return e;
  } else if (e->value > value) {
    return Find(e->left, value);
  } else {
    return Find(e->right, value);
  }
}

static RbNode *Insert(RbNode *father, RbNode *e) {
  assert(father);
  assert(e);

  if (is_nil(father)) {
    return e;
  }

  //利用二分查找找到适合value插入的位置e

  if (father->value > e->value) {
    father->left = Insert(father->left, e);
    father->left->father = father;
  } else if (father->value < e->value) {
    father->right = Insert(father->right, e);
    father->right->father = father;
  } else {
    assert(father->value != e->value);
  }
  return father;
}

RedBlackTree *RedBlackTreeNew() {
  RedBlackTree *t = new RedBlackTree();
  if (!t)
    return NULL;
  t->root = &RBNIL;
  return t;
}

void RedBlackTreeFree(RedBlackTree *t) {
  assert(t);
  Free(t->root);
  delete t;
}

void RedBlackTreeInsert(RedBlackTree *t, int value) {
  assert(t);
  assert(value >= 0);

  RbNode *e = new RbNode();
  set_nil(e->left);
  set_nil(e->right);
  set_nil(e->father);
  e->color = RED; // new node is red
  e->value = value;

  t->root = Insert(t->root, e);
  FixInsert(t->root, e);
  DumpTree(t);
}

RbNode *RedBlackTreeFind(RedBlackTree *t, int value) {
  return Find(t->root, value);
}

void RedBlackTreeErase(RedBlackTree *t, int value) {
  RbNode *e = Find(t->root, value);
  if (is_nil(e)) {
    return;
  }
  Erase(t->root, e);
  DumpTree(t);
}

<commit_msg>fix wrong ptr<commit_after>#include "RedBlackTree.h"
#include <algorithm>
#include <cassert>
#include <utility>
#include <iostream>
#include <string>

#define RED 'R'
#define BLACK 'B'

RbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};

static RbNode *Next(RbNode *e) {
  if (is_nil(e->right)) {
    return &RBNIL;
  }
  RbNode *next = e->right;
  while (not_nil(next->left)) {
    next = next->left;
  }
  return next;
}

static RbNode *GrandFather(RbNode *e) {
  if (is_nil(e))
    return &RBNIL;
  if (is_nil(e->father))
    return &RBNIL;
  return e->father->father;
}

static RbNode *Uncle(RbNode *e) {
  if (is_nil(GrandFather(e)))
    return &RBNIL;
  if (GrandFather(e)->left == e)
    return GrandFather(e)->right;
  if (GrandFather(e)->right == e)
    return GrandFather(e)->left;
  return &RBNIL;
}

static bool IsLeft(RbNode *e) {
  if (is_nil(e->father))
    return false;
  return e->father->left == e;
}

static bool IsRight(RbNode *e) {
  if (is_nil(e->father))
    return false;
  return e->father->right == e;
}

static RbNode *Brother(RbNode *e) {
  if (is_nil(e))
    return &RBNIL;
  if (IsLeft(e)) {
    return e->father->right;
  }
  if (IsRight(e)) {
    return e->father->left;
  }
  return &RBNIL;
}

static void DumpNode(RbNode *e) {
  assert(e);
  if (is_nil(e)) {
    std::cout << " [nil B]" << std::endl;
  } else {
    std::cout << " [" << e->value << " "
      << (e->color == RED ? "R" : "B")
      << " left:" << (is_nil(e->left) ? "nil" : std::to_string(e->left->value))
      << " right:" << (is_nil(e->right) ? "nil" : std::to_string(e->right->value))
      << " father:" << (is_nil(e->father) ? "nil" : std::to_string(e->father->value))
      << "]" << std::endl;
    if (not_nil(e->left)) {
      DumpNode(e->left);
    }
    if (not_nil(e->right)) {
      DumpNode(e->right);
    }
  }
}

static void DumpTree(RedBlackTree *t) {
  assert(t);
  std::cout << std::endl << std::endl << std::endl;
  DumpNode(t->root);
}

static void Free(RbNode *e) {
  if (is_nil(e))
    return;
  Free(e->left);
  Free(e->right);
  delete e;
}

static void LeftRotate(RbNode *&father, RbNode *&e) {
  RbNode *p_right = e->right;
  e->right = p_right->left;

  if (not_nil(e->right)) {
    e->right->father = e;
  }

  p_right->father = e->father;

  if (is_nil(e->father)) {
    father = p_right;
  } else if (e == e->father->left) {
    e->father->left = p_right;
  } else {
    e->father->right = p_right;
  }

  p_right->left = e;
  e->father = p_right;
}

static void RightRotate(RbNode *&father, RbNode *&e) {
  RbNode *p_left = e->left;
  e->left = p_left->right;

  if (not_nil(e->left)) {
    e->left->father = e;
  }

  p_left->father = e->father;

  if (is_nil(e->father)) {
    father = p_left;
  } else if (e == e->father->left) {
    e->father->left = p_left;
  } else {
    e->father->right = p_left;
  }

  p_left->right = e;
  e->father = p_left;
}

void FixInsert(RbNode *&root, RbNode *&e) {
  RbNode *e_father, *e_grand_father;
  set_nil(e_father);
  set_nil(e_grand_father);

  while ((e != root) && (e->color != BLACK) && (e->father->color == RED)) {
    e_father = e->father;
    e_grand_father = e->father->father;

    // case A
    if (e_father == e_grand_father->left) {
      RbNode *e_uncle = e_grand_father->right;

      // case 1: Red Uncle
      if (not_nil(e_uncle) && e_uncle->color == RED) {
        e_grand_father->color = RED;
        e_father->color = BLACK;
        e_uncle->color = BLACK;
        e = e_grand_father;
      } else {

        // case 2: Black Uncle, left-right-case
        if (e == e_father->right) {
          LeftRotate(root, e_father);
          e = e_father;
          e_father = e->father;
        }

        // case 3: Black Uncle, left-left-case
        RightRotate(root, e_grand_father);
        std::swap(e_father->color, e_grand_father->color);
        e = e_father;
      }
    }

    // case B
    else {
      RbNode *e_uncle = e_grand_father->right;

      // case 1: Red Uncle
      if (not_nil(e_uncle) && (e_uncle->color == RED)) {
        e_grand_father->color = RED;
        e_father->color = BLACK;
        e_uncle->color = BLACK;
        e = e_grand_father;
      } else {

        // case 4: Black Uncle, left-right-case
        if (e == e_father->left) {
          RightRotate(root, e_father);
          e = e_father;
          e_father = e->father;
        }

        // case 5: Black Uncle, right-right-case
        LeftRotate(root, e_grand_father);
        std::swap(e_father->color, e_grand_father->color);
        e = e_father;
      }
    }
  } // while

  root->color = BLACK;
}

static void FixErase(RbNode *&root, RbNode *&e) {
  // Reached root
  if (e == root) {
    return;
  }

  RbNode *e_brother = Brother(e);
  RbNode *e_father = e->father;

  if (is_nil(e_brother)) {
    // No sibiling, double black pushed up
    FixErase(root, e_father);
  } else {
    if (e_brother->color == RED) {
      // brother red
      e_father->color = RED;
      e_brother->color = BLACK;
      if (IsLeft(e_brother)) {
        // left case
        RightRotate(root, e_father);
      } else {
        // right case
        LeftRotate(root, e_father);
      }
      FixErase(root, e);
    } else {
      // brother black
      if (e_brother->left->color == RED || e_brother->right->color == RED) {
        // at least 1 red children
        if (not_nil(e_brother->left) && e_brother->left->color == RED) {
          if (IsLeft(e_brother)) {
            // left left
            e_brother->left->color = e_brother->color;
            e_brother->color = e_father->color;
            RightRotate(root, e_father);
          } else {
            // right left
            e_brother->left->color = e_father->color;
            RightRotate(root, e_brother);
            LeftRotate(root, e_father);
          }
        } else {
          if (IsLeft(e_brother)) {
            // left right
            e_brother->right->color = e_father->color;
            LeftRotate(root, e_brother);
            RightRotate(root, e_father);
          } else {
            // right right
            e_brother->right->color = e_brother->color;
            e_brother->color = e_father->color;
            LeftRotate(root, e_father);
          }
        }
        e_father->color = BLACK;
      } else {
        // 2 black children
        e_brother->color = RED;
        if (e_father->color == BLACK) {
          FixErase(root, e_father);
        } else {
          e_father->color = BLACK;
        }
      }
    }
  }
}

static void Erase(RbNode *&root, RbNode *&e) {

  // case 1: e has no child
  if (is_nil(e->left) && is_nil(e->right)) {
    if (e == root) {
      set_nil(root);
    } else {
      if (e->color == BLACK) {
        FixErase(root, e);
      } else {
        if (not_nil(Uncle(e))) {
          Uncle(e)->color = RED;
        }
      }
      if (IsLeft(e)) {
        set_nil(e->father->left);
      } else {
        set_nil(e->father->right);
      }
    }
    delete e;
    return;
  }

  // case 2: e has 1 child
  if (is_nil(e->left) || is_nil(e->right)) {
    RbNode *p = not_nil(e->left) ? e->left : e->right;
    if (e == root) {
      e->value = p->value;
      set_nil(e->left);
      set_nil(e->right);
      delete p;
    } else {
      if (IsLeft(e)) {
        e->father->left = p;
      } else {
        e->father->right = p;
      }
      delete e;
      p->father = e->father;
      if (e->color == BLACK && p->color == BLACK) {
        FixErase(root, e);
      } else {
        p->color = BLACK;
      }
    }
    return;
  }

  // case 3: e has 2 child
  RbNode *p = Next(e);
  std::swap(p->color, e->color);
  Erase(root, p);
}

static RbNode *Find(RbNode *e, int value) {
  if (is_nil(e)) {
    return &RBNIL;
  }
  //二分查找
  if (e->value == value) {
    return e;
  } else if (e->value > value) {
    return Find(e->left, value);
  } else {
    return Find(e->right, value);
  }
}

static RbNode *Insert(RbNode *father, RbNode *e) {
  assert(father);
  assert(e);

  if (is_nil(father)) {
    return e;
  }

  //利用二分查找找到适合value插入的位置e

  if (father->value > e->value) {
    father->left = Insert(father->left, e);
    father->left->father = father;
  } else if (father->value < e->value) {
    father->right = Insert(father->right, e);
    father->right->father = father;
  } else {
    assert(father->value != e->value);
  }
  return father;
}

RedBlackTree *RedBlackTreeNew() {
  RedBlackTree *t = new RedBlackTree();
  if (!t)
    return NULL;
  t->root = &RBNIL;
  return t;
}

void RedBlackTreeFree(RedBlackTree *t) {
  assert(t);
  Free(t->root);
  delete t;
}

void RedBlackTreeInsert(RedBlackTree *t, int value) {
  assert(t);
  assert(value >= 0);

  RbNode *e = new RbNode();
  set_nil(e->left);
  set_nil(e->right);
  set_nil(e->father);
  e->color = RED; // new node is red
  e->value = value;

  t->root = Insert(t->root, e);
  FixInsert(t->root, e);
  DumpTree(t);
}

RbNode *RedBlackTreeFind(RedBlackTree *t, int value) {
  return Find(t->root, value);
}

void RedBlackTreeErase(RedBlackTree *t, int value) {
  RbNode *e = Find(t->root, value);
  if (is_nil(e)) {
    return;
  }
  Erase(t->root, e);
  DumpTree(t);
}

<|endoftext|>


<commit_before>

/**
 * Copyright (c) 2016-2017 blueback
 * Released under the MIT License
 * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
 * http://bbbproject.sakura.ne.jp/wordpress/mitlicense
 * @brief テスト。
*/

/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../entry.h"
#pragma warning(pop)

/** warning

4710 : The given function was selected for inline expansion, but the compiler did not perform the inlining.

*/
#pragma warning(disable:4710)

/** NTest
*/
#if(DEF_TEST_INDEX == 2)
namespace NTest
{
	/** File_Allocator
	*/
	class File_Allocator : public NBsys::NFile::File_Allocator
	{
	public:

		/** constructor
		*/
		File_Allocator()
		{
		}

		/** destructor
		*/
		virtual ~File_Allocator()
		{
		}

	public:

		/** Alloc
		*/
		virtual void* Alloc(u32 a_size)
		{
			return ::malloc(a_size);
		}

		/** Free
		*/
		virtual void Free(void* a_pointer)
		{
			return ::free(a_pointer);
		}

	};

	/** Test_Main
	*/
	void Test_Main()
	{
		//ファイル開始。
		NBsys::NFile::StartSystem(1);
		NBsys::NFile::SetRoot(0,L"./project_test/test" DEF_TEST_STRING);

		//読み込み開始。
		sharedptr<NBsys::NFile::File_Object> t_fileobject(new NBsys::NFile::File_Object(0,L"test2.json",-1,new File_Allocator,1));

		//読み込み中。
		while(t_fileobject->IsBusy()){
			ThreadSleep(10);
		}

		if(t_fileobject->GetErrorCode() != ErrorCode::Success){
			t_fileobject.reset();
		}

		if(t_fileobject){

			//コンバート。
			for(;;){
				NBsys::NFile::File_ConvertLock_ReturnType::Id t_ret = t_fileobject->ConvertLock();
				if(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::Locked){
					//未コンバート => コンバート中。

					//コンバート中 => コンバート済み。
					t_fileobject->GetLoadData().get()[static_cast<s32>(t_fileobject->GetLoadSize())] = 0x00;
					t_fileobject->ConvertUnlock();

					break;
				}else if(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::ConvertNow){
					//コンバート中。

					//ロックに成功していないのでアンロック不要。
				}else{
					//コンバート済み。

					//ロックに成功していないのでアンロック不要。
					break;
				}
			}

			//ＪＳＯＮ解析。
			sharedptr<JsonItem> t_json(new JsonItem(reinterpret_cast<char*>(t_fileobject->GetLoadData().get())));

			//ＪＳＯＮ取得。
			if(t_json->GetValueType() == JsonItem::ValueType::AssociativeArray){
				if(t_json->IsExistItem("name1") == true){
					STLString t_value = *t_json->GetItem("name1")->GetStringData();
					DEBUGLOG("name1 = %s\n",t_value.c_str());
				}
				if(t_json->IsExistItem("name2") == true){
					s32 t_value = t_json->GetItem("name2")->GetInteger();
					DEBUGLOG("name1 = %d\n",t_value);
				}
				if(t_json->IsExistItem("name3") == true){
					f32 t_value = t_json->GetItem("name3")->GetFloat();
					DEBUGLOG("name1 = %f\n",t_value);
				}
				if(t_json->IsExistItem("name4") == true){
					bool t_value = t_json->GetItem("name4")->GetBoolData();
					DEBUGLOG("name1 = %d\n",t_value?1:0);
				}
			}

			//ＪＳＯＮ出力。
			{
				FileHandle t_filehandle;
				t_filehandle.WriteOpen(L"./project_test/test2/out.json");
				STLString t_jsonstring = t_json->ConvertJsonString();
				t_filehandle.Write(reinterpret_cast<const u8*>(t_jsonstring.c_str()),t_jsonstring.size(),0);
				t_filehandle.Close();
			}
		}

		//ファイル終了。
		NBsys::NFile::EndSystemRequest();
		NBsys::NFile::EndWaitSystem();

		return;
	}

}
#endif

<commit_msg>bug fix<commit_after>

/**
 * Copyright (c) 2016-2017 blueback
 * Released under the MIT License
 * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
 * http://bbbproject.sakura.ne.jp/wordpress/mitlicense
 * @brief テスト。
*/

/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../entry.h"
#pragma warning(pop)

/** warning

4710 : The given function was selected for inline expansion, but the compiler did not perform the inlining.

*/
#pragma warning(disable:4710)

/** NTest
*/
#if(DEF_TEST_INDEX == 2)
namespace NTest
{
	/** File_Allocator
	*/
	class File_Allocator : public NBsys::NFile::File_Allocator
	{
	public:

		/** constructor
		*/
		File_Allocator()
		{
		}

		/** destructor
		*/
		virtual ~File_Allocator()
		{
		}

	public:

		/** Alloc
		*/
		virtual void* Alloc(u32 a_size)
		{
			return ::malloc(a_size);
		}

		/** Free
		*/
		virtual void Free(void* a_pointer)
		{
			return ::free(a_pointer);
		}

	};

	/** Test_Main
	*/
	void Test_Main()
	{
		//ファイル開始。
		NBsys::NFile::StartSystem(1);
		NBsys::NFile::SetRoot(0,L"./project_test/test" DEF_TEST_STRING);

		//読み込み開始。
		sharedptr<NBsys::NFile::File_Object> t_fileobject(new NBsys::NFile::File_Object(0,L"test2.json",-1,new File_Allocator,1));

		//読み込み中。
		while(t_fileobject->IsBusy()){
			ThreadSleep(10);
		}

		if(t_fileobject->GetErrorCode() != ErrorCode::Success){
			t_fileobject.reset();
		}

		if(t_fileobject){

			//コンバート。
			for(;;){
				NBsys::NFile::File_ConvertLock_ReturnType::Id t_ret = t_fileobject->ConvertLock();
				if(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::Locked){
					//未コンバート => コンバート中。

					//コンバート中 => コンバート済み。
					t_fileobject->GetLoadData().get()[static_cast<s32>(t_fileobject->GetLoadSize())] = 0x00;
					t_fileobject->ConvertUnlock();

					break;
				}else if(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::ConvertNow){
					//コンバート中。

					//ロックに成功していないのでアンロック不要。
				}else{
					//コンバート済み。

					//ロックに成功していないのでアンロック不要。
					break;
				}
			}

			//ＪＳＯＮ解析。
			sharedptr<JsonItem> t_json(new JsonItem(reinterpret_cast<char*>(t_fileobject->GetLoadData().get())));

			//ＪＳＯＮ取得。
			if(t_json->GetValueType() == JsonItem::ValueType::AssociativeArray){
				if(t_json->IsExistItem("name1") == true){
					STLString t_value = *t_json->GetItem("name1")->GetStringData();
					DEBUGLOG("name1 = %s\n",t_value.c_str());
				}
				if(t_json->IsExistItem("name2") == true){
					s32 t_value = t_json->GetItem("name2")->GetInteger();
					DEBUGLOG("name1 = %d\n",t_value);
				}
				if(t_json->IsExistItem("name3") == true){
					f32 t_value = t_json->GetItem("name3")->GetFloat();
					DEBUGLOG("name1 = %f\n",t_value);
				}
				if(t_json->IsExistItem("name4") == true){
					bool t_value = t_json->GetItem("name4")->GetBoolData();
					DEBUGLOG("name1 = %d\n",t_value?1:0);
				}
			}

			//ＪＳＯＮ出力。
			{
				FileHandle t_filehandle;
				t_filehandle.WriteOpen(L"./project_test/test2/out.json");
				STLString t_jsonstring = t_json->ConvertJsonString();
				t_filehandle.Write(reinterpret_cast<const u8*>(t_jsonstring.c_str()),t_jsonstring.size(),0);
				t_filehandle.SetEOF(t_jsonstring.size());
				t_filehandle.Close();
			}
		}

		//ファイル終了。
		NBsys::NFile::EndSystemRequest();
		NBsys::NFile::EndWaitSystem();

		return;
	}

}
#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MABConnection.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: dkenny $ $Date: 2001-05-31 07:22:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_
#define _CONNECTIVITY_MAB_CONNECTION_HXX_

#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif

namespace com { namespace sun { namespace star { namespace sheet {
    class XSpreadsheetDocument;
} } } }

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabDriver;
        class OMozabConnection : public file::OConnection
        {

            sal_Int32       m_nAnonABCount;
            rtl::OUString   m_sMozillaURI;

        public:
            OMozabConnection(OMozabDriver* _pDriver);
            virtual ~OMozabConnection();

            virtual void construct(const ::rtl::OUString& _rUrl,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )
                throw( ::com::sun::star::sdbc::SQLException);

            // XServiceInfo
            DECLARE_SERVICE_INFO();

            // OComponentHelper
            virtual void SAL_CALL disposing(void);

            // XConnection
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // no interface methods
            rtl::OUString getMozURI() const
                { return m_sMozillaURI; }

            sal_Int32 getNextAnonymousAB()
                { return (++m_nAnonABCount); }
        };
    }
}

#endif // _CONNECTIVITY_MAB_CONNECTION_HXX_

<commit_msg>#88665#<commit_after>/*************************************************************************
 *
 *  $RCSfile: MABConnection.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fs $ $Date: 2001-06-25 09:51:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_
#define _CONNECTIVITY_MAB_CONNECTION_HXX_

#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif

namespace com { namespace sun { namespace star { namespace sheet {
    class XSpreadsheetDocument;
} } } }

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabDriver;
        class OMozabConnection : public file::OConnection
        {

            sal_Int32       m_nAnonABCount;
            rtl::OUString   m_sMozillaURI;
            sal_Bool        m_UsesFactory ;
            sal_Bool        m_IsLDAP ;

        public:
            OMozabConnection(OMozabDriver* _pDriver);
            virtual ~OMozabConnection();

            virtual void construct(const ::rtl::OUString& _rUrl,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )
                throw( ::com::sun::star::sdbc::SQLException);

            // XServiceInfo
            DECLARE_SERVICE_INFO();

            // OComponentHelper
            virtual void SAL_CALL disposing(void);

            // XConnection
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // no interface methods
            rtl::OUString getMozURI() const
                { return m_sMozillaURI; }

            sal_Bool usesFactory(void) const { return m_UsesFactory ; }
            sal_Bool isLDAP(void) const { return m_IsLDAP ; }

            sal_Int32 getNextAnonymousAB()
                { return (++m_nAnonABCount); }
        };
    }
}

#endif // _CONNECTIVITY_MAB_CONNECTION_HXX_

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/common/gpu/media/gpu_video_decode_accelerator.h"

#include <vector>

#include "base/bind.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "gpu/command_buffer/common/command_buffer.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_message_utils.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/gpu_command_buffer_stub.h"
#include "content/common/gpu/gpu_messages.h"
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
#include "content/common/gpu/media/omx_video_decode_accelerator.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#endif
#include "ui/gfx/size.h"

GpuVideoDecodeAccelerator::GpuVideoDecodeAccelerator(
    IPC::Message::Sender* sender,
    int32 host_route_id,
    GpuCommandBufferStub* stub)
    : sender_(sender),
      init_done_msg_(NULL),
      host_route_id_(host_route_id),
      stub_(stub),
      video_decode_accelerator_(NULL) {
}

GpuVideoDecodeAccelerator::~GpuVideoDecodeAccelerator() {
  if (video_decode_accelerator_)
    video_decode_accelerator_->Destroy();
}

bool GpuVideoDecodeAccelerator::OnMessageReceived(const IPC::Message& msg) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(GpuVideoDecodeAccelerator, msg)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Decode, OnDecode)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_AssignPictureBuffers,
                        OnAssignPictureBuffers)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_ReusePictureBuffer,
                        OnReusePictureBuffer)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Flush, OnFlush)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Reset, OnReset)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Destroy, OnDestroy)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void GpuVideoDecodeAccelerator::ProvidePictureBuffers(
    uint32 requested_num_of_buffers, const gfx::Size& dimensions) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers(
          host_route_id_, requested_num_of_buffers, dimensions))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers) "
               << "failed";
  }
}

void GpuVideoDecodeAccelerator::DismissPictureBuffer(
    int32 picture_buffer_id) {
  // Notify client that picture buffer is now unused.
  if (!Send(new AcceleratedVideoDecoderHostMsg_DismissPictureBuffer(
          host_route_id_, picture_buffer_id))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_DismissPictureBuffer) "
               << "failed";
  }
}

void GpuVideoDecodeAccelerator::PictureReady(
    const media::Picture& picture) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_PictureReady(
          host_route_id_,
          picture.picture_buffer_id(),
          picture.bitstream_buffer_id()))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_PictureReady) failed";
  }
}

void GpuVideoDecodeAccelerator::NotifyEndOfStream() {
  Send(new AcceleratedVideoDecoderHostMsg_EndOfStream(host_route_id_));
}

void GpuVideoDecodeAccelerator::NotifyError(
    media::VideoDecodeAccelerator::Error error) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_ErrorNotification(
          host_route_id_, error))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_ErrorNotification) "
               << "failed";
  }
}

void GpuVideoDecodeAccelerator::Initialize(
    const std::vector<int32>& configs,
    IPC::Message* init_done_msg) {
  DCHECK(!video_decode_accelerator_.get());
  DCHECK(!init_done_msg_);
  DCHECK(init_done_msg);
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
  DCHECK(stub_ && stub_->scheduler());
  init_done_msg_ = init_done_msg;
  OmxVideoDecodeAccelerator* omx_decoder = new OmxVideoDecodeAccelerator(this);
  omx_decoder->SetEglState(
      gfx::GLSurfaceEGL::GetHardwareDisplay(),
      stub_->scheduler()->decoder()->GetGLContext()->GetHandle());
  video_decode_accelerator_ = omx_decoder;
  video_decode_accelerator_->Initialize(configs);
#else
  NOTIMPLEMENTED() << "HW video decode acceleration not available.";
#endif  // defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
}

void GpuVideoDecodeAccelerator::OnDecode(
    base::SharedMemoryHandle handle, int32 id, int32 size) {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));
}

void GpuVideoDecodeAccelerator::OnAssignPictureBuffers(
      const std::vector<int32>& buffer_ids,
      const std::vector<uint32>& texture_ids,
      const std::vector<gfx::Size>& sizes) {
  DCHECK(stub_ && stub_->scheduler());  // Ensure already Initialize()'d.
  gpu::gles2::GLES2Decoder* command_decoder = stub_->scheduler()->decoder();

  std::vector<media::PictureBuffer> buffers;
  for (uint32 i = 0; i < buffer_ids.size(); ++i) {
    uint32 service_texture_id;
    if (!command_decoder->GetServiceTextureId(
            texture_ids[i], &service_texture_id)) {
      // TODO(vrk): Send an error for invalid GLES buffers.
      LOG(DFATAL) << "Failed to translate texture!";
      return;
    }
    buffers.push_back(media::PictureBuffer(
        buffer_ids[i], sizes[i], service_texture_id));
  }
  video_decode_accelerator_->AssignPictureBuffers(buffers);
}

void GpuVideoDecodeAccelerator::OnReusePictureBuffer(
    int32 picture_buffer_id) {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->ReusePictureBuffer(picture_buffer_id);
}

void GpuVideoDecodeAccelerator::OnFlush() {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Flush();
}

void GpuVideoDecodeAccelerator::OnReset() {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Reset();
}

void GpuVideoDecodeAccelerator::OnDestroy() {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Destroy();
}

void GpuVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer(
    int32 bitstream_buffer_id) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed(
          host_route_id_, bitstream_buffer_id))) {
    DLOG(ERROR)
        << "Send(AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed) "
        << "failed";
  }
}

void GpuVideoDecodeAccelerator::NotifyInitializeDone() {
  if (!Send(init_done_msg_))
    LOG(ERROR) << "Send(init_done_msg_) failed";
  init_done_msg_ = NULL;
}

void GpuVideoDecodeAccelerator::NotifyFlushDone() {
  if (!Send(new AcceleratedVideoDecoderHostMsg_FlushDone(host_route_id_)))
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_FlushDone) failed";
}

void GpuVideoDecodeAccelerator::NotifyResetDone() {
  if (!Send(new AcceleratedVideoDecoderHostMsg_ResetDone(host_route_id_)))
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_ResetDone) failed";
}

bool GpuVideoDecodeAccelerator::Send(IPC::Message* message) {
  DCHECK(sender_);
  return sender_->Send(message);
}
<commit_msg>Send error reply to GpuVideoDecodeAccelerator::Initialize when not available<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/common/gpu/media/gpu_video_decode_accelerator.h"

#include <vector>

#include "base/bind.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "gpu/command_buffer/common/command_buffer.h"
#include "ipc/ipc_message_macros.h"
#include "ipc/ipc_message_utils.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/gpu_command_buffer_stub.h"
#include "content/common/gpu/gpu_messages.h"
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
#include "content/common/gpu/media/omx_video_decode_accelerator.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#endif
#include "ui/gfx/size.h"

GpuVideoDecodeAccelerator::GpuVideoDecodeAccelerator(
    IPC::Message::Sender* sender,
    int32 host_route_id,
    GpuCommandBufferStub* stub)
    : sender_(sender),
      init_done_msg_(NULL),
      host_route_id_(host_route_id),
      stub_(stub),
      video_decode_accelerator_(NULL) {
}

GpuVideoDecodeAccelerator::~GpuVideoDecodeAccelerator() {
  if (video_decode_accelerator_)
    video_decode_accelerator_->Destroy();
}

bool GpuVideoDecodeAccelerator::OnMessageReceived(const IPC::Message& msg) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(GpuVideoDecodeAccelerator, msg)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Decode, OnDecode)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_AssignPictureBuffers,
                        OnAssignPictureBuffers)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_ReusePictureBuffer,
                        OnReusePictureBuffer)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Flush, OnFlush)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Reset, OnReset)
    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Destroy, OnDestroy)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void GpuVideoDecodeAccelerator::ProvidePictureBuffers(
    uint32 requested_num_of_buffers, const gfx::Size& dimensions) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers(
          host_route_id_, requested_num_of_buffers, dimensions))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers) "
               << "failed";
  }
}

void GpuVideoDecodeAccelerator::DismissPictureBuffer(
    int32 picture_buffer_id) {
  // Notify client that picture buffer is now unused.
  if (!Send(new AcceleratedVideoDecoderHostMsg_DismissPictureBuffer(
          host_route_id_, picture_buffer_id))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_DismissPictureBuffer) "
               << "failed";
  }
}

void GpuVideoDecodeAccelerator::PictureReady(
    const media::Picture& picture) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_PictureReady(
          host_route_id_,
          picture.picture_buffer_id(),
          picture.bitstream_buffer_id()))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_PictureReady) failed";
  }
}

void GpuVideoDecodeAccelerator::NotifyEndOfStream() {
  Send(new AcceleratedVideoDecoderHostMsg_EndOfStream(host_route_id_));
}

void GpuVideoDecodeAccelerator::NotifyError(
    media::VideoDecodeAccelerator::Error error) {
  if (init_done_msg_) {
    // If we get an error while we're initializing, NotifyInitializeDone won't
    // be called, so we need to send the reply (with an error) here.
    init_done_msg_->set_reply_error();
    Send(init_done_msg_);
    init_done_msg_ = NULL;
  }
  if (!Send(new AcceleratedVideoDecoderHostMsg_ErrorNotification(
          host_route_id_, error))) {
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_ErrorNotification) "
               << "failed";
  }
}

void GpuVideoDecodeAccelerator::Initialize(
    const std::vector<int32>& configs,
    IPC::Message* init_done_msg) {
  DCHECK(!video_decode_accelerator_.get());
  DCHECK(!init_done_msg_);
  DCHECK(init_done_msg);
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
  DCHECK(stub_ && stub_->scheduler());
  init_done_msg_ = init_done_msg;
  OmxVideoDecodeAccelerator* omx_decoder = new OmxVideoDecodeAccelerator(this);
  omx_decoder->SetEglState(
      gfx::GLSurfaceEGL::GetHardwareDisplay(),
      stub_->scheduler()->decoder()->GetGLContext()->GetHandle());
  video_decode_accelerator_ = omx_decoder;
  video_decode_accelerator_->Initialize(configs);
#else
  NOTIMPLEMENTED() << "HW video decode acceleration not available.";
  NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);
#endif  // defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
}

void GpuVideoDecodeAccelerator::OnDecode(
    base::SharedMemoryHandle handle, int32 id, int32 size) {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));
}

void GpuVideoDecodeAccelerator::OnAssignPictureBuffers(
      const std::vector<int32>& buffer_ids,
      const std::vector<uint32>& texture_ids,
      const std::vector<gfx::Size>& sizes) {
  DCHECK(stub_ && stub_->scheduler());  // Ensure already Initialize()'d.
  gpu::gles2::GLES2Decoder* command_decoder = stub_->scheduler()->decoder();

  std::vector<media::PictureBuffer> buffers;
  for (uint32 i = 0; i < buffer_ids.size(); ++i) {
    uint32 service_texture_id;
    if (!command_decoder->GetServiceTextureId(
            texture_ids[i], &service_texture_id)) {
      // TODO(vrk): Send an error for invalid GLES buffers.
      LOG(DFATAL) << "Failed to translate texture!";
      return;
    }
    buffers.push_back(media::PictureBuffer(
        buffer_ids[i], sizes[i], service_texture_id));
  }
  video_decode_accelerator_->AssignPictureBuffers(buffers);
}

void GpuVideoDecodeAccelerator::OnReusePictureBuffer(
    int32 picture_buffer_id) {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->ReusePictureBuffer(picture_buffer_id);
}

void GpuVideoDecodeAccelerator::OnFlush() {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Flush();
}

void GpuVideoDecodeAccelerator::OnReset() {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Reset();
}

void GpuVideoDecodeAccelerator::OnDestroy() {
  DCHECK(video_decode_accelerator_.get());
  video_decode_accelerator_->Destroy();
}

void GpuVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer(
    int32 bitstream_buffer_id) {
  if (!Send(new AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed(
          host_route_id_, bitstream_buffer_id))) {
    DLOG(ERROR)
        << "Send(AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed) "
        << "failed";
  }
}

void GpuVideoDecodeAccelerator::NotifyInitializeDone() {
  if (!Send(init_done_msg_))
    LOG(ERROR) << "Send(init_done_msg_) failed";
  init_done_msg_ = NULL;
}

void GpuVideoDecodeAccelerator::NotifyFlushDone() {
  if (!Send(new AcceleratedVideoDecoderHostMsg_FlushDone(host_route_id_)))
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_FlushDone) failed";
}

void GpuVideoDecodeAccelerator::NotifyResetDone() {
  if (!Send(new AcceleratedVideoDecoderHostMsg_ResetDone(host_route_id_)))
    LOG(ERROR) << "Send(AcceleratedVideoDecoderHostMsg_ResetDone) failed";
}

bool GpuVideoDecodeAccelerator::Send(IPC::Message* message) {
  DCHECK(sender_);
  return sender_->Send(message);
}
<|endoftext|>


<commit_before>/* Definition of the Stellar Structure derivatives and their integrations
 * using RK4 */

#include <cmath>
#include "ssFunctions.h"

	using namespace std; //Because YOLO

//Mass

double massDerivative(double radius, double mass, double density)
	{
		double derivative = 4 * ::pi * pow (radius , 2) * density ;

		return derivative;
	}

	//RK4 integration
double massFunction(double radius, double mass, double density)
	{
		double k1,k2,k3,k4;
		double newMass;

		k1=massDerivative( radius , mass , density);
		k2=massDerivative( radius+0.5 * ::step , mass+0.5*::step*k1 , density);
		k3=massDerivative( radius+ 0.5 * ::step, mass + 0.5* ::step *k2 , density);
		k4=massDerivative( radius+ ::step , mass + ::step *k3 , density );

		newMass = mass + (::step/6)*(k1+2*k2+2*k3+k4);

		return newMass;
	}

//Pressure

double pressureDerivative(double radius, double pressure , double mass, double density)
	{
		double derivative = -1 * ::gravitationalConstant * mass * ( 1 / pow( radius , 2 ) ) * density ;

		return derivative;
	}

	//RK4 integration
double pressureFunction(double radius, double pressure, double mass, double density)
	{
		double k1,k2,k3,k4;
		double newPressure;

		k1=pressureDerivative( radius , pressure , mass , density);
		k2=pressureDerivative(radius+0.5* ::step , pressure+ 0.5* ::step * k1 , mass, density);
		k3=pressureDerivative(radius+ 0.5 * ::step , pressure + 0.5* ::step *k2 , mass , density);
		k4=pressureDerivative(radius+ ::step , pressure + ::step *k3 , mass , density );

		newPressure = pressure + (::step/6)*(k1+2*k2+2*k3+k4);

		return newPressure;
	}

//Density, polytropic fluid equation
double densityFunction( double pressure )
	{
		double newValue, base;

		base = ( pressure / polytropicConstant );

		newValue = pow( base , polytropicIndex );

		return newValue;
	}
<commit_msg>Delete ssFunctions.cpp<commit_after><|endoftext|>


<commit_before>#ifndef UTILITY_HPP
# define UTILITY_HPP

#include <cstddef>

#include <type_traits>

namespace generic
{

template <::std::size_t...> struct indices { };

namespace detail
{

// indices
template<class A, class B> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void> struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  using indices_type = indices;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  static_assert(A  B");
  using indices_type = typename catenate_indices<
    typename expand_indices::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template<typename T> constexpr inline T const& as_const(T& t) { return t; }

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A>::indices_type
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices::indices_type
{
};

// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at
{
};

template <typename A, typename ...B>
struct type_at<0, A, B...>
{
  using type = A;
};

template <typename A, typename ...B>
struct front
{
  using type = A;
};

template <typename A, typename ...B>
struct back : back
{
};

template <typename A>
struct back
{
  using type = A;
};

template <bool B>
using bool_ = ::std::integral_constant<bool, B>;

template <class A, class ...B>
struct all_of : bool_<A::value && all_of::value> { };

template <class A>
struct all_of : bool_ { };

}

#endif // UTILITY_HPP
<commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP
# define UTILITY_HPP

#include <cstddef>

#include <type_traits>

namespace generic
{

template<typename T> constexpr inline T const& as_const(T& t) { return t; }

template <::std::size_t...> struct indices { };

namespace detail
{

// indices
template<class A, class B> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void> struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  using indices_type = indices;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if::type>
{
  static_assert(A  B");
  using indices_type = typename catenate_indices<
    typename expand_indices::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A>::indices_type
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices::indices_type
{
};

// sequences
template <::std::size_t I, typename A, typename ...B>
struct type_at : type_at
{
};

template <typename A, typename ...B>
struct type_at<0, A, B...>
{
  using type = A;
};

template <typename A, typename ...B>
struct front
{
  using type = A;
};

template <typename A, typename ...B>
struct back : back
{
};

template <typename A>
struct back
{
  using type = A;
};

template <bool B>
using bool_ = ::std::integral_constant<bool, B>;

template <class A, class ...B>
struct all_of : bool_<A::value && all_of::value> { };

template <class A>
struct all_of : bool_ { };

}

#endif // UTILITY_HPP
<|endoftext|>