<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "version.h"

#include <string>

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef BUILD_SUFFIX
#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#    elif defined(GIT_COMMIT_ID)
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Remove -beta suffix<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "version.h"

#include <string>

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef BUILD_SUFFIX
#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#    elif defined(GIT_COMMIT_ID)
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>#include <libcryptosec/certificate/CertificateBuilder.h>
#include <fstream>
#include "gtest.h"
#include <iostream>

class EncodingTest : public ::testing::Test {
protected:
    virtual void SetUp() {
        cbuilder = new CertificateBuilder();
        before = X509_NAME_new();
        after = X509_NAME_new();
    }

    virtual void TearDown() {
        delete cbuilder;
        X509_NAME_free(before);
        X509_NAME_free(after);
    }

    /*!
     * @brief Adiciona uma entrada de um X509_NAME com a codificação desejada.
     *
     * @param name Ponteiro para o X509_NAME.
     * @param entry Entrada a ser adicionada.
     * @param encoding Codificação desejada.
     */
    void insertEntry(X509_NAME* name, const char* entry, int encoding) {
        if (entry == LN_countryName) {
            X509_NAME_add_entry_by_txt(name, entry , V_ASN1_PRINTABLESTRING, (const unsigned char*)"CO", -1, -1, 0);
        }
        else {
            X509_NAME_add_entry_by_txt(name, entry , encoding, (const unsigned char*)entry, -1, -1, 0);
        }
    }

    /*!
     * @brief Adiciona as entradas DN de um X509_NAME com a codificação desejada.
     *
     * @param name Ponteiro para o X509_NAME.
     * @param encoding Codificação desejada.
     */
    void fillEntries(X509_NAME* name, int encoding) {
        insertEntry(name, LN_countryName, encoding);
        insertEntry(name, LN_stateOrProvinceName, encoding);
        insertEntry(name, LN_localityName, encoding);
        insertEntry(name, LN_organizationName, encoding);
        insertEntry(name, LN_organizationalUnitName, encoding);
        insertEntry(name, LN_commonName, encoding);
        insertEntry(name, LN_userId, encoding);
    }

    /*!
     * @brief Aplica um caso de teste com uma entrada preenchida com a codificação desejada e as restantes com a
     *        codificação padrão da versão OpenSSL.
     *
     * @param entry Entrada
     * @param encoding Codificação desejada.
     *
     * @return true se o caso de teste estiver correto, falso caso contrário.
     */
    bool applyOne(const char* entry, int encoding) {
        // create certificate:
        insertEntry(before, LN_commonName, encoding);    // common name é compulsório
        if (entry != LN_commonName) {
            insertEntry(before, entry, encoding);    // insere a entrada se não for common name
        }
        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));

        // fill entries and apply alterSubject:
        fillEntries(before, MBSTRING_ASC);
        RDNSequence rdn(X509_NAME_dup(before));
        cbuilder->alterSubject(rdn);
        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));

        return test();
    }

    /*!
     * @brief Aplica um caso de teste com todas as entradas preenchidas com a codificação desejada.
     *
     * @param encoding Codificação desejada.
     *
     * @return true se o caso de teste estiver correto, falso caso contrário.
     */
    bool applyAll(int encoding) {
        // create certificate:
        fillEntries(before, encoding);
        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));

        // apply alterSubject:
        RDNSequence rdn(X509_NAME_dup(before));
        cbuilder->alterSubject(rdn);
        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));

        return test();
    }

    /*!
     * @brief Testa se a codificação das entradas estão de acordo com o esperado.
     *
     * Testa se a codificação das entradas no certificado gerado estão de acordo com a primeira entrada commonName que é
     * obrigatória na geração da requisição.
     */
    bool test() {
        int encodingCommonName = X509_NAME_get_entry(before, 0)->value->type;
        for (int i = 0; i < X509_NAME_entry_count(after); i++) {
            int encodingAfter = X509_NAME_get_entry(after, i)->value->type;
            if (encodingAfter != encodingCommonName) {
                return false;
            }
        }
        return true;
    }

    CertificateBuilder* cbuilder;  //!< CertificateBuilder usado para aplicar a função testada.
    X509_NAME* before;  //!< Ponteiro para o X509_NAME antes de aplicar a função testada.
    X509_NAME* after;  //!< Ponteiro para o X509_NAME depois de aplicar a função testada.
};

/*!
 * @brief Teste usando todas as entradas preenchidas com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos são preenchidos na geração do certificado. Na versão utilizada do OpenSSL, essa
 * codificação é equivalente a V_ASN1_UTF8STRING.
 */
 TEST_F(EncodingTest, MBStringFilled) {
     ASSERT_TRUE(applyAll(MBSTRING_ASC));
 }

/*!
 * @brief Teste usando todas as entradas preenchidas com codificação V_ASN1_PRINTABLESTRING.
 *
 * Simula a situação onde os campos são preenchidos na geração da requisição, devendo manter sua codificação no
 * certificado gerado.
 */
TEST_F(EncodingTest, PrintableFilled) {
    ASSERT_TRUE(applyAll(V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando as entradas commonName e countryName preenchidas com codificação V_ASN1_PRINTABLESTRING e as
 *        restantes com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos Common Name e Country Name são preenchidos na geração da requisição e os restantes
 * são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.
 */
TEST_F(EncodingTest, PrintablecountryName) {
    ASSERT_TRUE(applyOne(LN_countryName, V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando as entradas commonName e stateOrProvinceName preenchidas com codificação V_ASN1_PRINTABLESTRING e
 *        as restantes com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos Common Name e State or Province Name são preenchidos na geração da requisição e os
 * restantes são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na
 * requisição.
 */
TEST_F(EncodingTest, PrintableState) {
    ASSERT_TRUE(applyOne(LN_stateOrProvinceName, V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando as entradas commonName e localityName preenchidas com codificação V_ASN1_PRINTABLESTRING e as
 *        restantes com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos Common Name e Locality Name são preenchidos na geração da requisição e os restantes
 * são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.
 */
TEST_F(EncodingTest, PrintableLocality) {
    ASSERT_TRUE(applyOne(LN_localityName, V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando as entradas commonName e organizationName preenchidas com codificação V_ASN1_PRINTABLESTRING e as
 *        restantes com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos Common Name e Organization Name são preenchidos na geração da requisição e os
 * restantes são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na
 * requisição.
 */
TEST_F(EncodingTest, PrintableOrganization) {
    ASSERT_TRUE(applyOne(LN_organizationName, V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando as entradas commonName e organizationalUnitName preenchidas com codificação
 *        V_ASN1_PRINTABLESTRING e as restantes com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos Common Name e Organizational Unit Name são preenchidos na geração da requisição e os
 * restantes são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na
 * requisição.
 */
TEST_F(EncodingTest, PrintableOrganizationalUnit) {
    ASSERT_TRUE(applyOne(LN_organizationalUnitName, V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando a entrada commonName preenchida com codificação V_ASN1_PRINTABLESTRING e asrestantes com
 *        codificação MBSTRING_ASC.
 *
 * Simula a situação onde apenas o campo Common Name é preenchido na geração da requisição e os restantes são
 * adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.
 */
TEST_F(EncodingTest, PrintableCommonName) {
    ASSERT_TRUE(applyOne(LN_commonName, V_ASN1_PRINTABLESTRING));
}

/*!
 * @brief Teste usando as entradas commonName e userId preenchidas com codificação V_ASN1_PRINTABLESTRING e as
 *        restantes com codificação MBSTRING_ASC.
 *
 * Simula a situação onde os campos Common Name e User ID são preenchidos na geração da requisição e os restantes são
 * adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.
 */
TEST_F(EncodingTest, PrintableUserID) {
    ASSERT_TRUE(applyOne(LN_userId, V_ASN1_PRINTABLESTRING));
}
<commit_msg>Change tests to use a requisition<commit_after>#include <libcryptosec/certificate/CertificateBuilder.h>
#include <fstream>
#include "gtest.h"
#include <iostream>
#include <sstream>

using std::endl;

class EncodingTest : public ::testing::Test {
protected:
    virtual void SetUp() {
        cbuilder = new CertificateBuilder();
        req = CertificateRequest();
        before = X509_NAME_new();
        after = X509_NAME_new();

        initialization();
    }

    virtual void TearDown() {
        delete cbuilder;
        X509_NAME_free(before);
        X509_NAME_free(after);
    }

    void initialization() {
        entry_fields.insert(std::make_pair<int, const char*>(NID_countryName, LN_countryName));
        entry_fields.insert(std::make_pair<int, const char*>(NID_stateOrProvinceName, LN_stateOrProvinceName));
        entry_fields.insert(std::make_pair<int, const char*>(NID_localityName, LN_localityName));
        entry_fields.insert(std::make_pair<int, const char*>(NID_organizationName, LN_organizationName));
        entry_fields.insert(std::make_pair<int, const char*>(NID_organizationalUnitName, LN_organizationalUnitName));
        entry_fields.insert(std::make_pair<int, const char*>(NID_commonName, LN_commonName));
        entry_fields.insert(std::make_pair<int, const char*>(NID_userId, LN_userId));
        std::stringstream stream;
        stream << 	"some pem encoded";
        req_pem_encoded = stream.str();
        req = CertificateRequest(req_pem_encoded);
//		cbuilder = new CertificateBuilder(req);
    }

    /*!
     * @brief Adiciona uma entrada de um X509_NAME com a codificaÃ§Ã£o desejada.
     *
     * @param name Ponteiro para o X509_NAME.
     * @param entry Entrada a ser adicionada.
     * @param encoding CodificaÃ§Ã£o desejada.
     */
    void addNameEntry(X509_NAME* name, const char* entry, int encoding, int NID) {
        X509_NAME_ENTRY *new_entry = X509_NAME_ENTRY_new();
        if (NID == NID_countryName) {
            X509_NAME_ENTRY_create_by_NID(&new_entry, NID, V_ASN1_PRINTABLESTRING, (unsigned char*)entry, strlen(entry));
            X509_NAME_add_entry(name, new_entry, -1, 0);
        }
        else {
            X509_NAME_ENTRY_create_by_NID(&new_entry, NID, encoding, (unsigned char*)entry, strlen(entry));
            X509_NAME_add_entry(name, new_entry, -1, 0);
        }
        X509_NAME_ENTRY_free(new_entry);
    }

    /*!
     * @brief Adiciona as entradas DN de um X509_NAME com a codificaÃ§Ã£o desejada.
     *
     * @param name Ponteiro para o X509_NAME.
     * @param encoding CodificaÃ§Ã£o desejada.
     */
    void fillEntries(X509_NAME* name, int encoding) {
        for(std::map<int, const char*>::iterator entries = entry_fields.begin(); entries != entry_fields.end(); entries++){
            addNameEntry(name, entries->second, encoding, entries->first);
            rdn.addEntry(id2Type(entries->first), entries->second);
        }
    }

    /*!
     * @brief Aplica um caso de teste com todas as entradas preenchidas com a codificaÃ§Ã£o desejada.
     *
     * @param encoding CodificaÃ§Ã£o desejada.
     *
     * @return true se o caso de teste estiver correto, falso caso contrÃ¡rio.
     */
    void populateCertificateBuilderX509(int entriesCodification) {
        // create requisition and populate certificateBuilder:
        fillEntries(before, entriesCodification);
        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));
    }

    void populateCertificateBuilderPem(int entriesCodification) {
        // create requisition and populate certificateBuilder:
        cbuilder = new CertificateBuilder(req);
        fillEntries(before, entriesCodification);
    }

    /*!
     * @brief Aplica um caso de teste com uma entrada preenchida com a codificaÃ§Ã£o desejada e as restantes com a
     *        codificaÃ§Ã£o padrÃ£o da versÃ£o OpenSSL.
     *
     * @param entry Entrada
     * @param encoding CodificaÃ§Ã£o desejada.
     *
     * @return true se o caso de teste estiver correto, falso caso contrÃ¡rio.
     */
    void applyOne(const char* entry, int encoding) {
        // create certificate:
        addNameEntry(before, entry, encoding, NID_commonName);    // insere a entrada se nÃ£o for common name
        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));

        // fill entries and apply alterSubject:
        fillEntries(before, MBSTRING_ASC);
        RDNSequence rrr(X509_NAME_dup(before));
        cbuilder->alterSubject(rrr);
        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));
    }

    void alterRDNSequences() {
        // apply alterSubject:
        cbuilder->alterSubject(rdn);
        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));
    }

    /*!
     * @brief Testa se a codificaÃ§Ã£o das entradas estÃ£o de acordo com o esperado.
     *
     * Testa se a codificaÃ§Ã£o das entradas no certificado gerado estÃ£o de acordo com a primeira entrada commonName que Ã©
     * obrigatÃ³ria na geraÃ§Ã£o da requisiÃ§Ã£o.
     */
    bool testStringCodificaton(int expectedCodification) {
        for (int i = 0; i < X509_NAME_entry_count(after); i++) {
            X509_NAME_ENTRY* entry = X509_NAME_get_entry(after, i);
            if (entry->object->nid != NID_countryName) {
                if(entry->value->type != expectedCodification) {
                    return false;
                }
            }
        }
        return true;
    }

    bool testStringValues() {
        return true;
    }

    int getReqStringCodification() {
        return 0;
    }

    int getCertStringCodification() {
        return 0;
    }

    RDNSequence::EntryType id2Type(int id) {
        RDNSequence::EntryType ret;
        switch (id) {
            case NID_countryName: ret = RDNSequence::COUNTRY; break;
            case NID_organizationName: ret = RDNSequence::ORGANIZATION; break;
            case NID_organizationalUnitName: ret = RDNSequence::ORGANIZATION_UNIT; break;
            case NID_dnQualifier: ret = RDNSequence::DN_QUALIFIER; break;
            case NID_stateOrProvinceName: ret = RDNSequence::STATE_OR_PROVINCE; break;
            case NID_commonName: ret = RDNSequence::COMMON_NAME; break;
            case NID_serialNumber: ret = RDNSequence::SERIAL_NUMBER; break;
            case NID_localityName: ret = RDNSequence::LOCALITY; break;
            case NID_title: ret = RDNSequence::TITLE; break;
            case NID_surname: ret = RDNSequence::SURNAME; break;
            case NID_givenName: ret = RDNSequence::GIVEN_NAME; break;
            case NID_initials: ret = RDNSequence::INITIALS; break;
            case NID_pseudonym: ret = RDNSequence::PSEUDONYM; break;
            case NID_generationQualifier: ret = RDNSequence::GENERATION_QUALIFIER; break;
            case NID_pkcs9_emailAddress: ret = RDNSequence::EMAIL; break;
            case NID_domainComponent: ret = RDNSequence::DOMAIN_COMPONENT; break;
            default: ret = RDNSequence::UNKNOWN;
        }
        return ret;
    }

    CertificateBuilder* cbuilder;  //!< CertificateBuilder usado para aplicar a funÃ§Ã£o testada.
    std::string req_pem_encoded;
    CertificateRequest req;
    RDNSequence rdn;
    X509_NAME* before;  //!< Ponteiro para o X509_NAME antes de aplicar a funÃ§Ã£o testada.
    X509_NAME* after;  //!< Ponteiro para o X509_NAME depois de aplicar a funÃ§Ã£o testada.

    std::map<int, const char*> entry_fields;
};

/**
 * AtravÃ©s de uma requisiÃ§Ã£o previamente gerada, testa se o certificado mantem a formataÃ§Ã£o antes de ser emitido.
 *
 **/
 TEST_F(EncodingTest, ReqPEM_keep_codification) {
	 populateCertificateBuilderPem(V_ASN1_UTF8STRING);

     ASSERT_TRUE(testStringCodificaton(V_ASN1_UTF8STRING));
 }

/**
 * Tests se a codificaÃ§Ã£o do re
 */

 TEST_F(EncodingTest, ReqPEM_alter_all_fields) {
	 populateCertificateBuilderPem(V_ASN1_UTF8STRING);
	 alterRDNSequences();

     ASSERT_TRUE(testStringCodificaton(V_ASN1_PRINTABLESTRING));
 }

/*!
 * @brief Teste usando todas as entradas preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING.
 *
 * Simula a situaÃ§Ã£o onde os campos sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o, devendo manter sua codificaÃ§Ã£o no
 * certificado gerado.
 */
//TEST_F(EncodingTest, PrintableFilled) {
//    ASSERT_TRUE(createCertificate(V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando as entradas commonName e countryName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as
// *        restantes com codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde os campos Common Name e Country Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes
// * sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintablecountryName) {
//    ASSERT_TRUE(applyOne(LN_countryName, V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando as entradas commonName e stateOrProvinceName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e
// *        as restantes com codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde os campos Common Name e State or Province Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os
// * restantes sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na
// * requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintableState) {
//    ASSERT_TRUE(applyOne(LN_stateOrProvinceName, V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando as entradas commonName e localityName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as
// *        restantes com codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde os campos Common Name e Locality Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes
// * sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintableLocality) {
//    ASSERT_TRUE(applyOne(LN_localityName, V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando as entradas commonName e organizationName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as
// *        restantes com codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde os campos Common Name e Organization Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os
// * restantes sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na
// * requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintableOrganization) {
//    ASSERT_TRUE(applyOne(LN_organizationName, V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando as entradas commonName e organizationalUnitName preenchidas com codificaÃ§Ã£o
// *        V_ASN1_PRINTABLESTRING e as restantes com codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde os campos Common Name e Organizational Unit Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os
// * restantes sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na
// * requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintableOrganizationalUnit) {
//    ASSERT_TRUE(applyOne(LN_organizationalUnitName, V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando a entrada commonName preenchida com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e asrestantes com
// *        codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde apenas o campo Common Name Ã© preenchido na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes sÃ£o
// * adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintableCommonName) {
//    ASSERT_TRUE(applyOne(LN_commonName, V_ASN1_PRINTABLESTRING));
//}
//
///*!
// * @brief Teste usando as entradas commonName e userId preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as
// *        restantes com codificaÃ§Ã£o MBSTRING_ASC.
// *
// * Simula a situaÃ§Ã£o onde os campos Common Name e User ID sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes sÃ£o
// * adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.
// */
//TEST_F(EncodingTest, PrintableUserID) {
//    ASSERT_TRUE(applyOne(LN_userId, V_ASN1_PRINTABLESTRING));
//}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>

using namespace fnord;

namespace cm {

RefPtr<IndexWriter> IndexWriter::openIndex(const String& index_path) {
  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
    RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
  }

  /* set up feature schema */
  FeatureSchema feature_schema;
  feature_schema.registerFeature("shop_id", 1, 1);
  feature_schema.registerFeature("category1", 2, 1);
  feature_schema.registerFeature("category2", 3, 1);
  feature_schema.registerFeature("category3", 4, 1);
  feature_schema.registerFeature("title~de", 5, 2);

  /* open mdb */
  auto db_path = FileUtil::joinPaths(index_path, "db");
  FileUtil::mkdir_p(db_path);
  auto db = mdb::MDB::open(db_path);
  db->setMaxSize(1000000 * 512000);

  /* open docs store */
  auto docs_path = FileUtil::joinPaths(index_path, "docs");
  FileUtil::mkdir_p(docs_path);
  RefPtr<DocStore> docs(new DocStore(docs_path));

  /* open lucene */
  RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer("./conf"));
  auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);

  auto fts_path = FileUtil::joinPaths(index_path, "fts");
  auto fts =
      fts::newLucene<fts::IndexWriter>(
          fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
          adapter,
          true,
          fts::IndexWriter::MaxFieldLengthLIMITED);

  return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));
}

IndexWriter::IndexWriter(
    FeatureSchema schema,
    RefPtr<mdb::MDB> db,
    RefPtr<DocStore> docs,
    std::shared_ptr<fts::IndexWriter> fts) :
    schema_(schema),
    db_(db),
    feature_idx_(new FeatureIndexWriter(&schema_)),
    docs_(docs),
    fts_(fts) {}

IndexWriter::~IndexWriter() {
  fts_->close();
}

void IndexWriter::updateDocument(const IndexRequest& index_request) {
  stat_documents_indexed_total_.incr(1);
  auto doc = docs_->updateDocument(index_request);
  rebuildFTS(doc);
  stat_documents_indexed_success_.incr(1);
}

void IndexWriter::commit() {
  fts_->commit();
}

void IndexWriter::rebuildFTS(DocID docid) {
  auto doc = docs_->findDocument(docid);
  rebuildFTS(doc);
}

void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
  auto fts_doc = fts::newLucene<fts::Document>();

  fnord::logDebug(
      "cm.indexwriter",
      "Rebuilding FTS Index for docid=$0",
      doc->docID().docid);

  HashMap<String, String> fts_fields_anal;
  for (const auto& f : doc->fields()) {

    /* title~LANG */
    if (StringUtil::beginsWith(f.first, "title~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "title~","text~");
      fts_fields_anal[k] += " ";
      fts_fields_anal[k] += f.second;
    }

    /* description~LANG */
    if (StringUtil::beginsWith(f.first, "description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "description~","text~");
      fts_fields_anal[k] += " ";
      fts_fields_anal[k] += f.second;
    }

    /* tags_as_text~LANG */
    if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "tags_as_text~","text~");
      fts_fields_anal[k] += " ";
      fts_fields_anal[k] += f.second;
    }

  }

  for (const auto& f : fts_fields_anal) {
    fnord::iputs("field $0 = $1", f.first, f.second);

    fts_doc->add(
        fts::newLucene<fts::Field>(
            StringUtil::convertUTF8To16(f.first),
            StringUtil::convertUTF8To16(f.second),
            fts::Field::STORE_NO,
            fts::Field::INDEX_ANALYZED));
  }

  fts_->addDocument(fts_doc);
}

void IndexWriter::rebuildFTS() {
  fnord::iputs("rebuild fts...", 1);

  docs_->listDocuments([this] (const DocID& docid) -> bool {
    fnord::iputs("rebuild fts for $0", docid.docid);
    return true;
  });
}

RefPtr<mdb::MDB> IndexWriter::featureDB() {
  return db_;
}

void IndexWriter::exportStats(const String& prefix) {
  exportStat(
      StringUtil::format("$0/documents_indexed_total", prefix),
      &stat_documents_indexed_total_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_success", prefix),
      &stat_documents_indexed_success_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_error", prefix),
      &stat_documents_indexed_error_,
      fnord::stats::ExportMode::EXPORT_DELTA);
}

} // namespace cm
<commit_msg>--rebuild_fts all<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "IndexWriter.h"
#include <fnord-fts/AnalyzerAdapter.h>

using namespace fnord;

namespace cm {

RefPtr<IndexWriter> IndexWriter::openIndex(const String& index_path) {
  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {
    RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path);
  }

  /* set up feature schema */
  FeatureSchema feature_schema;
  feature_schema.registerFeature("shop_id", 1, 1);
  feature_schema.registerFeature("category1", 2, 1);
  feature_schema.registerFeature("category2", 3, 1);
  feature_schema.registerFeature("category3", 4, 1);
  feature_schema.registerFeature("title~de", 5, 2);

  /* open mdb */
  auto db_path = FileUtil::joinPaths(index_path, "db");
  FileUtil::mkdir_p(db_path);
  auto db = mdb::MDB::open(db_path);
  db->setMaxSize(1000000 * 512000);

  /* open docs store */
  auto docs_path = FileUtil::joinPaths(index_path, "docs");
  FileUtil::mkdir_p(docs_path);
  RefPtr<DocStore> docs(new DocStore(docs_path));

  /* open lucene */
  RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer("./conf"));
  auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);

  auto fts_path = FileUtil::joinPaths(index_path, "fts");
  auto fts =
      fts::newLucene<fts::IndexWriter>(
          fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),
          adapter,
          true,
          fts::IndexWriter::MaxFieldLengthLIMITED);

  return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));
}

IndexWriter::IndexWriter(
    FeatureSchema schema,
    RefPtr<mdb::MDB> db,
    RefPtr<DocStore> docs,
    std::shared_ptr<fts::IndexWriter> fts) :
    schema_(schema),
    db_(db),
    feature_idx_(new FeatureIndexWriter(&schema_)),
    docs_(docs),
    fts_(fts) {}

IndexWriter::~IndexWriter() {
  fts_->close();
}

void IndexWriter::updateDocument(const IndexRequest& index_request) {
  stat_documents_indexed_total_.incr(1);
  auto doc = docs_->updateDocument(index_request);
  rebuildFTS(doc);
  stat_documents_indexed_success_.incr(1);
}

void IndexWriter::commit() {
  fts_->commit();
}

void IndexWriter::rebuildFTS(DocID docid) {
  auto doc = docs_->findDocument(docid);
  rebuildFTS(doc);
}

void IndexWriter::rebuildFTS(RefPtr<Document> doc) {
  auto fts_doc = fts::newLucene<fts::Document>();

  fnord::logDebug(
      "cm.indexwriter",
      "Rebuilding FTS Index for docid=$0",
      doc->docID().docid);

  HashMap<String, String> fts_fields_anal;
  for (const auto& f : doc->fields()) {

    /* title~LANG */
    if (StringUtil::beginsWith(f.first, "title~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "title~","text~");
      fts_fields_anal[k] += " ";
      fts_fields_anal[k] += f.second;
    }

    /* description~LANG */
    if (StringUtil::beginsWith(f.first, "description~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "description~","text~");
      fts_fields_anal[k] += " ";
      fts_fields_anal[k] += f.second;
    }

    /* tags_as_text~LANG */
    if (StringUtil::beginsWith(f.first, "tags_as_text~")) {
      auto k = f.first;
      StringUtil::replaceAll(&k, "tags_as_text~","text~");
      fts_fields_anal[k] += " ";
      fts_fields_anal[k] += f.second;
    }

  }

  for (const auto& f : fts_fields_anal) {
    fnord::iputs("field $0 = $1", f.first, f.second);

    fts_doc->add(
        fts::newLucene<fts::Field>(
            StringUtil::convertUTF8To16(f.first),
            StringUtil::convertUTF8To16(f.second),
            fts::Field::STORE_NO,
            fts::Field::INDEX_ANALYZED));
  }

  fts_->addDocument(fts_doc);
}

void IndexWriter::rebuildFTS() {
  docs_->listDocuments([this] (const DocID& docid) -> bool {
    rebuildFTS(docid);
    return true;
  });
}

RefPtr<mdb::MDB> IndexWriter::featureDB() {
  return db_;
}

void IndexWriter::exportStats(const String& prefix) {
  exportStat(
      StringUtil::format("$0/documents_indexed_total", prefix),
      &stat_documents_indexed_total_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_success", prefix),
      &stat_documents_indexed_success_,
      fnord::stats::ExportMode::EXPORT_DELTA);

  exportStat(
      StringUtil::format("$0/documents_indexed_error", prefix),
      &stat_documents_indexed_error_,
      fnord::stats::ExportMode::EXPORT_DELTA);
}

} // namespace cm
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "WeightGraph.hpp"
#include "Edge.hpp"
#include "Bus.hpp"
#include <memory>

class TestWeightGraph: public testing::Test {
public:
    TestWeightGraph()
	{
		mBusStop =  {{{5, 6}, "First Stop"},
					 {{7, 8}, "Second Stop"},
					 {{7, 9}, "Third Stop"},
					 {{9, 10}, "Fifth Stop"}};
        WeightGraph wG;
        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,8))));
        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,9))));
        sut = std::make_unique<WeightGraph>(wG);

	}
    std::unique_ptr<WeightGraph> sut;
	std::vector<BusStop> mBusStop;
    Edge edge1;
    Edge edge2;
};
TEST_F(TestWeightGraph, appendEdges){
    EXPECT_EQ(sut->size(), 2);
    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    EXPECT_EQ(sut->at(0), edge2);
}
TEST_F(TestWeightGraph, isEdgeInGraph){
    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    EXPECT_TRUE(sut->isEdgeInGraph(edge1));
    EXPECT_FALSE(sut->isEdgeInGraph(edge2));
}

TEST_F(TestWeightGraph, searchNeighbours){
    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,9)));
    sut->append(edge1);
    sut->append(edge2);
    EXPECT_EQ(edge1, sut->searchNeighbours(Node(Coordinate(5,6))).at(0));
    EXPECT_EQ(edge2,  sut->searchNeighbours(Node(Coordinate(5,6))).at(1));
}

TEST_F(TestWeightGraph, changeEdgeWeight){
    sut->changeEdgeWeight(Node(Coordinate(5,6)), Node(Coordinate(7,8)), 5);
    EXPECT_EQ(sut->at(0).getWeight(), Weight(0.2));
}

TEST_F(TestWeightGraph, searchEdge){
    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    sut->append(edge1);
    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
   // EXPECT_EQ(sut->edge(edge2), sut->at(0));
}

TEST_F(TestWeightGraph, createGraph){
	sut->createGraph(mBusStop);
    //EXPECT_EQ()
}
<commit_msg>test_WeightGraph and edge method in WeighGraph class refactor<commit_after>#include <gtest/gtest.h>

#include "WeightGraph.hpp"
#include "Edge.hpp"
#include "Bus.hpp"
#include <memory>

class TestWeightGraph: public testing::Test {
public:
    TestWeightGraph()
    {
        mBusStop =  {{{5, 6}, "First Stop"},
                     {{7, 8}, "Second Stop"},
                     {{7, 9}, "Third Stop"},
                     {{9, 10}, "Fifth Stop"}};
        addEdges();
    }

    void addEdges(){
        WeightGraph wG;
        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,8))));
        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,9))));
        sut = std::make_unique<WeightGraph>(wG);
    }

    std::unique_ptr<WeightGraph> sut;
	std::vector<BusStop> mBusStop;
    Edge edge1;
    Edge edge2;
};
TEST_F(TestWeightGraph, appendEdges){
    EXPECT_EQ(sut->size(), 2);
    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    EXPECT_EQ(sut->at(0), edge2);
}
TEST_F(TestWeightGraph, isEdgeInGraph){
    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    EXPECT_TRUE(sut->isEdgeInGraph(edge1));
    EXPECT_FALSE(sut->isEdgeInGraph(edge2));
}

TEST_F(TestWeightGraph, searchNeighbours){
    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));
    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,9)));
    EXPECT_EQ(edge1, sut->searchNeighbours(Node(Coordinate(5,6))).at(0));
    EXPECT_EQ(edge2,  sut->searchNeighbours(Node(Coordinate(5,6))).at(1));
}

TEST_F(TestWeightGraph, changeEdgeWeight){
    sut->changeEdgeWeight(Node(Coordinate(5,6)), Node(Coordinate(7,8)), 5);
    EXPECT_EQ(sut->at(0).getWeight(), Weight(0.2));
}

TEST_F(TestWeightGraph, searchEdge){
    EXPECT_EQ(sut->edge(Node(Coordinate(5,6)), Node(Coordinate(7,8))), sut->at(0));
}

TEST_F(TestWeightGraph, createGraph){
	sut->createGraph(mBusStop);
    //EXPECT_EQ()
}
<|endoftext|>


<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "PrimeTower.h"

#include <algorithm>
#include <limits>

#include "ExtruderTrain.h"
#include "sliceDataStorage.h"
#include "gcodeExport.h"
#include "LayerPlan.h"
#include "infill.h"
#include "PrintFeature.h"
#include "raft.h"

#define CIRCLE_RESOLUTION 32 //The number of vertices in each circle.

namespace cura
{

PrimeTower::PrimeTower(const SliceDataStorage& storage)
: wipe_from_middle(false)
{
    enabled = storage.getSettingBoolean("prime_tower_enable")
           && storage.getSettingInMicrons("prime_tower_min_volume") > 10
           && storage.getSettingInMicrons("prime_tower_size") > 10;

    extruder_count = storage.meshgroup->getExtruderCount();
    extruder_order.resize(extruder_count);
    for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)
    {
        extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort.
    }
    //Sort from high adhesion to low adhesion.
    const SliceDataStorage* storage_ptr = &storage; //Communicate to lambda via pointer to prevent copy.
    std::sort(extruder_order.begin(), extruder_order.end(), [storage_ptr](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool
    {
        const double adhesion_a = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_a)->getSettingAsRatio("material_adhesion_tendency");
        const double adhesion_b = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_b)->getSettingAsRatio("material_adhesion_tendency");
        return adhesion_a < adhesion_b;
    });
}

void PrimeTower::generateGroundpoly(const SliceDataStorage& storage)
{
    if (!enabled)
    {
        return;
    }

    coord_t tower_size = storage.getSettingInMicrons("prime_tower_size");
    bool circular_prime_tower = storage.getSettingBoolean("prime_tower_circular");

    PolygonRef p = outer_poly.newPoly();
    int tower_distance = 0;
    int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x
    int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y
    if (circular_prime_tower)
    {
        double_t tower_radius = tower_size / 2;
        for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)
        {
            const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians.
            p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,
                        y + tower_radius + tower_distance + sin(angle) * tower_radius));
        }
    }
    else
    {
        p.add(Point(x + tower_distance, y + tower_distance));
        p.add(Point(x + tower_distance, y + tower_distance + tower_size));
        p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
        p.add(Point(x + tower_distance - tower_size, y + tower_distance));
    }
    middle = Point(x - tower_size / 2, y + tower_size / 2);

    post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
}

void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
    enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
    if (enabled)
    {
        generatePaths_denseInfill(storage);
    }
}

void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage)
{
    const coord_t layer_height = storage.getSettingInMicrons("layer_height");
    pattern_per_extruder.resize(extruder_count);

    coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.
    for (unsigned int extruder : extruder_order)
    {
        const coord_t line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width");
        const coord_t required_volume = storage.meshgroup->getExtruderTrain(extruder)->getSettingInCubicMillimeters("prime_tower_min_volume") * 1000000000; //To cubic microns.
        const double flow = storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio("prime_tower_flow");
        coord_t current_volume = 0;
        ExtrusionMoves& pattern = pattern_per_extruder[extruder];

        //Create the walls of the prime tower.
        unsigned int wall_nr = 0;
        for (; current_volume < required_volume; wall_nr++)
        {
            //Create a new polygon with an offset from the outer polygon.
            Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2);
            pattern.polygons.add(polygons);
            current_volume += polygons.polygonLength() * line_width * layer_height * flow;
            if (polygons.empty()) //Don't continue. We won't ever reach the required volume because it doesn't fit.
            {
                break;
            }
        }
        cumulative_inset += wall_nr * line_width;

        //Generate the pattern for the first layer.
        coord_t line_width_layer0 = line_width;
        if (storage.getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::RAFT)
        {
            line_width_layer0 *= storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio("initial_layer_line_width_factor");
        }
        pattern_per_extruder_layer0.emplace_back();
        ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();
        pattern_layer0.polygons = outer_poly.offset(-line_width_layer0 / 2);
        const coord_t outline_offset = -line_width_layer0;
        const coord_t line_distance = line_width_layer0;
        constexpr double fill_angle = 45;
        constexpr bool zig_zaggify_infill = false;
        constexpr coord_t extra_infill_shift = 0;
        constexpr coord_t infill_overlap = 60; // so that it can't be zero; EDIT: wtf?
        constexpr coord_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position
        constexpr bool connect_polygons = false;
        constexpr int infill_multiplier = 1;
        Infill infill_comp(EFillMethod::CONCENTRIC, zig_zaggify_infill, connect_polygons, outer_poly, outline_offset, line_width_layer0, line_distance, infill_overlap, infill_multiplier, fill_angle, z, extra_infill_shift);
        infill_comp.generate(pattern_layer0.polygons, pattern_layer0.lines);
    }
}

void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const GCodeExport& gcode, const int prev_extruder, const int new_extruder) const
{
    if (!enabled)
    {
        return;
    }
    if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))
    { // don't print the prime tower if it has been printed already with this extruder.
        return;
    }

    if (gcode_layer.getLayerNr() > storage.max_print_height_second_to_last_extruder + 1)
    {
        return;
    }

    bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled");

    // Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.
    const int layer_nr = gcode_layer.getLayerNr();
    if (prev_extruder == new_extruder || layer_nr == 0)
    {
        post_wipe = false;
    }

    addToGcode_denseInfill(storage, gcode_layer, new_extruder);

    // post-wipe:
    if (post_wipe)
    { //Make sure we wipe the old extruder on the prime tower.
        gcode_layer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder));
    }

    gcode_layer.setPrimeTowerIsPlanned(new_extruder);
}

void PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int extruder_nr) const
{
    const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -Raft::getFillerLayerCount(storage))
        ? pattern_per_extruder_layer0[extruder_nr]
        : pattern_per_extruder[extruder_nr];

    const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];

    gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);
    gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);
}

Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const
{
    Point ret(0, 0);
    int absolute_starting_points = 0;
    for (unsigned int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)
    {
        ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0);
        if (train.getSettingBoolean("machine_extruder_start_pos_abs"))
        {
            ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y"));
            absolute_starting_points++;
        }
    }
    if (absolute_starting_points > 0)
    { // take the average over all absolute starting positions
        ret /= absolute_starting_points;
    }
    else
    { // use the middle of the bed
        ret = storage.machine_size.flatten().getMiddle();
    }
    return ret;
}

void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
    const Polygons outside_polygon = outer_poly.getOutsidePolygons();
    AABB outside_polygon_boundary_box(outside_polygon);
    for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
    {
        SupportLayer& support_layer = storage.support.supportLayers[layer];
        // take the differences of the support infill parts and the prime tower area
        support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);
    }
}

}//namespace cura
<commit_msg>Revert "Do not connect polygons in the first layer of the prime tower."<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "PrimeTower.h"

#include <algorithm>
#include <limits>

#include "ExtruderTrain.h"
#include "sliceDataStorage.h"
#include "gcodeExport.h"
#include "LayerPlan.h"
#include "infill.h"
#include "PrintFeature.h"
#include "raft.h"

#define CIRCLE_RESOLUTION 32 //The number of vertices in each circle.

namespace cura
{

PrimeTower::PrimeTower(const SliceDataStorage& storage)
: wipe_from_middle(false)
{
    enabled = storage.getSettingBoolean("prime_tower_enable")
           && storage.getSettingInMicrons("prime_tower_min_volume") > 10
           && storage.getSettingInMicrons("prime_tower_size") > 10;

    extruder_count = storage.meshgroup->getExtruderCount();
    extruder_order.resize(extruder_count);
    for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)
    {
        extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort.
    }
    //Sort from high adhesion to low adhesion.
    const SliceDataStorage* storage_ptr = &storage; //Communicate to lambda via pointer to prevent copy.
    std::sort(extruder_order.begin(), extruder_order.end(), [storage_ptr](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool
    {
        const double adhesion_a = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_a)->getSettingAsRatio("material_adhesion_tendency");
        const double adhesion_b = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_b)->getSettingAsRatio("material_adhesion_tendency");
        return adhesion_a < adhesion_b;
    });
}

void PrimeTower::generateGroundpoly(const SliceDataStorage& storage)
{
    if (!enabled)
    {
        return;
    }

    coord_t tower_size = storage.getSettingInMicrons("prime_tower_size");
    bool circular_prime_tower = storage.getSettingBoolean("prime_tower_circular");

    PolygonRef p = outer_poly.newPoly();
    int tower_distance = 0;
    int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x
    int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y
    if (circular_prime_tower)
    {
        double_t tower_radius = tower_size / 2;
        for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)
        {
            const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians.
            p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,
                        y + tower_radius + tower_distance + sin(angle) * tower_radius));
        }
    }
    else
    {
        p.add(Point(x + tower_distance, y + tower_distance));
        p.add(Point(x + tower_distance, y + tower_distance + tower_size));
        p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));
        p.add(Point(x + tower_distance - tower_size, y + tower_distance));
    }
    middle = Point(x - tower_size / 2, y + tower_size / 2);

    post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2);
}

void PrimeTower::generatePaths(const SliceDataStorage& storage)
{
    enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches.
    if (enabled)
    {
        generatePaths_denseInfill(storage);
    }
}

void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage)
{
    const coord_t layer_height = storage.getSettingInMicrons("layer_height");
    pattern_per_extruder.resize(extruder_count);

    coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.
    for (unsigned int extruder : extruder_order)
    {
        const coord_t line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width");
        const coord_t required_volume = storage.meshgroup->getExtruderTrain(extruder)->getSettingInCubicMillimeters("prime_tower_min_volume") * 1000000000; //To cubic microns.
        const double flow = storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio("prime_tower_flow");
        coord_t current_volume = 0;
        ExtrusionMoves& pattern = pattern_per_extruder[extruder];

        //Create the walls of the prime tower.
        unsigned int wall_nr = 0;
        for (; current_volume < required_volume; wall_nr++)
        {
            //Create a new polygon with an offset from the outer polygon.
            Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2);
            pattern.polygons.add(polygons);
            current_volume += polygons.polygonLength() * line_width * layer_height * flow;
            if (polygons.empty()) //Don't continue. We won't ever reach the required volume because it doesn't fit.
            {
                break;
            }
        }
        cumulative_inset += wall_nr * line_width;

        //Generate the pattern for the first layer.
        coord_t line_width_layer0 = line_width;
        if (storage.getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::RAFT)
        {
            line_width_layer0 *= storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio("initial_layer_line_width_factor");
        }
        pattern_per_extruder_layer0.emplace_back();
        ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();
        pattern_layer0.polygons = outer_poly.offset(-line_width_layer0 / 2);
        const coord_t outline_offset = -line_width_layer0;
        const coord_t line_distance = line_width_layer0;
        constexpr double fill_angle = 45;
        constexpr bool zig_zaggify_infill = false;
        constexpr coord_t extra_infill_shift = 0;
        constexpr coord_t infill_overlap = 60; // so that it can't be zero; EDIT: wtf?
        constexpr coord_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position
        constexpr bool connect_polygons = true;
        constexpr int infill_multiplier = 1;
        Infill infill_comp(EFillMethod::CONCENTRIC, zig_zaggify_infill, connect_polygons, outer_poly, outline_offset, line_width_layer0, line_distance, infill_overlap, infill_multiplier, fill_angle, z, extra_infill_shift);
        infill_comp.generate(pattern_layer0.polygons, pattern_layer0.lines);
    }
}

void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const GCodeExport& gcode, const int prev_extruder, const int new_extruder) const
{
    if (!enabled)
    {
        return;
    }
    if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))
    { // don't print the prime tower if it has been printed already with this extruder.
        return;
    }

    if (gcode_layer.getLayerNr() > storage.max_print_height_second_to_last_extruder + 1)
    {
        return;
    }

    bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled");

    // Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.
    const int layer_nr = gcode_layer.getLayerNr();
    if (prev_extruder == new_extruder || layer_nr == 0)
    {
        post_wipe = false;
    }

    addToGcode_denseInfill(storage, gcode_layer, new_extruder);

    // post-wipe:
    if (post_wipe)
    { //Make sure we wipe the old extruder on the prime tower.
        gcode_layer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder));
    }

    gcode_layer.setPrimeTowerIsPlanned(new_extruder);
}

void PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int extruder_nr) const
{
    const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -Raft::getFillerLayerCount(storage))
        ? pattern_per_extruder_layer0[extruder_nr]
        : pattern_per_extruder[extruder_nr];

    const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];

    gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);
    gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);
}

Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const
{
    Point ret(0, 0);
    int absolute_starting_points = 0;
    for (unsigned int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)
    {
        ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0);
        if (train.getSettingBoolean("machine_extruder_start_pos_abs"))
        {
            ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y"));
            absolute_starting_points++;
        }
    }
    if (absolute_starting_points > 0)
    { // take the average over all absolute starting positions
        ret /= absolute_starting_points;
    }
    else
    { // use the middle of the bed
        ret = storage.machine_size.flatten().getMiddle();
    }
    return ret;
}

void PrimeTower::subtractFromSupport(SliceDataStorage& storage)
{
    const Polygons outside_polygon = outer_poly.getOutsidePolygons();
    AABB outside_polygon_boundary_box(outside_polygon);
    for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)
    {
        SupportLayer& support_layer = storage.support.supportLayers[layer];
        // take the differences of the support infill parts and the prime tower area
        support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);
    }
}

}//namespace cura
<|endoftext|>


<commit_before><commit_msg>Use simpler matrix constructor<commit_after><|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX デバイス選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#include "common/device.hpp"

#include "RX600/bus.hpp"

#if defined(SIG_RX24T)
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX600/cmpc.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX64M) || defined(SIG_RX71M)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/scif.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX65N)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX66T)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/can.hpp"
#include "RX600/r12da.hpp"
#include "RX600/usb.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/cmpc.hpp"

#else
#  error "renesas.hpp: Requires SIG_XXX to be defined"
#endif

// RX マイコン共通ペリフェラル
#include "RX600/cac.hpp"
#include "RX600/dtc.hpp"
#include "RX600/port.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/gpt.hpp"
#include "RX600/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX600/iwdt.hpp"
#include "RX600/sci.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/crc.hpp"
#include "RX600/mpu.hpp"
#include "RX600/doc.hpp"
<commit_msg>update: add lvda include<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX デバイス選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#include "common/device.hpp"

#include "RX600/lvda.hpp"
#include "RX600/bus.hpp"

#if defined(SIG_RX24T)
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX600/cmpc.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX64M) || defined(SIG_RX71M)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/scif.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX65N)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX66T)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/can.hpp"
#include "RX600/r12da.hpp"
#include "RX600/usb.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/cmpc.hpp"

#else
#  error "renesas.hpp: Requires SIG_XXX to be defined"
#endif

// RX マイコン共通ペリフェラル
#include "RX600/cac.hpp"
#include "RX600/dtc.hpp"
#include "RX600/port.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/gpt.hpp"
#include "RX600/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX600/iwdt.hpp"
#include "RX600/sci.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/crc.hpp"
#include "RX600/mpu.hpp"
#include "RX600/doc.hpp"
<|endoftext|>


<commit_before>//
//  File:   Actor.cpp
//  Class:  Actor
//  Author: John Barbero Unenge
//          All code is my own except where credited to others.
//
//  Copyright (c) 2012 Catch22. All Rights Reserved.
//
//  Date:   2/10/12
//

#include "Actor.hpp"
#include "../Helper/Logger.hpp"

//  Used until proper model object is used to track rendering location
const Vertex txPos[] = {
    Vertex(100.0f ,100.0f),
    Vertex(132.0f ,100.0f),
    Vertex(100.0f ,132.0f),
    Vertex(132.0f ,132.0f),
};

Actor::Actor(AnimationArray* animations, Animation* currentAnimation)
{
    m_pBody = 0;

    m_animations = animations;
    m_currentAnimation = currentAnimation;
}
Actor::Actor(Actor* actor)
{
    m_pBody = 0;

    Animation** newAnimations = new Animation*[actor->m_animations->m_size];
    for (int i = 0; i < actor->m_animations->m_size; i++) {
        newAnimations[i] = new Animation(actor->m_animations->m_animationArray[i]);
    }

    m_animations = new AnimationArray(newAnimations, actor->m_animations->m_size);
    m_currentAnimation = m_animations->m_animationArray[0];
}
void Actor::setPBody(PBody* pBody)
{
    m_pBody = pBody;
}
const Vertex* Actor::getVertexData()
{
    if (m_pBody != 0) {
        Vertex* v = new Vertex[4];
        v[0] = Vertex(m_pBody->getPosition()->m_x ,m_pBody->getPosition()->m_y);
        v[1] = Vertex(m_pBody->getPosition()->m_x + m_pBody->getSize()->m_x,m_pBody->getPosition()->m_y);
        v[2] = Vertex(m_pBody->getPosition()->m_x ,m_pBody->getPosition()->m_y + m_pBody->getSize()->m_y);
        v[3] = Vertex(m_pBody->getPosition()->m_x + m_pBody->getSize()->m_x,m_pBody->getPosition()->m_y + m_pBody->getSize()->m_y);

        return v;
    }

    return txPos;
}
const Vertex* Actor::getTextureVertexData()
{
    if (m_currentAnimation == 0) {
        Log(LOG_ERROR, "Actor", "Current animation null!");
        return 0;
    }

    return m_currentAnimation->getTextureVertexData();
}
int Actor::getTextureID()
{
    return m_currentAnimation->getTextureID();
}
void Actor::update(float dt){
    m_currentAnimation->update(dt);
}<commit_msg>Made changes to complie with how the new PBody works.<commit_after>//
//  File:   Actor.cpp
//  Class:  Actor
//  Author: John Barbero Unenge
//          All code is my own except where credited to others.
//
//  Copyright (c) 2012 Catch22. All Rights Reserved.
//
//  Date:   2/10/12
//

#include "Actor.hpp"
#include "../Helper/Logger.hpp"

//  Used until proper model object is used to track rendering location
const Vertex txPos[] = {
    Vertex(100.0f ,100.0f),
    Vertex(132.0f ,100.0f),
    Vertex(100.0f ,132.0f),
    Vertex(132.0f ,132.0f),
};

Actor::Actor(AnimationArray* animations, Animation* currentAnimation)
{
    m_pBody = 0;

    m_animations = animations;
    m_currentAnimation = currentAnimation;
}
Actor::Actor(Actor* actor)
{
    m_pBody = 0;

    Animation** newAnimations = new Animation*[actor->m_animations->m_size];
    for (int i = 0; i < actor->m_animations->m_size; i++) {
        newAnimations[i] = new Animation(actor->m_animations->m_animationArray[i]);
    }

    m_animations = new AnimationArray(newAnimations, actor->m_animations->m_size);
    m_currentAnimation = m_animations->m_animationArray[0];
}
void Actor::setPBody(PBody* pBody)
{
    m_pBody = pBody;
}
const Vertex* Actor::getVertexData()
{
    if (m_pBody != 0) {
        Vertex* v = new Vertex[m_pBody->getVectorArray()->m_size];

        for (int i = 0; i < m_pBody->getVectorArray()->m_size; i++) {
            v[i] = Vertex(m_pBody->getVectorArray()->m_vectors[i]->m_x, m_pBody->getVectorArray()->m_vectors[i]->m_y);
        }

        return v;
    }

    return txPos;
}
const Vertex* Actor::getTextureVertexData()
{
    if (m_currentAnimation == 0) {
        Log(LOG_ERROR, "Actor", "Current animation null!");
        return 0;
    }

    return m_currentAnimation->getTextureVertexData();
}
int Actor::getTextureID()
{
    return m_currentAnimation->getTextureID();
}
void Actor::update(float dt){
    m_currentAnimation->update(dt);
}<|endoftext|>


<commit_before>int main()
{
    freopen("in.txt", "r", stdin);
    freopen("A-small-attempt0.in", "r", stdin);
    freopen("A-small-attempt0.out", "w", stdout);
    freopen("A-large.in", "r", stdin);
    freopen("A-large.out", "w", stdout);
    int T, TC = 0;
    scanf("%d", &T);
    while (++TC <= T)
    {
        printf("Case #%d: ", TC);
        solve();
    }
    return 0;
}
<commit_msg>gcj use macro in out<commit_after>#define FRsmall(x,y) do{freopen(#x"-small-attempt"#y".in","r",stdin);freopen(#x"-small-attempt"#y".out","w",stdout);}while(0)
#define FRlarge(x) do{freopen(#x"-large.in","r",stdin);freopen(#x"-large.out","w",stdout);}while(0)

int main()
{
    freopen("in.txt", "r", stdin);
    FRsmall(A, 0);
    FRlarge(A);
    int T, TC = 0;
    scanf("%d", &T);
    while (++TC <= T)
    {
        printf("Case #%d: ", TC);
        solve();
    }
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Wrapped boot into a transaction, shaves a couple of seconds<commit_after><|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * adiosComm.tcc : specialization of template functions defined in
 * adiosComm.h
 */

#ifndef ADIOS2_HELPER_ADIOSCOMM_TCC_
#define ADIOS2_HELPER_ADIOSCOMM_TCC_

#include "adiosComm.h"

#include "adios2/common/ADIOSMPI.h"

#include <stdexcept> //std::runtime_error

namespace adios2
{
namespace helper
{

namespace
{

std::vector<size_t> GetGathervDisplacements(const size_t *counts,
                                            const size_t countsSize)
{
    std::vector<size_t> displacements(countsSize);
    displacements[0] = 0;

    for (size_t i = 1; i < countsSize; ++i)
    {
        displacements[i] = displacements[i - 1] + counts[i - 1];
    }
    return displacements;
}

}

// GatherArrays full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::GatherArrays(const char *source, size_t sourceCount,
                        char *destination, int rankDestination) const
{
    int countsInt = static_cast<int>(sourceCount);
    int result = SMPI_Gather(const_cast<char *>(source), countsInt, MPI_CHAR,
                             destination, countsInt, MPI_CHAR, rankDestination,
                             m_MPIComm);

    if (result != MPI_SUCCESS)
    {
        throw std::runtime_error("ERROR: in ADIOS2 detected failure in MPI "
                                 "Gather type MPI_CHAR function\n");
    }
}

template <>
void Comm::GatherArrays(const size_t *source, size_t sourceCount,
                        size_t *destination, int rankDestination) const
{
    int countsInt = static_cast<int>(sourceCount);
    int result = SMPI_Gather(const_cast<size_t *>(source), countsInt,
                             ADIOS2_MPI_SIZE_T, destination, countsInt,
                             ADIOS2_MPI_SIZE_T, rankDestination, m_MPIComm);

    if (result != MPI_SUCCESS)
    {
        throw std::runtime_error("ERROR: in ADIOS2 detected failure in MPI "
                                 "Gather type size_t function\n");
    }
}

// GathervArrays full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::GathervArrays(const char *source, size_t sourceCount,
                         const size_t *counts, size_t countsSize,
                         char *destination, int rankDestination) const
{
    std::vector<size_t> displs;
    if (rankDestination == this->Rank())
    {
        displs = GetGathervDisplacements(counts, countsSize);
    }
    this->Gatherv(source, sourceCount, destination, counts, displs.data(),
                  rankDestination);
}

template <>
void Comm::GathervArrays(const size_t *source, size_t sourceCount,
                         const size_t *counts, size_t countsSize,
                         size_t *destination, int rankDestination) const
{
    std::vector<size_t> displs;
    if (rankDestination == this->Rank())
    {
        displs = GetGathervDisplacements(counts, countsSize);
    }
    this->Gatherv(source, sourceCount, destination, counts, displs.data(),
                  rankDestination);
}

// AllGatherArrays full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::AllGatherArrays(const size_t *source, const size_t sourceCount,
                           size_t *destination) const
{
    int countsInt = static_cast<int>(sourceCount);
    int result = MPI_Allgather(const_cast<size_t *>(source), countsInt,
                               ADIOS2_MPI_SIZE_T, destination, countsInt,
                               ADIOS2_MPI_SIZE_T, m_MPIComm);

    if (result != MPI_SUCCESS)
    {
        throw std::runtime_error("ERROR: in ADIOS2 detected failure in MPI "
                                 "Allgather type size_t function\n");
    }
}

// ReduceValues full specializations forward-declared in 'adiosComm.inl'.
template <>
unsigned int Comm::ReduceValues(const unsigned int source, MPI_Op operation,
                                const int rankDestination) const
{
    unsigned int sourceLocal = source;
    unsigned int reduceValue = 0;
    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED, operation,
                rankDestination, m_MPIComm);
    return reduceValue;
}

template <>
unsigned long int Comm::ReduceValues(const unsigned long int source,
                                     MPI_Op operation,
                                     const int rankDestination) const
{
    unsigned long int sourceLocal = source;
    unsigned long int reduceValue = 0;
    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG, operation,
                rankDestination, m_MPIComm);
    return reduceValue;
}

template <>
unsigned long long int Comm::ReduceValues(const unsigned long long int source,
                                          MPI_Op operation,
                                          const int rankDestination) const
{
    unsigned long long int sourceLocal = source;
    unsigned long long int reduceValue = 0;
    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG_LONG,
                operation, rankDestination, m_MPIComm);
    return reduceValue;
}

// BroadcastValue full specializations forward-declared in 'adiosComm.inl'.
template <>
size_t Comm::BroadcastValue(const size_t &input, const int rankSource) const
{
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);
    size_t output = 0;

    if (rank == rankSource)
    {
        output = input;
    }

    SMPI_Bcast(&output, 1, ADIOS2_MPI_SIZE_T, rankSource, m_MPIComm);

    return output;
}

template <>
std::string Comm::BroadcastValue(const std::string &input,
                                 const int rankSource) const
{
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);
    const size_t inputSize = input.size();
    const size_t length = this->BroadcastValue(inputSize, rankSource);
    std::string output;

    if (rank == rankSource)
    {
        output = input;
    }
    else
    {
        output.resize(length);
    }

    SMPI_Bcast(const_cast<char *>(output.data()), static_cast<int>(length),
               MPI_CHAR, rankSource, m_MPIComm);

    return output;
}

// BroadcastVector full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::BroadcastVector(std::vector<char> &vector,
                           const int rankSource) const
{
    int size;
    SMPI_Comm_size(m_MPIComm, &size);

    if (size == 1)
    {
        return;
    }

    // First Broadcast the size, then the contents
    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);

    if (rank != rankSource)
    {
        vector.resize(inputSize);
    }

    const int MAXBCASTSIZE = 1073741824;
    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    char *buffer = vector.data();
    while (inputSize > 0)
    {
        SMPI_Bcast(buffer, static_cast<int>(blockSize), MPI_CHAR, rankSource,
                   m_MPIComm);
        buffer += blockSize;
        inputSize -= blockSize;
        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    }
}

template <>
void Comm::BroadcastVector(std::vector<size_t> &vector,
                           const int rankSource) const
{
    int size;
    SMPI_Comm_size(m_MPIComm, &size);

    if (size == 1)
    {
        return;
    }

    // First Broadcast the size, then the contents
    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);

    if (rank != rankSource)
    {
        vector.resize(inputSize);
    }

    const int MAXBCASTSIZE = 1073741824 / sizeof(size_t);
    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    size_t *buffer = vector.data();
    while (inputSize > 0)
    {
        SMPI_Bcast(buffer, static_cast<int>(blockSize), ADIOS2_MPI_SIZE_T,
                   rankSource, m_MPIComm);
        buffer += blockSize;
        inputSize -= blockSize;
        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    }
}

// Datatype full specializations forward-declared in 'adiosComm.inl'.
template <>
MPI_Datatype Comm::Datatype<signed char>()
{
    return MPI_SIGNED_CHAR;
}

template <>
MPI_Datatype Comm::Datatype<char>()
{
    return MPI_CHAR;
}

template <>
MPI_Datatype Comm::Datatype<short>()
{
    return MPI_SHORT;
}

template <>
MPI_Datatype Comm::Datatype<int>()
{
    return MPI_INT;
}

template <>
MPI_Datatype Comm::Datatype<long>()
{
    return MPI_LONG;
}

template <>
MPI_Datatype Comm::Datatype<unsigned char>()
{
    return MPI_UNSIGNED_CHAR;
}

template <>
MPI_Datatype Comm::Datatype<unsigned short>()
{
    return MPI_UNSIGNED_SHORT;
}

template <>
MPI_Datatype Comm::Datatype<unsigned int>()
{
    return MPI_UNSIGNED;
}

template <>
MPI_Datatype Comm::Datatype<unsigned long>()
{
    return MPI_UNSIGNED_LONG;
}

template <>
MPI_Datatype Comm::Datatype<unsigned long long>()
{
    return MPI_UNSIGNED_LONG_LONG;
}

template <>
MPI_Datatype Comm::Datatype<long long>()
{
    return MPI_LONG_LONG_INT;
}

template <>
MPI_Datatype Comm::Datatype<double>()
{
    return MPI_DOUBLE;
}

template <>
MPI_Datatype Comm::Datatype<long double>()
{
    return MPI_LONG_DOUBLE;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<int, int>>()
{
    return MPI_2INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<float, int>>()
{
    return MPI_FLOAT_INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<double, int>>()
{
    return MPI_DOUBLE_INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<long double, int>>()
{
    return MPI_LONG_DOUBLE_INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<short, int>>()
{
    return MPI_SHORT_INT;
}

} // end namespace helper
} // end namespace adios2

#endif /* ADIOS2_HELPER_ADIOSCOMM_TCC_ */
<commit_msg>helper: Implement Comm::GatherArrays in terms of our encapsulation<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * adiosComm.tcc : specialization of template functions defined in
 * adiosComm.h
 */

#ifndef ADIOS2_HELPER_ADIOSCOMM_TCC_
#define ADIOS2_HELPER_ADIOSCOMM_TCC_

#include "adiosComm.h"

#include "adios2/common/ADIOSMPI.h"

#include <stdexcept> //std::runtime_error

namespace adios2
{
namespace helper
{

namespace
{

std::vector<size_t> GetGathervDisplacements(const size_t *counts,
                                            const size_t countsSize)
{
    std::vector<size_t> displacements(countsSize);
    displacements[0] = 0;

    for (size_t i = 1; i < countsSize; ++i)
    {
        displacements[i] = displacements[i - 1] + counts[i - 1];
    }
    return displacements;
}

}

// GatherArrays full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::GatherArrays(const char *source, size_t sourceCount,
                        char *destination, int rankDestination) const
{
    this->Gather(source, sourceCount, destination, sourceCount,
                 rankDestination);
}

template <>
void Comm::GatherArrays(const size_t *source, size_t sourceCount,
                        size_t *destination, int rankDestination) const
{
    this->Gather(source, sourceCount, destination, sourceCount,
                 rankDestination);
}

// GathervArrays full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::GathervArrays(const char *source, size_t sourceCount,
                         const size_t *counts, size_t countsSize,
                         char *destination, int rankDestination) const
{
    std::vector<size_t> displs;
    if (rankDestination == this->Rank())
    {
        displs = GetGathervDisplacements(counts, countsSize);
    }
    this->Gatherv(source, sourceCount, destination, counts, displs.data(),
                  rankDestination);
}

template <>
void Comm::GathervArrays(const size_t *source, size_t sourceCount,
                         const size_t *counts, size_t countsSize,
                         size_t *destination, int rankDestination) const
{
    std::vector<size_t> displs;
    if (rankDestination == this->Rank())
    {
        displs = GetGathervDisplacements(counts, countsSize);
    }
    this->Gatherv(source, sourceCount, destination, counts, displs.data(),
                  rankDestination);
}

// AllGatherArrays full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::AllGatherArrays(const size_t *source, const size_t sourceCount,
                           size_t *destination) const
{
    int countsInt = static_cast<int>(sourceCount);
    int result = MPI_Allgather(const_cast<size_t *>(source), countsInt,
                               ADIOS2_MPI_SIZE_T, destination, countsInt,
                               ADIOS2_MPI_SIZE_T, m_MPIComm);

    if (result != MPI_SUCCESS)
    {
        throw std::runtime_error("ERROR: in ADIOS2 detected failure in MPI "
                                 "Allgather type size_t function\n");
    }
}

// ReduceValues full specializations forward-declared in 'adiosComm.inl'.
template <>
unsigned int Comm::ReduceValues(const unsigned int source, MPI_Op operation,
                                const int rankDestination) const
{
    unsigned int sourceLocal = source;
    unsigned int reduceValue = 0;
    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED, operation,
                rankDestination, m_MPIComm);
    return reduceValue;
}

template <>
unsigned long int Comm::ReduceValues(const unsigned long int source,
                                     MPI_Op operation,
                                     const int rankDestination) const
{
    unsigned long int sourceLocal = source;
    unsigned long int reduceValue = 0;
    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG, operation,
                rankDestination, m_MPIComm);
    return reduceValue;
}

template <>
unsigned long long int Comm::ReduceValues(const unsigned long long int source,
                                          MPI_Op operation,
                                          const int rankDestination) const
{
    unsigned long long int sourceLocal = source;
    unsigned long long int reduceValue = 0;
    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG_LONG,
                operation, rankDestination, m_MPIComm);
    return reduceValue;
}

// BroadcastValue full specializations forward-declared in 'adiosComm.inl'.
template <>
size_t Comm::BroadcastValue(const size_t &input, const int rankSource) const
{
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);
    size_t output = 0;

    if (rank == rankSource)
    {
        output = input;
    }

    SMPI_Bcast(&output, 1, ADIOS2_MPI_SIZE_T, rankSource, m_MPIComm);

    return output;
}

template <>
std::string Comm::BroadcastValue(const std::string &input,
                                 const int rankSource) const
{
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);
    const size_t inputSize = input.size();
    const size_t length = this->BroadcastValue(inputSize, rankSource);
    std::string output;

    if (rank == rankSource)
    {
        output = input;
    }
    else
    {
        output.resize(length);
    }

    SMPI_Bcast(const_cast<char *>(output.data()), static_cast<int>(length),
               MPI_CHAR, rankSource, m_MPIComm);

    return output;
}

// BroadcastVector full specializations forward-declared in 'adiosComm.inl'.
template <>
void Comm::BroadcastVector(std::vector<char> &vector,
                           const int rankSource) const
{
    int size;
    SMPI_Comm_size(m_MPIComm, &size);

    if (size == 1)
    {
        return;
    }

    // First Broadcast the size, then the contents
    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);

    if (rank != rankSource)
    {
        vector.resize(inputSize);
    }

    const int MAXBCASTSIZE = 1073741824;
    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    char *buffer = vector.data();
    while (inputSize > 0)
    {
        SMPI_Bcast(buffer, static_cast<int>(blockSize), MPI_CHAR, rankSource,
                   m_MPIComm);
        buffer += blockSize;
        inputSize -= blockSize;
        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    }
}

template <>
void Comm::BroadcastVector(std::vector<size_t> &vector,
                           const int rankSource) const
{
    int size;
    SMPI_Comm_size(m_MPIComm, &size);

    if (size == 1)
    {
        return;
    }

    // First Broadcast the size, then the contents
    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);
    int rank;
    SMPI_Comm_rank(m_MPIComm, &rank);

    if (rank != rankSource)
    {
        vector.resize(inputSize);
    }

    const int MAXBCASTSIZE = 1073741824 / sizeof(size_t);
    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    size_t *buffer = vector.data();
    while (inputSize > 0)
    {
        SMPI_Bcast(buffer, static_cast<int>(blockSize), ADIOS2_MPI_SIZE_T,
                   rankSource, m_MPIComm);
        buffer += blockSize;
        inputSize -= blockSize;
        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);
    }
}

// Datatype full specializations forward-declared in 'adiosComm.inl'.
template <>
MPI_Datatype Comm::Datatype<signed char>()
{
    return MPI_SIGNED_CHAR;
}

template <>
MPI_Datatype Comm::Datatype<char>()
{
    return MPI_CHAR;
}

template <>
MPI_Datatype Comm::Datatype<short>()
{
    return MPI_SHORT;
}

template <>
MPI_Datatype Comm::Datatype<int>()
{
    return MPI_INT;
}

template <>
MPI_Datatype Comm::Datatype<long>()
{
    return MPI_LONG;
}

template <>
MPI_Datatype Comm::Datatype<unsigned char>()
{
    return MPI_UNSIGNED_CHAR;
}

template <>
MPI_Datatype Comm::Datatype<unsigned short>()
{
    return MPI_UNSIGNED_SHORT;
}

template <>
MPI_Datatype Comm::Datatype<unsigned int>()
{
    return MPI_UNSIGNED;
}

template <>
MPI_Datatype Comm::Datatype<unsigned long>()
{
    return MPI_UNSIGNED_LONG;
}

template <>
MPI_Datatype Comm::Datatype<unsigned long long>()
{
    return MPI_UNSIGNED_LONG_LONG;
}

template <>
MPI_Datatype Comm::Datatype<long long>()
{
    return MPI_LONG_LONG_INT;
}

template <>
MPI_Datatype Comm::Datatype<double>()
{
    return MPI_DOUBLE;
}

template <>
MPI_Datatype Comm::Datatype<long double>()
{
    return MPI_LONG_DOUBLE;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<int, int>>()
{
    return MPI_2INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<float, int>>()
{
    return MPI_FLOAT_INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<double, int>>()
{
    return MPI_DOUBLE_INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<long double, int>>()
{
    return MPI_LONG_DOUBLE_INT;
}

template <>
MPI_Datatype Comm::Datatype<std::pair<short, int>>()
{
    return MPI_SHORT_INT;
}

} // end namespace helper
} // end namespace adios2

#endif /* ADIOS2_HELPER_ADIOSCOMM_TCC_ */
<|endoftext|>


<commit_before>#include "gum/TextboxSprLoader.h"
#include "gum/TextboxLoader.h"
#include "gum/Config.h"

#include <sprite2/TextboxSprite.h>
#include <sprite2/TextTable.h>
#include <sprite2/UpdateParams.h>
#include <simp/NodeLabel.h>

namespace gum
{

TextboxSprLoader::TextboxSprLoader(s2::TextboxSprite& spr)
	: m_spr(spr)
{
}

void TextboxSprLoader::LoadJson(const Json::Value& val)
{
	const Json::Value& text_val = val["text"];

	TextboxLoader loader(m_spr.GetTextbox());
	loader.LoadJson(text_val);

	CU_STR text = text_val["text"].asString().c_str();
	if (text.empty()) {
		text = s2::TextTable::Instance()->Query(
			Config::Instance()->GetLanguage(), text_val["tid"].asString().c_str());
	}
	m_spr.SetText(s2::UpdateParams(), text);
}

void TextboxSprLoader::LoadBin(const simp::NodeLabel* node)
{
	TextboxLoader loader(m_spr.GetTextbox());
	loader.LoadBin(node);

	if (node->text) {
		m_spr.SetText(s2::UpdateParams(), node->text);
	} else if (node->tid) {
		auto text = s2::TextTable::Instance()->Query(
			Config::Instance()->GetLanguage(), node->tid);
		m_spr.SetText(s2::UpdateParams(), text);
	}
}

}<commit_msg>[CHANGED] up s2, add tid<commit_after>#include "gum/TextboxSprLoader.h"
#include "gum/TextboxLoader.h"
#include "gum/Config.h"

#include <sprite2/TextboxSprite.h>
#include <sprite2/TextTable.h>
#include <sprite2/UpdateParams.h>
#include <simp/NodeLabel.h>

namespace gum
{

TextboxSprLoader::TextboxSprLoader(s2::TextboxSprite& spr)
	: m_spr(spr)
{
}

void TextboxSprLoader::LoadJson(const Json::Value& val)
{
	const Json::Value& text_val = val["text"];

	TextboxLoader loader(m_spr.GetTextbox());
	loader.LoadJson(text_val);

	CU_STR text = text_val["text"].asString().c_str();
	if (text.empty()) {
		text = s2::TextTable::Instance()->Query(
			Config::Instance()->GetLanguage(), text_val["tid"].asString().c_str());
	}
	m_spr.SetText(s2::UpdateParams(), text);

	CU_STR tid = text_val["text"].asString().c_str();
	m_spr.SetTID(tid);
}

void TextboxSprLoader::LoadBin(const simp::NodeLabel* node)
{
	TextboxLoader loader(m_spr.GetTextbox());
	loader.LoadBin(node);

	if (node->text) {
		m_spr.SetText(s2::UpdateParams(), node->text);
	} else if (node->tid) {
		auto text = s2::TextTable::Instance()->Query(
			Config::Instance()->GetLanguage(), node->tid);
		m_spr.SetText(s2::UpdateParams(), text);
	}
}

}<|endoftext|>


<commit_before><commit_msg>Do not use QOverload for compatibility with older Qt5 (Linux Mint) Fixes #30<commit_after><|endoftext|>