<commit_before>#include "EdgesSubPix.h"
#include <cmath>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

static void getCannyKernel(OutputArray _d, double alpha)
{
    int r = cvRound(alpha * 3);
    int ksize = 2 * r + 1;

    _d.create(ksize, 1, CV_16S, -1, true);

    Mat k = _d.getMat();

    vector<float> kerF(ksize, 0.0f);
    kerF[r] = 0.0f;
    double a2 = alpha * alpha;
    float sum = 0.0f;
    for (int x = 1; x <= r; ++x)
    {
        float v = (float)(-x * std::exp(-x * x / (2 * a2)));
        sum += v;
        kerF[r + x] = v;
        kerF[r - x] = -v;
    }
    float scale = 128 / sum;
    for (int i = 0; i < ksize; ++i)
    {
        kerF[i] *= scale;
    }
    Mat temp(ksize, 1, CV_32F, &kerF[0]);
    temp.convertTo(k, CV_16S);
}

// non-maximum supression and hysteresis
static void postCannyFilter(const Mat &src, Mat &dx, Mat &dy, int low, int high, Mat &dst)
{
    ptrdiff_t mapstep = src.cols + 2;
    AutoBuffer<uchar> buffer((src.cols + 2)*(src.rows + 2) + mapstep * 3 * sizeof(int));

    // L2Gradient comparison with square
    high = high * high;
    low = low * low;

    int* mag_buf[3];
    mag_buf[0] = (int*)(uchar*)buffer;
    mag_buf[1] = mag_buf[0] + mapstep;
    mag_buf[2] = mag_buf[1] + mapstep;
    memset(mag_buf[0], 0, /* cn* */mapstep*sizeof(int));

    uchar* map = (uchar*)(mag_buf[2] + mapstep);
    memset(map, 1, mapstep);
    memset(map + mapstep*(src.rows + 1), 1, mapstep);

    int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
    std::vector<uchar*> stack(maxsize);
    uchar **stack_top = &stack[0];
    uchar **stack_bottom = &stack[0];

    /* sector numbers
    (Top-Left Origin)

    1   2   3
    *  *  *
    * * *
    0*******0
    * * *
    *  *  *
    3   2   1
    */

#define CANNY_PUSH(d)    *(d) = uchar(2), *stack_top++ = (d)
#define CANNY_POP(d)     (d) = *--stack_top

#if CV_SSE2
    bool haveSSE2 = checkHardwareSupport(CV_CPU_SSE2);
#endif

    // calculate magnitude and angle of gradient, perform non-maxima suppression.
    // fill the map with one of the following values:
    //   0 - the pixel might belong to an edge
    //   1 - the pixel can not belong to an edge
    //   2 - the pixel does belong to an edge
    for (int i = 0; i <= src.rows; i++)
    {
        int* _norm = mag_buf[(i > 0) + 1] + 1;
        if (i < src.rows)
        {
            short* _dx = dx.ptr<short>(i);
            short* _dy = dy.ptr<short>(i);

            int j = 0, width = src.cols;
#if CV_SSE2
            if (haveSSE2)
            {
                for (; j <= width - 8; j += 8)
                {
                    __m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j));
                    __m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j));

                    __m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx);
                    __m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy);

                    __m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh));
                    _mm_storeu_si128((__m128i *)(_norm + j), v_norm);

                    v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh));
                    _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm);
                }
            }
#elif CV_NEON
            for (; j <= width - 8; j += 8)
            {
                int16x8_t v_dx = vld1q_s16(_dx + j), v_dy = vld1q_s16(_dy + j);
                int16x4_t v_dxp = vget_low_s16(v_dx), v_dyp = vget_low_s16(v_dy);
                int32x4_t v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
                vst1q_s32(_norm + j, v_dst);

                v_dxp = vget_high_s16(v_dx), v_dyp = vget_high_s16(v_dy);
                v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
                vst1q_s32(_norm + j + 4, v_dst);
            }
#endif
            for (; j < width; ++j)
                _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];

            _norm[-1] = _norm[src.cols] = 0;
        }
        else
            memset(_norm - 1, 0, /* cn* */mapstep*sizeof(int));

        // at the very beginning we do not have a complete ring
        // buffer of 3 magnitude rows for non-maxima suppression
        if (i == 0)
            continue;

        uchar* _map = map + mapstep*i + 1;
        _map[-1] = _map[src.cols] = 1;

        int* _mag = mag_buf[1] + 1; // take the central row
        ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
        ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];

        const short* _x = dx.ptr<short>(i - 1);
        const short* _y = dy.ptr<short>(i - 1);

        if ((stack_top - stack_bottom) + src.cols > maxsize)
        {
            int sz = (int)(stack_top - stack_bottom);
            maxsize = std::max(maxsize * 3 / 2, sz + src.cols);
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        int prev_flag = 0;
        for (int j = 0; j < src.cols; j++)
        {
#define CANNY_SHIFT 15
            const int TG22 = (int)(0.4142135623730950488016887242097*(1 << CANNY_SHIFT) + 0.5);

            int m = _mag[j];

            if (m > low)
            {
                int xs = _x[j];
                int ys = _y[j];
                int x = std::abs(xs);
                int y = std::abs(ys) << CANNY_SHIFT;

                int tg22x = x * TG22;

                if (y < tg22x)
                {
                    if (m > _mag[j - 1] && m >= _mag[j + 1]) goto __ocv_canny_push;
                }
                else
                {
                    int tg67x = tg22x + (x << (CANNY_SHIFT + 1));
                    if (y > tg67x)
                    {
                        if (m > _mag[j + magstep2] && m >= _mag[j + magstep1]) goto __ocv_canny_push;
                    }
                    else
                    {
                        int s = (xs ^ ys) < 0 ? -1 : 1;
                        if (m > _mag[j + magstep2 - s] && m > _mag[j + magstep1 + s]) goto __ocv_canny_push;
                    }
                }
            }
            prev_flag = 0;
            _map[j] = uchar(1);
            continue;
        __ocv_canny_push:
            if (!prev_flag && m > high && _map[j - mapstep] != 2)
            {
                CANNY_PUSH(_map + j);
                prev_flag = 1;
            }
            else
                _map[j] = 0;
        }

        // scroll the ring buffer
        _mag = mag_buf[0];
        mag_buf[0] = mag_buf[1];
        mag_buf[1] = mag_buf[2];
        mag_buf[2] = _mag;
    }

    // now track the edges (hysteresis thresholding)
    while (stack_top > stack_bottom)
    {
        uchar* m;
        if ((stack_top - stack_bottom) + 8 > maxsize)
        {
            int sz = (int)(stack_top - stack_bottom);
            maxsize = maxsize * 3 / 2;
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        CANNY_POP(m);

        if (!m[-1])         CANNY_PUSH(m - 1);
        if (!m[1])          CANNY_PUSH(m + 1);
        if (!m[-mapstep - 1]) CANNY_PUSH(m - mapstep - 1);
        if (!m[-mapstep])   CANNY_PUSH(m - mapstep);
        if (!m[-mapstep + 1]) CANNY_PUSH(m - mapstep + 1);
        if (!m[mapstep - 1])  CANNY_PUSH(m + mapstep - 1);
        if (!m[mapstep])    CANNY_PUSH(m + mapstep);
        if (!m[mapstep + 1])  CANNY_PUSH(m + mapstep + 1);
    }

    // the final pass, form the final image
    const uchar* pmap = map + mapstep + 1;
    uchar* pdst = dst.ptr();
    for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
    {
        for (int j = 0; j < src.cols; j++)
            pdst[j] = (uchar)-(pmap[j] >> 1);
    }
}

//---------------------------------------------------------------------
//          INTERFACE FUNCTION
//---------------------------------------------------------------------
void EdgesSubPix(Mat &gray, double alpha, int low, int high,
    vector<Contour> &contours, OutputArray hierarchy,
    int mode, Point2f offset)
{
    Mat blur;
    GaussianBlur(gray, blur, Size(0, 0), alpha, alpha);

    Mat d;
    getCannyKernel(d, alpha);
    Mat one = Mat::ones(Size(1, 1), CV_16S);
    Mat dx, dy;
    sepFilter2D(blur, dx, CV_16S, d, one);
    sepFilter2D(blur, dy, CV_16S, one, d);

    // non-maximum supression & hysteresis threshold
    Mat edge = Mat::zeros(gray.size(), CV_8UC1);
    double scale = 128.0;                          // sum of half Canny filter is 128
    int lowThresh = cvRound(scale * low);
    int highThresh = cvRound(scale * high);
    postCannyFilter(gray, dx, dy, lowThresh, highThresh, edge);
}

void EdgesSubPix(Mat &gray, double alpha, int low, int high,
    vector<Contour> &contours, Point2f offset)
{
    vector<Vec4i> hierarchy;
    EdgesSubPix(gray, alpha, low, high, contours, hierarchy, RETR_LIST);
}
<commit_msg>some text formating<commit_after>#include "EdgesSubPix.h"
#include <cmath>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

static void getCannyKernel(OutputArray _d, double alpha)
{
    int r = cvRound(alpha * 3);
    int ksize = 2 * r + 1;

    _d.create(ksize, 1, CV_16S, -1, true);

    Mat k = _d.getMat();

    vector<float> kerF(ksize, 0.0f);
    kerF[r] = 0.0f;
    double a2 = alpha * alpha;
    float sum = 0.0f;
    for (int x = 1; x <= r; ++x)
    {
        float v = (float)(-x * std::exp(-x * x / (2 * a2)));
        sum += v;
        kerF[r + x] = v;
        kerF[r - x] = -v;
    }
    float scale = 128 / sum;
    for (int i = 0; i < ksize; ++i)
    {
        kerF[i] *= scale;
    }
    Mat temp(ksize, 1, CV_32F, &kerF[0]);
    temp.convertTo(k, CV_16S);
}

// non-maximum supression and hysteresis
static void postCannyFilter(const Mat &src, Mat &dx, Mat &dy, int low, int high, Mat &dst)
{
    ptrdiff_t mapstep = src.cols + 2;
    AutoBuffer<uchar> buffer((src.cols + 2)*(src.rows + 2) + mapstep * 3 * sizeof(int));

    // L2Gradient comparison with square
    high = high * high;
    low = low * low;

    int* mag_buf[3];
    mag_buf[0] = (int*)(uchar*)buffer;
    mag_buf[1] = mag_buf[0] + mapstep;
    mag_buf[2] = mag_buf[1] + mapstep;
    memset(mag_buf[0], 0, mapstep*sizeof(int));

    uchar* map = (uchar*)(mag_buf[2] + mapstep);
    memset(map, 1, mapstep);
    memset(map + mapstep*(src.rows + 1), 1, mapstep);

    int maxsize = std::max(1 << 10, src.cols * src.rows / 10);
    std::vector<uchar*> stack(maxsize);
    uchar **stack_top = &stack[0];
    uchar **stack_bottom = &stack[0];

    /* sector numbers
    (Top-Left Origin)

    1   2   3
    *  *  *
    * * *
    0*******0
    * * *
    *  *  *
    3   2   1
    */

#define CANNY_PUSH(d)    *(d) = uchar(2), *stack_top++ = (d)
#define CANNY_POP(d)     (d) = *--stack_top

#if CV_SSE2
    bool haveSSE2 = checkHardwareSupport(CV_CPU_SSE2);
#endif

    // calculate magnitude and angle of gradient, perform non-maxima suppression.
    // fill the map with one of the following values:
    //   0 - the pixel might belong to an edge
    //   1 - the pixel can not belong to an edge
    //   2 - the pixel does belong to an edge
    for (int i = 0; i <= src.rows; i++)
    {
        int* _norm = mag_buf[(i > 0) + 1] + 1;
        if (i < src.rows)
        {
            short* _dx = dx.ptr<short>(i);
            short* _dy = dy.ptr<short>(i);

            int j = 0, width = src.cols;
#if CV_SSE2
            if (haveSSE2)
            {
                for (; j <= width - 8; j += 8)
                {
                    __m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j));
                    __m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j));

                    __m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx);
                    __m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy);

                    __m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh));
                    _mm_storeu_si128((__m128i *)(_norm + j), v_norm);

                    v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh));
                    _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm);
                }
            }
#elif CV_NEON
            for (; j <= width - 8; j += 8)
            {
                int16x8_t v_dx = vld1q_s16(_dx + j), v_dy = vld1q_s16(_dy + j);
                int16x4_t v_dxp = vget_low_s16(v_dx), v_dyp = vget_low_s16(v_dy);
                int32x4_t v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
                vst1q_s32(_norm + j, v_dst);

                v_dxp = vget_high_s16(v_dx), v_dyp = vget_high_s16(v_dy);
                v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);
                vst1q_s32(_norm + j + 4, v_dst);
            }
#endif
            for (; j < width; ++j)
                _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];

            _norm[-1] = _norm[src.cols] = 0;
        }
        else
            memset(_norm - 1, 0, /* cn* */mapstep*sizeof(int));

        // at the very beginning we do not have a complete ring
        // buffer of 3 magnitude rows for non-maxima suppression
        if (i == 0)
            continue;

        uchar* _map = map + mapstep*i + 1;
        _map[-1] = _map[src.cols] = 1;

        int* _mag = mag_buf[1] + 1; // take the central row
        ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];
        ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];

        const short* _x = dx.ptr<short>(i - 1);
        const short* _y = dy.ptr<short>(i - 1);

        if ((stack_top - stack_bottom) + src.cols > maxsize)
        {
            int sz = (int)(stack_top - stack_bottom);
            maxsize = std::max(maxsize * 3 / 2, sz + src.cols);
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        int prev_flag = 0;
        for (int j = 0; j < src.cols; j++)
        {
            #define CANNY_SHIFT 15
            const int TG22 = (int)(0.4142135623730950488016887242097*(1 << CANNY_SHIFT) + 0.5);

            int m = _mag[j];

            if (m > low)
            {
                int xs = _x[j];
                int ys = _y[j];
                int x = std::abs(xs);
                int y = std::abs(ys) << CANNY_SHIFT;

                int tg22x = x * TG22;

                if (y < tg22x)
                {
                    if (m > _mag[j - 1] && m >= _mag[j + 1]) goto __ocv_canny_push;
                }
                else
                {
                    int tg67x = tg22x + (x << (CANNY_SHIFT + 1));
                    if (y > tg67x)
                    {
                        if (m > _mag[j + magstep2] && m >= _mag[j + magstep1]) goto __ocv_canny_push;
                    }
                    else
                    {
                        int s = (xs ^ ys) < 0 ? -1 : 1;
                        if (m > _mag[j + magstep2 - s] && m > _mag[j + magstep1 + s]) goto __ocv_canny_push;
                    }
                }
            }
            prev_flag = 0;
            _map[j] = uchar(1);
            continue;
        __ocv_canny_push:
            if (!prev_flag && m > high && _map[j - mapstep] != 2)
            {
                CANNY_PUSH(_map + j);
                prev_flag = 1;
            }
            else
                _map[j] = 0;
        }

        // scroll the ring buffer
        _mag = mag_buf[0];
        mag_buf[0] = mag_buf[1];
        mag_buf[1] = mag_buf[2];
        mag_buf[2] = _mag;
    }

    // now track the edges (hysteresis thresholding)
    while (stack_top > stack_bottom)
    {
        uchar* m;
        if ((stack_top - stack_bottom) + 8 > maxsize)
        {
            int sz = (int)(stack_top - stack_bottom);
            maxsize = maxsize * 3 / 2;
            stack.resize(maxsize);
            stack_bottom = &stack[0];
            stack_top = stack_bottom + sz;
        }

        CANNY_POP(m);

        if (!m[-1])         CANNY_PUSH(m - 1);
        if (!m[1])          CANNY_PUSH(m + 1);
        if (!m[-mapstep - 1]) CANNY_PUSH(m - mapstep - 1);
        if (!m[-mapstep])   CANNY_PUSH(m - mapstep);
        if (!m[-mapstep + 1]) CANNY_PUSH(m - mapstep + 1);
        if (!m[mapstep - 1])  CANNY_PUSH(m + mapstep - 1);
        if (!m[mapstep])    CANNY_PUSH(m + mapstep);
        if (!m[mapstep + 1])  CANNY_PUSH(m + mapstep + 1);
    }

    // the final pass, form the final image
    const uchar* pmap = map + mapstep + 1;
    uchar* pdst = dst.ptr();
    for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)
    {
        for (int j = 0; j < src.cols; j++)
            pdst[j] = (uchar)-(pmap[j] >> 1);
    }
}

//---------------------------------------------------------------------
//          INTERFACE FUNCTION
//---------------------------------------------------------------------
void EdgesSubPix(Mat &gray, double alpha, int low, int high,
    vector<Contour> &contours, OutputArray hierarchy,
    int mode, Point2f offset)
{
    Mat blur;
    GaussianBlur(gray, blur, Size(0, 0), alpha, alpha);

    Mat d;
    getCannyKernel(d, alpha);
    Mat one = Mat::ones(Size(1, 1), CV_16S);
    Mat dx, dy;
    sepFilter2D(blur, dx, CV_16S, d, one);
    sepFilter2D(blur, dy, CV_16S, one, d);

    // non-maximum supression & hysteresis threshold
    Mat edge = Mat::zeros(gray.size(), CV_8UC1);
    double scale = 128.0;                          // sum of half Canny filter is 128
    int lowThresh = cvRound(scale * low);
    int highThresh = cvRound(scale * high);
    postCannyFilter(gray, dx, dy, lowThresh, highThresh, edge);
}

void EdgesSubPix(Mat &gray, double alpha, int low, int high,
    vector<Contour> &contours, Point2f offset)
{
    vector<Vec4i> hierarchy;
    EdgesSubPix(gray, alpha, low, high, contours, hierarchy, RETR_LIST);
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkSpatialObjectToImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkEllipseSpatialObject.h"
#include <itkSpatialObjectToImageFilter.h>

int itkSpatialObjectToImageFilterTest(int, char* [] )
{
  typedef itk::EllipseSpatialObject<2>   EllipseType;

  EllipseType::Pointer ellipse = EllipseType::New();
  ellipse->SetRadius(10);

  // Center the circle in the image
  EllipseType::TransformType::OffsetType offset;
  offset.Fill(25);
  ellipse->GetObjectToParentTransform()->SetOffset(offset);
  ellipse->ComputeObjectToWorldTransform();

  typedef itk::Image<double,2> ImageType;

  typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> SpatialObjectToImageFilterType;
  SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
  imageFilter->SetInput(ellipse);
  imageFilter->SetInsideValue(1);
  imageFilter->SetOutsideValue(0);
  ImageType::SizeType size;
  size[0]=50;
  size[1]=50;
  imageFilter->SetSize(size);

  // Testing spacing
  std::cout << "Testing Spacing: ";

  float spacing_float[2];
  double spacing_double[2];

  for(unsigned int i=0;i<2;i++)
  {
    spacing_float[i]=1.0;
    spacing_double[i]=1.0;
  }
  imageFilter->SetSpacing(spacing_float);
  imageFilter->SetSpacing(spacing_double);
  const double* spacing_result = imageFilter->GetSpacing();

  for(unsigned int i=0;i<2;i++)
  {
    if(spacing_result[i]!=1.0)
    {
      std::cout << "[FAILURE]" << std::endl;
      return EXIT_FAILURE;
    }
  }

  std::cout << "[PASSED]" << std::endl;

  // Testing Origin
  std::cout << "Testing Origin: ";

  float origin_float[2];
  double origin_double[2];

  for(unsigned int i=0;i<2;i++)
  {
    origin_float[i]=0.0;
    origin_double[i]=0.0;
  }
  imageFilter->SetOrigin(origin_float);
  imageFilter->SetOrigin(origin_double);
  const double* origin_result = imageFilter->GetOrigin();

  for(unsigned int i=0;i<2;i++)
  {
    if(origin_result[i]!=0.0)
    {
      std::cout << "[FAILURE]" << std::endl;
      return EXIT_FAILURE;
    }
  }

  std::cout << "[PASSED]" << std::endl;

  // Testing PrintSelf
  std::cout << imageFilter << std::endl;

  //Update the filter
  imageFilter->Update();

  ImageType::Pointer image = imageFilter->GetOutput();

  std::cout << "Testing Output Image: ";

  ImageType::IndexType index;
  // Test only centered pixels
  for(int i=-5;i<5;i++)
  {
    for(int j=-5;j<5;j++)
    {
      index[0] = 25+i;
      index[1] = 25+j;

      if(image->GetPixel(index) != 1.0)
      {
        std::cout << "[FAILURE]" << std::endl;
        return EXIT_FAILURE;
      }
    }
  }

  std::cout << "[PASSED]" << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>ENH: improve coverage<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkSpatialObjectToImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkEllipseSpatialObject.h"
#include <itkSpatialObjectToImageFilter.h>

int itkSpatialObjectToImageFilterTest(int, char* [] )
{
  typedef itk::EllipseSpatialObject<2>   EllipseType;

  EllipseType::Pointer ellipse = EllipseType::New();
  ellipse->SetRadius(10);

  // Center the circle in the image
  EllipseType::TransformType::OffsetType offset;
  offset.Fill(25);
  ellipse->GetObjectToParentTransform()->SetOffset(offset);
  ellipse->ComputeObjectToWorldTransform();

  typedef itk::Image<double,2> ImageType;

  typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> SpatialObjectToImageFilterType;
  SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();
  imageFilter->SetInput(ellipse);
  imageFilter->SetInsideValue(1);
  imageFilter->GetInsideValue();
  imageFilter->SetOutsideValue(0);
  imageFilter->GetOutsideValue();
  imageFilter->SetChildrenDepth(1);
  imageFilter->GetChildrenDepth();
  ImageType::SizeType size;
  size[0]=50;
  size[1]=50;
  imageFilter->SetSize(size);

  // Testing spacing
  std::cout << "Testing Spacing: ";

  float spacing_float[2];
  double spacing_double[2];

  for(unsigned int i=0;i<2;i++)
  {
    spacing_float[i]=1.0;
    spacing_double[i]=1.0;
  }
  imageFilter->SetSpacing(spacing_float);
  imageFilter->SetSpacing(spacing_double);
  const double* spacing_result = imageFilter->GetSpacing();

  for(unsigned int i=0;i<2;i++)
  {
    if(spacing_result[i]!=1.0)
    {
      std::cout << "[FAILURE]" << std::endl;
      return EXIT_FAILURE;
    }
  }

  std::cout << "[PASSED]" << std::endl;

  // Testing Origin
  std::cout << "Testing Origin: ";

  float origin_float[2];
  double origin_double[2];

  for(unsigned int i=0;i<2;i++)
  {
    origin_float[i]=0.0;
    origin_double[i]=0.0;
  }
  imageFilter->SetOrigin(origin_float);
  imageFilter->SetOrigin(origin_double);
  const double* origin_result = imageFilter->GetOrigin();

  for(unsigned int i=0;i<2;i++)
  {
    if(origin_result[i]!=0.0)
    {
      std::cout << "[FAILURE]" << std::endl;
      return EXIT_FAILURE;
    }
  }

  std::cout << "[PASSED]" << std::endl;

  // Testing PrintSelf
  std::cout << imageFilter << std::endl;

  //Update the filter
  imageFilter->Update();

  ImageType::Pointer image = imageFilter->GetOutput();

  std::cout << "Testing Output Image: ";

  ImageType::IndexType index;
  // Test only centered pixels
  for(int i=-5;i<5;i++)
  {
    for(int j=-5;j<5;j++)
    {
      index[0] = 25+i;
      index[1] = 25+j;

      if(image->GetPixel(index) != 1.0)
      {
        std::cout << "[FAILURE]" << std::endl;
        return EXIT_FAILURE;
      }
    }
  }

  std::cout << "[PASSED]" << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <functional>

// result_of<Fn(ArgTypes...)>

#include <type_traits>
#include <memory>

typedef bool (&PF1)();
typedef short (*PF2)(long);

struct S
{
    operator PF2() const;
    double operator()(char, int&);
    void calc(long) const;
    char data_;
};

typedef void (S::*PMS)(long) const;
typedef char S::*PMD;

int main()
{
    static_assert((std::is_same<std::result_of<S(int)>::type, short>::value), "Error!");
    static_assert((std::is_same<std::result_of<S&(unsigned char, int&)>::type, double>::value), "Error!");
    static_assert((std::is_same<std::result_of<PF1()>::type, bool>::value), "Error!");
    static_assert((std::is_same<std::result_of<PMS(std::unique_ptr<S>, int)>::type, void>::value), "Error!");
    static_assert((std::is_same<std::result_of<PMS(S, int)>::type, void>::value), "Error!");
    static_assert((std::is_same<std::result_of<PMS(const S&, int)>::type, void>::value), "Error!");
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    static_assert((std::is_same<std::result_of<PMD(S)>::type, char&&>::value), "Error!");
#endif
    static_assert((std::is_same<std::result_of<PMD(const S*)>::type, const char&>::value), "Error!");
}
<commit_msg>Constrain __invoke functions more accurately.  This fixes http://llvm.org/bugs/show_bug.cgi?id=15861 .<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <functional>

// result_of<Fn(ArgTypes...)>

#include <type_traits>
#include <memory>

typedef bool (&PF1)();
typedef short (*PF2)(long);

struct S
{
    operator PF2() const;
    double operator()(char, int&);
    void calc(long) const;
    char data_;
};

typedef void (S::*PMS)(long) const;
typedef char S::*PMD;

struct wat
{
    wat& operator*() { return *this; }
    void foo();
};

int main()
{
    static_assert((std::is_same<std::result_of<S(int)>::type, short>::value), "Error!");
    static_assert((std::is_same<std::result_of<S&(unsigned char, int&)>::type, double>::value), "Error!");
    static_assert((std::is_same<std::result_of<PF1()>::type, bool>::value), "Error!");
    static_assert((std::is_same<std::result_of<PMS(std::unique_ptr<S>, int)>::type, void>::value), "Error!");
    static_assert((std::is_same<std::result_of<PMS(S, int)>::type, void>::value), "Error!");
    static_assert((std::is_same<std::result_of<PMS(const S&, int)>::type, void>::value), "Error!");
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    static_assert((std::is_same<std::result_of<PMD(S)>::type, char&&>::value), "Error!");
#endif
    static_assert((std::is_same<std::result_of<PMD(const S*)>::type, const char&>::value), "Error!");
    using type = std::result_of<decltype(&wat::foo)(wat)>::type;
}
<|endoftext|>


<commit_before>// Copyright 2013 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/browser/renderer_host/pepper/pepper_network_monitor_host.h"

#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/browser/renderer_host/pepper/pepper_socket_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/socket_permission_request.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/private/net_address_private_impl.h"

namespace content {

namespace {

bool CanUseNetworkMonitor(bool external_plugin,
                          int render_process_id,
                          int render_view_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  SocketPermissionRequest request = SocketPermissionRequest(
      SocketPermissionRequest::NETWORK_STATE, std::string(), 0);
  return pepper_socket_utils::CanUseSocketAPIs(
      external_plugin, false /* private_api */, request, render_process_id,
      render_view_id);
}

scoped_ptr<net::NetworkInterfaceList> GetNetworkList() {
  scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList());
  net::GetNetworkList(list.get());
  return list.Pass();
}

}  // namespace

PepperNetworkMonitorHost::PepperNetworkMonitorHost(
    BrowserPpapiHostImpl* host,
    PP_Instance instance,
    PP_Resource resource)
    : ResourceHost(host->GetPpapiHost(), instance, resource),
      weak_factory_(this) {
  int render_process_id;
  int render_view_id;
  host->GetRenderViewIDsForInstance(instance,
                                    &render_process_id,
                                    &render_view_id);

  BrowserThread::PostTaskAndReplyWithResult(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&CanUseNetworkMonitor, host->external_plugin(),
                 render_process_id, render_view_id),
      base::Bind(&PepperNetworkMonitorHost::OnPermissionCheckResult,
                 weak_factory_.GetWeakPtr()));
}

PepperNetworkMonitorHost::~PepperNetworkMonitorHost() {
  net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
}

void PepperNetworkMonitorHost::OnIPAddressChanged() {
  GetAndSendNetworkList();
}

void PepperNetworkMonitorHost::OnPermissionCheckResult(
    bool can_use_network_monitor) {
  if (!can_use_network_monitor) {
    host()->SendUnsolicitedReply(pp_resource(),
                                 PpapiPluginMsg_NetworkMonitor_Forbidden());
    return;
  }

  net::NetworkChangeNotifier::AddIPAddressObserver(this);
  GetAndSendNetworkList();
}

void PepperNetworkMonitorHost::GetAndSendNetworkList() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // Call GetNetworkList() on a thread that allows blocking IO.
  base::PostTaskAndReplyWithResult(
      BrowserThread::GetBlockingPool(), FROM_HERE,
      base::Bind(&GetNetworkList),
      base::Bind(&PepperNetworkMonitorHost::SendNetworkList,
                 weak_factory_.GetWeakPtr()));
}

void PepperNetworkMonitorHost::SendNetworkList(
    scoped_ptr<net::NetworkInterfaceList> list) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  scoped_ptr<ppapi::proxy::SerializedNetworkList> list_copy(
      new ppapi::proxy::SerializedNetworkList(list->size()));
  for (size_t i = 0; i < list->size(); ++i) {
    const net::NetworkInterface& network = list->at(i);
    ppapi::proxy::SerializedNetworkInfo& network_copy = list_copy->at(i);
    network_copy.name = network.name;

    network_copy.addresses.resize(
        1, ppapi::NetAddressPrivateImpl::kInvalidNetAddress);
    bool result = ppapi::NetAddressPrivateImpl::IPEndPointToNetAddress(
        network.address, 0, &(network_copy.addresses[0]));
    DCHECK(result);

    // TODO(sergeyu): Currently net::NetworkInterfaceList provides
    // only name and one IP address. Add all other fields and copy
    // them here.
    network_copy.type = PP_NETWORKLIST_TYPE_UNKNOWN;
    network_copy.state = PP_NETWORKLIST_STATE_UP;
    network_copy.display_name = network.name;
    network_copy.mtu = 0;
  }
  host()->SendUnsolicitedReply(
      pp_resource(), PpapiPluginMsg_NetworkMonitor_NetworkList(*list_copy));
}

}  // namespace content
<commit_msg>Fixed broken build.<commit_after>// Copyright 2013 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/browser/renderer_host/pepper/pepper_network_monitor_host.h"

#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/browser/renderer_host/pepper/browser_ppapi_host_impl.h"
#include "content/browser/renderer_host/pepper/pepper_socket_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/socket_permission_request.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/private/net_address_private_impl.h"

namespace content {

namespace {

bool CanUseNetworkMonitor(bool external_plugin,
                          int render_process_id,
                          int render_view_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  SocketPermissionRequest request = SocketPermissionRequest(
      SocketPermissionRequest::NETWORK_STATE, std::string(), 0);
  return pepper_socket_utils::CanUseSocketAPIs(
      external_plugin, false /* private_api */, &request, render_process_id,
      render_view_id);
}

scoped_ptr<net::NetworkInterfaceList> GetNetworkList() {
  scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList());
  net::GetNetworkList(list.get());
  return list.Pass();
}

}  // namespace

PepperNetworkMonitorHost::PepperNetworkMonitorHost(
    BrowserPpapiHostImpl* host,
    PP_Instance instance,
    PP_Resource resource)
    : ResourceHost(host->GetPpapiHost(), instance, resource),
      weak_factory_(this) {
  int render_process_id;
  int render_view_id;
  host->GetRenderViewIDsForInstance(instance,
                                    &render_process_id,
                                    &render_view_id);

  BrowserThread::PostTaskAndReplyWithResult(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&CanUseNetworkMonitor, host->external_plugin(),
                 render_process_id, render_view_id),
      base::Bind(&PepperNetworkMonitorHost::OnPermissionCheckResult,
                 weak_factory_.GetWeakPtr()));
}

PepperNetworkMonitorHost::~PepperNetworkMonitorHost() {
  net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
}

void PepperNetworkMonitorHost::OnIPAddressChanged() {
  GetAndSendNetworkList();
}

void PepperNetworkMonitorHost::OnPermissionCheckResult(
    bool can_use_network_monitor) {
  if (!can_use_network_monitor) {
    host()->SendUnsolicitedReply(pp_resource(),
                                 PpapiPluginMsg_NetworkMonitor_Forbidden());
    return;
  }

  net::NetworkChangeNotifier::AddIPAddressObserver(this);
  GetAndSendNetworkList();
}

void PepperNetworkMonitorHost::GetAndSendNetworkList() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // Call GetNetworkList() on a thread that allows blocking IO.
  base::PostTaskAndReplyWithResult(
      BrowserThread::GetBlockingPool(), FROM_HERE,
      base::Bind(&GetNetworkList),
      base::Bind(&PepperNetworkMonitorHost::SendNetworkList,
                 weak_factory_.GetWeakPtr()));
}

void PepperNetworkMonitorHost::SendNetworkList(
    scoped_ptr<net::NetworkInterfaceList> list) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  scoped_ptr<ppapi::proxy::SerializedNetworkList> list_copy(
      new ppapi::proxy::SerializedNetworkList(list->size()));
  for (size_t i = 0; i < list->size(); ++i) {
    const net::NetworkInterface& network = list->at(i);
    ppapi::proxy::SerializedNetworkInfo& network_copy = list_copy->at(i);
    network_copy.name = network.name;

    network_copy.addresses.resize(
        1, ppapi::NetAddressPrivateImpl::kInvalidNetAddress);
    bool result = ppapi::NetAddressPrivateImpl::IPEndPointToNetAddress(
        network.address, 0, &(network_copy.addresses[0]));
    DCHECK(result);

    // TODO(sergeyu): Currently net::NetworkInterfaceList provides
    // only name and one IP address. Add all other fields and copy
    // them here.
    network_copy.type = PP_NETWORKLIST_TYPE_UNKNOWN;
    network_copy.state = PP_NETWORKLIST_STATE_UP;
    network_copy.display_name = network.name;
    network_copy.mtu = 0;
  }
  host()->SendUnsolicitedReply(
      pp_resource(), PpapiPluginMsg_NetworkMonitor_NetworkList(*list_copy));
}

}  // namespace content
<|endoftext|>


<commit_before>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>

#include <functional>
#include <iostream>
#include <sstream>

#include <boost/regex.hpp>
#include <boost/thread/thread.hpp>

#include <xUnit++/xUnit++.h>

namespace K3 {

std::string localhost = "127.0.0.1";
Address peer1;
Address peer2;
Address peer3;
Address rendezvous;

int nodeCounter(0);

using std::cout;
using std::endl;
using std::bind;
using std::string;
using std::shared_ptr;

// "Trigger" Declarations
void join(shared_ptr<Engine> engine, string message_contents) {
  Message m = Message(rendezvous, "register", "1");
  engine->send(m);
}

void register2(shared_ptr<Engine> engine, string message_contents) {
  int n = std::stoi(message_contents);
  nodeCounter += n;
}

// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
  TriggerDispatch table = TriggerDispatch();
  table["join"] = bind(&K3::join, engine, std::placeholders::_1);
  table["register"] = bind(&K3::register2, engine, std::placeholders::_1);
  return table;
}

shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
  auto table = buildTable(engine);
  shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
  return mp;
}

// Engine setup
shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {
  // Configure engine components
  shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());
  shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());

  // Construct an engine
  Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);
  return make_shared<Engine>(engine);
}

}

FACT("Simulation mode CountPeers with 3 peers should count 3") {
  K3::nodeCounter = 0;
  K3::peer1 = K3::make_address(K3::localhost, 3000);
  K3::peer2 = K3::make_address(K3::localhost, 3001);
  K3::peer3 = K3::make_address(K3::localhost, 3002);
  K3::rendezvous = K3::peer1;
  std::list<K3::Address> peers = std::list<K3::Address>();
  peers.push_back(K3::peer1);
  peers.push_back(K3::peer2);
  peers.push_back(K3::peer3);
  K3::SystemEnvironment s_env = K3::defaultEnvironment(peers);

  auto engine = K3::buildEngine(true, s_env);
  auto mp = K3::buildMP(engine);
  K3::Message m1 = K3::Message(K3::peer1, "join", "()");
  K3::Message m2 = K3::Message(K3::peer2, "join", "()");
  K3::Message m3 = K3::Message(K3::peer3, "join", "()");
  engine->send(m1);
  engine->send(m2);
  engine->send(m3);

  // Run Engine
  engine->runEngine(mp);

  // Check the result (the 6th fib number should = 8)
  Assert.Equal(3, K3::nodeCounter);
}

FACT("Network mode CountPeers with 3 peers should count 3") {
  K3::nodeCounter = 0;
  using boost::thread;
  using boost::thread_group;
  // Create peers
  K3::peer1 = K3::make_address(K3::localhost, 3000);
  K3::peer2 = K3::make_address(K3::localhost, 3005);
  K3::peer3 = K3::make_address(K3::localhost, 3002);
  K3::rendezvous = K3::peer1;
  // Create engines
  auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1));
  auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2));
  auto engine3 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer3));
  // Create MPs
  auto mp1 = K3::buildMP(engine1);
  auto mp2 = K3::buildMP(engine2);
  auto mp3 = K3::buildMP(engine3);
  // Create initial messages (source)
  K3::Message m1 = K3::Message(K3::peer1, "join", "()");
  K3::Message m2 = K3::Message(K3::peer2, "join", "()");
  K3::Message m3 = K3::Message(K3::peer3, "join", "()");
  engine1->send(m1);
  engine2->send(m2);
  engine3->send(m3);
  // Fork a thread for each engine
  auto service_threads = std::shared_ptr<thread_group>(new thread_group());
  thread t1 = engine1->forkEngine(mp1);
  thread t2 = engine2->forkEngine(mp2);
  thread t3 = engine3->forkEngine(mp3);

  service_threads->add_thread(&t1);
  service_threads->add_thread(&t2);
  service_threads->add_thread(&t3);

  boost::this_thread::sleep_for( boost::chrono::seconds(5) );
  engine1->forceTerminateEngine();
  engine2->forceTerminateEngine();
  engine3->forceTerminateEngine();
  service_threads->join_all();
  service_threads->remove_thread(&t1);
  service_threads->remove_thread(&t2);
  service_threads->remove_thread(&t3);

  // Check the result
  Assert.Equal(3, K3::nodeCounter);
}
<commit_msg>fixed another comment<commit_after>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>

#include <functional>
#include <iostream>
#include <sstream>

#include <boost/regex.hpp>
#include <boost/thread/thread.hpp>

#include <xUnit++/xUnit++.h>

namespace K3 {

std::string localhost = "127.0.0.1";
Address peer1;
Address peer2;
Address peer3;
Address rendezvous;

int nodeCounter(0);

using std::cout;
using std::endl;
using std::bind;
using std::string;
using std::shared_ptr;

// "Trigger" Declarations
void join(shared_ptr<Engine> engine, string message_contents) {
  Message m = Message(rendezvous, "register", "1");
  engine->send(m);
}

void register2(shared_ptr<Engine> engine, string message_contents) {
  int n = std::stoi(message_contents);
  nodeCounter += n;
}

// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
  TriggerDispatch table = TriggerDispatch();
  table["join"] = bind(&K3::join, engine, std::placeholders::_1);
  table["register"] = bind(&K3::register2, engine, std::placeholders::_1);
  return table;
}

shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
  auto table = buildTable(engine);
  shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
  return mp;
}

// Engine setup
shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {
  // Configure engine components
  shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());
  shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());

  // Construct an engine
  Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);
  return make_shared<Engine>(engine);
}

}

FACT("Simulation mode CountPeers with 3 peers should count 3") {
  K3::nodeCounter = 0;
  K3::peer1 = K3::make_address(K3::localhost, 3000);
  K3::peer2 = K3::make_address(K3::localhost, 3001);
  K3::peer3 = K3::make_address(K3::localhost, 3002);
  K3::rendezvous = K3::peer1;
  std::list<K3::Address> peers = std::list<K3::Address>();
  peers.push_back(K3::peer1);
  peers.push_back(K3::peer2);
  peers.push_back(K3::peer3);
  K3::SystemEnvironment s_env = K3::defaultEnvironment(peers);

  auto engine = K3::buildEngine(true, s_env);
  auto mp = K3::buildMP(engine);
  K3::Message m1 = K3::Message(K3::peer1, "join", "()");
  K3::Message m2 = K3::Message(K3::peer2, "join", "()");
  K3::Message m3 = K3::Message(K3::peer3, "join", "()");
  engine->send(m1);
  engine->send(m2);
  engine->send(m3);

  // Run Engine
  engine->runEngine(mp);

  // Check the result
  Assert.Equal(3, K3::nodeCounter);
}

FACT("Network mode CountPeers with 3 peers should count 3") {
  K3::nodeCounter = 0;
  using boost::thread;
  using boost::thread_group;
  // Create peers
  K3::peer1 = K3::make_address(K3::localhost, 3000);
  K3::peer2 = K3::make_address(K3::localhost, 3005);
  K3::peer3 = K3::make_address(K3::localhost, 3002);
  K3::rendezvous = K3::peer1;
  // Create engines
  auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1));
  auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2));
  auto engine3 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer3));
  // Create MPs
  auto mp1 = K3::buildMP(engine1);
  auto mp2 = K3::buildMP(engine2);
  auto mp3 = K3::buildMP(engine3);
  // Create initial messages (source)
  K3::Message m1 = K3::Message(K3::peer1, "join", "()");
  K3::Message m2 = K3::Message(K3::peer2, "join", "()");
  K3::Message m3 = K3::Message(K3::peer3, "join", "()");
  engine1->send(m1);
  engine2->send(m2);
  engine3->send(m3);
  // Fork a thread for each engine
  auto service_threads = std::shared_ptr<thread_group>(new thread_group());
  thread t1 = engine1->forkEngine(mp1);
  thread t2 = engine2->forkEngine(mp2);
  thread t3 = engine3->forkEngine(mp3);

  service_threads->add_thread(&t1);
  service_threads->add_thread(&t2);
  service_threads->add_thread(&t3);

  boost::this_thread::sleep_for( boost::chrono::seconds(5) );
  engine1->forceTerminateEngine();
  engine2->forceTerminateEngine();
  engine3->forceTerminateEngine();
  service_threads->join_all();
  service_threads->remove_thread(&t1);
  service_threads->remove_thread(&t2);
  service_threads->remove_thread(&t3);

  // Check the result
  Assert.Equal(3, K3::nodeCounter);
}
<|endoftext|>


<commit_before>/*
   Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>

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

   This 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LGPL.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.

   Alternatively, this file is available under the Mozilla Public License
   Version 1.1.  You may obtain a copy of the License at
   http://www.mozilla.org/MPL/
*/

#include "authclient.h"

#include "icompletionlistener.h"
#include "itransport.h"
#include "stringtools.h"

#include <cassert>
#include <iostream>
#include <sstream>

#ifdef __unix__
#include <sys/types.h>
#include <unistd.h>
#endif

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sddl.h>
#include "winutil.h"
#endif

using namespace std;

AuthClient::AuthClient(ITransport *transport)
   : m_state(InitialState),
     m_completionListener(nullptr)
{
    cerr << "AuthClient constructing\n";
    transport->addListener(this);
    setReadNotificationEnabled(true);
    byte nullBuf[1] = { 0 };
    transport->write(chunk(nullBuf, 1));

    stringstream uidEncoded;
#ifdef _WIN32
    // Most common (or rather... actually used) authentication method on Windows:
    // - Server publishes address of a nonce file; the file name is in a shared memory segment
    // - Client reads nonce file
    // - Client connects and sends the nonce data, TODO: before or after the null byte / is there a null byte?
    // - Client uses EXTERNAL auth and says which Windows security ID (SID) it intends to have
    uidEncoded << fetchWindowsSid();
#else
    // Most common (or rather... actually used) authentication method on Unix derivatives:
    // - Client sends a null byte so the server has something to receive with recvmsg()
    // - Server checks UID using SCM_CREDENTIALS, a mechanism of Unix local sockets
    // - Client uses EXTERNAL auth and says which Unix user ID it intends to have

    // The numeric UID is first encoded to ASCII ("1000") and the ASCII to hex... because.
    uidEncoded << geteuid();
#endif
    string extLine = "AUTH EXTERNAL " + hexEncode(uidEncoded.str()) + "\r\n";
    cout << extLine;
    transport->write(chunk(extLine.c_str(), extLine.length()));
    m_state = ExpectOkState;
}

bool AuthClient::isFinished() const
{
    return m_state >= AuthenticationFailedState;
}

bool AuthClient::isAuthenticated() const
{
    return m_state == AuthenticatedState;
}

void AuthClient::setCompletionListener(ICompletionListener *listener)
{
    m_completionListener = listener;
}

void AuthClient::handleTransportCanRead()
{
    bool wasFinished = isFinished();
    while (!isFinished() && readLine()) {
        advanceState();
    }
    if (isFinished() && !wasFinished && m_completionListener) {
        m_completionListener->handleCompletion(this);
    }
}

bool AuthClient::readLine()
{
    // don't care about performance here, this doesn't run often or process much data
    if (isEndOfLine()) {
        m_line.clear(); // start a new line
    }
    while (transport()->availableBytesForReading()) {
        byte readBuf[1];
        chunk in = transport()->read(readBuf, 1);
        assert(in.length == 1);
        m_line += char(in.ptr[0]);

        if (isEndOfLine()) {
            return true;
        }
    }
    return false;
}

bool AuthClient::isEndOfLine() const
{
    return m_line.length() >= 2 &&
           m_line[m_line.length() - 2] == '\r' && m_line[m_line.length() - 1] == '\n';
}

void AuthClient::advanceState()
{
    // TODO authentication ping-pong done *properly* (grammar / some simple state machine),
    //      but hey, this works for now!
    // some findings:
    // - the string after the server OK is its UUID that also appears in the address string

    cout << "> " << m_line;

    switch (m_state) {
    case ExpectOkState: {
        // TODO check the OK
#ifdef __unix__
        cstring negotiateLine("NEGOTIATE_UNIX_FD\r\n");
        cout << negotiateLine.ptr;
        transport()->write(chunk(negotiateLine.ptr, negotiateLine.length));
        m_state = ExpectUnixFdResponseState;
        break; }
    case ExpectUnixFdResponseState: {
#endif
        // TODO check the response
        cstring beginLine("BEGIN\r\n");
        cout << beginLine.ptr;
        transport()->write(chunk(beginLine.ptr, beginLine.length));
        m_state = AuthenticatedState;
        break; }
    default:
        m_state = AuthenticationFailedState;
        transport()->close();
    }
}
<commit_msg>Remove some debug output<commit_after>/*
   Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>

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

   This 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LGPL.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.

   Alternatively, this file is available under the Mozilla Public License
   Version 1.1.  You may obtain a copy of the License at
   http://www.mozilla.org/MPL/
*/

#include "authclient.h"

#include "icompletionlistener.h"
#include "itransport.h"
#include "stringtools.h"

#include <cassert>
#include <iostream>
#include <sstream>

#ifdef __unix__
#include <sys/types.h>
#include <unistd.h>
#endif

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <sddl.h>
#include "winutil.h"
#endif

using namespace std;

AuthClient::AuthClient(ITransport *transport)
   : m_state(InitialState),
     m_completionListener(nullptr)
{
    transport->addListener(this);
    setReadNotificationEnabled(true);
    byte nullBuf[1] = { 0 };
    transport->write(chunk(nullBuf, 1));

    stringstream uidEncoded;
#ifdef _WIN32
    // Most common (or rather... actually used) authentication method on Windows:
    // - Server publishes address of a nonce file; the file name is in a shared memory segment
    // - Client reads nonce file
    // - Client connects and sends the nonce data, TODO: before or after the null byte / is there a null byte?
    // - Client uses EXTERNAL auth and says which Windows security ID (SID) it intends to have
    uidEncoded << fetchWindowsSid();
#else
    // Most common (or rather... actually used) authentication method on Unix derivatives:
    // - Client sends a null byte so the server has something to receive with recvmsg()
    // - Server checks UID using SCM_CREDENTIALS, a mechanism of Unix local sockets
    // - Client uses EXTERNAL auth and says which Unix user ID it intends to have

    // The numeric UID is first encoded to ASCII ("1000") and the ASCII to hex... because.
    uidEncoded << geteuid();
#endif
    string extLine = "AUTH EXTERNAL " + hexEncode(uidEncoded.str()) + "\r\n";
    cout << extLine;
    transport->write(chunk(extLine.c_str(), extLine.length()));
    m_state = ExpectOkState;
}

bool AuthClient::isFinished() const
{
    return m_state >= AuthenticationFailedState;
}

bool AuthClient::isAuthenticated() const
{
    return m_state == AuthenticatedState;
}

void AuthClient::setCompletionListener(ICompletionListener *listener)
{
    m_completionListener = listener;
}

void AuthClient::handleTransportCanRead()
{
    bool wasFinished = isFinished();
    while (!isFinished() && readLine()) {
        advanceState();
    }
    if (isFinished() && !wasFinished && m_completionListener) {
        m_completionListener->handleCompletion(this);
    }
}

bool AuthClient::readLine()
{
    // don't care about performance here, this doesn't run often or process much data
    if (isEndOfLine()) {
        m_line.clear(); // start a new line
    }
    while (transport()->availableBytesForReading()) {
        byte readBuf[1];
        chunk in = transport()->read(readBuf, 1);
        assert(in.length == 1);
        m_line += char(in.ptr[0]);

        if (isEndOfLine()) {
            return true;
        }
    }
    return false;
}

bool AuthClient::isEndOfLine() const
{
    return m_line.length() >= 2 &&
           m_line[m_line.length() - 2] == '\r' && m_line[m_line.length() - 1] == '\n';
}

void AuthClient::advanceState()
{
    // TODO authentication ping-pong done *properly* (grammar / some simple state machine),
    //      but hey, this works for now!
    // some findings:
    // - the string after the server OK is its UUID that also appears in the address string

    cout << "> " << m_line;

    switch (m_state) {
    case ExpectOkState: {
        // TODO check the OK
#ifdef __unix__
        cstring negotiateLine("NEGOTIATE_UNIX_FD\r\n");
        cout << negotiateLine.ptr;
        transport()->write(chunk(negotiateLine.ptr, negotiateLine.length));
        m_state = ExpectUnixFdResponseState;
        break; }
    case ExpectUnixFdResponseState: {
#endif
        // TODO check the response
        cstring beginLine("BEGIN\r\n");
        cout << beginLine.ptr;
        transport()->write(chunk(beginLine.ptr, beginLine.length));
        m_state = AuthenticatedState;
        break; }
    default:
        m_state = AuthenticationFailedState;
        transport()->close();
    }
}
<|endoftext|>


<commit_before>/*
 * Implement atoi to convert a string to an integer.
 *
 * Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
 *
 * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
 *
 * Update (2015-02-10):
 * The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.
 *
 * spoilers alert... click to show requirements for atoi.
 *
 * Requirements for atoi:
 * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
 *
 * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
 *
 * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
 *
 * If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
 * int myAtoi(string str)
 * */

#include "common.h"

int myAtoi(string str) {
    int size = str.size();
    int64_t ret = 0;
    int sign = 1;
    int i = 0;
    //filter spaces
    while(i < size && isspace(str[i])) {i++;}
    if (i == size) return 0;

    //deal with sign
    if (!isdigit(str[i])) {
        if (str[i] == '-') {
            sign = -1;
            i++;
        } else if (str[i] == '+') {
            i++;
        } else {
            return 0;
        }
    }
    while(i < size) {
        if (!isdigit(str[i])) break;
        ret = 10 * ret + str[i] - '0';
        if (ret > std::numeric_limits<int>::max()) {
            return std::numeric_limits<int>::max();
        }
        i++;
    }
    ret = ret * sign;
    if (ret > std::numeric_limits<int>::max() || ret < std::numeric_limits<int>::min()) {
        return std::numeric_limits<int>::max();
    }
    return ret;
}

int main() {
    struct Case {
        string str;
        int expect;
    } cases[] = {
        {"  +", 0},
        {"  -", 0},
        {"0", 0},
        {"-123", -123},
        {"+123", 123},
        {"123", 123},
        {"     123", 123},
        {"123abcde", 123},
        {"abc1323", 0},
        {"21474836499", std::numeric_limits<int>::max() },
    };
    int size = sizeof(cases)/sizeof(Case);

    bool ok = true;
    for (int i = 0; i < size; i++) {
        int result = myAtoi(cases[i].str);
        if (result != cases[i].expect) {
            ok = false;
            cerr << "Case " << i << " Failed. expect: " << cases[i].expect << " actual output: " << result << " \n";
        }
    }
    if (ok) {
        cout << "ALL PASSED.";
    }
    return 0;
}
<commit_msg>update no 8 reverse integer.<commit_after>/*
 * Implement atoi to convert a string to an integer.
 *
 * Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
 *
 * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
 *
 * Update (2015-02-10):
 * The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.
 *
 * spoilers alert... click to show requirements for atoi.
 *
 * Requirements for atoi:
 * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
 *
 * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
 *
 * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
 *
 * If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
 * int myAtoi(string str)
 * */

#include "common.h"

int myAtoi(string str) {
    int size = str.size();
    int64_t ret = 0;
    int sign = 1;
    int i = 0;
    //filter spaces
    while(i < size && isspace(str[i])) {i++;}
    if (i == size) return 0;

    //deal with sign
    if (!isdigit(str[i])) {
        if (str[i] == '-') {
            sign = -1;
            i++;
        } else if (str[i] == '+') {
            i++;
        } else {
            return 0;
        }
    }
    while(i < size) {
        if (!isdigit(str[i])) break;
        ret = 10 * ret + str[i] - '0';
        if (ret * sign > std::numeric_limits<int>::max()) {
            return std::numeric_limits<int>::max();
        } else if (ret * sign < std::numeric_limits<int>::min()) {
            return std::numeric_limits<int>::min();
        }
        i++;
    }
    return sign * ret;
}

int main() {
    struct Case {
        string str;
        int expect;
    } cases[] = {
        {"  +", 0},
        {"  -", 0},
        {"0", 0},
        {"-123", -123},
        {"+123", 123},
        {"123", 123},
        {"     123", 123},
        {"123abcde", 123},
        {"abc1323", 0},
        {"+2147483647", std::numeric_limits<int>::max() },
        {"+2147483648", std::numeric_limits<int>::max() },
        {"-2147483648", std::numeric_limits<int>::min() },
        {"-2147483649", std::numeric_limits<int>::min() },

    };
    int size = sizeof(cases)/sizeof(Case);

    bool ok = true;
    for (int i = 0; i < size; i++) {
        int result = myAtoi(cases[i].str);
        if (result != cases[i].expect) {
            ok = false;
            cerr << "Case " << i << " Failed. expect: " << cases[i].expect << " actual output: " << result << " \n";
        }
    }
    if (ok) {
        cout << "ALL PASSED.";
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMSupportDefault.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/XPathProcessorImpl.hpp>

#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesStdTextOutputStream.hpp>

#include <XercesParserLiaison/XercesParserLiaison.hpp>

#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/TraceListenerDefault.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>

int
main(
			int				argc,
			const char*		argv[])
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::auto_ptr;
	using std::cerr;
	using std::endl;
#endif

  // TraceListener flags...
  bool traceTemplates = false;
  bool traceTemplateChildren = false;
  bool traceGenerationEvent = false;
  bool traceSelectionEvent = false;

	if (argc < 2 || argc > 5)
	{
		cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
		return -1;
	}

	// Set the TraceListener flags...
	for (int i = 1;	i < argc;	i ++)
	{
		if(!stricmp("-TT", argv[i]))
		{
			traceTemplates = true;
		}
		else if(!stricmp("-TG", argv[i]))
		{
			traceGenerationEvent = true;
		}
		else if(!stricmp("-TS", argv[i]))
		{
			traceSelectionEvent = true;
		}
		else if(!stricmp("-TTC", argv[i]))
		{
			traceTemplateChildren = true;
		}
		else
		{
  			cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
	  		return -1;
		}
	}

	try
	{
		// Call the static initializers...
		XMLPlatformUtils::Initialize();
		XSLTEngineImpl::Initialize();

		// Create the support objects that are necessary for running the processor...
		DOMSupportDefault				theDOMSupport;
		XercesParserLiaison				theParserLiaison(theDOMSupport);
		XPathSupportDefault				theXPathSupport(theDOMSupport);
		XSLTProcessorEnvSupportDefault	theXSLTProcessorEnvSupport;
		XObjectFactoryDefault			theXObjectFactory;
		XPathFactoryDefault				theXPathFactory;

		// Create a processor...
		XSLTEngineImpl	theProcessor(
					theParserLiaison,
					theXPathSupport,
					theXSLTProcessorEnvSupport,
					theXObjectFactory,
					theXPathFactory);

		// Connect the processor to the support object...
		theXSLTProcessorEnvSupport.setProcessor(&theProcessor);

		// Create a stylesheet construction context, and a stylesheet
		// execution context...
		StylesheetConstructionContextDefault	theConstructionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathFactory);

		StylesheetExecutionContextDefault		theExecutionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathSupport,
						theXObjectFactory);

	  // Our input files...The assumption is that the executable will be run
		// from same directory as the input files.
		const XalanDOMString		theXMLFileName("birds.xml");
		const XalanDOMString		theXSLFileName("birds.xsl");

		// Our input sources...
		XSLTInputSource		theInputSource(c_wstr(theXMLFileName));
		XSLTInputSource		theStylesheetSource(c_wstr(theXSLFileName));

		// Our output target...
		TextFileOutputStream	theOutputStream("birds.out");
		XercesDOMPrintWriter	theResultWriter(theOutputStream);
		XSLTResultTarget		theResultTarget(&theResultWriter);

		// Set up a diagnostic writer to be used by the TraceListener...
		XercesStdTextOutputStream				theStdErr(cerr);
		XercesDOMPrintWriter					diagnosticsWriter(theStdErr);

	  // Set up the TraceListener...
		auto_ptr<TraceListener>		theTraceListener(
			new TraceListenerDefault(
				diagnosticsWriter,
				traceTemplates,
				traceTemplateChildren,
				traceGenerationEvent,
				traceSelectionEvent));

		// Add the TraceListener to the XSLT processor...
		theProcessor.setTraceSelects(traceSelectionEvent);
		theProcessor.addTraceListener(theTraceListener.get());

		// Perform the transformation...
		theProcessor.process(
						theInputSource,
						theStylesheetSource,
						theResultTarget,
						theConstructionContext,
						theExecutionContext);

		// Call the static terminators...
		XMLPlatformUtils::Terminate();
		XSLTEngineImpl::Terminate();
	}
	catch(...)
	{
		cerr << "Exception caught!  Exiting..." << endl;
	}

	return 0;
}
<commit_msg>Made some minor changes to support UNIX platforms.<commit_after>// Base header file.  Must be first.
#include <Include/PlatformDefinitions.hpp>

#include <iostream>
#include <fstream>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMSupportDefault.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/XPathProcessorImpl.hpp>

#include <XercesPlatformSupport/XercesDOMPrintWriter.hpp>
#include <XercesPlatformSupport/TextFileOutputStream.hpp>
#include <XercesPlatformSupport/XercesStdTextOutputStream.hpp>

#include <XercesParserLiaison/XercesParserLiaison.hpp>

#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/TraceListenerDefault.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>

int
main(
			int				argc,
			const char*		argv[])
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::auto_ptr;
	using std::cerr;
	using std::endl;
#endif

	// TraceListener flags...
	bool traceTemplates = false;
	bool traceTemplateChildren = false;
	bool traceGenerationEvent = false;
	bool traceSelectionEvent = false;

	if (argc < 2 || argc > 5)
	{
		cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
		return -1;
	}

	// Set the TraceListener flags...
	for (int i = 1;	i < argc;	i ++)
	{
		if(!stricmp("-TT", argv[i]))
		{
			traceTemplates = true;
		}
		else if(!stricmp("-TG", argv[i]))
		{
			traceGenerationEvent = true;
		}
		else if(!stricmp("-TS", argv[i]))
		{
			traceSelectionEvent = true;
		}
		else if(!stricmp("-TTC", argv[i]))
		{
			traceTemplateChildren = true;
		}
		else
		{
  			cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
	  		return -1;
		}
	}

	try
	{
		// Call the static initializers...
		XMLPlatformUtils::Initialize();
		XSLTEngineImpl::Initialize();

		// Create the support objects that are necessary for running the processor...
		DOMSupportDefault				theDOMSupport;
		XercesParserLiaison				theParserLiaison(theDOMSupport);
		XPathSupportDefault				theXPathSupport(theDOMSupport);
		XSLTProcessorEnvSupportDefault	theXSLTProcessorEnvSupport;
		XObjectFactoryDefault			theXObjectFactory;
		XPathFactoryDefault				theXPathFactory;

		// Create a processor...
		XSLTEngineImpl	theProcessor(
					theParserLiaison,
					theXPathSupport,
					theXSLTProcessorEnvSupport,
					theXObjectFactory,
					theXPathFactory);

		// Connect the processor to the support object...
		theXSLTProcessorEnvSupport.setProcessor(&theProcessor);

		// Create a stylesheet construction context, and a stylesheet
		// execution context...
		StylesheetConstructionContextDefault	theConstructionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathFactory);

		StylesheetExecutionContextDefault		theExecutionContext(
						theProcessor,
						theXSLTProcessorEnvSupport,
						theXPathSupport,
						theXObjectFactory);

		// Our input files...The assumption is that the executable will be run
		// from same directory as the input files.
		const XalanDOMString		theXMLFileName("birds.xml");
		const XalanDOMString		theXSLFileName("birds.xsl");

		// Our input sources...
		XSLTInputSource		theInputSource(c_wstr(theXMLFileName));
		XSLTInputSource		theStylesheetSource(c_wstr(theXSLFileName));

		// Our output target...
		TextFileOutputStream	theOutputStream("birds.out");
		XercesDOMPrintWriter	theResultWriter(theOutputStream);
		XSLTResultTarget		theResultTarget(&theResultWriter);

		// Set up a diagnostic writer to be used by the TraceListener...
		XercesStdTextOutputStream				theStdErr(cerr);
		XercesDOMPrintWriter					diagnosticsWriter(theStdErr);

		// Set up the TraceListener...
		TraceListenerDefault		theTraceListener(
				diagnosticsWriter,
				traceTemplates,
				traceTemplateChildren,
				traceGenerationEvent,
				traceSelectionEvent);

		// Add the TraceListener to the XSLT processor...
		theProcessor.setTraceSelects(traceSelectionEvent);
		theProcessor.addTraceListener(&theTraceListener);

		// Perform the transformation...
		theProcessor.process(
						theInputSource,
						theStylesheetSource,
						theResultTarget,
						theConstructionContext,
						theExecutionContext);

		// Call the static terminators...
		XMLPlatformUtils::Terminate();
		XSLTEngineImpl::Terminate();
	}
	catch(...)
	{
		cerr << "Exception caught!  Exiting..." << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "NeuralNetwork.hpp"
#include "FAST/Data/Image.hpp"
#include "FAST/Algorithms/ImageResizer/ImageResizer.hpp"

#include <tensorflow/core/framework/step_stats.pb.h>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/framework/types.pb.h>
#include <tensorflow/core/lib/strings/stringprintf.h>
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/platform/logging.h>
#include <tensorflow/core/platform/mutex.h>
#include <tensorflow/core/platform/types.h>
#include <tensorflow/core/public/session.h>
#include <tensorflow/core/graph/default_device.h>

namespace fast {

// See here for reference: https://github.com/tensorflow/tensorflow/blob/86f5ab7474825da756838b34e1b4eac93f5fc68a/tensorflow/contrib/android/jni/tensorflow_inference_jni.cc

void NeuralNetwork::load(std::string networkFilename) {

	tensorflow::SessionOptions options;
	tensorflow::ConfigProto &config = options.config;
	mSession.reset(tensorflow::NewSession(options));
	tensorflow::GraphDef tensorflow_graph;

    ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph);

	reportInfo() << "Creating session." << reportEnd();
	tensorflow::Status s = mSession->Create(tensorflow_graph);
	if (!s.ok()) {
		throw Exception("Could not create TensorFlow Graph");
	}

	//tensorflow::graph::SetDefaultDevice("/gpu:0", &tensorflow_graph);

	// Clear the proto to save memory space.
	tensorflow_graph.Clear();
	reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd();

	mModelLoaded = true;
}

NeuralNetwork::NeuralNetwork() {
	createInputPort<Image>(0, true, INPUT_STATIC_OR_DYNAMIC, true);
	mModelLoaded = false;
	mInputName = "";
	mWidth = -1;
	mHeight = -1;
	createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "Algorithms/NeuralNetwork/NeuralNetwork.cl");
}

void NeuralNetwork::execute() {

	std::vector<Image::pointer> images = getMultipleStaticInputData<Image>();

	if(mWidth < 0 || mHeight < 0)
		throw Exception("Network input layer width and height has to be specified before running the network");

    images = resizeImages(images);

	executeNetwork(images);
}

void NeuralNetwork::setInputParameters(std::string inputNodeNames, int width, int height) {
	mWidth = width;
	mHeight = height;
	mInputName = inputNodeNames;
}

std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput() {
    if(mOutputData.size() != 1)
		throw Exception("If network has more than 1 output can't return network output without name.");

	return mOutputData[mOutputNames[0]];
}

std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput(std::string name) {
	return mOutputData.at(name);
}

void NeuralNetwork::executeNetwork(const std::vector<Image::pointer>& images) {
    if(!mModelLoaded)
		throw Exception("Network and weights must be loaded in NeuralNetwork before execution.");
	if(mInputName == "")
		throw Exception("An input name must ge given to the NeuralNetwork before execution");
	if(mOutputNames.size() == 0)
		throw Exception("An output name must ge given to the NeuralNetwork before execution");

    int batchSize = images.size();
	if(batchSize == 0)
		throw Exception("Need at least one image to execute network.");

	// Create input tensor
	tensorflow::Tensor input_tensor(
			tensorflow::DT_FLOAT,
			tensorflow::TensorShape({batchSize, mHeight, mWidth, 1})
	);

	auto input_tensor_mapped = input_tensor.tensor<float, 4>();

	mRuntimeManager->startRegularTimer("input_data_copy");
	reportInfo() << "TensorFlow: Copying Data." << reportEnd();
	for(int n = 0; n < batchSize; ++n) {
		Image::pointer image = images[n];
		if (image->getWidth() != mWidth || image->getHeight() != mHeight)
			throw Exception("Input image sent to executeNetwork was of incrorrect size");

		ImageAccess::pointer access = image->getImageAccess(ACCESS_READ);
		for (int i = 0; i < mHeight; ++i) { // y
			for (int j = 0; j < mWidth; ++j) { // x
				input_tensor_mapped(n, i, j, 0) = access->getScalar(Vector2i(j, i)) / 255.0f;
			}
		}
	}
	mRuntimeManager->stopRegularTimer("input_data_copy");

    // TODO Need to know names of inputs and outputs in advance
	// Input: Only single for now
	// Output: Can be multiple

	// Create a scalar tensor which tells the system we are NOT doing training
	tensorflow::Tensor input_tensor2(
			tensorflow::DT_BOOL,
			tensorflow::TensorShape() // Scalar
	);
	auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>();
	input_tensor_mapped2(0) = false;

	std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors(
			{{mInputName, input_tensor}, {"keras_learning_phase", input_tensor2}});

	std::vector <tensorflow::Tensor> output_tensors;

	tensorflow::Status s;
	mRuntimeManager->startRegularTimer("network_execution");
	s = mSession->Run(input_tensors, mOutputNames, {}, &output_tensors);
	mRuntimeManager->stopRegularTimer("network_execution");

	if (!s.ok()) {
		reportError() << "Error during inference: " << s << reportEnd();
	}
	reportInfo() << "Finished executing network" << reportEnd();

    for(int j = 0; j < mOutputNames.size(); ++j) {
		tensorflow::Tensor *output = &output_tensors[j];
        std::string outputName = mOutputNames[j];

		//const auto outputData = output->flat<float>(); // This is some sort of Eigen tensor type
        auto output_tensor_mapped = output->tensor<float, 2>();
		std::vector<std::vector<float>> resultData;
		for(int n = 0; n < batchSize; ++n) {
            std::vector<float> outputValues;
			for (int i = 0; i < output_tensor_mapped.dimension(1); ++i) {
				outputValues.push_back(output_tensor_mapped(0, i));
			}
			resultData.push_back(outputValues);
		}

		mOutputData[outputName] = resultData;
	}
	reportInfo() << "Finished parsing output" << reportEnd();

}

std::vector<SharedPointer<Image>> NeuralNetwork::resizeImages(const std::vector<SharedPointer<Image>> &images) {
	reportInfo() << "Resizing images.." << reportEnd();
    std::vector<Image::pointer> resizedImages;
	for(Image::pointer image : images) {
		// Resize image to fit input layer
		if(mWidth != image->getWidth() || mHeight != image->getHeight()) {
			// Only resize if needed
            ImageResizer::pointer resizer = ImageResizer::New();
            resizer->setWidth(mWidth);
            resizer->setHeight(mHeight);
            resizer->setInputData(image);
            resizer->update();
            Image::pointer resizedImage = resizer->getOutputData<Image>();
            resizedImages.push_back(resizedImage);
		} else {
			resizedImages.push_back(image);
		}
	}

	return resizedImages;
}

};
<commit_msg>Check if tensorflow graph file is loaded properly<commit_after>#include "NeuralNetwork.hpp"
#include "FAST/Data/Image.hpp"
#include "FAST/Algorithms/ImageResizer/ImageResizer.hpp"

#include <tensorflow/core/framework/step_stats.pb.h>
#include <tensorflow/core/framework/tensor.h>
#include <tensorflow/core/framework/types.pb.h>
#include <tensorflow/core/lib/strings/stringprintf.h>
#include <tensorflow/core/platform/env.h>
#include <tensorflow/core/platform/logging.h>
#include <tensorflow/core/platform/mutex.h>
#include <tensorflow/core/platform/types.h>
#include <tensorflow/core/public/session.h>
#include <tensorflow/core/graph/default_device.h>

namespace fast {

// See here for reference: https://github.com/tensorflow/tensorflow/blob/86f5ab7474825da756838b34e1b4eac93f5fc68a/tensorflow/contrib/android/jni/tensorflow_inference_jni.cc

void NeuralNetwork::load(std::string networkFilename) {

	tensorflow::SessionOptions options;
	tensorflow::ConfigProto &config = options.config;
	mSession.reset(tensorflow::NewSession(options));
	tensorflow::GraphDef tensorflow_graph;

	{
		tensorflow::Status s = ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph);
		if (!s.ok()) {
			throw Exception("Could not read TensorFlow graph file " + networkFilename);
		}
	}

	reportInfo() << "Creating session." << reportEnd();
	tensorflow::Status s = mSession->Create(tensorflow_graph);
	if (!s.ok()) {
		throw Exception("Could not create TensorFlow Graph");
	}

	//tensorflow::graph::SetDefaultDevice("/gpu:0", &tensorflow_graph);

	// Clear the proto to save memory space.
	tensorflow_graph.Clear();
	reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd();

	mModelLoaded = true;
}

NeuralNetwork::NeuralNetwork() {
	createInputPort<Image>(0, true, INPUT_STATIC_OR_DYNAMIC, true);
	mModelLoaded = false;
	mInputName = "";
	mWidth = -1;
	mHeight = -1;
	createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "Algorithms/NeuralNetwork/NeuralNetwork.cl");
}

void NeuralNetwork::execute() {

	std::vector<Image::pointer> images = getMultipleStaticInputData<Image>();

	if(mWidth < 0 || mHeight < 0)
		throw Exception("Network input layer width and height has to be specified before running the network");

    images = resizeImages(images);

	executeNetwork(images);
}

void NeuralNetwork::setInputParameters(std::string inputNodeNames, int width, int height) {
	mWidth = width;
	mHeight = height;
	mInputName = inputNodeNames;
}

std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput() {
    if(mOutputData.size() != 1)
		throw Exception("If network has more than 1 output can't return network output without name.");

	return mOutputData[mOutputNames[0]];
}

std::vector<std::vector<float> > NeuralNetwork::getNetworkOutput(std::string name) {
	return mOutputData.at(name);
}

void NeuralNetwork::executeNetwork(const std::vector<Image::pointer>& images) {
    if(!mModelLoaded)
		throw Exception("Network and weights must be loaded in NeuralNetwork before execution.");
	if(mInputName == "")
		throw Exception("An input name must ge given to the NeuralNetwork before execution");
	if(mOutputNames.size() == 0)
		throw Exception("An output name must ge given to the NeuralNetwork before execution");

    int batchSize = images.size();
	if(batchSize == 0)
		throw Exception("Need at least one image to execute network.");

	// Create input tensor
	tensorflow::Tensor input_tensor(
			tensorflow::DT_FLOAT,
			tensorflow::TensorShape({batchSize, mHeight, mWidth, 1})
	);

	auto input_tensor_mapped = input_tensor.tensor<float, 4>();

	mRuntimeManager->startRegularTimer("input_data_copy");
	reportInfo() << "TensorFlow: Copying Data." << reportEnd();
	for(int n = 0; n < batchSize; ++n) {
		Image::pointer image = images[n];
		if (image->getWidth() != mWidth || image->getHeight() != mHeight)
			throw Exception("Input image sent to executeNetwork was of incrorrect size");

		ImageAccess::pointer access = image->getImageAccess(ACCESS_READ);
		for (int i = 0; i < mHeight; ++i) { // y
			for (int j = 0; j < mWidth; ++j) { // x
				input_tensor_mapped(n, i, j, 0) = access->getScalar(Vector2i(j, i)) / 255.0f;
			}
		}
	}
	mRuntimeManager->stopRegularTimer("input_data_copy");

    // TODO Need to know names of inputs and outputs in advance
	// Input: Only single for now
	// Output: Can be multiple

	// Create a scalar tensor which tells the system we are NOT doing training
	tensorflow::Tensor input_tensor2(
			tensorflow::DT_BOOL,
			tensorflow::TensorShape() // Scalar
	);
	auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>();
	input_tensor_mapped2(0) = false;

	std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors(
			{{mInputName, input_tensor}, {"keras_learning_phase", input_tensor2}});

	std::vector <tensorflow::Tensor> output_tensors;

	tensorflow::Status s;
	mRuntimeManager->startRegularTimer("network_execution");
	s = mSession->Run(input_tensors, mOutputNames, {}, &output_tensors);
	mRuntimeManager->stopRegularTimer("network_execution");

	if (!s.ok()) {
		reportError() << "Error during inference: " << s << reportEnd();
	}
	reportInfo() << "Finished executing network" << reportEnd();

    for(int j = 0; j < mOutputNames.size(); ++j) {
		tensorflow::Tensor *output = &output_tensors[j];
        std::string outputName = mOutputNames[j];

		//const auto outputData = output->flat<float>(); // This is some sort of Eigen tensor type
        auto output_tensor_mapped = output->tensor<float, 2>();
		std::vector<std::vector<float>> resultData;
		for(int n = 0; n < batchSize; ++n) {
            std::vector<float> outputValues;
			for (int i = 0; i < output_tensor_mapped.dimension(1); ++i) {
				outputValues.push_back(output_tensor_mapped(0, i));
			}
			resultData.push_back(outputValues);
		}

		mOutputData[outputName] = resultData;
	}
	reportInfo() << "Finished parsing output" << reportEnd();

}

std::vector<SharedPointer<Image>> NeuralNetwork::resizeImages(const std::vector<SharedPointer<Image>> &images) {
	reportInfo() << "Resizing images.." << reportEnd();
    std::vector<Image::pointer> resizedImages;
	for(Image::pointer image : images) {
		// Resize image to fit input layer
		if(mWidth != image->getWidth() || mHeight != image->getHeight()) {
			// Only resize if needed
            ImageResizer::pointer resizer = ImageResizer::New();
            resizer->setWidth(mWidth);
            resizer->setHeight(mHeight);
            resizer->setInputData(image);
            resizer->update();
            Image::pointer resizedImage = resizer->getOutputData<Image>();
            resizedImages.push_back(resizedImage);
		} else {
			resizedImages.push_back(image);
		}
	}

	return resizedImages;
}

};
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>

#include "akapplication.h"
#include "protocol_p.h"

#include "controlmanagerinterface.h"
#include "akonadistarter.h"

#include <unistd.h>

static bool startServer()
{
  if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE )
       || QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE ) ) {
    qDebug() << "Akonadi is already running.";
    return false;
  }
  AkonadiStarter starter;
  return starter.start();
}

static bool stopServer()
{
  org::freedesktop::Akonadi::ControlManager iface( AKONADI_DBUS_CONTROL_SERVICE, "/ControlManager", QDBusConnection::sessionBus(), 0 );
  iface.shutdown();

  return true;
}

static bool statusServer()
{
  bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE );
  qDebug( "Akonadi Control: %s", registered ? "running" : "stopped" );

  registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE );
  qDebug( "Akonadi Server: %s", registered ? "running" : "stopped" );

  return true;
}

int main( int argc, char **argv )
{
  AkApplication app( argc, argv );
  app.setDescription( "Akonadi server manipulation tool\n"
      "Usage: akonadictl [command]\n\n"
      "Commands:\n"
      "  start      : Starts the Akonadi server with all its processes\n"
      "  stop       : Stops the Akonadi server and all its processes cleanly\n"
      "  status     : Shows a status overview of the Akonadi server\n"
      "  restart    : Restart the Akonadi"
  );

  app.parseCommandLine();

  QString optionsList;
  optionsList.append( QLatin1String( "start" ) );
  optionsList.append( QLatin1String( "stop" ) );
  optionsList.append( QLatin1String( "status" ) );
  optionsList.append( QLatin1String( "restart" ) );

  const QStringList arguments = app.arguments();
  if ( arguments.count() != 2 ) {
    app.printUsage();
    return 1;
  } else if ( !optionsList.contains( arguments[ 1 ] ) ) {
    app.printUsage();
    return 2;
  }

  if ( arguments[ 1 ] == QLatin1String( "start" ) ) {
    if ( !startServer() )
      return 3;
  } else if ( arguments[ 1 ] == QLatin1String( "stop" ) ) {
    if ( !stopServer() )
      return 4;
  } else if ( arguments[ 1 ] == QLatin1String( "status" ) ) {
    if ( !statusServer() )
      return 5;
  } else if ( arguments[ 1 ] == QLatin1String( "restart") ) {
      if ( !stopServer() )
        return 4;
      else {
        do {
          usleep(100000);
        } while( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE ) );
        if ( !startServer() )
          return 3;
      }
  }

  return 0;
}
<commit_msg>Oops ... let me try again<commit_after>/***************************************************************************
 *   Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>

#include "akapplication.h"
#include "protocol_p.h"

#include "controlmanagerinterface.h"
#include "akonadistarter.h"

#include <unistd.h>

static bool startServer()
{
  if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE )
       || QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE ) ) {
    qDebug() << "Akonadi is already running.";
    return false;
  }
  AkonadiStarter starter;
  return starter.start();
}

static bool stopServer()
{
  org::freedesktop::Akonadi::ControlManager iface( AKONADI_DBUS_CONTROL_SERVICE, "/ControlManager", QDBusConnection::sessionBus(), 0 );
  iface.shutdown();

  return true;
}

static bool statusServer()
{
  bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE );
  qDebug( "Akonadi Control: %s", registered ? "running" : "stopped" );

  registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE );
  qDebug( "Akonadi Server: %s", registered ? "running" : "stopped" );

  return true;
}

int main( int argc, char **argv )
{
  AkApplication app( argc, argv );
  app.setDescription( "Akonadi server manipulation tool\n"
      "Usage: akonadictl [command]\n\n"
      "Commands:\n"
      "  start      : Starts the Akonadi server with all its processes\n"
      "  stop       : Stops the Akonadi server and all its processes cleanly\n"
      "  restart    : Restart Akonadi server with all its processes\n"
      "  status     : Shows a status overview of the Akonadi server"
  );

  app.parseCommandLine();

  QString optionsList;
  optionsList.append( QLatin1String( "start" ) );
  optionsList.append( QLatin1String( "stop" ) );
  optionsList.append( QLatin1String( "status" ) );
  optionsList.append( QLatin1String( "restart" ) );

  const QStringList arguments = app.arguments();
  if ( arguments.count() != 2 ) {
    app.printUsage();
    return 1;
  } else if ( !optionsList.contains( arguments[ 1 ] ) ) {
    app.printUsage();
    return 2;
  }

  if ( arguments[ 1 ] == QLatin1String( "start" ) ) {
    if ( !startServer() )
      return 3;
  } else if ( arguments[ 1 ] == QLatin1String( "stop" ) ) {
    if ( !stopServer() )
      return 4;
  } else if ( arguments[ 1 ] == QLatin1String( "status" ) ) {
    if ( !statusServer() )
      return 5;
  } else if ( arguments[ 1 ] == QLatin1String( "restart") ) {
      if ( !stopServer() )
        return 4;
      else {
        do {
          usleep(100000);
        } while( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE ) );
        if ( !startServer() )
          return 3;
      }
  }

  return 0;
}
<|endoftext|>