<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <map>

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"

namespace {

class FrameRateTest : public UIPerfTest {
 public:
  FrameRateTest() {
    show_window_ = true;
    dom_automation_enabled_ = true;
  }

  virtual FilePath GetDataPath(const std::string& name) {
    // Make sure the test data is checked out.
    FilePath test_path;
    PathService::Get(chrome::DIR_TEST_DATA, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("perf"));
    test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate"));
    test_path = test_path.Append(FILE_PATH_LITERAL("content"));
    test_path = test_path.AppendASCII(name);
    return test_path;
  }

  void RunTest(const std::string& name, const std::string& suffix) {
    FilePath test_path = GetDataPath(name);
    ASSERT_TRUE(file_util::DirectoryExists(test_path))
        << "Missing test directory: " << test_path.value();

    test_path = test_path.Append(FILE_PATH_LITERAL("test.html"));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
              tab->NavigateToURL(net::FilePathToFileURL(test_path)));

    // Start the tests.
    ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();")));

    // Block until the tests completes.
    ASSERT_TRUE(WaitUntilJavaScriptCondition(
        tab, L"", L"window.domAutomationController.send(!__running_all);",
        TestTimeouts::huge_test_timeout_ms()));

    // Read out the results.
    std::wstring json;
    ASSERT_TRUE(tab->ExecuteAndExtractString(
        L"",
        L"window.domAutomationController.send("
        L"JSON.stringify(__calc_results_total()));",
        &json));

    std::map<std::string, std::string> results;
    ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));

    ASSERT_TRUE(results.find("mean") != results.end());
    ASSERT_TRUE(results.find("sigma") != results.end());
    ASSERT_TRUE(results.find("gestures") != results.end());
    ASSERT_TRUE(results.find("means") != results.end());
    ASSERT_TRUE(results.find("sigmas") != results.end());

    std::cout << "Gestures: " + results["gestures"] + "\n";
    std::cout << "Means:    " + results["means"] + "\n";
    std::cout << "Sigmas:   " + results["sigmas"] + "\n";
    PrintResultList("fps", suffix, "", results["means"],
                    "frames-per-second", true);

    std::string mean_and_error = results["mean"] + "," + results["sigma"];
    PrintResultMeanAndError("fps", suffix, "", mean_and_error,
                            "frames-per-second", true);
  }
};

class FrameRateTest_Reference : public FrameRateTest {
 public:
  void SetUp() {
    UseReferenceBuild();
    FrameRateTest::SetUp();
  }
};

#define FRAME_RATE_TEST(content) \
TEST_F(FrameRateTest, content) { \
  RunTest(#content, ""); \
} \
TEST_F(FrameRateTest_Reference, content) { \
  RunTest(#content, "_ref"); \
}
FRAME_RATE_TEST(blank);
FRAME_RATE_TEST(googleblog);

}  // namespace
<commit_msg>Fixed frame rate test output for performance dashboard.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <map>

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"

namespace {

class FrameRateTest : public UIPerfTest {
 public:
  FrameRateTest() {
    show_window_ = true;
    dom_automation_enabled_ = true;
  }

  virtual FilePath GetDataPath(const std::string& name) {
    // Make sure the test data is checked out.
    FilePath test_path;
    PathService::Get(chrome::DIR_TEST_DATA, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("perf"));
    test_path = test_path.Append(FILE_PATH_LITERAL("frame_rate"));
    test_path = test_path.Append(FILE_PATH_LITERAL("content"));
    test_path = test_path.AppendASCII(name);
    return test_path;
  }

  void RunTest(const std::string& name, const std::string& suffix) {
    FilePath test_path = GetDataPath(name);
    ASSERT_TRUE(file_util::DirectoryExists(test_path))
        << "Missing test directory: " << test_path.value();

    test_path = test_path.Append(FILE_PATH_LITERAL("test.html"));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
              tab->NavigateToURL(net::FilePathToFileURL(test_path)));

    // Start the tests.
    ASSERT_TRUE(tab->NavigateToURLAsync(GURL("javascript:__start_all();")));

    // Block until the tests completes.
    ASSERT_TRUE(WaitUntilJavaScriptCondition(
        tab, L"", L"window.domAutomationController.send(!__running_all);",
        TestTimeouts::huge_test_timeout_ms()));

    // Read out the results.
    std::wstring json;
    ASSERT_TRUE(tab->ExecuteAndExtractString(
        L"",
        L"window.domAutomationController.send("
        L"JSON.stringify(__calc_results_total()));",
        &json));

    std::map<std::string, std::string> results;
    ASSERT_TRUE(JsonDictionaryToMap(WideToUTF8(json), &results));

    ASSERT_TRUE(results.find("mean") != results.end());
    ASSERT_TRUE(results.find("sigma") != results.end());
    ASSERT_TRUE(results.find("gestures") != results.end());
    ASSERT_TRUE(results.find("means") != results.end());
    ASSERT_TRUE(results.find("sigmas") != results.end());

    std::string trace_name = "fps" + suffix;
    printf("GESTURES %s: %s= [%s] [%s] [%s]\n", name.c_str(),
                                                trace_name.c_str(),
                                                results["gestures"].c_str(),
                                                results["means"].c_str(),
                                                results["sigmas"].c_str());

    std::string mean_and_error = results["mean"] + "," + results["sigma"];
    PrintResultMeanAndError(name, "", trace_name, mean_and_error,
                            "frames-per-second", true);
  }
};

class FrameRateTest_Reference : public FrameRateTest {
 public:
  void SetUp() {
    UseReferenceBuild();
    FrameRateTest::SetUp();
  }
};

#define FRAME_RATE_TEST(content) \
TEST_F(FrameRateTest, content) { \
  RunTest(#content, ""); \
} \
TEST_F(FrameRateTest_Reference, content) { \
  RunTest(#content, "_ref"); \
}
FRAME_RATE_TEST(blank);
FRAME_RATE_TEST(googleblog);

}  // namespace
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/util/util.hpp>
#include <nix/DataArray.hpp>

using namespace nix;

void DataArray::getData(DataType dtype,
                        void *data,
                        const NDSize &count,
                        const NDSize &offset) const {
    backend()->read(dtype, data, count, offset);
}

void DataArray::setData(DataType dtype,
                        const void *data,
                        const NDSize &count,
                        const NDSize &offset)
{
    backend()->write(dtype, data, count, offset);
}

double DataArray::applyPolynomial(std::vector<double> &coefficients, double origin, double input) const{
    double value = 0.0;
    double term = 1.0;
    for (size_t i = 0; i < coefficients.size(); i++) {
        value += coefficients[i] * term;
        term *= input - origin;
    }
    return value;
}

void DataArray::unit(const std::string &unit) {
    if (!(util::isSIUnit(unit) || util::isCompoundSIUnit(unit))) {
        throw InvalidUnit("Unit is not SI or composite of SI units.", "DataArray::unit(const string &unit)");
    }
    backend()->unit(unit);
}

std::vector<Dimension> DataArray::dimensions(const util::Filter<Dimension>::type &filter) const {
    auto f = [this] (size_t i) { return getDimension(i+1); }; // +1 since index starts at 1
    return getEntities<Dimension>(f,
                                  dimensionCount(),
                                  filter);
}

std::ostream& nix::operator<<(std::ostream &out, const DataArray &ent) {
    out << "DataArray: {name = " << ent.name();
    out << ", type = " << ent.type();
    out << ", id = " << ent.id() << "}";
    return out;
}

<commit_msg>DataArray::getData: support polynom while reading<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/util/util.hpp>
#include <nix/DataArray.hpp>
#include <nix/hdf5/DataTypeHDF5.hpp>

using namespace nix;

static void convertData(DataType source, DataType destination, void *data, size_t nelms)
{
    H5::DataType h5_src = hdf5::data_type_to_h5_memtype(source);
    H5::DataType h5_dst = hdf5::data_type_to_h5_memtype(destination);

    h5_src.convert(h5_dst, nelms, data, nullptr);
}

void DataArray::getData(DataType dtype,
        void *data,
        const NDSize &count,
        const NDSize &offset) const {

    std::vector<double> poly = polynomCoefficients();

    if (poly.size()) {
        size_t data_esize = data_type_to_size(dtype);
        size_t nelms = count.nelms();
        std::vector<double> tmp;
        double *read_buffer;

        if (data_esize < sizeof(double)) {
            //need temporary buffer
            tmp.resize(nelms);
            read_buffer = tmp.data();
        } else {
            read_buffer = reinterpret_cast<double *>(data);
        }

        backend()->read(DataType::Double, read_buffer, count, offset);
        std::transform(read_buffer, read_buffer + nelms, read_buffer, [this, &poly](double x) -> double {
            return applyPolynomial(poly, 0.0, x);
        });

        convertData(DataType::Double, dtype, read_buffer, nelms);

        if (tmp.size()) {
            memcpy(data, read_buffer, nelms * data_esize);
        }

    } else {
        backend()->read(dtype, data, count, offset);
    }
}

void DataArray::setData(DataType dtype,
                        const void *data,
                        const NDSize &count,
                        const NDSize &offset)
{
    backend()->write(dtype, data, count, offset);
}

double DataArray::applyPolynomial(std::vector<double> &coefficients, double origin, double input) const{
    double value = 0.0;
    double term = 1.0;
    for (size_t i = 0; i < coefficients.size(); i++) {
        value += coefficients[i] * term;
        term *= input - origin;
    }
    return value;
}

void DataArray::unit(const std::string &unit) {
    if (!(util::isSIUnit(unit) || util::isCompoundSIUnit(unit))) {
        throw InvalidUnit("Unit is not SI or composite of SI units.", "DataArray::unit(const string &unit)");
    }
    backend()->unit(unit);
}

std::vector<Dimension> DataArray::dimensions(const util::Filter<Dimension>::type &filter) const {
    auto f = [this] (size_t i) { return getDimension(i+1); }; // +1 since index starts at 1
    return getEntities<Dimension>(f,
                                  dimensionCount(),
                                  filter);
}

std::ostream& nix::operator<<(std::ostream &out, const DataArray &ent) {
    out << "DataArray: {name = " << ent.name();
    out << ", type = " << ent.type();
    out << ", id = " << ent.id() << "}";
    return out;
}

<|endoftext|>


<commit_before>/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  LAS Dimension implementation for C++ libLAS
 * Author:   Howard Butler, hobu.inc@gmail.com
 *
 ******************************************************************************
 * Copyright (c) 2010, Howard Butler
 *
 * 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 Martin Isenburg or Iowa Department
 *       of Natural Resources 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 <pdal/Dimension.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <map>

#include <time.h>
#include <cstdlib>

namespace pdal
{

Dimension::Dimension(std::string const& name,
                     dimension::Interpretation interpretation,
                     dimension::size_type sizeInBytes,
                     std::string description)
    : m_name(name)
    , m_flags(0)
    , m_endian(pdal::Endian_Little)
    , m_byteSize(sizeInBytes)
    , m_description(description)
    , m_min(0.0)
    , m_max(0.0)
    , m_numericScale(1.0)
    , m_numericOffset(0.0)
    , m_byteOffset(0)
    , m_position(-1)
    , m_interpretation(interpretation)
    , m_uuid(boost::uuids::nil_uuid())
    , m_namespace(std::string(""))
    , m_parentDimensionID(boost::uuids::nil_uuid())

{

    if (!m_name.size())
    {
        // Generate a random name from the time
        ::time_t seconds;
        ::time(&seconds);

        std::ostringstream oss;
        srand(static_cast<unsigned int>(seconds));
        oss << "unnamed" << rand();
        m_name = oss.str();

    }

}

/// copy constructor
Dimension::Dimension(Dimension const& other)
    : m_name(other.m_name)
    , m_flags(other.m_flags)
    , m_endian(other.m_endian)
    , m_byteSize(other.m_byteSize)
    , m_description(other.m_description)
    , m_min(other.m_min)
    , m_max(other.m_max)
    , m_numericScale(other.m_numericScale)
    , m_numericOffset(other.m_numericOffset)
    , m_byteOffset(other.m_byteOffset)
    , m_position(other.m_position)
    , m_interpretation(other.m_interpretation)
    , m_uuid(other.m_uuid)
    , m_namespace(other.m_namespace)
    , m_parentDimensionID(other.m_parentDimensionID)
{
    return;
}

/// assignment operator
Dimension& Dimension::operator=(Dimension const& rhs)
{
    if (&rhs != this)
    {
        m_name = rhs.m_name;
        m_flags = rhs.m_flags;
        m_endian = rhs.m_endian;
        m_byteSize = rhs.m_byteSize;
        m_description = rhs.m_description;
        m_min = rhs.m_min;
        m_max = rhs.m_max;
        m_numericScale = rhs.m_numericScale;
        m_numericOffset = rhs.m_numericOffset;
        m_byteOffset = rhs.m_byteOffset;
        m_position = rhs.m_position;
        m_interpretation = rhs.m_interpretation;
        m_uuid = rhs.m_uuid;
        m_namespace = rhs.m_namespace;
        m_parentDimensionID = rhs.m_parentDimensionID;
    }

    return *this;
}

bool Dimension::operator==(const Dimension& other) const
{
    if (boost::iequals(m_name, other.m_name) &&
            m_flags == other.m_flags &&
            m_endian == other.m_endian &&
            m_byteSize == other.m_byteSize &&
            boost::iequals(m_description, other.m_description) &&
            Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) &&
            Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) &&
            Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) &&
            Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) &&
            m_byteOffset == other.m_byteOffset &&
            m_position == other.m_position &&
            m_interpretation == other.m_interpretation &&
            m_uuid == other.m_uuid &&
            m_parentDimensionID == other.m_parentDimensionID
       )
    {
        return true;
    }

    return false;
}

bool Dimension::operator!=(const Dimension& other) const
{
    return !(*this==other);
}

boost::property_tree::ptree Dimension::toPTree() const
{
    using boost::property_tree::ptree;
    ptree dim;
    dim.put("name", getName());
    dim.put("namespace", getNamespace());
    dim.put("parent", getParent());
    dim.put("description", getDescription());
    dim.put("bytesize", getByteSize());

    std::string e("little");
    if (getEndianness() == Endian_Big)
        e = std::string("big");
    dim.put("endianness", e);

    dim.put("minimum", getMinimum());
    dim.put("maximum", getMaximum());
    dim.put("scale", getNumericScale());
    dim.put("offset", getNumericOffset());

    dim.put("scale", getNumericScale());

    dim.put("isValid", isValid());
    dim.put("isIgnored", isIgnored());

    std::stringstream oss;

    dimension::id t =  getUUID();
    oss << t;

    dim.put("uuid", oss.str());
    return dim;
}

void Dimension::setUUID(std::string const& id)
{
    boost::uuids::string_generator gen;
    m_uuid = gen(id);
}

void Dimension::createUUID()
{
    boost::uuids::basic_random_generator<boost::mt19937> gen(pdal::Environment::get()->getRNG());
    m_uuid = gen();
}
void Dimension::dump() const
{
    std::cout << *this;
}

std::string Dimension::getInterpretationName() const
{
    std::ostringstream type;
    dimension::Interpretation t = getInterpretation();
    boost::uint32_t bytesize = getByteSize();

    switch (t)
    {
        case dimension::SignedByte:
            if (bytesize == 1)
                type << "int8_t";
            break;
        case dimension::UnsignedByte:
            if (bytesize == 1)
                type << "uint8_t";
            break;

        case dimension::SignedInteger:
            if (bytesize == 1)
                type << "int8_t";
            else if (bytesize == 2)
                type << "int16_t";
            else if (bytesize == 4)
                type << "int32_t";
            else if (bytesize == 8)
                type << "int64_t";
            else
                type << "unknown";
            break;
        case dimension::UnsignedInteger:
            if (bytesize == 1)
                type << "uint8_t";
            else if (bytesize == 2)
                type << "uint16_t";
            else if (bytesize == 4)
                type << "uint32_t";
            else if (bytesize == 8)
                type << "uint64_t";
            else
                type << "unknown";
            break;

        case dimension::Float:
            if (bytesize == 4)
                type << "float";
            else if (bytesize == 8)
                type << "double";
            else
                type << "unknown";
            break;

        case dimension::Pointer:
            type << "pointer";
            break;
        case dimension::Undefined:
            type << "unknown";
            break;
    }

    return type.str();
}

std::ostream& operator<<(std::ostream& os, pdal::Dimension const& d)
{
    using boost::property_tree::ptree;
    ptree tree = d.toPTree();

    std::string const name = tree.get<std::string>("name");
    std::string const ns = tree.get<std::string>("namespace");

    std::ostringstream quoted_name;
    if (ns.size())
        quoted_name << "'" << ns << "." << name << "'";
    else
        quoted_name << "'" << name << "'";
    std::ostringstream pad;
    std::string const& cur = quoted_name.str();
    std::string::size_type size = cur.size();
    std::string::size_type buffer(24);
    std::string::size_type pad_size = buffer - size;
    if (size > buffer)
        pad_size = 4;
    for (std::string::size_type i=0; i != pad_size; i++)
    {
        pad << " ";
    }
    os << quoted_name.str() << pad.str() <<" -- "<< " size: " << tree.get<boost::uint32_t>("bytesize");

    double scale = tree.get<double>("scale");
    boost::uint32_t precision = Utils::getStreamPrecision(scale);
    os.setf(std::ios_base::fixed, std::ios_base::floatfield);
    os.precision(precision);
    os << " scale: " << scale;

    double offset = tree.get<double>("offset");
    os << " offset: " << offset;

    os << " ignored: " << tree.get<bool>("isIgnored");
    os << std::endl;

    return os;
}

} // namespace pdal
<commit_msg>put position and byteoffset in the ptree output<commit_after>/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  LAS Dimension implementation for C++ libLAS
 * Author:   Howard Butler, hobu.inc@gmail.com
 *
 ******************************************************************************
 * Copyright (c) 2010, Howard Butler
 *
 * 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 Martin Isenburg or Iowa Department
 *       of Natural Resources 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 <pdal/Dimension.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <map>

#include <time.h>
#include <cstdlib>

namespace pdal
{

Dimension::Dimension(std::string const& name,
                     dimension::Interpretation interpretation,
                     dimension::size_type sizeInBytes,
                     std::string description)
    : m_name(name)
    , m_flags(0)
    , m_endian(pdal::Endian_Little)
    , m_byteSize(sizeInBytes)
    , m_description(description)
    , m_min(0.0)
    , m_max(0.0)
    , m_numericScale(1.0)
    , m_numericOffset(0.0)
    , m_byteOffset(0)
    , m_position(-1)
    , m_interpretation(interpretation)
    , m_uuid(boost::uuids::nil_uuid())
    , m_namespace(std::string(""))
    , m_parentDimensionID(boost::uuids::nil_uuid())

{

    if (!m_name.size())
    {
        // Generate a random name from the time
        ::time_t seconds;
        ::time(&seconds);

        std::ostringstream oss;
        srand(static_cast<unsigned int>(seconds));
        oss << "unnamed" << rand();
        m_name = oss.str();

    }

}

/// copy constructor
Dimension::Dimension(Dimension const& other)
    : m_name(other.m_name)
    , m_flags(other.m_flags)
    , m_endian(other.m_endian)
    , m_byteSize(other.m_byteSize)
    , m_description(other.m_description)
    , m_min(other.m_min)
    , m_max(other.m_max)
    , m_numericScale(other.m_numericScale)
    , m_numericOffset(other.m_numericOffset)
    , m_byteOffset(other.m_byteOffset)
    , m_position(other.m_position)
    , m_interpretation(other.m_interpretation)
    , m_uuid(other.m_uuid)
    , m_namespace(other.m_namespace)
    , m_parentDimensionID(other.m_parentDimensionID)
{
    return;
}

/// assignment operator
Dimension& Dimension::operator=(Dimension const& rhs)
{
    if (&rhs != this)
    {
        m_name = rhs.m_name;
        m_flags = rhs.m_flags;
        m_endian = rhs.m_endian;
        m_byteSize = rhs.m_byteSize;
        m_description = rhs.m_description;
        m_min = rhs.m_min;
        m_max = rhs.m_max;
        m_numericScale = rhs.m_numericScale;
        m_numericOffset = rhs.m_numericOffset;
        m_byteOffset = rhs.m_byteOffset;
        m_position = rhs.m_position;
        m_interpretation = rhs.m_interpretation;
        m_uuid = rhs.m_uuid;
        m_namespace = rhs.m_namespace;
        m_parentDimensionID = rhs.m_parentDimensionID;
    }

    return *this;
}

bool Dimension::operator==(const Dimension& other) const
{
    if (boost::iequals(m_name, other.m_name) &&
            m_flags == other.m_flags &&
            m_endian == other.m_endian &&
            m_byteSize == other.m_byteSize &&
            boost::iequals(m_description, other.m_description) &&
            Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) &&
            Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) &&
            Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) &&
            Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) &&
            m_byteOffset == other.m_byteOffset &&
            m_position == other.m_position &&
            m_interpretation == other.m_interpretation &&
            m_uuid == other.m_uuid &&
            m_parentDimensionID == other.m_parentDimensionID
       )
    {
        return true;
    }

    return false;
}

bool Dimension::operator!=(const Dimension& other) const
{
    return !(*this==other);
}

boost::property_tree::ptree Dimension::toPTree() const
{
    using boost::property_tree::ptree;
    ptree dim;
    dim.put("name", getName());
    dim.put("namespace", getNamespace());
    dim.put("parent", getParent());
    dim.put("description", getDescription());
    dim.put("bytesize", getByteSize());

    std::string e("little");
    if (getEndianness() == Endian_Big)
        e = std::string("big");
    dim.put("endianness", e);

    dim.put("minimum", getMinimum());
    dim.put("maximum", getMaximum());
    dim.put("scale", getNumericScale());
    dim.put("offset", getNumericOffset());

    dim.put("scale", getNumericScale());

    dim.put("position", getPosition());
    dim.put("byteoffset", getByteOffset());
    dim.put("isIgnored", isIgnored());

    std::stringstream oss;

    dimension::id t =  getUUID();
    oss << t;

    dim.put("uuid", oss.str());
    return dim;
}

void Dimension::setUUID(std::string const& id)
{
    boost::uuids::string_generator gen;
    m_uuid = gen(id);
}

void Dimension::createUUID()
{
    boost::uuids::basic_random_generator<boost::mt19937> gen(pdal::Environment::get()->getRNG());
    m_uuid = gen();
}
void Dimension::dump() const
{
    std::cout << *this;
}

std::string Dimension::getInterpretationName() const
{
    std::ostringstream type;
    dimension::Interpretation t = getInterpretation();
    boost::uint32_t bytesize = getByteSize();

    switch (t)
    {
        case dimension::SignedByte:
            if (bytesize == 1)
                type << "int8_t";
            break;
        case dimension::UnsignedByte:
            if (bytesize == 1)
                type << "uint8_t";
            break;

        case dimension::SignedInteger:
            if (bytesize == 1)
                type << "int8_t";
            else if (bytesize == 2)
                type << "int16_t";
            else if (bytesize == 4)
                type << "int32_t";
            else if (bytesize == 8)
                type << "int64_t";
            else
                type << "unknown";
            break;
        case dimension::UnsignedInteger:
            if (bytesize == 1)
                type << "uint8_t";
            else if (bytesize == 2)
                type << "uint16_t";
            else if (bytesize == 4)
                type << "uint32_t";
            else if (bytesize == 8)
                type << "uint64_t";
            else
                type << "unknown";
            break;

        case dimension::Float:
            if (bytesize == 4)
                type << "float";
            else if (bytesize == 8)
                type << "double";
            else
                type << "unknown";
            break;

        case dimension::Pointer:
            type << "pointer";
            break;
        case dimension::Undefined:
            type << "unknown";
            break;
    }

    return type.str();
}

std::ostream& operator<<(std::ostream& os, pdal::Dimension const& d)
{
    using boost::property_tree::ptree;
    ptree tree = d.toPTree();

    std::string const name = tree.get<std::string>("name");
    std::string const ns = tree.get<std::string>("namespace");

    std::ostringstream quoted_name;
    if (ns.size())
        quoted_name << "'" << ns << "." << name << "'";
    else
        quoted_name << "'" << name << "'";
    std::ostringstream pad;
    std::string const& cur = quoted_name.str();
    std::string::size_type size = cur.size();
    std::string::size_type buffer(24);
    std::string::size_type pad_size = buffer - size;
    if (size > buffer)
        pad_size = 4;
    for (std::string::size_type i=0; i != pad_size; i++)
    {
        pad << " ";
    }
    os << quoted_name.str() << pad.str() <<" -- "<< " size: " << tree.get<boost::uint32_t>("bytesize");

    double scale = tree.get<double>("scale");
    boost::uint32_t precision = Utils::getStreamPrecision(scale);
    os.setf(std::ios_base::fixed, std::ios_base::floatfield);
    os.precision(precision);
    os << " scale: " << scale;

    double offset = tree.get<double>("offset");
    os << " offset: " << offset;

    os << " ignored: " << tree.get<bool>("isIgnored");
    os << std::endl;

    return os;
}

} // namespace pdal
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// START SNIPPET: demo

#include <activemq/concurrent/Thread.h>
#include <activemq/concurrent/Runnable.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Integer.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <iostream>

using namespace activemq::core;
using namespace activemq::util;
using namespace activemq::concurrent;
using namespace cms;
using namespace std;

class HelloWorldProducer : public Runnable {
private:

	Connection* connection;
	Session* session;
	Destination* destination;
	MessageProducer* producer;
	int numMessages;
    bool useTopic;

public:

	HelloWorldProducer( int numMessages, bool useTopic = false ){
		connection = NULL;
    	session = NULL;
    	destination = NULL;
    	producer = NULL;
    	this->numMessages = numMessages;
        this->useTopic = useTopic;
	}

	virtual ~HelloWorldProducer(){
		cleanup();
	}

    virtual void run() {
        try {
            // Create a ConnectionFactory
            ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61613");

            // Create a Connection
            connection = connectionFactory->createConnection();
            connection->start();

            // Create a Session
            session = connection->createSession( Session::AUTO_ACKNOWLEDGE );

            // Create the destination (Topic or Queue)
            if( useTopic ) {
                destination = session->createTopic( "TEST.FOO" );
            } else {
                destination = session->createQueue( "TEST.FOO" );
            }

            // Create a MessageProducer from the Session to the Topic or Queue
            producer = session->createProducer( destination );
            producer->setDeliveryMode( DeliveryMode::NON_PERSISTANT );

            // Create the Thread Id String
            string threadIdStr = Integer::toString( Thread::getId() );

            // Create a messages
            string text = (string)"Hello world! from thread " + threadIdStr;

            for( int ix=0; ix<numMessages; ++ix ){
	            TextMessage* message = session->createTextMessage( text );

    	        // Tell the producer to send the message
        	    printf( "Sent message from thread %s\n", threadIdStr.c_str() );
            	producer->send( message );

            	delete message;
            }

        }catch ( CMSException& e ) {
            e.printStackTrace();
        }
    }

private:

    void cleanup(){

			// Destroy resources.
			try{
            	if( destination != NULL ) delete destination;
			}catch ( CMSException& e ) {}
			destination = NULL;

			try{
	            if( producer != NULL ) delete producer;
			}catch ( CMSException& e ) {}
			producer = NULL;

    		// Close open resources.
    		try{
    			if( session != NULL ) session->close();
    			if( connection != NULL ) connection->close();
			}catch ( CMSException& e ) {}

			try{
            	if( session != NULL ) delete session;
			}catch ( CMSException& e ) {}
			session = NULL;

            try{
            	if( connection != NULL ) delete connection;
			}catch ( CMSException& e ) {}
    		connection = NULL;
    }
};

class HelloWorldConsumer : public ExceptionListener,
                           public MessageListener,
                           public Runnable {

private:

	Connection* connection;
	Session* session;
	Destination* destination;
	MessageConsumer* consumer;
	long waitMillis;
    bool useTopic;

public:

	HelloWorldConsumer( long waitMillis, bool useTopic = false ){
		connection = NULL;
    	session = NULL;
    	destination = NULL;
    	consumer = NULL;
    	this->waitMillis = waitMillis;
        this->useTopic = useTopic;
	}
    virtual ~HelloWorldConsumer(){
    	cleanup();
    }

    virtual void run() {

        try {

            // Create a ConnectionFactory
            ActiveMQConnectionFactory* connectionFactory =
                new ActiveMQConnectionFactory( "tcp://127.0.0.1:61613" );

            // Create a Connection
            connection = connectionFactory->createConnection();
            delete connectionFactory;
            connection->start();

            connection->setExceptionListener(this);

            // Create a Session
            session = connection->createSession( Session::AUTO_ACKNOWLEDGE );

            // Create the destination (Topic or Queue)
            if( useTopic ) {
                destination = session->createTopic( "TEST.FOO" );
            } else {
                destination = session->createQueue( "TEST.FOO" );
            }

            // Create a MessageConsumer from the Session to the Topic or Queue
            consumer = session->createConsumer( destination );

            consumer->setMessageListener( this );

            // Sleep while asynchronous messages come in.
            Thread::sleep( waitMillis );

        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }

    // Called from the consumer since this class is a registered MessageListener.
    virtual void onMessage( const Message* message ){

        static int count = 0;

        try
        {
            count++;
    	    const TextMessage* textMessage =
                dynamic_cast< const TextMessage* >( message );
            string text = textMessage->getText();
            printf( "Message #%d Received: %s\n", count, text.c_str() );
        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }

    // If something bad happens you see it here as this class is also been
    // registered as an ExceptionListener with the connection.
    virtual void onException( const CMSException& ex ) {
        printf("JMS Exception occured.  Shutting down client.\n");
    }

private:

    void cleanup(){

        //*************************************************
        // Always close destination, consumers and producers before
        // you destroy their sessions and connection.
        //*************************************************

		// Destroy resources.
		try{
        	if( destination != NULL ) delete destination;
		}catch (CMSException& e) {}
		destination = NULL;

		try{
            if( consumer != NULL ) delete consumer;
		}catch (CMSException& e) {}
		consumer = NULL;

		// Close open resources.
		try{
			if( session != NULL ) session->close();
			if( connection != NULL ) connection->close();
		}catch (CMSException& e) {}

        // Now Destroy them
        try{
        	if( session != NULL ) delete session;
		}catch (CMSException& e) {}
		session = NULL;

		try{
        	if( connection != NULL ) delete connection;
		}catch (CMSException& e) {}
		connection = NULL;
    }
};

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

    std::cout << "=====================================================\n";
    std::cout << "Starting the example:" << std::endl;
    std::cout << "-----------------------------------------------------\n";

    //============================================================
    // set to true to use topics instead of queues
    // Note in the code above that this causes createTopic or
    // createQueue to be used in both consumer an producer.
    //============================================================
    bool useTopics = false;

    HelloWorldProducer producer( 1000, useTopics );
	HelloWorldConsumer consumer( 8000, useTopics );

	// Start the consumer thread.
	Thread consumerThread( &consumer );
	consumerThread.start();

	// Start the producer thread.
	Thread producerThread( &producer );
	producerThread.start();

	// Wait for the threads to complete.
	producerThread.join();
	consumerThread.join();

    std::cout << "-----------------------------------------------------\n";
    std::cout << "Finished with the example, ignore errors from this"
              << std::endl
              << "point on as the sockets breaks when we shutdown."
              << std::endl;
    std::cout << "=====================================================\n";
}

// END SNIPPET: demo
<commit_msg>cleaning up the spaces/tabs in the example ActiveMQ CPP main.cpp<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// START SNIPPET: demo

#include <activemq/concurrent/Thread.h>
#include <activemq/concurrent/Runnable.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Integer.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <iostream>

using namespace activemq::core;
using namespace activemq::util;
using namespace activemq::concurrent;
using namespace cms;
using namespace std;

class HelloWorldProducer : public Runnable {
private:

    Connection* connection;
    Session* session;
    Destination* destination;
    MessageProducer* producer;
    int numMessages;
    bool useTopic;

public:

    HelloWorldProducer( int numMessages, bool useTopic = false ){
        connection = NULL;
        session = NULL;
        destination = NULL;
        producer = NULL;
        this->numMessages = numMessages;
        this->useTopic = useTopic;
    }

    virtual ~HelloWorldProducer(){
        cleanup();
    }

    virtual void run() {
        try {
            // Create a ConnectionFactory
            ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61613");

            // Create a Connection
            connection = connectionFactory->createConnection();
            connection->start();

            // Create a Session
            session = connection->createSession( Session::AUTO_ACKNOWLEDGE );

            // Create the destination (Topic or Queue)
            if( useTopic ) {
                destination = session->createTopic( "TEST.FOO" );
            } else {
                destination = session->createQueue( "TEST.FOO" );
            }

            // Create a MessageProducer from the Session to the Topic or Queue
            producer = session->createProducer( destination );
            producer->setDeliveryMode( DeliveryMode::NON_PERSISTANT );

            // Create the Thread Id String
            string threadIdStr = Integer::toString( Thread::getId() );

            // Create a messages
            string text = (string)"Hello world! from thread " + threadIdStr;

            for( int ix=0; ix<numMessages; ++ix ){
                TextMessage* message = session->createTextMessage( text );

                // Tell the producer to send the message
                printf( "Sent message from thread %s\n", threadIdStr.c_str() );
                producer->send( message );

                delete message;
            }

        }catch ( CMSException& e ) {
            e.printStackTrace();
        }
    }

private:

    void cleanup(){

            // Destroy resources.
            try{
                if( destination != NULL ) delete destination;
            }catch ( CMSException& e ) {}
            destination = NULL;

            try{
                if( producer != NULL ) delete producer;
            }catch ( CMSException& e ) {}
            producer = NULL;

            // Close open resources.
            try{
                if( session != NULL ) session->close();
                if( connection != NULL ) connection->close();
            }catch ( CMSException& e ) {}

            try{
                if( session != NULL ) delete session;
            }catch ( CMSException& e ) {}
            session = NULL;

            try{
                if( connection != NULL ) delete connection;
            }catch ( CMSException& e ) {}
            connection = NULL;
    }
};

class HelloWorldConsumer : public ExceptionListener,
                           public MessageListener,
                           public Runnable {

private:

    Connection* connection;
    Session* session;
    Destination* destination;
    MessageConsumer* consumer;
    long waitMillis;
    bool useTopic;

public:

    HelloWorldConsumer( long waitMillis, bool useTopic = false ){
        connection = NULL;
        session = NULL;
        destination = NULL;
        consumer = NULL;
        this->waitMillis = waitMillis;
        this->useTopic = useTopic;
    }
    virtual ~HelloWorldConsumer(){
        cleanup();
    }

    virtual void run() {

        try {

            // Create a ConnectionFactory
            ActiveMQConnectionFactory* connectionFactory =
                new ActiveMQConnectionFactory( "tcp://127.0.0.1:61613" );

            // Create a Connection
            connection = connectionFactory->createConnection();
            delete connectionFactory;
            connection->start();

            connection->setExceptionListener(this);

            // Create a Session
            session = connection->createSession( Session::AUTO_ACKNOWLEDGE );

            // Create the destination (Topic or Queue)
            if( useTopic ) {
                destination = session->createTopic( "TEST.FOO" );
            } else {
                destination = session->createQueue( "TEST.FOO" );
            }

            // Create a MessageConsumer from the Session to the Topic or Queue
            consumer = session->createConsumer( destination );

            consumer->setMessageListener( this );

            // Sleep while asynchronous messages come in.
            Thread::sleep( waitMillis );

        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }

    // Called from the consumer since this class is a registered MessageListener.
    virtual void onMessage( const Message* message ){

        static int count = 0;

        try
        {
            count++;
            const TextMessage* textMessage =
                dynamic_cast< const TextMessage* >( message );
            string text = textMessage->getText();
            printf( "Message #%d Received: %s\n", count, text.c_str() );
        } catch (CMSException& e) {
            e.printStackTrace();
        }
    }

    // If something bad happens you see it here as this class is also been
    // registered as an ExceptionListener with the connection.
    virtual void onException( const CMSException& ex ) {
        printf("JMS Exception occured.  Shutting down client.\n");
    }

private:

    void cleanup(){

        //*************************************************
        // Always close destination, consumers and producers before
        // you destroy their sessions and connection.
        //*************************************************

        // Destroy resources.
        try{
            if( destination != NULL ) delete destination;
        }catch (CMSException& e) {}
        destination = NULL;

        try{
            if( consumer != NULL ) delete consumer;
        }catch (CMSException& e) {}
        consumer = NULL;

        // Close open resources.
        try{
            if( session != NULL ) session->close();
            if( connection != NULL ) connection->close();
        }catch (CMSException& e) {}

        // Now Destroy them
        try{
            if( session != NULL ) delete session;
        }catch (CMSException& e) {}
        session = NULL;

        try{
            if( connection != NULL ) delete connection;
        }catch (CMSException& e) {}
        connection = NULL;
    }
};

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

    std::cout << "=====================================================\n";
    std::cout << "Starting the example:" << std::endl;
    std::cout << "-----------------------------------------------------\n";

    //============================================================
    // set to true to use topics instead of queues
    // Note in the code above that this causes createTopic or
    // createQueue to be used in both consumer an producer.
    //============================================================
    bool useTopics = false;

    HelloWorldProducer producer( 1000, useTopics );
    HelloWorldConsumer consumer( 8000, useTopics );

    // Start the consumer thread.
    Thread consumerThread( &consumer );
    consumerThread.start();

    // Start the producer thread.
    Thread producerThread( &producer );
    producerThread.start();

    // Wait for the threads to complete.
    producerThread.join();
    consumerThread.join();

    std::cout << "-----------------------------------------------------\n";
    std::cout << "Finished with the example, ignore errors from this"
              << std::endl
              << "point on as the sockets breaks when we shutdown."
              << std::endl;
    std::cout << "=====================================================\n";
}

// END SNIPPET: demo
<|endoftext|>


<commit_before>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** Centreon Clib 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
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef CC_UNIQUE_ARRAY_PTR_HH
#  define CC_UNIQUE_ARRAY_PTR_HH

#  include <cstddef>
#  include "com/centreon/namespace.hh"

CC_BEGIN()

/**
 *  @class unique_array_ptr unique_array_ptr.hh
 *  @brief Similar to unique_ptr for arrays.
 *
 *  Provide similar feature as unique_ptr but for array pointers.
 */
template     <typename T>
class        unique_array_ptr {
 private:
  T*         _ptr;

 public:
  /**
   *  Constructor.
   *
   *  @param[in] t Array pointer.
   */
             unique_array_ptr(T* t) : _ptr(t) {}

  /**
   *  Copy constructor.
   *
   *  @param[in] uap Object to copy.
   */
             unique_array_ptr(unique_array_ptr& uap) : _ptr(uap._ptr) {
    uap._ptr = NULL;
  }

  /**
   *  Destructor.
   */
             ~unique_array_ptr() {
    delete [] _ptr;
  }

  /**
   *  Assignment operator.
   *
   *  @param[in] uap Object to copy.
   *
   *  @return This object.
   */
  unique_array_ptr& operator=(unique_array_ptr& uap) {
    if (&uap != this) {
      _ptr = uap._ptr;
      uap._ptr = NULL;
    }
    return (*this);
  }

  /**
   *  Dereferencing pointer.
   *
   *  @return Dereferenced pointer.
   */
  T&         operator*() {
    return (*_ptr);
  }

  /**
   *  Array access operator.
   *
   *  @param[in] idx Index in array.
   *
   *  @return Element at position idx.
   */
  T&         operator[](unsigned int idx) {
    return (_ptr[idx]);
  }

  /**
   *  Get the pointer associated with this object.
   *
   *  @return Pointer associated with this object.
   */
  T*         get() const {
    return (_ptr);
  }

  /**
   *  Release the associated pointer and release it.
   *
   *  @return Pointer associated with this object.
   */
  T*         release() {
    T* tmp(_ptr);
    _ptr = NULL;
    return (tmp);
  }
};

CC_END()

#endif // !CC_UNIQUE_ARRAY_PTR_HH
<commit_msg>Added default argument to unique_array_ptr's constructor.<commit_after>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** Centreon Clib 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
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef CC_UNIQUE_ARRAY_PTR_HH
#  define CC_UNIQUE_ARRAY_PTR_HH

#  include <cstddef>
#  include "com/centreon/namespace.hh"

CC_BEGIN()

/**
 *  @class unique_array_ptr unique_array_ptr.hh
 *  @brief Similar to unique_ptr for arrays.
 *
 *  Provide similar feature as unique_ptr but for array pointers.
 */
template     <typename T>
class        unique_array_ptr {
 private:
  T*         _ptr;

 public:
  /**
   *  Constructor.
   *
   *  @param[in] t Array pointer.
   */
             unique_array_ptr(T* t = NULL) : _ptr(t) {}

  /**
   *  Copy constructor.
   *
   *  @param[in] uap Object to copy.
   */
             unique_array_ptr(unique_array_ptr& uap) : _ptr(uap._ptr) {
    uap._ptr = NULL;
  }

  /**
   *  Destructor.
   */
             ~unique_array_ptr() {
    delete [] _ptr;
  }

  /**
   *  Assignment operator.
   *
   *  @param[in] uap Object to copy.
   *
   *  @return This object.
   */
  unique_array_ptr& operator=(unique_array_ptr& uap) {
    if (&uap != this) {
      _ptr = uap._ptr;
      uap._ptr = NULL;
    }
    return (*this);
  }

  /**
   *  Dereferencing pointer.
   *
   *  @return Dereferenced pointer.
   */
  T&         operator*() {
    return (*_ptr);
  }

  /**
   *  Array access operator.
   *
   *  @param[in] idx Index in array.
   *
   *  @return Element at position idx.
   */
  T&         operator[](unsigned int idx) {
    return (_ptr[idx]);
  }

  /**
   *  Get the pointer associated with this object.
   *
   *  @return Pointer associated with this object.
   */
  T*         get() const {
    return (_ptr);
  }

  /**
   *  Release the associated pointer and release it.
   *
   *  @return Pointer associated with this object.
   */
  T*         release() {
    T* tmp(_ptr);
    _ptr = NULL;
    return (tmp);
  }
};

CC_END()

#endif // !CC_UNIQUE_ARRAY_PTR_HH
<|endoftext|>


<commit_before>#include "RSolid.h"

#include <iostream>

#include "../Maths/Matrix_Maths.h"

#include "../Camera.h"

#include "../World/Chunk/CSection.h"

namespace Renderer
{
    void RChunk::draw(const Chunk::Section& section)
    {
        m_chunks.push_back(&section);
    }

    void RChunk::update(const Camera& camera)
    {
        //glEnable    (GL_CULL_FACE);

        m_shader.bind();

        m_shader.setProjMatrix(camera.getProjectionMatrix());
        m_shader.setViewMatrix(camera.getViewMatrix());

        for (const auto* section : m_chunks)
        {
            prepare(*section);

            glDrawElements(GL_TRIANGLES,
                           section->getMeshes().solidMesh.getModel().getIndicesCount(),
                           GL_UNSIGNED_INT,
                           nullptr);

        }
        m_chunks.clear();
    }

    void RChunk::prepare(const Chunk::Section& section)
    {
        section.getMeshes().solidMesh.getModel().bind();
    }
}
<commit_msg>readd face cull<commit_after>#include "RSolid.h"

#include <iostream>

#include "../Maths/Matrix_Maths.h"

#include "../Camera.h"

#include "../World/Chunk/CSection.h"

namespace Renderer
{
    void RChunk::draw(const Chunk::Section& section)
    {
        m_chunks.push_back(&section);
    }

    void RChunk::update(const Camera& camera)
    {
        glEnable    (GL_CULL_FACE);

        m_shader.bind();

        m_shader.setProjMatrix(camera.getProjectionMatrix());
        m_shader.setViewMatrix(camera.getViewMatrix());

        for (const auto* section : m_chunks)
        {
            prepare(*section);

            glDrawElements(GL_TRIANGLES,
                           section->getMeshes().solidMesh.getModel().getIndicesCount(),
                           GL_UNSIGNED_INT,
                           nullptr);

        }
        m_chunks.clear();
    }

    void RChunk::prepare(const Chunk::Section& section)
    {
        section.getMeshes().solidMesh.getModel().bind();
    }
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2794
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1720329 by chui@ocl-promo-incrementor on 2018/12/14 03:00:54<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2795
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of asciival, software which can return an ASCII
// representation of the data read from a DAP server.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// asciival is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2, or (at your option) any later
// version.
//
// asciival is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with GCC; see the file COPYING. If not, write to the Free Software
// Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1998,2000
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

// Implementation for the class AsciiStructure. See AsciiByte.cc
//
// 3/12/98 jhrg

#include "config.h"

#include <iostream>
#include <string>

#include "InternalErr.h"
#include "AsciiSequence.h"
#include "AsciiStructure.h"
//#include "name_map.h"
#include "get_ascii.h"
#include "debug.h"

using std::endl ;
using namespace dap_asciival;

BaseType *
AsciiSequence::ptr_duplicate()
{
    return new AsciiSequence(*this);
}

AsciiSequence::AsciiSequence(const string &n) : Sequence(n)
{
}

AsciiSequence::AsciiSequence(Sequence * bt):AsciiOutput(bt)
{
    // Let's make the alternative structure of Ascii types now so that we
    // don't have to do it on the fly.
    Vars_iter p = bt->var_begin();
    while (p != bt->var_end()) {
        if ((*p)->send_p()) {
            BaseType *new_bt = basetype_to_asciitype(*p);
            add_var(new_bt);
            delete new_bt;
        }
        p++;
    }
    set_name(bt->name());
}

AsciiSequence::~AsciiSequence()
{
}

int
AsciiSequence::length()
{
    return -1;
}

int
AsciiSequence::element_count(bool leaves)
{
    if (!leaves)
        return _vars.size();
    else {
        int i = 0;
        for (Vars_iter iter = _vars.begin(); iter != _vars.end(); iter++) {
            if ((*iter)->send_p())
                i += (*iter)->element_count(true);
        }
        return i;
    }
}

// case 1: Simple, Seq - handled
// Case 2: Seq, Simple
void
 AsciiSequence::print_ascii_row(FILE * os, int row, BaseTypeRow outer_vars)
{
    Sequence *seq = dynamic_cast < Sequence * >(_redirect);
    if (!seq)
        seq = this;

    // Print the values from this sequence.
    // AsciiSequence::element_count() returns only vars with send_p() set.
    int elements = element_count() - 1;
    int j = 0;
    bool done = false;
    do {
        BaseType *bt_ptr = seq->var_value(row, j);
        if (bt_ptr) {           // Check for data.
            BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);
            if (bt_ptr->type() == dods_sequence_c) {
                dynamic_cast <
                    AsciiSequence * >(abt_ptr)->print_ascii_rows(os,
                                                                 outer_vars);
            } else {
                // push the real base type pointer instead of the ascii one.
                // We can cast it again later from the outer_vars vector.
                outer_vars.push_back(bt_ptr);
                dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,
                                                                     false);
            }
            ++j;
            // we only need the ascii type here, so delete it
            delete abt_ptr;
        }

        // ++j;
        // When we're finally done, set the flag and omit the comma.
        if (j > elements)
            done = true;
        else if (bt_ptr)
            fprintf(os, ", ");

    } while (!done);
}

void
 AsciiSequence::print_leading_vars(FILE * os, BaseTypeRow & outer_vars)
{
    BaseTypeRow::iterator BTR_iter = outer_vars.begin();
    for (BTR_iter = outer_vars.begin(); BTR_iter != outer_vars.end();
         BTR_iter++) {
        BaseType *abt_ptr = basetype_to_asciitype(*BTR_iter);
        dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os, false);
        fprintf(os, ", ");
        // we only need the ascii base type locally, so delete it
        delete abt_ptr;
    }
}

void
 AsciiSequence::print_ascii_rows(FILE * os, BaseTypeRow outer_vars)
{
    Sequence *seq = dynamic_cast < Sequence * >(_redirect);
    if (!seq)
        seq = this;

    int rows = seq->number_of_rows() - 1;
    int i = 0;
    bool done = false;
    do {
        if (i > 0 && !outer_vars.empty())
            print_leading_vars(os, outer_vars);

        print_ascii_row(os, i++, outer_vars);

        if (i > rows)
            done = true;
        else
            fprintf(os, "\n");
    } while (!done);
}

// Assume that this mfunc is called only for simple sequences. Do not print
// table style headers for complex sequences.

void
 AsciiSequence::print_header(FILE * os)
{
    Vars_iter p = var_begin();
    while (p != var_end()) {
        if ((*p)->is_simple_type())
            fprintf(os, "%s",
                    dynamic_cast <
                    AsciiOutput * >(*p)->get_full_name().c_str());
        else if ((*p)->type() == dods_sequence_c)
            dynamic_cast < AsciiSequence * >((*p))->print_header(os);
        else if ((*p)->type() == dods_structure_c)
            dynamic_cast < AsciiStructure * >((*p))->print_header(os);
        else
            throw InternalErr(__FILE__, __LINE__,
                              "This method should only be called by instances for which `is_simple_sequence' returns true.");
        if (++p != var_end())
            fprintf(os, ", ");
    }
}

void
 AsciiSequence::print_ascii(FILE * os, bool print_name) throw(InternalErr)
{
    Sequence *seq = dynamic_cast < Sequence * >(_redirect);
    if (!seq)
        seq = this;

    if (seq->is_linear()) {
        if (print_name) {
            print_header(os);
            fprintf(os, "\n");
        }

        BaseTypeRow outer_vars(0);
        print_ascii_rows(os, outer_vars);
    } else {
        int rows = seq->number_of_rows() - 1;
        int elements = seq->element_count() - 1;

        // For each row of the Sequence...
        bool rows_done = false;
        int i = 0;
        do {
            // For each variable of the row...
            bool vars_done = false;
            int j = 0;
            do {
                BaseType *bt_ptr = seq->var_value(i, j++);
                BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);
                dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,
                                                                     true);
                // abt_ptr is not stored for future use, so delete it
                delete abt_ptr;

                if (j > elements)
                    vars_done = true;
                else
                    fprintf(os, "\n");
            } while (!vars_done);

            i++;
            if (i > rows)
                rows_done = true;
            else
                fprintf(os, "\n");
        } while (!rows_done);
    }
}

<commit_msg>AsciiSequence.cc: Added a comment about a specialization of element_count().<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of asciival, software which can return an ASCII
// representation of the data read from a DAP server.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// asciival is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2, or (at your option) any later
// version.
//
// asciival is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with GCC; see the file COPYING. If not, write to the Free Software
// Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1998,2000
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

// Implementation for the class AsciiStructure. See AsciiByte.cc
//
// 3/12/98 jhrg

#include "config.h"

#include <iostream>
#include <string>

#include "InternalErr.h"
#include "AsciiSequence.h"
#include "AsciiStructure.h"
//#include "name_map.h"
#include "get_ascii.h"
#include "debug.h"

using std::endl ;
using namespace dap_asciival;

BaseType *
AsciiSequence::ptr_duplicate()
{
    return new AsciiSequence(*this);
}

AsciiSequence::AsciiSequence(const string &n) : Sequence(n)
{
}

AsciiSequence::AsciiSequence(Sequence * bt):AsciiOutput(bt)
{
    // Let's make the alternative structure of Ascii types now so that we
    // don't have to do it on the fly.
    Vars_iter p = bt->var_begin();
    while (p != bt->var_end()) {
        if ((*p)->send_p()) {
            BaseType *new_bt = basetype_to_asciitype(*p);
            add_var(new_bt);
            delete new_bt;
        }
        p++;
    }
    set_name(bt->name());
}

AsciiSequence::~AsciiSequence()
{
}

int
AsciiSequence::length()
{
    return -1;
}

// This specialization is different from the Sequence version only in that
// it tests '*iter)->send_p()' before incrementing 'i' by
// '(*iter)->element_count(true)'.
int
AsciiSequence::element_count(bool leaves)
{
    if (!leaves)
        return _vars.size();
    else {
        int i = 0;
        for (Vars_iter iter = _vars.begin(); iter != _vars.end(); iter++) {
            if ((*iter)->send_p())
                i += (*iter)->element_count(true);
        }
        return i;
    }
}

// case 1: Simple, Seq - handled
// Case 2: Seq, Simple
void
AsciiSequence::print_ascii_row(FILE * os, int row, BaseTypeRow outer_vars)
{
    Sequence *seq = dynamic_cast < Sequence * >(_redirect);
    if (!seq)
        seq = this;

    // Print the values from this sequence.
    // AsciiSequence::element_count() returns only vars with send_p() set.
    int elements = element_count() - 1;
    int j = 0;
    bool done = false;
    do {
        BaseType *bt_ptr = seq->var_value(row, j);
        if (bt_ptr) {           // Check for data.
            BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);
            if (bt_ptr->type() == dods_sequence_c) {
                dynamic_cast <
                    AsciiSequence * >(abt_ptr)->print_ascii_rows(os,
                                                                 outer_vars);
            } else {
                // push the real base type pointer instead of the ascii one.
                // We can cast it again later from the outer_vars vector.
                outer_vars.push_back(bt_ptr);
                dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,
                                                                     false);
            }
            ++j;
            // we only need the ascii type here, so delete it
            delete abt_ptr;
        }

        // ++j;
        // When we're finally done, set the flag and omit the comma.
        if (j > elements)
            done = true;
        else if (bt_ptr)
            fprintf(os, ", ");

    } while (!done);
}

void
 AsciiSequence::print_leading_vars(FILE * os, BaseTypeRow & outer_vars)
{
    BaseTypeRow::iterator BTR_iter = outer_vars.begin();
    for (BTR_iter = outer_vars.begin(); BTR_iter != outer_vars.end();
         BTR_iter++) {
        BaseType *abt_ptr = basetype_to_asciitype(*BTR_iter);
        dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os, false);
        fprintf(os, ", ");
        // we only need the ascii base type locally, so delete it
        delete abt_ptr;
    }
}

void
 AsciiSequence::print_ascii_rows(FILE * os, BaseTypeRow outer_vars)
{
    Sequence *seq = dynamic_cast < Sequence * >(_redirect);
    if (!seq)
        seq = this;

    int rows = seq->number_of_rows() - 1;
    int i = 0;
    bool done = false;
    do {
        if (i > 0 && !outer_vars.empty())
            print_leading_vars(os, outer_vars);

        print_ascii_row(os, i++, outer_vars);

        if (i > rows)
            done = true;
        else
            fprintf(os, "\n");
    } while (!done);
}

// Assume that this mfunc is called only for simple sequences. Do not print
// table style headers for complex sequences.

void
 AsciiSequence::print_header(FILE * os)
{
    Vars_iter p = var_begin();
    while (p != var_end()) {
        if ((*p)->is_simple_type())
            fprintf(os, "%s",
                    dynamic_cast <
                    AsciiOutput * >(*p)->get_full_name().c_str());
        else if ((*p)->type() == dods_sequence_c)
            dynamic_cast < AsciiSequence * >((*p))->print_header(os);
        else if ((*p)->type() == dods_structure_c)
            dynamic_cast < AsciiStructure * >((*p))->print_header(os);
        else
            throw InternalErr(__FILE__, __LINE__,
                              "This method should only be called by instances for which `is_simple_sequence' returns true.");
        if (++p != var_end())
            fprintf(os, ", ");
    }
}

void
 AsciiSequence::print_ascii(FILE * os, bool print_name) throw(InternalErr)
{
    Sequence *seq = dynamic_cast < Sequence * >(_redirect);
    if (!seq)
        seq = this;

    if (seq->is_linear()) {
        if (print_name) {
            print_header(os);
            fprintf(os, "\n");
        }

        BaseTypeRow outer_vars(0);
        print_ascii_rows(os, outer_vars);
    } else {
        int rows = seq->number_of_rows() - 1;
        int elements = seq->element_count() - 1;

        // For each row of the Sequence...
        bool rows_done = false;
        int i = 0;
        do {
            // For each variable of the row...
            bool vars_done = false;
            int j = 0;
            do {
                BaseType *bt_ptr = seq->var_value(i, j++);
                BaseType *abt_ptr = basetype_to_asciitype(bt_ptr);
                dynamic_cast < AsciiOutput * >(abt_ptr)->print_ascii(os,
                                                                     true);
                // abt_ptr is not stored for future use, so delete it
                delete abt_ptr;

                if (j > elements)
                    vars_done = true;
                else
                    fprintf(os, "\n");
            } while (!vars_done);

            i++;
            if (i > rows)
                rows_done = true;
            else
                fprintf(os, "\n");
        } while (!rows_done);
    }
}

<|endoftext|>


<commit_before>#include "core/cli_progress_bar.h"

#include "core/cli_position.h"
#include "core/range.h"

#include <iostream>
#include <string>
#include <string_view>
#include <array>

namespace euphoria::core
{
    CliProgressBar::CliProgressBar()
        : position(GetConsolePosition().value_or(vec2i::Zero()))
        , last(Now())
    {
    }

    CliProgressBar::~CliProgressBar()
    {
        Update(1.0f, true);
    }

    void
    CliProgressBar::Update(float apercent, bool force)
    {
        constexpr float min_interval_seconds = 0.1f;
        constexpr int total_number_of_characters = 30;
        constexpr std::array animation_chars
        {
            std::string_view{"|"},
            std::string_view{"/"},
            std::string_view{"-"},
            std::string_view{"\\"}
        };
        constexpr std::string_view filled_char = "#";
        constexpr std::string_view empty_char = "-";
        constexpr std::string_view start_char = "[";
        constexpr std::string_view end_char = "]";

        const auto percent = KeepWithin(R01(), apercent);

        const auto number_of_characters = static_cast<int>(percent * total_number_of_characters);

        const auto now = Now();
        if (!force && SecondsBetween(last, now) < min_interval_seconds)
        {
            return;
        }
        last = now;

        SetConsolePosition(position);
        std::cout << start_char;
        for (int i = 0; i < number_of_characters; i += 1)
        {
            std::cout << filled_char;
        }
        for (int i = number_of_characters; i < total_number_of_characters; i += 1)
        {
            std::cout << empty_char;
        }
        std::cout << end_char;

        std::cout << "\n";
    }

    void
    CliProgressBarInfinite::Step(int each)
    {
        index += 1;
        if (index < each)
        {
            return;
        }
        index -= each;

        percent += 0.01f;
        if (percent > 1)
        {
            percent -= 1;
        }
        progress.Update(percent);
    }
}  // namespace euphoria::core
<commit_msg>better format<commit_after>#include "core/cli_progress_bar.h"

#include "core/cli_position.h"
#include "core/range.h"

#include <iostream>
#include <string>
#include <string_view>
#include <array>

namespace euphoria::core
{
    CliProgressBar::CliProgressBar()
        : position(GetConsolePosition().value_or(vec2i::Zero()))
        , last(Now())
    {
    }

    CliProgressBar::~CliProgressBar()
    {
        Update(1.0f, true);
    }

    void
    CliProgressBar::Update(float apercent, bool force)
    {
        constexpr float min_interval_seconds = 0.1f;
        constexpr int total_number_of_characters = 30;
        constexpr std::array animation_chars
        {
            std::string_view{"|"},
            std::string_view{"/"},
            std::string_view{"-"},
            std::string_view{"\\"}
        };
        constexpr std::string_view filled_char = "#";
        constexpr std::string_view empty_char = "-";
        constexpr std::string_view start_char = "[";
        constexpr std::string_view end_char = "]";

        const auto percent = KeepWithin(R01(), apercent);

        const auto number_of_characters = static_cast<int>
        (
            percent * total_number_of_characters
        );

        const auto now = Now();
        if (!force && SecondsBetween(last, now) < min_interval_seconds)
        {
            return;
        }
        last = now;

        SetConsolePosition(position);
        std::cout << start_char;
        for (int i = 0; i < number_of_characters; i += 1)
        {
            std::cout << filled_char;
        }
        for
        (
            int i = number_of_characters;
            i < total_number_of_characters;
            i += 1
        )
        {
            std::cout << empty_char;
        }
        std::cout << end_char;

        std::cout << "\n";
    }

    void
    CliProgressBarInfinite::Step(int each)
    {
        index += 1;
        if(index < each) { return; }

        index -= each;

        percent += 0.01f;
        if(percent > 1) { percent -= 1; }

        progress.Update(percent);
    }
}  // namespace euphoria::core
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1580
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1052481 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/07/06 03:00:12<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1581
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>/*!
 * \file varying_list.hpp
 * \brief file varying_list.hpp
 *
 * Copyright 2016 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#pragma once

#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/c_array.hpp>
#include <fastuidraw/util/string_array.hpp>

namespace fastuidraw
{
  namespace glsl
  {
/*!\addtogroup GLSL
 * @{
 */
    /*!
     * \brief
     * A varying_list lists all the in's of a frag shader (and
     * their names) which is the same as the out's of the vertex
     * shader which which it is paired.
     *
     * A varying is ALWAYS a SCALAR. The varyings of shaders should
     * -never- be declared in the shader code. Instead, each varying
     * should be declared in the \ref varying_list object passed to
     * the shader object's ctor. The \ref GLSL module will share the
     * varyings across different shaders within the uber-shader.
     * Indeed, the number of varying the uber-shader has is not the
     * sum of the varyings across all the shaders, but rather is the
     * maximum number of varyings across the shaders present in the
     * uber-shader.
     */
    class varying_list
    {
    public:
      /*!
       * \brief
       * Enumeration to define the interpolator type of a varying
       */
      enum interpolator_type_t
        {
          interpolator_smooth, /*!< corresponds to "smooth" of type float in GLSL */
          interpolator_noperspective, /*!< corresponds to "noperspective" of type float in GLSL */
          interpolator_flat, /*!< corresponds to "flat" of type float in GLSL */
          interpolator_uint, /*!< corresponds to "flat" of type uint in GLSL */
          interpolator_int, /*!< corresponds to "flat" of type int in GLSL */

          interpolator_number_types,
        };

      /*!
       * Ctor.
       */
      varying_list(void);

      /*!
       * Copy ctor.
       * \param rhs value from which to copy
       */
      varying_list(const varying_list &rhs);

      ~varying_list();

      /*!
       * Assignment operator.
       * \param rhs value from which to copy
       */
      varying_list&
      operator=(const varying_list &rhs);

      /*!
       * Swap operation
       * \param obj object with which to swap
       */
      void
      swap(varying_list &obj);

      /*!
       * Returns the names of the varyings of the
       * specified interpolator type.
       * \param q interpolator type
       */
      c_array<const c_string>
      varyings(enum interpolator_type_t q) const;

      /*!
       * Returns the alias names of the aliases, i.e.
       * the values of the first argument of calls
       * to \ref add_varying_alias().
       */
      c_array<const c_string>
      alias_varying_names(void) const;

      /*!
       * Returns the source names of the aliases, i.e.
       * the values of the second argument of calls to
       * \ref add_varying_alias().
       */
      c_array<const c_string>
      alias_varying_source_names(void) const;

      /*!
       * Add a varying
       * \param pname name by which to reference the varying
       * \param q interpolator type of the varying
       */
      varying_list&
      add_varying(c_string pname, enum interpolator_type_t q);

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_uint);
       * \endcode
       */
      varying_list&
      add_uint(c_string pname)
      {
        return add_varying(pname, interpolator_uint);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_int);
       * \endcode
       */
      varying_list&
      add_int(c_string pname)
      {
        return add_varying(pname, interpolator_int);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_smooth);
       * \endcode
       */
      varying_list&
      add_float(c_string pname)
      {
        return add_varying(pname, interpolator_smooth);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_flat);
       * \endcode
       */
      varying_list&
      add_float_flat(c_string pname)
      {
        return add_varying(pname, interpolator_flat);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_noperspective);
       * \endcode
       */
      varying_list&
      add_float_noperspective(c_string pname)
      {
        return add_varying(pname, interpolator_noperspective);
      }

      /*!
       * Add an alias to a varying. The use case being if a fixed
       * varying is used in two different roles and aliasing the
       * name makes the GLSL shader code more readable.
       * \param name the new identifier to reference an existing alias
       * \param src_name the varying referenced by name, which should
       *                 be a string value that has been passed as
       *                 the first argument to \ref add_varying() or
       *                 \ref add_varying_alias().
       */
      varying_list&
      add_varying_alias(c_string name, c_string src_name);

    private:
      void *m_d;
    };
/*! @} */

  }
}
<commit_msg>fastuidraw/glsl/varying_list: doxytag fix<commit_after>/*!
 * \file varying_list.hpp
 * \brief file varying_list.hpp
 *
 * Copyright 2016 by Intel.
 *
 * Contact: kevin.rogovin@intel.com
 *
 * This Source Code Form is subject to the
 * terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with
 * this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 *
 * \author Kevin Rogovin <kevin.rogovin@intel.com>
 *
 */

#pragma once

#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/c_array.hpp>
#include <fastuidraw/util/string_array.hpp>

namespace fastuidraw
{
  namespace glsl
  {
/*!\addtogroup GLSL
 * @{
 */
    /*!
     * \brief
     * A varying_list lists all the in's of a frag shader (and
     * their names) which is the same as the out's of the vertex
     * shader which which it is paired.
     *
     * A varying is ALWAYS a SCALAR. The varyings of shaders should
     * -never- be declared in the shader code. Instead, each varying
     * should be declared in the \ref varying_list object passed to
     * the shader object's ctor. The \ref GLSL module will share the
     * varyings across different shaders within the uber-shader.
     * Indeed, the number of varying the uber-shader has is not the
     * sum of the varyings across all the shaders, but rather is the
     * maximum number of varyings across the shaders present in the
     * uber-shader.
     */
    class varying_list
    {
    public:
      /*!
       * \brief
       * Enumeration to define the interpolator type of a varying
       */
      enum interpolator_type_t
        {
          interpolator_smooth, /*!< corresponds to "smooth" of type float in GLSL */
          interpolator_noperspective, /*!< corresponds to "noperspective" of type float in GLSL */
          interpolator_flat, /*!< corresponds to "flat" of type float in GLSL */
          interpolator_uint, /*!< corresponds to "flat" of type uint in GLSL */
          interpolator_int, /*!< corresponds to "flat" of type int in GLSL */

          interpolator_number_types,
        };

      /*!
       * Ctor.
       */
      varying_list(void);

      /*!
       * Copy ctor.
       * \param rhs value from which to copy
       */
      varying_list(const varying_list &rhs);

      ~varying_list();

      /*!
       * Assignment operator.
       * \param rhs value from which to copy
       */
      varying_list&
      operator=(const varying_list &rhs);

      /*!
       * Swap operation
       * \param obj object with which to swap
       */
      void
      swap(varying_list &obj);

      /*!
       * Returns the names of the varyings of the
       * specified interpolator type.
       * \param q interpolator type
       */
      c_array<const c_string>
      varyings(enum interpolator_type_t q) const;

      /*!
       * Returns the alias names of the aliases, i.e.
       * the values of the first argument of calls
       * to \ref add_varying_alias().
       */
      c_array<const c_string>
      alias_varying_names(void) const;

      /*!
       * Returns the source names of the aliases, i.e.
       * the values of the second argument of calls to
       * \ref add_varying_alias().
       */
      c_array<const c_string>
      alias_varying_source_names(void) const;

      /*!
       * Add a varying
       * \param pname name by which to reference the varying
       * \param q interpolator type of the varying
       */
      varying_list&
      add_varying(c_string pname, enum interpolator_type_t q);

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_uint);
       * \endcode
       */
      varying_list&
      add_uint(c_string pname)
      {
        return add_varying(pname, interpolator_uint);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_int);
       * \endcode
       */
      varying_list&
      add_int(c_string pname)
      {
        return add_varying(pname, interpolator_int);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_smooth);
       * \endcode
       */
      varying_list&
      add_float(c_string pname)
      {
        return add_varying(pname, interpolator_smooth);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_flat);
       * \endcode
       */
      varying_list&
      add_float_flat(c_string pname)
      {
        return add_varying(pname, interpolator_flat);
      }

      /*!
       * Add an uint varying, equivalent to
       * \code
       * add_varying(pname, interpolator_noperspective);
       * \endcode
       */
      varying_list&
      add_float_noperspective(c_string pname)
      {
        return add_varying(pname, interpolator_noperspective);
      }

      /*!
       * Add an alias to a varying. The use case being if a fixed
       * varying is used in two different roles and aliasing the
       * name makes the GLSL shader code more readable.
       * \param name the new identifier to reference an existing varying
       * \param src_name the varying referenced by name, which should
       *                 be a string value that has been passed as
       *                 the first argument to \ref add_varying() or
       *                 \ref add_varying_alias().
       */
      varying_list&
      add_varying_alias(c_string name, c_string src_name);

    private:
      void *m_d;
    };
/*! @} */

  }
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2095
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1258794 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/04/16 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2096
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2410
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1403666 by johtaylo@johtaylo-jtincrementor-increment on 2017/04/28 03:00:06<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2411
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>