<commit_before>#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "TestResult.h"
#include "TestBCFile.h"
#include "braincloud/http_codes.h"
#include "braincloud/reason_codes.h"

//#define UPLOAD_TIMEOUT_SECS 30
#define SLEEP_INTERVAL_MS 300

int TestBCFile::createFile(const char * in_path, int in_size)
{
    FILE* fp = NULL;
    fp = fopen(in_path, "w");
    if (fp == NULL)
    {
        return -1;
    }
    for (int i = 0; i < in_size; ++i)
    {
        fputc('!', fp);
    }
    fseek(fp, 0, SEEK_END);
    int fileLen = ftell(fp);
    fclose(fp);
    fp = NULL;
    return fileLen;
}

bool TestBCFile::simpleUpload(int mb, const std::string & cloudPath, const std::string & cloudFilename, std::string & out_uploadId)
{
    std::string localPath = cloudFilename;
    createFile(localPath.c_str(), mb * 1024 * 1024);

    TestResult tr;
    m_bc->getFileService()->uploadFile(cloudPath.c_str(), cloudFilename.c_str(), true, true, localPath.c_str(), &tr);
    if (!tr.run(m_bc))
    {
        return false;
    }
    out_uploadId = tr.m_response["data"]["fileDetails"]["uploadId"].asString();

    m_bc->registerFileUploadCallback(this);
    while (_completedUploadDetails.size() == 0 && _failedUploadDetails.size() == 0)
    {
        int64_t transferred = m_bc->getFileService()->getUploadBytesTransferred(out_uploadId.c_str());
        int64_t total = m_bc->getFileService()->getUploadTotalBytesToTransfer(out_uploadId.c_str());
        double progress = m_bc->getFileService()->getUploadProgress(out_uploadId.c_str());
        printf("%lld transfered %lld total %f progress\n", transferred, total, progress);

        m_bc->runCallbacks();
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    m_bc->deregisterFileUploadCallback();
    return true;
}

void TestBCFile::fileUploadCompleted(const char * in_fileUploadId, const std::string & in_jsonResponse)
{
    std::cout << "FileUploadCompleted callback hit" << std::endl;

    UploadCompletedDetails details;
    details._fileUploadId = in_fileUploadId;
    details._jsonResponse = in_jsonResponse;
    _completedUploadDetails.push_back(details);
}

void TestBCFile::fileUploadFailed(const char * in_fileUploadId, int in_statusCode, int in_reasonCode, const std::string & in_jsonResponse)
{
    std::cout << "FileUploadFailed callback hit status(" << in_statusCode << ") reason(" << in_reasonCode << ") id(" << in_fileUploadId << ")" << std::endl;

    UploadFailedDetails details;
    details._fileUploadId = in_fileUploadId;
    details._statusCode = in_statusCode;
    details._reasonCode = in_reasonCode;
    details._jsonResponse = in_jsonResponse;
    _failedUploadDetails.push_back(details);
}

// marmalade does not support file uploads... yet!
#if !defined(IW_SDK)

TEST_F(TestBCFile, UploadSimpleFile)
{
    std::string uploadId;
    if (!simpleUpload(5, "", "uploadsimplefile.txt", uploadId))
    {
        return;
    }

    ASSERT_EQ(_completedUploadDetails.size(), 1);
    ASSERT_EQ(_failedUploadDetails.size(), 0);
}

TEST_F(TestBCFile, UploadSimpleFileAndCancel)
{
    std::string localPath = "uploadsimplefile.txt";
    createFile(localPath.c_str(), 3*1024*1024);

    TestResult tr;
    m_bc->getFileService()->uploadFile("", localPath.c_str(), true, true, localPath.c_str(), &tr);
    if (!tr.run(m_bc))
    {
        return;
    }
    std::string uploadId = tr.m_response["data"]["fileDetails"]["uploadId"].asString();

    m_bc->registerFileUploadCallback(this);
    bool transferHasStarted = false;
    while(!transferHasStarted)
    {
        m_bc->runCallbacks();
        int64_t transferred = m_bc->getFileService()->getUploadBytesTransferred(uploadId.c_str());
        int64_t total = m_bc->getFileService()->getUploadTotalBytesToTransfer(uploadId.c_str());
        double progress = m_bc->getFileService()->getUploadProgress(uploadId.c_str());
        printf("%lld transfered %lld total %f progress\n", transferred, total, progress);

        if (transferred > 0)
        {
            transferHasStarted = true;
        }
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    if (!transferHasStarted)
    {
        m_bc->deregisterFileUploadCallback();
        ASSERT_TRUE(transferHasStarted);
        return;
    }

    printf("Cancelling upload\n");
    m_bc->getFileService()->cancelUpload(uploadId.c_str());
    while (_completedUploadDetails.size() == 0 && _failedUploadDetails.size() == 0)
    {
        m_bc->runCallbacks();
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    m_bc->deregisterFileUploadCallback();

    ASSERT_EQ(_failedUploadDetails.size(), 1);
    ASSERT_EQ(_completedUploadDetails.size(), 0);
    ASSERT_EQ(_failedUploadDetails[0]._statusCode, HTTP_CLIENT_NETWORK_ERROR);
    ASSERT_EQ(_failedUploadDetails[0]._reasonCode, CLIENT_UPLOAD_FILE_CANCELLED);
}

TEST_F(TestBCFile, ListUserFiles)
{
    TestResult tr;
    m_bc->getFileService()->listUserFiles(&tr);
    tr.run(m_bc);
}

TEST_F(TestBCFile, UploadMultipleFiles)
{
	m_bc->registerFileUploadCallback(this);

    std::vector<std::string> uploadIds;
    int numTransfers = 3;
    for (int i = 0; i < numTransfers; ++i)
    {
        std::string localPath = "uploadmultiplefile"  + std::to_string(i + 1) + ".txt";
        createFile(localPath.c_str(), 2*1024*1024);

        TestResult tr;
        m_bc->getFileService()->uploadFile("", localPath.c_str(), true, true, localPath.c_str(), &tr);
        if (!tr.run(m_bc))
        {
            return;
        }
        std::string uploadId = tr.m_response["data"]["fileDetails"]["uploadId"].asString();
        uploadIds.push_back(uploadId);
    }

    int timeoutMs = 120000;
    while (_completedUploadDetails.size() + _failedUploadDetails.size() < numTransfers && timeoutMs > 0)
    {
        m_bc->runCallbacks();
        for (int i = 0; i < numTransfers; ++i)
        {
            int64_t transferred = m_bc->getFileService()->getUploadBytesTransferred(uploadIds[i].c_str());
            int64_t total = m_bc->getFileService()->getUploadTotalBytesToTransfer(uploadIds[i].c_str());
            double progress = m_bc->getFileService()->getUploadProgress(uploadIds[i].c_str());
            if (transferred >= 0)
            {
                printf("File%d %lld transfered %lld total %f progress\n", i+1, transferred, total, progress);
            }
        }

        timeoutMs -= SLEEP_INTERVAL_MS;
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    m_bc->deregisterFileUploadCallback();

    ASSERT_TRUE(timeoutMs >= 0);
    ASSERT_EQ(_completedUploadDetails.size(), numTransfers);
    ASSERT_EQ(_failedUploadDetails.size(), 0);

    // Delete them. expect errors if the test failed, that's fine
    // So brainCloud doesn't grow indefinitely.
    for (int i = 0; i < numTransfers; ++i)
    {
        TestResult tr;
        std::string localPath = "uploadmultiplefile"  + std::to_string(i + 1) + ".txt";
        m_bc->getFileService()->deleteUserFile("", localPath.c_str(), &tr);
        tr.run(m_bc);
    }
}

TEST_F(TestBCFile, DeleteUserFile)
{
    std::string uploadId;
    if (!simpleUpload(19, "", "uploadsimplefile.txt", uploadId))
    {
        return;
    }

    ASSERT_EQ(_completedUploadDetails.size(), 1);
    ASSERT_EQ(_failedUploadDetails.size(), 0);

    TestResult tr;
    m_bc->getFileService()->deleteUserFile("", "uploadsimplefile.txt", &tr);
    tr.run(m_bc);
}

TEST_F(TestBCFile, GetCDNUrl)
{
	std::string uploadId;
	if (!simpleUpload(19, "", "uploadsimplefile.txt", uploadId))
	{
		return;
	}

	ASSERT_EQ(_completedUploadDetails.size(), 1);
	ASSERT_EQ(_failedUploadDetails.size(), 0);

	TestResult tr;
	m_bc->getFileService()->getCDNUrl("", "uploadsimplefile.txt", &tr);
	tr.run(m_bc);

	m_bc->getFileService()->deleteUserFile("", "uploadsimplefile.txt", &tr);
	tr.run(m_bc);
}

// this test requires use of a bandwidth limiter
// so it's normally commented out
/*
TEST_F(TestBCFile, LowRateTimeout)
{
    m_bc->setUploadLowTransferRateThreshold(500);
    m_bc->setUploadLowTransferRateTimeout(15);

    std::string uploadId;
    if (!simpleUpload(19, "", "uploadsimplefile.txt", uploadId))
    {
        return;
    }

    ASSERT_EQ(_completedUploadDetails.size(), 0);
    ASSERT_EQ(_failedUploadDetails.size(), 1);
    ASSERT_EQ(_failedUploadDetails[0]._statusCode, HTTP_CUSTOM);
    ASSERT_EQ(_failedUploadDetails[0]._reasonCode, CLIENT_UPLOAD_FILE_TIMED_OUT);
}
*/

#endif //!IW_SDK<commit_msg>Break before sleep in FileUploadCancel test<commit_after>#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "TestResult.h"
#include "TestBCFile.h"
#include "braincloud/http_codes.h"
#include "braincloud/reason_codes.h"

//#define UPLOAD_TIMEOUT_SECS 30
#define SLEEP_INTERVAL_MS 300

int TestBCFile::createFile(const char * in_path, int in_size)
{
    FILE* fp = NULL;
    fp = fopen(in_path, "w");
    if (fp == NULL)
    {
        return -1;
    }
    for (int i = 0; i < in_size; ++i)
    {
        fputc('!', fp);
    }
    fseek(fp, 0, SEEK_END);
    int fileLen = ftell(fp);
    fclose(fp);
    fp = NULL;
    return fileLen;
}

bool TestBCFile::simpleUpload(int mb, const std::string & cloudPath, const std::string & cloudFilename, std::string & out_uploadId)
{
    std::string localPath = cloudFilename;
    createFile(localPath.c_str(), mb * 1024 * 1024);

    TestResult tr;
    m_bc->getFileService()->uploadFile(cloudPath.c_str(), cloudFilename.c_str(), true, true, localPath.c_str(), &tr);
    if (!tr.run(m_bc))
    {
        return false;
    }
    out_uploadId = tr.m_response["data"]["fileDetails"]["uploadId"].asString();

    m_bc->registerFileUploadCallback(this);
    while (_completedUploadDetails.size() == 0 && _failedUploadDetails.size() == 0)
    {
        int64_t transferred = m_bc->getFileService()->getUploadBytesTransferred(out_uploadId.c_str());
        int64_t total = m_bc->getFileService()->getUploadTotalBytesToTransfer(out_uploadId.c_str());
        double progress = m_bc->getFileService()->getUploadProgress(out_uploadId.c_str());
        printf("%lld transfered %lld total %f progress\n", transferred, total, progress);

        m_bc->runCallbacks();
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    m_bc->deregisterFileUploadCallback();
    return true;
}

void TestBCFile::fileUploadCompleted(const char * in_fileUploadId, const std::string & in_jsonResponse)
{
    std::cout << "FileUploadCompleted callback hit" << std::endl;

    UploadCompletedDetails details;
    details._fileUploadId = in_fileUploadId;
    details._jsonResponse = in_jsonResponse;
    _completedUploadDetails.push_back(details);
}

void TestBCFile::fileUploadFailed(const char * in_fileUploadId, int in_statusCode, int in_reasonCode, const std::string & in_jsonResponse)
{
    std::cout << "FileUploadFailed callback hit status(" << in_statusCode << ") reason(" << in_reasonCode << ") id(" << in_fileUploadId << ")" << std::endl;

    UploadFailedDetails details;
    details._fileUploadId = in_fileUploadId;
    details._statusCode = in_statusCode;
    details._reasonCode = in_reasonCode;
    details._jsonResponse = in_jsonResponse;
    _failedUploadDetails.push_back(details);
}

// marmalade does not support file uploads... yet!
#if !defined(IW_SDK)

TEST_F(TestBCFile, UploadSimpleFile)
{
    std::string uploadId;
    if (!simpleUpload(5, "", "uploadsimplefile.txt", uploadId))
    {
        return;
    }

    ASSERT_EQ(_completedUploadDetails.size(), 1);
    ASSERT_EQ(_failedUploadDetails.size(), 0);
}

TEST_F(TestBCFile, UploadSimpleFileAndCancel)
{
    std::string localPath = "uploadsimplefile.txt";
    createFile(localPath.c_str(), 3*1024*1024);

    TestResult tr;
    m_bc->registerFileUploadCallback(this);
    m_bc->getFileService()->uploadFile("", localPath.c_str(), true, true, localPath.c_str(), &tr);
    if (!tr.run(m_bc))
    {
        return;
    }
    std::string uploadId = tr.m_response["data"]["fileDetails"]["uploadId"].asString();

    bool transferHasStarted = false;
    while(!transferHasStarted)
    {
        m_bc->runCallbacks();
        int64_t transferred = m_bc->getFileService()->getUploadBytesTransferred(uploadId.c_str());
        int64_t total = m_bc->getFileService()->getUploadTotalBytesToTransfer(uploadId.c_str());
        double progress = m_bc->getFileService()->getUploadProgress(uploadId.c_str());
        printf("%lld transfered %lld total %f progress\n", transferred, total, progress);

        if (transferred > 0)
        {
            transferHasStarted = true;
            break; // We don't want to get hit by the sleep
        }
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    if (!transferHasStarted)
    {
        m_bc->deregisterFileUploadCallback();
        ASSERT_TRUE(transferHasStarted);
        return;
    }

    printf("Cancelling upload\n");
    m_bc->getFileService()->cancelUpload(uploadId.c_str());
    while (_completedUploadDetails.size() == 0 && _failedUploadDetails.size() == 0)
    {
        m_bc->runCallbacks();
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    m_bc->deregisterFileUploadCallback();

    ASSERT_EQ(_failedUploadDetails.size(), 1);
    ASSERT_EQ(_completedUploadDetails.size(), 0);
    ASSERT_EQ(_failedUploadDetails[0]._statusCode, HTTP_CLIENT_NETWORK_ERROR);
    ASSERT_EQ(_failedUploadDetails[0]._reasonCode, CLIENT_UPLOAD_FILE_CANCELLED);
}

TEST_F(TestBCFile, ListUserFiles)
{
    TestResult tr;
    m_bc->getFileService()->listUserFiles(&tr);
    tr.run(m_bc);
}

TEST_F(TestBCFile, UploadMultipleFiles)
{
	m_bc->registerFileUploadCallback(this);

    std::vector<std::string> uploadIds;
    int numTransfers = 3;
    for (int i = 0; i < numTransfers; ++i)
    {
        std::string localPath = "uploadmultiplefile"  + std::to_string(i + 1) + ".txt";
        createFile(localPath.c_str(), 2*1024*1024);

        TestResult tr;
        m_bc->getFileService()->uploadFile("", localPath.c_str(), true, true, localPath.c_str(), &tr);
        if (!tr.run(m_bc))
        {
            return;
        }
        std::string uploadId = tr.m_response["data"]["fileDetails"]["uploadId"].asString();
        uploadIds.push_back(uploadId);
    }

    int timeoutMs = 120000;
    while (_completedUploadDetails.size() + _failedUploadDetails.size() < numTransfers && timeoutMs > 0)
    {
        m_bc->runCallbacks();
        for (int i = 0; i < numTransfers; ++i)
        {
            int64_t transferred = m_bc->getFileService()->getUploadBytesTransferred(uploadIds[i].c_str());
            int64_t total = m_bc->getFileService()->getUploadTotalBytesToTransfer(uploadIds[i].c_str());
            double progress = m_bc->getFileService()->getUploadProgress(uploadIds[i].c_str());
            if (transferred >= 0)
            {
                printf("File%d %lld transfered %lld total %f progress\n", i+1, transferred, total, progress);
            }
        }

        timeoutMs -= SLEEP_INTERVAL_MS;
        TestResult::sleep(SLEEP_INTERVAL_MS);
    }
    m_bc->deregisterFileUploadCallback();

    ASSERT_TRUE(timeoutMs >= 0);
    ASSERT_EQ(_completedUploadDetails.size(), numTransfers);
    ASSERT_EQ(_failedUploadDetails.size(), 0);

    // Delete them. expect errors if the test failed, that's fine
    // So brainCloud doesn't grow indefinitely.
    for (int i = 0; i < numTransfers; ++i)
    {
        TestResult tr;
        std::string localPath = "uploadmultiplefile"  + std::to_string(i + 1) + ".txt";
        m_bc->getFileService()->deleteUserFile("", localPath.c_str(), &tr);
        tr.run(m_bc);
    }
}

TEST_F(TestBCFile, DeleteUserFile)
{
    std::string uploadId;
    if (!simpleUpload(19, "", "uploadsimplefile.txt", uploadId))
    {
        return;
    }

    ASSERT_EQ(_completedUploadDetails.size(), 1);
    ASSERT_EQ(_failedUploadDetails.size(), 0);

    TestResult tr;
    m_bc->getFileService()->deleteUserFile("", "uploadsimplefile.txt", &tr);
    tr.run(m_bc);
}

TEST_F(TestBCFile, GetCDNUrl)
{
	std::string uploadId;
	if (!simpleUpload(19, "", "uploadsimplefile.txt", uploadId))
	{
		return;
	}

	ASSERT_EQ(_completedUploadDetails.size(), 1);
	ASSERT_EQ(_failedUploadDetails.size(), 0);

	TestResult tr;
	m_bc->getFileService()->getCDNUrl("", "uploadsimplefile.txt", &tr);
	tr.run(m_bc);

	m_bc->getFileService()->deleteUserFile("", "uploadsimplefile.txt", &tr);
	tr.run(m_bc);
}

// this test requires use of a bandwidth limiter
// so it's normally commented out
/*
TEST_F(TestBCFile, LowRateTimeout)
{
    m_bc->setUploadLowTransferRateThreshold(500);
    m_bc->setUploadLowTransferRateTimeout(15);

    std::string uploadId;
    if (!simpleUpload(19, "", "uploadsimplefile.txt", uploadId))
    {
        return;
    }

    ASSERT_EQ(_completedUploadDetails.size(), 0);
    ASSERT_EQ(_failedUploadDetails.size(), 1);
    ASSERT_EQ(_failedUploadDetails[0]._statusCode, HTTP_CUSTOM);
    ASSERT_EQ(_failedUploadDetails[0]._reasonCode, CLIENT_UPLOAD_FILE_TIMED_OUT);
}
*/

#endif //!IW_SDK<|endoftext|>


<commit_before>//
// Created by chase on 5/4/15.
//

#include "gtest/gtest.h"
#include "../EasyRedis.h"
#include "test_easyredis_fixture.h"

using namespace easyredis;{

}

TEST_F (EasyRedisTest, TestContextCreation)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6379);
    EXPECT_TRUE(easyRedis.raw_redis_context() != NULL);
    ASSERT_EQ(easyRedis.raw_redis_context()->err, 0);
}

TEST_F (EasyRedisTest, TestContextCreationFailure)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6378);
    EXPECT_TRUE(easyRedis.raw_redis_context() != NULL);
    ASSERT_EQ(easyRedis.raw_redis_context()->err, 1);
}

TEST_F (EasyRedisTest, TestRunCommandReply)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6379);
    EasyRedisReply setReply = easyRedis.run_command("SET %s %s", test_key_set.c_str(), test_value.c_str());
    EasyRedisReply getReply = easyRedis.run_command("GET %s", test_key_set.c_str());

    ASSERT_NE(setReply.raw_redis_reply()->type, REDIS_REPLY_ERROR);
    ASSERT_EQ(strcmp(test_value.c_str(), getReply.raw_redis_reply()->str), 0);
}

TEST_F (EasyRedisTest, TestRunCommandNoReply)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6379);
    EasyRedisReply setReply = easyRedis.run_command("SET %s %s", test_key_set.c_str(), test_value.c_str());
    EasyRedisReply getReply = easyRedis.run_command("GET %s", test_key_not_set.c_str());

    ASSERT_NE(setReply.raw_redis_reply()->type, REDIS_REPLY_ERROR);
    ASSERT_EQ(getReply.raw_redis_reply()->type, REDIS_REPLY_NIL);
}<commit_msg>fixing extra brackets<commit_after>//
// Created by chase on 5/4/15.
//

#include "gtest/gtest.h"
#include "../EasyRedis.h"
#include "test_easyredis_fixture.h"

using namespace easyredis;

TEST_F (EasyRedisTest, TestContextCreation)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6379);
    EXPECT_TRUE(easyRedis.raw_redis_context() != NULL);
    ASSERT_EQ(easyRedis.raw_redis_context()->err, 0);
}

TEST_F (EasyRedisTest, TestContextCreationFailure)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6378);
    EXPECT_TRUE(easyRedis.raw_redis_context() != NULL);
    ASSERT_EQ(easyRedis.raw_redis_context()->err, 1);
}

TEST_F (EasyRedisTest, TestRunCommandReply)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6379);
    EasyRedisReply setReply = easyRedis.run_command("SET %s %s", test_key_set.c_str(), test_value.c_str());
    EasyRedisReply getReply = easyRedis.run_command("GET %s", test_key_set.c_str());

    ASSERT_NE(setReply.raw_redis_reply()->type, REDIS_REPLY_ERROR);
    ASSERT_EQ(strcmp(test_value.c_str(), getReply.raw_redis_reply()->str), 0);
}

TEST_F (EasyRedisTest, TestRunCommandNoReply)
{
    EasyRedis easyRedis = EasyRedis("localhost", 6379);
    EasyRedisReply setReply = easyRedis.run_command("SET %s %s", test_key_set.c_str(), test_value.c_str());
    EasyRedisReply getReply = easyRedis.run_command("GET %s", test_key_not_set.c_str());

    ASSERT_NE(setReply.raw_redis_reply()->type, REDIS_REPLY_ERROR);
    ASSERT_EQ(getReply.raw_redis_reply()->type, REDIS_REPLY_NIL);
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

#include "../../entetes/parc.h"

using namespace std;

int main() {

    /** POUR DE L'ALÉATOIRE **/
    srand(time(NULL));

    /* *************************** */
    /* CRÉATION D'ANIMAUX          */
    /* *************************** */
    Tigre Helico(105, 654, "Diego", 1);
    Tigre Paul(241, 3321, "Pau'Pol", 2);

    Basque Xabi(125, 63, 1, 9999999, "Xabi", 3);
    Basque Ninicolas(12, 125, 14, 4419, "Nicolas Belloir", 4);

    Marmotte Miam(95, 6544, "Shakira", 5);
    Marmotte Tekitoi(245, 20, "Rihanna", 6);

    Elephant Pikachu(1021, 365, 102, "Valentin", 74);
    Elephant PHP(412, 35, 212, "C++", 744);

    Aigle Piafabec(95, 6544, "Poussin", 51);
    Aigle Roucarnage(652, 474, "Pousse pousse", 11);

    Lapin Valou(64, "Rouge", "Mimie Matti", 26);
    Lapin Tuture(205, "Blanche", "GTi", 205);

    Tortue Toto(35, 1201, "Arc-end-ciel", "Speedy Gonzalez", 7);
    Tortue Toutou(135, 11, "Invisible", "Faut pas pousser mes mail dans les ordis !", 17);

    Crocodile GrosseDent(3045, 124, "Mange de l'herbe", 8);
    Crocodile MoiJaiFaim(212345, 542, "Trotro Rigolo !", 84);

    Girafe PetiteB(120, 5412, "Gigi", 9);
    Girafe QuiVeutDesTalons(21, 6854, "Tour Eiffel", 19);

    Loutre loulou(12,14,"Moi j'ai des amis !", 110);
    Loutre PasDeSequelles(1,4,"Gnééé !", 150);

    /* *************************** */
    /* CRÉATION D'ENCLOS           */
    /* *************************** */
    Enclos parcSafari("Attrapez-les tous !", 1, 23 , 1);
    Enclos paysBasque("Zone 51", 3, 2 , 4);
    Enclos UPPA("Ça peut dégénérer en liste...", 2, 53 , 41);
    Enclos monkeyIsland("La planète des singes", 3, 5 , 11);
    Enclos azerty("Qwerty", 1, 2233 , 21);
    Enclos ocean("Hasta la victoria siempre", 3, 64 , 31);

    /* *************************** */
    /* CRÉATION D'UN PARC          */
    /* *************************** */
    cout << "*************************" << endl;
    cout << "* CRÉATION D'UN PARC    *" << endl;
    cout << "*************************" << endl;
    Parc Parc1;

    /* *************************** */
    /* AJOUT D'ENCLOS              */
    /* *************************** */
    cout << "*************************" << endl;
    cout << "* AJOUT D'ENCLOS        *" << endl;
    cout << "*************************" << endl;
    Parc1.creerEnclos("Attrapez-les tous !",1,23);
    Parc1.creerEnclos("Zone 51",3,2);
    Parc1.creerEnclos("Ça peut dégénérer en liste...",2,53);
    Parc1.creerEnclos("La planète des singes",3,5);
    Parc1.creerEnclos("Qwerty",1,21);
    Parc1.creerEnclos("Hasta la victoria siempre",3,64);

    cout << Parc1 << endl;

    for(int i=0; i<Parc1.getNbEnclos(); i++) {
        cout << Parc1.getEnclos(i) << endl;
    }

    /* *************************** */
    /* SUPPRESSION D'UN ENCLOS     */
    /* *************************** */
    cout << "***********************************" << endl;
    cout << "* SUPPRESSION D'UN ENCLOS (ID=4)  *" << endl;
    cout << "***********************************" << endl;
    Parc1.supprimerEnclos(4);
    for(int i=0; i<Parc1.getNbEnclos(); i++) {
        cout << Parc1.getEnclos(i) << endl;
    }

    /* *************************** */
    /* AJOUT D'ENCLOS              */
    /* *************************** */
    cout << "*************************" << endl;
    cout << "* AJOUT D'ANIMAUX       *" << endl;
    cout << "*************************" << endl;

    // Test ajout 1 animal dans 1 enclos
    Parc1.creerAnimal(&Helico, 1);
    cout << Parc1.getEnclos(0);
    cout << Parc1.getEnclos(0).getAnimal(0) << endl;

    // Test surpeupler enclos
    Parc1.creerAnimal(&Pikachu, 2);
    Parc1.creerAnimal(&Tuture, 2);
    Parc1.creerAnimal(&Valou, 2);
    Parc1.creerAnimal(&PetiteB, 2);
    cout << Parc1.getEnclos(1);
    cout << Parc1.getEnclos(1).getAnimal(0) << endl;
    cout << Parc1.getEnclos(1).getAnimal(1) << endl;

    // Test ajout aigle dans enclos
    Parc1.creerAnimal(&Roucarnage, 1);
    Parc1.creerAnimal(&Roucarnage, 1);
    cout << Parc1.getEnclos(0);
    cout << Parc1.getEnclos(0).getAnimal(0) << endl;

    // Test ajout proie dans enclos 1
    Parc1.creerAnimal(&Valou, 1);
    cout << Parc1.getEnclos(0);
    cout << Parc1.getEnclos(0).getAnimal(0) << endl;
    if(Parc1.getEnclos(0).getOccupation() == 2) {cout << Parc1.getEnclos(0).getAnimal(1) << endl;}

    // Test proies doivent se défendre
    Parc1.creerAnimal(&PHP, 3);
    Parc1.creerAnimal(&PHP, 3);
   // Parc1.creerAnimal(&Pikachu, 3);
  //  Parc1.creerAnimal(&Pikachu, 3);
    Parc1.creerAnimal(&Pikachu, 3);
    cout << Parc1.getEnclos(2);
    Parc1.creerAnimal(&MoiJaiFaim, 3);
    cout << Parc1.getEnclos(2) << endl;
    cout << *Parc1.getEnclos(2).getPtrAnimal(0) << endl;
   // Parc1.creerAnimal(&Helico, 5);
    //
    //cout << Parc1.getEnclos(0).getAnimal(1) << endl;
   // int a;
   // cin >> a;
    return 0;
}
<commit_msg>tests en cours sur Parc<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

#include "../../entetes/parc.h"

using namespace std;

int main() {

    /** POUR DE L'ALÉATOIRE **/
    srand(time(NULL));

    /* *************************** */
    /* CRÉATION D'ANIMAUX          */
    /* *************************** */
    Tigre Helico(105, 654, "Diego", 1);
    Tigre Paul(241, 3321, "Pau'Pol", 2);

    Basque Xabi(125, 63, 1, 9999999, "Xabi", 3);
    Basque Ninicolas(12, 125, 14, 4419, "Nicolas Belloir", 4);

    Marmotte Miam(95, 6544, "Shakira", 5);
    Marmotte Tekitoi(245, 20, "Rihanna", 6);

    Elephant Pikachu(1021, 365, 102, "Valentin", 74);
    Elephant PHP(412, 35, 212, "C++", 744);

    Aigle Piafabec(95, 6544, "Poussin", 51);
    Aigle Roucarnage(652, 474, "Pousse pousse", 11);

    Lapin Valou(64, "Rouge", "Mimie Matti", 26);
    Lapin Tuture(205, "Blanche", "GTi", 205);

    Tortue Toto(35, 1201, "Arc-end-ciel", "Speedy Gonzalez", 7);
    Tortue Toutou(135, 11, "Invisible", "Faut pas pousser mes mail dans les ordis !", 17);

    Crocodile GrosseDent(3045, 124, "Mange de l'herbe", 8);
    Crocodile MoiJaiFaim(212345, 542, "Trotro Rigolo !", 84);

    Girafe PetiteB(120, 5412, "Gigi", 9);
    Girafe QuiVeutDesTalons(21, 6854, "Tour Eiffel", 19);

    Loutre loulou(12,14,"Moi j'ai des amis !", 110);
    Loutre PasDeSequelles(1,4,"Gnééé !", 150);

    /* *************************** */
    /* CRÉATION D'ENCLOS           */
    /* *************************** */
    Enclos parcSafari("Attrapez-les tous !", 1, 23 , 1);
    Enclos paysBasque("Zone 51", 3, 2 , 4);
    Enclos UPPA("Ça peut dégénérer en liste...", 2, 53 , 41);
    Enclos monkeyIsland("La planète des singes", 3, 5 , 11);
    Enclos azerty("Qwerty", 1, 2233 , 21);
    Enclos ocean("Hasta la victoria siempre", 3, 64 , 31);

    /* *************************** */
    /* CRÉATION D'UN PARC          */
    /* *************************** */
    cout << "*************************" << endl;
    cout << "* CRÉATION D'UN PARC    *" << endl;
    cout << "*************************" << endl;
    Parc Parc1;

    /* *************************** */
    /* AJOUT D'ENCLOS              */
    /* *************************** */
    cout << "*************************" << endl;
    cout << "* AJOUT D'ENCLOS        *" << endl;
    cout << "*************************" << endl;
    Parc1.creerEnclos("Attrapez-les tous !",1,23);
    Parc1.creerEnclos("Zone 51",3,2);
    Parc1.creerEnclos("Ça peut dégénérer en liste...",2,53);
    Parc1.creerEnclos("La planète des singes",3,5);
    Parc1.creerEnclos("Qwerty",1,21);
    Parc1.creerEnclos("Hasta la victoria siempre",3,64);

    cout << Parc1 << endl;

    for(int i=0; i<Parc1.getNbEnclos(); i++) {
        cout << Parc1.getEnclos(i) << endl;
    }

    /* *************************** */
    /* SUPPRESSION D'UN ENCLOS     */
    /* *************************** */
    cout << "***********************************" << endl;
    cout << "* SUPPRESSION D'UN ENCLOS (ID=4)  *" << endl;
    cout << "***********************************" << endl;
    Parc1.supprimerEnclos(4);
    for(int i=0; i<Parc1.getNbEnclos(); i++) {
        cout << Parc1.getEnclos(i) << endl;
    }

    /* *************************** */
    /* AJOUT D'ENCLOS              */
    /* *************************** */
    cout << "*************************" << endl;
    cout << "* AJOUT D'ANIMAUX       *" << endl;
    cout << "*************************" << endl;

    // Test ajout 1 animal dans 1 enclos
    Parc1.creerAnimal(&Helico, 1);
    cout << Parc1.getEnclos(0);
    cout << Parc1.getEnclos(0).getAnimal(0) << endl;

    // Test surpeupler enclos
    Parc1.creerAnimal(&Pikachu, 2);
    Parc1.creerAnimal(&Tuture, 2);
    Parc1.creerAnimal(&Valou, 2);
    Parc1.creerAnimal(&PetiteB, 2);
    cout << Parc1.getEnclos(1);
    cout << Parc1.getEnclos(1).getAnimal(0) << endl;
    cout << Parc1.getEnclos(1).getAnimal(1) << endl;

    // Test ajout aigle dans enclos
    Parc1.creerAnimal(&Roucarnage, 1);
    Parc1.creerAnimal(&Roucarnage, 1);
    cout << Parc1.getEnclos(0);
    cout << Parc1.getEnclos(0).getAnimal(0) << endl;

    // Test ajout proie dans enclos 1
    Parc1.creerAnimal(&Valou, 1);
    cout << Parc1.getEnclos(0);
    cout << Parc1.getEnclos(0).getAnimal(0) << endl;
    if(Parc1.getEnclos(0).getOccupation() == 2) {cout << Parc1.getEnclos(0).getAnimal(1) << endl;}

    // Test proies doivent se défendre
    Parc1.creerAnimal(&PHP, 3);
    Parc1.creerAnimal(&PHP, 3);
   // Parc1.creerAnimal(&Pikachu, 3);
  //  Parc1.creerAnimal(&Pikachu, 3);
    Parc1.creerAnimal(&Pikachu, 3);
    cout << Parc1.getEnclos(2);
    Parc1.creerAnimal(&MoiJaiFaim, 3);
    cout << Parc1.getEnclos(2) << endl;
    cout << *Parc1.getEnclos(2).getPtrAnimal(0) << endl;
    cout << *Parc1.getEnclos(2).getPtrAnimal(1) << endl;
   // Parc1.creerAnimal(&Helico, 5);
    //
    //cout << Parc1.getEnclos(0).getAnimal(1) << endl;
   // int a;
   // cin >> a;
    return 0;
}
<|endoftext|>


<commit_before>/*===========================================================================*\
*                                                                           *
*                               OpenMesh                                    *
*      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
*                           www.openmesh.org                                *
*                                                                           *
*---------------------------------------------------------------------------*
*  This file is part of OpenMesh.                                           *
*                                                                           *
*  OpenMesh is free software: you can redistribute it and/or modify         *
*  it under the terms of the GNU Lesser General Public License as           *
*  published by the Free Software Foundation, either version 3 of           *
*  the License, or (at your option) any later version with the              *
*  following exceptions:                                                    *
*                                                                           *
*  If other files instantiate templates or use macros                       *
*  or inline functions from this file, or you compile this file and         *
*  link it with other files to produce an executable, this file does        *
*  not by itself cause the resulting executable to be covered by the        *
*  GNU Lesser General Public License. This exception does not however       *
*  invalidate any other reasons why the executable file might be            *
*  covered by the GNU Lesser General Public License.                        *
*                                                                           *
*  OpenMesh is distributed in the hope that it will be useful,              *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
*  GNU Lesser General Public License for more details.                      *
*                                                                           *
*  You should have received a copy of the GNU LesserGeneral Public          *
*  License along with OpenMesh.  If not,                                    *
*  see <http://www.gnu.org/licenses/>.                                      *
*                                                                           *
\*==========================================================================*/

/*==========================================================================*\
*                                                                           *
*   $Revision: 410 $                                                        *
*   $Date: 2010-06-17 12:45:58 +0200 (Do, 17. Jun 2010) $                   *
*                                                                           *
\*==========================================================================*/

/** \file LongestEdgeT.hh

*/

//=============================================================================
//
//  CLASS LongestEdgeT
//
//=============================================================================

#ifndef LINEAR_H
#define LINEAR_H

#include <OpenMesh/Tools/Subdivider/Uniform/SubdividerT.hh>
#include <OpenMesh/Core/Utils/vector_cast.hh>
#include <OpenMesh/Core/Utils/Property.hh>
// -------------------- STL
#include <vector>
#include <queue>
#if defined(OM_CC_MIPS)
#  include <math.h>
#else
#  include <cmath>
#endif

//== NAMESPACE ================================================================

namespace OpenMesh   { // BEGIN_NS_OPENMESH
namespace Subdivider { // BEGIN_NS_DECIMATER
namespace Uniform    { // BEGIN_NS_UNIFORM

//== CLASS DEFINITION =========================================================

template <typename MeshType, typename RealType = float>
class CompareLengthFunction {
    public:

    bool operator()( const std::pair< typename MeshType::EdgeHandle, RealType >& t1, const std::pair< typename MeshType::EdgeHandle, RealType >& t2) // Returns true if t1 is earlier than t2
    {
       if (t1.second < t2.second)
         return true;
       else
         return false;
    }
};

/** %Uniform LongestEdgeT subdivision algorithm
 *
 * Very simple algorithm splitting all edges which are longer than given via
 * set_max_edge_length(). The split is always performed on the longest
 * edge in the mesh.
 */
template <typename MeshType, typename RealType = float>
class LongestEdgeT : public SubdividerT<MeshType, RealType>
{
public:

  typedef RealType                                real_t;
  typedef MeshType                                mesh_t;
  typedef SubdividerT< mesh_t, real_t >           parent_t;

  typedef std::vector< std::vector<real_t> >      weights_t;
  typedef std::vector<real_t>                     weight_t;

public:

  LongestEdgeT() : parent_t()
  {  }

  LongestEdgeT( mesh_t& _m) : parent_t(_m)
  {  }

  ~LongestEdgeT() {}

public:

  const char *name() const { return "Longest Edge Split"; }

  void set_max_edge_length(double _value) {
    max_edge_length_squared_ = _value * _value;
  }

protected:

  bool prepare( mesh_t& _m )
  {
    return true;
  }

  bool cleanup( mesh_t& _m )
  {
    return true;
  }

  bool subdivide( MeshType& _m, size_t _n , const bool _update_points = true)
  {

    typedef std::pair< typename mesh_t::EdgeHandle, real_t > queueElement;
    // Sorted queue containing all edges sorted by their decreasing length
    std::priority_queue< queueElement, std::vector< queueElement > , CompareLengthFunction< typename mesh_t::EdgeHandle, real_t > > queue;

    // Build the initial queue
    // First element should be longest edge
    typename mesh_t::EdgeIter edgesEnd = _m.edges_end();
    for ( typename mesh_t::EdgeIter eit  = _m.edges_begin(); eit != edgesEnd; ++eit) {
      const typename MeshType::Point to   = _m.point(_m.to_vertex_handle(_m.halfedge_handle(eit,0)));
      const typename MeshType::Point from = _m.point(_m.from_vertex_handle(_m.halfedge_handle(eit,0)));

      real_t length = (to - from).sqrnorm();

      // Only push the edges that need to be split
      if ( length > max_edge_length_squared_ )
        queue.push( queueElement(eit.handle(),length) );
    }

    bool stop = false;
    while ( !stop && ! queue.empty() ) {
      queueElement a = queue.top();
      queue.pop();

      if ( a.second < max_edge_length_squared_ ) {
        stop = true;
        break;
      } else {
        const typename MeshType::Point to   = _m.point(_m.to_vertex_handle(_m.halfedge_handle(a.first,0)));
        const typename MeshType::Point from = _m.point(_m.from_vertex_handle(_m.halfedge_handle(a.first,0)));
        const typename MeshType::Point midpoint = 0.5 * ( to + from );

        const typename MeshType::VertexHandle newVertex = _m.add_vertex(midpoint);
        _m.split(a.first,newVertex);

        for ( typename MeshType::VertexOHalfedgeIter voh_it(_m,newVertex); voh_it; ++voh_it) {
          typename MeshType::EdgeHandle eh = _m.edge_handle(voh_it.handle());
          const typename MeshType::Point to   = _m.point(_m.to_vertex_handle(voh_it));
          const typename MeshType::Point from = _m.point(_m.from_vertex_handle(voh_it));
          real_t length = (to - from).sqrnorm();

          // Only push the edges that need to be split
          if ( length > max_edge_length_squared_ )
            queue.push( queueElement(eh,length) );

        }
      }
    }

#if defined(_DEBUG) || defined(DEBUG)
      // Now we have an consistent mesh!
      assert( OpenMesh::Utils::MeshCheckerT<mesh_t>(_m).check() );
#endif

    return true;
  }

private: // data
  real_t max_edge_length_squared_;

};

} // END_NS_UNIFORM
} // END_NS_SUBDIVIDER
} // END_NS_OPENMESH
#endif

<commit_msg>Try to fix build error on windows<commit_after>/*===========================================================================*\
*                                                                           *
*                               OpenMesh                                    *
*      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
*                           www.openmesh.org                                *
*                                                                           *
*---------------------------------------------------------------------------*
*  This file is part of OpenMesh.                                           *
*                                                                           *
*  OpenMesh is free software: you can redistribute it and/or modify         *
*  it under the terms of the GNU Lesser General Public License as           *
*  published by the Free Software Foundation, either version 3 of           *
*  the License, or (at your option) any later version with the              *
*  following exceptions:                                                    *
*                                                                           *
*  If other files instantiate templates or use macros                       *
*  or inline functions from this file, or you compile this file and         *
*  link it with other files to produce an executable, this file does        *
*  not by itself cause the resulting executable to be covered by the        *
*  GNU Lesser General Public License. This exception does not however       *
*  invalidate any other reasons why the executable file might be            *
*  covered by the GNU Lesser General Public License.                        *
*                                                                           *
*  OpenMesh is distributed in the hope that it will be useful,              *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
*  GNU Lesser General Public License for more details.                      *
*                                                                           *
*  You should have received a copy of the GNU LesserGeneral Public          *
*  License along with OpenMesh.  If not,                                    *
*  see <http://www.gnu.org/licenses/>.                                      *
*                                                                           *
\*==========================================================================*/

/*==========================================================================*\
*                                                                           *
*   $Revision: 410 $                                                        *
*   $Date: 2010-06-17 12:45:58 +0200 (Do, 17. Jun 2010) $                   *
*                                                                           *
\*==========================================================================*/

/** \file LongestEdgeT.hh

*/

//=============================================================================
//
//  CLASS LongestEdgeT
//
//=============================================================================

#ifndef LINEAR_H
#define LINEAR_H

#include <OpenMesh/Tools/Subdivider/Uniform/SubdividerT.hh>
#include <OpenMesh/Core/Utils/vector_cast.hh>
#include <OpenMesh/Core/Utils/Property.hh>
// -------------------- STL
#include <vector>
#include <queue>
#if defined(OM_CC_MIPS)
#  include <math.h>
#else
#  include <cmath>
#endif

//== NAMESPACE ================================================================

namespace OpenMesh   { // BEGIN_NS_OPENMESH
namespace Subdivider { // BEGIN_NS_DECIMATER
namespace Uniform    { // BEGIN_NS_UNIFORM

//== CLASS DEFINITION =========================================================

template <typename MeshType, typename RealType = float>
class CompareLengthFunction {
  public:

    typedef std::pair<typename MeshType::EdgeHandle, RealType> queueElement;

    bool operator()(const queueElement& t1, const queueElement& t2) // Returns true if t1 is smaller than t2
    {
      return (t1.second < t2.second);
    }
};

/** %Uniform LongestEdgeT subdivision algorithm
 *
 * Very simple algorithm splitting all edges which are longer than given via
 * set_max_edge_length(). The split is always performed on the longest
 * edge in the mesh.
 */
template <typename MeshType, typename RealType = float>
class LongestEdgeT : public SubdividerT<MeshType, RealType>
{
public:

  typedef RealType                                real_t;
  typedef MeshType                                mesh_t;
  typedef SubdividerT< mesh_t, real_t >           parent_t;

  typedef std::vector< std::vector<real_t> >      weights_t;
  typedef std::vector<real_t>                     weight_t;

  typedef std::pair< typename mesh_t::EdgeHandle, real_t > queueElement;

public:

  LongestEdgeT() : parent_t()
  {  }

  LongestEdgeT( mesh_t& _m) : parent_t(_m)
  {  }

  ~LongestEdgeT() {}

public:

  const char *name() const { return "Longest Edge Split"; }

  void set_max_edge_length(double _value) {
    max_edge_length_squared_ = _value * _value;
  }

protected:

  bool prepare( mesh_t& _m )
  {
    return true;
  }

  bool cleanup( mesh_t& _m )
  {
    return true;
  }

  bool subdivide( MeshType& _m, size_t _n , const bool _update_points = true)
  {

    // Sorted queue containing all edges sorted by their decreasing length
    std::priority_queue< queueElement, std::vector< queueElement > , CompareLengthFunction< typename mesh_t::EdgeHandle, real_t > > queue;

    // Build the initial queue
    // First element should be longest edge
    typename mesh_t::EdgeIter edgesEnd = _m.edges_end();
    for ( typename mesh_t::EdgeIter eit  = _m.edges_begin(); eit != edgesEnd; ++eit) {
      const typename MeshType::Point to   = _m.point(_m.to_vertex_handle(_m.halfedge_handle(eit,0)));
      const typename MeshType::Point from = _m.point(_m.from_vertex_handle(_m.halfedge_handle(eit,0)));

      real_t length = (to - from).sqrnorm();

      // Only push the edges that need to be split
      if ( length > max_edge_length_squared_ )
        queue.push( queueElement(eit.handle(),length) );
    }

    bool stop = false;
    while ( !stop && ! queue.empty() ) {
      queueElement a = queue.top();
      queue.pop();

      if ( a.second < max_edge_length_squared_ ) {
        stop = true;
        break;
      } else {
        const typename MeshType::Point to   = _m.point(_m.to_vertex_handle(_m.halfedge_handle(a.first,0)));
        const typename MeshType::Point from = _m.point(_m.from_vertex_handle(_m.halfedge_handle(a.first,0)));
        const typename MeshType::Point midpoint = 0.5 * ( to + from );

        const typename MeshType::VertexHandle newVertex = _m.add_vertex(midpoint);
        _m.split(a.first,newVertex);

        for ( typename MeshType::VertexOHalfedgeIter voh_it(_m,newVertex); voh_it; ++voh_it) {
          typename MeshType::EdgeHandle eh = _m.edge_handle(voh_it.handle());
          const typename MeshType::Point to   = _m.point(_m.to_vertex_handle(voh_it));
          const typename MeshType::Point from = _m.point(_m.from_vertex_handle(voh_it));
          real_t length = (to - from).sqrnorm();

          // Only push the edges that need to be split
          if ( length > max_edge_length_squared_ )
            queue.push( queueElement(eh,length) );

        }
      }
    }

#if defined(_DEBUG) || defined(DEBUG)
      // Now we have an consistent mesh!
      assert( OpenMesh::Utils::MeshCheckerT<mesh_t>(_m).check() );
#endif

    return true;
  }

private: // data
  real_t max_edge_length_squared_;

};

} // END_NS_UNIFORM
} // END_NS_SUBDIVIDER
} // END_NS_OPENMESH
#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MABTable.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:31:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_TABLE_HXX_
#define _CONNECTIVITY_MAB_TABLE_HXX_

#ifndef _CONNECTIVITY_FILE_TABLE_HXX_
#include "file/FTable.hxx"
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif

#include <mozaddressbook/MABQuery.hxx>

#ifdef DARREN_WORK
namespace com { namespace sun { namespace star { namespace sheet {
    class XSpreadsheet;
} } } }

namespace com { namespace sun { namespace star { namespace util {
    class XNumberFormats;
} } } }

#endif /* DARREN_WORK */

namespace connectivity
{
    namespace mozaddressbook
    {
        typedef file::OFileTable OMozabTable_BASE;
        class OMozabConnection;

        typedef ::std::map< ::rtl::OUString,
                        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed>,
                        comphelper::UStringMixLess > OContainer;
        static sal_Int32 const m_nNR_OF_FIELDS = 37;

        class OMozabTable : public OMozabTable_BASE
        {
        private:
            //static sal_Int32 const m_nNR_OF_FIELDS = 37;
            const OMozabColumnAlias & m_aColumnAlias;
            OMozabQuery             *m_xQuery;
            ::std::vector<sal_Int32> m_aTypes;      // holds all type for columns just to avoid to ask the propertyset
            ::std::vector<sal_Int32> m_aPrecisions; // same as aboth
            ::std::vector<sal_Int32> m_aScales;
#ifdef DARREN_WORK
            ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > m_xSheet;
            ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats > m_xFormats;
            ::Date m_aNullDate;
#endif /* DARREN_WORK */
            ::std::vector< ::rtl::OUString> m_aAttributeStrings;

            void fillColumns();

            BOOL WriteBuffer();
            BOOL UpdateBuffer(connectivity::OValueVector& rRow, connectivity::OValueRow pOrgRow,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> isUniqueByColumnName(const ::rtl::OUString& _rColName);
            OValueRow                               m_aParameterRow;

            sal_Int32   sParamIndex;

            inline void resetParameters()
                          { sParamIndex = 0; }

            void parseParameter( const OSQLParseNode* pNode, rtl::OUString& rMatchString );

        protected:
            virtual void FileClose();

            // special ctor is needed for clone
            OMozabTable(const OMozabTable* _pTable);
        public:
            virtual void refreshColumns();
            virtual void refreshIndexes();

        public:
            //  DECLARE_CTY_DEFAULTS( OMozabTable_BASE);
            OMozabTable( sdbcx::OCollection* _pTables,OMozabConnection* _pConnection);
            OMozabTable( sdbcx::OCollection* _pTables,OMozabConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );
            ~OMozabTable( );

            virtual sal_Int32 getCurrentLastPos() const;
            virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos);
            virtual sal_Bool fetchRow(connectivity::OValueRow _rRow,const OSQLColumns& _rCols, sal_Bool _bUseTableDefs,sal_Bool bRetrieveData);

            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL disposing(void);

            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            BOOL DropImpl();
            BOOL CreateImpl();

            virtual BOOL InsertRow(connectivity::OValueVector& rRow, BOOL bFlush,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            virtual BOOL DeleteRow(const OSQLColumns& _rCols);
            virtual BOOL UpdateRow(connectivity::OValueVector& rRow, connectivity::OValueRow pOrgRow,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);

            void fillRowData( connectivity::OSQLParseTreeIterator& _aSQLIterator );

            void analyseWhereClause( const OSQLParseNode*          parseTree,
                            ::std::vector< ::rtl::OUString >       &matchItems,
                            ::std::vector< OMozabQuery::eSqlOppr > &matchOper,
                            ::std::vector< ::rtl::OUString >       &matchValues,
                            connectivity::OSQLParseTreeIterator&   aSQLIterator);

            // returns a copy of this object
            OMozabTable* clone() const;
            const OMozabColumnAlias & getColumnAlias() const
                          { return (m_aColumnAlias); }

            void setParameterRow(const OValueRow& _rParaRow)
                          { m_aParameterRow = _rParaRow; }

        };
    }
}

#endif // _CONNECTIVITY_MAB_TABLE_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.10.372); FILE MERGED 2008/04/01 15:09:16 thb 1.10.372.3: #i85898# Stripping all external header guards 2008/04/01 10:53:40 thb 1.10.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:32 rt 1.10.372.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: MABTable.hxx,v $
 * $Revision: 1.11 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_TABLE_HXX_
#define _CONNECTIVITY_MAB_TABLE_HXX_

#include "file/FTable.hxx"
#include <tools/date.hxx>

#include <mozaddressbook/MABQuery.hxx>

#ifdef DARREN_WORK
namespace com { namespace sun { namespace star { namespace sheet {
    class XSpreadsheet;
} } } }

namespace com { namespace sun { namespace star { namespace util {
    class XNumberFormats;
} } } }

#endif /* DARREN_WORK */

namespace connectivity
{
    namespace mozaddressbook
    {
        typedef file::OFileTable OMozabTable_BASE;
        class OMozabConnection;

        typedef ::std::map< ::rtl::OUString,
                        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed>,
                        comphelper::UStringMixLess > OContainer;
        static sal_Int32 const m_nNR_OF_FIELDS = 37;

        class OMozabTable : public OMozabTable_BASE
        {
        private:
            //static sal_Int32 const m_nNR_OF_FIELDS = 37;
            const OMozabColumnAlias & m_aColumnAlias;
            OMozabQuery             *m_xQuery;
            ::std::vector<sal_Int32> m_aTypes;      // holds all type for columns just to avoid to ask the propertyset
            ::std::vector<sal_Int32> m_aPrecisions; // same as aboth
            ::std::vector<sal_Int32> m_aScales;
#ifdef DARREN_WORK
            ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet > m_xSheet;
            ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats > m_xFormats;
            ::Date m_aNullDate;
#endif /* DARREN_WORK */
            ::std::vector< ::rtl::OUString> m_aAttributeStrings;

            void fillColumns();

            BOOL WriteBuffer();
            BOOL UpdateBuffer(connectivity::OValueVector& rRow, connectivity::OValueRow pOrgRow,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> isUniqueByColumnName(const ::rtl::OUString& _rColName);
            OValueRow                               m_aParameterRow;

            sal_Int32   sParamIndex;

            inline void resetParameters()
                          { sParamIndex = 0; }

            void parseParameter( const OSQLParseNode* pNode, rtl::OUString& rMatchString );

        protected:
            virtual void FileClose();

            // special ctor is needed for clone
            OMozabTable(const OMozabTable* _pTable);
        public:
            virtual void refreshColumns();
            virtual void refreshIndexes();

        public:
            //  DECLARE_CTY_DEFAULTS( OMozabTable_BASE);
            OMozabTable( sdbcx::OCollection* _pTables,OMozabConnection* _pConnection);
            OMozabTable( sdbcx::OCollection* _pTables,OMozabConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );
            ~OMozabTable( );

            virtual sal_Int32 getCurrentLastPos() const;
            virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos);
            virtual sal_Bool fetchRow(connectivity::OValueRow _rRow,const OSQLColumns& _rCols, sal_Bool _bUseTableDefs,sal_Bool bRetrieveData);

            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL disposing(void);

            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            BOOL DropImpl();
            BOOL CreateImpl();

            virtual BOOL InsertRow(connectivity::OValueVector& rRow, BOOL bFlush,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            virtual BOOL DeleteRow(const OSQLColumns& _rCols);
            virtual BOOL UpdateRow(connectivity::OValueVector& rRow, connectivity::OValueRow pOrgRow,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);

            void fillRowData( connectivity::OSQLParseTreeIterator& _aSQLIterator );

            void analyseWhereClause( const OSQLParseNode*          parseTree,
                            ::std::vector< ::rtl::OUString >       &matchItems,
                            ::std::vector< OMozabQuery::eSqlOppr > &matchOper,
                            ::std::vector< ::rtl::OUString >       &matchValues,
                            connectivity::OSQLParseTreeIterator&   aSQLIterator);

            // returns a copy of this object
            OMozabTable* clone() const;
            const OMozabColumnAlias & getColumnAlias() const
                          { return (m_aColumnAlias); }

            void setParameterRow(const OValueRow& _rParaRow)
                          { m_aParameterRow = _rParaRow; }

        };
    }
}

#endif // _CONNECTIVITY_MAB_TABLE_HXX_

<|endoftext|>


<commit_before>/**
 * @file cmiss_optimisation_private.cpp
 *
 * The Cmiss_optimisation object.
 *
 * @see-also api/zinc/optimisation.h
 *
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include <cstdio>
	#include "zinc/field.h"
	#include "zinc/region.h"
	#include "computed_field/computed_field.h"
	#include "computed_field/computed_field_composite.h"
	#include "computed_field/computed_field_finite_element.h"
	#include "general/mystring.h"
	#include "general/debug.h"
#include "general/enumerator_conversion.hpp"
#include "minimise/cmiss_optimisation_private.hpp"
#include "minimise/optimisation.hpp"

char *Cmiss_optimisation::getSolutionReport()
{
	std::string temp = solution_report.str();
	return duplicate_string(temp.c_str());
}

int Cmiss_optimisation::runOptimisation()
{
	int return_code = 1;
	solution_report.str("");
	// check required attributes are set
	if (method == CMISS_OPTIMISATION_METHOD_INVALID)
	{
		display_message(ERROR_MESSAGE, "Cmiss_optimisation_optimise.  Optimisation method invalid or not set.");
		return_code = 0;
	}
	if (independentFields.size() < 1)
	{
		display_message(ERROR_MESSAGE, "Cmiss_optimisation_optimise.  Must set at least one independent field.");
		return_code = 0;
	}
	if (objectiveFields.size() < 1)
	{
		display_message(ERROR_MESSAGE, "Cmiss_optimisation_optimise.  Must set at least one objective field.");
		return_code = 0;
	}
	if (return_code)
	{
		Minimisation minimisation(*this);
		return_code = return_code && minimisation.prepareOptimisation();
		return_code = return_code && minimisation.runOptimisation();
	}
	return return_code;
}

Cmiss_optimisation_id Cmiss_field_module_create_optimisation(Cmiss_field_module_id field_module)
{
	if (field_module)
		return new Cmiss_optimisation(field_module);
	return 0;
}

Cmiss_optimisation_id Cmiss_optimisation_access(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		optimisation->access();

	return 0;
}

int Cmiss_optimisation_destroy(Cmiss_optimisation_id *optimisation_address)
{
	if (optimisation_address)
		return Cmiss_optimisation::deaccess(*optimisation_address);
	return 0;
}

enum Cmiss_optimisation_method Cmiss_optimisation_get_method(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->method;
	return CMISS_OPTIMISATION_METHOD_INVALID;
}

int Cmiss_optimisation_set_method(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_method method)
{
	if (optimisation && (
		(method == CMISS_OPTIMISATION_METHOD_QUASI_NEWTON) ||
		(method == CMISS_OPTIMISATION_METHOD_LEAST_SQUARES_QUASI_NEWTON)))
	{
		optimisation->method = method;
		return 1;
	}
	return 0;
}

class Cmiss_optimisation_method_conversion
{
public:
    static const char *to_string(enum Cmiss_optimisation_method method)
    {
    	const char *enum_string = 0;
    	switch (method)
    	{
    		case CMISS_OPTIMISATION_METHOD_QUASI_NEWTON:
    			enum_string = "QUASI_NEWTON";
    			break;
    		case CMISS_OPTIMISATION_METHOD_LEAST_SQUARES_QUASI_NEWTON:
    			enum_string = "LEAST_SQUARES_QUASI_NEWTON";
    			break;
    		default:
    			break;
    	}
    	return enum_string;
    }
};

enum Cmiss_optimisation_method
	Cmiss_optimisation_method_enum_from_string(const char *string)
{
	return string_to_enum<enum Cmiss_optimisation_method,
	Cmiss_optimisation_method_conversion>(string);
}

char *Cmiss_optimisation_method_enum_to_string(
	enum Cmiss_optimisation_method method)
{
	const char *method_string = Cmiss_optimisation_method_conversion::to_string(method);
	return (method_string ? duplicate_string(method_string) : 0);
}

int Cmiss_optimisation_get_attribute_integer(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute)
{
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_ITERATIONS:
			return optimisation->maximumIterations;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_FUNCTION_EVALUATIONS:
			return optimisation->maximumNumberFunctionEvaluations;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_BACKTRACK_ITERATIONS:
			return optimisation->maximumBacktrackIterations;
			break;
		default:
			break;
		}
	}
	return 0;
}

int Cmiss_optimisation_set_attribute_integer(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute, int value)
{
	int return_code = 1;
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_ITERATIONS:
			optimisation->maximumIterations = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_FUNCTION_EVALUATIONS:
			optimisation->maximumNumberFunctionEvaluations = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_BACKTRACK_ITERATIONS:
			optimisation->maximumBacktrackIterations = value;
			break;
		default:
			return_code = 0;
			break;
		}
	}
	return return_code;
}

double Cmiss_optimisation_get_attribute_real(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute)
{
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_FUNCTION_TOLERANCE:
			return optimisation->functionTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_GRADIENT_TOLERANCE:
			return optimisation->gradientTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_STEP_TOLERANCE:
			return optimisation->stepTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_STEP:
			return optimisation->maximumStep;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MINIMUM_STEP:
			return optimisation->minimumStep;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_LINESEARCH_TOLERANCE:
			return optimisation->linesearchTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_TRUST_REGION_SIZE:
			return optimisation->trustRegionSize;
			break;
		default:
			break;
		}
	}
	return 0.0;
}

int Cmiss_optimisation_set_attribute_real(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute, double value)
{
	int return_code = 1;
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_FUNCTION_TOLERANCE:
			optimisation->functionTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_GRADIENT_TOLERANCE:
			optimisation->gradientTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_STEP_TOLERANCE:
			optimisation->stepTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_STEP:
			optimisation->maximumStep = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MINIMUM_STEP:
			optimisation->minimumStep = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_LINESEARCH_TOLERANCE:
			optimisation->linesearchTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_TRUST_REGION_SIZE:
			optimisation->trustRegionSize = value;
			break;
		default:
			return_code = 0;
			break;
		}
	}
	return return_code;
}

class Cmiss_optimisation_attribute_conversion
{
public:
    static const char *to_string(enum Cmiss_optimisation_attribute attribute)
    {
        const char *enum_string = 0;
        switch (attribute)
        {
        	case CMISS_OPTIMISATION_ATTRIBUTE_FUNCTION_TOLERANCE:
        		enum_string = "FUNCTION_TOLERANCE";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_GRADIENT_TOLERANCE:
        		enum_string = "GRADIENT_TOLERANCE";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_STEP_TOLERANCE:
        		enum_string = "STEP_TOLERANCE";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_ITERATIONS:
        		enum_string = "MAXIMUM_ITERATIONS";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_FUNCTION_EVALUATIONS:
        		enum_string = "MAXIMUM_FUNCTION_EVALUATIONS";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_STEP:
        		enum_string = "MAXIMUM_STEP";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_MINIMUM_STEP:
        		enum_string = "MINIMUM_STEP";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_LINESEARCH_TOLERANCE:
        		enum_string = "LINESEARCH_TOLERANCE";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_BACKTRACK_ITERATIONS:
        		enum_string = "MAXIMUM_BACKTRACK_ITERATIONS";
        		break;
        	case CMISS_OPTIMISATION_ATTRIBUTE_TRUST_REGION_SIZE:
        		enum_string = "TRUST_REGION_SIZE";
        		break;
        	default:
        		break;
        }
        return enum_string;
    }
};

enum Cmiss_optimisation_attribute Cmiss_optimisation_attribute_enum_from_string(
	const char *string)
{
	return string_to_enum<enum Cmiss_optimisation_attribute,
	Cmiss_optimisation_attribute_conversion>(string);
}

char *Cmiss_optimisation_attribute_enum_to_string(
	enum Cmiss_optimisation_attribute attribute)
{
	const char *attribute_string = Cmiss_optimisation_attribute_conversion::to_string(attribute);
	return (attribute_string ? duplicate_string(attribute_string) : 0);
}

Cmiss_field_id Cmiss_optimisation_get_first_independent_field(
	Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->getFirstIndependentField();
	return 0;
}

Cmiss_field_id Cmiss_optimisation_get_next_independent_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id ref_field)
{
	if (optimisation && ref_field)
		return optimisation->getNextIndependentField(ref_field);
	return 0;
}

int Cmiss_optimisation_add_independent_field(Cmiss_optimisation_id optimisation,
	Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->addIndependentField(field);
	return 0;
}

int Cmiss_optimisation_remove_independent_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->removeIndependentField(field);
	return 0;
}

Cmiss_field_id Cmiss_optimisation_get_first_objective_field(
	Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->getFirstObjectiveField();
	return 0;
}

Cmiss_field_id Cmiss_optimisation_get_next_objective_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id ref_field)
{
	if (optimisation && ref_field)
		return optimisation->getNextObjectiveField(ref_field);
	return 0;
}

int Cmiss_optimisation_add_objective_field(Cmiss_optimisation_id optimisation,
	Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->addObjectiveField(field);
	return 0;
}

int Cmiss_optimisation_remove_objective_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->removeObjectiveField(field);
	return 0;
}

char *Cmiss_optimisation_get_solution_report(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->getSolutionReport();
	return 0;
}

int Cmiss_optimisation_optimise(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->runOptimisation();
	return 0;
}
<commit_msg>Fixing bug in accessing of optimisation object.  https://tracker.physiomeproject.org/show_bug.cgi?id=3260<commit_after>/**
 * @file cmiss_optimisation_private.cpp
 *
 * The Cmiss_optimisation object.
 *
 * @see-also api/zinc/optimisation.h
 *
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include <cstdio>
	#include "zinc/field.h"
	#include "zinc/region.h"
	#include "computed_field/computed_field.h"
	#include "computed_field/computed_field_composite.h"
	#include "computed_field/computed_field_finite_element.h"
	#include "general/mystring.h"
	#include "general/debug.h"
#include "general/enumerator_conversion.hpp"
#include "minimise/cmiss_optimisation_private.hpp"
#include "minimise/optimisation.hpp"

char *Cmiss_optimisation::getSolutionReport()
{
	std::string temp = solution_report.str();
	return duplicate_string(temp.c_str());
}

int Cmiss_optimisation::runOptimisation()
{
	int return_code = 1;
	solution_report.str("");
	// check required attributes are set
	if (method == CMISS_OPTIMISATION_METHOD_INVALID)
	{
		display_message(ERROR_MESSAGE, "Cmiss_optimisation_optimise.  Optimisation method invalid or not set.");
		return_code = 0;
	}
	if (independentFields.size() < 1)
	{
		display_message(ERROR_MESSAGE, "Cmiss_optimisation_optimise.  Must set at least one independent field.");
		return_code = 0;
	}
	if (objectiveFields.size() < 1)
	{
		display_message(ERROR_MESSAGE, "Cmiss_optimisation_optimise.  Must set at least one objective field.");
		return_code = 0;
	}
	if (return_code)
	{
		Minimisation minimisation(*this);
		return_code = return_code && minimisation.prepareOptimisation();
		return_code = return_code && minimisation.runOptimisation();
	}
	return return_code;
}

Cmiss_optimisation_id Cmiss_field_module_create_optimisation(Cmiss_field_module_id field_module)
{
	if (field_module)
		return new Cmiss_optimisation(field_module);
	return 0;
}

Cmiss_optimisation_id Cmiss_optimisation_access(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->access();

	return 0;
}

int Cmiss_optimisation_destroy(Cmiss_optimisation_id *optimisation_address)
{
	if (optimisation_address)
		return Cmiss_optimisation::deaccess(*optimisation_address);
	return 0;
}

enum Cmiss_optimisation_method Cmiss_optimisation_get_method(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->method;
	return CMISS_OPTIMISATION_METHOD_INVALID;
}

int Cmiss_optimisation_set_method(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_method method)
{
	if (optimisation && (
		(method == CMISS_OPTIMISATION_METHOD_QUASI_NEWTON) ||
		(method == CMISS_OPTIMISATION_METHOD_LEAST_SQUARES_QUASI_NEWTON)))
	{
		optimisation->method = method;
		return 1;
	}
	return 0;
}

class Cmiss_optimisation_method_conversion
{
public:
	static const char *to_string(enum Cmiss_optimisation_method method)
	{
		const char *enum_string = 0;
		switch (method)
		{
			case CMISS_OPTIMISATION_METHOD_QUASI_NEWTON:
				enum_string = "QUASI_NEWTON";
				break;
			case CMISS_OPTIMISATION_METHOD_LEAST_SQUARES_QUASI_NEWTON:
				enum_string = "LEAST_SQUARES_QUASI_NEWTON";
				break;
			default:
				break;
		}
		return enum_string;
	}
};

enum Cmiss_optimisation_method
	Cmiss_optimisation_method_enum_from_string(const char *string)
{
	return string_to_enum<enum Cmiss_optimisation_method,
	Cmiss_optimisation_method_conversion>(string);
}

char *Cmiss_optimisation_method_enum_to_string(
	enum Cmiss_optimisation_method method)
{
	const char *method_string = Cmiss_optimisation_method_conversion::to_string(method);
	return (method_string ? duplicate_string(method_string) : 0);
}

int Cmiss_optimisation_get_attribute_integer(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute)
{
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_ITERATIONS:
			return optimisation->maximumIterations;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_FUNCTION_EVALUATIONS:
			return optimisation->maximumNumberFunctionEvaluations;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_BACKTRACK_ITERATIONS:
			return optimisation->maximumBacktrackIterations;
			break;
		default:
			break;
		}
	}
	return 0;
}

int Cmiss_optimisation_set_attribute_integer(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute, int value)
{
	int return_code = 1;
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_ITERATIONS:
			optimisation->maximumIterations = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_FUNCTION_EVALUATIONS:
			optimisation->maximumNumberFunctionEvaluations = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_BACKTRACK_ITERATIONS:
			optimisation->maximumBacktrackIterations = value;
			break;
		default:
			return_code = 0;
			break;
		}
	}
	return return_code;
}

double Cmiss_optimisation_get_attribute_real(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute)
{
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_FUNCTION_TOLERANCE:
			return optimisation->functionTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_GRADIENT_TOLERANCE:
			return optimisation->gradientTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_STEP_TOLERANCE:
			return optimisation->stepTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_STEP:
			return optimisation->maximumStep;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MINIMUM_STEP:
			return optimisation->minimumStep;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_LINESEARCH_TOLERANCE:
			return optimisation->linesearchTolerance;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_TRUST_REGION_SIZE:
			return optimisation->trustRegionSize;
			break;
		default:
			break;
		}
	}
	return 0.0;
}

int Cmiss_optimisation_set_attribute_real(Cmiss_optimisation_id optimisation,
		enum Cmiss_optimisation_attribute attribute, double value)
{
	int return_code = 1;
	if (optimisation)
	{
		switch (attribute)
		{
		case CMISS_OPTIMISATION_ATTRIBUTE_FUNCTION_TOLERANCE:
			optimisation->functionTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_GRADIENT_TOLERANCE:
			optimisation->gradientTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_STEP_TOLERANCE:
			optimisation->stepTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_STEP:
			optimisation->maximumStep = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_MINIMUM_STEP:
			optimisation->minimumStep = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_LINESEARCH_TOLERANCE:
			optimisation->linesearchTolerance = value;
			break;
		case CMISS_OPTIMISATION_ATTRIBUTE_TRUST_REGION_SIZE:
			optimisation->trustRegionSize = value;
			break;
		default:
			return_code = 0;
			break;
		}
	}
	return return_code;
}

class Cmiss_optimisation_attribute_conversion
{
public:
	static const char *to_string(enum Cmiss_optimisation_attribute attribute)
	{
		const char *enum_string = 0;
		switch (attribute)
		{
			case CMISS_OPTIMISATION_ATTRIBUTE_FUNCTION_TOLERANCE:
				enum_string = "FUNCTION_TOLERANCE";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_GRADIENT_TOLERANCE:
				enum_string = "GRADIENT_TOLERANCE";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_STEP_TOLERANCE:
				enum_string = "STEP_TOLERANCE";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_ITERATIONS:
				enum_string = "MAXIMUM_ITERATIONS";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_FUNCTION_EVALUATIONS:
				enum_string = "MAXIMUM_FUNCTION_EVALUATIONS";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_STEP:
				enum_string = "MAXIMUM_STEP";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_MINIMUM_STEP:
				enum_string = "MINIMUM_STEP";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_LINESEARCH_TOLERANCE:
				enum_string = "LINESEARCH_TOLERANCE";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_MAXIMUM_BACKTRACK_ITERATIONS:
				enum_string = "MAXIMUM_BACKTRACK_ITERATIONS";
				break;
			case CMISS_OPTIMISATION_ATTRIBUTE_TRUST_REGION_SIZE:
				enum_string = "TRUST_REGION_SIZE";
				break;
			default:
				break;
		}
		return enum_string;
	}
};

enum Cmiss_optimisation_attribute Cmiss_optimisation_attribute_enum_from_string(
	const char *string)
{
	return string_to_enum<enum Cmiss_optimisation_attribute,
	Cmiss_optimisation_attribute_conversion>(string);
}

char *Cmiss_optimisation_attribute_enum_to_string(
	enum Cmiss_optimisation_attribute attribute)
{
	const char *attribute_string = Cmiss_optimisation_attribute_conversion::to_string(attribute);
	return (attribute_string ? duplicate_string(attribute_string) : 0);
}

Cmiss_field_id Cmiss_optimisation_get_first_independent_field(
	Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->getFirstIndependentField();
	return 0;
}

Cmiss_field_id Cmiss_optimisation_get_next_independent_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id ref_field)
{
	if (optimisation && ref_field)
		return optimisation->getNextIndependentField(ref_field);
	return 0;
}

int Cmiss_optimisation_add_independent_field(Cmiss_optimisation_id optimisation,
	Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->addIndependentField(field);
	return 0;
}

int Cmiss_optimisation_remove_independent_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->removeIndependentField(field);
	return 0;
}

Cmiss_field_id Cmiss_optimisation_get_first_objective_field(
	Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->getFirstObjectiveField();
	return 0;
}

Cmiss_field_id Cmiss_optimisation_get_next_objective_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id ref_field)
{
	if (optimisation && ref_field)
		return optimisation->getNextObjectiveField(ref_field);
	return 0;
}

int Cmiss_optimisation_add_objective_field(Cmiss_optimisation_id optimisation,
	Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->addObjectiveField(field);
	return 0;
}

int Cmiss_optimisation_remove_objective_field(
	Cmiss_optimisation_id optimisation, Cmiss_field_id field)
{
	if (optimisation && field)
		return optimisation->removeObjectiveField(field);
	return 0;
}

char *Cmiss_optimisation_get_solution_report(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->getSolutionReport();
	return 0;
}

int Cmiss_optimisation_optimise(Cmiss_optimisation_id optimisation)
{
	if (optimisation)
		return optimisation->runOptimisation();
	return 0;
}
<|endoftext|>


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

#include <gtest/gtest.h>

#include "arrow/chunked_array.h"
#include "arrow/compute/api.h"
#include "arrow/compute/kernels/test_util.h"
#include "arrow/result.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/util/checked_cast.h"

namespace arrow {
namespace compute {

using arrow::internal::checked_cast;

TEST(TestVectorNested, ListFlatten) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input = ArrayFromJSON(ty, "[[0, null, 1], null, [2, 3], []]");
    auto expected = ArrayFromJSON(int16(), "[0, null, 1, 2, 3]");
    CheckVectorUnary("list_flatten", input, expected);

    // Construct a list with a non-empty null slot
    TweakValidityBit(input, 0, false);
    expected = ArrayFromJSON(int16(), "[2, 3]");
    CheckVectorUnary("list_flatten", input, expected);
  }
}

TEST(TestVectorNested, ListFlattenChunkedArray) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input = ChunkedArrayFromJSON(ty, {"[[0, null, 1], null]", "[[2, 3], []]"});
    auto expected = ChunkedArrayFromJSON(int16(), {"[0, null, 1]", "[2, 3]"});
    CheckVectorUnary("list_flatten", input, expected);

    input = ChunkedArrayFromJSON(ty, {});
    expected = ChunkedArrayFromJSON(int16(), {});
    CheckVectorUnary("list_flatten", input, expected);
  }
}

TEST(TestVectorNested, ListFlattenFixedSizeList) {
  for (auto ty : {fixed_size_list(int16(), 2), fixed_size_list(uint32(), 2)}) {
    const auto& out_ty = checked_cast<const FixedSizeListType&>(*ty).value_type();
    {
      auto input = ArrayFromJSON(ty, "[[0, null], null, [2, 3], [0, 42]]");
      auto expected = ArrayFromJSON(out_ty, "[0, null, 2, 3, 0, 42]");
      CheckVectorUnary("list_flatten", input, expected);
    }

    {
      // Test a chunked array
      auto input = ChunkedArrayFromJSON(ty, {"[[0, null], null]", "[[2, 3], [0, 42]]"});
      auto expected = ChunkedArrayFromJSON(out_ty, {"[0, null]", "[2, 3, 0, 42]"});
      CheckVectorUnary("list_flatten", input, expected);

      input = ChunkedArrayFromJSON(ty, {});
      expected = ChunkedArrayFromJSON(out_ty, {});
      CheckVectorUnary("list_flatten", input, expected);
    }
  }
}

TEST(TestVectorNested, ListParentIndices) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input = ArrayFromJSON(ty, "[[0, null, 1], null, [2, 3], [], [4, 5]]");

    auto expected = ArrayFromJSON(int64(), "[0, 0, 0, 2, 2, 4, 4]");
    CheckVectorUnary("list_parent_indices", input, expected);
  }

  // Construct a list with a non-empty null slot
  auto input = ArrayFromJSON(list(int16()), "[[0, null, 1], [0, 0], [2, 3], [], [4, 5]]");
  TweakValidityBit(input, 1, false);
  auto expected = ArrayFromJSON(int64(), "[0, 0, 0, 1, 1, 2, 2, 4, 4]");
  CheckVectorUnary("list_parent_indices", input, expected);
}

TEST(TestVectorNested, ListParentIndicesChunkedArray) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input =
        ChunkedArrayFromJSON(ty, {"[[0, null, 1], null]", "[[2, 3], [], [4, 5]]"});

    auto expected = ChunkedArrayFromJSON(int64(), {"[0, 0, 0]", "[2, 2, 4, 4]"});
    CheckVectorUnary("list_parent_indices", input, expected);

    input = ChunkedArrayFromJSON(ty, {});
    expected = ChunkedArrayFromJSON(int64(), {});
    CheckVectorUnary("list_parent_indices", input, expected);
  }
}

TEST(TestVectorNested, ListParentIndicesFixedSizeList) {
  for (auto ty : {fixed_size_list(int16(), 2), fixed_size_list(uint32(), 2)}) {
    {
      auto input = ArrayFromJSON(ty, "[[0, null], null, [1, 2], [3, 4], [null, 5]]");
      auto expected = ArrayFromJSON(int64(), "[0, 0, 2, 2, 3, 3, 4, 4]");
      CheckVectorUnary("list_parent_indices", input, expected);
    }
    {
      // Test a chunked array
      auto input =
          ChunkedArrayFromJSON(ty, {"[[0, null], null, [1, 2]]", "[[3, 4], [null, 5]]"});
      auto expected = ChunkedArrayFromJSON(int64(), {"[0, 0, 2, 2]", "[3, 3, 4, 4]"});
      CheckVectorUnary("list_parent_indices", input, expected);

      input = ChunkedArrayFromJSON(ty, {});
      expected = ChunkedArrayFromJSON(int64(), {});
      CheckVectorUnary("list_parent_indices", input, expected);
    }
  }
}

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

#include <gtest/gtest.h>

#include "arrow/chunked_array.h"
#include "arrow/compute/api.h"
#include "arrow/compute/kernels/test_util.h"
#include "arrow/result.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/util/checked_cast.h"

namespace arrow {
namespace compute {

using arrow::internal::checked_cast;

TEST(TestVectorNested, ListFlatten) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input = ArrayFromJSON(ty, "[[0, null, 1], null, [2, 3], []]");
    auto expected = ArrayFromJSON(int16(), "[0, null, 1, 2, 3]");
    CheckVectorUnary("list_flatten", input, expected);

    // Construct a list with a non-empty null slot
    auto tweaked = TweakValidityBit(input, 0, false);
    expected = ArrayFromJSON(int16(), "[2, 3]");
    CheckVectorUnary("list_flatten", tweaked, expected);
  }
}

TEST(TestVectorNested, ListFlattenChunkedArray) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input = ChunkedArrayFromJSON(ty, {"[[0, null, 1], null]", "[[2, 3], []]"});
    auto expected = ChunkedArrayFromJSON(int16(), {"[0, null, 1]", "[2, 3]"});
    CheckVectorUnary("list_flatten", input, expected);

    input = ChunkedArrayFromJSON(ty, {});
    expected = ChunkedArrayFromJSON(int16(), {});
    CheckVectorUnary("list_flatten", input, expected);
  }
}

TEST(TestVectorNested, ListFlattenFixedSizeList) {
  for (auto ty : {fixed_size_list(int16(), 2), fixed_size_list(uint32(), 2)}) {
    const auto& out_ty = checked_cast<const FixedSizeListType&>(*ty).value_type();
    {
      auto input = ArrayFromJSON(ty, "[[0, null], null, [2, 3], [0, 42]]");
      auto expected = ArrayFromJSON(out_ty, "[0, null, 2, 3, 0, 42]");
      CheckVectorUnary("list_flatten", input, expected);
    }

    {
      // Test a chunked array
      auto input = ChunkedArrayFromJSON(ty, {"[[0, null], null]", "[[2, 3], [0, 42]]"});
      auto expected = ChunkedArrayFromJSON(out_ty, {"[0, null]", "[2, 3, 0, 42]"});
      CheckVectorUnary("list_flatten", input, expected);

      input = ChunkedArrayFromJSON(ty, {});
      expected = ChunkedArrayFromJSON(out_ty, {});
      CheckVectorUnary("list_flatten", input, expected);
    }
  }
}

TEST(TestVectorNested, ListParentIndices) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input = ArrayFromJSON(ty, "[[0, null, 1], null, [2, 3], [], [4, 5]]");

    auto expected = ArrayFromJSON(int64(), "[0, 0, 0, 2, 2, 4, 4]");
    CheckVectorUnary("list_parent_indices", input, expected);
  }

  // Construct a list with a non-empty null slot
  auto input = ArrayFromJSON(list(int16()), "[[0, null, 1], [0, 0], [2, 3], [], [4, 5]]");
  auto tweaked = TweakValidityBit(input, 1, false);
  auto expected = ArrayFromJSON(int64(), "[0, 0, 0, 1, 1, 2, 2, 4, 4]");
  CheckVectorUnary("list_parent_indices", tweaked, expected);
}

TEST(TestVectorNested, ListParentIndicesChunkedArray) {
  for (auto ty : {list(int16()), large_list(int16())}) {
    auto input =
        ChunkedArrayFromJSON(ty, {"[[0, null, 1], null]", "[[2, 3], [], [4, 5]]"});

    auto expected = ChunkedArrayFromJSON(int64(), {"[0, 0, 0]", "[2, 2, 4, 4]"});
    CheckVectorUnary("list_parent_indices", input, expected);

    input = ChunkedArrayFromJSON(ty, {});
    expected = ChunkedArrayFromJSON(int64(), {});
    CheckVectorUnary("list_parent_indices", input, expected);
  }
}

TEST(TestVectorNested, ListParentIndicesFixedSizeList) {
  for (auto ty : {fixed_size_list(int16(), 2), fixed_size_list(uint32(), 2)}) {
    {
      auto input = ArrayFromJSON(ty, "[[0, null], null, [1, 2], [3, 4], [null, 5]]");
      auto expected = ArrayFromJSON(int64(), "[0, 0, 2, 2, 3, 3, 4, 4]");
      CheckVectorUnary("list_parent_indices", input, expected);
    }
    {
      // Test a chunked array
      auto input =
          ChunkedArrayFromJSON(ty, {"[[0, null], null, [1, 2]]", "[[3, 4], [null, 5]]"});
      auto expected = ChunkedArrayFromJSON(int64(), {"[0, 0, 2, 2]", "[3, 3, 4, 4]"});
      CheckVectorUnary("list_parent_indices", input, expected);

      input = ChunkedArrayFromJSON(ty, {});
      expected = ChunkedArrayFromJSON(int64(), {});
      CheckVectorUnary("list_parent_indices", input, expected);
    }
  }
}

}  // namespace compute
}  // namespace arrow
<|endoftext|>