<commit_before>/* The goal of these tests is to verify the behavior of all blob commands given
 * the current state is verificationStarted.  This state is achieved as a out of
 * verificationPending.
 */
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include "status.hpp"
#include "util.hpp"

#include <cstdint>
#include <string>
#include <vector>

#include <gtest/gtest.h>

namespace ipmi_flash
{
namespace
{

using ::testing::Return;

/*
 * There are the following calls (parameters may vary):
 * canHandleBlob(blob)
 * getBlobIds
 * deleteBlob(blob)
 * stat(blob)
 * stat(session)
 * open(blob)
 * close(session)
 * writemeta(session)
 * write(session)
 * read(session)
 * commit(session)
 *
 * Testing canHandleBlob is uninteresting in this state.  Getting the BlobIDs
 * will inform what canHandleBlob will return.
 */

class FirmwareHandlerVerificationStartedTest : public IpmiOnlyFirmwareStaticTest
{
  protected:
    void getToVerificationStarted(const std::string& blobId)
    {
        auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
        EXPECT_CALL(imageMock, open(blobId)).WillOnce(Return(true));
        EXPECT_TRUE(handler->open(session, flags, blobId));
        EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,
                  realHandler->getCurrentState());
        EXPECT_CALL(imageMock, close()).WillRepeatedly(Return());
        handler->close(session);
        EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationPending,
                  realHandler->getCurrentState());

        EXPECT_TRUE(handler->open(session, flags, verifyBlobId));
        EXPECT_CALL(*verifyMockPtr, triggerVerification())
            .WillOnce(Return(true));

        EXPECT_TRUE(handler->commit(session, {}));
        EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationStarted,
                  realHandler->getCurrentState());
    }

    std::uint16_t session = 1;
    std::uint16_t flags =
        blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;
};

/*
 * stat(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsRunning)
{
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_CALL(*verifyMockPtr, checkVerificationState())
        .WillOnce(Return(VerifyCheckResponses::running));

    blobs::BlobMeta meta, expectedMeta = {};
    expectedMeta.size = 0;
    expectedMeta.blobState = flags | blobs::StateFlags::committing;
    expectedMeta.metadata.push_back(
        static_cast<std::uint8_t>(VerifyCheckResponses::running));

    EXPECT_TRUE(handler->stat(session, &meta));
    EXPECT_EQ(expectedMeta, meta);
}

TEST_F(FirmwareHandlerVerificationStartedTest,
       StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsFailed)
{
    /* If the returned state from the verification handler is failed, it sets
     * commit_error and transitions to verificationCompleted.
     */
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_CALL(*verifyMockPtr, checkVerificationState())
        .WillOnce(Return(VerifyCheckResponses::failed));

    blobs::BlobMeta meta, expectedMeta = {};
    expectedMeta.size = 0;
    expectedMeta.blobState = flags | blobs::StateFlags::commit_error;
    expectedMeta.metadata.push_back(
        static_cast<std::uint8_t>(VerifyCheckResponses::failed));

    auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
    EXPECT_TRUE(handler->stat(session, &meta));
    EXPECT_EQ(expectedMeta, meta);

    EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,
              realHandler->getCurrentState());
}

TEST_F(FirmwareHandlerVerificationStartedTest,
       StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsSuccess)
{
    /* If the returned state from the verification handler is success, it sets
     * committed and transitions to verificationCompleted.
     */
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_CALL(*verifyMockPtr, checkVerificationState())
        .WillOnce(Return(VerifyCheckResponses::success));

    blobs::BlobMeta meta, expectedMeta = {};
    expectedMeta.size = 0;
    expectedMeta.blobState = flags | blobs::StateFlags::committed;
    expectedMeta.metadata.push_back(
        static_cast<std::uint8_t>(VerifyCheckResponses::success));

    auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
    EXPECT_TRUE(handler->stat(session, &meta));
    EXPECT_EQ(expectedMeta, meta);

    EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,
              realHandler->getCurrentState());
}

/* TODO: Once verificationCompleted is the state, canHandleBlob should accept
 * updateBlobId.
 */

/* TODO:
 * canHandleBlob(blob)
 *
 * getBlobIds
 *
 * deleteBlob(blob)
 */

/*
 * stat(blob)
 */
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveImageReturnsFailure)
{
    getToVerificationStarted(staticLayoutBlobId);
    ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));

    blobs::BlobMeta meta;
    EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));
}

TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveHashReturnsFailure)
{
    getToVerificationStarted(hashBlobId);
    ASSERT_TRUE(handler->canHandleBlob(activeHashBlobId));

    blobs::BlobMeta meta;
    EXPECT_FALSE(handler->stat(activeHashBlobId, &meta));
}

TEST_F(FirmwareHandlerVerificationStartedTest, StatOnVerifyBlobReturnsFailure)
{
    /* the verifyBlobId is available starting at verificationPending. */
    getToVerificationStarted(staticLayoutBlobId);
    ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));

    blobs::BlobMeta meta;
    EXPECT_FALSE(handler->stat(verifyBlobId, &meta));
}

TEST_F(FirmwareHandlerVerificationStartedTest, StatOnNormalBlobsReturnsSuccess)
{
    getToVerificationStarted(staticLayoutBlobId);

    blobs::BlobMeta expected;
    expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
    expected.size = 0;

    std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
    for (const auto& blob : testBlobs)
    {
        ASSERT_TRUE(handler->canHandleBlob(blob));

        blobs::BlobMeta meta = {};
        EXPECT_TRUE(handler->stat(blob, &meta));
        EXPECT_EQ(expected, meta);
    }
}

/*
 * writemeta(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       WriteMetaOnVerifySessionReturnsFailure)
{
    getToVerificationStarted(staticLayoutBlobId);

    std::vector<std::uint8_t> bytes = {0x01, 0x02};
    EXPECT_FALSE(handler->writeMeta(session, 0, bytes));
}

/*
 * write(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       WriteOnVerifySessionReturnsFailure)
{
    getToVerificationStarted(staticLayoutBlobId);

    std::vector<std::uint8_t> bytes = {0x01, 0x02};
    EXPECT_FALSE(handler->write(session, 0, bytes));
}

/*
 * open(blob) - there is nothing you can open, this state has an open file.
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       AttemptToOpenImageFileReturnsFailure)
{
    /* Attempt to open a file one normally can open, however, as there is
     * already a file open, this will fail.
     */
    getToVerificationStarted(staticLayoutBlobId);

    EXPECT_FALSE(handler->open(session + 1, flags, staticLayoutBlobId));
}

/*
 * close(session) - close while state if verificationStarted without calling
 * stat first will abort.
 *
 * read(session)
 *
 * commit(session)
 */

} // namespace
} // namespace ipmi_flash
<commit_msg>test: firmware verificationStarted: read<commit_after>/* The goal of these tests is to verify the behavior of all blob commands given
 * the current state is verificationStarted.  This state is achieved as a out of
 * verificationPending.
 */
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include "status.hpp"
#include "util.hpp"

#include <cstdint>
#include <string>
#include <vector>

#include <gtest/gtest.h>

namespace ipmi_flash
{
namespace
{

using ::testing::IsEmpty;
using ::testing::Return;

/*
 * There are the following calls (parameters may vary):
 * canHandleBlob(blob)
 * getBlobIds
 * deleteBlob(blob)
 * stat(blob)
 * stat(session)
 * open(blob)
 * close(session)
 * writemeta(session)
 * write(session)
 * read(session)
 * commit(session)
 *
 * Testing canHandleBlob is uninteresting in this state.  Getting the BlobIDs
 * will inform what canHandleBlob will return.
 */

class FirmwareHandlerVerificationStartedTest : public IpmiOnlyFirmwareStaticTest
{
  protected:
    void getToVerificationStarted(const std::string& blobId)
    {
        auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
        EXPECT_CALL(imageMock, open(blobId)).WillOnce(Return(true));
        EXPECT_TRUE(handler->open(session, flags, blobId));
        EXPECT_EQ(FirmwareBlobHandler::UpdateState::uploadInProgress,
                  realHandler->getCurrentState());
        EXPECT_CALL(imageMock, close()).WillRepeatedly(Return());
        handler->close(session);
        EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationPending,
                  realHandler->getCurrentState());

        EXPECT_TRUE(handler->open(session, flags, verifyBlobId));
        EXPECT_CALL(*verifyMockPtr, triggerVerification())
            .WillOnce(Return(true));

        EXPECT_TRUE(handler->commit(session, {}));
        EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationStarted,
                  realHandler->getCurrentState());
    }

    std::uint16_t session = 1;
    std::uint16_t flags =
        blobs::OpenFlags::write | FirmwareBlobHandler::UpdateFlags::ipmi;
};

/*
 * stat(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsRunning)
{
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_CALL(*verifyMockPtr, checkVerificationState())
        .WillOnce(Return(VerifyCheckResponses::running));

    blobs::BlobMeta meta, expectedMeta = {};
    expectedMeta.size = 0;
    expectedMeta.blobState = flags | blobs::StateFlags::committing;
    expectedMeta.metadata.push_back(
        static_cast<std::uint8_t>(VerifyCheckResponses::running));

    EXPECT_TRUE(handler->stat(session, &meta));
    EXPECT_EQ(expectedMeta, meta);
}

TEST_F(FirmwareHandlerVerificationStartedTest,
       StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsFailed)
{
    /* If the returned state from the verification handler is failed, it sets
     * commit_error and transitions to verificationCompleted.
     */
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_CALL(*verifyMockPtr, checkVerificationState())
        .WillOnce(Return(VerifyCheckResponses::failed));

    blobs::BlobMeta meta, expectedMeta = {};
    expectedMeta.size = 0;
    expectedMeta.blobState = flags | blobs::StateFlags::commit_error;
    expectedMeta.metadata.push_back(
        static_cast<std::uint8_t>(VerifyCheckResponses::failed));

    auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
    EXPECT_TRUE(handler->stat(session, &meta));
    EXPECT_EQ(expectedMeta, meta);

    EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,
              realHandler->getCurrentState());
}

TEST_F(FirmwareHandlerVerificationStartedTest,
       StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsSuccess)
{
    /* If the returned state from the verification handler is success, it sets
     * committed and transitions to verificationCompleted.
     */
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_CALL(*verifyMockPtr, checkVerificationState())
        .WillOnce(Return(VerifyCheckResponses::success));

    blobs::BlobMeta meta, expectedMeta = {};
    expectedMeta.size = 0;
    expectedMeta.blobState = flags | blobs::StateFlags::committed;
    expectedMeta.metadata.push_back(
        static_cast<std::uint8_t>(VerifyCheckResponses::success));

    auto realHandler = dynamic_cast<FirmwareBlobHandler*>(handler.get());
    EXPECT_TRUE(handler->stat(session, &meta));
    EXPECT_EQ(expectedMeta, meta);

    EXPECT_EQ(FirmwareBlobHandler::UpdateState::verificationCompleted,
              realHandler->getCurrentState());
}

/* TODO: Once verificationCompleted is the state, canHandleBlob should accept
 * updateBlobId.
 */

/* TODO:
 * canHandleBlob(blob)
 *
 * getBlobIds
 *
 * deleteBlob(blob)
 */

/*
 * stat(blob)
 */
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveImageReturnsFailure)
{
    getToVerificationStarted(staticLayoutBlobId);
    ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));

    blobs::BlobMeta meta;
    EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));
}

TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveHashReturnsFailure)
{
    getToVerificationStarted(hashBlobId);
    ASSERT_TRUE(handler->canHandleBlob(activeHashBlobId));

    blobs::BlobMeta meta;
    EXPECT_FALSE(handler->stat(activeHashBlobId, &meta));
}

TEST_F(FirmwareHandlerVerificationStartedTest, StatOnVerifyBlobReturnsFailure)
{
    /* the verifyBlobId is available starting at verificationPending. */
    getToVerificationStarted(staticLayoutBlobId);
    ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));

    blobs::BlobMeta meta;
    EXPECT_FALSE(handler->stat(verifyBlobId, &meta));
}

TEST_F(FirmwareHandlerVerificationStartedTest, StatOnNormalBlobsReturnsSuccess)
{
    getToVerificationStarted(staticLayoutBlobId);

    blobs::BlobMeta expected;
    expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
    expected.size = 0;

    std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
    for (const auto& blob : testBlobs)
    {
        ASSERT_TRUE(handler->canHandleBlob(blob));

        blobs::BlobMeta meta = {};
        EXPECT_TRUE(handler->stat(blob, &meta));
        EXPECT_EQ(expected, meta);
    }
}

/*
 * writemeta(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       WriteMetaOnVerifySessionReturnsFailure)
{
    getToVerificationStarted(staticLayoutBlobId);

    std::vector<std::uint8_t> bytes = {0x01, 0x02};
    EXPECT_FALSE(handler->writeMeta(session, 0, bytes));
}

/*
 * write(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       WriteOnVerifySessionReturnsFailure)
{
    getToVerificationStarted(staticLayoutBlobId);

    std::vector<std::uint8_t> bytes = {0x01, 0x02};
    EXPECT_FALSE(handler->write(session, 0, bytes));
}

/*
 * open(blob) - there is nothing you can open, this state has an open file.
 */
TEST_F(FirmwareHandlerVerificationStartedTest,
       AttemptToOpenImageFileReturnsFailure)
{
    /* Attempt to open a file one normally can open, however, as there is
     * already a file open, this will fail.
     */
    getToVerificationStarted(staticLayoutBlobId);

    EXPECT_FALSE(handler->open(session + 1, flags, staticLayoutBlobId));
}

/*
 * read(session)
 */
TEST_F(FirmwareHandlerVerificationStartedTest, ReadOfVerifyBlobReturnsEmpty)
{
    getToVerificationStarted(staticLayoutBlobId);
    EXPECT_THAT(handler->read(session, 0, 32), IsEmpty());
}

/*
 * close(session) - close while state if verificationStarted without calling
 * stat first will abort.
 *
 * commit(session)
 */

} // namespace
} // namespace ipmi_flash
<|endoftext|>


<commit_before>#include <arrayfire.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <af/utils.h>
#include <math.h>
#include "mnist_common.h"

using namespace af;

// Get accuracy of the predicted results
float accuracy(const array& predicted, const array& target)
{
    return 100 * count(predicted == target) / target.elements();
}

void naive_bayes_train(array &mu, array &sig2, const array &train_feats, const array &train_classes, int num_classes)
{
    int feat_len = train_feats.dims(0);

    // Get mean and variance from trianing data
    mu  = constant(0, feat_len, num_classes);
    sig2 = constant(0, feat_len, num_classes);
    for (int ii = 0; ii < num_classes; ii++) {
        array idx = where(train_classes == ii);
        array train_feats_ii = train_feats(span, idx);

        mu(span, ii)  = mean(train_feats_ii, 1);

        // Some pixels are always 0. Add a small variance.
        sig2(span,ii) = var(train_feats_ii, 0, 1) + 0.01;
    }

    mu.eval();
    sig2.eval();
}

array naive_bayes_predict(const array &mu, const array &sig2, const array &test_feats, int num_classes)
{
    int num_test = test_feats.dims(1);

    // Predict the probabilities for testing data
    // Using log of probabilities to reduce rounding errors
    array log_probs = constant(1, num_test, num_classes);
    for (int ii = 0; ii < num_classes; ii++) {

        // Tile the current mean and variance to the testing data size
        array Mu  = tile(mu (span, ii), 1, num_test);
        array Sig2 = tile(sig2(span, ii), 1, num_test);

        array Df = test_feats - Mu;
        array log_P =  (-(Df * Df) / (2 * Sig2))  - log(sqrt(2 * af::Pi * Sig2));

        // Accumulate the probabilities
        log_probs(span, ii) = sum(log_P).T();
    }

    // Get the location of the maximum value
    array val, idx;
    max(val, idx, log_probs, 1);
    return idx.as(f32);
}

void benchmark_nb(const array &train_feats, const array test_feats,
                  const array &train_labels, int num_classes)
{
    array mu, sig2;
    int iter = 25;

    timer::start();
    for (int i = 0; i < iter; i++) {
        naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);
    }
    af::sync();
    printf("Training time: %4.4lf s\n", timer::stop() / iter);

    timer::start();
    for (int i = 0; i < iter; i++) {
        naive_bayes_predict(mu, sig2, test_feats, num_classes);
    }
    af::sync();
    printf("Prediction time: %4.4lf s\n", timer::stop() / iter);
}

void naive_bayes_demo(bool console, int perc)
{
    array train_images, train_labels;
    array test_images, test_labels;
    int num_train, num_test, num_classes;

    // Load mnist data
    float frac = (float)(perc) / 100.0;
    setup_mnist<false>(&num_classes, &num_train, &num_test,
                       train_images, test_images,
                       train_labels, test_labels, frac);

    int feature_length = train_images.elements() / num_train;
    array train_feats = moddims(train_images, feature_length, num_train);
    array test_feats  = moddims(test_images , feature_length, num_test );

    // Preprocess
    train_feats = train_feats + tile(min(train_feats, 1), 1, num_train);
    test_feats  =  test_feats + tile(min(test_feats , 1), 1, num_test );

    // Get training parameters
    array mu, sig2;
    naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);

    // Predict the classes
    array res_labels = naive_bayes_predict(mu, sig2, test_feats, num_classes);

    // Results
    printf("Trainng samples: %4d, Testing samples: %4d\n", num_train, num_test);
    printf("Accuracy on testing  data: %2.2f\n",
           accuracy(res_labels , test_labels));

    benchmark_nb(train_feats, test_feats, train_labels, num_classes);

    if (!console) {
        display_results<false>(test_images, res_labels, 20);
    }
}

int main(int argc, char** argv)
{
    int device   = argc > 1 ? atoi(argv[1]) : 0;
    bool console = argc > 2 ? argv[2][0] == '-' : false;
    int perc     = argc > 3 ? atoi(argv[3]) : 60;

    try {

        af::deviceset(device);
        af::info();
        naive_bayes_demo(console, perc);

    } catch (af::exception &ae) {
        std::cout << ae.what() << std::endl;
    }

}
<commit_msg>Cleaning up naive bayes<commit_after>#include <arrayfire.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <af/utils.h>
#include <math.h>
#include "mnist_common.h"

using namespace af;

// Get accuracy of the predicted results
float accuracy(const array& predicted, const array& target)
{
    return 100 * count(predicted == target) / target.elements();
}

void naive_bayes_train(array &mu, array &sig2, const array &train_feats,
                       const array &train_classes, int num_classes)
{
    int feat_len = train_feats.dims(0);

    // Get mean and variance from trianing data
    mu  = constant(0, feat_len, num_classes);
    sig2 = constant(0, feat_len, num_classes);
    for (int ii = 0; ii < num_classes; ii++) {
        array idx = where(train_classes == ii);
        array train_feats_ii = train_feats(span, idx);

        mu(span, ii)  = mean(train_feats_ii, 1);

        // Some pixels are always 0. Add a small variance.
        sig2(span,ii) = var(train_feats_ii, 0, 1) + 0.01;
    }

    mu.eval();
    sig2.eval();
}

array naive_bayes_predict(const array &mu, const array &sig2, const array &test_feats, int num_classes)
{
    int num_test = test_feats.dims(1);

    // Predict the probabilities for testing data
    // Using log of probabilities to reduce rounding errors
    array log_probs = constant(1, num_test, num_classes);
    for (int ii = 0; ii < num_classes; ii++) {

        // Tile the current mean and variance to the testing data size
        array Mu  = tile(mu (span, ii), 1, num_test);
        array Sig2 = tile(sig2(span, ii), 1, num_test);

        array Df = test_feats - Mu;
        array log_P =  (-(Df * Df) / (2 * Sig2))  - log(sqrt(2 * af::Pi * Sig2));

        // Accumulate the probabilities
        log_probs(span, ii) = sum(log_P).T();
    }

    // Get the location of the maximum value
    array val, idx;
    max(val, idx, log_probs, 1);
    return idx.as(f32);
}

void benchmark_nb(const array &train_feats, const array test_feats,
                  const array &train_labels, int num_classes)
{
    array mu, sig2;
    int iter = 25;

    timer::start();
    for (int i = 0; i < iter; i++) {
        naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);
    }
    af::sync();
    printf("Training time: %4.4lf s\n", timer::stop() / iter);

    timer::start();
    for (int i = 0; i < iter; i++) {
        naive_bayes_predict(mu, sig2, test_feats, num_classes);
    }
    af::sync();
    printf("Prediction time: %4.4lf s\n", timer::stop() / iter);
}

void naive_bayes_demo(bool console, int perc)
{
    array train_images, train_labels;
    array test_images, test_labels;
    int num_train, num_test, num_classes;

    // Load mnist data
    float frac = (float)(perc) / 100.0;
    setup_mnist<false>(&num_classes, &num_train, &num_test,
                       train_images, test_images,
                       train_labels, test_labels, frac);

    int feature_length = train_images.elements() / num_train;
    array train_feats = moddims(train_images, feature_length, num_train);
    array test_feats  = moddims(test_images , feature_length, num_test );

    // Preprocess
    train_feats = train_feats;
    test_feats  =  test_feats;

    // Get training parameters
    array mu, sig2;
    naive_bayes_train(mu, sig2, train_feats, train_labels, num_classes);

    // Predict the classes
    array res_labels = naive_bayes_predict(mu, sig2, test_feats, num_classes);

    // Results
    printf("Trainng samples: %4d, Testing samples: %4d\n", num_train, num_test);
    printf("Accuracy on testing  data: %2.2f\n",
           accuracy(res_labels , test_labels));

    benchmark_nb(train_feats, test_feats, train_labels, num_classes);

    if (!console) {
        display_results<false>(test_images, res_labels, 20);
    }
}

int main(int argc, char** argv)
{
    int device   = argc > 1 ? atoi(argv[1]) : 0;
    bool console = argc > 2 ? argv[2][0] == '-' : false;
    int perc     = argc > 3 ? atoi(argv[3]) : 60;

    try {

        af::deviceset(device);
        af::info();
        naive_bayes_demo(console, perc);

    } catch (af::exception &ae) {
        std::cout << ae.what() << std::endl;
    }

}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cstdlib>		//for exit()

int main(int argc, char *argv[])
{
	using namespace std;
	if(argc==1)			//quit if no argument
	{
		cerr<<"Usage: "<<argv[0]<<" filename[s]\n";
		exit(EXIT_FAILUERE);
	}
	ifstream fin;		//open stream
	long count;
	long total = 0;
	int in;

	for(int file=1;file<argc;file++)
	{
		fin.open(argv[file]);
		count = 0;
		while(fin>>in)
		{
			cout<<in<<endl;
		}
		cout<<count<<" int in "<<argv[file]<<endl;
		total += in;
		fin.clear();
		fin.close();
	}
	cout<<"All int's value in all files is "
	<<total<<endl;

	return 0;
}<commit_msg>修改了，ex1_16.cpp<commit_after>#include <iostream>
#include <fstream>
#include <cstdlib>		//for exit()

int main(int argc, char *argv[])
{
	using namespace std;
	if(argc==1)			//quit if no argument
	{
		cerr<<"Usage: "<<argv[0]<<" filename[s]\n";
		exit(EXIT_FAILURE);
	}
	ifstream fin;		//open stream
	long count;
	long total = 0;
	int in;

	for(int file=1;file<argc;file++)
	{
		fin.open(argv[file]);
		count = 0;
		while(fin>>in)
		{
			cout<<in<<endl;
		}
		cout<<count<<" int in "<<argv[file]<<endl;
		total += in;
		fin.clear();
		fin.close();
	}
	cout<<"All int's value in all files is "
	<<total<<endl;

	return 0;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/fiber/FiberScheduler2.h"

#include <algorithm>
#include <setjmp.h>

using namespace std;
using namespace db::fiber;
using namespace db::modest;
using namespace db::rt;

#define DEFAULT_STACK_SIZE 0x1000 // 32k

FiberScheduler2::FiberScheduler2()
{
   // add first FiberId
   mFiberIdFreeList.push_back(1);
}

FiberScheduler2::~FiberScheduler2()
{
   // ensure stopped
   FiberScheduler2::stop();

   // delete all fibers
   for(FiberMap::iterator i = mFiberMap.begin(); i != mFiberMap.end(); i++)
   {
      i->second->setState(Fiber2::Dead);
      delete i->second;
   }
   mFiberMap.clear();
}

void FiberScheduler2::start(
   OperationRunner* opRunner, int numOps, size_t fiberStackSize)
{
   // save stack size
   mFiberStackSize =
      (fiberStackSize == 0 ? DEFAULT_STACK_SIZE : fiberStackSize);

   // create "numOps" Operations
   for(int i = 0; i < numOps; i++)
   {
      // create Operation
      Operation op(*this);
      mOpList.add(op);
   }

   // queue Operations
   mOpList.queue(opRunner);
}

inline void FiberScheduler2::stop()
{
   // terminate all operations
   mOpList.terminate();

   // delete all thread contexts
   for(ContextList::iterator i = mContextList.begin();
       i != mContextList.end(); i++)
   {
      delete *i;
   }
   mContextList.clear();
}

bool FiberScheduler2::waitForLastFiberExit(bool stop)
{
   bool rval = true;

   mNoFibersWaitLock.lock();
   {
      // wait on the no fibers lock until there are no more fibers
      while(rval && !mFiberMap.empty())
      {
         rval = mNoFibersWaitLock.wait();
      }
   }
   mNoFibersWaitLock.unlock();

   if(rval && stop)
   {
      // stop fiber scheduler
      this->stop();
   }

   return rval;
}

FiberId2 FiberScheduler2::addFiber(Fiber2* fiber)
{
   FiberId2 id;

   // lock scheduler to add fiber
   mScheduleLock.lock();
   {
      // get available FiberId
      id = mFiberIdFreeList.front();
      mFiberIdFreeList.pop_front();

      // add new id if list is empty
      if(mFiberIdFreeList.empty())
      {
         mFiberIdFreeList.push_back(id + 1);
      }

      // assign id and scheduler to fiber
      fiber->setScheduler(id, this);

      // add fiber to map and queue
      mFiberMap.insert(make_pair(id, fiber));
      mFiberQueue.push_back(fiber);

      // notify that a fiber is available for scheduling
      fiberAvailable();
   }
   mScheduleLock.unlock();

   return id;
}

void FiberScheduler2::run()
{
   // get and store scheduler context for this thread
   FiberContext* scheduler = new FiberContext();
   mScheduleLock.lock();
   {
      mContextList.push_back(scheduler);
   }
   mScheduleLock.unlock();

   // continue scheduling fibers while this thread is not interrupted
   Thread* t = Thread::currentThread();
   while(!t->isInterrupted())
   {
      // synchronously get the next fiber to schedule
      Fiber2* fiber = nextFiber();

      // if there is no fiber to schedule
      if(fiber == NULL)
      {
         // wait until one is available
         waitForFiber();
      }
      // else a fiber has been found
      else
      {
         if(fiber->getState() == Fiber2::New)
         {
            // initialize the fiber's context
            if(fiber->getContext()->init(fiber, mFiberStackSize))
            {
               // set fiber state to running
               fiber->setState(Fiber2::Running);
            }
            else
            {
               // failed to init fiber, not enough memory, lock to re-queue it
               mScheduleLock.lock();
               {
                  mFiberQueue.push_back(fiber);
               }
               mScheduleLock.unlock();
            }
         }

         if(fiber->getState() == Fiber2::Running)
         {
            // swap in the fiber's context
            scheduler->swap(fiber->getContext());

            if(fiber->getState() != Fiber2::Sleeping)
            {
               // lock scheduling while adding fiber back to queue
               mScheduleLock.lock();
               {
                  mFiberQueue.push_back(fiber);
               }
               mScheduleLock.unlock();

               // notify that a fiber is available
               fiberAvailable();
            }
         }
      }
   }
}

void FiberScheduler2::yield(Fiber2* fiber)
{
   // swap scheduler back in
   fiber->getContext()->swapBack();
}

void FiberScheduler2::sleep(Fiber2* fiber)
{
   fiber->setState(Fiber2::Sleeping);

   // lock scheduling to insert sleeping fiber entry
   mScheduleLock.lock();
   {
      mSleepingFibers.insert(make_pair(fiber->getId(), fiber));
   }
   mScheduleLock.unlock();

   // swap scheduler back in
   fiber->getContext()->swapBack();
}

void FiberScheduler2::wakeup(FiberId2 id)
{
   // lock scheduling while waking up sleeping fiber
   mScheduleLock.lock();
   {
      // find the sleeping fiber
      FiberMap::iterator i = mSleepingFibers.find(id);
      if(i != mSleepingFibers.end())
      {
         // update fiber state, add to queue, remove from sleeping fibers map
         i->second->setState(Fiber2::Running);
         mFiberQueue.push_back(i->second);
         mSleepingFibers.erase(i);

         // notify that a fiber is available
         fiberAvailable();
      }
   }
   mScheduleLock.unlock();
}

void FiberScheduler2::exit(Fiber2* fiber)
{
   fiber->setState(Fiber2::Exited);

   // load scheduler back in
   fiber->getContext()->loadBack();
}

Fiber2* FiberScheduler2::nextFiber()
{
   Fiber2* rval = NULL;

   // lock scheduling while iterating over and modifying fiber queue
   mScheduleLock.lock();
   {
      // look for a fiber that can be scheduled:

      // cycle through fibers not more than once
      FiberId2 cycleEnd = 0;
      for(FiberQueue::iterator i = mFiberQueue.begin();
          rval == NULL && i != mFiberQueue.end() && (*i)->getId() != cycleEnd;)
      {
         // pop fiber off queue
         Fiber2* fiber = *i;
         i = mFiberQueue.erase(i);

         // check state of fiber
         switch(fiber->getState())
         {
            // if fiber is new or running, it can be scheduled
            case Fiber2::New:
            case Fiber2::Running:
               rval = fiber;
               break;
               // exited or dead fibers must be deleted
            case Fiber2::Exited:
               fiber->setState(Fiber2::Dead);
            case Fiber2::Dead:
               // add fiber ID to free list, remove fiber from scheduler
               mFiberIdFreeList.push_front(fiber->getId());
               mFiberMap.erase(fiber->getId());
               delete fiber;
               fiber = NULL;
               break;
               // sleeping fibers cannot be scheduled
            case Fiber2::Sleeping:
               break;
         }

         // if current fiber cannot be scheduled
         if(rval == NULL && fiber != NULL)
         {
            // push fiber onto end of queue
            mFiberQueue.push_back(fiber);

            // ensure current fiber is not checked again
            if(cycleEnd == 0)
            {
               cycleEnd = fiber->getId();
            }
         }
      }

      if(mFiberMap.empty())
      {
         // notify that no fibers are available
         noFibersAvailable();
      }
   }
   mScheduleLock.unlock();

   return rval;
}

inline void FiberScheduler2::fiberAvailable()
{
   mFiberWaitLock.lock();
   mFiberWaitLock.notifyAll();
   mFiberWaitLock.unlock();
}

inline void FiberScheduler2::waitForFiber()
{
   mFiberWaitLock.lock();
   mFiberWaitLock.wait();
   mFiberWaitLock.unlock();
}

inline void FiberScheduler2::noFibersAvailable()
{
   mNoFibersWaitLock.lock();
   mNoFibersWaitLock.notifyAll();
   mNoFibersWaitLock.unlock();
}
<commit_msg>Added optimizations to handle low memory for fiber stacks.<commit_after>/*
 * Copyright (c) 2009 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/fiber/FiberScheduler2.h"

#include <algorithm>
#include <setjmp.h>

using namespace std;
using namespace db::fiber;
using namespace db::modest;
using namespace db::rt;

#define DEFAULT_STACK_SIZE 0x1000 // 32k

FiberScheduler2::FiberScheduler2()
{
   // add first FiberId
   mFiberIdFreeList.push_back(1);
}

FiberScheduler2::~FiberScheduler2()
{
   // ensure stopped
   FiberScheduler2::stop();

   // delete all fibers
   for(FiberMap::iterator i = mFiberMap.begin(); i != mFiberMap.end(); i++)
   {
      i->second->setState(Fiber2::Dead);
      delete i->second;
   }
   mFiberMap.clear();
}

void FiberScheduler2::start(
   OperationRunner* opRunner, int numOps, size_t fiberStackSize)
{
   // save stack size
   mFiberStackSize =
      (fiberStackSize == 0 ? DEFAULT_STACK_SIZE : fiberStackSize);

   // create "numOps" Operations
   for(int i = 0; i < numOps; i++)
   {
      // create Operation
      Operation op(*this);
      mOpList.add(op);
   }

   // queue Operations
   mOpList.queue(opRunner);
}

inline void FiberScheduler2::stop()
{
   // terminate all operations
   mOpList.terminate();

   // delete all thread contexts
   for(ContextList::iterator i = mContextList.begin();
       i != mContextList.end(); i++)
   {
      delete *i;
   }
   mContextList.clear();
}

bool FiberScheduler2::waitForLastFiberExit(bool stop)
{
   bool rval = true;

   mNoFibersWaitLock.lock();
   {
      // wait on the no fibers lock until there are no more fibers
      while(rval && !mFiberMap.empty())
      {
         rval = mNoFibersWaitLock.wait();
      }
   }
   mNoFibersWaitLock.unlock();

   if(rval && stop)
   {
      // stop fiber scheduler
      this->stop();
   }

   return rval;
}

FiberId2 FiberScheduler2::addFiber(Fiber2* fiber)
{
   FiberId2 id;

   // lock scheduler to add fiber
   mScheduleLock.lock();
   {
      // get available FiberId
      id = mFiberIdFreeList.front();
      mFiberIdFreeList.pop_front();

      // add new id if list is empty
      if(mFiberIdFreeList.empty())
      {
         mFiberIdFreeList.push_back(id + 1);
      }

      // assign id and scheduler to fiber
      fiber->setScheduler(id, this);

      // add fiber to map and queue
      mFiberMap.insert(make_pair(id, fiber));
      mFiberQueue.push_back(fiber);

      // notify that a fiber is available for scheduling
      fiberAvailable();
   }
   mScheduleLock.unlock();

   return id;
}

void FiberScheduler2::run()
{
   // get and store scheduler context for this thread
   FiberContext* scheduler = new FiberContext();
   mScheduleLock.lock();
   {
      mContextList.push_back(scheduler);
   }
   mScheduleLock.unlock();

   // continue scheduling fibers while this thread is not interrupted
   bool tryInit = true;
   Thread* t = Thread::currentThread();
   while(!t->isInterrupted())
   {
      // synchronously get the next fiber to schedule
      Fiber2* fiber = nextFiber();

      // if there is no fiber to schedule
      if(fiber == NULL)
      {
         // wait until one is available
         waitForFiber();
      }
      // else a fiber has been found
      else
      {
         if(fiber->getState() == Fiber2::New)
         {
            // initialize the fiber's context
            if(tryInit && fiber->getContext()->init(fiber, mFiberStackSize))
            {
               // set fiber state to running
               fiber->setState(Fiber2::Running);
            }
            else
            {
               // do not try init again until a fiber's stack is reclaimed
               tryInit = false;
            }
         }

         if(fiber->getState() != Fiber2::Running)
         {
            // failed to init fiber, not enough memory, lock to re-queue it
            mScheduleLock.lock();
            {
               mFiberQueue.push_back(fiber);
            }
            mScheduleLock.unlock();
         }
         else
         {
            // swap in the fiber's context
            scheduler->swap(fiber->getContext());

            if(fiber->getState() != Fiber2::Sleeping)
            {
               // lock scheduling while adding fiber back to queue
               mScheduleLock.lock();
               {
                  // if fiber is running, put it in the back of the queue
                  if(fiber->getState() == Fiber2::Running)
                  {
                     mFiberQueue.push_back(fiber);
                  }
                  // fiber is dying, so put it in front for quicker cleanup
                  else
                  {
                     mFiberQueue.push_front(fiber);

                     // because fiber's stack memory will be reclaimed, it
                     // is safe to try init on new fibers again
                     tryInit = true;
                  }
               }
               mScheduleLock.unlock();

               // notify that a fiber is available
               fiberAvailable();
            }
         }
      }
   }
}

void FiberScheduler2::yield(Fiber2* fiber)
{
   // swap scheduler back in
   fiber->getContext()->swapBack();
}

void FiberScheduler2::sleep(Fiber2* fiber)
{
   fiber->setState(Fiber2::Sleeping);

   // lock scheduling to insert sleeping fiber entry
   mScheduleLock.lock();
   {
      mSleepingFibers.insert(make_pair(fiber->getId(), fiber));
   }
   mScheduleLock.unlock();

   // swap scheduler back in
   fiber->getContext()->swapBack();
}

void FiberScheduler2::wakeup(FiberId2 id)
{
   // lock scheduling while waking up sleeping fiber
   mScheduleLock.lock();
   {
      // find the sleeping fiber
      FiberMap::iterator i = mSleepingFibers.find(id);
      if(i != mSleepingFibers.end())
      {
         // update fiber state, add to queue, remove from sleeping fibers map
         i->second->setState(Fiber2::Running);
         mFiberQueue.push_back(i->second);
         mSleepingFibers.erase(i);

         // notify that a fiber is available
         fiberAvailable();
      }
   }
   mScheduleLock.unlock();
}

void FiberScheduler2::exit(Fiber2* fiber)
{
   fiber->setState(Fiber2::Exited);

   // load scheduler back in
   fiber->getContext()->loadBack();
}

Fiber2* FiberScheduler2::nextFiber()
{
   Fiber2* rval = NULL;

   // lock scheduling while iterating over and modifying fiber queue
   mScheduleLock.lock();
   {
      // look for a fiber that can be scheduled:

      // cycle through fibers not more than once
      FiberId2 cycleEnd = 0;
      for(FiberQueue::iterator i = mFiberQueue.begin();
          rval == NULL && i != mFiberQueue.end() && (*i)->getId() != cycleEnd;)
      {
         // pop fiber off queue
         Fiber2* fiber = *i;
         i = mFiberQueue.erase(i);

         // check state of fiber
         switch(fiber->getState())
         {
            // if fiber is new or running, it can be scheduled
            case Fiber2::New:
            case Fiber2::Running:
               rval = fiber;
               break;
               // exited or dead fibers must be deleted
            case Fiber2::Exited:
               fiber->setState(Fiber2::Dead);
            case Fiber2::Dead:
               // add fiber ID to free list, remove fiber from scheduler
               mFiberIdFreeList.push_front(fiber->getId());
               mFiberMap.erase(fiber->getId());
               delete fiber;
               fiber = NULL;
               break;
               // sleeping fibers cannot be scheduled
            case Fiber2::Sleeping:
               break;
         }

         // if current fiber cannot be scheduled
         if(rval == NULL && fiber != NULL)
         {
            // push fiber onto end of queue
            mFiberQueue.push_back(fiber);

            // ensure current fiber is not checked again
            if(cycleEnd == 0)
            {
               cycleEnd = fiber->getId();
            }
         }
      }

      if(mFiberMap.empty())
      {
         // notify that no fibers are available
         noFibersAvailable();
      }
   }
   mScheduleLock.unlock();

   return rval;
}

inline void FiberScheduler2::fiberAvailable()
{
   mFiberWaitLock.lock();
   mFiberWaitLock.notifyAll();
   mFiberWaitLock.unlock();
}

inline void FiberScheduler2::waitForFiber()
{
   mFiberWaitLock.lock();
   mFiberWaitLock.wait();
   mFiberWaitLock.unlock();
}

inline void FiberScheduler2::noFibersAvailable()
{
   mNoFibersWaitLock.lock();
   mNoFibersWaitLock.notifyAll();
   mNoFibersWaitLock.unlock();
}
<|endoftext|>


<commit_before><commit_msg>cppcheck reduce scope of var in toolkit/...controlmodelcontainerbase.cxx<commit_after><|endoftext|>


<commit_before>// Copyright 2016 Benjamin Glatzel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Precompiled header file
#include "stdafx.h"
#include "stdafx_editor.h"

// Ui
#include "ui_IntrinsicEdPropertyEditorRotation.h"

IntrinsicEdPropertyEditorRotation::IntrinsicEdPropertyEditorRotation(
    rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties,
    rapidjson::Value* p_CurrentProperty, const char* p_PropertyName,
    QWidget* parent)
    : IntrinsicEdPropertyEditorBase(p_Document, p_CurrentProperties,
                                    p_CurrentProperty, p_PropertyName, parent)
{
  _ui.setupUi(this);
  updateFromProperty();

  QObject::connect(_ui.yaw, SIGNAL(valueChanged(double)), this,
                   SLOT(onValueChanged()));
  QObject::connect(_ui.pitch, SIGNAL(valueChanged(double)), this,
                   SLOT(onValueChanged()));
  QObject::connect(_ui.roll, SIGNAL(valueChanged(double)), this,
                   SLOT(onValueChanged()));
  QObject::connect(_ui.sYaw, SIGNAL(valueChanged(int)), this,
                   SLOT(onSliderValueChanged()));
  QObject::connect(_ui.sPitch, SIGNAL(valueChanged(int)), this,
                   SLOT(onSliderValueChanged()));
  QObject::connect(_ui.sRoll, SIGNAL(valueChanged(int)), this,
                   SLOT(onSliderValueChanged()));
}

IntrinsicEdPropertyEditorRotation::~IntrinsicEdPropertyEditorRotation() {}

void IntrinsicEdPropertyEditorRotation::updateFromProperty()
{
  _INTR_ASSERT(_property);
  const rapidjson::Value& prop = *_property;

  if (prop["readOnly"].GetBool())
  {
    _ui.yaw->setReadOnly(true);
    _ui.pitch->setReadOnly(true);
    _ui.roll->setReadOnly(true);
    _ui.sYaw->setDisabled(true);
    _ui.sPitch->setDisabled(true);
    _ui.sRoll->setDisabled(true);
  }

  glm::vec3 euler;

  if (strcmp(prop["type"].GetString(), "quat") == 0u)
  {
    const glm::quat quat =
        glm::quat(prop["values"][3].GetFloat(), prop["values"][0].GetFloat(),
                  prop["values"][1].GetFloat(), prop["values"][2].GetFloat());
    euler = glm::eulerAngles(quat);
  }
  else if (strcmp(prop["type"].GetString(), "vec3") == 0u)
  {
    euler =
        glm::vec3(glm::radians(glm::mod(prop["values"][0].GetFloat(), 360.0f)),
                  glm::radians(glm::mod(prop["values"][1].GetFloat(), 360.0f)),
                  glm::radians(glm::mod(prop["values"][2].GetFloat(), 360.0f)));
  }

  bool changed = _ui.yaw->value() != glm::degrees(euler.x) ||
                 _ui.pitch->value() != glm::degrees(euler.y) ||
                 _ui.roll->value() != glm::degrees(euler.z);

  if (changed)
  {
    _ui.yaw->blockSignals(true);
    _ui.pitch->blockSignals(true);
    _ui.roll->blockSignals(true);
    _ui.yaw->setValue(glm::degrees(euler.x));
    _ui.pitch->setValue(glm::degrees(euler.y));
    _ui.roll->setValue(glm::degrees(euler.z));
    _ui.sYaw->setValue(glm::degrees(euler.x));
    _ui.sPitch->setValue(glm::degrees(euler.y));
    _ui.sRoll->setValue(glm::degrees(euler.z));
    _ui.yaw->blockSignals(false);
    _ui.pitch->blockSignals(false);
    _ui.roll->blockSignals(false);
  }

  _ui.propertyTitle->setText(_propertyName.c_str());
}

void IntrinsicEdPropertyEditorRotation::onValueChanged()
{
  _INTR_ASSERT(_property);
  rapidjson::Value& prop = *_property;

  _ui.sYaw->setValue(_ui.yaw->value());
  _ui.sPitch->setValue(_ui.pitch->value());
  _ui.sRoll->setValue(_ui.roll->value());

  const glm::vec3 euler = glm::vec3(glm::radians(_ui.yaw->value()),
                                    glm::radians(_ui.pitch->value()),
                                    glm::radians(_ui.roll->value()));

  bool changed = false;
  if (strcmp(prop["type"].GetString(), "quat") == 0u)
  {
    const glm::quat quat = glm::quat(euler);

    changed = prop["values"][0].GetFloat() != quat.x ||
              prop["values"][1].GetFloat() != quat.y ||
              prop["values"][2].GetFloat() != quat.z ||
              prop["values"][3].GetFloat() != quat.w;

    if (changed)
    {
      prop["values"][0].SetFloat(quat.x);
      prop["values"][1].SetFloat(quat.y);
      prop["values"][2].SetFloat(quat.z);
      prop["values"][3].SetFloat(quat.w);
    }
  }
  else if (strcmp(prop["type"].GetString(), "vec3") == 0u)
  {
    changed = prop["values"][0].GetFloat() != glm::degrees(euler.x) ||
              prop["values"][1].GetFloat() != glm::degrees(euler.y) ||
              prop["values"][2].GetFloat() != glm::degrees(euler.z);

    if (changed)
    {
      prop["values"][0].SetFloat(glm::degrees(euler.x));
      prop["values"][1].SetFloat(glm::degrees(euler.y));
      prop["values"][2].SetFloat(glm::degrees(euler.z));
    }
  }

  if (changed)
    emit valueChanged(*_properties);
}

void IntrinsicEdPropertyEditorRotation::onSliderValueChanged()
{
  _INTR_ASSERT(_property);
  rapidjson::Value& prop = *_property;

  _ui.yaw->setValue(_ui.sYaw->value());
  _ui.pitch->setValue(_ui.sPitch->value());
  _ui.roll->setValue(_ui.sRoll->value());

  onValueChanged();
}
<commit_msg>Correctly block signals from sliders when updating from a property<commit_after>// Copyright 2016 Benjamin Glatzel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Precompiled header file
#include "stdafx.h"
#include "stdafx_editor.h"

// Ui
#include "ui_IntrinsicEdPropertyEditorRotation.h"

IntrinsicEdPropertyEditorRotation::IntrinsicEdPropertyEditorRotation(
    rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties,
    rapidjson::Value* p_CurrentProperty, const char* p_PropertyName,
    QWidget* parent)
    : IntrinsicEdPropertyEditorBase(p_Document, p_CurrentProperties,
                                    p_CurrentProperty, p_PropertyName, parent)
{
  _ui.setupUi(this);
  updateFromProperty();

  QObject::connect(_ui.yaw, SIGNAL(valueChanged(double)), this,
                   SLOT(onValueChanged()));
  QObject::connect(_ui.pitch, SIGNAL(valueChanged(double)), this,
                   SLOT(onValueChanged()));
  QObject::connect(_ui.roll, SIGNAL(valueChanged(double)), this,
                   SLOT(onValueChanged()));
  QObject::connect(_ui.sYaw, SIGNAL(valueChanged(int)), this,
                   SLOT(onSliderValueChanged()));
  QObject::connect(_ui.sPitch, SIGNAL(valueChanged(int)), this,
                   SLOT(onSliderValueChanged()));
  QObject::connect(_ui.sRoll, SIGNAL(valueChanged(int)), this,
                   SLOT(onSliderValueChanged()));
}

IntrinsicEdPropertyEditorRotation::~IntrinsicEdPropertyEditorRotation() {}

void IntrinsicEdPropertyEditorRotation::updateFromProperty()
{
  _INTR_ASSERT(_property);
  const rapidjson::Value& prop = *_property;

  if (prop["readOnly"].GetBool())
  {
    _ui.yaw->setReadOnly(true);
    _ui.pitch->setReadOnly(true);
    _ui.roll->setReadOnly(true);
    _ui.sYaw->setDisabled(true);
    _ui.sPitch->setDisabled(true);
    _ui.sRoll->setDisabled(true);
  }

  glm::vec3 euler;

  if (strcmp(prop["type"].GetString(), "quat") == 0u)
  {
    const glm::quat quat =
        glm::quat(prop["values"][3].GetFloat(), prop["values"][0].GetFloat(),
                  prop["values"][1].GetFloat(), prop["values"][2].GetFloat());
    euler = glm::eulerAngles(quat);
  }
  else if (strcmp(prop["type"].GetString(), "vec3") == 0u)
  {
    euler =
        glm::vec3(glm::radians(glm::mod(prop["values"][0].GetFloat(), 360.0f)),
                  glm::radians(glm::mod(prop["values"][1].GetFloat(), 360.0f)),
                  glm::radians(glm::mod(prop["values"][2].GetFloat(), 360.0f)));
  }

  bool changed = _ui.yaw->value() != glm::degrees(euler.x) ||
                 _ui.pitch->value() != glm::degrees(euler.y) ||
                 _ui.roll->value() != glm::degrees(euler.z);

  if (changed)
  {
    _ui.yaw->blockSignals(true);
    _ui.pitch->blockSignals(true);
    _ui.roll->blockSignals(true);
    _ui.sYaw->blockSignals(true);
    _ui.sPitch->blockSignals(true);
    _ui.sRoll->blockSignals(true);
    _ui.yaw->setValue(glm::degrees(euler.x));
    _ui.pitch->setValue(glm::degrees(euler.y));
    _ui.roll->setValue(glm::degrees(euler.z));
    _ui.sYaw->setValue(glm::degrees(euler.x));
    _ui.sPitch->setValue(glm::degrees(euler.y));
    _ui.sRoll->setValue(glm::degrees(euler.z));
    _ui.yaw->blockSignals(false);
    _ui.pitch->blockSignals(false);
    _ui.roll->blockSignals(false);
    _ui.sYaw->blockSignals(false);
    _ui.sPitch->blockSignals(false);
    _ui.sRoll->blockSignals(false);
  }

  _ui.propertyTitle->setText(_propertyName.c_str());
}

void IntrinsicEdPropertyEditorRotation::onValueChanged()
{
  _INTR_ASSERT(_property);
  rapidjson::Value& prop = *_property;

  _ui.sYaw->setValue(_ui.yaw->value());
  _ui.sPitch->setValue(_ui.pitch->value());
  _ui.sRoll->setValue(_ui.roll->value());

  const glm::vec3 euler = glm::vec3(glm::radians(_ui.yaw->value()),
                                    glm::radians(_ui.pitch->value()),
                                    glm::radians(_ui.roll->value()));

  bool changed = false;
  if (strcmp(prop["type"].GetString(), "quat") == 0u)
  {
    const glm::quat quat = glm::quat(euler);

    changed = prop["values"][0].GetFloat() != quat.x ||
              prop["values"][1].GetFloat() != quat.y ||
              prop["values"][2].GetFloat() != quat.z ||
              prop["values"][3].GetFloat() != quat.w;

    if (changed)
    {
      prop["values"][0].SetFloat(quat.x);
      prop["values"][1].SetFloat(quat.y);
      prop["values"][2].SetFloat(quat.z);
      prop["values"][3].SetFloat(quat.w);
    }
  }
  else if (strcmp(prop["type"].GetString(), "vec3") == 0u)
  {
    changed = prop["values"][0].GetFloat() != glm::degrees(euler.x) ||
              prop["values"][1].GetFloat() != glm::degrees(euler.y) ||
              prop["values"][2].GetFloat() != glm::degrees(euler.z);

    if (changed)
    {
      prop["values"][0].SetFloat(glm::degrees(euler.x));
      prop["values"][1].SetFloat(glm::degrees(euler.y));
      prop["values"][2].SetFloat(glm::degrees(euler.z));
    }
  }

  if (changed)
    emit valueChanged(*_properties);
}

void IntrinsicEdPropertyEditorRotation::onSliderValueChanged()
{
  _INTR_ASSERT(_property);
  rapidjson::Value& prop = *_property;

  _ui.yaw->setValue(_ui.sYaw->value());
  _ui.pitch->setValue(_ui.sPitch->value());
  _ui.roll->setValue(_ui.sRoll->value());

  onValueChanged();
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief String template class.
 *//*--------------------------------------------------------------------*/

#include "tcuStringTemplate.hpp"
#include "tcuDefs.hpp"

#include <sstream>

using std::string;
using std::map;
using std::ostringstream;

namespace tcu
{

StringTemplate::StringTemplate (void)
{
}

StringTemplate::StringTemplate (const std::string& str)
{
	setString(str);
}

StringTemplate::~StringTemplate (void)
{
}

void StringTemplate::setString (const std::string& str)
{
	m_template = str;
}

string StringTemplate::specialize (const map<string, string>& params) const
{
	ostringstream res;

	size_t curNdx = 0;
	for (;;)
	{
		size_t paramNdx = m_template.find("${", curNdx);
		if (paramNdx != string::npos)
		{
			// Append in-between stuff.
			res << m_template.substr(curNdx, paramNdx - curNdx);

			// Find end-of-param.
			size_t paramEndNdx = m_template.find("}", paramNdx);
			if (paramEndNdx == string::npos)
				throw tcu::InternalError("No '}' found in template parameter", "", __FILE__, __LINE__);

			// Parse parameter contents.
			string	paramStr		= m_template.substr(paramNdx+2, paramEndNdx-2-paramNdx);
			bool	paramSingleLine	= false;
			string	paramName;
			size_t colonNdx = paramStr.find(":");
			if (colonNdx != string::npos)
			{
				paramName = paramStr.substr(0, colonNdx);
				string flagsStr = paramStr.substr(colonNdx+1);
				TCU_CHECK(flagsStr == "single-line");
				paramSingleLine = true;
			}
			else
				paramName = paramStr;

			// Fill in parameter value.
			if (params.find(paramName) != params.end())
			{
				const string& val = (*params.find(paramName)).second;
				if (paramSingleLine)
				{
					string tmp = val;
					for (size_t ndx = tmp.find("\n"); ndx != string::npos; ndx = tmp.find("\n"))
						tmp = tmp.replace(ndx, 1, " ");
					res << tmp;
				}
				else
					res << val;
			}
			else
				throw tcu::InternalError((string("Value for parameter '") + paramName + "' not found in map").c_str(), "", __FILE__, __LINE__);

			// Skip over template.
			curNdx = paramEndNdx + 1;
		}
		else
		{
			if (curNdx < m_template.length())
				res << &m_template[curNdx];

			break;
		}
	}

	return res.str();
}

} // tcu
<commit_msg>Cherry-pick a few tcu::StringTemplate fixes to master<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief String template class.
 *//*--------------------------------------------------------------------*/

#include "tcuStringTemplate.hpp"
#include "tcuDefs.hpp"

#include <sstream>

using std::string;
using std::map;
using std::ostringstream;

namespace tcu
{

StringTemplate::StringTemplate (void)
{
}

StringTemplate::StringTemplate (const std::string& str)
{
	setString(str);
}

StringTemplate::~StringTemplate (void)
{
}

void StringTemplate::setString (const std::string& str)
{
	m_template = str;
}

string StringTemplate::specialize (const map<string, string>& params) const
{
	ostringstream res;

	size_t curNdx = 0;
	for (;;)
	{
		size_t paramNdx = m_template.find("${", curNdx);
		if (paramNdx != string::npos)
		{
			// Append in-between stuff.
			res << m_template.substr(curNdx, paramNdx - curNdx);

			// Find end-of-param.
			size_t paramEndNdx = m_template.find("}", paramNdx);
			if (paramEndNdx == string::npos)
				TCU_THROW(InternalError, "No '}' found in template parameter");

			// Parse parameter contents.
			string	paramStr		= m_template.substr(paramNdx+2, paramEndNdx-2-paramNdx);
			bool	paramSingleLine	= false;
			bool	paramOptional	= false;
			string	paramName;
			size_t colonNdx = paramStr.find(":");
			if (colonNdx != string::npos)
			{
				paramName = paramStr.substr(0, colonNdx);
				string flagsStr = paramStr.substr(colonNdx+1);
				if (flagsStr == "single-line")
				{
					paramSingleLine = true;
				}
				else if (flagsStr == "opt")
				{
					paramOptional = true;
				}
				else
				{
					TCU_THROW(InternalError, (string("Unrecognized flag") + paramStr).c_str());
				}
			}
			else
				paramName = paramStr;

			// Fill in parameter value.
			if (params.find(paramName) != params.end())
			{
				const string& val = (*params.find(paramName)).second;
				if (paramSingleLine)
				{
					string tmp = val;
					for (size_t ndx = tmp.find("\n"); ndx != string::npos; ndx = tmp.find("\n"))
						tmp = tmp.replace(ndx, 1, " ");
					res << tmp;
				}
				else
					res << val;
			}
			else if (!paramOptional)
				TCU_THROW(InternalError, (string("Value for parameter '") + paramName + "' not found in map").c_str());

			// Skip over template.
			curNdx = paramEndNdx + 1;
		}
		else
		{
			if (curNdx < m_template.length())
				res << &m_template[curNdx];

			break;
		}
	}

	return res.str();
}

} // tcu
<|endoftext|>


<commit_before>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2017                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <QApplication>
#include <QFile>

#include "mainwindow.h"

#include <ghoul/filesystem/filesystem>

static const QString style = R"style(
QWidget {
    /*font-family: "Helvetica";*/
}
QWidget#MainWindow, QTextEdit, QWidget#SyncWidget, QWidget#DownloadArea {
    background-color: rgb(40, 40, 40);
}
QTextEdit, QLabel, QComboBox, QCheckBox {
    color: #EDEDED;
    font-size: 12px;
}
QLabel {
    font-size: 13px;
}
QLabel#Image {
    margin: -10px 0px -5px 0px;
}
QTextEdit {
    border-width: 2px 2px 0px 0px;
    border-style: solid;
    background-color: rgb(60, 60, 60);
}
QPushButton {
    color:#202020;
    background-color:
        qlineargradient(
            x1: 0, y1: 0, x2: 0, y2: 1,
            stop: 0 white,
            stop: 1 #555555
        );
    border: 1px solid black;
    font-size: 11px;
    min-height: 20px;
}
QComboBox {
    background-color: rgb(60, 60, 60);
    min-height: 20px;
}
QComboBox:focus, QComboBox:focus QAbstractItemView {
    color: white;
    background-color: rgb(60, 60, 60);
    selection-background-color: rgb(75, 75, 75);
}
QCheckBox {
    border: none;
}
QCheckBox::indicator {
    width: 12px;
    height: 12px;
}
QCheckBox::indicator::unchecked {
    border: 1px solid #5A5A5A;
    background: #A0A0A0;
}
QCheckBox::indicator:unchecked:hover {
    border: 1px solid #DDDDDD;
}
QCheckBox::indicator::checked {
    border: 1px solid #5A5A5A;
    background: #5AB65A;
}
QCheckBox::indicator:checked:hover {
    border: 1px solid #DDDDDD;
}
QGroupBox, QScrollArea {
    border: 0px;
}
InfoWidget {
    border-width: 1px;
    border-style: solid;
    border-color: #BBBBBB;
    margin: 2px 1px 2px 1px;
    padding: 7.5px;
}
InfoWidget QLabel#Name {
    font-size: 17px;
}
InfoWidget QLabel#Bytes {
    font-size: 13px;
    font-family: "Lucida Console";
}
InfoWidget QLabel#MessageLeft, QLabel#MessageCenter, QLabel#MessageRight {
    font-size: 11.5px;
    margin-top: -2px;
}
InfoWidget QProgressBar {
    border: 2px solid #BBBBBB;
    border-radius: 5px;
    background: white;
    height: 15px;
}
InfoWidget QProgressBar::chunk {
    background: qlineargradient(
        x1: 0, y1: 0.5, x2: 1, y2: 0.5,
        stop: 0 #444444,
        stop: 1 #600000
    );
}
QScrollBar {
    border: 1px solid #000000;
    background: #282828;
    width: 15px;
    margin: 16px 0px 16px 0px;
}
QScrollBar::handle {
    background: #B0B0B0;
    border: 1px solid #000000;
    border-width: 1px 0px 1px 0px;
    min-height: 20px;
}
QScrollBar::add-line, QScrollBar::sub-line {
    background:#B0B0B0;
    border: 1px solid #5A5A5A;
    subcontrol-origin: margin;
}
QScrollBar::add-line {
    top: 15px;
    height: 15px;
}
QScrollBar::sub-line {
    height: 15px;
    subcontrol-position: top;
}
QScrollBar::up-arrow, QScrollBar::down-arrow {
    border: 1px solid #5A5A5A;
    width: 3px;
    height: 3px;
    background-color: #353535;
}
QScrollBar::add-page, QScrollBar::sub-page {
    background: none;
}
)style";

int main(int argc, char** argv) {
    QApplication app(argc, argv);
    app.setStyleSheet(style);

	MainWindow window;
    window.show();

    return app.exec();
}
<commit_msg>Change tab to spaces<commit_after>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2017                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <QApplication>
#include <QFile>

#include "mainwindow.h"

#include <ghoul/filesystem/filesystem>

static const QString style = R"style(
QWidget {
    /*font-family: "Helvetica";*/
}
QWidget#MainWindow, QTextEdit, QWidget#SyncWidget, QWidget#DownloadArea {
    background-color: rgb(40, 40, 40);
}
QTextEdit, QLabel, QComboBox, QCheckBox {
    color: #EDEDED;
    font-size: 12px;
}
QLabel {
    font-size: 13px;
}
QLabel#Image {
    margin: -10px 0px -5px 0px;
}
QTextEdit {
    border-width: 2px 2px 0px 0px;
    border-style: solid;
    background-color: rgb(60, 60, 60);
}
QPushButton {
    color:#202020;
    background-color:
        qlineargradient(
            x1: 0, y1: 0, x2: 0, y2: 1,
            stop: 0 white,
            stop: 1 #555555
        );
    border: 1px solid black;
    font-size: 11px;
    min-height: 20px;
}
QComboBox {
    background-color: rgb(60, 60, 60);
    min-height: 20px;
}
QComboBox:focus, QComboBox:focus QAbstractItemView {
    color: white;
    background-color: rgb(60, 60, 60);
    selection-background-color: rgb(75, 75, 75);
}
QCheckBox {
    border: none;
}
QCheckBox::indicator {
    width: 12px;
    height: 12px;
}
QCheckBox::indicator::unchecked {
    border: 1px solid #5A5A5A;
    background: #A0A0A0;
}
QCheckBox::indicator:unchecked:hover {
    border: 1px solid #DDDDDD;
}
QCheckBox::indicator::checked {
    border: 1px solid #5A5A5A;
    background: #5AB65A;
}
QCheckBox::indicator:checked:hover {
    border: 1px solid #DDDDDD;
}
QGroupBox, QScrollArea {
    border: 0px;
}
InfoWidget {
    border-width: 1px;
    border-style: solid;
    border-color: #BBBBBB;
    margin: 2px 1px 2px 1px;
    padding: 7.5px;
}
InfoWidget QLabel#Name {
    font-size: 17px;
}
InfoWidget QLabel#Bytes {
    font-size: 13px;
    font-family: "Lucida Console";
}
InfoWidget QLabel#MessageLeft, QLabel#MessageCenter, QLabel#MessageRight {
    font-size: 11.5px;
    margin-top: -2px;
}
InfoWidget QProgressBar {
    border: 2px solid #BBBBBB;
    border-radius: 5px;
    background: white;
    height: 15px;
}
InfoWidget QProgressBar::chunk {
    background: qlineargradient(
        x1: 0, y1: 0.5, x2: 1, y2: 0.5,
        stop: 0 #444444,
        stop: 1 #600000
    );
}
QScrollBar {
    border: 1px solid #000000;
    background: #282828;
    width: 15px;
    margin: 16px 0px 16px 0px;
}
QScrollBar::handle {
    background: #B0B0B0;
    border: 1px solid #000000;
    border-width: 1px 0px 1px 0px;
    min-height: 20px;
}
QScrollBar::add-line, QScrollBar::sub-line {
    background:#B0B0B0;
    border: 1px solid #5A5A5A;
    subcontrol-origin: margin;
}
QScrollBar::add-line {
    top: 15px;
    height: 15px;
}
QScrollBar::sub-line {
    height: 15px;
    subcontrol-position: top;
}
QScrollBar::up-arrow, QScrollBar::down-arrow {
    border: 1px solid #5A5A5A;
    width: 3px;
    height: 3px;
    background-color: #353535;
}
QScrollBar::add-page, QScrollBar::sub-page {
    background: none;
}
)style";

int main(int argc, char** argv) {
    QApplication app(argc, argv);
    app.setStyleSheet(style);

    MainWindow window;
    window.show();

    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_Containers_Set_inl_
#define _Stroika_Foundation_Containers_Set_inl_

#include    "../Debug/Assertions.h"

#include    "Concrete/Set_Factory.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Containers {

            /*
             ********************************************************************************
             ***************************** Set<T, TRAITS> ***********************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set ()
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set (const Set<T, TRAITS>& src)
                : inherited (static_cast<const inherited&> (src))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
            }
#if      qCompilerAndStdLib_Supports_initializer_lists
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set (const std::initializer_list<T>& s)
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                AddAll (src);
            }
#endif
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Set<T, TRAITS>::Set (const CONTAINER_OF_T& src)
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                AddAll (src);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set (const _SharedPtrIRep& rep)
                : inherited (typename inherited::_SharedPtrIRep (rep))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                RequireNotNull (rep);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline Set<T, TRAITS>::Set (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                AddAll (start, end);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator= (const Set<T, TRAITS>& rhs)
            {
                inherited::operator= (rhs);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  const typename  Set<T, TRAITS>::_IRep&    Set<T, TRAITS>::_GetRep () const
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // use static_cast cuz more efficient, but validate with assertion
                return *static_cast<const _IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  typename    Set<T, TRAITS>::_IRep&  Set<T, TRAITS>::_GetRep ()
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // use static_cast cuz more efficient, but validate with assertion
                return *static_cast<_IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  bool    Set<T, TRAITS>::Contains (T item) const
            {
                return _GetRep ().Contains (item);
            }
            template    <typename T, typename TRAITS>
            inline  Memory::Optional<T>    Set<T, TRAITS>::Lookup (T item) const
            {
                return _GetRep ().Lookup (item);
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::Add (T item)
            {
                _GetRep ().Add (item);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            void    Set<T, TRAITS>::AddAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                for (auto i = start; i != end; ++i) {
                    Add (*i);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Set<T, TRAITS>::AddAll (const CONTAINER_OF_T& s)
            {
                // Note - unlike Bag<T, TRAITS> - we dont need to check for this != &s because if we
                // attempt to add items that already exist, it would do nothing, and not lead to
                // an infinite loop
                AddAll (std::begin (s), std::end (s));
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::Remove (T item)
            {
                _GetRep ().Remove (item);
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::Remove (const Iterator<T>& i)
            {
                _GetRep ().Remove (i);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            void    Set<T, TRAITS>::RemoveAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                for (auto i = start; i != end; ++i) {
                    Remove (*i);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Set<T, TRAITS>::RemoveAll (const CONTAINER_OF_T& s)
            {
                RemoveAll (std::begin (s), std::end (s));
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::RemoveAll ()
            {
                _GetRep ().RemoveAll ();
            }
            template    <typename T, typename TRAITS>
            bool  Set<T, TRAITS>::Equals (const Set<T, TRAITS>& rhs) const
            {
                return (_GetRep ().Equals (rhs._GetRep ()));
            }
            template    <typename T, typename TRAITS>
            inline  bool  Set<T, TRAITS>::operator== (const Set<T, TRAITS>& rhs) const
            {
                return Equals (rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool    Set<T, TRAITS>::operator!= (const Set<T, TRAITS>& rhs) const
            {
                return (not Equals (rhs));
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator+= (T item)
            {
                Add (item);
                return *this;
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator+= (const CONTAINER_OF_T& items)
            {
                AddAll (items);
                return (*this);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator-= (T item)
            {
                Remove (item);
                return *this;
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator-= (const CONTAINER_OF_T& items)
            {
                RemoveAll (items);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::clear ()
            {
                RemoveAll ();
            }

            /*
             ********************************************************************************
             ************************** Set<T, TRAITS>::_IRep *******************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::_IRep::_IRep ()
            {
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::_IRep::~_IRep ()
            {
            }
            template    <typename T, typename TRAITS>
            bool    Set<T, TRAITS>::_IRep::_Equals_Reference_Implementation (const _IRep& rhs) const
            {
                if (this == &rhs) {
                    return true;
                }
                if (this->GetLength () != rhs.GetLength ()) {
                    return false;
                }
                // Note - no need to iterate over rhs because we checked sizes the same
                for (auto i = this->MakeIterator (); not i.Done (); ++i) {
                    if (not rhs.Contains (*i)) {
                        return false;
                    }
                }
                return true;
            }

        }
    }
}
#endif /* _Stroika_Foundation_Containers_Set_inl_ */
<commit_msg>fixed typo<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_Containers_Set_inl_
#define _Stroika_Foundation_Containers_Set_inl_

#include    "../Debug/Assertions.h"

#include    "Concrete/Set_Factory.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Containers {

            /*
             ********************************************************************************
             ***************************** Set<T, TRAITS> ***********************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set ()
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set (const Set<T, TRAITS>& src)
                : inherited (static_cast<const inherited&> (src))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
            }
#if      qCompilerAndStdLib_Supports_initializer_lists
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set (const std::initializer_list<T>& src)
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                AddAll (src);
            }
#endif
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Set<T, TRAITS>::Set (const CONTAINER_OF_T& src)
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                AddAll (src);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::Set (const _SharedPtrIRep& rep)
                : inherited (typename inherited::_SharedPtrIRep (rep))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                RequireNotNull (rep);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline Set<T, TRAITS>::Set (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
                : inherited (static_cast<const inherited&> (Concrete::Set_Factory<T, TRAITS>::mk ()))
            {
                AssertMember (&inherited::_GetRep (), _IRep);
                AddAll (start, end);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator= (const Set<T, TRAITS>& rhs)
            {
                inherited::operator= (rhs);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  const typename  Set<T, TRAITS>::_IRep&    Set<T, TRAITS>::_GetRep () const
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // use static_cast cuz more efficient, but validate with assertion
                return *static_cast<const _IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  typename    Set<T, TRAITS>::_IRep&  Set<T, TRAITS>::_GetRep ()
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // use static_cast cuz more efficient, but validate with assertion
                return *static_cast<_IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  bool    Set<T, TRAITS>::Contains (T item) const
            {
                return _GetRep ().Contains (item);
            }
            template    <typename T, typename TRAITS>
            inline  Memory::Optional<T>    Set<T, TRAITS>::Lookup (T item) const
            {
                return _GetRep ().Lookup (item);
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::Add (T item)
            {
                _GetRep ().Add (item);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            void    Set<T, TRAITS>::AddAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                for (auto i = start; i != end; ++i) {
                    Add (*i);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Set<T, TRAITS>::AddAll (const CONTAINER_OF_T& s)
            {
                // Note - unlike Bag<T, TRAITS> - we dont need to check for this != &s because if we
                // attempt to add items that already exist, it would do nothing, and not lead to
                // an infinite loop
                AddAll (std::begin (s), std::end (s));
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::Remove (T item)
            {
                _GetRep ().Remove (item);
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::Remove (const Iterator<T>& i)
            {
                _GetRep ().Remove (i);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            void    Set<T, TRAITS>::RemoveAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                for (auto i = start; i != end; ++i) {
                    Remove (*i);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Set<T, TRAITS>::RemoveAll (const CONTAINER_OF_T& s)
            {
                RemoveAll (std::begin (s), std::end (s));
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::RemoveAll ()
            {
                _GetRep ().RemoveAll ();
            }
            template    <typename T, typename TRAITS>
            bool  Set<T, TRAITS>::Equals (const Set<T, TRAITS>& rhs) const
            {
                return (_GetRep ().Equals (rhs._GetRep ()));
            }
            template    <typename T, typename TRAITS>
            inline  bool  Set<T, TRAITS>::operator== (const Set<T, TRAITS>& rhs) const
            {
                return Equals (rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool    Set<T, TRAITS>::operator!= (const Set<T, TRAITS>& rhs) const
            {
                return (not Equals (rhs));
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator+= (T item)
            {
                Add (item);
                return *this;
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator+= (const CONTAINER_OF_T& items)
            {
                AddAll (items);
                return (*this);
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator-= (T item)
            {
                Remove (item);
                return *this;
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Set<T, TRAITS>& Set<T, TRAITS>::operator-= (const CONTAINER_OF_T& items)
            {
                RemoveAll (items);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  void    Set<T, TRAITS>::clear ()
            {
                RemoveAll ();
            }

            /*
             ********************************************************************************
             ************************** Set<T, TRAITS>::_IRep *******************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::_IRep::_IRep ()
            {
            }
            template    <typename T, typename TRAITS>
            inline  Set<T, TRAITS>::_IRep::~_IRep ()
            {
            }
            template    <typename T, typename TRAITS>
            bool    Set<T, TRAITS>::_IRep::_Equals_Reference_Implementation (const _IRep& rhs) const
            {
                if (this == &rhs) {
                    return true;
                }
                if (this->GetLength () != rhs.GetLength ()) {
                    return false;
                }
                // Note - no need to iterate over rhs because we checked sizes the same
                for (auto i = this->MakeIterator (); not i.Done (); ++i) {
                    if (not rhs.Contains (*i)) {
                        return false;
                    }
                }
                return true;
            }

        }
    }
}
#endif /* _Stroika_Foundation_Containers_Set_inl_ */
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "util.h"

using namespace std;

bool show_addresses;

void status(string message) {
  cout << "[+] " << message << "\n";
}

void header() {
  cout << "SIC-Disassembler v1.3 by Jay Bosamiya\n"
          "-------------------------------------\n\n";
}

void usage(string progname) {
  cerr << "Usage: " << progname << " input_object_file output_assembly_file [-a]\n";
  cerr << "  Options:\n";
  cerr << "    -a   Show addresses in assembly output\n";
  exit(-2);
}

void error(string err) {
  cerr << "[!] Error: " << err << "\n";
}

void fatal(string err, int code) {
  error(err);
  exit(code);
}

bool is_hex_digit(char c) {
	return
		(c >= 'A' && c <= 'F') ||
		(c >= '0' && c <= '9');
}

bool is_hex_string(std::string s) {
	bool ret = true;
	for ( const char *c = s.c_str(); *c && ret ; c++ ) {
		ret = ret && is_hex_digit(*c);
	}
	return ret;
}

void make_upper_case(std::string &s) {
	for ( string::iterator c = s.begin() ; c != s.end() ; c++ ) {
		if ( *c >= 'a' && *c <= 'z' ) {
			*c = (*c - 'a') + 'A';
		}
	}
}

int hexchar2int(char c) {
	int ret = -1;
	if ( c >= '0' && c <= '9' ) {
		ret = (c-'0');
	} else if ( c >= 'A' && c <= 'F' ) {
		ret = (c-'A')+10;
	}
	return ret;
}

int hex2int(string s) {
	int ret = 0;
	for ( const char * cc = s.c_str() ; *cc ; cc++ ) {
		ret *= 16;
		const char &c = *cc;
		if ( is_hex_digit(c) ) {
			ret += hexchar2int(c);
		} else {
			fatal("Hex values need to be 0-9 or A-F");
		}
	}
	return ret;
}

string byte2hex(int c) {
	string ret = "";
	if ( c < 0 || c >= 256 ) {
		fatal("Illegal value for byte");
	}
	ret += (c/16 < 10)?('0'+c/16):('A'+c/16-10);
	ret += (c%16 < 10)?('0'+c%16):('A'+c%16-10);
	return ret;
}

string int2hex(int c, int bytes) {
	if ( c < 0 ) {
		return int2hex(c&0x7FFFFFFF,bytes);
	}
	if ( bytes <= 0 ) {
		return "";
	}
	return int2hex(c/256,bytes-1)+byte2hex(c%256);
}

std::string int2str(int c) {
	char ret[20];
	sprintf(ret,"%d",c);
	return ret;
}
<commit_msg>Update version<commit_after>#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "util.h"

using namespace std;

bool show_addresses;

void status(string message) {
  cout << "[+] " << message << "\n";
}

void header() {
  cout << "SIC-Disassembler v1.4 by Jay Bosamiya\n"
          "-------------------------------------\n\n";
}

void usage(string progname) {
  cerr << "Usage: " << progname << " input_object_file output_assembly_file [-a]\n";
  cerr << "  Options:\n";
  cerr << "    -a   Show addresses in assembly output\n";
  exit(-2);
}

void error(string err) {
  cerr << "[!] Error: " << err << "\n";
}

void fatal(string err, int code) {
  error(err);
  exit(code);
}

bool is_hex_digit(char c) {
	return
		(c >= 'A' && c <= 'F') ||
		(c >= '0' && c <= '9');
}

bool is_hex_string(std::string s) {
	bool ret = true;
	for ( const char *c = s.c_str(); *c && ret ; c++ ) {
		ret = ret && is_hex_digit(*c);
	}
	return ret;
}

void make_upper_case(std::string &s) {
	for ( string::iterator c = s.begin() ; c != s.end() ; c++ ) {
		if ( *c >= 'a' && *c <= 'z' ) {
			*c = (*c - 'a') + 'A';
		}
	}
}

int hexchar2int(char c) {
	int ret = -1;
	if ( c >= '0' && c <= '9' ) {
		ret = (c-'0');
	} else if ( c >= 'A' && c <= 'F' ) {
		ret = (c-'A')+10;
	}
	return ret;
}

int hex2int(string s) {
	int ret = 0;
	for ( const char * cc = s.c_str() ; *cc ; cc++ ) {
		ret *= 16;
		const char &c = *cc;
		if ( is_hex_digit(c) ) {
			ret += hexchar2int(c);
		} else {
			fatal("Hex values need to be 0-9 or A-F");
		}
	}
	return ret;
}

string byte2hex(int c) {
	string ret = "";
	if ( c < 0 || c >= 256 ) {
		fatal("Illegal value for byte");
	}
	ret += (c/16 < 10)?('0'+c/16):('A'+c/16-10);
	ret += (c%16 < 10)?('0'+c%16):('A'+c%16-10);
	return ret;
}

string int2hex(int c, int bytes) {
	if ( c < 0 ) {
		return int2hex(c&0x7FFFFFFF,bytes);
	}
	if ( bytes <= 0 ) {
		return "";
	}
	return int2hex(c/256,bytes-1)+byte2hex(c%256);
}

std::string int2str(int c) {
	char ret[20];
	sprintf(ret,"%d",c);
	return ret;
}
<|endoftext|>