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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    VectorCurvatureAnisotropicDiffusionImageFilter.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.

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

//  Software Guide : BeginLatex
//
//  The \doxygen{VectorCurvatureAnisotropicDiffusionImageFilter} performs
//  anisotropic diffusion on a vector image using a modified curvature
//  diffusion equation (MCDE).  The MCDE is the same described in
//  \ref{sec:CurvatureAnisotropicDiffusionImageFilter}.
//
//  Typically in vector-valued diffusion, vector components are diffused
//  independently of one another using a conductance term that is linked across
//  the components.
//
//  This filter is designed to process images of \doxygen{Vector} type.  The
//  code relies on various typedefs and overloaded operators defined in
//  \doxygen{Vector}. It is perfectly reasonable, however, to apply this
//  filter to images of other, user-defined types as long as the appropriate
//  typedefs and operator overloads are in place.  As a general rule, follow
//  the example of \doxygen{Vector} in defining your data types.
//
//  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter|textbf}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"

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

// Software Guide : BeginCodeSnippet
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
// Software Guide : EndCodeSnippet

int main( int argc, char * argv[] )
{
  if( argc < 6 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputGradientImageFile ";
    std::cerr << "outputSmoothedGradientImageFile ";
    std::cerr << "numberOfIterations  timeStep  " << std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  Types should be selected based on required pixel type for the input and
  //  output images.  The image types are defined using the pixel type and
  //  the dimension.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef    float    InputPixelType;
  typedef itk::CovariantVector<float,2>    VectorPixelType;
  typedef itk::Image< InputPixelType,  2 >   InputImageType;
  typedef itk::Image< VectorPixelType, 2 >   VectorImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType >  ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  //  Software Guide : BeginLatex
  //
  //  The filter type is now instantiated using both the input image and the
  //  output image types. The filter object is created by the \code{New()}
  //  method.
  //
  //  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter!instantiation}
  //  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter!New()}
  //  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::VectorCurvatureAnisotropicDiffusionImageFilter<
                       VectorImageType, VectorImageType >  FilterType;
  FilterType::Pointer filter = FilterType::New();
  // Software Guide : EndCodeSnippet

  typedef itk::GradientRecursiveGaussianImageFilter<
                       InputImageType, VectorImageType >   GradientFilterType;

  GradientFilterType::Pointer gradient = GradientFilterType::New();

  //  Software Guide : BeginLatex
  //
  //  The input image can be obtained from the output of another filter. Here,
  //  an image reader is used as source and its data is passed through a
  //  gradient filter in order to generate an image of vectors.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  gradient->SetInput( reader->GetOutput() );
  filter->SetInput( gradient->GetOutput() );
  // Software Guide : EndCodeSnippet

  const unsigned int numberOfIterations = atoi( argv[4] );
  const double       timeStep = atof( argv[5] );

  //  Software Guide : BeginLatex
  //
  //  This filter requires two parameters, the number of iterations to be
  //  performed and the time step used in the computation of the level set
  //  evolution. These parameters are set using the methods
  //  \code{SetNumberOfIterations()} and \code{SetTimeStep()} respectively.
  //  The filter can be executed by invoking \code{Update()}.
  //
  //  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter!Update()}
  //  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter!SetTimeStep()}
  //  \index{itk::VectorCurvatureAnisotropicDiffusionImageFilter!SetNumberOfIterations()}
  //  \index{SetTimeStep()!itk::VectorCurvatureAnisotropicDiffusionImageFilter}
  //  \index{SetNumberOfIterations()!itk::VectorCurvatureAnisotropicDiffusionImageFilter}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetNumberOfIterations( numberOfIterations );
  filter->SetTimeStep( timeStep );
  filter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Typical values for the time step are $0.125$ in $2D$ images and
  //  $0.0625$ in $3D$ images. The number of iterations can be usually around
  //  $5$, more iterations will result in further smoothing and will increase
  //  linearly the computing time.
  //
  //  Software Guide : EndLatex

  //
  //  If the output of this filter has been connected to other filters down the
  //  pipeline, updating any of the downstream filters would have triggered the
  //  execution of this one. For example, a writer filter could have been used
  //  after the curvatur flow filter.
  //
  typedef    float    OutputPixelType;
  typedef itk::Image< OutputPixelType,  2 >   OutputImageType;
  typedef itk::VectorIndexSelectionCastImageFilter<
                  VectorImageType, OutputImageType > ComponentFilterType;
  ComponentFilterType::Pointer component = ComponentFilterType::New();

  // Select the component to extract.
  component->SetIndex( 0 );

  typedef unsigned char WritePixelType;
  typedef itk::Image< WritePixelType, 2 > WriteImageType;
  typedef itk::RescaleIntensityImageFilter<
               OutputImageType, WriteImageType > RescaleFilterType;
  RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
  rescaler->SetOutputMinimum(   0 );
  rescaler->SetOutputMaximum( 255 );

  typedef itk::ImageFileWriter< WriteImageType >  WriterType;
  WriterType::Pointer writer = WriterType::New();
  rescaler->SetInput( component->GetOutput() );
  writer->SetInput( rescaler->GetOutput() );

  // Save the component of the original gradient
  component->SetInput( gradient->GetOutput() );
  writer->SetFileName( argv[2] );
  writer->Update();

  // Save the component of the smoothed gradient
  component->SetInput( filter->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();

  //  Software Guide : BeginLatex
  //
  // \begin{figure} \center
  // \includegraphics[width=0.44\textwidth]{VectorCurvatureAnisotropicDiffusionImageFilterInput.eps}
  // \includegraphics[width=0.44\textwidth]{VectorCurvatureAnisotropicDiffusionImageFilterOutput.eps}
  // \itkcaption[VectorCurvatureAnisotropicDiffusionImageFilter output] ]{Effect
  // of the VectorCurvatureAnisotropicDiffusionImageFilter on the $X$ component
  // of the gradient from a MRIproton density brain image.}
  // \label{fig:VectorCurvatureAnisotropicDiffusionImageFilterInputOutput}
  // \end{figure}
  //
  //  Figure
  //  \ref{fig:VectorCurvatureAnisotropicDiffusionImageFilterInputOutput}
  //  illustrates the effect of this filter on a MRI proton density image of
  //  the brain. The images show the $X$ component of the gradient before
  //  (left) and after (right) the application of the filter. In this example
  //  the filter was run with a time step of 0.25, and 5 iterations.
  //
  //  Software Guide : EndLatex

  return 0;
}

<commit_msg>DOC: ENH: index hyphenation.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    VectorCurvatureAnisotropicDiffusionImageFilter.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.

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

//  Software Guide : BeginLatex
//
//  The \doxygen{VectorCurvatureAnisotropicDiffusionImageFilter} performs
//  anisotropic diffusion on a vector image using a modified curvature
//  diffusion equation (MCDE).  The MCDE is the same described in
//  \ref{sec:CurvatureAnisotropicDiffusionImageFilter}.
//
//  Typically in vector-valued diffusion, vector components are diffused
//  independently of one another using a conductance term that is linked across
//  the components.
//
//  This filter is designed to process images of \doxygen{Vector} type.  The
//  code relies on various typedefs and overloaded operators defined in
//  \doxygen{Vector}. It is perfectly reasonable, however, to apply this
//  filter to images of other, user-defined types as long as the appropriate
//  typedefs and operator overloads are in place.  As a general rule, follow
//  the example of \doxygen{Vector} in defining your data types.
//
//  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter}
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"

//  Software Guide : BeginLatex
//
//  The first step required to use this filter is to include its header file.
//
//  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!header}
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
// Software Guide : EndCodeSnippet

int main( int argc, char * argv[] )
{
  if( argc < 6 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  outputGradientImageFile ";
    std::cerr << "outputSmoothedGradientImageFile ";
    std::cerr << "numberOfIterations  timeStep  " << std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  Types should be selected based on required pixel type for the input and
  //  output images.  The image types are defined using the pixel type and
  //  the dimension.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef    float    InputPixelType;
  typedef itk::CovariantVector<float,2>    VectorPixelType;
  typedef itk::Image< InputPixelType,  2 >   InputImageType;
  typedef itk::Image< VectorPixelType, 2 >   VectorImageType;
  // Software Guide : EndCodeSnippet

  typedef itk::ImageFileReader< InputImageType >  ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  //  Software Guide : BeginLatex
  //
  //  The filter type is now instantiated using both the input image and the
  //  output image types. The filter object is created by the \code{New()}
  //  method.
  //
  //  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!instantiation}
  //  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!New()}
  //  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!Pointer}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::VectorCurvatureAnisotropicDiffusionImageFilter<
                       VectorImageType, VectorImageType >  FilterType;
  FilterType::Pointer filter = FilterType::New();
  // Software Guide : EndCodeSnippet

  typedef itk::GradientRecursiveGaussianImageFilter<
                       InputImageType, VectorImageType >   GradientFilterType;

  GradientFilterType::Pointer gradient = GradientFilterType::New();

  //  Software Guide : BeginLatex
  //
  //  The input image can be obtained from the output of another filter. Here,
  //  an image reader is used as source and its data is passed through a
  //  gradient filter in order to generate an image of vectors.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  gradient->SetInput( reader->GetOutput() );
  filter->SetInput( gradient->GetOutput() );
  // Software Guide : EndCodeSnippet

  const unsigned int numberOfIterations = atoi( argv[4] );
  const double       timeStep = atof( argv[5] );

  //  Software Guide : BeginLatex
  //
  //  This filter requires two parameters, the number of iterations to be
  //  performed and the time step used in the computation of the level set
  //  evolution. These parameters are set using the methods
  //  \code{SetNumberOfIterations()} and \code{SetTimeStep()} respectively.
  //  The filter can be executed by invoking \code{Update()}.
  //
  //  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!Update()}
  //  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!SetTimeStep()}
  //  \index{itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter!SetNumberOfIterations()}
  //  \index{SetTimeStep()!itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter}
  //  \index{SetNumberOfIterations()!itk::Vector\-Curvature\-Anisotropic\-Diffusion\-Image\-Filter}
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetNumberOfIterations( numberOfIterations );
  filter->SetTimeStep( timeStep );
  filter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Typical values for the time step are $0.125$ in $2D$ images and
  //  $0.0625$ in $3D$ images. The number of iterations can be usually around
  //  $5$, more iterations will result in further smoothing and will increase
  //  linearly the computing time.
  //
  //  Software Guide : EndLatex

  //
  //  If the output of this filter has been connected to other filters down the
  //  pipeline, updating any of the downstream filters would have triggered the
  //  execution of this one. For example, a writer filter could have been used
  //  after the curvatur flow filter.
  //
  typedef    float    OutputPixelType;
  typedef itk::Image< OutputPixelType,  2 >   OutputImageType;
  typedef itk::VectorIndexSelectionCastImageFilter<
                  VectorImageType, OutputImageType > ComponentFilterType;
  ComponentFilterType::Pointer component = ComponentFilterType::New();

  // Select the component to extract.
  component->SetIndex( 0 );

  typedef unsigned char WritePixelType;
  typedef itk::Image< WritePixelType, 2 > WriteImageType;
  typedef itk::RescaleIntensityImageFilter<
               OutputImageType, WriteImageType > RescaleFilterType;
  RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
  rescaler->SetOutputMinimum(   0 );
  rescaler->SetOutputMaximum( 255 );

  typedef itk::ImageFileWriter< WriteImageType >  WriterType;
  WriterType::Pointer writer = WriterType::New();
  rescaler->SetInput( component->GetOutput() );
  writer->SetInput( rescaler->GetOutput() );

  // Save the component of the original gradient
  component->SetInput( gradient->GetOutput() );
  writer->SetFileName( argv[2] );
  writer->Update();

  // Save the component of the smoothed gradient
  component->SetInput( filter->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();

  //  Software Guide : BeginLatex
  //
  // \begin{figure} \center
  // \includegraphics[width=0.44\textwidth]{VectorCurvatureAnisotropicDiffusionImageFilterInput.eps}
  // \includegraphics[width=0.44\textwidth]{VectorCurvatureAnisotropicDiffusionImageFilterOutput.eps}
  // \itkcaption[VectorCurvatureAnisotropicDiffusionImageFilter output] ]{Effect
  // of the VectorCurvatureAnisotropicDiffusionImageFilter on the $X$ component
  // of the gradient from a MRIproton density brain image.}
  // \label{fig:VectorCurvatureAnisotropicDiffusionImageFilterInputOutput}
  // \end{figure}
  //
  //  Figure
  //  \ref{fig:VectorCurvatureAnisotropicDiffusionImageFilterInputOutput}
  //  illustrates the effect of this filter on a MRI proton density image of
  //  the brain. The images show the $X$ component of the gradient before
  //  (left) and after (right) the application of the filter. In this example
  //  the filter was run with a time step of 0.25, and 5 iterations.
  //
  //  Software Guide : EndLatex

  return 0;
}

<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param head a ListNode
     * @param k an integer
     * @return a ListNode
     */
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode dummy = ListNode(std::numeric_limits<int>::min());
        dummy.next = head;
        ListNode *cur = head, *cur_dummy = &dummy;
        int length = 0;

        while (cur) {
            ListNode *next_cur = cur->next;
            length = (length + 1) % k;

            if (length == 0) {
                ListNode *next_dummy = cur_dummy->next;
                reverse(&cur_dummy, cur->next);
                cur_dummy = next_dummy;
            }
            cur = next_cur;
        }
        return dummy.next;
    }

    void reverse(ListNode **begin, const ListNode *end) {
        ListNode *first = (*begin)->next;
        ListNode *cur = first->next;

        while (cur != end) {
            first->next = cur->next;
            cur->next = (*begin)->next;
            (*begin)->next = cur;
            cur = first->next;
        }
    }
};
<commit_msg>Update reverse-nodes-in-k-group.cpp<commit_after>// Time:  O(n)
// Space: O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param head a ListNode
     * @param k an integer
     * @return a ListNode
     */
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode dummy{0};
        dummy.next = head;
        auto curr = head, curr_dummy = &dummy;
        int length = 0;

        while (curr) {
            ListNode *next_curr = curr->next;
            length = (length + 1) % k;

            if (length == 0) {
                ListNode *next_dummy = curr_dummy->next;
                reverse(&curr_dummy, curr->next);
                curr_dummy = next_dummy;
            }
            curr = next_curr;
        }
        return dummy.next;
    }

    void reverse(ListNode **begin, const ListNode *end) {
        ListNode *first = (*begin)->next;
        ListNode *curr = first->next;

        while (curr != end) {
            first->next = curr->next;
            curr->next = (*begin)->next;
            (*begin)->next = curr;
            curr = first->next;
        }
    }
};
<|endoftext|>


<commit_before><commit_msg>Add to spirit test<commit_after><|endoftext|>


<commit_before><commit_msg>Buildfix<commit_after><|endoftext|>


<commit_before>#include "simpleplayer.h"
#include "randomplayer.h"

void SimplePlayer::newGame(int /*player*/, const Game * game)
{
	SimplePlayer::game = game;
	board = game->getBoard();
}

void SimplePlayer::playerMoved(int /*player*/, const Tile * /*tile*/, const MoveHistoryEntry & /*move*/)
{
}

#define SIMPLE_PLAYER_RULE_CLOISTER_1    1
#define SIMPLE_PLAYER_RULE_CLOISTER_2    1
#define SIMPLE_PLAYER_RULE_ROAD_CITY     1
#define SIMPLE_PLAYER_USE_MEEPLE_PENALTY 0
TileMove SimplePlayer::getTileMove(int player, const Tile * tile, const MoveHistoryEntry & move, const TileMovesType & possible)
{
	static constexpr int dx[8] = {-1,  0, +1,  0, -1, +1, +1, -1};
	static constexpr int dy[8] = { 0, -1,  0, +1, -1, -1, +1, +1};
	static constexpr Tile::Side dir[4]    = {Tile::left,  Tile::up,    Tile::right, Tile::down};
	static constexpr Tile::Side oppDir[4] = {Tile::right, Tile::down,  Tile::left,  Tile::up  };
#if SIMPLE_PLAYER_USE_MEEPLE_PENALTY
	static constexpr int meeplePenalties[MEEPLE_COUNT+1] = {5, 4, 3, 2, 1, 1, 0, 0};
	int const meeplePenalty = meeplePenalties[meepleCount];
#else
	static constexpr int meeplePenalty = 0;
#endif

	int const myBonus = game->getPlayerCount();
	int const opponentBonus = myBonus - 1;
	int const meepleCount = game->getPlayerMeeples(player);
	bool const hasMeeples = (meepleCount > 0);

	meepleMoveSet = false;
	if (tile->getCloisterNode() != 0)
	{
		if (hasMeeples)
		{
#if SIMPLE_PLAYER_RULE_CLOISTER_1
			//TODO filter out rotations?
			VarLengthArrayWrapper<TileMove const *, TILE_ARRAY_LENGTH>::type goodMoves;
			int best = 0;
			for (TileMove const & tileMove : possible)
			{
				int surroundingTiles = 0;
				for (int i = 0; i < 8; ++i)
				{
					if (board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]) != 0)
						++surroundingTiles;
				}
				if (surroundingTiles > best)
				{
					goodMoves.clear();
					goodMoves.append(&tileMove);
				}
				else if (surroundingTiles == best)
				{
					goodMoves.append(&tileMove);
				}
			}

			for (uchar i = 0, c = tile->getNodeCount(); i < c; ++i)
			{
				if (tile->getNode(i)->getTerrain() == Cloister)
				{
					meepleMove.nodeIndex = i;
					meepleMoveSet = true;
					break;
				}
			}

			return *goodMoves[r.nextInt(goodMoves.size())];
#endif
		}
		else
		{
#if SIMPLE_PLAYER_RULE_CLOISTER_2
			VarLengthArrayWrapper<TileMove const *, TILE_ARRAY_LENGTH>::type goodMoves;
			int best = -10;
			for (TileMove const & tileMove : possible)
			{
				int points = 0;
				for (int i = 0; i < 8; ++i)
				{
					Tile const * t = board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]);
					if (t != 0)
					{
						Node const * n = t->getCloisterNode();
						if (n != 0 && n->getMaxMeeples() != 0)
						{
							if (n->getPlayerMeeples(player) != 0)
								points += myBonus;
							else
								points -= opponentBonus;
						}
					}
				}
				if (points > best)
				{
					goodMoves.clear();
					goodMoves.append(&tileMove);
				}
				else if (points == best)
				{
					goodMoves.append(&tileMove);
				}
			}

			return *goodMoves[r.nextInt(goodMoves.size())];
#endif
		}
	}
	else // No cloister tile
	{
#if  SIMPLE_PLAYER_RULE_ROAD_CITY
		VarLengthArrayWrapper<Move, TILE_ARRAY_LENGTH * NODE_ARRAY_LENGTH>::type goodMoves;
		int best = std::numeric_limits<int>::min();
		for (TileMove const & tileMove : possible)
		{
			int points = 0;
			VarLengthArrayWrapper<MeepleMove, TILE_ARRAY_LENGTH>::type meepleMoves(1);
			int bestNodePoints = 0; //std::numeric_limits<int>::min();
			for (int i = 0; i < 4; ++i)
			{
				Tile const * t = board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]);
				if (t == 0)
					continue;

				Tile::Side const & oppDirection = oppDir[i];
				TerrainType const & type = t->getEdge(oppDirection);
				if (type == Field)	//TODO Fields
					continue;
				//else Cities and Roads

				Tile::Side const & direction = dir[i];
				Q_ASSERT(type == tile->getEdge(direction, tileMove.orientation));

				uchar nodeIndex;
				Node const * nn = tile->getFeatureNodeAndIndex(direction, nodeIndex, tileMove.orientation);
				Node const * on = t->getFeatureNode(oppDirection);
				Q_ASSERT(nn != 0);
				Q_ASSERT(on != 0);
				Q_ASSERT(nodeIndex != uchar(-1));
				Q_ASSERT(on->getTerrain() == nn->getTerrain());

				int const score = nn->getScore() + on->getScore();
				uchar const max = on->getMaxMeeples();
				if (max != 0) //isOccupied
				{
					for (uint p = 0; p < game->getPlayerCount(); ++p)
					{
						if (on->getPlayerMeeples(p) != max)
							continue;
						if (p == (uint)player)
							points += myBonus*score;
						else
							points -= opponentBonus * score;
					}
				}
				else if (hasMeeples)
				{
					int nodePoints = myBonus*score - meeplePenalty;
					switch (type)
					{
						case City:
							nodePoints *= 3;
							break;
						case Road:
							nodePoints *= 2;
							break;
						case Field:
						case Cloister:
						case None:
							Q_UNREACHABLE();
							break;
					}

					if (nodePoints > bestNodePoints)
					{
						bestNodePoints = nodePoints;
						meepleMoves.clear();
						meepleMoves.push_back(MeepleMove{nodeIndex});
					}
					else if (nodePoints == bestNodePoints)
					{
						meepleMoves.append(MeepleMove{nodeIndex});
					}
				}

				switch (type)
				{
					case City:
						points *= 3;
						break;
					case Road:
						points *= 2;
						break;
					case Field:
					case Cloister:
					case None:
						Q_UNREACHABLE();
						break;
				}
			}

			points += bestNodePoints;
			if (points > best)
			{
				best = points;
				goodMoves.clear();
				for (MeepleMove const & mm : meepleMoves)
				{
					goodMoves.push_back(Move{tileMove, mm});
				}
			}
		}

		Move const & m = goodMoves[r.nextInt(goodMoves.size())];
		meepleMove = m.meepleMove;
		meepleMoveSet = true;
		return m.tileMove;
#endif
	}
	return RandomPlayer::instance.getTileMove(player, tile, move, possible);
}

MeepleMove SimplePlayer::getMeepleMove(int player, const Tile * tile, const MoveHistoryEntry & move, const MeepleMovesType & possible)
{
	if (meepleMoveSet && std::find(possible.cbegin(), possible.cend(), meepleMove) != possible.cend())
		return meepleMove;
	return RandomPlayer::instance.getMeepleMove(player, tile, move, possible);
}

void SimplePlayer::endGame()
{
}

QString SimplePlayer::getTypeName()
{
	return "SimplePlayer";
}

Player *SimplePlayer::clone() const
{
	return new SimplePlayer();
}
<commit_msg>SimplePlayer bugfix. How did this even work?<commit_after>#include "simpleplayer.h"
#include "randomplayer.h"

void SimplePlayer::newGame(int /*player*/, const Game * game)
{
	SimplePlayer::game = game;
	board = game->getBoard();
}

void SimplePlayer::playerMoved(int /*player*/, const Tile * /*tile*/, const MoveHistoryEntry & /*move*/)
{
}

#define SIMPLE_PLAYER_RULE_CLOISTER_1    1
#define SIMPLE_PLAYER_RULE_CLOISTER_2    1
#define SIMPLE_PLAYER_RULE_ROAD_CITY     1
#define SIMPLE_PLAYER_USE_MEEPLE_PENALTY 0
TileMove SimplePlayer::getTileMove(int player, const Tile * tile, const MoveHistoryEntry & move, const TileMovesType & possible)
{
	static constexpr int dx[8] = {-1,  0, +1,  0, -1, +1, +1, -1};
	static constexpr int dy[8] = { 0, -1,  0, +1, -1, -1, +1, +1};
	static constexpr Tile::Side dir[4]    = {Tile::left,  Tile::up,    Tile::right, Tile::down};
	static constexpr Tile::Side oppDir[4] = {Tile::right, Tile::down,  Tile::left,  Tile::up  };
#if SIMPLE_PLAYER_USE_MEEPLE_PENALTY
	static constexpr int meeplePenalties[MEEPLE_COUNT+1] = {5, 4, 3, 2, 1, 1, 0, 0};
	int const meeplePenalty = meeplePenalties[meepleCount];
#else
	static constexpr int meeplePenalty = 0;
#endif

	int const myBonus = game->getPlayerCount();
	int const opponentBonus = myBonus - 1;
	int const meepleCount = game->getPlayerMeeples(player);
	bool const hasMeeples = (meepleCount > 0);

	meepleMoveSet = false;
	if (tile->getCloisterNode() != 0)
	{
		if (hasMeeples)
		{
#if SIMPLE_PLAYER_RULE_CLOISTER_1
			//TODO filter out rotations?
			VarLengthArrayWrapper<TileMove const *, TILE_ARRAY_LENGTH>::type goodMoves;
			int best = 0;
			for (TileMove const & tileMove : possible)
			{
				int surroundingTiles = 0;
				for (int i = 0; i < 8; ++i)
				{
					if (board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]) != 0)
						++surroundingTiles;
				}
				if (surroundingTiles > best)
				{
					best = surroundingTiles;
					goodMoves.clear();
					goodMoves.append(&tileMove);
				}
				else if (surroundingTiles == best)
				{
					goodMoves.append(&tileMove);
				}
			}

			for (uchar i = 0, c = tile->getNodeCount(); i < c; ++i)
			{
				if (tile->getNode(i)->getTerrain() == Cloister)
				{
					meepleMove.nodeIndex = i;
					meepleMoveSet = true;
					break;
				}
			}

			return *goodMoves[r.nextInt(goodMoves.size())];
#endif
		}
		else
		{
#if SIMPLE_PLAYER_RULE_CLOISTER_2
			VarLengthArrayWrapper<TileMove const *, TILE_ARRAY_LENGTH>::type goodMoves;
			int best = -10;
			for (TileMove const & tileMove : possible)
			{
				int points = 0;
				for (int i = 0; i < 8; ++i)
				{
					Tile const * t = board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]);
					if (t != 0)
					{
						Node const * n = t->getCloisterNode();
						if (n != 0 && n->getMaxMeeples() != 0)
						{
							if (n->getPlayerMeeples(player) != 0)
								points += myBonus;
							else
								points -= opponentBonus;
						}
					}
				}
				if (points > best)
				{
					best = points;
					goodMoves.clear();
					goodMoves.append(&tileMove);
				}
				else if (points == best)
				{
					goodMoves.append(&tileMove);
				}
			}

			return *goodMoves[r.nextInt(goodMoves.size())];
#endif
		}
	}
	else // No cloister tile
	{
#if  SIMPLE_PLAYER_RULE_ROAD_CITY
		VarLengthArrayWrapper<Move, TILE_ARRAY_LENGTH * NODE_ARRAY_LENGTH>::type goodMoves;
		int best = std::numeric_limits<int>::min();
		for (TileMove const & tileMove : possible)
		{
			int points = 0;
			VarLengthArrayWrapper<MeepleMove, TILE_ARRAY_LENGTH>::type meepleMoves(1);
			int bestNodePoints = 0; //std::numeric_limits<int>::min();
			for (int i = 0; i < 4; ++i)
			{
				Tile const * t = board->getTile(tileMove.x + dx[i], tileMove.y + dy[i]);
				if (t == 0)
					continue;

				Tile::Side const & oppDirection = oppDir[i];
				TerrainType const & type = t->getEdge(oppDirection);
				if (type == Field)	//TODO Fields
					continue;
				//else Cities and Roads

				Tile::Side const & direction = dir[i];
				Q_ASSERT(type == tile->getEdge(direction, tileMove.orientation));

				uchar nodeIndex;
				Node const * nn = tile->getFeatureNodeAndIndex(direction, nodeIndex, tileMove.orientation);
				Node const * on = t->getFeatureNode(oppDirection);
				Q_ASSERT(nn != 0);
				Q_ASSERT(on != 0);
				Q_ASSERT(nodeIndex != uchar(-1));
				Q_ASSERT(on->getTerrain() == nn->getTerrain());

				int const score = nn->getScore() + on->getScore();
				uchar const max = on->getMaxMeeples();
				if (max != 0) //isOccupied
				{
					for (uint p = 0; p < game->getPlayerCount(); ++p)
					{
						if (on->getPlayerMeeples(p) != max)
							continue;
						if (p == (uint)player)
							points += myBonus*score;
						else
							points -= opponentBonus * score;
					}
				}
				else if (hasMeeples)
				{
					int nodePoints = myBonus*score - meeplePenalty;
					switch (type)
					{
						case City:
							nodePoints *= 3;
							break;
						case Road:
							nodePoints *= 2;
							break;
						case Field:
						case Cloister:
						case None:
							Q_UNREACHABLE();
							break;
					}

					if (nodePoints > bestNodePoints)
					{
						bestNodePoints = nodePoints;
						meepleMoves.clear();
						meepleMoves.push_back(MeepleMove{nodeIndex});
					}
					else if (nodePoints == bestNodePoints)
					{
						meepleMoves.append(MeepleMove{nodeIndex});
					}
				}

				switch (type)
				{
					case City:
						points *= 3;
						break;
					case Road:
						points *= 2;
						break;
					case Field:
					case Cloister:
					case None:
						Q_UNREACHABLE();
						break;
				}
			}

			points += bestNodePoints;
			if (points > best)
			{
				best = points;
				goodMoves.clear();
				for (MeepleMove const & mm : meepleMoves)
					goodMoves.push_back(Move{tileMove, mm});
			}
			else if (points == best)
			{
				for (MeepleMove const & mm : meepleMoves)
					goodMoves.push_back(Move{tileMove, mm});
			}
		}

		Move const & m = goodMoves[r.nextInt(goodMoves.size())];
		meepleMove = m.meepleMove;
		meepleMoveSet = true;
		return m.tileMove;
#endif
	}
	return RandomPlayer::instance.getTileMove(player, tile, move, possible);
}

MeepleMove SimplePlayer::getMeepleMove(int player, const Tile * tile, const MoveHistoryEntry & move, const MeepleMovesType & possible)
{
	if (meepleMoveSet && std::find(possible.cbegin(), possible.cend(), meepleMove) != possible.cend())
		return meepleMove;
	return RandomPlayer::instance.getMeepleMove(player, tile, move, possible);
}

void SimplePlayer::endGame()
{
}

QString SimplePlayer::getTypeName()
{
	return "SimplePlayer";
}

Player *SimplePlayer::clone() const
{
	return new SimplePlayer();
}
<|endoftext|>


<commit_before>
/***************************************************************************/
/**
**  @file
**  @brief definition of ParamMMFS_t
*/
/***************************************************************************/

#include <math.h>
#include "../tListInputData/tListInputData.h"
#include "ParamMesh_t.h"

ParamMMFS_t::ParamMMFS_t(tInputFile &infile) :
  kSloped(0),
  xout(0), yout(0)
{
  //reads in size of mesh (meters)
  xGrid = infile.ReadItem( xGrid, "X_GRID_SIZE" );
  yGrid = infile.ReadItem( yGrid, "Y_GRID_SIZE" );
  //read type of open boundary:
  //  0 = corner outlet (lower left)
  //  1 = one open side (lower)
  //  2 = two opposite sides (upper and lower)
  //  3 = all sides
  //  4 = specify outlet coordinates
  boundType = infile.ReadItem( boundType, "TYP_BOUND" );
   //ng 12/99 added so that the initial surface could be sloped
   //with one side open bndry cndtn if kSloped = 1.
   if(boundType == kOpenSide){
      kSloped = infile.ReadItem( kSloped, "SLOPED_SURF" );
      if(kSloped)
          upperZ = infile.ReadItem( upperZ, "UPPER_BOUND_Z" );
   }
   //read mean elevation & amplitude for random variation in elevation
   mElev = infile.ReadItem( mElev, "MEAN_ELEV" );
   randElev = infile.ReadItem( randElev, "RAND_ELEV" );
   //reads method of point placement:
   //  0 = uniform grid;
   //  1 = perturbed grid;
   //  2 = random scatter;
   ptPlace = infile.ReadItem( ptPlace, "OPT_PT_PLACE" );
   //read point spacing or number of points (excluding four boundary points)
   if( ptPlace == kUniformMesh || ptPlace == kPerturbedMesh )
     {
       delGrid = infile.ReadItem( delGrid, "GRID_SPACING" );
       if( delGrid >= xGrid || delGrid >= yGrid )
	 ReportFatalError(
			  "Mesh point spacing must be smaller than total mesh width." );
     }
   else
     {
       numPts = infile.ReadItem( numPts, "NUM_PTS" );
       delGrid = sqrt( xGrid * yGrid / numPts );
     }
   if( boundType == kOppositeSidesOpen )
     {
       upperZ = infile.ReadItem( upperZ, "UPPER_BOUND_Z" );
     }
   else if( boundType == kSpecifyOutlet )
     {
       // Read outlet coordinates from input file
       xout = infile.ReadItem( xout, "OUTLET_X_COORD" );
       yout = infile.ReadItem( yout, "OUTLET_Y_COORD" );
     }
}

<commit_msg>Sloping initial surface now allowed for any boundary configuration, not just 1-side open<commit_after>
/***************************************************************************/
/**
**  @file
**  @brief definition of ParamMMFS_t
*/
/***************************************************************************/

#include <math.h>
#include "../tListInputData/tListInputData.h"
#include "ParamMesh_t.h"

ParamMMFS_t::ParamMMFS_t(tInputFile &infile) :
  kSloped(0),
  xout(0), yout(0)
{
  //reads in size of mesh (meters)
  xGrid = infile.ReadItem( xGrid, "X_GRID_SIZE" );
  yGrid = infile.ReadItem( yGrid, "Y_GRID_SIZE" );
  //read type of open boundary:
  //  0 = corner outlet (lower left)
  //  1 = one open side (lower)
  //  2 = two opposite sides (upper and lower)
  //  3 = all sides
  //  4 = specify outlet coordinates
  boundType = infile.ReadItem( boundType, "TYP_BOUND" );
   //ng 12/99 added so that the initial surface could be sloped
   //with one side open bndry cndtn if kSloped = 1.
  //if(boundType == kOpenSide){
      kSloped = infile.ReadItem( kSloped, "SLOPED_SURF" );
      if(kSloped)
          upperZ = infile.ReadItem( upperZ, "UPPER_BOUND_Z" );
      //}
   //read mean elevation & amplitude for random variation in elevation
   mElev = infile.ReadItem( mElev, "MEAN_ELEV" );
   randElev = infile.ReadItem( randElev, "RAND_ELEV" );
   //reads method of point placement:
   //  0 = uniform grid;
   //  1 = perturbed grid;
   //  2 = random scatter;
   ptPlace = infile.ReadItem( ptPlace, "OPT_PT_PLACE" );
   //read point spacing or number of points (excluding four boundary points)
   if( ptPlace == kUniformMesh || ptPlace == kPerturbedMesh )
     {
       delGrid = infile.ReadItem( delGrid, "GRID_SPACING" );
       if( delGrid >= xGrid || delGrid >= yGrid )
	 ReportFatalError(
			  "Mesh point spacing must be smaller than total mesh width." );
     }
   else
     {
       numPts = infile.ReadItem( numPts, "NUM_PTS" );
       delGrid = sqrt( xGrid * yGrid / numPts );
     }
   if( boundType == kOppositeSidesOpen )
     {
       upperZ = infile.ReadItem( upperZ, "UPPER_BOUND_Z" );
     }
   else if( boundType == kSpecifyOutlet )
     {
       // Read outlet coordinates from input file
       xout = infile.ReadItem( xout, "OUTLET_X_COORD" );
       yout = infile.ReadItem( yout, "OUTLET_Y_COORD" );
     }
}

<|endoftext|>


<commit_before>#include "ocu.h"
#include <cuda.h>
#include <nvrtc.h>

#ifdef __USE_CUDA__

ocu_args_d_t& getOcu(void)
{
    static bool bInit = false;
    static ocu_args_d_t ocu;

    if (bInit == true) return ocu;

    bInit = true;

    CUresult err = cuInit(0);
    LOG_CU_RESULT(err);
    CUdevice dev = 0;
    CUcontext ctxt;
    CUstream  stream;

    err = cuCtxCreate(&ctxt, CU_CTX_SCHED_BLOCKING_SYNC, dev);
    LOG_CU_RESULT(err);

    char name[1024];
    int proc_count = 0;
    int thread_count = 0;
    int cap_major = 0, cap_minor = 0;
    cuDeviceGetName(name, sizeof(name), dev);
    cuDeviceGetAttribute(&cap_major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev);
    cuDeviceGetAttribute(&cap_minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
    cuDeviceGetAttribute(&proc_count, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev);
    cuDeviceGetAttribute(&thread_count, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev);
    LogError("CUDA Adapter:%s Ver%d.%d MP %d MaxThread Per MP %d)\r\n", name, cap_major, cap_minor, proc_count, thread_count);
/*
    char* source = nullptr;
    size_t src_size = 0;
    ReadSourceFromFile("clguetzli/clguetzli.cl", &source, &src_size);

    nvrtcProgram prog;
    const char *opts[] = { "-arch=compute_30", "-default-device", "-G", "-I\"./\"", "--fmad=false" };
    nvrtcCreateProgram(&prog, source, "clguetzli.cl", 0, NULL, NULL);
    nvrtcResult compile_result;// = nvrtcCompileProgram(prog, 3, opts);
    if (NVRTC_SUCCESS != compile_result)
    {
        // Obtain compilation log from the program.
        size_t logSize = 0;
        nvrtcGetProgramLogSize(prog, &logSize);
        char *log = new char[logSize];
        nvrtcGetProgramLog(prog, log);

        LogError("BuildInfo:\r\n%s\r\n", log);

        delete[] log;
    }

    delete[] source;
    // Obtain PTX from the program.
    size_t ptxSize = 0;
    nvrtcGetPTXSize(prog, &ptxSize);
    char *ptx = new char[ptxSize];
    nvrtcGetPTX(prog, ptx);
*/

    char* ptx = nullptr;
    size_t src_size = 0;
#ifdef _WIN64
    ReadSourceFromFile("clguetzli/clguetzli.cu.ptx64", &ptx, &src_size);
#else
    ReadSourceFromFile("clguetzli/clguetzli.cu.ptx32", &ptx, &src_size);
#endif

    CUmodule mod;
    CUjit_option jit_options[2];
    void *jit_optvals[2];
    jit_options[0] = CU_JIT_CACHE_MODE;
    jit_optvals[0] = (void*)(uintptr_t)CU_JIT_CACHE_OPTION_CA;
    err = cuModuleLoadDataEx(&mod, ptx, 1, jit_options, jit_optvals);
    LOG_CU_RESULT(err);

    delete[] ptx;

    cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTION], mod, "clConvolutionEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONX], mod, "clConvolutionXEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONY], mod, "clConvolutionYEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_SQUARESAMPLE], mod, "clSquareSampleEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_OPSINDYNAMICSIMAGE], mod, "clOpsinDynamicsImageEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_MASKHIGHINTENSITYCHANGE], mod, "clMaskHighIntensityChangeEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTOR], mod, "clEdgeDetectorMapEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_BLOCKDIFFMAP], mod, "clBlockDiffMapEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTORLOWFREQ], mod, "clEdgeDetectorLowFreqEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_DIFFPRECOMPUTE], mod, "clDiffPrecomputeEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_SCALEIMAGE], mod, "clScaleImageEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_AVERAGE5X5], mod, "clAverage5x5Ex");
    cuModuleGetFunction(&ocu.kernel[KERNEL_MINSQUAREVAL], mod, "clMinSquareValEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_DOMASK], mod, "clDoMaskEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_COMBINECHANNELS], mod, "clCombineChannelsEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_UPSAMPLESQUAREROOT], mod, "clUpsampleSquareRootEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_REMOVEBORDER], mod, "clRemoveBorderEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_ADDBORDER], mod, "clAddBorderEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_COMPUTEBLOCKZEROINGORDER], mod, "clComputeBlockZeroingOrderEx");

    cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_SHARED);
    cuCtxSetSharedMemConfig(CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE);

    cuStreamCreate(&stream, 0);

    ocu.dev = dev;
    ocu.commandQueue = stream;
    ocu.mod = mod;
    ocu.ctxt = ctxt;

    return ocu;
}

ocu_args_d_t::ocu_args_d_t()
    : dev(0)
    , commandQueue(NULL)
    , mod(NULL)
    , ctxt(NULL)
{

}

ocu_args_d_t::~ocu_args_d_t()
{
    cuModuleUnload(mod);
    cuCtxDestroy(ctxt);
//    cuStreamDestroy(commandQueue);
}

cu_mem ocu_args_d_t::allocMem(size_t s, const void *init)
{
    cu_mem mem;
    cuMemAlloc(&mem, s);
    if (init)
    {
        cuMemcpyHtoDAsync(mem, init, s, commandQueue);
    }
    else
    {
        cuMemsetD8Async(mem, 0, s, commandQueue);
    }

    return mem;
}

ocu_channels ocu_args_d_t::allocMemChannels(size_t s, const void *c0, const void *c1, const void *c2)
{
    const void *c[3] = { c0, c1, c2 };

    ocu_channels img;
    for (int i = 0; i < 3; i++)
    {
        img.ch[i] = allocMem(s, c[i]);
    }

    return img;
}

void ocu_args_d_t::releaseMemChannels(ocu_channels &rgb)
{
    for (int i = 0; i < 3; i++)
    {
        cuMemFree(rgb.ch[i]);
        rgb.ch[i] = NULL;
    }
}

const char* TranslateCUDAError(CUresult errorCode)
{
    switch (errorCode)
    {
    case CUDA_SUCCESS: return "CUDA_SUCCESS";
    case CUDA_ERROR_INVALID_VALUE: return "CUDA_ERROR_INVALID_VALUE";
    case CUDA_ERROR_OUT_OF_MEMORY: return "CUDA_ERROR_OUT_OF_MEMORY";
    case CUDA_ERROR_NOT_INITIALIZED: return "CUDA_ERROR_NOT_INITIALIZED";
    case CUDA_ERROR_DEINITIALIZED: return "CUDA_ERROR_DEINITIALIZED";
    case CUDA_ERROR_PROFILER_DISABLED: return "CUDA_ERROR_PROFILER_DISABLED";
    case CUDA_ERROR_PROFILER_NOT_INITIALIZED: return "CUDA_ERROR_PROFILER_NOT_INITIALIZED";
    case CUDA_ERROR_PROFILER_ALREADY_STARTED: return "CUDA_ERROR_PROFILER_ALREADY_STARTED";
    case CUDA_ERROR_PROFILER_ALREADY_STOPPED: return "CUDA_ERROR_PROFILER_ALREADY_STOPPED";
    case CUDA_ERROR_NO_DEVICE: return "CUDA_ERROR_NO_DEVICE";
    case CUDA_ERROR_INVALID_DEVICE: return "CUDA_ERROR_INVALID_DEVICE";
    case CUDA_ERROR_INVALID_IMAGE: return "CUDA_ERROR_INVALID_IMAGE";
    case CUDA_ERROR_INVALID_CONTEXT: return "CUDA_ERROR_INVALID_CONTEXT";
    case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "CUDA_ERROR_CONTEXT_ALREADY_CURRENT";
    case CUDA_ERROR_MAP_FAILED: return "CUDA_ERROR_MAP_FAILED";
    case CUDA_ERROR_UNMAP_FAILED: return "CUDA_ERROR_UNMAP_FAILED";
    case CUDA_ERROR_ARRAY_IS_MAPPED: return "CUDA_ERROR_ARRAY_IS_MAPPED";
    case CUDA_ERROR_ALREADY_MAPPED: return "CUDA_ERROR_ALREADY_MAPPED";
    case CUDA_ERROR_NO_BINARY_FOR_GPU: return "CUDA_ERROR_NO_BINARY_FOR_GPU";
    case CUDA_ERROR_ALREADY_ACQUIRED: return "CUDA_ERROR_ALREADY_ACQUIRED";
    case CUDA_ERROR_NOT_MAPPED: return "CUDA_ERROR_NOT_MAPPED";
    case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "CUDA_ERROR_NOT_MAPPED_AS_ARRAY";
    case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "CUDA_ERROR_NOT_MAPPED_AS_POINTER";
    case CUDA_ERROR_ECC_UNCORRECTABLE: return "CUDA_ERROR_ECC_UNCORRECTABLE";
    case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUDA_ERROR_UNSUPPORTED_LIMIT";
    case CUDA_ERROR_CONTEXT_ALREADY_IN_USE: return "CUDA_ERROR_CONTEXT_ALREADY_IN_USE";
    case CUDA_ERROR_PEER_ACCESS_UNSUPPORTED: return "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED";
    case CUDA_ERROR_INVALID_PTX: return "CUDA_ERROR_INVALID_PTX";
    case CUDA_ERROR_INVALID_GRAPHICS_CONTEXT: return "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT";
    case CUDA_ERROR_NVLINK_UNCORRECTABLE: return "CUDA_ERROR_NVLINK_UNCORRECTABLE";
    case CUDA_ERROR_INVALID_SOURCE: return "CUDA_ERROR_INVALID_SOURCE";
    case CUDA_ERROR_FILE_NOT_FOUND: return "CUDA_ERROR_FILE_NOT_FOUND";
    case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND";
    case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED";
    case CUDA_ERROR_OPERATING_SYSTEM: return "CUDA_ERROR_OPERATING_SYSTEM";
    case CUDA_ERROR_INVALID_HANDLE: return "CUDA_ERROR_INVALID_HANDLE";
    case CUDA_ERROR_NOT_FOUND: return "CUDA_ERROR_NOT_FOUND";
    case CUDA_ERROR_NOT_READY: return "CUDA_ERROR_NOT_READY";
    case CUDA_ERROR_ILLEGAL_ADDRESS: return "CUDA_ERROR_ILLEGAL_ADDRESS";
    case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES";
    case CUDA_ERROR_LAUNCH_TIMEOUT: return "CUDA_ERROR_LAUNCH_TIMEOUT";
    case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING";
    case CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED: return "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED";
    case CUDA_ERROR_PEER_ACCESS_NOT_ENABLED: return "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED";
    case CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE: return "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE";
    case CUDA_ERROR_CONTEXT_IS_DESTROYED: return "CUDA_ERROR_CONTEXT_IS_DESTROYED";
    case CUDA_ERROR_ASSERT: return "CUDA_ERROR_ASSERT";
    case CUDA_ERROR_TOO_MANY_PEERS: return "CUDA_ERROR_TOO_MANY_PEERS";
    case CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED";
    case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED";
    case CUDA_ERROR_HARDWARE_STACK_ERROR: return "CUDA_ERROR_HARDWARE_STACK_ERROR";
    case CUDA_ERROR_ILLEGAL_INSTRUCTION: return "CUDA_ERROR_ILLEGAL_INSTRUCTION";
    case CUDA_ERROR_MISALIGNED_ADDRESS: return "CUDA_ERROR_MISALIGNED_ADDRESS";
    case CUDA_ERROR_INVALID_ADDRESS_SPACE: return "CUDA_ERROR_INVALID_ADDRESS_SPACE";
    case CUDA_ERROR_INVALID_PC: return "CUDA_ERROR_INVALID_PC";
    case CUDA_ERROR_LAUNCH_FAILED: return "CUDA_ERROR_LAUNCH_FAILED";
    case CUDA_ERROR_NOT_PERMITTED: return "CUDA_ERROR_NOT_PERMITTED";
    case CUDA_ERROR_NOT_SUPPORTED: return "CUDA_ERROR_NOT_SUPPORTED";
    case CUDA_ERROR_UNKNOWN: return "CUDA_ERROR_UNKNOWN";
    default: return "CUDA_ERROR_UNKNOWN";
    }
}
#endif<commit_msg>修正64、32位判断的宏<commit_after>#include "ocu.h"
#include <cuda.h>
#include <nvrtc.h>

#ifdef __USE_CUDA__

ocu_args_d_t& getOcu(void)
{
    static bool bInit = false;
    static ocu_args_d_t ocu;

    if (bInit == true) return ocu;

    bInit = true;

    CUresult err = cuInit(0);
    LOG_CU_RESULT(err);
    CUdevice dev = 0;
    CUcontext ctxt;
    CUstream  stream;

    err = cuCtxCreate(&ctxt, CU_CTX_SCHED_BLOCKING_SYNC, dev);
    LOG_CU_RESULT(err);

    char name[1024];
    int proc_count = 0;
    int thread_count = 0;
    int cap_major = 0, cap_minor = 0;
    cuDeviceGetName(name, sizeof(name), dev);
    cuDeviceGetAttribute(&cap_major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev);
    cuDeviceGetAttribute(&cap_minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
    cuDeviceGetAttribute(&proc_count, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev);
    cuDeviceGetAttribute(&thread_count, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev);
    LogError("CUDA Adapter:%s Ver%d.%d MP %d MaxThread Per MP %d)\r\n", name, cap_major, cap_minor, proc_count, thread_count);
/*
    char* source = nullptr;
    size_t src_size = 0;
    ReadSourceFromFile("clguetzli/clguetzli.cl", &source, &src_size);

    nvrtcProgram prog;
    const char *opts[] = { "-arch=compute_30", "-default-device", "-G", "-I\"./\"", "--fmad=false" };
    nvrtcCreateProgram(&prog, source, "clguetzli.cl", 0, NULL, NULL);
    nvrtcResult compile_result;// = nvrtcCompileProgram(prog, 3, opts);
    if (NVRTC_SUCCESS != compile_result)
    {
        // Obtain compilation log from the program.
        size_t logSize = 0;
        nvrtcGetProgramLogSize(prog, &logSize);
        char *log = new char[logSize];
        nvrtcGetProgramLog(prog, log);

        LogError("BuildInfo:\r\n%s\r\n", log);

        delete[] log;
    }

    delete[] source;
    // Obtain PTX from the program.
    size_t ptxSize = 0;
    nvrtcGetPTXSize(prog, &ptxSize);
    char *ptx = new char[ptxSize];
    nvrtcGetPTX(prog, ptx);
*/

    char* ptx = nullptr;
    size_t src_size = 0;
if (sizeof(void*) == 8)
    ReadSourceFromFile("clguetzli/clguetzli.cu.ptx64", &ptx, &src_size);
else
    ReadSourceFromFile("clguetzli/clguetzli.cu.ptx32", &ptx, &src_size);

    CUmodule mod;
    CUjit_option jit_options[2];
    void *jit_optvals[2];
    jit_options[0] = CU_JIT_CACHE_MODE;
    jit_optvals[0] = (void*)(uintptr_t)CU_JIT_CACHE_OPTION_CA;
    err = cuModuleLoadDataEx(&mod, ptx, 1, jit_options, jit_optvals);
    LOG_CU_RESULT(err);

    delete[] ptx;

    cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTION], mod, "clConvolutionEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONX], mod, "clConvolutionXEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_CONVOLUTIONY], mod, "clConvolutionYEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_SQUARESAMPLE], mod, "clSquareSampleEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_OPSINDYNAMICSIMAGE], mod, "clOpsinDynamicsImageEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_MASKHIGHINTENSITYCHANGE], mod, "clMaskHighIntensityChangeEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTOR], mod, "clEdgeDetectorMapEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_BLOCKDIFFMAP], mod, "clBlockDiffMapEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_EDGEDETECTORLOWFREQ], mod, "clEdgeDetectorLowFreqEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_DIFFPRECOMPUTE], mod, "clDiffPrecomputeEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_SCALEIMAGE], mod, "clScaleImageEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_AVERAGE5X5], mod, "clAverage5x5Ex");
    cuModuleGetFunction(&ocu.kernel[KERNEL_MINSQUAREVAL], mod, "clMinSquareValEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_DOMASK], mod, "clDoMaskEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_COMBINECHANNELS], mod, "clCombineChannelsEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_UPSAMPLESQUAREROOT], mod, "clUpsampleSquareRootEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_REMOVEBORDER], mod, "clRemoveBorderEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_ADDBORDER], mod, "clAddBorderEx");
    cuModuleGetFunction(&ocu.kernel[KERNEL_COMPUTEBLOCKZEROINGORDER], mod, "clComputeBlockZeroingOrderEx");

    cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_SHARED);
    cuCtxSetSharedMemConfig(CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE);

    cuStreamCreate(&stream, 0);

    ocu.dev = dev;
    ocu.commandQueue = stream;
    ocu.mod = mod;
    ocu.ctxt = ctxt;

    return ocu;
}

ocu_args_d_t::ocu_args_d_t()
    : dev(0)
    , commandQueue(NULL)
    , mod(NULL)
    , ctxt(NULL)
{

}

ocu_args_d_t::~ocu_args_d_t()
{
    cuModuleUnload(mod);
    cuCtxDestroy(ctxt);
//    cuStreamDestroy(commandQueue);
}

cu_mem ocu_args_d_t::allocMem(size_t s, const void *init)
{
    cu_mem mem;
    cuMemAlloc(&mem, s);
    if (init)
    {
        cuMemcpyHtoDAsync(mem, init, s, commandQueue);
    }
    else
    {
        cuMemsetD8Async(mem, 0, s, commandQueue);
    }

    return mem;
}

ocu_channels ocu_args_d_t::allocMemChannels(size_t s, const void *c0, const void *c1, const void *c2)
{
    const void *c[3] = { c0, c1, c2 };

    ocu_channels img;
    for (int i = 0; i < 3; i++)
    {
        img.ch[i] = allocMem(s, c[i]);
    }

    return img;
}

void ocu_args_d_t::releaseMemChannels(ocu_channels &rgb)
{
    for (int i = 0; i < 3; i++)
    {
        cuMemFree(rgb.ch[i]);
        rgb.ch[i] = NULL;
    }
}

const char* TranslateCUDAError(CUresult errorCode)
{
    switch (errorCode)
    {
    case CUDA_SUCCESS: return "CUDA_SUCCESS";
    case CUDA_ERROR_INVALID_VALUE: return "CUDA_ERROR_INVALID_VALUE";
    case CUDA_ERROR_OUT_OF_MEMORY: return "CUDA_ERROR_OUT_OF_MEMORY";
    case CUDA_ERROR_NOT_INITIALIZED: return "CUDA_ERROR_NOT_INITIALIZED";
    case CUDA_ERROR_DEINITIALIZED: return "CUDA_ERROR_DEINITIALIZED";
    case CUDA_ERROR_PROFILER_DISABLED: return "CUDA_ERROR_PROFILER_DISABLED";
    case CUDA_ERROR_PROFILER_NOT_INITIALIZED: return "CUDA_ERROR_PROFILER_NOT_INITIALIZED";
    case CUDA_ERROR_PROFILER_ALREADY_STARTED: return "CUDA_ERROR_PROFILER_ALREADY_STARTED";
    case CUDA_ERROR_PROFILER_ALREADY_STOPPED: return "CUDA_ERROR_PROFILER_ALREADY_STOPPED";
    case CUDA_ERROR_NO_DEVICE: return "CUDA_ERROR_NO_DEVICE";
    case CUDA_ERROR_INVALID_DEVICE: return "CUDA_ERROR_INVALID_DEVICE";
    case CUDA_ERROR_INVALID_IMAGE: return "CUDA_ERROR_INVALID_IMAGE";
    case CUDA_ERROR_INVALID_CONTEXT: return "CUDA_ERROR_INVALID_CONTEXT";
    case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "CUDA_ERROR_CONTEXT_ALREADY_CURRENT";
    case CUDA_ERROR_MAP_FAILED: return "CUDA_ERROR_MAP_FAILED";
    case CUDA_ERROR_UNMAP_FAILED: return "CUDA_ERROR_UNMAP_FAILED";
    case CUDA_ERROR_ARRAY_IS_MAPPED: return "CUDA_ERROR_ARRAY_IS_MAPPED";
    case CUDA_ERROR_ALREADY_MAPPED: return "CUDA_ERROR_ALREADY_MAPPED";
    case CUDA_ERROR_NO_BINARY_FOR_GPU: return "CUDA_ERROR_NO_BINARY_FOR_GPU";
    case CUDA_ERROR_ALREADY_ACQUIRED: return "CUDA_ERROR_ALREADY_ACQUIRED";
    case CUDA_ERROR_NOT_MAPPED: return "CUDA_ERROR_NOT_MAPPED";
    case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "CUDA_ERROR_NOT_MAPPED_AS_ARRAY";
    case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "CUDA_ERROR_NOT_MAPPED_AS_POINTER";
    case CUDA_ERROR_ECC_UNCORRECTABLE: return "CUDA_ERROR_ECC_UNCORRECTABLE";
    case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUDA_ERROR_UNSUPPORTED_LIMIT";
    case CUDA_ERROR_CONTEXT_ALREADY_IN_USE: return "CUDA_ERROR_CONTEXT_ALREADY_IN_USE";
    case CUDA_ERROR_PEER_ACCESS_UNSUPPORTED: return "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED";
    case CUDA_ERROR_INVALID_PTX: return "CUDA_ERROR_INVALID_PTX";
    case CUDA_ERROR_INVALID_GRAPHICS_CONTEXT: return "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT";
    case CUDA_ERROR_NVLINK_UNCORRECTABLE: return "CUDA_ERROR_NVLINK_UNCORRECTABLE";
    case CUDA_ERROR_INVALID_SOURCE: return "CUDA_ERROR_INVALID_SOURCE";
    case CUDA_ERROR_FILE_NOT_FOUND: return "CUDA_ERROR_FILE_NOT_FOUND";
    case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND";
    case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED";
    case CUDA_ERROR_OPERATING_SYSTEM: return "CUDA_ERROR_OPERATING_SYSTEM";
    case CUDA_ERROR_INVALID_HANDLE: return "CUDA_ERROR_INVALID_HANDLE";
    case CUDA_ERROR_NOT_FOUND: return "CUDA_ERROR_NOT_FOUND";
    case CUDA_ERROR_NOT_READY: return "CUDA_ERROR_NOT_READY";
    case CUDA_ERROR_ILLEGAL_ADDRESS: return "CUDA_ERROR_ILLEGAL_ADDRESS";
    case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES";
    case CUDA_ERROR_LAUNCH_TIMEOUT: return "CUDA_ERROR_LAUNCH_TIMEOUT";
    case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING";
    case CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED: return "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED";
    case CUDA_ERROR_PEER_ACCESS_NOT_ENABLED: return "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED";
    case CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE: return "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE";
    case CUDA_ERROR_CONTEXT_IS_DESTROYED: return "CUDA_ERROR_CONTEXT_IS_DESTROYED";
    case CUDA_ERROR_ASSERT: return "CUDA_ERROR_ASSERT";
    case CUDA_ERROR_TOO_MANY_PEERS: return "CUDA_ERROR_TOO_MANY_PEERS";
    case CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED";
    case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED";
    case CUDA_ERROR_HARDWARE_STACK_ERROR: return "CUDA_ERROR_HARDWARE_STACK_ERROR";
    case CUDA_ERROR_ILLEGAL_INSTRUCTION: return "CUDA_ERROR_ILLEGAL_INSTRUCTION";
    case CUDA_ERROR_MISALIGNED_ADDRESS: return "CUDA_ERROR_MISALIGNED_ADDRESS";
    case CUDA_ERROR_INVALID_ADDRESS_SPACE: return "CUDA_ERROR_INVALID_ADDRESS_SPACE";
    case CUDA_ERROR_INVALID_PC: return "CUDA_ERROR_INVALID_PC";
    case CUDA_ERROR_LAUNCH_FAILED: return "CUDA_ERROR_LAUNCH_FAILED";
    case CUDA_ERROR_NOT_PERMITTED: return "CUDA_ERROR_NOT_PERMITTED";
    case CUDA_ERROR_NOT_SUPPORTED: return "CUDA_ERROR_NOT_SUPPORTED";
    case CUDA_ERROR_UNKNOWN: return "CUDA_ERROR_UNKNOWN";
    default: return "CUDA_ERROR_UNKNOWN";
    }
}
#endif<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include "otbPlaceNameToLonLat.h"
#include "otbTinyXML.h"
#include "otbCurlHelper.h"

namespace otb
{

PlaceNameToLonLat::PlaceNameToLonLat() :
      m_Lon(-1000.0), m_Lat(-1000.0),
      m_PlaceName("Where everything started"),
      m_RequestSucceed(false)
{
  m_Curl = CurlHelper::New();
}

void
PlaceNameToLonLat
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << " m_Lon "  << m_Lon << std::endl;
  os << indent << " m_Lat "  << m_Lat << std::endl;
  os << indent << " m_PlaceName "  << m_PlaceName << std::endl;
}

bool PlaceNameToLonLat::Evaluate()
{
  std::string::size_type loc = m_PlaceName.find(" ", 0);
  while (loc != std::string::npos)
    {
    m_PlaceName.replace(loc, 1, "+");
    loc = m_PlaceName.find(" ", loc);
    }
  // TODO : replace unsafe ASCII character with "%" followed by their hex equivalent

  // Geonames service
  if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
    {
    std::ostringstream urlStream;
    urlStream << "http://api.geonames.org/search?q=";
    urlStream << m_PlaceName;
    urlStream << "&maxRows=1&type=xml&orderby=relevance&username=otbteam";
    RetrieveXML(urlStream);
    if ( m_RequestSucceed )
      ParseXMLGeonames();
    }

  // Google Maps service
  // if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
  //   {
  //   std::ostringstream urlStream;
  //   urlStream << "http://maps.google.com/maps?q=";
  //   urlStream << m_PlaceName;
  //   urlStream << "&sll=38.9594,-95.2655&sspn=119.526,360&output=kml&ie=utf-8&v=2.2&cv=4.2.0180.1134&hl=en";
  //   RetrieveXML(urlStream);
  //   if ( m_RequestSucceed )
  //     ParseXMLGoogle();
  //   }

  // Yahoo new PlaceFinder API need an application ID to be able
  // to use it
  // if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
  //   {
  //   std::ostringstream urlStream;
  //   urlStream << "http://api.local.yahoo.com/MapsService/V1/geocode?appid=com.sun.blueprints.ui.geocoder&location=";
  //   urlStream << m_PlaceName;
  //   RetrieveXML(urlStream);
  //   if ( m_RequestSucceed )
  //     ParseXMLYahoo();
  //   }

  if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
    {
    std::cout << "Search Error: fallback on the origin" << std::endl;
    m_Lat = 43.560204;
    m_Lon = 1.480736;
    return false;
    }
  return true;
}

void PlaceNameToLonLat::RetrieveXML(const std::ostringstream& urlStream)
{
  try
    {
    m_RequestSucceed = true;
    m_Curl->RetrieveUrlInMemory(urlStream.str(), m_CurlOutput);
    }
  catch(itk::ExceptionObject)
    {
    m_RequestSucceed = false;
    }
}

void PlaceNameToLonLat::ParseXMLYahoo()
{
  TiXmlDocument doc;
  doc.Parse(m_CurlOutput.c_str());

  TiXmlHandle docHandle(&doc);
  TiXmlElement* childLat = docHandle.FirstChild("ResultSet").FirstChild("Result").FirstChild("Latitude").Element();
  if (childLat)
    {
    m_Lat = atof(childLat->GetText());
    }
  TiXmlElement* childLon = docHandle.FirstChild("ResultSet").FirstChild("Result").FirstChild("Longitude").Element();
  if (childLon)
    {
    m_Lon = atof(childLon->GetText());
    }
}

void PlaceNameToLonLat::ParseXMLGoogle()
{
  TiXmlDocument doc;
  doc.Parse(m_CurlOutput.c_str());

  TiXmlHandle docHandle(&doc);
  TiXmlElement* childLat = docHandle.FirstChild("kml").FirstChild("Placemark").FirstChild("LookAt").FirstChild(
    "latitude").Element();
  if (childLat)
    {
    m_Lat = atof(childLat->GetText());
    }
  TiXmlElement* childLon = docHandle.FirstChild("kml").FirstChild("Placemark").FirstChild("LookAt").FirstChild(
    "longitude").Element();
  if (childLon)
    {
    m_Lon = atof(childLon->GetText());
    }
}

void PlaceNameToLonLat::ParseXMLGeonames()
{
  TiXmlDocument doc;
  doc.Parse(m_CurlOutput.c_str());

  TiXmlHandle docHandle(&doc);
  TiXmlElement* childLat = docHandle.FirstChild("geonames").FirstChild("geoname").FirstChild("lat").Element();
  if (childLat)
    {
    m_Lat = atof(childLat->GetText());
    }
  TiXmlElement* childLon = docHandle.FirstChild("geonames").FirstChild("geoname").FirstChild("lng").Element();
  if (childLon)
    {
    m_Lon = atof(childLon->GetText());
    }
}

} // namespace otb
<commit_msg>COV: Fixing coverity issues (uninitialized scalar field)<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include "otbPlaceNameToLonLat.h"
#include "otbTinyXML.h"
#include "otbCurlHelper.h"

namespace otb
{

PlaceNameToLonLat::PlaceNameToLonLat() :
      m_Lon(-1000.0), m_Lat(-1000.0),
      m_PlaceName("Where everything started"),
      m_SearchMethod(PlaceNameToLonLat::ALL),
      m_RequestSucceed(false)
{
  m_Curl = CurlHelper::New();
}

void
PlaceNameToLonLat
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << " m_Lon "  << m_Lon << std::endl;
  os << indent << " m_Lat "  << m_Lat << std::endl;
  os << indent << " m_PlaceName "  << m_PlaceName << std::endl;
}

bool PlaceNameToLonLat::Evaluate()
{
  std::string::size_type loc = m_PlaceName.find(" ", 0);
  while (loc != std::string::npos)
    {
    m_PlaceName.replace(loc, 1, "+");
    loc = m_PlaceName.find(" ", loc);
    }
  // TODO : replace unsafe ASCII character with "%" followed by their hex equivalent

  // Geonames service
  if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
    {
    std::ostringstream urlStream;
    urlStream << "http://api.geonames.org/search?q=";
    urlStream << m_PlaceName;
    urlStream << "&maxRows=1&type=xml&orderby=relevance&username=otbteam";
    RetrieveXML(urlStream);
    if ( m_RequestSucceed )
      ParseXMLGeonames();
    }

  // Google Maps service
  // if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
  //   {
  //   std::ostringstream urlStream;
  //   urlStream << "http://maps.google.com/maps?q=";
  //   urlStream << m_PlaceName;
  //   urlStream << "&sll=38.9594,-95.2655&sspn=119.526,360&output=kml&ie=utf-8&v=2.2&cv=4.2.0180.1134&hl=en";
  //   RetrieveXML(urlStream);
  //   if ( m_RequestSucceed )
  //     ParseXMLGoogle();
  //   }

  // Yahoo new PlaceFinder API need an application ID to be able
  // to use it
  // if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
  //   {
  //   std::ostringstream urlStream;
  //   urlStream << "http://api.local.yahoo.com/MapsService/V1/geocode?appid=com.sun.blueprints.ui.geocoder&location=";
  //   urlStream << m_PlaceName;
  //   RetrieveXML(urlStream);
  //   if ( m_RequestSucceed )
  //     ParseXMLYahoo();
  //   }

  if ((m_Lat == -1000.0) && (m_Lon == -1000.0))
    {
    std::cout << "Search Error: fallback on the origin" << std::endl;
    m_Lat = 43.560204;
    m_Lon = 1.480736;
    return false;
    }
  return true;
}

void PlaceNameToLonLat::RetrieveXML(const std::ostringstream& urlStream)
{
  try
    {
    m_RequestSucceed = true;
    m_Curl->RetrieveUrlInMemory(urlStream.str(), m_CurlOutput);
    }
  catch(itk::ExceptionObject)
    {
    m_RequestSucceed = false;
    }
}

void PlaceNameToLonLat::ParseXMLYahoo()
{
  TiXmlDocument doc;
  doc.Parse(m_CurlOutput.c_str());

  TiXmlHandle docHandle(&doc);
  TiXmlElement* childLat = docHandle.FirstChild("ResultSet").FirstChild("Result").FirstChild("Latitude").Element();
  if (childLat)
    {
    m_Lat = atof(childLat->GetText());
    }
  TiXmlElement* childLon = docHandle.FirstChild("ResultSet").FirstChild("Result").FirstChild("Longitude").Element();
  if (childLon)
    {
    m_Lon = atof(childLon->GetText());
    }
}

void PlaceNameToLonLat::ParseXMLGoogle()
{
  TiXmlDocument doc;
  doc.Parse(m_CurlOutput.c_str());

  TiXmlHandle docHandle(&doc);
  TiXmlElement* childLat = docHandle.FirstChild("kml").FirstChild("Placemark").FirstChild("LookAt").FirstChild(
    "latitude").Element();
  if (childLat)
    {
    m_Lat = atof(childLat->GetText());
    }
  TiXmlElement* childLon = docHandle.FirstChild("kml").FirstChild("Placemark").FirstChild("LookAt").FirstChild(
    "longitude").Element();
  if (childLon)
    {
    m_Lon = atof(childLon->GetText());
    }
}

void PlaceNameToLonLat::ParseXMLGeonames()
{
  TiXmlDocument doc;
  doc.Parse(m_CurlOutput.c_str());

  TiXmlHandle docHandle(&doc);
  TiXmlElement* childLat = docHandle.FirstChild("geonames").FirstChild("geoname").FirstChild("lat").Element();
  if (childLat)
    {
    m_Lat = atof(childLat->GetText());
    }
  TiXmlElement* childLon = docHandle.FirstChild("geonames").FirstChild("geoname").FirstChild("lng").Element();
  if (childLon)
    {
    m_Lon = atof(childLon->GetText());
    }
}

} // namespace otb
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
 *
 * This file is part of ZLToolKit(https://github.com/xiongziliang/ZLToolKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

#include "TcpClient.h"

namespace toolkit {

TcpClient::TcpClient(const EventPoller::Ptr &poller) : SocketHelper(nullptr) {
    _poller = poller;
    if(!_poller){
        _poller = EventPollerPool::Instance().getPoller();
    }
}

TcpClient::~TcpClient() {}

void TcpClient::shutdown(const SockException &ex) {
    _managerTimer.reset();
    SocketHelper::shutdown(ex);
}

bool TcpClient::alive() {
    bool ret = _sock.operator bool() && _sock->rawFD() >= 0;
    return ret;
}

void TcpClient::setNetAdapter(const string &localIp){
    _netAdapter = localIp;
}

void TcpClient::startConnect(const string &strUrl, uint16_t iPort,float fTimeOutSec) {
    weak_ptr<TcpClient> weakSelf = shared_from_this();
    _managerTimer.reset();
    _sock = std::make_shared<Socket>(_poller);
    _sock->connect(strUrl, iPort, [weakSelf](const SockException &err){
        auto strongSelf = weakSelf.lock();
        if(strongSelf){
            strongSelf->onSockConnect(err);
        }
    }, fTimeOutSec,_netAdapter.data());
}
void TcpClient::onSockConnect(const SockException &ex) {
    if(ex){
        //连接失败
        _managerTimer.reset();
        onConnect(ex);
        return;
    }

    weak_ptr<TcpClient> weakSelf = shared_from_this();
    auto sock_ptr = _sock.get();
    _sock->setOnErr([weakSelf,sock_ptr](const SockException &ex) {
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return;
        }
        if(sock_ptr != strongSelf->_sock.get()){
            //已经重连socket，上传socket的事件忽略掉
            return;
        }
        strongSelf->_managerTimer.reset();
        strongSelf->onErr(ex);
    });
    _sock->setOnFlush([weakSelf,sock_ptr]() {
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return false;
        }
        if(sock_ptr != strongSelf->_sock.get()){
            //已经重连socket，上传socket的事件忽略掉
            return false;
        }
        strongSelf->onFlush();
        return true;
    });
    _sock->setOnRead([weakSelf,sock_ptr](const Buffer::Ptr &pBuf, struct sockaddr * , int) {
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return;
        }
        if(sock_ptr != strongSelf->_sock.get()){
            //已经重连socket，上传socket的事件忽略掉
            return;
        }
        strongSelf->onRecv(pBuf);
    });
    _managerTimer = std::make_shared<Timer>(2,[weakSelf](){
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return false;
        }
        strongSelf->onManager();
        return true;
    },_poller);

    onConnect(ex);
}

string TcpClient::getIdentifier() const{
    return  to_string(reinterpret_cast<uint64_t>(this));
}

} /* namespace toolkit */
<commit_msg>fixed socket clone<commit_after>/*
 * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
 *
 * This file is part of ZLToolKit(https://github.com/xiongziliang/ZLToolKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

#include "TcpClient.h"

namespace toolkit {

TcpClient::TcpClient(const EventPoller::Ptr &poller) : SocketHelper(nullptr) {
    _poller = poller;
    if(!_poller){
        _poller = EventPollerPool::Instance().getPoller();
    }
}

TcpClient::~TcpClient() {}

void TcpClient::shutdown(const SockException &ex) {
    _managerTimer.reset();
    SocketHelper::shutdown(ex);
}

bool TcpClient::alive() {
    bool ret = _sock.operator bool() && _sock->rawFD() >= 0;
    return ret;
}

void TcpClient::setNetAdapter(const string &localIp){
    _netAdapter = localIp;
}

void TcpClient::startConnect(const string &strUrl, uint16_t iPort,float fTimeOutSec) {
    weak_ptr<TcpClient> weakSelf = shared_from_this();
    _managerTimer.reset();
    if (_sock)
        _sock = std::shared_ptr<Socket>(_sock->clone());
    else
        _sock = std::make_shared<Socket>(_poller);
    _sock->connect(strUrl, iPort, [weakSelf](const SockException &err){
        auto strongSelf = weakSelf.lock();
        if(strongSelf){
            strongSelf->onSockConnect(err);
        }
    }, fTimeOutSec,_netAdapter.data());
}
void TcpClient::onSockConnect(const SockException &ex) {
    if(ex){
        //连接失败
        _managerTimer.reset();
        onConnect(ex);
        return;
    }

    weak_ptr<TcpClient> weakSelf = shared_from_this();
    auto sock_ptr = _sock.get();
    _sock->setOnErr([weakSelf,sock_ptr](const SockException &ex) {
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return;
        }
        if(sock_ptr != strongSelf->_sock.get()){
            //已经重连socket，上传socket的事件忽略掉
            return;
        }
        strongSelf->_managerTimer.reset();
        strongSelf->onErr(ex);
    });
    _sock->setOnFlush([weakSelf,sock_ptr]() {
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return false;
        }
        if(sock_ptr != strongSelf->_sock.get()){
            //已经重连socket，上传socket的事件忽略掉
            return false;
        }
        strongSelf->onFlush();
        return true;
    });
    _sock->setOnRead([weakSelf,sock_ptr](const Buffer::Ptr &pBuf, struct sockaddr * , int) {
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return;
        }
        if(sock_ptr != strongSelf->_sock.get()){
            //已经重连socket，上传socket的事件忽略掉
            return;
        }
        strongSelf->onRecv(pBuf);
    });
    _managerTimer = std::make_shared<Timer>(2,[weakSelf](){
        auto strongSelf = weakSelf.lock();
        if (!strongSelf) {
            return false;
        }
        strongSelf->onManager();
        return true;
    },_poller);

    onConnect(ex);
}

string TcpClient::getIdentifier() const{
    return  to_string(reinterpret_cast<uint64_t>(this));
}

} /* namespace toolkit */
<|endoftext|>


<commit_before>/*
 * PrimeNumberFinder.cpp -- This file is part of primesieve
 *
 * Copyright (C) 2010 Kim Walisch, <kim.walisch@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

#include "PrimeNumberFinder.h"
#include "utils/cpuid.h"
#include "pmath.h"

#include <stdint.h>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cassert>

namespace {
  const uint32_t END = ~0u;
  const uint32_t BYTE_SIZE = 256;
}

const uint32_t PrimeNumberFinder::nextBitValue_[NUMBERS_PER_BYTE] = { 0,
     0, 0, 0, 0,  0, 0,
    11, 0, 0, 0, 13, 0,
    17, 0, 0, 0, 19, 0,
    23, 0, 0, 0, 29, 0,
     0, 0, 0, 0, 31 };

PrimeNumberFinder::PrimeNumberFinder(uint64_t startNumber, uint64_t stopNumber,
    uint32_t sieveSize, ResetSieve* resetSieve, Results* results,
    uint32_t flags) :
  SieveOfEratosthenes(startNumber, stopNumber, sieveSize, resetSieve), flags_(
      flags), isPOPCNTSupported_(utils::isPOPCNTSupported()), primeByteCounts_(
      NULL), primeBitValues_(NULL), results_(results), status_(0) {
  if (results_ == NULL && (flags_ & RESULTS_FLAGS))
    throw std::logic_error("PrimeNumberFinder: cannot use results_ (is NULL).");
  this->initLookupTables();
}

PrimeNumberFinder::~PrimeNumberFinder() {
  if (primeByteCounts_ != NULL) {
    for (uint32_t i = 0; i < 7; i++) {
      if (primeByteCounts_[i] != NULL)
        delete[] primeByteCounts_[i];
    }
    delete[] primeByteCounts_;
  }
  if (primeBitValues_ != NULL) {
    for (uint32_t i = 0; i < BYTE_SIZE; i++) {
      delete[] primeBitValues_[i];
    }
    delete[] primeBitValues_;
  }
}

/**
 * Initialize lookup tables needed to count and print primes.
 */
void PrimeNumberFinder::initLookupTables() {
  // bits and bitmasks representing the prime numbers and k-tuplets
  // within a byte of the sieve_ array
  const uint32_t bitmasks[7][9] = { { 0x01, 0x02, 0x04, 0x08, 0x10,
        0x20, 0x40, 0x80, END }, // prime numbers
      { 0x06, 0x18, 0xc0, END }, // twin primes
      { 0x07, 0x0e, 0x1c, 0x38, END }, // prime triplets
      { 0x1e, END },            // prime quadruplets
      { 0x1f, 0x3e, END },      // prime quintuplets
      { 0x3f, END },            // prime sextuplets
      { 0xfe, END } };          // prime septuplets

  if (flags_ & COUNT_FLAGS) {
    primeByteCounts_ = new uint32_t*[7];
    for (uint32_t i = 0; i < 7; i++) {
      if ((flags_  & (COUNT_PRIMES << i)) == 0)
        primeByteCounts_[i] = NULL;
      else {
        primeByteCounts_[i] = new uint32_t[BYTE_SIZE];
        // save the count of bitmasks within each byte value
        for (uint32_t j = 0; j < BYTE_SIZE; j++) {
          uint32_t bitmaskCount = 0;
          for (const uint32_t* b = bitmasks[i]; *b != END; b++) {
            if ((j & *b) == *b)
              bitmaskCount++;
          }
          primeByteCounts_[i][j] = bitmaskCount;
        }
      }
    }
  }
  if (flags_ & PRINT_FLAGS) {
    uint32_t index = 0;
    for (uint32_t i = PRINT_PRIMES; (i & flags_) == 0; i <<= 1)
      index++;
    primeBitValues_ = new uint32_t*[BYTE_SIZE];
    // generate the bitValues for each byte value
    for (uint32_t i = 0; i < BYTE_SIZE; i++) {
      primeBitValues_[i] = new uint32_t[9];
      uint32_t bitmaskCount = 0;
      // save the bitValues of the current byte value
      for (const uint32_t* b = bitmasks[index]; *b != END; b++) {
        if ((i & *b) == *b) {
          primeBitValues_[i][bitmaskCount] = bitValues_[ntz(*b)];
          bitmaskCount++;
        }
      }
      primeBitValues_[i][bitmaskCount] = END;
    }
  }
}

/**
 * Count the prime numbers and prime k-tuplets of the current
 * sieve round.
 */
void PrimeNumberFinder::count(const uint8_t* sieve, uint32_t sieveSize) {
  // count prime numbers
  if (flags_ & COUNT_PRIMES) {
    uint32_t primeCount = 0;
    uint32_t i = 0;
#if defined(POPCNT64)
    // count bits using the SSE 4.2 POPCNT instruction
    if (isPOPCNTSupported_) {
      uint32_t size = sieveSize >> 3;
      for (; i < size; i++)
        primeCount += POPCNT64(sieve, i);
      i = sieveSize - (sieveSize & 7);
    }
#endif
    // count bits using lookup table
    for (; i < sieveSize; i++)
      primeCount += primeByteCounts_[0][sieve[i]];
    results_->counts[0] += primeCount;
  }
  // count prime k-tuplets
  for (uint32_t i = 1; i < results_->COUNTS_SIZE; i++) {
    if (flags_  & (COUNT_PRIMES << i)) {
      uint32_t kTupletCount = 0;
      for (uint32_t j = 0; j < sieveSize; j++) {
        kTupletCount += primeByteCounts_[i][sieve[j]];
      }
      results_->counts[i] += kTupletCount;
    }
  }
}

/**
 * Print the status (in percents) of the sieving process
 * to the standard output.
 */
void PrimeNumberFinder::status(uint32_t sieveSize) {
  uint64_t upperBound = this->getLowerBound() + (sieveSize - 1)
      * NUMBERS_PER_BYTE;
  float status = 100.0f * (1.0f -
      static_cast<float> (this->getStopNumber() - upperBound) /
      static_cast<float> (this->getStopNumber() - this->getStartNumber()));
  if (flags_ & STORE_STATUS)
    results_->status = status;
  if (flags_ & PRINT_STATUS) {
    uint32_t floorStatus = static_cast<uint32_t> (status);
    if (status_ < floorStatus) {
      status_ = floorStatus;
      std::cout << '\r' << status_ << '%' << std::flush;
    }
  }
}

/**
 * Print the prime numbers or prime k-tuplets of the current
 * sieve round to the standard output.
 */
void PrimeNumberFinder::print(const uint8_t* sieve, uint32_t sieveSize) {
  uint64_t byteValue = this->getLowerBound();
  for (uint32_t i = 0; i < sieveSize; i++) {
    for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) {
      if (flags_ & PRINT_PRIMES)
        // print the current prime number
        std::cout << byteValue + *bitValue << std::endl;
      else {
        // print the current prime k-tuplet
        std::ostringstream kTuplet;
        kTuplet << "(";
        uint32_t v = *bitValue;
        for (uint32_t j = PRINT_PRIMES; (j & flags_) == 0; j <<= 1) {
          kTuplet << byteValue + v << ", ";
          v = nextBitValue_[v];
        }
        kTuplet << byteValue + v << ")";
        std::cout << kTuplet.str() << std::endl;
      }
    }
    byteValue += NUMBERS_PER_BYTE;
  }
}

void PrimeNumberFinder::analyseSieve(const uint8_t* sieve,
    uint32_t sieveSize) {
  if (flags_ & COUNT_FLAGS)
    this->count(sieve, sieveSize);
  if (flags_ & STATUS_FLAGS)
    this->status(sieveSize);
  if (flags_ & PRINT_FLAGS)
    this->print(sieve, sieveSize);
}
<commit_msg>added SSE 4.2 POPCNT support for x86 (32 bit)<commit_after>/*
 * PrimeNumberFinder.cpp -- This file is part of primesieve
 *
 * Copyright (C) 2010 Kim Walisch, <kim.walisch@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

#include "PrimeNumberFinder.h"
#include "utils/cpuid.h"
#include "pmath.h"

#include <stdint.h>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cassert>

namespace {
  const uint32_t END = ~0u;
  const uint32_t BYTE_SIZE = 256;
}

const uint32_t PrimeNumberFinder::nextBitValue_[NUMBERS_PER_BYTE] = { 0,
     0, 0, 0, 0,  0, 0,
    11, 0, 0, 0, 13, 0,
    17, 0, 0, 0, 19, 0,
    23, 0, 0, 0, 29, 0,
     0, 0, 0, 0, 31 };

PrimeNumberFinder::PrimeNumberFinder(uint64_t startNumber, uint64_t stopNumber,
    uint32_t sieveSize, ResetSieve* resetSieve, Results* results,
    uint32_t flags) :
  SieveOfEratosthenes(startNumber, stopNumber, sieveSize, resetSieve), flags_(
      flags), isPOPCNTSupported_(utils::isPOPCNTSupported()), primeByteCounts_(
      NULL), primeBitValues_(NULL), results_(results), status_(0) {
  if (results_ == NULL && (flags_ & RESULTS_FLAGS))
    throw std::logic_error("PrimeNumberFinder: cannot use results_ (is NULL).");
  this->initLookupTables();
}

PrimeNumberFinder::~PrimeNumberFinder() {
  if (primeByteCounts_ != NULL) {
    for (uint32_t i = 0; i < 7; i++) {
      if (primeByteCounts_[i] != NULL)
        delete[] primeByteCounts_[i];
    }
    delete[] primeByteCounts_;
  }
  if (primeBitValues_ != NULL) {
    for (uint32_t i = 0; i < BYTE_SIZE; i++) {
      delete[] primeBitValues_[i];
    }
    delete[] primeBitValues_;
  }
}

/**
 * Initialize lookup tables needed to count and print primes.
 */
void PrimeNumberFinder::initLookupTables() {
  // bits and bitmasks representing the prime numbers and k-tuplets
  // within a byte of the sieve_ array
  const uint32_t bitmasks[7][9] = { { 0x01, 0x02, 0x04, 0x08, 0x10,
        0x20, 0x40, 0x80, END }, // prime numbers
      { 0x06, 0x18, 0xc0, END }, // twin primes
      { 0x07, 0x0e, 0x1c, 0x38, END }, // prime triplets
      { 0x1e, END },            // prime quadruplets
      { 0x1f, 0x3e, END },      // prime quintuplets
      { 0x3f, END },            // prime sextuplets
      { 0xfe, END } };          // prime septuplets

  if (flags_ & COUNT_FLAGS) {
    primeByteCounts_ = new uint32_t*[7];
    for (uint32_t i = 0; i < 7; i++) {
      if ((flags_  & (COUNT_PRIMES << i)) == 0)
        primeByteCounts_[i] = NULL;
      else {
        primeByteCounts_[i] = new uint32_t[BYTE_SIZE];
        // save the count of bitmasks within each byte value
        for (uint32_t j = 0; j < BYTE_SIZE; j++) {
          uint32_t bitmaskCount = 0;
          for (const uint32_t* b = bitmasks[i]; *b != END; b++) {
            if ((j & *b) == *b)
              bitmaskCount++;
          }
          primeByteCounts_[i][j] = bitmaskCount;
        }
      }
    }
  }
  if (flags_ & PRINT_FLAGS) {
    uint32_t index = 0;
    for (uint32_t i = PRINT_PRIMES; (i & flags_) == 0; i <<= 1)
      index++;
    primeBitValues_ = new uint32_t*[BYTE_SIZE];
    // generate the bitValues for each byte value
    for (uint32_t i = 0; i < BYTE_SIZE; i++) {
      primeBitValues_[i] = new uint32_t[9];
      uint32_t bitmaskCount = 0;
      // save the bitValues of the current byte value
      for (const uint32_t* b = bitmasks[index]; *b != END; b++) {
        if ((i & *b) == *b) {
          primeBitValues_[i][bitmaskCount] = bitValues_[ntz(*b)];
          bitmaskCount++;
        }
      }
      primeBitValues_[i][bitmaskCount] = END;
    }
  }
}

/**
 * Count the prime numbers and prime k-tuplets of the current
 * sieve round.
 */
void PrimeNumberFinder::count(const uint8_t* sieve, uint32_t sieveSize) {
  // count prime numbers
  if (flags_ & COUNT_PRIMES) {
    uint32_t primeCount = 0;
    uint32_t i = 0;
#if defined(POPCNT64)
    // count bits using the SSE 4.2 POPCNT instruction
    if (isPOPCNTSupported_) {
      for (; i + 8 < sieveSize; i += 8)
        primeCount += POPCNT64(sieve, i);
    }
#endif
    // count bits using lookup table
    for (; i < sieveSize; i++)
      primeCount += primeByteCounts_[0][sieve[i]];
    results_->counts[0] += primeCount;
  }
  // count prime k-tuplets
  for (uint32_t i = 1; i < results_->COUNTS_SIZE; i++) {
    if (flags_  & (COUNT_PRIMES << i)) {
      uint32_t kTupletCount = 0;
      for (uint32_t j = 0; j < sieveSize; j++) {
        kTupletCount += primeByteCounts_[i][sieve[j]];
      }
      results_->counts[i] += kTupletCount;
    }
  }
}

/**
 * Print the status (in percents) of the sieving process
 * to the standard output.
 */
void PrimeNumberFinder::status(uint32_t sieveSize) {
  uint64_t upperBound = this->getLowerBound() + (sieveSize - 1)
      * NUMBERS_PER_BYTE;
  float status = 100.0f * (1.0f -
      static_cast<float> (this->getStopNumber() - upperBound) /
      static_cast<float> (this->getStopNumber() - this->getStartNumber()));
  if (flags_ & STORE_STATUS)
    results_->status = status;
  if (flags_ & PRINT_STATUS) {
    uint32_t floorStatus = static_cast<uint32_t> (status);
    if (status_ < floorStatus) {
      status_ = floorStatus;
      std::cout << '\r' << status_ << '%' << std::flush;
    }
  }
}

/**
 * Print the prime numbers or prime k-tuplets of the current
 * sieve round to the standard output.
 */
void PrimeNumberFinder::print(const uint8_t* sieve, uint32_t sieveSize) {
  uint64_t byteValue = this->getLowerBound();
  for (uint32_t i = 0; i < sieveSize; i++) {
    for (uint32_t* bitValue = primeBitValues_[sieve[i]]; *bitValue != END; bitValue++) {
      if (flags_ & PRINT_PRIMES)
        // print the current prime number
        std::cout << byteValue + *bitValue << std::endl;
      else {
        // print the current prime k-tuplet
        std::ostringstream kTuplet;
        kTuplet << "(";
        uint32_t v = *bitValue;
        for (uint32_t j = PRINT_PRIMES; (j & flags_) == 0; j <<= 1) {
          kTuplet << byteValue + v << ", ";
          v = nextBitValue_[v];
        }
        kTuplet << byteValue + v << ")";
        std::cout << kTuplet.str() << std::endl;
      }
    }
    byteValue += NUMBERS_PER_BYTE;
  }
}

void PrimeNumberFinder::analyseSieve(const uint8_t* sieve,
    uint32_t sieveSize) {
  if (flags_ & COUNT_FLAGS)
    this->count(sieve, sieveSize);
  if (flags_ & STATUS_FLAGS)
    this->status(sieveSize);
  if (flags_ & PRINT_FLAGS)
    this->print(sieve, sieveSize);
}
<|endoftext|>


<commit_before><commit_msg>Vulkan/Device: Make Device a handled object<commit_after><|endoftext|>


<commit_before><commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>Code-review: [FIX] type promotion, overflow preventing<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing include<commit_after><|endoftext|>


<commit_before><commit_msg>refactor parser combinator for Ulfberht<commit_after><|endoftext|>


<commit_before><commit_msg>Fix layout<commit_after><|endoftext|>


<commit_before>/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#include <ch_ethz_tell_ClientManager.h>
#include <tellstore/ClientConfig.hpp>
#include <tellstore/ClientManager.hpp>
#include "clientManager.h"

using namespace tell::store;

using ImplementationDetails = telljava::ClientManager;

crossbow::string to_string(JNIEnv* env, jstring str) {
    auto ptr = env->GetStringUTFChars(str, nullptr);
    crossbow::string res(ptr, env->GetStringUTFLength(str));
    env->ReleaseStringUTFChars(str, ptr);
    return res;
}

jlong Java_ch_ethz_tell_ClientManager_getClientManagerPtr(JNIEnv*, jclass, jlong impl) {
    auto o = reinterpret_cast<ImplementationDetails*>(impl);
    return reinterpret_cast<jlong>(&o->clientManager);
}

jlong Java_ch_ethz_tell_ClientManager_init(JNIEnv* env,
        jobject self,
        jstring commitManager,
        jstring tellStore,
        jlong chunkCount,
        jlong chunkSize)
{
    auto cM = to_string(env, commitManager);
    auto tS = to_string(env, tellStore);
    ClientConfig config;
    config.commitManager = ClientConfig::parseCommitManager(cM);
    config.tellStore = ClientConfig::parseTellStore(tS);
    auto res = new ImplementationDetails(std::move(config));
    return reinterpret_cast<jlong>(res);
}

void Java_ch_ethz_tell_ClientManager_shutdown(JNIEnv* env, jobject, jlong ptr) {
    delete reinterpret_cast<ImplementationDetails*>(ptr);
}

/* getters and setters for configuration */

void Java_ch_ethz_tell_ClientManager_setMaxPendingResponsesImpl(JNIEnv*, jobject, jlong obj, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(obj);
    o->mConfig.maxPendingResponses = value;
}

jlong Java_ch_ethz_tell_ClientManager_getMaxPendingResponsesImpl(JNIEnv*, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.maxPendingResponses;
}

void Java_ch_ethz_tell_ClientManager_setNumNetworkThreadsImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.numNetworkThreads = value;
}

jlong Java_ch_ethz_tell_ClientManager_getNumNetworkThreadsImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.numNetworkThreads;
}

void Java_ch_ethz_tell_ClientManager_setReceiveBufferCountImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.receiveBufferCount = value;
}

jlong Java_ch_ethz_tell_ClientManager_getReceiveBufferCountImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.receiveBufferCount;
}

void Java_ch_ethz_tell_ClientManager_setSendBufferCountImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.sendBufferCount = value;
}

jlong Java_ch_ethz_tell_ClientManager_getSendBufferCountImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.sendBufferCount;
}

void Java_ch_ethz_tell_ClientManager_setBufferLengthImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.bufferLength = value;
}

jlong Java_ch_ethz_tell_ClientManager_getBufferLengthImpl(JNIEnv *, jobject self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.bufferLength;
}

void Java_ch_ethz_tell_ClientManager_setCompletionQueueLengthImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.completionQueueLength = value;
}

jlong Java_ch_ethz_tell_ClientManager_getCompletionQueueLengthImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.completionQueueLength;
}

void Java_ch_ethz_tell_ClientManager_setSendQueueLengthImpl(JNIEnv*, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.sendQueueLength = value;
}

jlong Java_ch_ethz_tell_ClientManager_getSendQueueLengthImpl(JNIEnv*, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.sendQueueLength;
}
<commit_msg>fixed ClientManager-Init bug<commit_after>/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#include <ch_ethz_tell_ClientManager.h>
#include <tellstore/ClientConfig.hpp>
#include <tellstore/ClientManager.hpp>
#include "clientManager.h"

using namespace tell::store;

using ImplementationDetails = telljava::ClientManager;

crossbow::string to_string(JNIEnv* env, jstring str) {
    auto ptr = env->GetStringUTFChars(str, nullptr);
    crossbow::string res(ptr, env->GetStringUTFLength(str));
    env->ReleaseStringUTFChars(str, ptr);
    return res;
}

jlong Java_ch_ethz_tell_ClientManager_getClientManagerPtr(JNIEnv*, jclass, jlong impl) {
    auto o = reinterpret_cast<ImplementationDetails*>(impl);
    return reinterpret_cast<jlong>(&o->clientManager);
}

jlong Java_ch_ethz_tell_ClientManager_init(JNIEnv* env,
        jobject self,
        jstring commitManager,
        jstring tellStore)
{
    auto cM = to_string(env, commitManager);
    auto tS = to_string(env, tellStore);
    ClientConfig config;
    config.commitManager = ClientConfig::parseCommitManager(cM);
    config.tellStore = ClientConfig::parseTellStore(tS);
    auto res = new ImplementationDetails(std::move(config));
    return reinterpret_cast<jlong>(res);
}

void Java_ch_ethz_tell_ClientManager_shutdown(JNIEnv* env, jobject, jlong ptr) {
    delete reinterpret_cast<ImplementationDetails*>(ptr);
}

/* getters and setters for configuration */

void Java_ch_ethz_tell_ClientManager_setMaxPendingResponsesImpl(JNIEnv*, jobject, jlong obj, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(obj);
    o->mConfig.maxPendingResponses = value;
}

jlong Java_ch_ethz_tell_ClientManager_getMaxPendingResponsesImpl(JNIEnv*, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.maxPendingResponses;
}

void Java_ch_ethz_tell_ClientManager_setNumNetworkThreadsImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.numNetworkThreads = value;
}

jlong Java_ch_ethz_tell_ClientManager_getNumNetworkThreadsImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.numNetworkThreads;
}

void Java_ch_ethz_tell_ClientManager_setReceiveBufferCountImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.receiveBufferCount = value;
}

jlong Java_ch_ethz_tell_ClientManager_getReceiveBufferCountImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.receiveBufferCount;
}

void Java_ch_ethz_tell_ClientManager_setSendBufferCountImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.sendBufferCount = value;
}

jlong Java_ch_ethz_tell_ClientManager_getSendBufferCountImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.sendBufferCount;
}

void Java_ch_ethz_tell_ClientManager_setBufferLengthImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.bufferLength = value;
}

jlong Java_ch_ethz_tell_ClientManager_getBufferLengthImpl(JNIEnv *, jobject self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.bufferLength;
}

void Java_ch_ethz_tell_ClientManager_setCompletionQueueLengthImpl(JNIEnv *, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.completionQueueLength = value;
}

jlong Java_ch_ethz_tell_ClientManager_getCompletionQueueLengthImpl(JNIEnv *, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.completionQueueLength;
}

void Java_ch_ethz_tell_ClientManager_setSendQueueLengthImpl(JNIEnv*, jobject, jlong self, jlong value) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    o->mConfig.infinibandConfig.sendQueueLength = value;
}

jlong Java_ch_ethz_tell_ClientManager_getSendQueueLengthImpl(JNIEnv*, jobject, jlong self) {
    auto o = reinterpret_cast<ImplementationDetails*>(self);
    return o->mConfig.infinibandConfig.sendQueueLength;
}
<|endoftext|>