<commit_before>
#include "SpimRegistrationApp.h"

#include <GL/glew.h>
#include <GL/freeglut.h>

#include <iostream>
#include <vector>
#include <algorithm>

// goddamnit windows! :(
#undef near
#undef far

struct Mouse
{
	glm::ivec2		coordinates;
	int				button[3];
}				mouse;

SpimRegistrationApp*	regoApp = nullptr;

static void display()
{

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	regoApp->draw();

	glutSwapBuffers();

}

static void idle()
{

	unsigned int time = glutGet(GLUT_ELAPSED_TIME);
	static unsigned int oldTime = 0;

	float dt = (float)(time - oldTime) / 1000.f;
	oldTime = time;

	regoApp->update(dt);
	//regoApp->setCameraMoving(false);

	glutPostRedisplay();
}

static void keyboard(unsigned char key, int x, int y)
{
	if (key == 27)
		exit(0);

	if (key == '/')
		regoApp->toggleSlices();

	if (key == 'g')
		regoApp->toggleGrid();

	if (key == 'b')
		regoApp->toggleBboxes();

	// backspace
	if (key == '\b')
		regoApp->undoLastTransform();

	if (key == ' ')
		regoApp->beginAutoAlign();

	if (key == ',')
		regoApp->decreaseMinThreshold();
	if (key == '.')
		regoApp->increaseMaxThreshold();
	/*
	if (key == '<')
		regoApp->decreaseMinThreshold();
	if (key == '>')
		regoApp->decreaseMaxThreshold();
	*/
	if (key == 'C')
		regoApp->autoThreshold();
	if (key == 't')
		regoApp->contrastEditorApplyThresholds();

	if (key == ';')
		regoApp->decreaseSliceCount();
	if (key == '\'')
		regoApp->increaseSliceCount();

	if (key == '[')
		regoApp->rotateCurrentStack(-1);

	if (key == ']')
		regoApp->rotateCurrentStack(1);

	if (key == 'r')
		regoApp->switchRenderMode();
	if (key == 'R')
		regoApp->switchBlendMode();

	if (key == 's')
		regoApp->reloadShaders();

	if (key == 'u')
		regoApp->subsampleAllStacks();

	if (key == '1')
		regoApp->toggleSelectStack(0);

	if (key == '2')
		regoApp->toggleSelectStack(1);

	if (key == '3')
		regoApp->toggleSelectStack(2);

	if (key == '4')
		regoApp->toggleSelectStack(3);

	if (key == '5')
		regoApp->toggleSelectStack(4);

	/*
	if (key == 't')
		regoApp->loadStackTransformations();

	if (key == 'T')
		regoApp->saveStackTransformations();
	*/

	if (key == 'm')
		regoApp->maximizeViews();

	if (key == 'v')
		regoApp->toggleCurrentStack();
	if (key == 'V')
		regoApp->toggleAllStacks();

	if (key == '-')
		regoApp->zoomCamera(0.7f);
	if (key == '=')
		regoApp->zoomCamera(1.4f);
	if (key == 'c')
		regoApp->centerCamera();

	/*
	if (key == 'w')
		regoApp->panCamera(glm::vec2(0, 10));
	if (key == 's')
		regoApp->panCamera(glm::vec2(0, -10));
	if (key == 'a')
		regoApp->panCamera(glm::vec2(-10, 0));
	if (key == 'd')
		regoApp->panCamera(glm::vec2(10, 0));
	*/
}

static void keyboardUp(unsigned char key, int x, int y)
{
	if (key == ' ')
		regoApp->endAutoAlign();
}

static void motion(int x, int y)
{
	glm::ivec2 d = mouse.coordinates - glm::ivec2(x, y);

	float dt = (mouse.coordinates.y - y) * 0.1f;
	float dp = (mouse.coordinates.x - x) * 0.1f;

	//camera.rotate(dt, dp);

	float dx = (x - mouse.coordinates.x) * 2.f;
	float dy = (y - mouse.coordinates.y) * -2.f;

	mouse.coordinates.x = x;
	mouse.coordinates.y = y;

	int h = glutGet(GLUT_WINDOW_HEIGHT);

	if (mouse.button[1])
		regoApp->panCamera(glm::vec2(dx, dy));

	if (mouse.button[2])
		regoApp->rotateCamera(glm::vec2(dt, dp));

	if (mouse.button[0])
	{
		// let the application decide what to do with it:
		// camera movement in a perspective window
		//regoApp->rotateCamera(glm::vec2(dt, dp));

		// stack movement in an ortho window
		regoApp->moveStack(glm::vec2(dx, dy));

		// change contrast in the editor
		regoApp->changeContrast(glm::ivec2(x, h - y));

		regoApp->inspectOutputImage(glm::ivec2(x, h - y));

	}

	regoApp->updateMouseMotion(glm::ivec2(x, h - y));
}

static void passiveMotion(int x, int y)
{
	int h = glutGet(GLUT_WINDOW_HEIGHT);
	regoApp->updateMouseMotion(glm::ivec2(x, h - y));
}

static void special(int key, int x, int y)
{
	int w = glutGet(GLUT_WINDOW_WIDTH);
	int h = glutGet(GLUT_WINDOW_HEIGHT);
	const glm::ivec2 winRes(w, h);

	if (key == GLUT_KEY_F1)
		regoApp->setPerspectiveLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_F2)
		regoApp->setTopviewLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_F3)
		regoApp->setThreeViewLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_F4)
		regoApp->setContrastEditorLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_DOWN)
	{

	}

	if (key == GLUT_KEY_LEFT)
	{

	}

	if (key == GLUT_KEY_RIGHT)
	{

	}

}

static void button(int button, int state, int x, int y)
{
	//std::cout << "Button: " << button << " state: " << state << " x " << x << " y " << y << std::endl;

	mouse.coordinates.x = x;
	mouse.coordinates.y = y;

	mouse.button[button] = (state == GLUT_DOWN);

	if (state == GLUT_UP)
		regoApp->setCameraMoving(false);

	if (button == 0 && state == GLUT_DOWN)
		regoApp->startStackMove();
	if (button == 0 && state == GLUT_UP)
		regoApp->endStackMove();
}

static void reshape(int w, int h)
{
	regoApp->resize(glm::ivec2(w, h));
}

static void cleanup()
{

	try
	{
		regoApp->saveStackTransformations();
		regoApp->saveContrastSettings();
	}
	catch (std::runtime_error& e)
	{
		std::cerr << "[Error] " << e.what() << std::endl;
	}

	delete regoApp;
}

int main(int argc, const char** argv)
{

	if (argc < 2)
	{
		std::cerr << "[Error] No filename given!\n";
		std::cerr << "[Usage] " << argv[0] << " <spimfile>\n";
		return -1;
	}

	glutInit(&argc, const_cast<char**>(argv));
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowSize(1024, 768);
	glutCreateWindow("Geometry Image");
	glewInit();

	glutDisplayFunc(display);
	glutIdleFunc(idle);
	glutMouseFunc(button);
	glutKeyboardFunc(keyboard);
	glutKeyboardUpFunc(keyboardUp);
	glutMotionFunc(motion);
	glutReshapeFunc(reshape);
	glutPassiveMotionFunc(passiveMotion);
	glutSpecialFunc(special);

	glEnable(GL_DEPTH_TEST);
	glPointSize(2.f);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);

	glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE);
	glClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE);
	glClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);

	regoApp = new SpimRegistrationApp(glm::ivec2(1024,768));
	regoApp->setConfigPath("e:/regoApp/");

	try
	{
		for (int i = 1; i < argc; ++i)
		{
			regoApp->addSpimStack(argv[i]);

		}

		/*
		for (int i = 0; i < 3; ++i)
		{
			char filename[256];
			//sprintf(filename, "e:/spim/test/spim_TL00_Angle%d.tif", i);
			//sprintf(filename, "E:/spim/091015 SPIM various size beads/091015 20micron beads/spim_TL01_Angle%d.ome.tiff", i);
			//sprintf(filename, "e:/spim/zebra/spim_TL01_Angle%d.ome.tiff", i);
			sprintf(filename, "e:/spim/zebra_beads/spim_TL01_Angle%d.ome.tiff", i);
			//sprintf(filename, "e:/spim/121514 Fish2 no beads-selected/spim_TL01_Angle%d.ome.tiff", i);

			regoApp->addSpimStack(filename);
		}

		//regoApp->addSpimStack("e:/regoApp/result_31x31x360.bin");
		*/
		regoApp->centerCamera();
		regoApp->loadStackTransformations();
		regoApp->loadContrastSettings();

		/*
		regoApp->addSpimStack("e:/spim/test_beads/spim_TL01_Angle0.ome.tiff");
		regoApp->centerCamera();
		*/
	}
	catch (const std::runtime_error& e)
	{
		std::cerr << "[Error] " << e.what() << std::endl;
	}
	catch (const std::string& e)
	{
		std::cerr << "[Error] " << e << std::endl;
	}

	atexit(cleanup);

	glutMainLoop();

#ifdef _WIN32
	system("pause");
#endif

	return 0;
}

<commit_msg>Reloading shaders after file loading<commit_after>
#include "SpimRegistrationApp.h"

#include <GL/glew.h>
#include <GL/freeglut.h>

#include <iostream>
#include <vector>
#include <algorithm>

// goddamnit windows! :(
#undef near
#undef far

struct Mouse
{
	glm::ivec2		coordinates;
	int				button[3];
}				mouse;

SpimRegistrationApp*	regoApp = nullptr;

static void display()
{

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	regoApp->draw();

	glutSwapBuffers();

}

static void idle()
{

	unsigned int time = glutGet(GLUT_ELAPSED_TIME);
	static unsigned int oldTime = 0;

	float dt = (float)(time - oldTime) / 1000.f;
	oldTime = time;

	regoApp->update(dt);
	//regoApp->setCameraMoving(false);

	glutPostRedisplay();
}

static void keyboard(unsigned char key, int x, int y)
{
	if (key == 27)
		exit(0);

	if (key == '/')
		regoApp->toggleSlices();

	if (key == 'g')
		regoApp->toggleGrid();

	if (key == 'b')
		regoApp->toggleBboxes();

	// backspace
	if (key == '\b')
		regoApp->undoLastTransform();

	if (key == ' ')
		regoApp->beginAutoAlign();

	if (key == ',')
		regoApp->decreaseMinThreshold();
	if (key == '.')
		regoApp->increaseMaxThreshold();
	/*
	if (key == '<')
		regoApp->decreaseMinThreshold();
	if (key == '>')
		regoApp->decreaseMaxThreshold();
	*/
	if (key == 'C')
		regoApp->autoThreshold();
	if (key == 't')
		regoApp->contrastEditorApplyThresholds();

	if (key == ';')
		regoApp->decreaseSliceCount();
	if (key == '\'')
		regoApp->increaseSliceCount();

	if (key == '[')
		regoApp->rotateCurrentStack(-1);

	if (key == ']')
		regoApp->rotateCurrentStack(1);

	if (key == 'r')
		regoApp->switchRenderMode();
	if (key == 'R')
		regoApp->switchBlendMode();

	if (key == 's')
		regoApp->reloadShaders();

	if (key == 'u')
		regoApp->subsampleAllStacks();

	if (key == '1')
		regoApp->toggleSelectStack(0);

	if (key == '2')
		regoApp->toggleSelectStack(1);

	if (key == '3')
		regoApp->toggleSelectStack(2);

	if (key == '4')
		regoApp->toggleSelectStack(3);

	if (key == '5')
		regoApp->toggleSelectStack(4);

	/*
	if (key == 't')
		regoApp->loadStackTransformations();

	if (key == 'T')
		regoApp->saveStackTransformations();
	*/

	if (key == 'm')
		regoApp->maximizeViews();

	if (key == 'v')
		regoApp->toggleCurrentStack();
	if (key == 'V')
		regoApp->toggleAllStacks();

	if (key == '-')
		regoApp->zoomCamera(0.7f);
	if (key == '=')
		regoApp->zoomCamera(1.4f);
	if (key == 'c')
		regoApp->centerCamera();

	/*
	if (key == 'w')
		regoApp->panCamera(glm::vec2(0, 10));
	if (key == 's')
		regoApp->panCamera(glm::vec2(0, -10));
	if (key == 'a')
		regoApp->panCamera(glm::vec2(-10, 0));
	if (key == 'd')
		regoApp->panCamera(glm::vec2(10, 0));
	*/
}

static void keyboardUp(unsigned char key, int x, int y)
{
	if (key == ' ')
		regoApp->endAutoAlign();
}

static void motion(int x, int y)
{
	glm::ivec2 d = mouse.coordinates - glm::ivec2(x, y);

	float dt = (mouse.coordinates.y - y) * 0.1f;
	float dp = (mouse.coordinates.x - x) * 0.1f;

	//camera.rotate(dt, dp);

	float dx = (x - mouse.coordinates.x) * 2.f;
	float dy = (y - mouse.coordinates.y) * -2.f;

	mouse.coordinates.x = x;
	mouse.coordinates.y = y;

	int h = glutGet(GLUT_WINDOW_HEIGHT);

	if (mouse.button[1])
		regoApp->panCamera(glm::vec2(dx, dy));

	if (mouse.button[2])
		regoApp->rotateCamera(glm::vec2(dt, dp));

	if (mouse.button[0])
	{
		// let the application decide what to do with it:
		// camera movement in a perspective window
		//regoApp->rotateCamera(glm::vec2(dt, dp));

		// stack movement in an ortho window
		regoApp->moveStack(glm::vec2(dx, dy));

		// change contrast in the editor
		regoApp->changeContrast(glm::ivec2(x, h - y));

		regoApp->inspectOutputImage(glm::ivec2(x, h - y));

	}

	regoApp->updateMouseMotion(glm::ivec2(x, h - y));
}

static void passiveMotion(int x, int y)
{
	int h = glutGet(GLUT_WINDOW_HEIGHT);
	regoApp->updateMouseMotion(glm::ivec2(x, h - y));
}

static void special(int key, int x, int y)
{
	int w = glutGet(GLUT_WINDOW_WIDTH);
	int h = glutGet(GLUT_WINDOW_HEIGHT);
	const glm::ivec2 winRes(w, h);

	if (key == GLUT_KEY_F1)
		regoApp->setPerspectiveLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_F2)
		regoApp->setTopviewLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_F3)
		regoApp->setThreeViewLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_F4)
		regoApp->setContrastEditorLayout(winRes, mouse.coordinates);

	if (key == GLUT_KEY_DOWN)
	{

	}

	if (key == GLUT_KEY_LEFT)
	{

	}

	if (key == GLUT_KEY_RIGHT)
	{

	}

}

static void button(int button, int state, int x, int y)
{
	//std::cout << "Button: " << button << " state: " << state << " x " << x << " y " << y << std::endl;

	mouse.coordinates.x = x;
	mouse.coordinates.y = y;

	mouse.button[button] = (state == GLUT_DOWN);

	if (state == GLUT_UP)
		regoApp->setCameraMoving(false);

	if (button == 0 && state == GLUT_DOWN)
		regoApp->startStackMove();
	if (button == 0 && state == GLUT_UP)
		regoApp->endStackMove();
}

static void reshape(int w, int h)
{
	regoApp->resize(glm::ivec2(w, h));
}

static void cleanup()
{

	try
	{
		regoApp->saveStackTransformations();
		regoApp->saveContrastSettings();
	}
	catch (std::runtime_error& e)
	{
		std::cerr << "[Error] " << e.what() << std::endl;
	}

	delete regoApp;
}

int main(int argc, const char** argv)
{

	if (argc < 2)
	{
		std::cerr << "[Error] No filename given!\n";
		std::cerr << "[Usage] " << argv[0] << " <spimfile>\n";
		return -1;
	}

	glutInit(&argc, const_cast<char**>(argv));
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowSize(1024, 768);
	glutCreateWindow("Geometry Image");
	glewInit();

	glutDisplayFunc(display);
	glutIdleFunc(idle);
	glutMouseFunc(button);
	glutKeyboardFunc(keyboard);
	glutKeyboardUpFunc(keyboardUp);
	glutMotionFunc(motion);
	glutReshapeFunc(reshape);
	glutPassiveMotionFunc(passiveMotion);
	glutSpecialFunc(special);

	glEnable(GL_DEPTH_TEST);
	glPointSize(2.f);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);

	glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE);
	glClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE);
	glClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE);

	regoApp = new SpimRegistrationApp(glm::ivec2(1024,768));
	regoApp->setConfigPath("e:/regoApp/");

	try
	{
		for (int i = 1; i < argc; ++i)
		{
			regoApp->addSpimStack(argv[i]);

		}

		/*
		for (int i = 0; i < 3; ++i)
		{
			char filename[256];
			//sprintf(filename, "e:/spim/test/spim_TL00_Angle%d.tif", i);
			//sprintf(filename, "E:/spim/091015 SPIM various size beads/091015 20micron beads/spim_TL01_Angle%d.ome.tiff", i);
			//sprintf(filename, "e:/spim/zebra/spim_TL01_Angle%d.ome.tiff", i);
			sprintf(filename, "e:/spim/zebra_beads/spim_TL01_Angle%d.ome.tiff", i);
			//sprintf(filename, "e:/spim/121514 Fish2 no beads-selected/spim_TL01_Angle%d.ome.tiff", i);

			regoApp->addSpimStack(filename);
		}

		//regoApp->addSpimStack("e:/regoApp/result_31x31x360.bin");
		*/
		regoApp->centerCamera();
		regoApp->loadStackTransformations();
		regoApp->loadContrastSettings();

		regoApp->reloadShaders();

		/*
		regoApp->addSpimStack("e:/spim/test_beads/spim_TL01_Angle0.ome.tiff");
		regoApp->centerCamera();
		*/
	}
	catch (const std::runtime_error& e)
	{
		std::cerr << "[Error] " << e.what() << std::endl;
	}
	catch (const std::string& e)
	{
		std::cerr << "[Error] " << e << std::endl;
	}

	atexit(cleanup);

	glutMainLoop();

#ifdef _WIN32
	system("pause");
#endif

	return 0;
}

<|endoftext|>


<commit_before>be21ac3a-4b02-11e5-bf19-28cfe9171a43<commit_msg>Initial commit.2<commit_after>be2fb9e1-4b02-11e5-bcc0-28cfe9171a43<|endoftext|>


<commit_before>b580654a-ad5b-11e7-b687-ac87a332f658<commit_msg>Put the thingie in the thingie<commit_after>b5eb2e5c-ad5b-11e7-829e-ac87a332f658<|endoftext|>


<commit_before>class line{
  private: long long int Sum=0;

  public:
  void Sum(vector<line> a){
    for(i=0;i<a.size();i++)
      Sum+=a[i];
  };

  long long int GetSum(){
    return Sum;
  };
};

class line_collection{
  public: vector<line> Lines;

  public:
  line_collection(int count){
    Lines.resize(count);
  };

  vector<int> SumLines(int poz){
    int Index=Lines.size();
    int out=0;
    vector<int> result {0, 0};
    for(int i=0;i<Index; i++){
      if(i==poz)
        out++;
      result[out]+=Lines[i].GetSum();
    };
    return result;
  };
};

int solution(vector<vector<int>> &A){
  int Index_x=A.size();
  int Index_y=A[0].size();
  // co jeśli któryś wiersz ma mniej elementów?
  line_collection Lines_x(Index_x);
  line_collection Lines_y(Index_y);
  int result=0;

  vector<int> tmp(Index_y);
  for(int j=0;j<Index_y;j++){
    for(int i=0;i<Index_x;i++){
      Lines_x.Lines[i].Sum(A[i]);
      tmp[j]=A[i][j];
    };
    Lines_y.Lines[j].Sum(tmp);
  };

  for(int i=1;i<Index_x;i++){
    if(Lines_x.SumLines(i)[0]==Lines_x.SumLines(i)[1]){
      for(int j=1;j<Index_y;j++){
        if(Lines_y.SumLines(j)[0]==Lines_y.SumLines(j)[1]){
          result++;
        };
      };
    };
  };
};

int main(){
  vector<vector<int>> &A{{1, -1, 1},
                         {1, -1, 0}};
  cout<<solution(A)<<"\n";

};<commit_msg>attempt to run<commit_after>#include <vector>

class line{
  private: long long int Sum=0;

  public:
  void Sum(vector<line> a){
    for(int i=0;i<a.size();i++)
      Sum+=a[i];
  };

  long long int GetSum(){
    return Sum;
  };
};

class line_collection{
  public: vector<line> Lines;

  public:
  line_collection(int count){
    Lines.resize(count);
  };

  vector<int> SumLines(int poz){
    int Index=Lines.size();
    int out=0;
    vector<int> result {0, 0};
    for(int i=0;i<Index; i++){
      if(i==poz)
        out++;
      result[out]+=Lines[i].GetSum();
    };
    return result;
  };
};

int solution(vector<vector<int>> &A){
  int Index_x=A.size();
  int Index_y=A[0].size();
  // co jeśli któryś wiersz ma mniej elementów?
  line_collection Lines_x(Index_x);
  line_collection Lines_y(Index_y);
  int result=0;

  vector<int> tmp(Index_y);
  for(int j=0;j<Index_y;j++){
    for(int i=0;i<Index_x;i++){
      Lines_x.Lines[i].Sum(A[i]);
      tmp[j]=A[i][j];
    };
    Lines_y.Lines[j].Sum(tmp);
  };

  for(int i=1;i<Index_x;i++){
    if(Lines_x.SumLines(i)[0]==Lines_x.SumLines(i)[1]){
      for(int j=1;j<Index_y;j++){
        if(Lines_y.SumLines(j)[0]==Lines_y.SumLines(j)[1]){
          result++;
        };
      };
    };
  };
};

int main(){
  vector< vector<int> > A;
  A={{1, -1, 1}, {1, -1, 0}};
  cout<<solution(A)<<"\n";

};<|endoftext|>


<commit_before>b1ab61ab-2d3f-11e5-9318-c82a142b6f9b<commit_msg>Final commit :sunglasses:<commit_after>#include <iostream>
int main()
{
  std::cout << "Hello World!";
}<|endoftext|>


<commit_before>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <stdexcept>
#include <cassert>

int main(int argc, char **argv)
{
  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  //May throw std::runtime_error
  try {
  //Read the config file
  SpbConfigParser config(argv[1]);
  //Cosmological parameters
  const auto Omega = config.PopValue<double>("Omega");
  const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
  const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
  const auto HubbleParam = config.PopValue<double>("HubbleParam");
  //Which output format should we use. 4 is bigfile, 3 is HDF5, 2 is Gadget 2. Default to 3.
  const auto ICFormat = config.PopValue<int>("ICFormat", 3);
  //How many output files to use in the set
  const auto NumFiles = config.PopValue<int>("NumFiles");
  //Parameters of the simulation box
  const auto Box = config.PopValue<double>("Box");
  const auto Redshift = config.PopValue<double>("Redshift");
  const double InitTime = 1 / (1 + Redshift);
  //Size of FFT
  const size_t Nmesh = config.PopValue<int>("Nmesh");
  //Unused unless CAMB spectrum
  const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
  const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
  const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
  //Output filenames
  const auto OutputDir = config.PopValue<std::string>("OutputDir");
  const auto FileBase = config.PopValue<std::string>("FileBase");
  //Random number seed
  const auto Seed = config.PopValue<int>("Seed");
  //Various boolean flags
  const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
  const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
  //Power spectrum to use. Default to CAMB
  const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
  //Is twolpt on?
  const auto twolpt = config.PopValue<bool>("TWOLPT",true);
  //Unit system
  const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
  const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
  const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
  const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  //WDM options
  bool WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false);
  const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
  //Neutrino options
  //Add thermal velocities to type 2 particles
  bool NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",true);
  //This triggers the use of neutrinos via an altered transfer function
  //Should be on only if you are faking neutrinos by combining them with the dark matter,
  //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
  const auto combined_neutrinos = config.PopValue<bool>("NU_in_DM",false);
  //Changes whether we have two heavy and one light neutrino or one heavy two light.
  //0 is 3 degenerate species, 1 is normal (two light species) and -1 is inverted (two heavy)
  const auto Hierarchy = config.PopValue<int>("Hierarchy",0);
  //If enabled, turn off radiation in the initial velocities
  const auto NoRadiation = config.PopValue<bool>("NoRadiation",false);
  //Total neutrino mass
  const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
  //Parameter for the Efstathiou power spectrum. Generally does nothing.
  const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
  //Needed if ReNormaliseInputSpectrum is on. Otherwise unused
  const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
  const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
  //Number of particles desired
  std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
  int64_t CbRtNpart[6] = {0};
  CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
  CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
  CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
  for(int type=0; type<N_TYPES; ++type)
      npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];

  //Make a cosmology
  Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, Hierarchy, NoRadiation);
  //Init structure for neutrino velocities
  //Maximum velocity to sample Fermi-Dirac from, in km/s at z=0
  const double v_th = cosmo.NU_V0(Redshift, UnitVelocity_in_cm_per_s);
  //Convert physical km/s at z=0 in an unperturbed universe to internal gadget (comoving) velocity units at starting redshift.
  double vnumax = config.PopValue<double>("Max_nuvel", -1)*pow((1+Redshift),1.5)*(UnitVelocity_in_cm_per_s/1e5);
  if (vnumax < 0 || vnumax > v_th*MAX_FERMI_DIRAC)
      vnumax = v_th*MAX_FERMI_DIRAC;

  printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
  assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);

  if (Nmesh % 2 != 0){
    printf("Nmesh must be even or correct output is not guaranteed.\n");
    exit(1);
  }

  std::vector<std::string> unexpected = config.GetRemainingKeys();
  if(unexpected.size() > 0){
    std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
    for(auto unex: unexpected)
        std::cerr<<unex<<std::endl;
    exit(1);
  }
  DisplacementFields displace(Nmesh, Seed, Box, twolpt);
  /*Set particle numbers*/
  if(npart.sum() == 0)
          exit(1);
  //Set the flag that checks whether neutrinos are free-streaming
  cosmo.SetNeutrinoFreeStream(Box*UnitLength_in_cm, v_th * UnitVelocity_in_cm_per_s, InitTime);
  //Initialise a power spectrum
  PowerSpec * PSpec;
  switch(WhichSpectrum)
  {
      case 1:
            PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
            break;
      case 2:
            PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, cosmo.OmegaNu(1),InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
            break;
      default:
            PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
  }

  //If normalisation or WDM are on, decorate the base power spectrum
  //to do that
  if (ReNormalizeInputSpectrum) {
      double Dplus = cosmo.GrowthFactor(InitTime, 1.0);
      printf("Growth factor to z=0: %g \n", Dplus);
      PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, Dplus, UnitLength_in_cm);
  }
  if(WDM_Vtherm_On)
      PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);

  std::string extension("");
  if (ICFormat > 4 || ICFormat < 2) {
          fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
          exit(1);
  }
  if (ICFormat == 3){
      printf("Outputting HDF5 ICs\n");
      extension=".hdf5";
  }
  GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BGFL
  if(ICFormat == 4) {
     osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
  }
  else
#endif
  osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
  assert(osnap);
  /*Write headers*/
  gadget_header header = generate_header(npart, Omega, OmegaBaryon, cosmo.OmegaNu(1), OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);

  if ( vnumax/v_th < MAX_FERMI_DIRAC ) {
      FermiDiracVel therm_vels (v_th, vnumax/v_th);
      header.mass[NEUTRINO_TYPE]*=therm_vels.total_frac;
      printf("F-D velocity scale: %g (km/s). Max particle vel: %g (km/s). Fraction of mass in particles: %g\n",v_th/sqrt(1+Redshift), vnumax/sqrt(1+Redshift), therm_vels.total_frac);
  }

  //Generate regular particle grid
  part_grid Pgrid(CbRtNpart, header.mass, Box);

  if(osnap->WriteHeaders(header)) {
      fprintf(stderr, "Could not write headers to snapshot\n");
      exit(1);
  }

  int64_t FirstId=1;
  //Compute the factors to go from velocity to displacement
  const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
  const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
  //Only used if twolpt is on
  //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
  const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
  printf("vel_prefac= %g  hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);

  for(int type=0; type<N_TYPE;type++){
      if(npart[type] == 0)
              continue;
      FermiDiracVel * therm_vels = NULL;
      //For WDM thermal velocities
      if(WDM_Vtherm_On && type == DM_TYPE){
        const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
        therm_vels = new FermiDiracVel (wdm_vth);
        printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
      }
      //Neutrino thermal velocities
      if(NU_Vtherm_On && type == NEUTRINO_TYPE) {
          therm_vels = new FermiDiracVel (v_th, vnumax/v_th);
          printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
      }
      //Only compute zeldovich displacements if we have all the neutrinos in particles.
      if(type != 2 || !therm_vels || therm_vels->total_frac > 0.95) {
        lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
        outdata.SetVelPrefac(vel_prefac, vel_prefac2);
        FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
      }
      //Otherwise pass empty values for the velocity fields.
      else
        FirstId = write_particle_data(*osnap, type,NULL, Pgrid, therm_vels, FirstId);
      delete therm_vels;
  }

    delete osnap;
    delete PSpec;
  printf("Initial scale factor = %g\n", InitTime);

  }
  catch(std::ios_base::failure& e) {
      std::cerr<<e.what();
      return 4;
  }
  catch(std::runtime_error& e) {
      std::cerr<<e.what();
      return 1;
  }
  catch(std::invalid_argument& e) {
      std::cerr<<e.what();
      return 2;
  }
  catch(std::domain_error& e) {
      std::cerr<<e.what();
      return 3;
  }
  return 0;
}
<commit_msg>Correct factor in neutrino free-streaming velocity which would cause warning to not be printed for some large boxes<commit_after>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <stdexcept>
#include <cassert>

int main(int argc, char **argv)
{
  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  //May throw std::runtime_error
  try {
  //Read the config file
  SpbConfigParser config(argv[1]);
  //Cosmological parameters
  const auto Omega = config.PopValue<double>("Omega");
  const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
  const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
  const auto HubbleParam = config.PopValue<double>("HubbleParam");
  //Which output format should we use. 4 is bigfile, 3 is HDF5, 2 is Gadget 2. Default to 3.
  const auto ICFormat = config.PopValue<int>("ICFormat", 3);
  //How many output files to use in the set
  const auto NumFiles = config.PopValue<int>("NumFiles");
  //Parameters of the simulation box
  const auto Box = config.PopValue<double>("Box");
  const auto Redshift = config.PopValue<double>("Redshift");
  const double InitTime = 1 / (1 + Redshift);
  //Size of FFT
  const size_t Nmesh = config.PopValue<int>("Nmesh");
  //Unused unless CAMB spectrum
  const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
  const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
  const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
  //Output filenames
  const auto OutputDir = config.PopValue<std::string>("OutputDir");
  const auto FileBase = config.PopValue<std::string>("FileBase");
  //Random number seed
  const auto Seed = config.PopValue<int>("Seed");
  //Various boolean flags
  const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
  const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
  //Power spectrum to use. Default to CAMB
  const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
  //Is twolpt on?
  const auto twolpt = config.PopValue<bool>("TWOLPT",true);
  //Unit system
  const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
  const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
  const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
  const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
  //WDM options
  bool WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false);
  const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
  //Neutrino options
  //Add thermal velocities to type 2 particles
  bool NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",true);
  //This triggers the use of neutrinos via an altered transfer function
  //Should be on only if you are faking neutrinos by combining them with the dark matter,
  //and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
  const auto combined_neutrinos = config.PopValue<bool>("NU_in_DM",false);
  //Changes whether we have two heavy and one light neutrino or one heavy two light.
  //0 is 3 degenerate species, 1 is normal (two light species) and -1 is inverted (two heavy)
  const auto Hierarchy = config.PopValue<int>("Hierarchy",0);
  //If enabled, turn off radiation in the initial velocities
  const auto NoRadiation = config.PopValue<bool>("NoRadiation",false);
  //Total neutrino mass
  const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
  //Parameter for the Efstathiou power spectrum. Generally does nothing.
  const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
  //Needed if ReNormaliseInputSpectrum is on. Otherwise unused
  const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
  const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
  //Number of particles desired
  std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
  int64_t CbRtNpart[6] = {0};
  CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
  CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
  CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
  for(int type=0; type<N_TYPES; ++type)
      npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];

  //Make a cosmology
  Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, Hierarchy, NoRadiation);
  //Init structure for neutrino velocities
  //Maximum velocity to sample Fermi-Dirac from, in km/s at z=0
  const double v_th = cosmo.NU_V0(Redshift, UnitVelocity_in_cm_per_s);
  //Convert physical km/s at z=0 in an unperturbed universe to internal gadget (comoving) velocity units at starting redshift.
  double vnumax = config.PopValue<double>("Max_nuvel", -1)*pow((1+Redshift),1.5)*(UnitVelocity_in_cm_per_s/1e5);
  if (vnumax < 0 || vnumax > v_th*MAX_FERMI_DIRAC)
      vnumax = v_th*MAX_FERMI_DIRAC;

  printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
  assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);

  if (Nmesh % 2 != 0){
    printf("Nmesh must be even or correct output is not guaranteed.\n");
    exit(1);
  }

  std::vector<std::string> unexpected = config.GetRemainingKeys();
  if(unexpected.size() > 0){
    std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
    for(auto unex: unexpected)
        std::cerr<<unex<<std::endl;
    exit(1);
  }
  DisplacementFields displace(Nmesh, Seed, Box, twolpt);
  /*Set particle numbers*/
  if(npart.sum() == 0)
          exit(1);
  //Set the flag that checks whether neutrinos are free-streaming
  cosmo.SetNeutrinoFreeStream(Box*UnitLength_in_cm, v_th * UnitVelocity_in_cm_per_s*sqrt(InitTime), InitTime);
  //Initialise a power spectrum
  PowerSpec * PSpec;
  switch(WhichSpectrum)
  {
      case 1:
            PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
            break;
      case 2:
            PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, cosmo.OmegaNu(1),InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
            break;
      default:
            PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
  }

  //If normalisation or WDM are on, decorate the base power spectrum
  //to do that
  if (ReNormalizeInputSpectrum) {
      double Dplus = cosmo.GrowthFactor(InitTime, 1.0);
      printf("Growth factor to z=0: %g \n", Dplus);
      PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, Dplus, UnitLength_in_cm);
  }
  if(WDM_Vtherm_On)
      PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);

  std::string extension("");
  if (ICFormat > 4 || ICFormat < 2) {
          fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
          exit(1);
  }
  if (ICFormat == 3){
      printf("Outputting HDF5 ICs\n");
      extension=".hdf5";
  }
  GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BGFL
  if(ICFormat == 4) {
     osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
  }
  else
#endif
  osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
  assert(osnap);
  /*Write headers*/
  gadget_header header = generate_header(npart, Omega, OmegaBaryon, cosmo.OmegaNu(1), OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);

  if ( vnumax/v_th < MAX_FERMI_DIRAC ) {
      FermiDiracVel therm_vels (v_th, vnumax/v_th);
      header.mass[NEUTRINO_TYPE]*=therm_vels.total_frac;
      printf("F-D velocity scale: %g (km/s). Max particle vel: %g (km/s). Fraction of mass in particles: %g\n",v_th/sqrt(1+Redshift), vnumax/sqrt(1+Redshift), therm_vels.total_frac);
  }

  //Generate regular particle grid
  part_grid Pgrid(CbRtNpart, header.mass, Box);

  if(osnap->WriteHeaders(header)) {
      fprintf(stderr, "Could not write headers to snapshot\n");
      exit(1);
  }

  int64_t FirstId=1;
  //Compute the factors to go from velocity to displacement
  const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
  const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
  //Only used if twolpt is on
  //This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
  const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
  printf("vel_prefac= %g  hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);

  for(int type=0; type<N_TYPE;type++){
      if(npart[type] == 0)
              continue;
      FermiDiracVel * therm_vels = NULL;
      //For WDM thermal velocities
      if(WDM_Vtherm_On && type == DM_TYPE){
        const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
        therm_vels = new FermiDiracVel (wdm_vth);
        printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
      }
      //Neutrino thermal velocities
      if(NU_Vtherm_On && type == NEUTRINO_TYPE) {
          therm_vels = new FermiDiracVel (v_th, vnumax/v_th);
          printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
      }
      //Only compute zeldovich displacements if we have all the neutrinos in particles.
      if(type != 2 || !therm_vels || therm_vels->total_frac > 0.95) {
        lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
        outdata.SetVelPrefac(vel_prefac, vel_prefac2);
        FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
      }
      //Otherwise pass empty values for the velocity fields.
      else
        FirstId = write_particle_data(*osnap, type,NULL, Pgrid, therm_vels, FirstId);
      delete therm_vels;
  }

    delete osnap;
    delete PSpec;
  printf("Initial scale factor = %g\n", InitTime);

  }
  catch(std::ios_base::failure& e) {
      std::cerr<<e.what();
      return 4;
  }
  catch(std::runtime_error& e) {
      std::cerr<<e.what();
      return 1;
  }
  catch(std::invalid_argument& e) {
      std::cerr<<e.what();
      return 2;
  }
  catch(std::domain_error& e) {
      std::cerr<<e.what();
      return 3;
  }
  return 0;
}
<|endoftext|>


<commit_before>abe2893d-ad59-11e7-b631-ac87a332f658<commit_msg>Now it no longer crashes if X<commit_after>aca76c54-ad59-11e7-a151-ac87a332f658<|endoftext|>


<commit_before>88684f2e-ad5a-11e7-9f31-ac87a332f658<commit_msg>Fixed that one bug<commit_after>8915fa2b-ad5a-11e7-8a5d-ac87a332f658<|endoftext|>


<commit_before>bf973102-ad5c-11e7-ab5d-ac87a332f658<commit_msg>Fixed that one bug<commit_after>c028fe7a-ad5c-11e7-90d0-ac87a332f658<|endoftext|>


<commit_before>/* Copyright (C) 2005-2011 Fabio Riccardi */

/**
 * JavaAppLauncher: a simple Java application launcher for Windows.
 * JavaParamBlock.cpp
 *
 * Paul J. Lucas [paul@lightcrafts.com]
 */

// standard
#include <cstring>

// windows
#include <windows.h>
#include <winbase.h>
#include <winreg.h>                     /* for Registry functions */

// local
#include "JavaParamBlock.h"
#include "UI.h"

using namespace std;

/**
 * If there is no previously set user preference for the maximum amount of
 * memory to use, then this is the percentage of the physical memory that
 * should be used.
 */
float const DefaultMaxMemoryPercentage = 0.3;

/**
 * Insist on at least this much RAM.
 */
int const   JavaMinMemoryInMB = 256;

/**
 * Limit the JVM heap size because we now use non-heap memory for things like
 * tile caches.
 */
int const   JavaMaxMemoryInMB = 1536;

/**
 * Copy a C string to a newly allocated C buffer.
 */
static void new_strcpy( char **dest, char const *src ) {
    if ( src ) {
        *dest = new char[ ::strlen( src ) + 1 ];
        if ( !*dest )
            LC_die( TEXT("Could not allocate memory.") );
        ::strcpy( *dest, src );
    } else {
        *dest = new char[1];
        if ( !*dest )
            LC_die( TEXT("Could not allocate memory.") );
        **dest = '\0';
    }
}

/**
 * Allocate and copy a JVM option string.
 */
inline void newJVMOption( JavaVMOption *jvm_opt, char const *s ) {
    new_strcpy( &jvm_opt->optionString, s );
    jvm_opt->extraInfo = 0;
}

/**
 * Set the given JVM option string.
 */
inline void setJVMOption( JavaVMOption *jvm_opt, char const *s ) {
    jvm_opt->optionString = const_cast<char*>( s );
    jvm_opt->extraInfo = 0;
}

/**
 * Allocate and initialize an array of JavaVMOption data structures from the
 * JVM arguments.
 */
static int getJVMOptions( JavaVMOption **jvm_options,
                          char const *const jvmArgs[] ) {
    //
    // First, count the number of options.
    //
    int n = 0;
    for ( char const *const *arg = jvmArgs; *arg && **arg == '-'; ++arg )
        ++n;

    if ( n > 0 ) {
        //
        // Then, convert the options.
        //
        *jvm_options = new JavaVMOption[n];
        for ( int i = 0; i < n; ++i )
            newJVMOption( &(*jvm_options)[i], jvmArgs[i] );
    } else
        *jvm_options = 0;

    return n;
}

/**
 * Get the arguments to main() from the JVM arguments.
 */
static int getMainArgs( char ***main_argv, char const *const jvmArgs[] ) {
    int n = 0;
    *main_argv = 0;
    //
    // First, skip the JVM options.
    //
    char const *const *arg;
    for ( arg = jvmArgs; *arg && **arg == '-'; ++arg )
        ;

    if ( *arg && *++arg ) {             // skip the main class name
        //
        // Second, count the number of main() arguments.
        //
        for ( char const *const *temp = arg; *temp; ++temp )
            ++n;
        if ( n ) {
            //
            // Finally, convert the arguments.
            //
            *main_argv = new char*[n];
            if ( !*main_argv )
                LC_die( TEXT("Could not allocate main() argument array.") );
            for ( int i = 0; i < n; ++i )
                new_strcpy( &(*main_argv)[i], arg[i] );
        }
    }

    return n;
}

/**
 * Get the name of the class whose main() is to be executed from the Java
 * dictionary in the application's Info.plist file.
 */
static void getMainClassName( char **mainClassName,
                              char const *const jvmArgs[] ) {
    char const *const *arg;
    //
    // First, skip the JVM options.
    //
    for ( arg = jvmArgs; *arg && **arg == '-'; ++arg )
        ;

    if ( !*arg )
        LC_die( TEXT("Main class not specified.") );
    //
    // *arg is now pointing to the main class name.
    //
    new_strcpy( mainClassName, *arg );

    //
    // Convert a class name of the form com.foo.bar to com/foo/bar because the
    // latter is how FindClass() wants it.  Curiously, this step isn't in
    // Apple's sample code.  Hmmm....
    //
    for ( char *c = *mainClassName; *c; ++c )
        if ( *c == '.' )
            *c = '/';
}

/**
 * Get the value of the MaxMemory user preference in megabytes.
 */
static int getMaxMemoryFromPreference() {
    HKEY key;
    LONG status = ::RegOpenKeyEx(
        HKEY_CURRENT_USER,
        TEXT("Software\\JavaSoft\\Prefs\\com\\lightcrafts\\app"),
        0, KEY_QUERY_VALUE, &key
    );
    if ( status != ERROR_SUCCESS )
        return 0;

    DWORD keyType;
    BYTE  buf[ 10 ];
    DWORD bufSize = sizeof( buf );
    status = ::RegQueryValueExA(
        key, "/Max/Memory", NULL, &keyType, buf, &bufSize
    );
    if ( status != ERROR_SUCCESS || keyType != REG_SZ )
        return 0;
    return ::atoi( reinterpret_cast<char*>( buf ) );
}

/**
 * Get the value of the MaxMemory user preference in megabytes; if none,
 * default to some percentage of physical memory (but do not exceed what the
 * JVM can handle).
 */
static int getMaxMemory() {
    int memInMB = getMaxMemoryFromPreference();
    if ( !memInMB ) {
        MEMORYSTATUSEX ms;
        ms.dwLength = sizeof( MEMORYSTATUSEX );
        if ( !::GlobalMemoryStatusEx( &ms ) )
            LC_die( TEXT("Determining memory"), ::GetLastError() );
        memInMB = (int)(ms.ullTotalPhys / 1048576 * DefaultMaxMemoryPercentage);
    }
    if ( memInMB < JavaMinMemoryInMB )
        return JavaMinMemoryInMB;
    if ( memInMB > JavaMaxMemoryInMB )
        return JavaMaxMemoryInMB;
    return memInMB;
}

/**
 * Replace any -Xmx option that may have been specified in the Info.plist file
 * with one generated from the user preference.
 */
static void replaceXmxOption( JavaVMInitArgs *jvm_args ) {
    char jvmXmxOption[ 12 ];
    ::sprintf( jvmXmxOption, "-Xmx%dm", getMaxMemory() );
    if ( jvm_args->nOptions ) {
        //
        // There is at lease one JVM option: loop through them all looking for
        // an -Xmx option.  If found, replace it.
        //
        for ( int i = 0; i < jvm_args->nOptions; ++i ) {
            char **const optionString = &jvm_args->options[i].optionString;
            if ( ::strncmp( *optionString, "-Xmx", 4 ) == 0 ) {
                delete[] *optionString;
                new_strcpy( optionString, jvmXmxOption );
                return;
            }
        }
        //
        // No existing -Xmx option was found: we need to append one.
        //
        int const new_nOptions = jvm_args->nOptions + 1;
        JavaVMOption *const new_options = new JavaVMOption[ new_nOptions ];
        int i;
        for ( i = 0; i < jvm_args->nOptions; ++i )
            setJVMOption( &new_options[i], jvm_args->options[i].optionString );
        newJVMOption( &new_options[i], jvmXmxOption );
        delete[] jvm_args->options;
        jvm_args->options = new_options;
        jvm_args->nOptions = new_nOptions;
    } else {
        //
        // There are no JVM options: create one for the -Xmx option.
        //
        jvm_args->nOptions = 1;
        jvm_args->options = new JavaVMOption[1];
        newJVMOption( &jvm_args->options[0], jvmXmxOption );
    }
}

/**
 * Initialize the given JavaParamBlock from the application's Info.plist file.
 */
void initJavaParamBlock( JavaParamBlock *jpb, char const *const jvmArgs[] ) {
    //
    // Set-up the JVM initialization options.
    //
    jpb->jvm_args.version = JNI_VERSION_1_4;
    jpb->jvm_args.nOptions = getJVMOptions( &jpb->jvm_args.options, jvmArgs );
    jpb->jvm_args.ignoreUnrecognized = JNI_TRUE;

    //
    // We need to replace any -Xmx option that may have been specified in the
    // Info.plist file with one generated from the user preference.
    //
    replaceXmxOption( &jpb->jvm_args );

    //
    // Set-up the main class name and main()'s arguments.
    //
    getMainClassName( &jpb->main_className, jvmArgs );
    jpb->main_argc = getMainArgs( &jpb->main_argv, jvmArgs );
}

/* vim:set et sw=4 ts=4: */
<commit_msg>Windows - Different max heap sizes for 32 and 64-bit OS<commit_after>/* Copyright (C) 2005-2011 Fabio Riccardi */

/**
 * JavaAppLauncher: a simple Java application launcher for Windows.
 * JavaParamBlock.cpp
 *
 * Paul J. Lucas [paul@lightcrafts.com]
 */

// standard
#include <cstring>

// windows
#include <windows.h>
#include <winbase.h>
#include <winreg.h>                     /* for Registry functions */

// local
#include "JavaParamBlock.h"
#include "UI.h"

using namespace std;

/**
 * If there is no previously set user preference for the maximum amount of
 * memory to use, then this is the percentage of the physical memory that
 * should be used.
 */
float const DefaultMaxMemoryPercentage = 0.3;

/**
 * Insist on at least this much RAM.
 */
int const   JavaMinMemoryInMB = 256;

/**
 * Limit the JVM heap size because we now use non-heap memory for things like
 * tile caches.
 */
#if _WIN64 || __amd64__
int const   JavaMaxMemoryInMB = 4096;
#else
int const   JavaMaxMemoryInMB = 1024;
#endif

/**
 * Copy a C string to a newly allocated C buffer.
 */
static void new_strcpy( char **dest, char const *src ) {
    if ( src ) {
        *dest = new char[ ::strlen( src ) + 1 ];
        if ( !*dest )
            LC_die( TEXT("Could not allocate memory.") );
        ::strcpy( *dest, src );
    } else {
        *dest = new char[1];
        if ( !*dest )
            LC_die( TEXT("Could not allocate memory.") );
        **dest = '\0';
    }
}

/**
 * Allocate and copy a JVM option string.
 */
inline void newJVMOption( JavaVMOption *jvm_opt, char const *s ) {
    new_strcpy( &jvm_opt->optionString, s );
    jvm_opt->extraInfo = 0;
}

/**
 * Set the given JVM option string.
 */
inline void setJVMOption( JavaVMOption *jvm_opt, char const *s ) {
    jvm_opt->optionString = const_cast<char*>( s );
    jvm_opt->extraInfo = 0;
}

/**
 * Allocate and initialize an array of JavaVMOption data structures from the
 * JVM arguments.
 */
static int getJVMOptions( JavaVMOption **jvm_options,
                          char const *const jvmArgs[] ) {
    //
    // First, count the number of options.
    //
    int n = 0;
    for ( char const *const *arg = jvmArgs; *arg && **arg == '-'; ++arg )
        ++n;

    if ( n > 0 ) {
        //
        // Then, convert the options.
        //
        *jvm_options = new JavaVMOption[n];
        for ( int i = 0; i < n; ++i )
            newJVMOption( &(*jvm_options)[i], jvmArgs[i] );
    } else
        *jvm_options = 0;

    return n;
}

/**
 * Get the arguments to main() from the JVM arguments.
 */
static int getMainArgs( char ***main_argv, char const *const jvmArgs[] ) {
    int n = 0;
    *main_argv = 0;
    //
    // First, skip the JVM options.
    //
    char const *const *arg;
    for ( arg = jvmArgs; *arg && **arg == '-'; ++arg )
        ;

    if ( *arg && *++arg ) {             // skip the main class name
        //
        // Second, count the number of main() arguments.
        //
        for ( char const *const *temp = arg; *temp; ++temp )
            ++n;
        if ( n ) {
            //
            // Finally, convert the arguments.
            //
            *main_argv = new char*[n];
            if ( !*main_argv )
                LC_die( TEXT("Could not allocate main() argument array.") );
            for ( int i = 0; i < n; ++i )
                new_strcpy( &(*main_argv)[i], arg[i] );
        }
    }

    return n;
}

/**
 * Get the name of the class whose main() is to be executed from the Java
 * dictionary in the application's Info.plist file.
 */
static void getMainClassName( char **mainClassName,
                              char const *const jvmArgs[] ) {
    char const *const *arg;
    //
    // First, skip the JVM options.
    //
    for ( arg = jvmArgs; *arg && **arg == '-'; ++arg )
        ;

    if ( !*arg )
        LC_die( TEXT("Main class not specified.") );
    //
    // *arg is now pointing to the main class name.
    //
    new_strcpy( mainClassName, *arg );

    //
    // Convert a class name of the form com.foo.bar to com/foo/bar because the
    // latter is how FindClass() wants it.  Curiously, this step isn't in
    // Apple's sample code.  Hmmm....
    //
    for ( char *c = *mainClassName; *c; ++c )
        if ( *c == '.' )
            *c = '/';
}

/**
 * Get the value of the MaxMemory user preference in megabytes.
 */
static int getMaxMemoryFromPreference() {
    HKEY key;
    LONG status = ::RegOpenKeyEx(
        HKEY_CURRENT_USER,
        TEXT("Software\\JavaSoft\\Prefs\\com\\lightcrafts\\app"),
        0, KEY_QUERY_VALUE, &key
    );
    if ( status != ERROR_SUCCESS )
        return 0;

    DWORD keyType;
    BYTE  buf[ 10 ];
    DWORD bufSize = sizeof( buf );
    status = ::RegQueryValueExA(
        key, "/Max/Memory", NULL, &keyType, buf, &bufSize
    );
    if ( status != ERROR_SUCCESS || keyType != REG_SZ )
        return 0;
    return ::atoi( reinterpret_cast<char*>( buf ) );
}

/**
 * Get the value of the MaxMemory user preference in megabytes; if none,
 * default to some percentage of physical memory (but do not exceed what the
 * JVM can handle).
 */
static int getMaxMemory() {
    int memInMB = getMaxMemoryFromPreference();
    if ( !memInMB ) {
        MEMORYSTATUSEX ms;
        ms.dwLength = sizeof( MEMORYSTATUSEX );
        if ( !::GlobalMemoryStatusEx( &ms ) )
            LC_die( TEXT("Determining memory"), ::GetLastError() );
        memInMB = (int)(ms.ullTotalPhys / 1048576 * DefaultMaxMemoryPercentage);
    }
    if ( memInMB < JavaMinMemoryInMB )
        return JavaMinMemoryInMB;
    if ( memInMB > JavaMaxMemoryInMB )
        return JavaMaxMemoryInMB;
    return memInMB;
}

/**
 * Replace any -Xmx option that may have been specified in the Info.plist file
 * with one generated from the user preference.
 */
static void replaceXmxOption( JavaVMInitArgs *jvm_args ) {
    char jvmXmxOption[ 12 ];
    ::sprintf( jvmXmxOption, "-Xmx%dm", getMaxMemory() );
    if ( jvm_args->nOptions ) {
        //
        // There is at lease one JVM option: loop through them all looking for
        // an -Xmx option.  If found, replace it.
        //
        for ( int i = 0; i < jvm_args->nOptions; ++i ) {
            char **const optionString = &jvm_args->options[i].optionString;
            if ( ::strncmp( *optionString, "-Xmx", 4 ) == 0 ) {
                delete[] *optionString;
                new_strcpy( optionString, jvmXmxOption );
                return;
            }
        }
        //
        // No existing -Xmx option was found: we need to append one.
        //
        int const new_nOptions = jvm_args->nOptions + 1;
        JavaVMOption *const new_options = new JavaVMOption[ new_nOptions ];
        int i;
        for ( i = 0; i < jvm_args->nOptions; ++i )
            setJVMOption( &new_options[i], jvm_args->options[i].optionString );
        newJVMOption( &new_options[i], jvmXmxOption );
        delete[] jvm_args->options;
        jvm_args->options = new_options;
        jvm_args->nOptions = new_nOptions;
    } else {
        //
        // There are no JVM options: create one for the -Xmx option.
        //
        jvm_args->nOptions = 1;
        jvm_args->options = new JavaVMOption[1];
        newJVMOption( &jvm_args->options[0], jvmXmxOption );
    }
}

/**
 * Initialize the given JavaParamBlock from the application's Info.plist file.
 */
void initJavaParamBlock( JavaParamBlock *jpb, char const *const jvmArgs[] ) {
    //
    // Set-up the JVM initialization options.
    //
    jpb->jvm_args.version = JNI_VERSION_1_4;
    jpb->jvm_args.nOptions = getJVMOptions( &jpb->jvm_args.options, jvmArgs );
    jpb->jvm_args.ignoreUnrecognized = JNI_TRUE;

    //
    // We need to replace any -Xmx option that may have been specified in the
    // Info.plist file with one generated from the user preference.
    //
    replaceXmxOption( &jpb->jvm_args );

    //
    // Set-up the main class name and main()'s arguments.
    //
    getMainClassName( &jpb->main_className, jvmArgs );
    jpb->main_argc = getMainArgs( &jpb->main_argv, jvmArgs );
}

/* vim:set et sw=4 ts=4: */
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <sys/time.h>
#include <stdint.h>

#include "wavelet_tree.h"
#include "memory_usage.h"

using namespace std;

int main(int argc, char** argv)
{

	struct timeval start_time, end_time;
	char rank_or_select, character;
	string filename;
	uint32_t bound;
	long us;
	bool success;

	WaveletTree* wt = NULL;
	uint32_t result = 0;

	if (argc != 5) {
		cout <<"Wrong number of parameters: \n./WavletTree filename rank_or_select[R or S] char bound \n";
		return -1;
    }

	filename = argv[1];
	rank_or_select = argv[2][0];
	character = argv[3][0];
	bound = atoi(argv[4]);

	if (rank_or_select == 'R') {
		// Creating wavelet tree
		cout <<"Creating tree: ";
		gettimeofday(&start_time,NULL);
		wt = WaveletTree::CreateTreeFromFASTAFile(filename);
		gettimeofday(&end_time,NULL);

		if (wt == NULL) {
			cout <<"FAILED" <<endl;
			cout <<"Could not open file " <<filename <<endl;
			return 1;
		}

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
                       (1000000 * start_time.tv_sec + start_time.tv_usec));
		cout <<us <<"us" <<endl;

		// Rank operation
		cout <<"Rank("<<character <<", " <<bound <<"): ";
		gettimeofday(&start_time,NULL);
		success = wt->Rank(character, bound, result);
		gettimeofday(&end_time,NULL);

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
        	(1000000 * start_time.tv_sec + start_time.tv_usec));
		if (success) {
			cout <<result <<" [" <<us <<" us]" <<endl;
		}
		else {
			cout <<"Failed. Wrong index" <<endl;
		}
	}
	else if (rank_or_select == 'S') {
		// Creating wavelet tree
		cout <<"Creating tree: ";
		gettimeofday(&start_time,NULL);
		wt = WaveletTree::CreateTreeFromFASTAFile(filename);
		gettimeofday(&end_time,NULL);

		if (wt == NULL) {
			cout <<"FAILED" <<endl;
			cout <<"Could not open file " <<filename <<endl;
			return 1;
		}

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
                       (1000000 * start_time.tv_sec + start_time.tv_usec));
		cout <<us <<"us" <<endl;

		// Rank operation
		cout <<"Select("<<character <<", " <<bound <<"): ";
		gettimeofday(&start_time,NULL);
		success = wt->Select(character, bound, result);
		gettimeofday(&end_time,NULL);

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
        	(1000000 * start_time.tv_sec + start_time.tv_usec));

		if (success) {
			cout <<result <<" [" <<us <<" us]" <<endl;
		}
		else {
			cout <<"Failed. Wrong index" <<endl;
		}
	}
	else {
		cout <<"Value of 3rd parameter must be 'R' or 'S'" <<endl;
	}

	cout <<"Memory usage: " <<CalculateMemoryUsage(filename, 3, 1, 131072) <<" B" <<endl;

	delete wt;
	return 0;
}
<commit_msg>Ispravak u main.cc<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <sys/time.h>
#include <stdint.h>

#include "wavelet_tree.h"
#include "memory_usage.h"

using namespace std;

int main(int argc, char** argv)
{

	struct timeval start_time, end_time;
	char rank_or_select, character;
	string filename;
	uint32_t bound;
	long us;
	bool success;

	WaveletTree* wt = NULL;
	uint32_t result = 0;

	if (argc != 5) {
		cout <<"Wrong number of parameters: \n./WavletTree filename rank_or_select[R or S] char bound \n";
		return -1;
    }

	filename = argv[1];
	rank_or_select = argv[2][0];
	character = argv[3][0];
	bound = atoi(argv[4]);

	if (rank_or_select == 'R') {
		// Creating wavelet tree
		cout <<"Creating tree: ";
		gettimeofday(&start_time,NULL);
		wt = WaveletTree::CreateTreeFromFASTAFile(filename);
		gettimeofday(&end_time,NULL);

		if (wt == NULL) {
			cout <<"FAILED" <<endl;
			cout <<"Could not open file " <<filename <<endl;
			return 1;
		}

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
                       (1000000 * start_time.tv_sec + start_time.tv_usec));
		cout <<us <<"us" <<endl;

		// Rank operation
		cout <<"Rank("<<character <<", " <<bound <<"): ";
		gettimeofday(&start_time,NULL);
		success = wt->Rank(character, bound, result);
		gettimeofday(&end_time,NULL);

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
        	(1000000 * start_time.tv_sec + start_time.tv_usec));
		if (success) {
			cout <<result <<" [" <<us <<" us]" <<endl;
		}
		else {
			cout <<"Failed. Wrong character or index" <<endl;
		}
	}
	else if (rank_or_select == 'S') {
		// Creating wavelet tree
		cout <<"Creating tree: ";
		gettimeofday(&start_time,NULL);
		wt = WaveletTree::CreateTreeFromFASTAFile(filename);
		gettimeofday(&end_time,NULL);

		if (wt == NULL) {
			cout <<"FAILED" <<endl;
			cout <<"Could not open file " <<filename <<endl;
			return 1;
		}

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
                       (1000000 * start_time.tv_sec + start_time.tv_usec));
		cout <<us <<"us" <<endl;

		// Rank operation
		cout <<"Select("<<character <<", " <<bound <<"): ";
		gettimeofday(&start_time,NULL);
		success = wt->Select(character, bound, result);
		gettimeofday(&end_time,NULL);

		us = (long)((1000000 * end_time.tv_sec + end_time.tv_usec) -
        	(1000000 * start_time.tv_sec + start_time.tv_usec));

		if (success) {
			cout <<result <<" [" <<us <<" us]" <<endl;
		}
		else {
			cout <<"Failed. Wrong character or index" <<endl;
		}
	}
	else {
		cout <<"Value of 3rd parameter must be 'R' or 'S'" <<endl;
	}

	cout <<"Memory usage: " <<CalculateMemoryUsage(filename, 3, 1, 131072) <<" B" <<endl;

	delete wt;
	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlsignaturehelper.hxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLSECURITY_XMLSIGNATUREHELPER_HXX
#define _XMLSECURITY_XMLSIGNATUREHELPER_HXX

#ifndef _STLP_VECTOR
#include <vector>
#endif

#include <tools/link.hxx>

#include <rtl/ustring.hxx>

#include <xmlsecurity/sigstruct.hxx>

#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/crypto/XUriBinding.hpp>
#include <com/sun/star/xml/crypto/XSEInitializer.hpp>
#include <com/sun/star/xml/crypto/sax/XSecurityController.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureCreationResultListener.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureVerifyResultListener.hpp>

class XSecController;
class Date;
class Time;

namespace com {
namespace sun {
namespace star {
namespace lang {
    class XMultiServiceFactory; }
namespace io {
    class XOutputStream;
    class XInputStream; }
namespace embed {
    class XStorage; }
}}}

struct XMLSignatureCreationResult
{
    sal_Int32 nSecurityId;
    com::sun::star::xml::crypto::SecurityOperationStatus nSignatureCreationResult;

    XMLSignatureCreationResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult )
    {
        nSecurityId = nId;
        nSignatureCreationResult = nResult;
    }
};

struct XMLSignatureVerifyResult
{
    sal_Int32 nSecurityId;
    com::sun::star::xml::crypto::SecurityOperationStatus nSignatureVerifyResult;

    XMLSignatureVerifyResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult )
    {
        nSecurityId = nId;
        nSignatureVerifyResult = nResult;
    }
};

typedef ::std::vector<XMLSignatureCreationResult> XMLSignatureCreationResults;
typedef ::std::vector<XMLSignatureVerifyResult> XMLSignatureVerifyResults;

/**********************************************************
 XMLSignatureHelper

 Helper class for the XML Security framework

 Functions:
 1. help to create a security context;
 2. help to listen signature creation result;
 3. help to listen signature verify result;
 4. help to indicate which signature to verify.

 **********************************************************/

class XMLSignatureHelper
{
private:
    ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory> mxMSF;
    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::sax::XSecurityController > mxSecurityController;
    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > mxUriBinding;

    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XSEInitializer > mxSEInitializer;
    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XXMLSecurityContext > mxSecurityContext;

    XMLSignatureCreationResults maCreationResults;
    XMLSignatureVerifyResults   maVerifyResults;
    XSecController*             mpXSecController;
    bool                        mbError;
    Link                        maStartVerifySignatureHdl;

private:
    void        ImplCreateSEInitializer();
    DECL_LINK(  SignatureCreationResultListener, XMLSignatureCreationResult*);
    DECL_LINK(  SignatureVerifyResultListener, XMLSignatureVerifyResult* );
    DECL_LINK(  StartVerifySignatureElement, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >* );

    // Not allowed:
    XMLSignatureHelper(const XMLSignatureHelper&);

public:
    XMLSignatureHelper(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory>& rxMSF );
    ~XMLSignatureHelper();

                // Initialize the security context with given crypto token.
                // Empty string means default crypto token.
                // Returns true for success.
    bool        Init( const rtl::OUString& rTokenPath );

                // Set UriBinding to create input streams to open files.
                // Default implementation is capable to open files from disk.
    void        SetUriBinding( com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding >& rxUriBinding );
    com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > GetUriBinding() const;

                // Set the storage which should be used by the default UriBinding
                // Must be set before StatrtMission().
    void        SetStorage( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rxStorage );

                // Argument for the Link is a uno::Reference< xml::sax::XAttributeList >*
                // Return 1 to verify, 0 to skip.
                // Default handler will verify all.
    void        SetStartVerifySignatureHdl( const Link& rLink );

                // Get the security environment
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironment();
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironmentByIndex(sal_Int32 nId);
    sal_Int32 GetSecurityEnvironmentNumber();

                // After signing/veryfieng, get information about signatures
    SignatureInformation  GetSignatureInformation( sal_Int32 nSecurityId ) const;
    SignatureInformations GetSignatureInformations() const;

                // See XSecController for documentation
    void        StartMission();
    void        EndMission();
    sal_Int32   GetNewSecurityId();
    /** sets data that describes the certificate.

        It is absolutely necessary that the parameter ouX509IssuerName is set. It contains
        the base64 encoded certificate, which is DER encoded. The XMLSec needs it to find
        the private key. Although issuer name and certificate should be sufficient to identify
        the certificate the implementation in XMLSec is broken, both for Windows and mozilla.
        The reason is that they use functions to find the certificate which take as parameter
        the DER encoded ASN.1 issuer name. The issuer name is a DName, where most attributes
        are of type DirectoryName, which is a choice of 5 string types. This information is
        not contained in the issuer string and while it is converted to the ASN.1 name the
        conversion function must assume a particular type, which is often wrong. For example,
        the Windows function CertStrToName will use a T.61 string if the string does not contain
        special characters. So if the certificate uses simple characters but encodes the
        issuer attributes in Utf8, then CertStrToName will use T.61. The resulting DER encoded
        ASN.1 name now contains different bytes which indicate the string type. The functions
        for finding the certificate apparently use memcmp - hence they fail to find the
        certificate.
     */
    void SetX509Certificate(sal_Int32 nSecurityId, const rtl::OUString& ouX509IssuerName,
        const rtl::OUString& ouX509SerialNumber, const rtl::OUString& ouX509Cert);

    void SetX509Certificate(sal_Int32 nSecurityId, sal_Int32 nSecurityEnvironmentIndex,
        const rtl::OUString& ouX509IssuerName,  const rtl::OUString& ouX509SerialNumber,
        const rtl::OUString& ouX509Cert);
    void        SetDateTime( sal_Int32 nSecurityId, const Date& rDate, const Time& rTime );

    void        AddForSigning( sal_Int32 securityId, const rtl::OUString& uri, const rtl::OUString& objectURL, sal_Bool bBinary );
    bool        CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler );
    bool        CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream );
    bool        ReadAndVerifySignature( const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& xInputStream );

    // MT: ??? I think only for adding/removing, not for new signatures...
    // MM: Yes, but if you want to insert a new signature into an existing signature file, those function
    //     will be very usefull, see Mission 3 in the new "multisigdemo" program   :-)
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler> CreateDocumentHandlerWithHeader( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream );
    void CloseDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler>& xDocumentHandler );
    void ExportSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler, const SignatureInformation& signatureInfo );
};

#endif // _XMLSECURITY_XMLSIGNATUREHELPER_HXX
<commit_msg>INTEGRATION: CWS jl93 (1.10.140); FILE MERGED 2008/05/05 13:13:42 jl 1.10.140.2: RESYNC: (1.10-1.11); FILE MERGED 2008/03/20 10:04:12 jl 1.10.140.1: #i86651# changes for ODF 1.2 conform signature<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlsignaturehelper.hxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLSECURITY_XMLSIGNATUREHELPER_HXX
#define _XMLSECURITY_XMLSIGNATUREHELPER_HXX

#ifndef _STLP_VECTOR
#include <vector>
#endif

#include <tools/link.hxx>

#include <rtl/ustring.hxx>

#include <xmlsecurity/sigstruct.hxx>

#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/crypto/XUriBinding.hpp>
#include <com/sun/star/xml/crypto/XSEInitializer.hpp>
#include <com/sun/star/xml/crypto/sax/XSecurityController.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureCreationResultListener.hpp>
#include <com/sun/star/xml/crypto/sax/XSignatureVerifyResultListener.hpp>

class XSecController;
class Date;
class Time;

namespace com {
namespace sun {
namespace star {
namespace lang {
    class XMultiServiceFactory; }
namespace io {
    class XOutputStream;
    class XInputStream; }
namespace embed {
    class XStorage; }
}}}

struct XMLSignatureCreationResult
{
    sal_Int32 nSecurityId;
    com::sun::star::xml::crypto::SecurityOperationStatus nSignatureCreationResult;

    XMLSignatureCreationResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult )
    {
        nSecurityId = nId;
        nSignatureCreationResult = nResult;
    }
};

struct XMLSignatureVerifyResult
{
    sal_Int32 nSecurityId;
    com::sun::star::xml::crypto::SecurityOperationStatus nSignatureVerifyResult;

    XMLSignatureVerifyResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult )
    {
        nSecurityId = nId;
        nSignatureVerifyResult = nResult;
    }
};

typedef ::std::vector<XMLSignatureCreationResult> XMLSignatureCreationResults;
typedef ::std::vector<XMLSignatureVerifyResult> XMLSignatureVerifyResults;

/**********************************************************
 XMLSignatureHelper

 Helper class for the XML Security framework

 Functions:
 1. help to create a security context;
 2. help to listen signature creation result;
 3. help to listen signature verify result;
 4. help to indicate which signature to verify.

 **********************************************************/

class XMLSignatureHelper
{
private:
    ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory> mxMSF;
    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::sax::XSecurityController > mxSecurityController;
    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > mxUriBinding;

    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XSEInitializer > mxSEInitializer;
    ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XXMLSecurityContext > mxSecurityContext;

    XMLSignatureCreationResults maCreationResults;
    XMLSignatureVerifyResults   maVerifyResults;
    XSecController*             mpXSecController;
    bool                        mbError;
    bool mbODFPre1_2;
    Link                        maStartVerifySignatureHdl;

private:
    void        ImplCreateSEInitializer();
    DECL_LINK(  SignatureCreationResultListener, XMLSignatureCreationResult*);
    DECL_LINK(  SignatureVerifyResultListener, XMLSignatureVerifyResult* );
    DECL_LINK(  StartVerifySignatureElement, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >* );

    // Not allowed:
    XMLSignatureHelper(const XMLSignatureHelper&);

public:
    XMLSignatureHelper(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory>& rxMSF );
    ~XMLSignatureHelper();

                // Initialize the security context with given crypto token.
                // Empty string means default crypto token.
                // Returns true for success.
    bool        Init( const rtl::OUString& rTokenPath );

                // Set UriBinding to create input streams to open files.
                // Default implementation is capable to open files from disk.
    void        SetUriBinding( com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding >& rxUriBinding );
    com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > GetUriBinding() const;

                // Set the storage which should be used by the default UriBinding
                // Must be set before StatrtMission().
    void        SetStorage( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rxStorage );

                // Argument for the Link is a uno::Reference< xml::sax::XAttributeList >*
                // Return 1 to verify, 0 to skip.
                // Default handler will verify all.
    void        SetStartVerifySignatureHdl( const Link& rLink );

                // Get the security environment
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironment();
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironmentByIndex(sal_Int32 nId);
    sal_Int32 GetSecurityEnvironmentNumber();

                // After signing/veryfieng, get information about signatures
    SignatureInformation  GetSignatureInformation( sal_Int32 nSecurityId ) const;
    SignatureInformations GetSignatureInformations() const;

                // See XSecController for documentation
    void        StartMission();
    void        EndMission();
    sal_Int32   GetNewSecurityId();
    /** sets data that describes the certificate.

        It is absolutely necessary that the parameter ouX509IssuerName is set. It contains
        the base64 encoded certificate, which is DER encoded. The XMLSec needs it to find
        the private key. Although issuer name and certificate should be sufficient to identify
        the certificate the implementation in XMLSec is broken, both for Windows and mozilla.
        The reason is that they use functions to find the certificate which take as parameter
        the DER encoded ASN.1 issuer name. The issuer name is a DName, where most attributes
        are of type DirectoryName, which is a choice of 5 string types. This information is
        not contained in the issuer string and while it is converted to the ASN.1 name the
        conversion function must assume a particular type, which is often wrong. For example,
        the Windows function CertStrToName will use a T.61 string if the string does not contain
        special characters. So if the certificate uses simple characters but encodes the
        issuer attributes in Utf8, then CertStrToName will use T.61. The resulting DER encoded
        ASN.1 name now contains different bytes which indicate the string type. The functions
        for finding the certificate apparently use memcmp - hence they fail to find the
        certificate.
     */
    void SetX509Certificate(sal_Int32 nSecurityId, const rtl::OUString& ouX509IssuerName,
        const rtl::OUString& ouX509SerialNumber, const rtl::OUString& ouX509Cert);

    void SetX509Certificate(sal_Int32 nSecurityId, sal_Int32 nSecurityEnvironmentIndex,
        const rtl::OUString& ouX509IssuerName,  const rtl::OUString& ouX509SerialNumber,
        const rtl::OUString& ouX509Cert);
    void        SetDateTime( sal_Int32 nSecurityId, const Date& rDate, const Time& rTime );

    void        AddForSigning( sal_Int32 securityId, const rtl::OUString& uri, const rtl::OUString& objectURL, sal_Bool bBinary );
    bool        CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler );
    bool        CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream );
    bool        ReadAndVerifySignature( const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& xInputStream );

    // MT: ??? I think only for adding/removing, not for new signatures...
    // MM: Yes, but if you want to insert a new signature into an existing signature file, those function
    //     will be very usefull, see Mission 3 in the new "multisigdemo" program   :-)
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler> CreateDocumentHandlerWithHeader( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream );
    void CloseDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler>& xDocumentHandler );
    void ExportSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler, const SignatureInformation& signatureInfo );
};

#endif // _XMLSECURITY_XMLSIGNATUREHELPER_HXX
<|endoftext|>


<commit_before>///
/// @file  print.cpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <print.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <stdint.h>

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

namespace {

bool print_status_ = false;

bool partial_computation_ = true;

}

namespace primecount {

void set_print_status(bool print_status)
{
  print_status_ = print_status;
}

void set_partial_computation(bool partial_computation)
{
  partial_computation_ = partial_computation;
}

bool print_result()
{
  return partial_computation_;
}

bool print_status()
{
  return print_status_;
}

bool partial_computation()
{
  return partial_computation_;
}

void print(const string& str)
{
  if (print_status())
    cout << str << endl;
}

void print(maxint_t x, int64_t y, int64_t c, int threads)
{
  if (!partial_computation())
  {
    maxint_t z = x / y;
    double alpha = (double) y / (double) iroot<3>(x);

    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << alpha << endl;
    cout << "threads = " << validate_threads(threads) << endl;
    cout << endl;
  }
}

void print(maxint_t x, int64_t y, int64_t z, int64_t c, double alpha, int threads)
{
  if (print_status())
  {
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << alpha << endl;
    cout << "threads = " << validate_threads(threads) << endl;
  }
}

void print(const string& res_name, maxint_t res, double time)
{
  if (print_status())
  {
    cout << "\r" << string(40,' ') << "\r";
    cout << "Status: 100%" << endl;
    cout << res_name << " = " << res << endl;
    print_seconds(get_wtime() - time);
  }
}

void print_seconds(double seconds)
{
  if (print_status())
    cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
}

} // namespace
<commit_msg>Refactoring<commit_after>///
/// @file  print.cpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <print.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <stdint.h>

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

namespace {

bool print_status_ = false;

bool partial_computation_ = true;

}

namespace primecount {

void set_print_status(bool print_status)
{
  print_status_ = print_status;
}

void set_partial_computation(bool partial_computation)
{
  partial_computation_ = partial_computation;
}

bool print_result()
{
  return partial_computation();
}

bool print_status()
{
  return print_status_;
}

bool partial_computation()
{
  return partial_computation_;
}

void print(const string& str)
{
  if (print_status())
    cout << str << endl;
}

void print(maxint_t x, int64_t y, int64_t z, int64_t c, double alpha, int threads)
{
  if (print_status())
  {
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << alpha << endl;
    cout << "threads = " << validate_threads(threads) << endl;
  }
}

void print(maxint_t x, int64_t y, int64_t c, int threads)
{
  if (print_status() && !partial_computation())
  {
    maxint_t z = x / y;
    double alpha = (double) y / (double) iroot<3>(x);

    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << alpha << endl;
    cout << "threads = " << validate_threads(threads) << endl;
    cout << endl;
  }
}

void print(const string& res_name, maxint_t res, double time)
{
  if (print_status())
  {
    cout << "\r" << string(40,' ') << "\r";
    cout << "Status: 100%" << endl;
    cout << res_name << " = " << res << endl;
    print_seconds(get_wtime() - time);
  }
}

void print_seconds(double seconds)
{
  if (print_status())
    cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
}

} // namespace
<|endoftext|>


<commit_before>/*

Copyright (c) 2007-2008, Python File Format Interface
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

   * Redistributions in binary form must reproduce the above
     copyright notice, this list of conditions and the following
     disclaimer in the documentation and/or other materials provided
     with the distribution.

   * Neither the name of the Python File Format Interface
     project nor the names of its contributors may be used to endorse
     or promote products derived from this software without specific
     prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <boost/python.hpp>

using namespace boost::python;

int main(int argc, char **argv) {
	try {
		Py_Initialize();
		// start interactive console
		import("code").attr("InteractiveConsole")().attr("interact")();
	} catch (error_already_set) {
		PyErr_Print();
	}
}
<commit_msg>cpp: set up namespace for interactive console<commit_after>/*

Copyright (c) 2007-2008, Python File Format Interface
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

   * Redistributions in binary form must reproduce the above
     copyright notice, this list of conditions and the following
     disclaimer in the documentation and/or other materials provided
     with the distribution.

   * Neither the name of the Python File Format Interface
     project nor the names of its contributors may be used to endorse
     or promote products derived from this software without specific
     prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <boost/python.hpp>

using namespace boost::python;

int main(int argc, char **argv) {
	try {
		Py_Initialize();
		// get namespace
		object main_module = import("__main__");
		object main_namespace = main_module.attr("__dict__");
		// set some objects in the namespace
		// - import all format namespaces
		// - possibly, set up some convenience functions (load & save?)
		// - perhaps, if called from for instance a gui, automatically load
		//   data, and have it automatically saved upon exit of the
		//   interpreter
		// for now, just do a little test
		// import the sys module, and set x to a value
		main_namespace["sys"] = import("sys");
		main_namespace["x"] = 5;
		// start interactive console, using the main namespace
		import("code").attr("InteractiveConsole")(main_namespace).attr("interact")();
	} catch (error_already_set) {
		PyErr_Print();
	}
}
<|endoftext|>


<commit_before>#pragma once

#include <vector>

namespace acmacs
{
    using Indexes = std::vector<size_t>;

    class SortedIndexes : public Indexes
    {
     public:
        explicit SortedIndexes(const Indexes& source)
            : Indexes(source) { std::sort(begin(), end()); }
    };

    class ReverseSortedIndexes : public Indexes
    {
     public:
        explicit ReverseSortedIndexes(const Indexes& source) : Indexes(source) { sort(); }

        void add(const Indexes& to_add) { insert(end(), to_add.begin(), to_add.end()); sort(); }

     private:
        static inline bool cmp(size_t i1, size_t i2) { return i1 > i2; }
        void sort() { std::sort(begin(), end(), cmp); erase(std::unique(begin(), end(), cmp), end()); }
    };

    template <typename T> void remove(const ReverseSortedIndexes& indexes, std::vector<T>& data, size_t base_index = 0)
    {
        for (auto index : indexes)
            data.erase(data.begin() + static_cast<ReverseSortedIndexes::difference_type>(index + base_index));
    }
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs::ReverseSortedIndexes::add()<commit_after>#pragma once

#include <vector>

namespace acmacs
{
    using Indexes = std::vector<size_t>;

    class SortedIndexes : public Indexes
    {
     public:
        explicit SortedIndexes(const Indexes& source)
            : Indexes(source) { std::sort(begin(), end()); }
    };

    class ReverseSortedIndexes : public Indexes
    {
     public:
        explicit ReverseSortedIndexes(const Indexes& source) : Indexes(source) { sort(); }

        void add(const Indexes& to_add) { insert(end(), to_add.begin(), to_add.end()); sort(); }

     private:
        static inline bool cmp(size_t i1, size_t i2) { return i1 > i2; }
        void sort() { std::sort(begin(), end(), cmp); erase(std::unique(begin(), end()), end()); }
    };

    template <typename T> void remove(const ReverseSortedIndexes& indexes, std::vector<T>& data, size_t base_index = 0)
    {
        for (auto index : indexes)
            data.erase(data.begin() + static_cast<ReverseSortedIndexes::difference_type>(index + base_index));
    }
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>