text:
// system
#include <sstream>

// library headers
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>

// local
#include "appimage/desktop_integration/exceptions.h"
#include "appimage/desktop_integration/IntegrationManager.h"
#include "utils/hashlib.h"
#include "utils/path_utils.h"

using namespace appimage::desktop_integration;
namespace bf = boost::filesystem;

class TestIntegrationManager : public ::testing::Test {
protected:
    bf::path userDirPath;

    void SetUp() override {
        userDirPath = bf::temp_directory_path() / boost::filesystem::unique_path();
        bf::create_directories(userDirPath);

        ASSERT_FALSE(userDirPath.empty());
    }

    void TearDown() override {
        bf::remove_all(userDirPath);
    }

    void createStubFile(const bf::path& path, const std::string& content = "") {
        bf::create_directories(path.parent_path());
        bf::ofstream f(path);
        f << content;
    }
};

TEST_F(TestIntegrationManager, registerAppImage) {
    std::string appImagePath = TEST_DATA_DIR "Echo-x86_64.AppImage";
    IntegrationManager manager(userDirPath.string());
    appimage::core::AppImage appImage(appImagePath);
    manager.registerAppImage(appImage);

    std::string md5 = appimage::utils::hashPath(appImagePath.c_str());

    bf::path expectedDesktopFilePath = userDirPath / ("applications/appimagekit_" + md5 + "-Echo.desktop");
    ASSERT_TRUE(bf::exists(expectedDesktopFilePath));

    bf::path expectedIconFilePath =
        userDirPath / ("icons/hicolor/scalable/apps/appimagekit_" + md5 + "_utilities-terminal.svg");
    ASSERT_TRUE(bf::exists(expectedIconFilePath));
}

TEST_F(TestIntegrationManager, isARegisteredAppImage) {
    std::string appImagePath = TEST_DATA_DIR "Echo-x86_64.AppImage";
    IntegrationManager manager(userDirPath.string());

    ASSERT_FALSE(manager.isARegisteredAppImage(appImagePath));

    { // Generate fake desktop entry file
        std::string md5 = appimage::utils::hashPath(appImagePath.c_str());

        bf::path desployedDesktopFilePath = userDirPath / ("applications/appimagekit_" + md5 + "-Echo.desktop");
        createStubFile(desployedDesktopFilePath, "[Desktop Entry]");

        ASSERT_TRUE(bf::exists(desployedDesktopFilePath));
    }

    ASSERT_TRUE(manager.isARegisteredAppImage(appImagePath));
}

TEST_F(TestIntegrationManager, shallAppImageBeRegistered) {
    IntegrationManager manager;

    ASSERT_TRUE(manager.shallAppImageBeRegistered(
        appimage::core::AppImage(TEST_DATA_DIR "Echo-x86_64.AppImage")));
    ASSERT_FALSE(manager.shallAppImageBeRegistered(
        appimage::core::AppImage(TEST_DATA_DIR "Echo-no-integrate-x86_64.AppImage")));
    ASSERT_THROW(manager.shallAppImageBeRegistered(
        appimage::core::AppImage(TEST_DATA_DIR "elffile")), appimage::core::AppImageError);
}

TEST_F(TestIntegrationManager, unregisterAppImage) {
    std::string appImagePath = TEST_DATA_DIR "Echo-x86_64.AppImage";
    IntegrationManager manager(userDirPath.string());

    // Generate fake desktop entry file
    std::string md5 = appimage::utils::hashPath(appImagePath.c_str());

    bf::path desployedDesktopFilePath = userDirPath / ("applications/appimagekit_" + md5 + "-Echo.desktop");
    createStubFile(desployedDesktopFilePath, "[Desktop Entry]");
    ASSERT_TRUE(bf::exists(desployedDesktopFilePath));

    bf::path desployedIconFilePath = userDirPath /
                                     ("icons/hicolor/scalable/apps/appimagekit_" + md5 + "_utilities-terminal.svg");
    createStubFile(desployedIconFilePath, "<?xml");
    ASSERT_TRUE(bf::exists(desployedIconFilePath));

    bf::path desployedMimeTypePackageFilePath = userDirPath / ("mime/packages/appimagekit_" + md5 + "-echo.xml");
    createStubFile(desployedMimeTypePackageFilePath, "<?xml");
    ASSERT_TRUE(bf::exists(desployedMimeTypePackageFilePath));

    manager.unregisterAppImage(appImagePath);

    ASSERT_FALSE(bf::exists(desployedDesktopFilePath));
    ASSERT_FALSE(bf::exists(desployedIconFilePath));
    ASSERT_FALSE(bf::exists(desployedMimeTypePackageFilePath));
}

ext: cpp

max_stars_repo_name: srevinsaju/libappimage


text:
// Copyright 2015-2019 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HISTOGRAM_AXIS_OPTION_HPP
#define BOOST_HISTOGRAM_AXIS_OPTION_HPP

#include <boost/mp11.hpp>
#include <type_traits>

/**
  \file option.hpp Options for builtin axis types.

  Options circular and growth are mutually exclusive.
  Options circular and underflow are mutually exclusive.
*/

namespace boost {
namespace histogram {
namespace axis {

/// Holder of axis options.
template <unsigned Bits>
struct option_set : std::integral_constant<unsigned, Bits> {};

namespace option {
template <unsigned N>
struct bit : option_set<(1 << N)> {};

/// All bits set to zero.
using none = option_set<0>;
/// Axis has underflow bin. Mutually exclusive with circular.
using underflow = bit<0>;
/// Axis has overflow bin.
using overflow = bit<1>;
/// Axis is circular. Mutually exclusive with growth and underflow.
using circular = bit<2>;
/// Axis can grow. Mutually exclusive with circular.
using growth = bit<3>;
} // namespace option

} // namespace axis

namespace detail {

template <class T, class U>
struct join_impl : axis::option_set<(T::value | U::value)> {};
template <class T>
struct join_impl<T, axis::option::underflow>
    : axis::option_set<((T::value & ~axis::option::circular::value) |
                        axis::option::underflow::value)> {};
template <class T>
struct join_impl<T, axis::option::circular>
    : axis::option_set<(
          (T::value & ~(axis::option::growth::value | axis::option::underflow::value)) |
          axis::option::circular::value)> {};
template <class T>
struct join_impl<T, axis::option::growth>
    : axis::option_set<((T::value & ~axis::option::circular::value) |
                        axis::option::growth::value)> {};

} // namespace detail

namespace axis {
/// Metafunction that combines options and corrects for mutually exclusive flags.
template <class... Ts>
using join = mp11::mp_fold<mp11::mp_list<Ts...>, option_set<0>, detail::join_impl>;

/// Metafunction that tests whether the bits in b are also set in a.
template <class T, class U>
using test = std::integral_constant<bool, (T::value & U::value ? 1 : 0)>;
} // namespace axis
} // namespace histogram
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: henryiii/histogram

max_issues_repo_name: henryiii/histogram

max_forks_repo_name: henryiii/histogram


text:
/*
 * HDFFileReader.cpp
 *
 *  Created on: July 12, 2011
 *      Author: David Berrios
 */
// #include "config.h"
#include "Kameleon-plus-Config.h" //controlled by CMakeLists.txt
#ifdef HAVE_HDF5
#include "HDF5FileReader.h"
#include <string>
#include <vector>
#include <deque>
#include <iostream>
#include <fstream>
#include <queue>
#include <boost/current_function.hpp>

using namespace std;

namespace ccmc
{
	/**
	 * Default constructor. Does nothing.
	 */
	HDF5FileReader::HDF5FileReader()
	{
		this->current_file = NULL;
		this->rootGroup = NULL;
		this->variableGroup = NULL;
	}

	/**
	 * Opens a new file. If the previous file has been opened successfuly, and has the
	 * same filename as the requested filename, nothing will be done.
	 * @param filename
	 * @return The status of the open call.  This method should be called from open().
	 */
	long HDF5FileReader::openFile(const std::string& filename, bool readonly)
	{
		std::cerr << "HDF5FileReader::openFile" << std::endl;
		long status = -1L;
		if (current_file != NULL && filename != current_filename)
		{
			close();
		}

		if(!(ifstream(filename.c_str())))
		{
			status = FILE_DOES_NOT_EXIST;
			std::cerr << "Filename: \"" << filename << "\" does not exist." << std::endl;
		}
		else{
			std::cerr << "about to open HDF5 file" << std::endl;

			try
			{
				current_file = new H5::H5File(filename, H5F_ACC_RDONLY);
				this->rootGroup = new H5::Group(current_file->openGroup("/"));
				this->variableGroup = new H5::Group(current_file->openGroup("Variables"));
				int numVariables = variableGroup->getNumObjs();
				std::cerr << "num variables: " << numVariables << std::endl;
				for (int i = 0; i < numVariables; i++)
				{
					//std::cerr << "variable: " << variableGroup->getObjnameByIdx(i) << std::endl;

				}
				status = OK;
			}
			catch(H5::Exception const& ex)
			{
				status = OPEN_ERROR;
				if (current_file != NULL)
				{
					delete current_file;
					current_file = NULL;
				}
				if (rootGroup != NULL)
				{
					delete rootGroup;
					rootGroup = NULL;
				}
				if (variableGroup != NULL)
				{
					delete variableGroup;
					variableGroup = NULL;
				}
			}

			//file(filename, H5::H5F_ACC_RDONLY);
			//status = CDFopenCDF((char *)filename.c_str(), &current_file_id);

			if (status == OK)
			{
				current_filename = filename;
				FileReader::initializeGlobalAttributes();
				FileReader::initializeVariableAttributes();
				initializeVariableIDs();
				initializeVariableNames();
				//status = OK;
			} else
			{
				status = OPEN_ERROR;
				std::cerr << "Error opening hdf \"" << filename << "\". Not an hdf file?" << std::endl;
			}

		}
		//cout << "current_file_id: " << current_file_id << endl;
		//cout << "testing open in FileReader class" << endl;

		return status;
	}

	/**
	 * Closes the currently selected file.  Call this from the close() method.
	 * @return Status of close operation.
	 */
	long HDF5FileReader::closeFile()
	{
		if (current_file != NULL)
		{
			current_file->close();
			current_file = NULL;
		}

		return FileReader::OK;
	}

	/**
	 * @brief Returns a pointer to a std::vector<float> containing the values of the selected variable
	 *
	 * This allocates a new std::vector<float> pointer.  Make sure you
	 * delete the contents when you done using it, or you will have a memory leak.
	 *
	 * @param variable
	 * @return std::vector<float> containing the values of the selected variable.
	 */
	std::vector<float>* HDF5FileReader::getVariable(const std::string& variable)
	{
		std::vector<float>* variableData = new std::vector<float>();

		if (this->doesVariableExist(variable))
		{
			//std::cout << "reading " << variable << std::endl;
			//get variable number
			long variableNum = this->getVariableID(variable);

			//std::cout << "variableNum for " << variable << ": " << variableNum << std::endl;
			//get dim sizes

			H5::Group group = this->current_file->openGroup("Variables");
			//cout << "variable: " << variable << ": " << counts[0] << endl;
			H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));
			H5::DataSpace dataspace = dataset->getSpace();
			int rank = dataspace.getSimpleExtentNdims(); //should be 1
			hsize_t count[1];
			hsize_t offset[1] = {0};
			int ndims = dataspace.getSimpleExtentDims(count, NULL);

			//std::cout << "count[0]: " << count[0] << std::endl;
			float * buffer = new float[count[0]];

			dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

			H5::DataSpace memspace( rank, count);
			memspace.selectHyperslab(H5S_SELECT_SET, count, offset);

			dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);
			//std::cout << "after read" << std::endl;

			//add data to vector type, and delete original array
			variableData->reserve(count[0]);
			for (int i = 0; i < count[0]; i++)
			{
				variableData->push_back(buffer[i]);
			}
			//std::cout << "after adding to variableData vector" << std::endl;

			delete[] buffer;
			delete dataset;
			//std::cout << "finished reading " << variable << std::endl;
			//std::cout << "size of variable: " << variableData.size() << std::endl;
			//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;

		}

		return variableData;
	}

	/**
	 * Returns a pointer to a std::vector<float> containing the values of the selected variable
	 * in the range specified by the startIndex and count (the number of records to read) stored in the selected file.
	 * This allocates a new std::vector<float> pointer.  Make sure you
	 * delete the contents when you done using it, or you will have a memory leak.
	 * @param variable
	 * @param startIndex
	 * @param count
	 * @return std::vector<float> containing the values of the selected variable.
	 */
	std::vector<float>* HDF5FileReader::getVariable(const std::string& variable, long indexOffset, long length)
	{

		std::vector<float>* variableData = new std::vector<float>();

		if (this->doesVariableExist(variable))
		{
			//std::cout << "reading " << variable << std::endl;
			//get variable number
			long variableNum = this->getVariableID(variable);

			//get dim sizes

			H5::Group group = this->current_file->openGroup("Variables");
			//cout << "variable: " << variable << ": " << counts[0] << endl;
			H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));
			H5::DataSpace dataspace = dataset->getSpace();
			int rank = dataspace.getSimpleExtentNdims(); //should be 1
			hsize_t count[1] = {static_cast<hsize_t>(length)};
			hsize_t offset[1] = {static_cast<hsize_t>(indexOffset)};
			//int ndims = dataspace.getSimpleExtentDims(count, NULL);
			float * buffer = new float[count[0]];

			dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

			hsize_t dim[] = {count[0]};
			H5::DataSpace memspace( rank, dim);
			memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

			dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);

			//add data to vector type, and delete original array
			variableData->reserve(count[0]);
			for (int i = 0; i < count[0]; i++)
			{
				variableData->push_back(buffer[i]);
			}

			delete[] buffer;
			delete dataset;
			//std::cout << "finished reading " << variable << std::endl;
			//std::cout << "size of variable: " << variableData.size() << std::endl;
			//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;

		}

		return variableData;
	}

	/**
	 * Returns a pointer to a std::vector<float> containing the values of the selected variable
	 * in the range specified by the startIndex and count (the number of records to read) stored
	 * in the selected file.  This allocates a new std::vector<float> pointer.  Make sure you
	 * delete the contents when you done using it, or you will have a memory leak.
	 * @param variableID
	 * @param startIndex
	 * @param count
	 * @return std::vector<float> containing the values of the selected variable.
	 */
	std::vector<float>* HDF5FileReader::getVariable(long variable, long indexOffset, long count)
	{

		std::vector<float>* variableData = new std::vector<float>();

		//get dim sizes
		H5::Group group = this->current_file->openGroup("Variables");
		//cout << "variable: " << variable << ": " << counts[0] << endl;
		H5::DataSet * dataset = new H5::DataSet(group.openDataSet(group.getObjnameByIdx(variable)));
		H5::DataSpace dataspace = dataset->getSpace();
		int rank = dataspace.getSimpleExtentNdims(); //should be 1
		hsize_t length[1] = {static_cast<hsize_t>(count)};
		hsize_t offset[1] = {static_cast<hsize_t>(indexOffset)};
		//int ndims = dataspace.getSimpleExtentDims(count, NULL);
		float * buffer = new float[length[0]];

		dataspace.selectHyperslab(H5S_SELECT_SET, length, offset);

		hsize_t dim[] = {length[0]};
		H5::DataSpace memspace( rank, dim);
		memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

		dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);

		//add data to vector type, and delete original array
		variableData->reserve(length[0]);
		for (int i = 0; i < length[0]; i++)
		{
			variableData->push_back(buffer[i]);
		}

		delete[] buffer;
		delete dataset;
		//std::cout << "finished reading " << variable << std::endl;
		//std::cout << "size of variable: " << variableData.size() << std::endl;
		//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;
		return variableData;
	}

	/**
	 * Returns a pointer to a std::vector<float> containing the values of the selected variable
	 * stored in the selected file.  This allocates a new std::vector<float> pointer.  Make sure you
	 * delete the contents when you done using it, or you will have a memory leak.
	 * @param variable
	 * @return std::vector<float> containing the values of the selected variable.
	 */
	std::vector<float>* HDF5FileReader::getVariable(long variable)
	{

		std::vector<float>* variableData = new std::vector<float>();

		//get dim sizes
		H5::Group group = this->current_file->openGroup("Variables");
		//cout << "variable: " << variable << ": " << counts[0] << endl;
		H5::DataSet * dataset = new H5::DataSet(group.openDataSet(group.getObjnameByIdx(variable)));
		H5::DataSpace dataspace = dataset->getSpace();
		int rank = dataspace.getSimpleExtentNdims(); //should be 1
		hsize_t count[1];
		hsize_t offset[1] = {0};
		int ndims = dataspace.getSimpleExtentDims(count, NULL);
		float * buffer = new float[count[0]];

		dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

		hsize_t dim[] = {count[0]};
		H5::DataSpace memspace( rank, dim);
		memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

		dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);

		//add data to vector type, and delete original array
		variableData->reserve(count[0]);
		for (int i = 0; i < count[0]; i++)
		{
			variableData->push_back(buffer[i]);
		}

		delete[] buffer;
		delete dataset;
		//std::cout << "finished reading " << variable << std::endl;
		//std::cout << "size of variable: " << variableData.size() << std::endl;
		//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;
		return variableData;
	}

	/**
	 * @brief Returns a value in the flat array of the variable and index requested.
	 *
	 * Use this method on variables that have a type of float
	 *
	 * returns std::numeric_limits<float>::min() if missing
	 *
	 * @param variable The variable in the file
	 * @param index The index in the variable's array in the file
	 *
	 * @return float of the value in the array.
	 */
	float HDF5FileReader::getVariableAtIndex(const std::string& variable, long index)
	{

		float value = std::numeric_limits<float>::min();
		if (this->doesVariableExist(variable))
		{
			std::cout << "reading " << variable << std::endl;
			//get variable number
			long variableNum = this->getVariableID(variable);

			//get dim sizes

			H5::Group group = this->current_file->openGroup("Variables");
			//cout << "variable: " << variable << ": " << counts[0] << endl;
			H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));
			H5::DataSpace dataspace = dataset->getSpace();
			int rank = dataspace.getSimpleExtentNdims(); //should be 1
			hsize_t count[1];
			hsize_t offset[1] = {0};
			int ndims = dataspace.getSimpleExtentDims(count, NULL);
			float * buffer = new float[count[0]];

			dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

			hsize_t dim[] = {count[0]};
			H5::DataSpace memspace( rank, dim);
			memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

			dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);

			//add data to vector type, and delete original array
			value = buffer[0];
			delete[] buffer;
			delete dataset;
		}
		return value;
			//std::cout << "finished reading " << variable << std::endl;
			//std::cout << "size of variable: " << variableData.size() << std::endl;
			//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;

	}

	/**
	 * This allocates a new std::vector<int> pointer.  Make sure you
	 * delete the contents when you done using it, or you will have a memory leak.
	 * @param variable
	 * @return vector<int> containing the integer values of the variable
	 */
	std::vector<int>* HDF5FileReader::getVariableInt(const std::string& variable)
	{

		std::vector<int>* variableData = new std::vector<int>();

			//std::cout << "reading " << variable << std::endl;
			//get variable number
			long variableNum = this->getVariableID(variable);

			//get dim sizes

			H5::Group group = this->current_file->openGroup("Variables");
			//cout << "variable: " << variable << ": " << counts[0] << endl;
			H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));
			H5::DataSpace dataspace = dataset->getSpace();
			int rank = dataspace.getSimpleExtentNdims(); //should be 1
			hsize_t count[1];
			hsize_t offset[1] = {0};
			int ndims = dataspace.getSimpleExtentDims(count, NULL);
			float * buffer = new float[count[0]];

			dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

			hsize_t dim[] = {count[0]};
			H5::DataSpace memspace( rank, dim);
			memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

			dataset->read(buffer, H5::PredType::NATIVE_INT, memspace, dataspace);

			//add data to vector type, and delete original array
			variableData->reserve(count[0]);
			for (int i = 0; i < count[0]; i++)
			{
				variableData->push_back(buffer[i]);
			}

			delete[] buffer;
			delete dataset;
			//std::cout << "finished reading " << variable << std::endl;
			//std::cout << "size of variable: " << variableData.size() << std::endl;
			//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;
			return variableData;

	}

	/**
	 * @param variableNum
	 * @param index
	 * @return
	 */
	float HDF5FileReader::getVariableAtIndex(long variable, long index)
	{

		float value = std::numeric_limits<float>::min();

		//get dim sizes

		H5::Group group = this->current_file->openGroup("Variables");
		//cout << "variable: " << variable << ": " << counts[0] << endl;
		H5::DataSet * dataset = new H5::DataSet(group.openDataSet(group.getObjnameByIdx(variable)));
		H5::DataSpace dataspace = dataset->getSpace();
		int rank = dataspace.getSimpleExtentNdims(); //should be 1
		hsize_t count[1] = {1};
		hsize_t offset[1] = {static_cast<hsize_t>(index)};
		//int ndims = dataspace.getSimpleExtentDims(count, NULL);
		float * buffer = new float[count[0]];

		dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

		hsize_t dim[] = {count[0]};
		H5::DataSpace memspace( rank, dim);
		memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

		dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);

		//add data to vector type, and delete original array
		value = buffer[0];
		delete[] buffer;
		delete dataset;
		return value;
			//std::cout << "finished reading " << variable << std::endl;
			//std::cout << "size of variable: " << variableData.size() << std::endl;
			//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;

	}

	/**
	 * @brief Returns a value in the flat array of the variable and index requested.
	 *
	 * Use this method on variables that have a type of int
	 *
	 * @param variable The variable in the file
	 * @param index The index in the variable's array in the file
	 *
	 * @return int of the value in the array.
	 */
	int HDF5FileReader::getVariableIntAtIndex(const std::string& variable, long index)
	{
		long counts[1];
		int value = std::numeric_limits<int>::min();
		if (this->doesVariableExist(variable))
		{
			//std::cout << "reading " << variable << std::endl;
			//get variable number
			long variableNum = this->getVariableID(variable);

			//get dim sizes

			H5::Group group = this->current_file->openGroup("Variables");
			//cout << "variable: " << variable << ": " << counts[0] << endl;
			H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));
			H5::DataSpace dataspace = dataset->getSpace();
			int rank = dataspace.getSimpleExtentNdims(); //should be 1
			hsize_t count[1] = {1};
			hsize_t offset[1] = {0};
			//int ndims = dataspace.getSimpleExtentDims(count, NULL);
			float * buffer = new float[count[0]];

			dataspace.selectHyperslab(H5S_SELECT_SET, count, offset);

			hsize_t dim[] = {count[0]};
			H5::DataSpace memspace( rank, dim);
			memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

			dataset->read(buffer, H5::PredType::NATIVE_INT, memspace, dataspace);

			//add data to vector type, and delete original array
			value = buffer[0];
			delete[] buffer;
			delete dataset;
		}
		return value;
			//std::cout << "finished reading " << variable << std::endl;
			//std::cout << "size of variable: " << variableData.size() << std::endl;
			//std::cout << "dimSizes[0]: " << dimSizes[0] << std::endl;

	}

	/**
	 * @param i The attribute number
	 * @return
	 */
	Attribute HDF5FileReader::getGlobalAttribute(long i)
	{

		std::cerr << "entered " << BOOST_CURRENT_FUNCTION << " i = " << (int)i << std::endl;
		H5::Group group = this->current_file->openGroup("/");
		std::cout<< "group assigned\n";
		H5::Attribute h5attribute = group.openAttribute((unsigned int)i);
		std::cout<< "attribute opened\n";
		H5::DataType dataType = h5attribute.getDataType();
		std::cout<< "dataType retrieved\n";
		Attribute attribute;
		std::cout << "checking dataType"<<std::endl;
		if (dataType.getClass() == H5T_STRING)
		{
			std::string attributeValue = "NULL";
			h5attribute.read(dataType, attributeValue);

			std::string attributeName = "";
			attributeName = h5attribute.getName();

			attribute.setAttributeName(attributeName);
			//std::cout << "name: '" << attributeName << "' string attributeBuffer: '" << attributeValue << "'"<< std::endl;
			attribute.setAttributeValue(attributeValue);
			gAttributeByID[i] = attribute;
			gAttributes[attribute.getAttributeName()] = attribute;
			//return attribute;
		} else if (dataType.getClass() == H5T_INTEGER)
		{
			//int attributeValue = 0.f;
			int attributeBuffer;// = new int[1];

			h5attribute.read(dataType, &attributeBuffer);
			std::string attributeName = "";
			attributeName = h5attribute.getName();
			attribute.setAttributeName(attributeName);
			//std::cout << "int attributeBuffer: '" << attributeBuffer << "'"<< std::endl;
			attribute.setAttributeValue(attributeBuffer);
			gAttributeByID[i] = attribute;
			gAttributes[attribute.getAttributeName()] = attribute;
			//return attribute;
		} else if (dataType.getClass() == H5T_FLOAT)//CDF_FLOAT
		{
			//int attributeValue = 0.f;
			float attributeValue;// = new int[1];

			h5attribute.read(dataType, &attributeValue);
			std::string attributeName = "";
			attributeName = h5attribute.getName();
			attribute.setAttributeName(attributeName);
			//std::cout << "float attributeBuffer: '" << attributeValue << "'"<< std::endl;

			attribute.setAttributeValue(attributeValue);
			gAttributeByID[i] = attribute;
			gAttributes[attribute.getAttributeName()] = attribute;
			//return attribute;
		}

		//std::cout << "added: " << i << " name: '" << attribute.getAttributeName() << "'" << endl;
		//std::cout << "Attribute: " << attribute.toString() << std::endl;
		return attribute;

	}

	/**
	 * @param attribute
	 * @return
	 */
	Attribute HDF5FileReader::getGlobalAttribute(const std::string& attribute)
	{
		//first, check if the attribute has already been requested. If so, return stored value
		boost::unordered_map<std::string, Attribute>::iterator iter = gAttributes.find(attribute);
		if (iter != gAttributes.end())
			return (*iter).second;

//		std::cout << "after search in getGlobalAttribute(const std::string& attribute)" << std::endl;
//		std::cout << "attribute: " << attribute << std::endl;
		H5::Group group = this->current_file->openGroup("/");
		H5::Attribute h5attribute = group.openAttribute(attribute);
		long attrNum = h5attribute.getId();
		H5::DataType dataType = h5attribute.getDataType();
//		std::cout << "attrNum after attribute: " << attrNum << std::endl;
		Attribute current_attribute;
		if (attrNum < 0)
		{
			std::cout << "attrNum: " << attrNum << " returned for " << attribute << std::endl;
		}
		else
		{
//			std::cout << "attribute: " << attribute << " attribute number: " << attrNum << std::endl;
//			std::cout << "attempting to get attribute without using attribute number\n";
			if (dataType.getClass() == H5T_STRING)
			{
				std::string attributeValue = "NULL";
				h5attribute.read(dataType, attributeValue);

				std::string attributeName = "";
				attributeName = h5attribute.getName();

				current_attribute.setAttributeName(attributeName);
				//std::cout << "name: '" << attributeName << "' string attributeBuffer: '" << attributeValue << "'"<< std::endl;
				current_attribute.setAttributeValue(attributeValue);
				gAttributeByID[(int)attrNum] = current_attribute;
				gAttributes[current_attribute.getAttributeName()] = current_attribute;
				//return attribute;
			} else if (dataType.getClass() == H5T_INTEGER)
			{
				//int attributeValue = 0.f;
				int attributeBuffer;// = new int[1];

				h5attribute.read(dataType, &attributeBuffer);
				std::string attributeName = "";
				attributeName = h5attribute.getName();
				current_attribute.setAttributeName(attributeName);
				//std::cout << "int attributeBuffer: '" << attributeBuffer << "'"<< std::endl;
				current_attribute.setAttributeValue(attributeBuffer);
				gAttributeByID[(int)attrNum] = current_attribute;
				gAttributes[current_attribute.getAttributeName()] = current_attribute;
				//return attribute;
			} else if (dataType.getClass() == H5T_FLOAT)//CDF_FLOAT
			{
				//int attributeValue = 0.f;
				float attributeValue;// = new int[1];

				h5attribute.read(dataType, &attributeValue);
				std::string attributeName = "";
				attributeName = h5attribute.getName();
				current_attribute.setAttributeName(attributeName);
				//std::cout << "float attributeBuffer: '" << attributeValue << "'"<< std::endl;

				current_attribute.setAttributeValue(attributeValue);
				gAttributeByID[(int)attrNum] = current_attribute;
				gAttributes[current_attribute.getAttributeName()] = current_attribute;
				//return attribute;
			}

		}//gAttributes[attribute] = current_attribute;
		return current_attribute;
//		return Attribute();
	}

	/**
		 * @param attribute
		 * @return
		 */
		long HDF5FileReader::getGlobalAttributeID(const std::string& attribute)
		{
			//long attrNum = CDFgetAttrNum(current_file_id, (char *) attribute.c_str());
			long attrNum = 0;
			return attrNum;
		}

	/**
	 * @param variable
	 * @param vattribute
	 * @return
	 */
	Attribute HDF5FileReader::getVariableAttribute(const std::string& variable, const std::string& vattribute)
	{

		//first, check the vAttributes map
//		std::cout<<"Checking variable attributes map\n";
		boost::unordered_map<std::string, boost::unordered_map< std::string, Attribute> >::iterator iter =
				vAttributes.find(variable);
		if (iter != vAttributes.end())
		{
			boost::unordered_map< std::string, Attribute>::iterator iter2 = vAttributes[variable].find(vattribute);
			if (iter2 != vAttributes[variable].end())
			{
				return (*iter2).second;
			}
		}
	//	std::cout<<"Attribute not loaded, opening Variables group\n";

		H5::Group group = this->current_file->openGroup("Variables");
	//	std::cout<<"Group opened. Creating memory for H5::DataSet\n";
		H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));
	//	std::cout<<"creating h5attribute for variable\n";
		H5::Attribute h5attribute = dataset->openAttribute(vattribute); //changed from group.openAttribute(vattribute);
	//	std::cout<<"attribute opened, obtaining data type\n";
		H5::DataType dataType = h5attribute.getDataType();
		Attribute attribute;
	//	std::cerr<<"Retrieving Variable attribute info:"<<std::endl;
		if (dataType.getClass() == H5T_STRING)
		{
//			std::cout<<"String type variable attribute\n";
			std::string attributeValue = "NULL";
			h5attribute.read(dataType, &attributeValue);

			std::string attributeName = "";
			attributeName = h5attribute.getName();

			attribute.setAttributeName(attributeName);
			//std::cout << "attributeBuffer: " << attributeBuffer << endl;
			attribute.setAttributeValue(attributeValue);
			//return attribute;
		} else if (dataType.getClass() == H5T_INTEGER) //shouldn't this be H5T_INT or something?
		{
//			std::cout<<"Int type variable attribute\n";
			//int attributeValue = 0.f;
			int attributeBuffer;// = new int[1];

			h5attribute.read(dataType, &attributeBuffer);
			std::string attributeName = "";
			attributeName = h5attribute.getName();
			attribute.setAttributeName(attributeName);
			attribute.setAttributeValue(attributeBuffer);
			//return attribute;
		} else if (dataType.getClass() == H5T_FLOAT)//CDF_FLOAT
		{
//			std::cout<<"Float type variable attribute\n";
			//int attributeValue = 0.f;
			float attributeValue;// = new int[1];

			h5attribute.read(dataType, &attributeValue);
			std::string attributeName = "";
			attributeName = h5attribute.getName();
			attribute.setAttributeName(attributeName);
			attribute.setAttributeValue(attributeValue);
			//return attribute;
		}

		//cout << "added: " << i << " name: " << attribute.getAttributeName() << endl;
		//std::cout << "Attribute: " << attribute.toString() << std::endl;

		(vAttributes[variable])[vattribute] = attribute;
		return attribute;

	}

	/**
	 * TODO
	 * Retrieves the number of global attributes in the selected file.  This is useful for iterating over all
	 * available global attributes.
	 * @return The number of global attributes stored in the selected file.
	 */
	int HDF5FileReader::getNumberOfGlobalAttributes()
	{
		long num_attributes;
		H5::Group group = this->current_file->openGroup("/");
		num_attributes = group.getNumAttrs();
		return (int)num_attributes;
	}

	/**
	 * @param attribute
	 * @return
	 */
	bool HDF5FileReader::doesAttributeExist(const std::string& attribute)
	{
		bool exists = false;
		H5::Group group = this->current_file->openGroup("/");
		try
		{
			group.openAttribute(attribute);
			exists = true;
		} catch (H5::AttributeIException& e)
		{
			exists = false;
		}
		return exists;

	}

	/**
	 * Returns the variable ID as a long. Using the variable ID wherever possible is significantly faster than the
	 * equivalent methods accepting the variable string.
	 * @return Status of the file operation.
	 */
	long HDF5FileReader::getVariableID(const std::string& variable)
	{
		//first, check the current variableIDs map.  fetching the variableID from the file is expensive
		boost::unordered_map<std::string, long>::iterator iter = variableIDs.find(variable);
		if (iter != variableIDs.end())
			return (*iter).second;
		else
		{
			//since we prefetched all of the variables on open, it shouldn't exist
			return -1;
		}

		/*std::cout << "getting variable id for: " << variable << std::endl;
		long variableNumber = CDFgetVarNum((void *) current_file_id, (char *) variable.c_str());
		//std::cout << "variableNumber: " << variableNumber << std::endl;
		if (variableNumber >= 0) //we want to keep the crappy negative ids
			variableIDs[variable] = variableNumber;

		return variableNumber;*/
	}

	/**
	 * Returns the string representation of the variable referred to by variable_id
	 * @return String representation of the variable.
	 */
	std::string HDF5FileReader::getVariableName(long variable)
	{
		//first, check the current variableNames map.  fetching the variableNames from the file is expensive
		boost::unordered_map<long, std::string>::iterator iter = variableNames.find(variable);
		if (iter != variableNames.end())
			return (*iter).second;
		std::string variableName = this->variableGroup->getObjnameByIdx(variable);

		if (variableName != "")
		{
			variableNames[variable] = variableName;
		}
		return variableName;
	}

	/**
	 * @param variable
	 * @return
	 */
	bool HDF5FileReader::doesVariableExist(const std::string& variable)
	{

		//first, check the current variableIDs map.  fetching the variableID from the file is expensive
		boost::unordered_map<std::string, long>::iterator iter = variableIDs.find(variable);
		if (iter != variableIDs.end())
			return true;
/*
		try
		{
			H5::DataSet * dataset = new H5::DataSet(this->variableGroup->openDataSet(variable));
			long variableNumber = dataset->getId();
			//std::cout << "variableNumber: " << variableNumber << std::endl;
			if (variableNumber >= 0)
			{
				variableIDs[variable] = variableNumber;
				variableNames[variableNumber] = variable;
				return true;
			}
		} catch (H5::Exception const& ex)
		{

		}*/

		return false;
	}

	/**
	 * Returns the current filename.
	 * @return The current filename.
	 */
	const std::string& HDF5FileReader::getCurrentFilename()
	{
		return this->current_filename;
	}

	/**
	 *@param attribute_id
	 *@return
	 */
	std::string HDF5FileReader::getGlobalAttributeName(long attribute_id)
	{
//		CDFgetAttrName((void *) current_file_id, attribute_id, buffer);
		H5::Attribute attribute = this->rootGroup->openAttribute(attribute_id);
		std::string buffer_string = attribute.getName();
		//cout << "Attribute Name: '" << buffer_string << "'" << endl;

		return buffer_string;
	}

	/**
	 *@return
	 */
	int HDF5FileReader::getNumberOfVariables()
	{
		long numVars;
		H5::Group group = this->current_file->openGroup("Variables");
		numVars = group.getNumObjs();
		return (int)numVars;
	}

	/**
	 * Helper method to initialize a map containing variable IDs.  This solves some issues
	 * with threaded operations on CDF files.
	 */
	void HDF5FileReader::initializeVariableIDs()
	{
		int numVariables = this->getNumberOfVariables();
		//cout << "numVariables: " << numVariables << endl;
		for (int i = 0; i < numVariables; i++)
		{
			std::string variableName = this->variableGroup->getObjnameByIdx(i);
			variableIDs[variableName] = i;
//			std::cout << "variable[" << i << "]: " << variableName << std::endl;
		}
	}

	/**
	 * Helper method to initialize a variable names map. This solves some issues with
	 * threaded operations on CDF files.
	 */
	void HDF5FileReader::initializeVariableNames()
	{
		int numVariables = this->getNumberOfVariables();
		//cout << "numVariables: " << numVariables << endl;

		std::string variableName = "";
		for (int i = 0; i < numVariables; i++)
		{
			std::string variableName = this->variableGroup->getObjnameByIdx(i);
			variableNames[(long)i] = variableName;

		}
	}

	/**
	 * Gets the number of variable attributes.
	 * @return The number of variable attributes in the opened file.
	 */
	int HDF5FileReader::getNumberOfVariableAttributes()
	{
		int numVAttributes;

		//get the first variable and see how many attributes. They should all be the same.
		H5::DataSet dataset = this->variableGroup->openDataSet(this->variableGroup->getObjnameByIdx(0));
		numVAttributes = dataset.getNumAttrs();
		return numVAttributes;
	}

	/**
	 * @param attribute_id
	 * @return String representing the name of the attribute specified by attribute_id
	 */
	std::string HDF5FileReader::getVariableAttributeName(long attribute_id)
	{
		H5::DataSet dataset = this->variableGroup->openDataSet(this->variableGroup->getObjnameByIdx(0));
		H5::Attribute attribute = dataset.openAttribute(attribute_id);
		std::string buffer = attribute.getName();
		cout << "Attribute Name: '" << buffer << "'" << endl;
		return buffer;
	}

	/**
	 * @param variable
	 * @return
	 */
	long HDF5FileReader::getNumberOfRecords(const std::string& variable)
	{
		//std::cout << "reading " << variable << std::endl;
		//get variable number
		H5::DataSet dataset = this->variableGroup->openDataSet(variable);

		H5::DataSpace dataspace = dataset.getSpace();
		hsize_t count[1];
		int ndims = dataspace.getSimpleExtentDims(count, NULL);
		return (long)count[0];
	}

	/**
	 * @param variable_id
	 * @return
	 */
	long HDF5FileReader::getNumberOfRecords(long variable)
	{
		return getNumberOfRecords(this->variableGroup->getObjnameByIdx(variable));
	}

	/**
	 * @return
	 */
	std::vector<std::string> HDF5FileReader::getVariableAttributeNames()
	{
		std::vector<std::string> attributeNames;
		int numAttributes = this->getNumberOfVariableAttributes();
		H5::DataSet dataset = this->variableGroup->openDataSet(this->variableGroup->getObjnameByIdx(0));
		for (int i = 0; i < numAttributes; i++)
		{
			std::string value = "";
			H5::Attribute attribute = dataset.openAttribute(i);
			attributeNames.push_back(attribute.getName());

		}
		return attributeNames;
	}

	/**
	 * Destructor
	 */
	HDF5FileReader::~HDF5FileReader()
	{
		if (current_file != NULL)
			close();
	}
}
#endif /* HAVE_HDF5 */

max_stars_repo_name: alexanderbock/Kameleon-Converter

max_issues_repo_name: alexanderbock/Kameleon-Converter

max_forks_repo_name: alexanderbock/Kameleon-Converter


text:
// Date Last Altered: $Date: 2007-01-06 16:37:40 -0500 (Sat, 06 Jan 2007) $
// Revision Number: $Revision: 71 $
//--------------------------------------------*-C++-*------------------------------------//
/// \file: Iterator.hh
/// \author Greg Davidson
/// \date November 6, 2006
///
/// \brief This file provides the interface and implementation of the Iterator class
///
/// This file provides the interface and implementation of the Iterator class.
/// Iterators are wrappers for STL iterators with range checking  provided.
/// Additionally, these iterators prevent comparisons between Iterators that belong to
/// unrelated classes but share implementation details (i.e., we
/// don't want to be able to compare iterators between zone-centered fields and
/// node-centered fields).

#ifndef ITERATOR_HH
#define ITERATOR_HH

#include <iterator>
#include <boost/utility.hpp>
#include "IteratorExcept.hh"

using std::iterator_traits;
using std::iterator;
using boost::addressof;

/// \brief Provides a type-safe iterator with optional checking
///
/// Iterators are wrappers for STL iterators with range checking  provided.
/// Additionally, these iterators prevent comparisons between Iterators that belong to
/// unrelated classes but share implementation details (i.e., we
/// don't want to be able to compare iterators between zone-centered fields and
/// node-centered fields).
template<typename Cont, typename Iter = typename Cont::iterator, typename Type = Cont>
class Iterator : public iterator< typename iterator_traits<Iter>::iterator_category,
								  typename iterator_traits<Iter>::value_type,
								  typename iterator_traits<Iter>::difference_type,
								  typename iterator_traits<Iter>::pointer,
								  typename iterator_traits<Iter>::reference >
{
public:
	/// Type of unchecked-iterators we are using
	typedef Iter iterator_type;

	/// Default constructor.
	Iterator() : mContainer(), mIter() {  }
	/// Constructor taking a container and an iterator into that container
    Iterator(const Cont& cont_in, const Iter& x) throw(IteratorOutOfRange)
			: mContainer(addressof(cont_in)), mIter(x)
	{
#ifndef NITERCHK
		if(mIter > mContainer->end() || mIter < mContainer->begin()-1)
			throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
	}

	/// Copy Constructor
	Iterator(const Iterator<Cont, Iter, Type>& iter_in)
			: mContainer(iter_in.mContainer), mIter(iter_in.mIter)
	{ }

	/// Constructor taking an Iterator
    //template<typename Cont_2, typename Iter_2, typename Type_2>
	template<typename Iter_2>
    Iterator(const Iterator<Cont, Iter_2, Type>& iter_in)
			: mContainer(addressof(iter_in.container())),  mIter(iter_in.iterator())
	{ }

	/// Copy Operator
	const Iterator& operator=(const Iterator<Cont, Iter, Type>& iter_in)
	{
		mContainer = iter_in.mContainer;
		mIter = iter_in.mIter;

		return *this;
	}

	/// Return the unchecked iterator
    Iter iterator() const { return mIter; }
	/// Return a reference to the container
    const Cont& container() const { return *mContainer; }

	/// Dereference operator
    typename Iter::reference operator*() const throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter == mContainer->begin()-1 || mIter == mContainer->end())
			throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		return *mIter;
	}

	/// Pointer to member operator
    typename Iter::pointer operator->() const throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter == mContainer->begin()-1 || mIter == mContainer->end())
			throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		return &(*mIter);
	}

	/// Bracket operator
    typename Iter::reference operator[](typename Iter::difference_type n) const throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter+n < mContainer->begin() || mIter+n >= mContainer->end())
			throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		return mIter[n];
	}

	/// Increment prefix operator
    Iterator<Cont, Iter, Type>& operator++() throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter == mContainer->end()) throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		++mIter;
		return *this;
	}
	/// Increment postfix operator
	Iterator<Cont, Iter, Type> operator++(int) throw(IteratorOutOfRange)
	{
		Iterator<Cont, Iter, Type> tmp = *this;
		++mIter;
		return tmp;
	}
    /// Decrement prefix operator
    Iterator<Cont, Iter, Type>& operator--() throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter == mContainer->begin()-1) throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		--mIter;
		return *this;
	}
	/// Decrement postfix operator
    Iterator<Cont, Iter, Type> operator--(int) throw(IteratorOutOfRange)
	{
		Iterator<Cont, Iter, Type> tmp = *this;
		--mIter;
		return tmp;
	}
	/// Addition operator
    Iterator<Cont, Iter, Type> operator+(typename Iter::difference_type n) const
		throw(IteratorOutOfRange)
	{
		return Iterator<Cont, Iter, Type>(*mContainer, mIter+n);
	}
    /// Plus-equal operator
    Iterator<Cont, Iter, Type>& operator+=(typename Iter::difference_type n) const
		throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter+n < mContainer->begin() || mIter+n > mContainer->end())
			throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		mIter += n;
		return *this;
	}
	/// Subtraction operator
    Iterator<Cont, Iter, Type> operator-(typename Iter::difference_type n) const
		throw(IteratorOutOfRange)
	{
		return Iterator<Cont, Iter, Type>(*mContainer, mIter-n);
	}
	/// Minus-equal operator
    Iterator<Cont, Iter, Type>& operator-=(typename Iter::difference_type n) const
		throw(IteratorOutOfRange)
	{
#ifndef NITERCHK
		if(mIter-n < mContainer->begin() || mIter-n > mContainer->end())
			throw(IteratorOutOfRange(__LINE__, __FILE__));
#endif
		mIter -= n;
		return *this;
	}
	/// Difference operator
    template<typename Iter_2>
    typename Iter::difference_type operator-(const Iterator<Cont, Iter_2, Type>& iter_in) const
	{
		return mIter - iter_in.iterator();
	}

private:
    const Cont* mContainer; ///< Pointer to the container
    Iter mIter; ///< Store the container's unchecked iterator
};

// ******* Here's where we start to differ with Iterators.  We only allow comparisons between
// iterators that share the Cont, and not just the Impl.

/// Plus operator
template<typename Cont, typename Iter, typename Type>
Iterator<Cont, Iter, Type> operator+(typename Iter::difference_type n,
									 const Iterator<Cont, Iter, Type>& iter)
{
	return iter+n;
}

/// Subtraction operator
template<typename Cont, typename Iter, typename Type>
Iterator<Cont, Iter, Type> operator-(typename Iter::difference_type n,
									 const Iterator<Cont, Iter, Type>& iter)
{
	return iter-n;
}

// ******* Comparison operators ******
/// Equal comparison between two different iterators over the same container
template<typename Cont, typename Iter1, typename Iter2, typename Type>
bool operator==(const Iterator<Cont, Iter1, Type>& iter1,
				const Iterator<Cont, Iter2, Type>& iter2)
{
	if( &(iter1.container()) == &(iter2.container()) && iter1.iterator() == iter2.iterator())
		return true;
	else return false;
}

/// Not-equal comparison between two different iterators over the same container.
template<typename Cont, typename Iter1, typename Iter2, typename Type>
bool operator!=(const Iterator<Cont, Iter1, Type>& iter1,
				const Iterator<Cont, Iter2, Type>& iter2)
{
	return !(iter1==iter2);
}
/// Less-than comparison between two different iterators over the same container.
template<typename Cont, typename Iter1, typename Iter2, typename Type>
bool operator<(const Iterator<Cont, Iter1, Type>& iter1,
			   const Iterator<Cont, Iter2, Type>& iter2)
{
	if( iter1.iterator() < iter2.iterator())
		return true;
	else return false;
}
/// Greater-than comparison between two different iterators over the same container.
template<typename Cont, typename Iter1, typename Iter2, typename Type>
bool operator>(const Iterator<Cont, Iter1, Type>& iter1,
			   const Iterator<Cont, Iter2, Type>& iter2)
{
	if( iter1.iterator() > iter2.iterator())
		return true;
	else return false;
}
/// Less-than or equal Comparison between two different iterators over the same container.
template<typename Cont, typename Iter1, typename Iter2, typename Type>
bool operator<=(const Iterator<Cont, Iter1, Type>& iter1,
				const Iterator<Cont, Iter2, Type>& iter2)
{
	if( iter1.iterator() <= iter2.iterator())
		return true;
	else return false;
}
/// Greater-than or equal Comparison between two different iterators over the same container.
template<typename Cont, typename Iter1, typename Iter2, typename Type>
bool operator>=(const Iterator<Cont, Iter1, Type>& iter1, const Iterator<Cont, Iter2, Type>& iter2)
{
	if( iter1.iterator() >= iter2.iterator())
		return true;
	else return false;
}

#endif

ext: hh

max_stars_repo_name: jlconlin/PhDThesis

max_issues_repo_name: jlconlin/PhDThesis

max_forks_repo_name: jlconlin/PhDThesis


text:
// Copyright (c) 2019 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "math-server" project.
// For details, see https://github.com/egor-tensin/math-server.
// Distributed under the MIT License.

#include <lexer/details/parse.hpp>
#include <lexer/error.hpp>
#include <lexer/lexer.hpp>
#include <lexer/token.hpp>
#include <lexer/token_type.hpp>

#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test.hpp>

#include <ostream>
#include <string>
#include <string_view>
#include <vector>

namespace bdata = boost::unit_test::data;
using math::server::Lexer;
using math::server::LexerError;
using math::server::lexer::Token;
using math::server::lexer::token::Type;
namespace details = math::server::lexer::details;

namespace std {

ostream& operator<<(ostream& os, const vector<Token>& tokens) {
    for (const auto& token : tokens) {
        os << token;
    }
    return os;
}

} // namespace std

namespace {
namespace get_tokens::valid {

// clang-format off
// wtf, don't binpack this
const std::vector<std::string_view> input{
    "",
    " + - ",
    "1+2",
    ".5^-1 ^ 4",
    "1+2 *  (3- 4e-2)",
    " 2 * (1 + 3 * (1 - -3)) ",
};
// clang-format on

const std::vector<std::vector<Token>> expected{
    {},
    {
        Token{Type::PLUS},
        Token{Type::MINUS},
    },
    {
        Token{1},
        Token{Type::PLUS},
        Token{2},
    },
    {
        Token{.5},
        Token{Type::CARET},
        Token{Type::MINUS},
        Token{1},
        Token{Type::CARET},
        Token{4},
    },
    {
        Token{1},
        Token{Type::PLUS},
        Token{2},
        Token{Type::ASTERISK},
        Token{Type::LEFT_PAREN},
        Token{3},
        Token{Type::MINUS},
        Token{4e-2},
        Token{Type::RIGHT_PAREN},
    },
    {
        Token{2},
        Token{Type::ASTERISK},
        Token{Type::LEFT_PAREN},
        Token{1},
        Token{Type::PLUS},
        Token{3},
        Token{Type::ASTERISK},
        Token{Type::LEFT_PAREN},
        Token{1},
        Token{Type::MINUS},
        Token{Type::MINUS},
        Token{3},
        Token{Type::RIGHT_PAREN},
        Token{Type::RIGHT_PAREN},
    },
};

} // namespace get_tokens::valid

namespace get_tokens::invalid {

const std::vector<std::string_view> input{
    "&",
    " 1 + 123 & 456",
};

const std::vector<std::string> error_msg{
    "server error: lexer error: invalid input at: &",
    "server error: lexer error: invalid input at: & 456",
};

} // namespace get_tokens::invalid
} // namespace

BOOST_AUTO_TEST_SUITE(lexer_tests)

BOOST_AUTO_TEST_CASE(test_parse_number) {
    // These are valid numbers:
    BOOST_TEST(details::parse_number("0").value() == 0);
    BOOST_TEST(details::parse_number("1.").value() == 1.);
    BOOST_TEST(details::parse_number(".1").value() == .1);
    // parse_* functions only consume a single token:
    BOOST_TEST(details::parse_number(".1+1").value() == .1);
    BOOST_TEST(details::parse_number("1e3").value() == 1e3);
    BOOST_TEST(details::parse_number(".123e1").value() == .123e1);
    BOOST_TEST(details::parse_number("123e-1").value() == 123e-1);
    BOOST_TEST(details::parse_number("123e+1").value() == 123e+1);
    BOOST_TEST(details::parse_number("1.e6").value() == 1.e6);
    BOOST_TEST(details::parse_number("2.3e-4").value() == 2.3e-4);
    // These are not numbers, but perhaps something else?
    BOOST_TEST(!details::parse_number(".").has_value());
    BOOST_TEST(!details::parse_number(".e3").has_value());
    BOOST_TEST(!details::parse_number("e12").has_value());
    // This is definitely a number, but a malformed one (an exponent must be
    // followed by some digits).
    BOOST_CHECK_THROW(details::parse_number("12e"), LexerError);
}

BOOST_AUTO_TEST_CASE(test_parse_const_token) {
    BOOST_TEST(details::parse_const_token("+").value() == Type::PLUS);
    // parse_* functions only consume a single token:
    BOOST_TEST(details::parse_const_token("+/*").value() == Type::PLUS);
    BOOST_TEST(details::parse_const_token("-").value() == Type::MINUS);
    BOOST_TEST(details::parse_const_token("^^").value() == Type::CARET);
    BOOST_TEST(!details::parse_const_token("&+").has_value());
}

BOOST_DATA_TEST_CASE(test_get_tokens_valid,
                     bdata::make(get_tokens::valid::input) ^ get_tokens::valid::expected,
                     input,
                     expected) {
    Lexer lexer{input};
    const auto actual = lexer.get_tokens();
    BOOST_CHECK_EQUAL_COLLECTIONS(actual.cbegin(), actual.cend(), expected.cbegin(),
                                  expected.cend());
}

BOOST_DATA_TEST_CASE(test_get_tokens_invalid,
                     bdata::make(get_tokens::invalid::input) ^ get_tokens::invalid::error_msg,
                     input,
                     error_msg) {
    BOOST_REQUIRE_THROW(
        do {
            Lexer lexer{input};
            lexer.get_tokens();
        } while (0),
        LexerError);

    try {
        Lexer lexer{input};
        lexer.get_tokens();
    } catch (const LexerError& e) {
        BOOST_TEST(error_msg == e.what());
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: egor-tensin/math-server

max_issues_repo_name: egor-tensin/math-server

max_forks_repo_name: egor-tensin/math-server


text:
#include <boost/test/unit_test.hpp>

#include "init.h"
#include "main.h"
#include "util.h"

BOOST_AUTO_TEST_SUITE(allocator_tests)

static const void *last_lock_addr, *last_unlock_addr;
static size_t last_lock_len, last_unlock_len;
class TestLocker
{
public:
    bool Lock(const void *addr, size_t len)
    {
        last_lock_addr = addr;
        last_lock_len = len;
        return true;
    }
    bool Unlock(const void *addr, size_t len)
    {
        last_unlock_addr = addr;
        last_unlock_len = len;
        return true;
    }
};

BOOST_AUTO_TEST_CASE(test_LockedPageManagerBase)
{
    const size_t test_page_size = 4096;
    LockedPageManagerBase<TestLocker> lpm(test_page_size);
    size_t addr;
    last_lock_addr = last_unlock_addr = 0;
    last_lock_len = last_unlock_len = 0;

    addr = 0;
    for(int i=0; i<1000; ++i)
    {
        lpm.LockRange(reinterpret_cast<void*>(addr), 33);
        addr += 33;
    }

    addr = test_page_size*100 + 53;
    for(int i=0; i<100; ++i)
    {
        lpm.LockRange(reinterpret_cast<void*>(addr), test_page_size);
        addr += test_page_size;
    }

    addr = test_page_size*300;
    for(int i=0; i<100; ++i)
    {
        lpm.LockRange(reinterpret_cast<void*>(addr), test_page_size);
        addr += test_page_size;
    }

    lpm.LockRange(reinterpret_cast<void*>(test_page_size*600+1), test_page_size*500);
    BOOST_CHECK(last_lock_addr == reinterpret_cast<void*>(test_page_size*(600+500)));

    lpm.LockRange(reinterpret_cast<void*>(test_page_size*1200), test_page_size*500-1);
    BOOST_CHECK(last_lock_addr == reinterpret_cast<void*>(test_page_size*(1200+500-1)));

    BOOST_CHECK(lpm.GetLockedPageCount() == (

    addr = 0;
    for(int i=0; i<1000; ++i)
    {
        lpm.UnlockRange(reinterpret_cast<void*>(addr), 33);
        addr += 33;
    }
    addr = test_page_size*100 + 53;
    for(int i=0; i<100; ++i)
    {
        lpm.UnlockRange(reinterpret_cast<void*>(addr), test_page_size);
        addr += test_page_size;
    }
    addr = test_page_size*300;
    for(int i=0; i<100; ++i)
    {
        lpm.UnlockRange(reinterpret_cast<void*>(addr), test_page_size);
        addr += test_page_size;
    }
    lpm.UnlockRange(reinterpret_cast<void*>(test_page_size*600+1), test_page_size*500);
    lpm.UnlockRange(reinterpret_cast<void*>(test_page_size*1200), test_page_size*500-1);

    BOOST_CHECK(lpm.GetLockedPageCount() == 0);

    addr = 0;
    for(int i=0; i<1000; ++i)
    {
        lpm.LockRange(reinterpret_cast<void*>(addr), 0);
        addr += 1;
    }
    BOOST_CHECK(lpm.GetLockedPageCount() == 0);
    addr = 0;
    for(int i=0; i<1000; ++i)
    {
        lpm.UnlockRange(reinterpret_cast<void*>(addr), 0);
        addr += 1;
    }
    BOOST_CHECK(lpm.GetLockedPageCount() == 0);

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: sarakas/hellascoin

max_issues_repo_name: sarakas/hellascoin

max_forks_repo_name: sarakas/hellascoin


text: #include <boost/fusion/view/zip_view/zip_view_iterator.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino