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

//  Software Guide : BeginCommandLineArgs
//    INPUTS:  {BrainProtonDensitySlice.png}
//    ARGUMENTS:    LaplacianRecursiveGaussianImageFilterOutput3.mha 3
//    OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput3.png}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginCommandLineArgs
//    INPUTS:  {BrainProtonDensitySlice.png}
//    ARGUMENTS:    LaplacianRecursiveGaussianImageFilterOutput5.mha 5
//    OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput5.png}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example illustrates how to use the
//  \doxygen{RecursiveGaussianImageFilter} for computing the Laplacian of a 2D
//  image.
//
//  \index{itk::RecursiveGaussianImageFilter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkAddImageFilter.h"

//  Software Guide : BeginLatex
//
//  The first step required to use this filter is to include its header file.
//
//  \index{itk::RecursiveGaussianImageFilter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkRecursiveGaussianImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkRescaleIntensityImageFilter.h"

int main( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputImageFile  sigma [RescaledOutputImageFile] " << std::endl;
    return EXIT_FAILURE;
    }

  //  Software Guide : BeginLatex
  //
  //  Types should be selected on the desired input and output pixel types.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef    float    InputPixelType;
  typedef    float    OutputPixelType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input and output image types are instantiated using the pixel types.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Image< InputPixelType,  2 >   InputImageType;
  typedef itk::Image< OutputPixelType, 2 >   OutputImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType >  ReaderType;

  //  Software Guide : BeginLatex
  //
  //  The filter type is now instantiated using both the input image and the
  //  output image types.
  //
  //  \index{itk::RecursiveGaussianImageFilter!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::RecursiveGaussianImageFilter<
                        InputImageType, OutputImageType >  FilterType;
  // Software Guide : EndCodeSnippet

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  //  Software Guide : BeginLatex
  //
  //  This filter applies the approximation of the convolution along a single
  //  dimension. It is therefore necessary to concatenate several of these filters
  //  to produce smoothing in all directions.  In this example, we create a pair
  //  of filters since we are processing a $2D$ image.  The filters are
  //  created by invoking the \code{New()} method and assigning the result to
  //  a \doxygen{SmartPointer}.
  //
  //  We need two filters for computing the X component of the Laplacian and
  //  two other filters for computing the Y component.
  //
  //  \index{itk::RecursiveGaussianImageFilter!New()}
  //  \index{itk::RecursiveGaussianImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  FilterType::Pointer filterX1 = FilterType::New();
  FilterType::Pointer filterY1 = FilterType::New();

  FilterType::Pointer filterX2 = FilterType::New();
  FilterType::Pointer filterY2 = FilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Since each one of the newly created filters has the potential to perform
  //  filtering along any dimension, we have to restrict each one to a
  //  particular direction. This is done with the \code{SetDirection()} method.
  //
  //  \index{RecursiveGaussianImageFilter!SetDirection()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filterX1->SetDirection( 0 );   // 0 --> X direction
  filterY1->SetDirection( 1 );   // 1 --> Y direction

  filterX2->SetDirection( 0 );   // 0 --> X direction
  filterY2->SetDirection( 1 );   // 1 --> Y direction
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The \doxygen{RecursiveGaussianImageFilter} can approximate the
  //  convolution with the Gaussian or with its first and second
  //  derivatives. We select one of these options by using the
  //  \code{SetOrder()} method. Note that the argument is an \code{enum} whose
  //  values can be \code{ZeroOrder}, \code{FirstOrder} and
  //  \code{SecondOrder}. For example, to compute the $x$ partial derivative we
  //  should select \code{FirstOrder} for $x$ and \code{ZeroOrder} for
  //  $y$. Here we want only to smooth in $x$ and $y$, so we select
  //  \code{ZeroOrder} in both directions.
  //
  //  \index{RecursiveGaussianImageFilter!SetOrder()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filterX1->SetOrder( FilterType::ZeroOrder );
  filterY1->SetOrder( FilterType::SecondOrder );

  filterX2->SetOrder( FilterType::SecondOrder );
  filterY2->SetOrder( FilterType::ZeroOrder );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  There are two typical ways of normalizing Gaussians depending on their
  //  application. For scale-space analysis it is desirable to use a
  //  normalization that will preserve the maximum value of the input. This
  //  normalization is represented by the following equation.
  //
  //  \begin{equation}
  //          \frac{ 1 }{ \sigma  \sqrt{ 2 \pi } }
  //  \end{equation}
  //
  //  In applications that use the Gaussian as a solution of the diffusion
  //  equation it is desirable to use a normalization that preserve the
  //  integral of the signal. This last approach can be seen as a conservation
  //  of mass principle. This is represented by the following equation.
  //
  //  \begin{equation}
  //          \frac{ 1 }{ \sigma^2  \sqrt{ 2 \pi } }
  //  \end{equation}
  //
  //  The \doxygen{RecursiveGaussianImageFilter} has a boolean flag that allows
  //  users to select between these two normalization options. Selection is
  //  done with the method \code{SetNormalizeAcrossScale()}. Enable this flag
  //  to analyzing an image across scale-space.  In the current example, this
  //  setting has no impact because we are actually renormalizing the output to
  //  the dynamic range of the reader, so we simply disable the flag.
  //
  //  \index{RecursiveGaussianImageFilter!SetNormalizeAcrossScale()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const bool normalizeAcrossScale = false;
  filterX1->SetNormalizeAcrossScale( normalizeAcrossScale );
  filterY1->SetNormalizeAcrossScale( normalizeAcrossScale );
  filterX2->SetNormalizeAcrossScale( normalizeAcrossScale );
  filterY2->SetNormalizeAcrossScale( normalizeAcrossScale );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input image can be obtained from the output of another
  //  filter. Here, an image reader is used as the source. The image is passed to
  //  the $x$ filter and then to the $y$ filter. The reason for keeping these
  //  two filters separate is that it is usual in scale-space applications to
  //  compute not only the smoothing but also combinations of derivatives at
  //  different orders and smoothing. Some factorization is possible when
  //  separate filters are used to generate the intermediate results. Here
  //  this capability is less interesting, though, since we only want to smooth
  //  the image in all directions.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filterX1->SetInput( reader->GetOutput() );
  filterY1->SetInput( filterX1->GetOutput() );

  filterY2->SetInput( reader->GetOutput() );
  filterX2->SetInput( filterY2->GetOutput() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  It is now time to select the $\sigma$ of the Gaussian used to smooth the
  //  data.  Note that $\sigma$ must be passed to both filters and that sigma
  //  is considered to be in millimeters. That is, at the moment of applying
  //  the smoothing process, the filter will take into account the spacing
  //  values defined in the image.
  //
  //  \index{itk::RecursiveGaussianImageFilter!SetSigma()}
  //  \index{SetSigma()!itk::RecursiveGaussianImageFilter}
  //
  //  Software Guide : EndLatex

  const double sigma = atof( argv[3] );

  // Software Guide : BeginCodeSnippet
  filterX1->SetSigma( sigma );
  filterY1->SetSigma( sigma );
  filterX2->SetSigma( sigma );
  filterY2->SetSigma( sigma );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Finally the two components of the Laplacian should be added together. The
  //  \doxygen{AddImageFilter} is used for this purpose.
  //
  //  \index{itk::AddImageFilter!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::AddImageFilter<
                OutputImageType,
                OutputImageType,
                OutputImageType > AddFilterType;

  AddFilterType::Pointer addFilter = AddFilterType::New();

  addFilter->SetInput1( filterY1->GetOutput() );
  addFilter->SetInput2( filterX2->GetOutput() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The filters are triggered by invoking \code{Update()} on the Add filter
  //  at the end of the pipeline.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  try
    {
    addFilter->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The resulting image could be saved to a file using the
  //  \doxygen{ImageFileWriter} class.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  float WritePixelType;

  typedef itk::Image< WritePixelType, 2 >    WriteImageType;

  typedef itk::ImageFileWriter< WriteImageType >  WriterType;

  WriterType::Pointer writer = WriterType::New();

  writer->SetInput( addFilter->GetOutput() );

  writer->SetFileName( argv[2] );

  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{LaplacianRecursiveGaussianImageFilterOutput3}
  // \includegraphics[width=0.44\textwidth]{LaplacianRecursiveGaussianImageFilterOutput5}
  // \itkcaption[Output of the LaplacianRecursiveGaussianImageFilter.]{Effect of the
  // LaplacianRecursiveGaussianImageFilter on a slice from a MRI proton density image
  // of the brain.}
  // \label{fig:LaplacianRecursiveGaussianImageFilterInputOutput}
  // \end{figure}
  //
  //  Figure~\ref{fig:LaplacianRecursiveGaussianImageFilterInputOutput} illustrates the
  //  effect of this filter on a MRI proton density image of the brain using
  //  $\sigma$ values of $3$ (left) and $5$ (right).  The figure shows how the
  //  attenuation of noise can be regulated by selecting the appropriate
  //  standard deviation.  This type of scale-tunable filter is suitable for
  //  performing scale-space analysis.
  //
  //  Software Guide : EndLatex

  // Rescale float outputs to png for inclusion in the Software guide
  //
  if (argc > 4)
    {
    typedef unsigned char                CharPixelType;
    typedef itk::Image<CharPixelType, 2> CharImageType;

    typedef itk::RescaleIntensityImageFilter< OutputImageType, CharImageType>
                                                            RescaleFilterType;

    RescaleFilterType::Pointer rescale = RescaleFilterType::New();
    rescale->SetInput( addFilter->GetOutput() );
    rescale->SetOutputMinimum(   0 );
    rescale->SetOutputMaximum( 255 );
    typedef itk::ImageFileWriter< CharImageType >  CharWriterType;
    CharWriterType::Pointer charWriter = CharWriterType::New();
    charWriter->SetFileName( argv[4] );
    charWriter->SetInput( rescale->GetOutput() );
    charWriter->Update();
    }

  return EXIT_SUCCESS;
}
<commit_msg>DOC: Remove duplicate text in LaplacianRecursiveGaussian example.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS:  {BrainProtonDensitySlice.png}
//    ARGUMENTS:    LaplacianRecursiveGaussianImageFilterOutput3.mha 3
//    OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput3.png}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginCommandLineArgs
//    INPUTS:  {BrainProtonDensitySlice.png}
//    ARGUMENTS:    LaplacianRecursiveGaussianImageFilterOutput5.mha 5
//    OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput5.png}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example illustrates how to use the
//  \doxygen{RecursiveGaussianImageFilter} for computing the Laplacian of a 2D
//  image.
//
//  \index{itk::RecursiveGaussianImageFilter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkAddImageFilter.h"

//  Software Guide : BeginLatex
//
//  The first step required to use this filter is to include its header file.
//
//  \index{itk::RecursiveGaussianImageFilter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkRecursiveGaussianImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkRescaleIntensityImageFilter.h"

int main( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputImageFile  sigma [RescaledOutputImageFile] " << std::endl;
    return EXIT_FAILURE;
    }

  //  Software Guide : BeginLatex
  //
  //  Types should be selected on the desired input and output pixel types.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef    float    InputPixelType;
  typedef    float    OutputPixelType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input and output image types are instantiated using the pixel types.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Image< InputPixelType,  2 >   InputImageType;
  typedef itk::Image< OutputPixelType, 2 >   OutputImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType >  ReaderType;

  //  Software Guide : BeginLatex
  //
  //  The filter type is now instantiated using both the input image and the
  //  output image types.
  //
  //  \index{itk::RecursiveGaussianImageFilter!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::RecursiveGaussianImageFilter<
                        InputImageType, OutputImageType >  FilterType;
  // Software Guide : EndCodeSnippet

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  //  Software Guide : BeginLatex
  //
  //  This filter applies the approximation of the convolution along a single
  //  dimension. It is therefore necessary to concatenate several of these filters
  //  to produce smoothing in all directions.  In this example, we create a pair
  //  of filters since we are processing a $2D$ image.  The filters are
  //  created by invoking the \code{New()} method and assigning the result to
  //  a \doxygen{SmartPointer}.
  //
  //  We need two filters for computing the X component of the Laplacian and
  //  two other filters for computing the Y component.
  //
  //  \index{itk::RecursiveGaussianImageFilter!New()}
  //  \index{itk::RecursiveGaussianImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  FilterType::Pointer filterX1 = FilterType::New();
  FilterType::Pointer filterY1 = FilterType::New();

  FilterType::Pointer filterX2 = FilterType::New();
  FilterType::Pointer filterY2 = FilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Since each one of the newly created filters has the potential to perform
  //  filtering along any dimension, we have to restrict each one to a
  //  particular direction. This is done with the \code{SetDirection()} method.
  //
  //  \index{RecursiveGaussianImageFilter!SetDirection()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filterX1->SetDirection( 0 );   // 0 --> X direction
  filterY1->SetDirection( 1 );   // 1 --> Y direction

  filterX2->SetDirection( 0 );   // 0 --> X direction
  filterY2->SetDirection( 1 );   // 1 --> Y direction
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The \doxygen{RecursiveGaussianImageFilter} can approximate the
  //  convolution with the Gaussian or with its first and second
  //  derivatives. We select one of these options by using the
  //  \code{SetOrder()} method. Note that the argument is an \code{enum} whose
  //  values can be \code{ZeroOrder}, \code{FirstOrder} and
  //  \code{SecondOrder}. For example, to compute the $x$ partial derivative we
  //  should select \code{FirstOrder} for $x$ and \code{ZeroOrder} for
  //  $y$. Here we want only to smooth in $x$ and $y$, so we select
  //  \code{ZeroOrder} in both directions.
  //
  //  \index{RecursiveGaussianImageFilter!SetOrder()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filterX1->SetOrder( FilterType::ZeroOrder );
  filterY1->SetOrder( FilterType::SecondOrder );

  filterX2->SetOrder( FilterType::SecondOrder );
  filterY2->SetOrder( FilterType::ZeroOrder );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  There are two typical ways of normalizing Gaussians depending on their
  //  application. For scale-space analysis it is desirable to use a
  //  normalization that will preserve the maximum value of the input. This
  //  normalization is represented by the following equation.
  //
  //  \begin{equation}
  //          \frac{ 1 }{ \sigma  \sqrt{ 2 \pi } }
  //  \end{equation}
  //
  //  In applications that use the Gaussian as a solution of the diffusion
  //  equation it is desirable to use a normalization that preserve the
  //  integral of the signal. This last approach can be seen as a conservation
  //  of mass principle. This is represented by the following equation.
  //
  //  \begin{equation}
  //          \frac{ 1 }{ \sigma^2  \sqrt{ 2 \pi } }
  //  \end{equation}
  //
  //  The \doxygen{RecursiveGaussianImageFilter} has a boolean flag that allows
  //  users to select between these two normalization options. Selection is
  //  done with the method \code{SetNormalizeAcrossScale()}. Enable this flag
  //  to analyzing an image across scale-space.  In the current example, this
  //  setting has no impact because we are actually renormalizing the output to
  //  the dynamic range of the reader, so we simply disable the flag.
  //
  //  \index{RecursiveGaussianImageFilter!SetNormalizeAcrossScale()}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const bool normalizeAcrossScale = false;
  filterX1->SetNormalizeAcrossScale( normalizeAcrossScale );
  filterY1->SetNormalizeAcrossScale( normalizeAcrossScale );
  filterX2->SetNormalizeAcrossScale( normalizeAcrossScale );
  filterY2->SetNormalizeAcrossScale( normalizeAcrossScale );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The input image can be obtained from the output of another
  //  filter. Here, an image reader is used as the source. The image is passed to
  //  the $x$ filter and then to the $y$ filter. The reason for keeping these
  //  two filters separate is that it is usual in scale-space applications to
  //  compute not only the smoothing but also combinations of derivatives at
  //  different orders and smoothing. Some factorization is possible when
  //  separate filters are used to generate the intermediate results. Here
  //  this capability is less interesting, though, since we only want to smooth
  //  the image in all directions.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filterX1->SetInput( reader->GetOutput() );
  filterY1->SetInput( filterX1->GetOutput() );

  filterY2->SetInput( reader->GetOutput() );
  filterX2->SetInput( filterY2->GetOutput() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  It is now time to select the $\sigma$ of the Gaussian used to smooth the
  //  data.  Note that $\sigma$ must be passed to both filters and that sigma
  //  is considered to be in millimeters. That is, at the moment of applying
  //  the smoothing process, the filter will take into account the spacing
  //  values defined in the image.
  //
  //  \index{itk::RecursiveGaussianImageFilter!SetSigma()}
  //  \index{SetSigma()!itk::RecursiveGaussianImageFilter}
  //
  //  Software Guide : EndLatex

  const double sigma = atof( argv[3] );

  // Software Guide : BeginCodeSnippet
  filterX1->SetSigma( sigma );
  filterY1->SetSigma( sigma );
  filterX2->SetSigma( sigma );
  filterY2->SetSigma( sigma );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Finally the two components of the Laplacian should be added together. The
  //  \doxygen{AddImageFilter} is used for this purpose.
  //
  //  \index{itk::AddImageFilter!Instantiation}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::AddImageFilter<
                OutputImageType,
                OutputImageType,
                OutputImageType > AddFilterType;

  AddFilterType::Pointer addFilter = AddFilterType::New();

  addFilter->SetInput1( filterY1->GetOutput() );
  addFilter->SetInput2( filterX2->GetOutput() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The filters are triggered by invoking \code{Update()} on the Add filter
  //  at the end of the pipeline.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  try
    {
    addFilter->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The resulting image could be saved to a file using the
  //  \doxygen{ImageFileWriter} class.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  float WritePixelType;

  typedef itk::Image< WritePixelType, 2 >    WriteImageType;

  typedef itk::ImageFileWriter< WriteImageType >  WriterType;

  WriterType::Pointer writer = WriterType::New();

  writer->SetInput( addFilter->GetOutput() );

  writer->SetFileName( argv[2] );

  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.44\textwidth]{LaplacianRecursiveGaussianImageFilterOutput3}
  // \includegraphics[width=0.44\textwidth]{LaplacianRecursiveGaussianImageFilterOutput5}
  // \itkcaption[Output of the LaplacianRecursiveGaussianImageFilter.]{Effect of the
  // LaplacianRecursiveGaussianImageFilter on a slice from a MRI proton density image
  // of the brain.}
  // \label{fig:LaplacianRecursiveGaussianImageFilterInputOutput}
  // \end{figure}
  //
  //  Software Guide : EndLatex

  // Rescale float outputs to png for inclusion in the Software guide
  //
  if (argc > 4)
    {
    typedef unsigned char                CharPixelType;
    typedef itk::Image<CharPixelType, 2> CharImageType;

    typedef itk::RescaleIntensityImageFilter< OutputImageType, CharImageType>
                                                            RescaleFilterType;

    RescaleFilterType::Pointer rescale = RescaleFilterType::New();
    rescale->SetInput( addFilter->GetOutput() );
    rescale->SetOutputMinimum(   0 );
    rescale->SetOutputMaximum( 255 );
    typedef itk::ImageFileWriter< CharImageType >  CharWriterType;
    CharWriterType::Pointer charWriter = CharWriterType::New();
    charWriter->SetFileName( argv[4] );
    charWriter->SetInput( rescale->GetOutput() );
    charWriter->Update();
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_DPOBJECT_HXX
#define SC_DPOBJECT_HXX

#include "scdllapi.h"
#include "global.hxx"
#include "address.hxx"
#include "collect.hxx"
#include "dpoutput.hxx"
#include "pivot.hxx"
#include <com/sun/star/sheet/XDimensionsSupplier.hpp>

#include <boost/ptr_container/ptr_list.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>

namespace com { namespace sun { namespace star { namespace sheet {

    struct DataPilotTablePositionData;
    struct DataPilotTableHeaderData;

}}}}

namespace com { namespace sun { namespace star { namespace sheet {
    struct DataPilotFieldFilter;
}}}}

class Rectangle;
class SvStream;
class ScDPSaveData;
class ScDPOutput;
class ScPivot;
class ScPivotCollection;
struct ScPivotParam;
struct ScImportSourceDesc;
struct ScSheetSourceDesc;
class ScStrCollection;
class TypedScStrCollection;
struct PivotField;
class ScDPCacheTable;
class ScDPTableData;

struct ScDPServiceDesc
{
    String  aServiceName;
    String  aParSource;
    String  aParName;
    String  aParUser;
    String  aParPass;

    ScDPServiceDesc( const String& rServ, const String& rSrc, const String& rNam,
                        const String& rUser, const String& rPass ) :
        aServiceName( rServ ), aParSource( rSrc ), aParName( rNam ),
        aParUser( rUser ), aParPass( rPass ) {  }

    sal_Bool operator== ( const ScDPServiceDesc& rOther ) const
        { return aServiceName == rOther.aServiceName &&
                 aParSource   == rOther.aParSource &&
                 aParName     == rOther.aParName &&
                 aParUser     == rOther.aParUser &&
                 aParPass     == rOther.aParPass; }
};

class SC_DLLPUBLIC ScDPObject
{
private:
    ScDocument*             pDoc;
                                            // settings
    ScDPSaveData*           pSaveData;
    String                  aTableName;
    String                  aTableTag;
    ScRange                 aOutRange;
    ScSheetSourceDesc*      pSheetDesc;     //  for sheet data
    ScImportSourceDesc*     pImpDesc;       //  for database data
    ScDPServiceDesc*        pServDesc;      //  for external service
    ::boost::shared_ptr<ScDPTableData>  mpTableData;
                                            // cached data
    com::sun::star::uno::Reference<com::sun::star::sheet::XDimensionsSupplier> xSource;
    ScDPOutput*             pOutput;
    sal_Bool                    bSettingsChanged;
    sal_Bool                    bAlive;         // sal_False if only used to hold settings
    sal_uInt16              mnAutoFormatIndex;
    sal_Bool                    bAllowMove;
    long                    nHeaderRows;    // page fields plus filter button
    bool                    mbHeaderLayout;  // sal_True : grid, sal_False : standard

    SC_DLLPRIVATE ScDPTableData*    GetTableData();
    SC_DLLPRIVATE void              CreateObjects();
    SC_DLLPRIVATE void              CreateOutput();
    sal_Bool                    bRefresh;
    long                        mnCacheId;

public:
    ScDPObject(ScDocument* pD);
    ScDPObject(const ScDPObject& r);
    ~ScDPObject();

    /**
     * When a DP object is "alive", it has table output on a sheet.  This flag
     * doesn't really change the behavior of the object, but is used only for
     * testing purposes.
     */
    void                SetAlive(sal_Bool bSet);
    void                SetAllowMove(sal_Bool bSet);

    void                InvalidateData();
    void                ClearSource();

    void                Output( const ScAddress& rPos );
    ScRange             GetNewOutputRange( bool& rOverflow );
    const ScRange       GetOutputRangeByType( sal_Int32 nType );

    void                SetSaveData(const ScDPSaveData& rData);
    ScDPSaveData*       GetSaveData() const     { return pSaveData; }

    void                SetOutRange(const ScRange& rRange);
    const ScRange&      GetOutRange() const     { return aOutRange; }

    void                SetHeaderLayout(bool bUseGrid);
    bool                GetHeaderLayout() const;

    void                SetSheetDesc(const ScSheetSourceDesc& rDesc);
    void                SetImportDesc(const ScImportSourceDesc& rDesc);
    void                SetServiceData(const ScDPServiceDesc& rDesc);

    void                WriteSourceDataTo( ScDPObject& rDest ) const;
    void                WriteTempDataTo( ScDPObject& rDest ) const;

    const ScSheetSourceDesc* GetSheetDesc() const   { return pSheetDesc; }
    const ScImportSourceDesc* GetImportSourceDesc() const   { return pImpDesc; }
    const ScDPServiceDesc* GetDPServiceDesc() const { return pServDesc; }

    com::sun::star::uno::Reference<com::sun::star::sheet::XDimensionsSupplier> GetSource();

    sal_Bool                IsSheetData() const;
    sal_Bool                IsImportData() const { return(pImpDesc != NULL); }
    sal_Bool                IsServiceData() const { return(pServDesc != NULL); }

    void                SetName(const String& rNew);
    const String&       GetName() const                 { return aTableName; }
    void                SetTag(const String& rNew);
    const String&       GetTag() const                  { return aTableTag; }

    /**
     *  Data description cell displays the description of a data dimension if
     *  and only if there is only one data dimension.  It's usually located at
     *  the upper-left corner of the table output.
     */
    bool                IsDataDescriptionCell(const ScAddress& rPos);

    bool                IsDimNameInUse(const ::rtl::OUString& rName) const;
    String              GetDimName( long nDim, sal_Bool& rIsDataLayout, sal_Int32* pFlags = NULL );
    sal_Bool                IsDuplicated( long nDim );
    long                GetDimCount();
    void                GetHeaderPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTableHeaderData& rData);
    long                GetHeaderDim( const ScAddress& rPos, sal_uInt16& rOrient );
    sal_Bool                GetHeaderDrag( const ScAddress& rPos, sal_Bool bMouseLeft, sal_Bool bMouseTop,
                                        long nDragDim,
                                        Rectangle& rPosRect, sal_uInt16& rOrient, long& rDimPos );
    sal_Bool                IsFilterButton( const ScAddress& rPos );

    sal_Bool                GetPivotData( ScDPGetPivotDataField& rTarget, /* returns result */
                                      const std::vector< ScDPGetPivotDataField >& rFilters );
    sal_Bool                ParseFilters( ScDPGetPivotDataField& rTarget,
                                      std::vector< ScDPGetPivotDataField >& rFilters,
                                      const String& rFilterList );

    void                GetMemberResultNames( ScStrCollection& rNames, long nDimension );

    void                FillPageList( TypedScStrCollection& rStrings, long nField );

    void                ToggleDetails(const ::com::sun::star::sheet::DataPilotTableHeaderData& rElemDesc, ScDPObject* pDestObj);

    sal_Bool                FillOldParam(ScPivotParam& rParam) const;
    sal_Bool                FillLabelData(ScPivotParam& rParam);
    void                InitFromOldPivot(const ScPivot& rOld, ScDocument* pDoc, sal_Bool bSetSource);

    sal_Bool                GetHierarchiesNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xHiers );
    sal_Bool                GetHierarchies( sal_Int32 nDim, com::sun::star::uno::Sequence< rtl::OUString >& rHiers );

    sal_Int32           GetUsedHierarchy( sal_Int32 nDim );

    sal_Bool                GetMembersNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );
    sal_Bool                GetMembersNA( sal_Int32 nDim, sal_Int32 nHier, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );

    bool                GetMemberNames( sal_Int32 nDim, ::com::sun::star::uno::Sequence< ::rtl::OUString >& rNames );
    bool                GetMembers( sal_Int32 nDim, sal_Int32 nHier, ::std::vector<ScDPLabelData::Member>& rMembers );

    void                UpdateReference( UpdateRefMode eUpdateRefMode,
                                         const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    sal_Bool                RefsEqual( const ScDPObject& r ) const;
    void                WriteRefsTo( ScDPObject& r ) const;

    void                GetPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTablePositionData& rPosData);

    bool                GetDataFieldPositionData(const ScAddress& rPos,
                                                 ::com::sun::star::uno::Sequence<
                                                    ::com::sun::star::sheet::DataPilotFieldFilter >& rFilters);

    void                GetDrillDownData(const ScAddress& rPos,
                                         ::com::sun::star::uno::Sequence<
                                            ::com::sun::star::uno::Sequence<
                                                ::com::sun::star::uno::Any > >& rTableData);

    // apply drop-down attribute, initialize nHeaderRows, without accessing the source
    // (button attribute must be present)
    void                RefreshAfterLoad();

    void                BuildAllDimensionMembers();

    static sal_Bool         HasRegisteredSources();
    static com::sun::star::uno::Sequence<rtl::OUString> GetRegisteredSources();
    static com::sun::star::uno::Reference<com::sun::star::sheet::XDimensionsSupplier>
                        CreateSource( const ScDPServiceDesc& rDesc );

    static void         ConvertOrientation( ScDPSaveData& rSaveData,
                            const ::std::vector<PivotField>& rFields, sal_uInt16 nOrient,
                            const com::sun::star::uno::Reference<
                                com::sun::star::sheet::XDimensionsSupplier>& xSource,
                            ::std::vector<PivotField>* pRefColFields = NULL,
                            ::std::vector<PivotField>* pRefRowFields = NULL,
                            ::std::vector<PivotField>* pRefPageFields = NULL );

    static bool         IsOrientationAllowed( sal_uInt16 nOrient, sal_Int32 nDimFlags );
};

class ScDPCollection
{
private:
    typedef ::boost::ptr_vector<ScDPObject> TablesType;

    ScDocument* pDoc;
    TablesType maTables;

public:
    ScDPCollection(ScDocument* pDocument);
    ScDPCollection(const ScDPCollection& r);
    ~ScDPCollection();

    SC_DLLPUBLIC size_t GetCount() const;
    SC_DLLPUBLIC ScDPObject* operator[](size_t nIndex);
    SC_DLLPUBLIC const ScDPObject* operator[](size_t nIndex) const;

    const ScDPObject* GetByName(const String& rName) const;

    void DeleteOnTab( SCTAB nTab );
    void UpdateReference( UpdateRefMode eUpdateRefMode,
                          const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );

    bool RefsEqual( const ScDPCollection& r ) const;
    void WriteRefsTo( ScDPCollection& r ) const;

    /**
     * Create a new name that's not yet used by any existing data pilot
     * objects.  All data pilot names are 'DataPilot' + <num>, and the nMin
     * specifies the minimum number allowed.
     *
     * @param nMin minimum number allowed.
     *
     * @return new name for data pilot object.
     */
    String CreateNewName( sal_uInt16 nMin = 1 ) const;

    void FreeTable(ScDPObject* pDPObj);
    SC_DLLPUBLIC bool InsertNewTable(ScDPObject* pDPObj);

    bool HasDPTable(SCCOL nCol, SCROW nRow, SCTAB nTab) const;
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: consistent struct/class declaration<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_DPOBJECT_HXX
#define SC_DPOBJECT_HXX

#include "scdllapi.h"
#include "global.hxx"
#include "address.hxx"
#include "collect.hxx"
#include "dpoutput.hxx"
#include "pivot.hxx"
#include <com/sun/star/sheet/XDimensionsSupplier.hpp>

#include <boost/ptr_container/ptr_list.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>

namespace com { namespace sun { namespace star { namespace sheet {

    struct DataPilotTablePositionData;
    struct DataPilotTableHeaderData;

}}}}

namespace com { namespace sun { namespace star { namespace sheet {
    struct DataPilotFieldFilter;
}}}}

class Rectangle;
class SvStream;
class ScDPSaveData;
class ScDPOutput;
class ScPivot;
class ScPivotCollection;
struct ScPivotParam;
struct ScImportSourceDesc;
class ScSheetSourceDesc;
class ScStrCollection;
class TypedScStrCollection;
struct PivotField;
class ScDPCacheTable;
class ScDPTableData;

struct ScDPServiceDesc
{
    String  aServiceName;
    String  aParSource;
    String  aParName;
    String  aParUser;
    String  aParPass;

    ScDPServiceDesc( const String& rServ, const String& rSrc, const String& rNam,
                        const String& rUser, const String& rPass ) :
        aServiceName( rServ ), aParSource( rSrc ), aParName( rNam ),
        aParUser( rUser ), aParPass( rPass ) {  }

    sal_Bool operator== ( const ScDPServiceDesc& rOther ) const
        { return aServiceName == rOther.aServiceName &&
                 aParSource   == rOther.aParSource &&
                 aParName     == rOther.aParName &&
                 aParUser     == rOther.aParUser &&
                 aParPass     == rOther.aParPass; }
};

class SC_DLLPUBLIC ScDPObject
{
private:
    ScDocument*             pDoc;
                                            // settings
    ScDPSaveData*           pSaveData;
    String                  aTableName;
    String                  aTableTag;
    ScRange                 aOutRange;
    ScSheetSourceDesc*      pSheetDesc;     //  for sheet data
    ScImportSourceDesc*     pImpDesc;       //  for database data
    ScDPServiceDesc*        pServDesc;      //  for external service
    ::boost::shared_ptr<ScDPTableData>  mpTableData;
                                            // cached data
    com::sun::star::uno::Reference<com::sun::star::sheet::XDimensionsSupplier> xSource;
    ScDPOutput*             pOutput;
    sal_Bool                    bSettingsChanged;
    sal_Bool                    bAlive;         // sal_False if only used to hold settings
    sal_uInt16              mnAutoFormatIndex;
    sal_Bool                    bAllowMove;
    long                    nHeaderRows;    // page fields plus filter button
    bool                    mbHeaderLayout;  // sal_True : grid, sal_False : standard

    SC_DLLPRIVATE ScDPTableData*    GetTableData();
    SC_DLLPRIVATE void              CreateObjects();
    SC_DLLPRIVATE void              CreateOutput();
    sal_Bool                    bRefresh;
    long                        mnCacheId;

public:
    ScDPObject(ScDocument* pD);
    ScDPObject(const ScDPObject& r);
    ~ScDPObject();

    /**
     * When a DP object is "alive", it has table output on a sheet.  This flag
     * doesn't really change the behavior of the object, but is used only for
     * testing purposes.
     */
    void                SetAlive(sal_Bool bSet);
    void                SetAllowMove(sal_Bool bSet);

    void                InvalidateData();
    void                ClearSource();

    void                Output( const ScAddress& rPos );
    ScRange             GetNewOutputRange( bool& rOverflow );
    const ScRange       GetOutputRangeByType( sal_Int32 nType );

    void                SetSaveData(const ScDPSaveData& rData);
    ScDPSaveData*       GetSaveData() const     { return pSaveData; }

    void                SetOutRange(const ScRange& rRange);
    const ScRange&      GetOutRange() const     { return aOutRange; }

    void                SetHeaderLayout(bool bUseGrid);
    bool                GetHeaderLayout() const;

    void                SetSheetDesc(const ScSheetSourceDesc& rDesc);
    void                SetImportDesc(const ScImportSourceDesc& rDesc);
    void                SetServiceData(const ScDPServiceDesc& rDesc);

    void                WriteSourceDataTo( ScDPObject& rDest ) const;
    void                WriteTempDataTo( ScDPObject& rDest ) const;

    const ScSheetSourceDesc* GetSheetDesc() const   { return pSheetDesc; }
    const ScImportSourceDesc* GetImportSourceDesc() const   { return pImpDesc; }
    const ScDPServiceDesc* GetDPServiceDesc() const { return pServDesc; }

    com::sun::star::uno::Reference<com::sun::star::sheet::XDimensionsSupplier> GetSource();

    sal_Bool                IsSheetData() const;
    sal_Bool                IsImportData() const { return(pImpDesc != NULL); }
    sal_Bool                IsServiceData() const { return(pServDesc != NULL); }

    void                SetName(const String& rNew);
    const String&       GetName() const                 { return aTableName; }
    void                SetTag(const String& rNew);
    const String&       GetTag() const                  { return aTableTag; }

    /**
     *  Data description cell displays the description of a data dimension if
     *  and only if there is only one data dimension.  It's usually located at
     *  the upper-left corner of the table output.
     */
    bool                IsDataDescriptionCell(const ScAddress& rPos);

    bool                IsDimNameInUse(const ::rtl::OUString& rName) const;
    String              GetDimName( long nDim, sal_Bool& rIsDataLayout, sal_Int32* pFlags = NULL );
    sal_Bool                IsDuplicated( long nDim );
    long                GetDimCount();
    void                GetHeaderPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTableHeaderData& rData);
    long                GetHeaderDim( const ScAddress& rPos, sal_uInt16& rOrient );
    sal_Bool                GetHeaderDrag( const ScAddress& rPos, sal_Bool bMouseLeft, sal_Bool bMouseTop,
                                        long nDragDim,
                                        Rectangle& rPosRect, sal_uInt16& rOrient, long& rDimPos );
    sal_Bool                IsFilterButton( const ScAddress& rPos );

    sal_Bool                GetPivotData( ScDPGetPivotDataField& rTarget, /* returns result */
                                      const std::vector< ScDPGetPivotDataField >& rFilters );
    sal_Bool                ParseFilters( ScDPGetPivotDataField& rTarget,
                                      std::vector< ScDPGetPivotDataField >& rFilters,
                                      const String& rFilterList );

    void                GetMemberResultNames( ScStrCollection& rNames, long nDimension );

    void                FillPageList( TypedScStrCollection& rStrings, long nField );

    void                ToggleDetails(const ::com::sun::star::sheet::DataPilotTableHeaderData& rElemDesc, ScDPObject* pDestObj);

    sal_Bool                FillOldParam(ScPivotParam& rParam) const;
    sal_Bool                FillLabelData(ScPivotParam& rParam);
    void                InitFromOldPivot(const ScPivot& rOld, ScDocument* pDoc, sal_Bool bSetSource);

    sal_Bool                GetHierarchiesNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xHiers );
    sal_Bool                GetHierarchies( sal_Int32 nDim, com::sun::star::uno::Sequence< rtl::OUString >& rHiers );

    sal_Int32           GetUsedHierarchy( sal_Int32 nDim );

    sal_Bool                GetMembersNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );
    sal_Bool                GetMembersNA( sal_Int32 nDim, sal_Int32 nHier, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );

    bool                GetMemberNames( sal_Int32 nDim, ::com::sun::star::uno::Sequence< ::rtl::OUString >& rNames );
    bool                GetMembers( sal_Int32 nDim, sal_Int32 nHier, ::std::vector<ScDPLabelData::Member>& rMembers );

    void                UpdateReference( UpdateRefMode eUpdateRefMode,
                                         const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
    sal_Bool                RefsEqual( const ScDPObject& r ) const;
    void                WriteRefsTo( ScDPObject& r ) const;

    void                GetPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTablePositionData& rPosData);

    bool                GetDataFieldPositionData(const ScAddress& rPos,
                                                 ::com::sun::star::uno::Sequence<
                                                    ::com::sun::star::sheet::DataPilotFieldFilter >& rFilters);

    void                GetDrillDownData(const ScAddress& rPos,
                                         ::com::sun::star::uno::Sequence<
                                            ::com::sun::star::uno::Sequence<
                                                ::com::sun::star::uno::Any > >& rTableData);

    // apply drop-down attribute, initialize nHeaderRows, without accessing the source
    // (button attribute must be present)
    void                RefreshAfterLoad();

    void                BuildAllDimensionMembers();

    static sal_Bool         HasRegisteredSources();
    static com::sun::star::uno::Sequence<rtl::OUString> GetRegisteredSources();
    static com::sun::star::uno::Reference<com::sun::star::sheet::XDimensionsSupplier>
                        CreateSource( const ScDPServiceDesc& rDesc );

    static void         ConvertOrientation( ScDPSaveData& rSaveData,
                            const ::std::vector<PivotField>& rFields, sal_uInt16 nOrient,
                            const com::sun::star::uno::Reference<
                                com::sun::star::sheet::XDimensionsSupplier>& xSource,
                            ::std::vector<PivotField>* pRefColFields = NULL,
                            ::std::vector<PivotField>* pRefRowFields = NULL,
                            ::std::vector<PivotField>* pRefPageFields = NULL );

    static bool         IsOrientationAllowed( sal_uInt16 nOrient, sal_Int32 nDimFlags );
};

class ScDPCollection
{
private:
    typedef ::boost::ptr_vector<ScDPObject> TablesType;

    ScDocument* pDoc;
    TablesType maTables;

public:
    ScDPCollection(ScDocument* pDocument);
    ScDPCollection(const ScDPCollection& r);
    ~ScDPCollection();

    SC_DLLPUBLIC size_t GetCount() const;
    SC_DLLPUBLIC ScDPObject* operator[](size_t nIndex);
    SC_DLLPUBLIC const ScDPObject* operator[](size_t nIndex) const;

    const ScDPObject* GetByName(const String& rName) const;

    void DeleteOnTab( SCTAB nTab );
    void UpdateReference( UpdateRefMode eUpdateRefMode,
                          const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );

    bool RefsEqual( const ScDPCollection& r ) const;
    void WriteRefsTo( ScDPCollection& r ) const;

    /**
     * Create a new name that's not yet used by any existing data pilot
     * objects.  All data pilot names are 'DataPilot' + <num>, and the nMin
     * specifies the minimum number allowed.
     *
     * @param nMin minimum number allowed.
     *
     * @return new name for data pilot object.
     */
    String CreateNewName( sal_uInt16 nMin = 1 ) const;

    void FreeTable(ScDPObject* pDPObj);
    SC_DLLPUBLIC bool InsertNewTable(ScDPObject* pDPObj);

    bool HasDPTable(SCCOL nCol, SCROW nRow, SCTAB nTab) const;
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "PyLogHook.h"

#include <boost/python.hpp>

#include <cassert>

#include <iostream>

// todo: remove dependency
#include "../PyMeshPlugin.hh"

void* data = 0;

void pyLog(const char* log)
{
    assert(data); // todo: remove when depedency is removed
    reinterpret_cast<PyMeshPlugin*>(data)->pyOutput(log);
}

PyObject* stdOutPutCPP(PyObject* self, PyObject* args)
{
    // parse parameters
    const char* str;
    if (!PyArg_ParseTuple(args, "s", &str))
        return NULL;

    // callback
    pyLog(str);

    // return nothing
    Py_INCREF(Py_None);
    return Py_None;
}

void stdOutPutCPP2(const char* w)
{
    pyLog(w);
}

void initPyLogger(PyObject* module, void* customData)
{
    assert(Py_IsInitialized());
    data = customData;

    const char* register_stdOutErrClass = "\
import sys\n\
class CatchOutErr:\n\
    def write(self, txt):\n\
        stdOutPutCPP(txt)\n\
    def flush(self):\n\
        pass\n\
sys.stdout = CatchOutErr()\n\
sys.stderr = CatchOutErr()\n\
";

    boost::python::object main_module(boost::python::handle<>(boost::python::borrowed(module)));
    boost::python::object main_namespace = main_module.attr("__dict__");
    main_namespace["stdOutPutCPP"] = stdOutPutCPP2;

    PyMethodDef pmd[] = { {"stdOutPutCPP",stdOutPutCPP,METH_VARARGS, ""},{NULL,NULL,0,NULL} };
    //PyModule_AddFunctions(module, pmd);
    //boost::python::exec("stdOutPutCPP(\"Hello non Hook\")", main_namespace);

    PyRun_SimpleString(register_stdOutErrClass);

    PyErr_Print();
}

<commit_msg>redirect PY error message to OF error output<commit_after>#include "PyLogHook.h"

#include <boost/python.hpp>

#include <cassert>

#include <iostream>

// todo: remove dependency
#include "../PyMeshPlugin.hh"

void* data = 0;

void pyLog(const char* log)
{
    assert(data);
    reinterpret_cast<PyMeshPlugin*>(data)->pyOutput(log);
}

void pyErr(const char* log)
{
    assert(data);
    reinterpret_cast<PyMeshPlugin*>(data)->pyError(log);
}

PyObject* stdOutPutCPP(PyObject* self, PyObject* args)
{
    // parse parameters
    const char* str;
    if (!PyArg_ParseTuple(args, "s", &str))
        return NULL;

    // callback
    pyLog(str);

    // return nothing
    Py_INCREF(Py_None);
    return Py_None;
}

PyObject* stdErrCPP(PyObject* self, PyObject* args)
{
    // parse parameters
    const char* str;
    if (!PyArg_ParseTuple(args, "s", &str))
        return NULL;

    // callback
    pyErr(str);

    // return nothing
    Py_INCREF(Py_None);
    return Py_None;
}

void stdOutPutCPP2(const char* w)
{
    pyLog(w);
}

void stdErrCPP2(const char* w)
{
    pyErr(w);
}

void initPyLogger(PyObject* module, void* customData)
{
    assert(Py_IsInitialized());
    data = customData;

    const char* register_stdOutErrClass = "\
import sys\n\
class OF_CatchOutput:\n\
    def write(self, txt):\n\
        stdOutPutCPP(txt)\n\
    def flush(self):\n\
        pass\n\
class OF_CatchError:\n\
    def write(self, txt):\n\
        stdErrCPP(txt)\n\
    def flush(self):\n\
        pass\n\
sys.stdout = OF_CatchOutput()\n\
sys.stderr = OF_CatchError()\n\
";

    boost::python::object main_module(boost::python::handle<>(boost::python::borrowed(module)));
    boost::python::object main_namespace = main_module.attr("__dict__");
    main_namespace["stdOutPutCPP"] = stdOutPutCPP2;
    main_namespace["stdErrCPP"] = stdErrCPP2;

    //PyMethodDef pmd[] = {
    //    {"stdOutPutCPP",stdOutPutCPP,METH_VARARGS, ""},
    //    {"stdErrCPP",stdErrCPP,METH_VARARGS, ""},
    //    {NULL,NULL,0,NULL} };

    PyRun_SimpleString(register_stdOutErrClass);

    PyErr_Print();
}

<|endoftext|>


<commit_before>//===--- DummyFuzzerMain.cpp - Entry point to sanity check the fuzzer -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation of main so we can build and test without linking libFuzzer.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);
extern "C" LLVM_ATTRIBUTE_WEAK int LLVMFuzzerInitialize(int *argc,
                                                        char ***argv) {
  return 0;
}

int main(int argc, char *argv[]) {
  errs() << "*** This tool was not linked to libFuzzer.\n"
         << "*** No fuzzing will be performed.\n";
  if (int RC = LLVMFuzzerInitialize(&argc, &argv)) {
    errs() << "Initialization failed\n";
    return RC;
  }

  for (int I = 1; I < argc; ++I) {
    StringRef Arg(argv[I]);
    if (Arg.startswith("-")) {
      if (Arg.equals("-ignore_remaining_args=1"))
        break;
      continue;
    }

    auto BufOrErr = MemoryBuffer::getFile(Arg, /*FileSize-*/ -1,
                                          /*RequiresNullTerminator=*/false);
    if (std::error_code EC = BufOrErr.getError()) {
      errs() << "Error reading file: " << Arg << ": " << EC.message() << "\n";
      return 1;
    }
    std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
    errs() << "Running: " << Arg << " (" << Buf->getBufferSize() << " bytes)\n";
    LLVMFuzzerTestOneInput(
        reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
        Buf->getBufferSize());
  }
}
<commit_msg>llvm-isel-fuzzer: Weak function invoke the ire of PE/COFF<commit_after>//===--- DummyFuzzerMain.cpp - Entry point to sanity check the fuzzer -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation of main so we can build and test without linking libFuzzer.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv);

int main(int argc, char *argv[]) {
  errs() << "*** This tool was not linked to libFuzzer.\n"
         << "*** No fuzzing will be performed.\n";
  if (int RC = LLVMFuzzerInitialize(&argc, &argv)) {
    errs() << "Initialization failed\n";
    return RC;
  }

  for (int I = 1; I < argc; ++I) {
    StringRef Arg(argv[I]);
    if (Arg.startswith("-")) {
      if (Arg.equals("-ignore_remaining_args=1"))
        break;
      continue;
    }

    auto BufOrErr = MemoryBuffer::getFile(Arg, /*FileSize-*/ -1,
                                          /*RequiresNullTerminator=*/false);
    if (std::error_code EC = BufOrErr.getError()) {
      errs() << "Error reading file: " << Arg << ": " << EC.message() << "\n";
      return 1;
    }
    std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
    errs() << "Running: " << Arg << " (" << Buf->getBufferSize() << " bytes)\n";
    LLVMFuzzerTestOneInput(
        reinterpret_cast<const uint8_t *>(Buf->getBufferStart()),
        Buf->getBufferSize());
  }
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    const string
        SHA = " -b 1|224|256|384|512|512_224|512_256",
        PAIR = " -p BN128|Edwards",
        R = " -r",
        DIG = " -d digest",
        EQ = " -e pattern",
        NEQ = " -n pattern",
        optPAIR = " [-p BN128|Edwards]",
        optR = " [-r]",
        optDIG = " [-d hex_digest]",
        optEQ = " [-e equal_pattern]",
        optNEQ = " [-n not_equal_pattern]";

    cout << "usage: " << exeName << SHA << optPAIR << optR << optDIG << optEQ << optNEQ << endl
         << endl
         << "text from standard input:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << endl
         << endl
         << "pre-image pattern and hash:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << DIG << EQ << NEQ << endl
         << endl
         << "hash only, skip zero knowledge proof:" << endl
         << "echo \"abc\" | " << exeName << SHA << endl
         << endl
         << "random data:" << endl
         << exeName << PAIR << SHA << R << endl;

    exit(EXIT_FAILURE);
}

template <typename ZK_SHA, typename EVAL_SHA>
bool runTest(const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    DataBufferStream buf;

    if (stdInput) {
        // fill message block(s) from standard input
        cin >> buf;

        ZK_SHA::padMessage(buf);

    } else {
        // fill entire message block with random data
        random_device rd;
        const size_t M = sizeof(typename EVAL_SHA::WordType) / sizeof(uint32_t);
        for (size_t i = 0; i < 16 * M; ++i)
            buf->push32(rd());

        // no padding is not SHA-2 standard (compression function only)
    }

    if (!hashOnly) {
        // print buffer
        HexDumper dump(cout);
        dump.print(buf);
    }

    // compute message digest (adds padding if necessary)
    typename ZK_SHA::DigType zk_digest;
    if (eqPattern.empty() && neqPattern.empty()) {
        // just hash the buffer data
        zk_digest = digest(ZK_SHA(), buf);

    } else {
        // additional constraints on pre-image
        // must expose buffer as variables
        std::size_t idx = 0;

        ZK_SHA hashAlgo;

        auto bufCopy = buf;
        while (! bufCopy.empty()) {
            typename ZK_SHA::MsgType msg;
            bless(msg, bufCopy);
            hashAlgo.msgInput(msg);

            // pre-image buffer variables as octets
            typename ZK_SHA::PreType preimg;
            bless(preimg, msg);

            PrintHex pr(cout, false);

            // constraints on pre-image, if any
            for (std::size_t i = 0; i < preimg.size(); ++i) {
                // equal
                if ((idx < eqPattern.size()) && ('?' != eqPattern[idx])) {
                    assert_true(preimg[i] == eqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] == ";
                    pr.pushOctet(eqPattern[idx]);
                    cout << endl;
                }

                // not equal
                if ((idx < neqPattern.size()) && ('?' != neqPattern[idx])) {
                    assert_true(preimg[i] != neqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] != ";
                    pr.pushOctet(neqPattern[idx]);
                    cout << endl;
                }

                ++idx;
            }
        }

        hashAlgo.computeHash();
        zk_digest = hashAlgo.digest();
    }

    const auto eval_digest = digest(EVAL_SHA(), buf);

    assert(zk_digest.size() == eval_digest.size());

    DataBuffer<PrintHex> hexpr(cout, false);

    // compare message digest values
    bool ok = true;
    for (size_t i = 0; i < zk_digest.size(); ++i) {
        if (zk_digest[i]->value() != eval_digest[i]) {
            ok = false;
            cout << "digest[" << i << "] error zk: ";
            hexpr.push(zk_digest[i]->value());
            cout << " eval: ";
            hexpr.push(eval_digest[i]);
            cout << endl;
        }
    }

    // message digest proof constraint
    if (hashDig.empty()) {
        // hash digest calculated by SHA template
        assert_true(zk_digest == eval_digest);

    } else {
        // hash digest specified as ASCII hex string
        vector<uint8_t> v;
        if (!asciiHexToVector(hashDig, v)) {
            ok = false;

        } else {
            // check that hash digest is correct size
            const size_t N = sizeof(typename EVAL_SHA::DigType);
            if (v.size() != N) {
                ok = false;
                cout << "error: hash digest " << hashDig
                     << " must be for " << N << " octets"
                     << endl;

            } else {
                DataBufferStream digBuf(v);

                typename ZK_SHA::DigType dig;
                bless(dig, digBuf);

                assert_true(zk_digest == dig);
            }
        }
    }

    if (!hashOnly) cout << "digest ";
    cout << asciiHex(eval_digest, !hashOnly) << endl;

    return ok;
}

template <typename PAIRING>
bool runTest(const string& shaBits,
             const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    reset<PAIRING>();

    bool valueOK = false;
    typedef typename PAIRING::Fr FR;

    if ("1" == shaBits) {
        valueOK = runTest<zk::SHA1<FR>, eval::SHA1>(stdInput, hashOnly,
                                                    hashDig, eqPattern, neqPattern);
    } else if ("224" == shaBits) {
        valueOK = runTest<zk::SHA224<FR>, eval::SHA224>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("256" == shaBits) {
        valueOK = runTest<zk::SHA256<FR>, eval::SHA256>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("384" == shaBits) {
        valueOK = runTest<zk::SHA384<FR>, eval::SHA384>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512" == shaBits) {
        valueOK = runTest<zk::SHA512<FR>, eval::SHA512>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512_224" == shaBits) {
        valueOK = runTest<zk::SHA512_224<FR>, eval::SHA512_224>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    } else if ("512_256" == shaBits) {
        valueOK = runTest<zk::SHA512_256<FR>, eval::SHA512_256>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    }

    // special case for hash only, skip zero knowledge proof
    if (hashOnly) return valueOK;

    cout << "variable count " << variable_count<PAIRING>() << endl;

    GenericProgressBar progress1(cerr), progress2(cerr, 50);

    cerr << "generate key pair";
    const auto key = keypair<PAIRING>(progress2);
    cerr << endl;

    const auto in = input<PAIRING>();

    cerr << "generate proof";
    const auto p = proof(key, progress2);
    cerr << endl;

    cerr << "verify proof ";
    const bool proofOK = verify(key, in, p, progress1);
    cerr << endl;

    return valueOK && proofOK;
}

int main(int argc, char *argv[])
{
    Getopt cmdLine(argc, argv, "pbden", "", "r");
    if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);

    auto pairing = cmdLine.getString('p');

    const auto
        shaBits = cmdLine.getString('b'),
        hashDig = cmdLine.getString('d'),
        eqPattern = cmdLine.getString('e'),
        neqPattern = cmdLine.getString('n');

    const auto stdInput = !cmdLine.getFlag('r');

    // special case for hash only, skip zero knowledge proof
    const bool hashOnly = pairing.empty() && validSHA2Name(shaBits) && stdInput;
    if (hashOnly) pairing = "BN128"; // elliptic curve pairing is arbitrary

    if (!validPairingName(pairing) || !validSHA2Name(shaBits))
        printUsage(argv[0]);

    bool result;

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        result = runTest<BN128_PAIRING>(shaBits,
                                        stdInput,
                                        hashOnly,
                                        hashDig,
                                        eqPattern,
                                        neqPattern);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        result = runTest<EDWARDS_PAIRING>(shaBits,
                                          stdInput,
                                          hashOnly,
                                          hashDig,
                                          eqPattern,
                                          neqPattern);
    }

    if (!hashOnly) {
        cout << "test " << (result ? "passed" : "failed") << endl;
    }

    return EXIT_SUCCESS;
}
<commit_msg>distinguish snarkfront.hpp<commit_after>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <vector>

#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    const string
        SHA = " -b 1|224|256|384|512|512_224|512_256",
        PAIR = " -p BN128|Edwards",
        R = " -r",
        DIG = " -d digest",
        EQ = " -e pattern",
        NEQ = " -n pattern",
        optPAIR = " [-p BN128|Edwards]",
        optR = " [-r]",
        optDIG = " [-d hex_digest]",
        optEQ = " [-e equal_pattern]",
        optNEQ = " [-n not_equal_pattern]";

    cout << "usage: " << exeName << SHA << optPAIR << optR << optDIG << optEQ << optNEQ << endl
         << endl
         << "text from standard input:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << endl
         << endl
         << "pre-image pattern and hash:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << DIG << EQ << NEQ << endl
         << endl
         << "hash only, skip zero knowledge proof:" << endl
         << "echo \"abc\" | " << exeName << SHA << endl
         << endl
         << "random data:" << endl
         << exeName << PAIR << SHA << R << endl;

    exit(EXIT_FAILURE);
}

template <typename ZK_SHA, typename EVAL_SHA>
bool runTest(const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    DataBufferStream buf;

    if (stdInput) {
        // fill message block(s) from standard input
        cin >> buf;

        ZK_SHA::padMessage(buf);

    } else {
        // fill entire message block with random data
        random_device rd;
        const size_t M = sizeof(typename EVAL_SHA::WordType) / sizeof(uint32_t);
        for (size_t i = 0; i < 16 * M; ++i)
            buf->push32(rd());

        // no padding is not SHA-2 standard (compression function only)
    }

    if (!hashOnly) {
        // print buffer
        HexDumper dump(cout);
        dump.print(buf);
    }

    // compute message digest (adds padding if necessary)
    typename ZK_SHA::DigType zk_digest;
    if (eqPattern.empty() && neqPattern.empty()) {
        // just hash the buffer data
        zk_digest = digest(ZK_SHA(), buf);

    } else {
        // additional constraints on pre-image
        // must expose buffer as variables
        std::size_t idx = 0;

        ZK_SHA hashAlgo;

        auto bufCopy = buf;
        while (! bufCopy.empty()) {
            typename ZK_SHA::MsgType msg;
            bless(msg, bufCopy);
            hashAlgo.msgInput(msg);

            // pre-image buffer variables as octets
            typename ZK_SHA::PreType preimg;
            bless(preimg, msg);

            PrintHex pr(cout, false);

            // constraints on pre-image, if any
            for (std::size_t i = 0; i < preimg.size(); ++i) {
                // equal
                if ((idx < eqPattern.size()) && ('?' != eqPattern[idx])) {
                    assert_true(preimg[i] == eqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] == ";
                    pr.pushOctet(eqPattern[idx]);
                    cout << endl;
                }

                // not equal
                if ((idx < neqPattern.size()) && ('?' != neqPattern[idx])) {
                    assert_true(preimg[i] != neqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] != ";
                    pr.pushOctet(neqPattern[idx]);
                    cout << endl;
                }

                ++idx;
            }
        }

        hashAlgo.computeHash();
        zk_digest = hashAlgo.digest();
    }

    const auto eval_digest = digest(EVAL_SHA(), buf);

    assert(zk_digest.size() == eval_digest.size());

    DataBuffer<PrintHex> hexpr(cout, false);

    // compare message digest values
    bool ok = true;
    for (size_t i = 0; i < zk_digest.size(); ++i) {
        if (zk_digest[i]->value() != eval_digest[i]) {
            ok = false;
            cout << "digest[" << i << "] error zk: ";
            hexpr.push(zk_digest[i]->value());
            cout << " eval: ";
            hexpr.push(eval_digest[i]);
            cout << endl;
        }
    }

    // message digest proof constraint
    if (hashDig.empty()) {
        // hash digest calculated by SHA template
        assert_true(zk_digest == eval_digest);

    } else {
        // hash digest specified as ASCII hex string
        vector<uint8_t> v;
        if (!asciiHexToVector(hashDig, v)) {
            ok = false;

        } else {
            // check that hash digest is correct size
            const size_t N = sizeof(typename EVAL_SHA::DigType);
            if (v.size() != N) {
                ok = false;
                cout << "error: hash digest " << hashDig
                     << " must be for " << N << " octets"
                     << endl;

            } else {
                DataBufferStream digBuf(v);

                typename ZK_SHA::DigType dig;
                bless(dig, digBuf);

                assert_true(zk_digest == dig);
            }
        }
    }

    if (!hashOnly) cout << "digest ";
    cout << asciiHex(eval_digest, !hashOnly) << endl;

    return ok;
}

template <typename PAIRING>
bool runTest(const string& shaBits,
             const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    reset<PAIRING>();

    bool valueOK = false;
    typedef typename PAIRING::Fr FR;

    if ("1" == shaBits) {
        valueOK = runTest<zk::SHA1<FR>, eval::SHA1>(stdInput, hashOnly,
                                                    hashDig, eqPattern, neqPattern);
    } else if ("224" == shaBits) {
        valueOK = runTest<zk::SHA224<FR>, eval::SHA224>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("256" == shaBits) {
        valueOK = runTest<zk::SHA256<FR>, eval::SHA256>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("384" == shaBits) {
        valueOK = runTest<zk::SHA384<FR>, eval::SHA384>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512" == shaBits) {
        valueOK = runTest<zk::SHA512<FR>, eval::SHA512>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512_224" == shaBits) {
        valueOK = runTest<zk::SHA512_224<FR>, eval::SHA512_224>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    } else if ("512_256" == shaBits) {
        valueOK = runTest<zk::SHA512_256<FR>, eval::SHA512_256>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    }

    // special case for hash only, skip zero knowledge proof
    if (hashOnly) return valueOK;

    cout << "variable count " << variable_count<PAIRING>() << endl;

    GenericProgressBar progress1(cerr), progress2(cerr, 50);

    cerr << "generate key pair";
    const auto key = keypair<PAIRING>(progress2);
    cerr << endl;

    const auto in = input<PAIRING>();

    cerr << "generate proof";
    const auto p = proof(key, progress2);
    cerr << endl;

    cerr << "verify proof ";
    const bool proofOK = verify(key, in, p, progress1);
    cerr << endl;

    return valueOK && proofOK;
}

int main(int argc, char *argv[])
{
    Getopt cmdLine(argc, argv, "pbden", "", "r");
    if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);

    auto pairing = cmdLine.getString('p');

    const auto
        shaBits = cmdLine.getString('b'),
        hashDig = cmdLine.getString('d'),
        eqPattern = cmdLine.getString('e'),
        neqPattern = cmdLine.getString('n');

    const auto stdInput = !cmdLine.getFlag('r');

    // special case for hash only, skip zero knowledge proof
    const bool hashOnly = pairing.empty() && validSHA2Name(shaBits) && stdInput;
    if (hashOnly) pairing = "BN128"; // elliptic curve pairing is arbitrary

    if (!validPairingName(pairing) || !validSHA2Name(shaBits))
        printUsage(argv[0]);

    bool result;

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        result = runTest<BN128_PAIRING>(shaBits,
                                        stdInput,
                                        hashOnly,
                                        hashDig,
                                        eqPattern,
                                        neqPattern);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        result = runTest<EDWARDS_PAIRING>(shaBits,
                                          stdInput,
                                          hashOnly,
                                          hashDig,
                                          eqPattern,
                                          neqPattern);
    }

    if (!hashOnly) {
        cout << "test " << (result ? "passed" : "failed") << endl;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*!
*	@file	psalm.cpp
*	@brief	Main file for "psalm"
*
*	"psalm" (Pretty Subdivision ALgorithms on Meshes) is a CLI tool that
*	implements the Doo-Sabin and Catmull-Clark subdivision schemes.
*/

#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>

#include <unistd.h>
#include <getopt.h>
#include <libgen.h>

#include "mesh.h"

using namespace std;

mesh scene_mesh;
string input;
string output;

/*!
*	Shows usage information for the program.
*/

void show_usage()
{
	cout	<< "psalm\n\n"
		<< "Usage: psalm [arguments] [file...]\n\n"
		<< "Arguments:\n\n"
		<< "-a, --algorithm <algorithm>\tSelect subdivision algorithm to use on the\n"
		<< "\t\t\t\tinput mesh. Valid values for <algorithm> are:\n\n"
		<< "\t\t\t\t\t* catmull-clark, catmull, clark, cc\n"
		<< "\t\t\t\t\t* doo-sabin, doo, sabin, ds\n"
		<< "\t\t\t\t\t* loop, l\n\n"
		<< "\t\t\t\tDefault algorithm: Catmull-Clark\n\n"
		<< "-t, --type <type>\t\tSelect type of input data. Valid values for\n"
		<< "\t\t\t\tthe <type> parameter are:\n\n"
		<< "\t\t\t\t\t* ply (Standford PLY files)\n"
		<< "\t\t\t\t\t* obj (Wavefront OBJ files)\n"
		<< "\t\t\t\t\t* off (Geomview object files)\n\n"
		<< "-i, --ignore <list of numbers>\tIgnore any face whose number of sides matches\n"
		<< "\t\t\t\tone of the numbers in the list. Use commas to\n"
		<< "\t\t\t\tseparate list values.\n\n"
		<< "-o, --output <file>\t\tSet output file\n\n"
		<< "-n, --steps <n>\t\t\tSet number of subdivision steps to perform on\n"
		<< "\t\t\t\tthe input mesh.\n\n"
		<< "\t\t\t\tDefault value: 0\n\n"
		<< "-h, --help\t\t\tShow this screen\n"
		<< "\n";
}

/*!
*	Handles user interaction.
*
*	@param argc Number of command-line arguments
*	@param argv Vector of command-line arguments
*/

int main(int argc, char* argv[])
{
	static option cmd_line_opts[] =
	{
		{"output",	required_argument,	NULL,	'o'},
		{"steps",	required_argument,	NULL,	'n'},
		{"type",	required_argument,	NULL,	't'},
		{"ignore",	required_argument,	NULL,	'i'},
		{"algorithm",	required_argument,	NULL,	'a'},

		{"help",	no_argument,		NULL,	'h'},

		{NULL, 0, NULL, 0}
	};

	short type	= mesh::TYPE_EXT;
	short algorithm	= mesh::ALG_CATMULL_CLARK;

	std::set<size_t> ignore_faces;

	size_t steps	= 0;

	int option = 0;
	while((option = getopt_long(argc, argv, "o:n:i:t:a:h", cmd_line_opts, NULL)) != -1)
	{
		switch(option)
		{
			case 'o':
				output = optarg;
				break;

			case 't':
			{
				string type_str = optarg;
				transform(type_str.begin(), type_str.end(), type_str.begin(), (int(*)(int)) tolower);

				if(type_str == "ply")
					type = mesh::TYPE_PLY;
				else if(type_str == "obj")
					type = mesh::TYPE_OBJ;
				else if(type_str == "off")
					type = mesh::TYPE_OFF;
				else
				{
					cerr << "Error: \"" << type_str << "\" is an unknown mesh data type.\n";
					show_usage();
					return(-1);
				}

				break;
			}

			case 'a':
			{
				string algorithm_str = optarg;
				transform(algorithm_str.begin(), algorithm_str.end(), algorithm_str.begin(), (int(*)(int)) tolower);

				if(	algorithm_str == "catmull-clark"	||
					algorithm_str == "catmull"		||
					algorithm_str == "clark"		||
					algorithm_str == "cc")
					algorithm = mesh::ALG_CATMULL_CLARK;
				else if(algorithm_str == "doo-sabin"		||
					algorithm_str == "doo"			||
					algorithm_str == "sabin"		||
					algorithm_str == "ds")
					algorithm = mesh::ALG_DOO_SABIN;
				else if(algorithm_str == "loop"	||
					algorithm_str == "l")
					algorithm = mesh::ALG_LOOP;
				else
				{
					cerr << "Error: \"" << algorithm_str << "\" is an unknown algorithm.\n";
					show_usage();
					return(-1);
				}

				break;
			}

			case 'i':
			{
				std::istringstream ignore_faces_str(optarg);
				std::istringstream converter;
				std::string val_str;
				while(getline(ignore_faces_str, val_str, ','))
				{
					converter.clear();
					converter.str(val_str);

					size_t value;
					converter >> value;
					if(converter.fail())
					{
						show_usage();
						cerr << "psalm: Unable to convert \"" << val_str << "\" to a number.\n";
						return(-1);
					}

					ignore_faces.insert(value);
				}

				break;
			}

			case 'n':
			{
				istringstream converter(optarg);
				converter >> steps;
				if(converter.fail())
				{
					cerr << "Error: Unable to  convert \"" << optarg << "\" to a number.\n";
					show_usage();
					return(-1);
				}
				break;
			}

			case 'h':
			case '?':
				show_usage();
				return(0);
		}
	}

	// Read further command-line parameters; these are all supposed to be
	// input files. If the user already specified an output file, only one
	// input file will be accepted.

	vector<string> files;
	while(optind < argc)
	{
		files.push_back(argv[optind++]);
		if(output.length() != 0 && files.size() > 1)
		{
			cerr << "Error: Output file specified, but more than one input file present.\n";
			return(-1);
		}
	}

	// Replace the special file "-" by an empty string, thereby signalling
	// that standard input and standard output are to be used as file
	// streams.

	for(vector<string>::iterator it = files.begin(); it != files.end(); it++)
	{
		if(it->length() == 1 && (*it)[0] == '-')
			*it = "";
	}

	bool output_set = (output.length() > 0);
	if(output.length() == 1 && output[0] == '-')
		output = "";

	// Try to read from STDIN if no input files have been specified
	if(files.size() == 0)
		files.push_back("");

	// Apply subdivision algorithm to all files

	for(vector<string>::iterator it = files.begin(); it != files.end(); it++)
	{
		scene_mesh.load(*it, type);
		scene_mesh.subdivide(algorithm, steps);
		scene_mesh.prune(ignore_faces);

		// If an output file has been set (even if it is empty), it
		// will be used.
		if(output_set)
			scene_mesh.save(output, type);

		// If no output file has been set and the input file name is
		// not empty, the output will be written to a file.
		else if(it->length() > 0)
		{
			size_t ext_pos = (*it).find_last_of(".");
			if(ext_pos == string::npos)
				scene_mesh.save(*it+".subdivided", type);
			else
				scene_mesh.save( (*it).substr(0, ext_pos) + "_subdivided"
						+(*it).substr(ext_pos));
		}

		// If no output file has been set and the input file name is
		// empty, the output will be written to STDOUT.
		else
			scene_mesh.save("", type);
	}

	return(0);
}
<commit_msg>Removed usage information in case of errors<commit_after>/*!
*	@file	psalm.cpp
*	@brief	Main file for "psalm"
*
*	"psalm" (Pretty Subdivision ALgorithms on Meshes) is a CLI tool that
*	implements the Doo-Sabin and Catmull-Clark subdivision schemes.
*/

#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>

#include <unistd.h>
#include <getopt.h>
#include <libgen.h>

#include "mesh.h"

using namespace std;

mesh scene_mesh;
string input;
string output;

/*!
*	Shows usage information for the program.
*/

void show_usage()
{
	cout	<< "psalm\n\n"
		<< "Usage: psalm [arguments] [file...]\n\n"
		<< "Arguments:\n\n"
		<< "-a, --algorithm <algorithm>\tSelect subdivision algorithm to use on the\n"
		<< "\t\t\t\tinput mesh. Valid values for <algorithm> are:\n\n"
		<< "\t\t\t\t\t* catmull-clark, catmull, clark, cc\n"
		<< "\t\t\t\t\t* doo-sabin, doo, sabin, ds\n"
		<< "\t\t\t\t\t* loop, l\n\n"
		<< "\t\t\t\tDefault algorithm: Catmull-Clark\n\n"
		<< "-t, --type <type>\t\tSelect type of input data. Valid values for\n"
		<< "\t\t\t\tthe <type> parameter are:\n\n"
		<< "\t\t\t\t\t* ply (Standford PLY files)\n"
		<< "\t\t\t\t\t* obj (Wavefront OBJ files)\n"
		<< "\t\t\t\t\t* off (Geomview object files)\n\n"
		<< "-i, --ignore <list of numbers>\tIgnore any face whose number of sides matches\n"
		<< "\t\t\t\tone of the numbers in the list. Use commas to\n"
		<< "\t\t\t\tseparate list values.\n\n"
		<< "-o, --output <file>\t\tSet output file\n\n"
		<< "-n, --steps <n>\t\t\tSet number of subdivision steps to perform on\n"
		<< "\t\t\t\tthe input mesh.\n\n"
		<< "\t\t\t\tDefault value: 0\n\n"
		<< "-h, --help\t\t\tShow this screen\n"
		<< "\n";
}

/*!
*	Handles user interaction.
*
*	@param argc Number of command-line arguments
*	@param argv Vector of command-line arguments
*/

int main(int argc, char* argv[])
{
	static option cmd_line_opts[] =
	{
		{"output",	required_argument,	NULL,	'o'},
		{"steps",	required_argument,	NULL,	'n'},
		{"type",	required_argument,	NULL,	't'},
		{"ignore",	required_argument,	NULL,	'i'},
		{"algorithm",	required_argument,	NULL,	'a'},

		{"help",	no_argument,		NULL,	'h'},

		{NULL, 0, NULL, 0}
	};

	short type	= mesh::TYPE_EXT;
	short algorithm	= mesh::ALG_CATMULL_CLARK;

	std::set<size_t> ignore_faces;

	size_t steps	= 0;

	int option = 0;
	while((option = getopt_long(argc, argv, "o:n:i:t:a:h", cmd_line_opts, NULL)) != -1)
	{
		switch(option)
		{
			case 'o':
				output = optarg;
				break;

			case 't':
			{
				string type_str = optarg;
				transform(type_str.begin(), type_str.end(), type_str.begin(), (int(*)(int)) tolower);

				if(type_str == "ply")
					type = mesh::TYPE_PLY;
				else if(type_str == "obj")
					type = mesh::TYPE_OBJ;
				else if(type_str == "off")
					type = mesh::TYPE_OFF;
				else
				{
					cerr << "psalm: \"" << type_str << "\" is an unknown mesh data type.\n";
					return(-1);
				}

				break;
			}

			case 'a':
			{
				string algorithm_str = optarg;
				transform(algorithm_str.begin(), algorithm_str.end(), algorithm_str.begin(), (int(*)(int)) tolower);

				if(	algorithm_str == "catmull-clark"	||
					algorithm_str == "catmull"		||
					algorithm_str == "clark"		||
					algorithm_str == "cc")
					algorithm = mesh::ALG_CATMULL_CLARK;
				else if(algorithm_str == "doo-sabin"		||
					algorithm_str == "doo"			||
					algorithm_str == "sabin"		||
					algorithm_str == "ds")
					algorithm = mesh::ALG_DOO_SABIN;
				else if(algorithm_str == "loop"	||
					algorithm_str == "l")
					algorithm = mesh::ALG_LOOP;
				else
				{
					cerr << "psalm: \"" << algorithm_str << "\" is an unknown algorithm.\n";
					return(-1);
				}

				break;
			}

			case 'i':
			{
				std::istringstream ignore_faces_str(optarg);
				std::istringstream converter;
				std::string val_str;
				while(getline(ignore_faces_str, val_str, ','))
				{
					converter.clear();
					converter.str(val_str);

					size_t value;
					converter >> value;
					if(converter.fail())
					{
						cerr << "psalm: Unable to convert \"" << val_str << "\" to a number.\n";
						return(-1);
					}

					ignore_faces.insert(value);
				}

				break;
			}

			case 'n':
			{
				istringstream converter(optarg);
				converter >> steps;
				if(converter.fail())
				{
					cerr << "psalm: Unable to  convert \"" << optarg << "\" to a number.\n";
					return(-1);
				}
				break;
			}

			case 'h':
			case '?':
				show_usage();
				return(0);
		}
	}

	// Read further command-line parameters; these are all supposed to be
	// input files. If the user already specified an output file, only one
	// input file will be accepted.

	vector<string> files;
	while(optind < argc)
	{
		files.push_back(argv[optind++]);
		if(output.length() != 0 && files.size() > 1)
		{
			cerr << "psalm: Output file specified, but more than one input file present.\n";
			return(-1);
		}
	}

	// Replace the special file "-" by an empty string, thereby signalling
	// that standard input and standard output are to be used as file
	// streams.

	for(vector<string>::iterator it = files.begin(); it != files.end(); it++)
	{
		if(it->length() == 1 && (*it)[0] == '-')
			*it = "";
	}

	bool output_set = (output.length() > 0);
	if(output.length() == 1 && output[0] == '-')
		output = "";

	// Try to read from STDIN if no input files have been specified
	if(files.size() == 0)
		files.push_back("");

	// Apply subdivision algorithm to all files

	for(vector<string>::iterator it = files.begin(); it != files.end(); it++)
	{
		scene_mesh.load(*it, type);
		scene_mesh.subdivide(algorithm, steps);
		scene_mesh.prune(ignore_faces);

		// If an output file has been set (even if it is empty), it
		// will be used.
		if(output_set)
			scene_mesh.save(output, type);

		// If no output file has been set and the input file name is
		// not empty, the output will be written to a file.
		else if(it->length() > 0)
		{
			size_t ext_pos = (*it).find_last_of(".");
			if(ext_pos == string::npos)
				scene_mesh.save(*it+".subdivided", type);
			else
				scene_mesh.save( (*it).substr(0, ext_pos) + "_subdivided"
						+(*it).substr(ext_pos));
		}

		// If no output file has been set and the input file name is
		// empty, the output will be written to STDOUT.
		else
			scene_mesh.save("", type);
	}

	return(0);
}
<|endoftext|>