<commit_before>extern "C" {
#include "keystate/keystate_ds_submit_task.h"
#include "shared/file.h"
#include "shared/duration.h"
#include "libhsm.h"
#include "libhsmdns.h"
}

#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>

#include "keystate/keystate.pb.h"
#include "xmlext-pb/xmlext-rd.h"

#include <fcntl.h>

static const char *module_str = "keystate_ds_submit_task";

static bool submit_dnskey_by_id(int sockfd,
                                const char *ds_submit_command,
                                const char *id,
                                ::ods::keystate::keyrole role,
                                const char *zone,
                                int algorithm)
{
    char buf[ODS_SE_MAXLINE];

    /* Code to output the DNSKEY record  (stolen from hsmutil) */
    hsm_key_t *key = hsm_find_key_by_id(NULL, id);

    if (!key) {
        ods_log_error("[%s] key %s not found in any HSM",
                      module_str,id);
        (void)snprintf(buf,ODS_SE_MAXLINE, "key %s not found in any HSM\n", id);
        ods_writen(sockfd, buf, strlen(buf));
        return false;
    }

    bool bOK = false;
    char *dnskey_rr_str;

    hsm_sign_params_t *sign_params = hsm_sign_params_new();
    sign_params->owner = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_DNAME, zone);
    sign_params->algorithm = (ldns_algorithm)algorithm;
    sign_params->flags = LDNS_KEY_ZONE_KEY;
    sign_params->flags += LDNS_KEY_SEP_KEY; /*KSK=>SEP*/

    ldns_rr *dnskey_rr = hsm_get_dnskey(NULL, key, sign_params);
#if 0
    ldns_rr_print(stdout, dnskey_rr);
#endif
    dnskey_rr_str = ldns_rr2str(dnskey_rr);

    hsm_sign_params_free(sign_params);
    ldns_rr_free(dnskey_rr);
    hsm_key_free(key);

    /* Replace tab with white-space */
    for (int i = 0; dnskey_rr_str[i]; ++i) {
        if (dnskey_rr_str[i] == '\t') {
            dnskey_rr_str[i] = ' ';
        }
    }

    /* We need to strip off trailing comments before we send
     to any clients that might be listening */
    for (int i = 0; dnskey_rr_str[i]; ++i) {
        if (dnskey_rr_str[i] == ';') {
            dnskey_rr_str[i] = '\n';
            dnskey_rr_str[i+1] = '\0';
            break;
        }
    }

    // submit the dnskey rr string to a configured
    // delegation signer submit program.
    if (ds_submit_command && ds_submit_command[0] != '\0') {
        /* send records to the configured command */
        FILE *fp = popen(ds_submit_command, "w");
        if (fp == NULL) {
            ods_log_error("[%s] Failed to run command: %s: %s",
                          module_str,ds_submit_command,strerror(errno));
            (void)snprintf(buf,ODS_SE_MAXLINE,"failed to run command: %s: %s\n",
                           ds_submit_command,strerror(errno));
            ods_writen(sockfd, buf, strlen(buf));

        } else {
            int bytes_written = fprintf(fp, "%s", dnskey_rr_str);
            if (bytes_written < 0) {
                ods_log_error("[%s] Failed to write to %s: %s",
                              module_str,ds_submit_command,strerror(errno));
                (void)snprintf(buf,ODS_SE_MAXLINE,"failed to write to %s: %s\n",
                               ds_submit_command,strerror(errno));
                               ods_writen(sockfd, buf, strlen(buf));

            } else {

                if (pclose(fp) == -1) {

                    ods_log_error("[%s] Failed to close %s: %s",
                                  module_str,ds_submit_command,strerror(errno));
                    (void)snprintf(buf,ODS_SE_MAXLINE,"failed to close %s: %s\n",
                                   ds_submit_command,strerror(errno));
                    ods_writen(sockfd, buf, strlen(buf));

                } else {
                    bOK = true;
                    (void)snprintf(buf,ODS_SE_MAXLINE,
                                   "key %s submitted to %s\n",
                                   id, ds_submit_command);
                    ods_writen(sockfd, buf, strlen(buf));
                }
            }
        }
    } else {
        ods_log_error("[%s] No Delegation Signer Submit Command configured "
                      "in conf.xml.",module_str);
        (void)snprintf(buf,ODS_SE_MAXLINE,
                       "no ds submit command configured in conf.xml.\n");
        ods_writen(sockfd, buf, strlen(buf));
    }

    LDNS_FREE(dnskey_rr_str);

    // Once the new DS records are seen in DNS please issue the ds-seen
    // command for zone %s with the following cka_ids %s
    return bOK;
}

void
perform_keystate_ds_submit(int sockfd, engineconfig_type *config,
                           const char *zone, const char *id, int bauto)
{
    char buf[ODS_SE_MAXLINE];
    const char *datastore = config->datastore;
    const char *ds_submit_command = config->delegation_signer_submit_command;

	GOOGLE_PROTOBUF_VERIFY_VERSION;

    ::ods::keystate::KeyStateDocument *keystateDoc =
    new ::ods::keystate::KeyStateDocument;
    {
        std::string datapath(datastore);
        datapath += ".keystate.pb";
        int fd = open(datapath.c_str(),O_RDONLY);
        if (keystateDoc->ParseFromFileDescriptor(fd)) {
            ods_log_debug("[%s] keys have been loaded",
                          module_str);
        } else {
            ods_log_error("[%s] keys could not be loaded from \"%s\"",
                          module_str,datapath.c_str());
        }
        close(fd);
    }

    // Evalutate parameters and submit keys to the parent when instructed
    // to do so.
    if (id || zone || bauto) {
        bool bFlagsChanged = false;
        for (int z=0; z<keystateDoc->zones_size(); ++z) {
            const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
            for (int k=0; k<enfzone.keys_size(); ++k) {
                const ::ods::keystate::KeyData &key = enfzone.keys(k);

                // Don't ever submit ZSKs to the parent.
                if (key.role()==::ods::keystate::ZSK)
                    continue;

                if (id) {
                    // --id <id>
                    //     Force submit key to the parent for specific key id.
                    if (key.locator()==id) {
                        // submit key with this id to the parent
                        if (submit_dnskey_by_id(sockfd,ds_submit_command,
                                            key.locator().c_str(),
                                            key.role(),
                                            enfzone.name().c_str(),
                                            key.algorithm()))
                        {
                            bFlagsChanged = true;
                            keystateDoc->mutable_zones(z)->mutable_keys(k)
                                ->set_submit_to_parent(false);
                        }
                    }
                } else {
                    if (zone) {
                        // --zone <zone>
                        //     Force submit key to the parent for specific zone.
                        if (enfzone.name()==zone) {
                            // submit key for this zone to the parent
                            if (submit_dnskey_by_id(sockfd,ds_submit_command,
                                                key.locator().c_str(),
                                                key.role(),
                                                enfzone.name().c_str(),
                                                key.algorithm()))
                            {
                                bFlagsChanged = true;
                                keystateDoc->mutable_zones(z)->mutable_keys(k)
                                    ->set_submit_to_parent(false);
                            }
                        }
                    } else {
                        // --auto
                        //     Submit keys to the parent that have
                        //     the "submit to parent" flag set.
                        if (key.submit_to_parent()) {
                            // only submit the key to the parent when flag is set.
                            if (submit_dnskey_by_id(sockfd,ds_submit_command,
                                                key.locator().c_str(),
                                                key.role(),
                                                enfzone.name().c_str(),
                                                key.algorithm()))
                            {
                                bFlagsChanged = true;
                                keystateDoc->mutable_zones(z)->mutable_keys(k)
                                    ->set_submit_to_parent(false);
                            }
                        }
                    }
                }
            }
        }

        if (bFlagsChanged) {
            // Persist the keystate zones back to disk as they may have
            // been changed by the enforcer update
            if (keystateDoc->IsInitialized()) {
                std::string datapath(datastore);
                datapath += ".keystate.pb";
                int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
                if (keystateDoc->SerializeToFileDescriptor(fd)) {
                    ods_log_debug("[%s] key states have been updated",
                                  module_str);

                    (void)snprintf(buf, ODS_SE_MAXLINE,
                                   "update of key states completed.\n");
                    ods_writen(sockfd, buf, strlen(buf));
                } else {
                    (void)snprintf(buf, ODS_SE_MAXLINE,
                                   "error: key states file could not be written.\n");
                    ods_writen(sockfd, buf, strlen(buf));
                }
                close(fd);
            } else {
                (void)snprintf(buf, ODS_SE_MAXLINE,
                               "error: a message in the key states is missing "
                               "mandatory information.\n");
                ods_writen(sockfd, buf, strlen(buf));
            }
        }

        return;
    }

    // List the keys with ds-submit flags.
    (void)snprintf(buf, ODS_SE_MAXLINE,
                   "Database set to: %s\n"
                   "Keys:\n"
                   "Zone:                           "
                   "Key role:     "
                   "Id:                                      "
                   "Should Submit: "
                   "\n"
                   ,datastore
                   );
    ods_writen(sockfd, buf, strlen(buf));
    for (int z=0; z<keystateDoc->zones_size(); ++z) {
        const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
        for (int k=0; k<enfzone.keys_size(); ++k) {
            const ::ods::keystate::KeyData &key = enfzone.keys(k);
            // Don't suggest ZSKs can be submitted, leave them out of the list.
            if (key.role() == ::ods::keystate::ZSK)
                continue;
            std::string keyrole = keyrole_Name(key.role());
            const char *action = key.submit_to_parent() ? "yes" : "no";
            (void)snprintf(buf, ODS_SE_MAXLINE,
                           "%-31s %-13s %-40s %-14s\n",
                           enfzone.name().c_str(),
                           keyrole.c_str(),
                           key.locator().c_str(),
                           action
                           );
            ods_writen(sockfd, buf, strlen(buf));
        }
    }
}

static task_type *
keystate_ds_submit_task_perform(task_type *task)
{
    perform_keystate_ds_submit(-1,(engineconfig_type *)task->context,NULL,NULL,
                               1);
    task_cleanup(task);
    return NULL;
}

task_type *
keystate_ds_submit_task(engineconfig_type *config, const char *what,
                        const char *who)
{
    task_id what_id = task_register(what, "keystate_ds_submit_task_perform",
                                    keystate_ds_submit_task_perform);
	return task_create(what_id, time_now(), who, (void*)config);
}
<commit_msg>Don't show 'key ds-submit' keys that have ds-seen flag set true because they are no longer of any interest w.r.t. submitting to the parent.<commit_after>extern "C" {
#include "keystate/keystate_ds_submit_task.h"
#include "shared/file.h"
#include "shared/duration.h"
#include "libhsm.h"
#include "libhsmdns.h"
}

#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>

#include "keystate/keystate.pb.h"
#include "xmlext-pb/xmlext-rd.h"

#include <fcntl.h>

static const char *module_str = "keystate_ds_submit_task";

static bool submit_dnskey_by_id(int sockfd,
                                const char *ds_submit_command,
                                const char *id,
                                ::ods::keystate::keyrole role,
                                const char *zone,
                                int algorithm)
{
    char buf[ODS_SE_MAXLINE];

    /* Code to output the DNSKEY record  (stolen from hsmutil) */
    hsm_key_t *key = hsm_find_key_by_id(NULL, id);

    if (!key) {
        ods_log_error("[%s] key %s not found in any HSM",
                      module_str,id);
        (void)snprintf(buf,ODS_SE_MAXLINE, "key %s not found in any HSM\n", id);
        ods_writen(sockfd, buf, strlen(buf));
        return false;
    }

    bool bOK = false;
    char *dnskey_rr_str;

    hsm_sign_params_t *sign_params = hsm_sign_params_new();
    sign_params->owner = ldns_rdf_new_frm_str(LDNS_RDF_TYPE_DNAME, zone);
    sign_params->algorithm = (ldns_algorithm)algorithm;
    sign_params->flags = LDNS_KEY_ZONE_KEY;
    sign_params->flags += LDNS_KEY_SEP_KEY; /*KSK=>SEP*/

    ldns_rr *dnskey_rr = hsm_get_dnskey(NULL, key, sign_params);
#if 0
    ldns_rr_print(stdout, dnskey_rr);
#endif
    dnskey_rr_str = ldns_rr2str(dnskey_rr);

    hsm_sign_params_free(sign_params);
    ldns_rr_free(dnskey_rr);
    hsm_key_free(key);

    /* Replace tab with white-space */
    for (int i = 0; dnskey_rr_str[i]; ++i) {
        if (dnskey_rr_str[i] == '\t') {
            dnskey_rr_str[i] = ' ';
        }
    }

    /* We need to strip off trailing comments before we send
     to any clients that might be listening */
    for (int i = 0; dnskey_rr_str[i]; ++i) {
        if (dnskey_rr_str[i] == ';') {
            dnskey_rr_str[i] = '\n';
            dnskey_rr_str[i+1] = '\0';
            break;
        }
    }

    // submit the dnskey rr string to a configured
    // delegation signer submit program.
    if (ds_submit_command && ds_submit_command[0] != '\0') {
        /* send records to the configured command */
        FILE *fp = popen(ds_submit_command, "w");
        if (fp == NULL) {
            ods_log_error("[%s] Failed to run command: %s: %s",
                          module_str,ds_submit_command,strerror(errno));
            (void)snprintf(buf,ODS_SE_MAXLINE,"failed to run command: %s: %s\n",
                           ds_submit_command,strerror(errno));
            ods_writen(sockfd, buf, strlen(buf));

        } else {
            int bytes_written = fprintf(fp, "%s", dnskey_rr_str);
            if (bytes_written < 0) {
                ods_log_error("[%s] Failed to write to %s: %s",
                              module_str,ds_submit_command,strerror(errno));
                (void)snprintf(buf,ODS_SE_MAXLINE,"failed to write to %s: %s\n",
                               ds_submit_command,strerror(errno));
                               ods_writen(sockfd, buf, strlen(buf));

            } else {

                if (pclose(fp) == -1) {

                    ods_log_error("[%s] Failed to close %s: %s",
                                  module_str,ds_submit_command,strerror(errno));
                    (void)snprintf(buf,ODS_SE_MAXLINE,"failed to close %s: %s\n",
                                   ds_submit_command,strerror(errno));
                    ods_writen(sockfd, buf, strlen(buf));

                } else {
                    bOK = true;
                    (void)snprintf(buf,ODS_SE_MAXLINE,
                                   "key %s submitted to %s\n",
                                   id, ds_submit_command);
                    ods_writen(sockfd, buf, strlen(buf));
                }
            }
        }
    } else {
        ods_log_error("[%s] No Delegation Signer Submit Command configured "
                      "in conf.xml.",module_str);
        (void)snprintf(buf,ODS_SE_MAXLINE,
                       "no ds submit command configured in conf.xml.\n");
        ods_writen(sockfd, buf, strlen(buf));
    }

    LDNS_FREE(dnskey_rr_str);

    // Once the new DS records are seen in DNS please issue the ds-seen
    // command for zone %s with the following cka_ids %s
    return bOK;
}

void
perform_keystate_ds_submit(int sockfd, engineconfig_type *config,
                           const char *zone, const char *id, int bauto)
{
    char buf[ODS_SE_MAXLINE];
    const char *datastore = config->datastore;
    const char *ds_submit_command = config->delegation_signer_submit_command;

	GOOGLE_PROTOBUF_VERIFY_VERSION;

    ::ods::keystate::KeyStateDocument *keystateDoc =
    new ::ods::keystate::KeyStateDocument;
    {
        std::string datapath(datastore);
        datapath += ".keystate.pb";
        int fd = open(datapath.c_str(),O_RDONLY);
        if (keystateDoc->ParseFromFileDescriptor(fd)) {
            ods_log_debug("[%s] keys have been loaded",
                          module_str);
        } else {
            ods_log_error("[%s] keys could not be loaded from \"%s\"",
                          module_str,datapath.c_str());
        }
        close(fd);
    }

    // Evalutate parameters and submit keys to the parent when instructed
    // to do so.
    if (id || zone || bauto) {
        bool bFlagsChanged = false;
        for (int z=0; z<keystateDoc->zones_size(); ++z) {
            const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
            for (int k=0; k<enfzone.keys_size(); ++k) {
                const ::ods::keystate::KeyData &key = enfzone.keys(k);

                // Don't ever submit ZSKs to the parent.
                if (key.role()==::ods::keystate::ZSK || key.ds_seen())
                    continue;

                if (id) {
                    // --id <id>
                    //     Force submit key to the parent for specific key id.
                    if (key.locator()==id) {
                        // submit key with this id to the parent
                        if (submit_dnskey_by_id(sockfd,ds_submit_command,
                                            key.locator().c_str(),
                                            key.role(),
                                            enfzone.name().c_str(),
                                            key.algorithm()))
                        {
                            bFlagsChanged = true;
                            keystateDoc->mutable_zones(z)->mutable_keys(k)
                                ->set_submit_to_parent(false);
                        }
                    }
                } else {
                    if (zone) {
                        // --zone <zone>
                        //     Force submit key to the parent for specific zone.
                        if (enfzone.name()==zone) {
                            // submit key for this zone to the parent
                            if (submit_dnskey_by_id(sockfd,ds_submit_command,
                                                key.locator().c_str(),
                                                key.role(),
                                                enfzone.name().c_str(),
                                                key.algorithm()))
                            {
                                bFlagsChanged = true;
                                keystateDoc->mutable_zones(z)->mutable_keys(k)
                                    ->set_submit_to_parent(false);
                            }
                        }
                    } else {
                        // --auto
                        //     Submit keys to the parent that have
                        //     the "submit to parent" flag set.
                        if (key.submit_to_parent()) {
                            // only submit the key to the parent when flag is set.
                            if (submit_dnskey_by_id(sockfd,ds_submit_command,
                                                key.locator().c_str(),
                                                key.role(),
                                                enfzone.name().c_str(),
                                                key.algorithm()))
                            {
                                bFlagsChanged = true;
                                keystateDoc->mutable_zones(z)->mutable_keys(k)
                                    ->set_submit_to_parent(false);
                            }
                        }
                    }
                }
            }
        }

        if (bFlagsChanged) {
            // Persist the keystate zones back to disk as they may have
            // been changed by the enforcer update
            if (keystateDoc->IsInitialized()) {
                std::string datapath(datastore);
                datapath += ".keystate.pb";
                int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
                if (keystateDoc->SerializeToFileDescriptor(fd)) {
                    ods_log_debug("[%s] key states have been updated",
                                  module_str);

                    (void)snprintf(buf, ODS_SE_MAXLINE,
                                   "update of key states completed.\n");
                    ods_writen(sockfd, buf, strlen(buf));
                } else {
                    (void)snprintf(buf, ODS_SE_MAXLINE,
                                   "error: key states file could not be written.\n");
                    ods_writen(sockfd, buf, strlen(buf));
                }
                close(fd);
            } else {
                (void)snprintf(buf, ODS_SE_MAXLINE,
                               "error: a message in the key states is missing "
                               "mandatory information.\n");
                ods_writen(sockfd, buf, strlen(buf));
            }
        }

        return;
    }

    // List the keys with ds-submit flags.
    (void)snprintf(buf, ODS_SE_MAXLINE,
                   "Database set to: %s\n"
                   "Keys:\n"
                   "Zone:                           "
                   "Key role:     "
                   "Id:                                      "
                   "Should Submit: "
                   "\n"
                   ,datastore
                   );
    ods_writen(sockfd, buf, strlen(buf));
    for (int z=0; z<keystateDoc->zones_size(); ++z) {
        const ::ods::keystate::EnforcerZone &enfzone  = keystateDoc->zones(z);
        for (int k=0; k<enfzone.keys_size(); ++k) {
            const ::ods::keystate::KeyData &key = enfzone.keys(k);
            // Don't suggest ZSKs can be submitted, leave them out of the list.
            if (key.role() == ::ods::keystate::ZSK || key.ds_seen())
                continue;
            std::string keyrole = keyrole_Name(key.role());
            const char *action = key.submit_to_parent() ? "yes" : "no";
            (void)snprintf(buf, ODS_SE_MAXLINE,
                           "%-31s %-13s %-40s %-14s\n",
                           enfzone.name().c_str(),
                           keyrole.c_str(),
                           key.locator().c_str(),
                           action
                           );
            ods_writen(sockfd, buf, strlen(buf));
        }
    }
}

static task_type *
keystate_ds_submit_task_perform(task_type *task)
{
    perform_keystate_ds_submit(-1,(engineconfig_type *)task->context,NULL,NULL,
                               1);
    task_cleanup(task);
    return NULL;
}

task_type *
keystate_ds_submit_task(engineconfig_type *config, const char *what,
                        const char *who)
{
    task_id what_id = task_register(what, "keystate_ds_submit_task_perform",
                                    keystate_ds_submit_task_perform);
	return task_create(what_id, time_now(), who, (void*)config);
}
<|endoftext|>


<commit_before>AliAnalysisTask *AddTaskHFEpPb(Bool_t isAOD = kFALSE){
  // Switches for the TOF-TPC analysis
  Bool_t kTPC_Only                   = kTRUE;
  Bool_t kTPCTOF_Ref                 = kTRUE;
  Bool_t kTPCTOF_Sys                 = kFALSE;
  Bool_t kTRD_Test                   = kFALSE;
  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_hfe_HFE", "No analysis manager found.");
    return 0;
  }

  Bool_t MCthere=kTRUE;
  AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  if(!mcH){
    MCthere=kFALSE;
  }

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();

  //@@ 0 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  // Default settings
  const int kDefITScl = 3;
  const int kDefTPCcl = 110;
  const int kDefTPCclPID = 80;
  const double kDefDCAr = 1.;
  const double kDefDCAz = 2.;
  // For pPb, new fits by Martin, 07.02.2013
  const double kDefTPCs = 0.045;
  // it seems the sigma is 1 and not 0.88 (3 sigma = 2.685)
  const double kDefTPCu = 3.045;
  const double kDefTOFs = 3.;

  Double_t dEdxlm[12] = {0.045,0.045,0.045,0.045,0.045,0.045,0.045,0.045,0.045,0.045,0.045,0.045};  //  50%
  Double_t dEdxhm[12] = {2.685,2.685,2.685,2.685,2.685,2.685,2.685,2.685,2.685,2.685,2.685,2.685};
  // For systematics:
  Double_t tpcl0[12]  = {-0.835,-0.835,-0.835,-0.835,-0.835,-0.835,-0.835,-0.835,-0.835,-0.835,-0.835,-0.835};  //  84%
  Double_t tpcl1[12]  = {-0.184,-0.184,-0.184,-0.184,-0.184,-0.184,-0.184,-0.184,-0.184,-0.184,-0.184,-0.184};  //  60%
  Double_t tpcl2[12]  = {0.265,0.265,0.265,0.265,0.265,0.265,0.265,0.265,0.265,0.265,0.265,0.265};  //   40%

  // For TPC only
  const double kDefTPCs1 = 0.034;
  const double kDefTPCu1 = 2.674;

  if(kTPC_Only){
    // for the moment (09.02.2013) use the same as TOF-TPC. Refine later on
    RegisterTaskPID2(MCthere,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,0,0,AliHFEextraCuts::kBoth);
  }

  //------------------------------//
  //   TPC-TOF analysis
  //------------------------------//

  if(kTPCTOF_Ref){
    // Reference task
     // Fits by Martin 07.02.2013
    // mean = 0.045
    // sigma = 0.88
    // 50%
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,0.295,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);

    // add centrality
    RegisterTask(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,&dEdxlm[0],&dEdxhm[0],kDefTOFs,0,AliHFEextraCuts::kBoth); // 50%
    //if (!MCthere){
    //  RegisterTask(MCthere,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,&tpcl0[0],&dEdxhm[0],kDefTOFs,0,AliHFEextraCuts::kBoth);  // 84%
    //}
  }
  if(kTPCTOF_Sys){

    // TPC PID
    if (!MCthere){
      // 84%
      RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,-0.835,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
      // 60%
      RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,-0.184,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
      // 40%
      RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,0.265,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    }

    // TOF PID
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,2.0,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,4.0,0,AliHFEextraCuts::kBoth);
    // TOF latest mismatch - helps nothing
    //RegisterTaskPID2(MCthere,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,1,AliHFEextraCuts::kBoth);

    // ITS hits and SPD request
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,4,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,5,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,3,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kFirst);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,4,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kFirst);

    // TPC clusters
    RegisterTaskPID2(MCthere,isAOD,100,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,120,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,130,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    // TPC clusters PID
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,100,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);

  }

  return NULL;
}

//===============================================================================

AliAnalysisTask *RegisterTask(Bool_t useMC, Bool_t isAOD, Int_t tpcCls=120, Int_t tpcClsPID = 80,
			      Int_t itsCls=4, Double_t dcaxy=1.0, Double_t dcaz=2.0,
			      Double_t *tpcdEdxcutlow=NULL,
			      Double_t *tpcdEdxcuthigh=NULL,
			      //Double_t tpcs=-0.0113, Double_t tpcu=3.09,
			      Double_t tofs=3., Int_t tofm=0,
			      Int_t itshitpixel = AliHFEextraCuts::kBoth,
			      Bool_t withetacorrection = kFALSE){

  Int_t idcaxy = (Int_t)(dcaxy*10.);
  Int_t idcaz = (Int_t)(dcaz*10.);
  Int_t tpclow = 0;
  if(tpcdEdxcutlow) tpclow = (Int_t) (tpcdEdxcutlow[0]*1000.);
  Int_t itofs = (Int_t)(tofs*10.);
  Int_t ipixelany = itshitpixel;
  Int_t ietacorr = 0;
  if(withetacorrection) ietacorr = 1;

  TString appendix(TString::Format("centTPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dm%ipa%d",tpcCls,
				   tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,tofm,ipixelany));
  printf("Add macro appendix %s\n", appendix.Data());

  gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/pPb/ConfigHFEpPb.C");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskHFE *task = ConfigHFEpPb(useMC, isAOD, appendix, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz,
					  tpcdEdxcutlow,tpcdEdxcuthigh,
					  tofs,tofm,itshitpixel);

  if(isAOD)
    task->SetAODAnalysis();
  else
    task->SetESDAnalysis();
  if (useMC)
    task->SetHasMCData(kTRUE);
  else{
    task->SetHasMCData(kFALSE);
  }
  task->SelectCollisionCandidates(AliVEvent::kINT7);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":HFEpPbcent";
  containerName += appendix.Data();
  printf("container name: %s\n", containerName.Data());

  //create data containers
  task->ConnectOutput(1, mgr->CreateContainer(Form("HFE_Results_%s", appendix.Data()),
					      TList::Class(), AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  task->ConnectOutput(2, mgr->CreateContainer(Form("HFE_QA_%s", appendix.Data()), TList::Class(),
					      AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  mgr->ConnectInput(task,  0, cinput );

  mgr->AddTask(task);
  return NULL;
}

//===============================================================================

AliAnalysisTask *RegisterTaskPID2(Bool_t useMC, Bool_t isAOD, Int_t tpcCls=120, Int_t tpcClsPID = 80,
				  Int_t itsCls=4, Double_t dcaxy=1.0, Double_t dcaz=2.0,
				  Double_t tpcs=-0.0113, Double_t tpcu=3.09, Double_t tofs=3.,
				  Int_t tofm=0,
				  Int_t itshitpixel = AliHFEextraCuts::kBoth,
				  Bool_t withetacorrection = kTRUE){
  gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/pPb/ConfigHFEmbpPb.C");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskHFE *task = ConfigHFEmbpPb(useMC, isAOD, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz,
					     tpcs,tpcu,tofs,tofm,3.,kFALSE,kTRUE,kFALSE,itshitpixel,withetacorrection);
  if()
    task->SetAODAnalysis();
  else
    task->SetESDAnalysis();
  if (useMC)
    task->SetHasMCData(kTRUE);
  else{
    task->SetHasMCData(kFALSE);
  }
  task->SelectCollisionCandidates(AliVEvent::kINT7);

  Int_t idcaxy = (Int_t)(dcaxy*10.);
  Int_t idcaz = (Int_t)(dcaz*10.);
  Int_t itpcs = (Int_t)(tpcs*1000.);
  Int_t itofs = (Int_t)(tofs*10.);
  Int_t ipixelany = itshitpixel;
  Int_t ietacorr = 0;
  if(withetacorrection) ietacorr = 1;

  TString appendix(TString::Format("TPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dm%ipa%d",tpcCls,
				   tpcClsPID,itsCls,idcaxy,idcaz,itpcs,itofs,tofm,ipixelany));
  printf("Add macro appendix %s\n", appendix.Data());

  TString containerName = mgr->GetCommonFileName();
  containerName += ":HFEpPbmb";
  containerName += appendix.Data();
  printf("container name: %s\n", containerName.Data());

  //create data containers
  task->ConnectOutput(1, mgr->CreateContainer(Form("HFE_Results_%s", appendix.Data()),
					      TList::Class(), AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  task->ConnectOutput(2, mgr->CreateContainer(Form("HFE_QA_%s", appendix.Data()), TList::Class(),
					      AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  mgr->ConnectInput(task,  0, cinput );

  mgr->AddTask(task);
  return NULL;
}

//=========================================================================
<commit_msg>updated<commit_after>AliAnalysisTask *AddTaskHFEpPb(Bool_t isAOD = kFALSE){
  // Switches for the TOF-TPC analysis
  Bool_t kTPC_Only                   = kTRUE;
  Bool_t kTPCTOF_Ref                 = kTRUE;
  Bool_t kTPCTOF_Sys                 = kFALSE;
  Bool_t kTRD_Test                   = kFALSE;
  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_hfe_HFE", "No analysis manager found.");
    return 0;
  }

  Bool_t MCthere=kTRUE;
  AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  if(!mcH){
    MCthere=kFALSE;
  }

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();

  //@@ 0 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  // Default settings
  const int kDefITScl = 3;
  const int kDefTPCcl = 110;
  const int kDefTPCclPID = 80;
  const double kDefDCAr = 1.;
  const double kDefDCAz = 2.;
  // For pPb, new fits by Martin, 07.02.2013
  const double kDefTPCs = 0.045;
  // it seems the sigma is 1 and not 0.88 (3 sigma = 2.685)
  const double kDefTPCu = 3.045;
  const double kDefTOFs = 3.;

  Double_t dEdxlm[12] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};  //  50%
  Double_t dEdxhm[12] = {3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0};
  // For systematics:
  Double_t tpcl0[12]  = {-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0};  //  84%
  Double_t tpcl1[12]  = {-0.26,-0.26,-0.26,-0.26,-0.26,-0.26,-0.26,-0.26,-0.26,-0.26,-0.26,-0.26};  //  60%
  Double_t tpcl2[12]  = {0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25,0.25};  //   40%

  // For TPC only
  const double kDefTPCs1 = 0.034;
  const double kDefTPCu1 = 2.674;

  if(kTPC_Only){
    // for the moment (09.02.2013) use the same as TOF-TPC. Refine later on
    RegisterTaskPID2(MCthere,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,0,0,AliHFEextraCuts::kBoth);
  }

  //------------------------------//
  //   TPC-TOF analysis
  //------------------------------//

  if(kTPCTOF_Ref){
    // Reference task
     // Fits by Martin 07.02.2013
    // mean = 0.045
    // sigma = 0.88
    // 50%
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,0.295,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);

    // add centrality
    RegisterTask(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,&dEdxlm[0],&dEdxhm[0],kDefTOFs,0,AliHFEextraCuts::kBoth); // 50%
    //if (!MCthere){
    //  RegisterTask(MCthere,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,&tpcl0[0],&dEdxhm[0],kDefTOFs,0,AliHFEextraCuts::kBoth);  // 84%
    //}
  }
  if(kTPCTOF_Sys){

    // TPC PID
    if (!MCthere){
      // 84%
      RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,-0.835,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
      // 60%
      RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,-0.184,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
      // 40%
      RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,0.265,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    }

    // TOF PID
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,2.0,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,4.0,0,AliHFEextraCuts::kBoth);
    // TOF latest mismatch - helps nothing
    //RegisterTaskPID2(MCthere,kDefTPCcl,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,1,AliHFEextraCuts::kBoth);

    // ITS hits and SPD request
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,4,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,5,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,3,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kFirst);
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,kDefTPCclPID,4,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kFirst);

    // TPC clusters
    RegisterTaskPID2(MCthere,isAOD,100,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,120,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    RegisterTaskPID2(MCthere,isAOD,130,kDefTPCclPID,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);
    // TPC clusters PID
    RegisterTaskPID2(MCthere,isAOD,kDefTPCcl,100,kDefITScl,kDefDCAr,kDefDCAz,kDefTPCs,kDefTPCu,kDefTOFs,0,AliHFEextraCuts::kBoth);

  }

  return NULL;
}

//===============================================================================

AliAnalysisTask *RegisterTask(Bool_t useMC, Bool_t isAOD, Int_t tpcCls=120, Int_t tpcClsPID = 80,
			      Int_t itsCls=4, Double_t dcaxy=1.0, Double_t dcaz=2.0,
			      Double_t *tpcdEdxcutlow=NULL,
			      Double_t *tpcdEdxcuthigh=NULL,
			      //Double_t tpcs=-0.0113, Double_t tpcu=3.09,
			      Double_t tofs=3., Int_t tofm=0,
			      Int_t itshitpixel = AliHFEextraCuts::kBoth,
			      Bool_t withetacorrection = kFALSE){

  Int_t idcaxy = (Int_t)(dcaxy*10.);
  Int_t idcaz = (Int_t)(dcaz*10.);
  Int_t tpclow = 0;
  if(tpcdEdxcutlow) tpclow = (Int_t) (tpcdEdxcutlow[0]*1000.);
  Int_t itofs = (Int_t)(tofs*10.);
  Int_t ipixelany = itshitpixel;
  Int_t ietacorr = 0;
  if(withetacorrection) ietacorr = 1;

  TString appendix(TString::Format("centTPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dm%ipa%d",tpcCls,
				   tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,tofm,ipixelany));
  printf("Add macro appendix %s\n", appendix.Data());

  gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/pPb/ConfigHFEpPb.C");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskHFE *task = ConfigHFEpPb(useMC, isAOD, appendix, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz,
					  tpcdEdxcutlow,tpcdEdxcuthigh,
					  tofs,tofm,itshitpixel);

  if(isAOD)
    task->SetAODAnalysis();
  else
    task->SetESDAnalysis();
  if (useMC)
    task->SetHasMCData(kTRUE);
  else{
    task->SetHasMCData(kFALSE);
  }
  task->SelectCollisionCandidates(AliVEvent::kINT7);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":HFEpPbcent";
  containerName += appendix.Data();
  printf("container name: %s\n", containerName.Data());

  //create data containers
  task->ConnectOutput(1, mgr->CreateContainer(Form("HFE_Results_%s", appendix.Data()),
					      TList::Class(), AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  task->ConnectOutput(2, mgr->CreateContainer(Form("HFE_QA_%s", appendix.Data()), TList::Class(),
					      AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  mgr->ConnectInput(task,  0, cinput );

  mgr->AddTask(task);
  return NULL;
}

//===============================================================================

AliAnalysisTask *RegisterTaskPID2(Bool_t useMC, Bool_t isAOD, Int_t tpcCls=120, Int_t tpcClsPID = 80,
				  Int_t itsCls=4, Double_t dcaxy=1.0, Double_t dcaz=2.0,
				  Double_t tpcs=-0.0113, Double_t tpcu=3.09, Double_t tofs=3.,
				  Int_t tofm=0,
				  Int_t itshitpixel = AliHFEextraCuts::kBoth,
				  Bool_t withetacorrection = kTRUE){
  gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/pPb/ConfigHFEmbpPb.C");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
  AliAnalysisTaskHFE *task = ConfigHFEmbpPb(useMC, isAOD, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz,
					     tpcs,tpcu,tofs,tofm,3.,kFALSE,kTRUE,kFALSE,itshitpixel,withetacorrection);
  if()
    task->SetAODAnalysis();
  else
    task->SetESDAnalysis();
  if (useMC)
    task->SetHasMCData(kTRUE);
  else{
    task->SetHasMCData(kFALSE);
  }
  task->SelectCollisionCandidates(AliVEvent::kINT7);

  Int_t idcaxy = (Int_t)(dcaxy*10.);
  Int_t idcaz = (Int_t)(dcaz*10.);
  Int_t itpcs = (Int_t)(tpcs*1000.);
  Int_t itofs = (Int_t)(tofs*10.);
  Int_t ipixelany = itshitpixel;
  Int_t ietacorr = 0;
  if(withetacorrection) ietacorr = 1;

  TString appendix(TString::Format("TPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dm%ipa%d",tpcCls,
				   tpcClsPID,itsCls,idcaxy,idcaz,itpcs,itofs,tofm,ipixelany));
  printf("Add macro appendix %s\n", appendix.Data());

  TString containerName = mgr->GetCommonFileName();
  containerName += ":HFEpPbmb";
  containerName += appendix.Data();
  printf("container name: %s\n", containerName.Data());

  //create data containers
  task->ConnectOutput(1, mgr->CreateContainer(Form("HFE_Results_%s", appendix.Data()),
					      TList::Class(), AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  task->ConnectOutput(2, mgr->CreateContainer(Form("HFE_QA_%s", appendix.Data()), TList::Class(),
					      AliAnalysisManager::kOutputContainer,
					      containerName.Data()));
  mgr->ConnectInput(task,  0, cinput );

  mgr->AddTask(task);
  return NULL;
}

//=========================================================================
<|endoftext|>


<commit_before>#include <locale>
#include "window.hpp"
#include "compileconfig.hpp"
#include "log.hpp"
#include "timer.hpp"
#include "appcontroller.hpp"
#include <lib/include/iapp.hpp>
#include "events/event.hpp"
#include "events/inputevent.hpp"
#include "eventmanager.hpp"
#include "convops.hpp"
#include <lib/draw/camera.hpp>
#include <lib/driv_impl/sfml/wwindow_impl.hpp>
#include "appcontroller.hpp"
#include "driver.hpp"

namespace lib
{
	namespace core
	{
		namespace
		{
			sf::String getAsString(const std::string &other)
			{
				std::wstring wsTmp(other.begin(), other.end());
				sf::String temp(wsTmp);
				return temp;
			}
		}
		struct WindowPrivate
		{
			Timer globalClock;
			u64 lastTimeFps{ 0 };
			s32 lastFps{ 0 };
			s32 currentFps{ 0 };
			sptr<drivers::window::IWWindow> m_renderWindow{ nullptr };
		};
		Window::Window(AppController *const appController, const WindowCreationParams &wcp)
			: p_wPrivate{ new WindowPrivate() }, AppService{ appController }, _title(wcp.windowTitle)
		{
			LOG_CONSTRUCT_NOPARAMS;
			create(wcp);
		}

		Window::~Window()
		{
			LOG_DESTRUCT_NOPARAMS;
		}

		void Window::create(const WindowCreationParams &wcp)
		{
			LOG_DEBUG("Going to create Window");
			LOG_DEBUG("Resolution:" << wcp.width << "x" << wcp.height << "x" << std::to_string(wcp.bpp));
			LOG_DEBUG("Fullscreen:" << wcp.fullScreen);
			LOG_DEBUG("Antialiasing:" << wcp.antialiasing);

			sf::Uint32 style{ sf::Style::Titlebar | sf::Style::Close };
			if (wcp.fullScreen)
				style = sf::Style::Fullscreen;

			p_wPrivate->m_renderWindow = appController->driver()->newWindow(); //sptr<drivers::window>{new RenderWindow()};
			p_wPrivate->m_renderWindow->create(wcp.width, wcp.height, wcp.bpp, _title.c_str(), 0, 0, 0, 0, 0, 0);

			p_wPrivate->m_renderWindow->setVerticalSync(wcp.vsync);
		}

		bool Window::preLoop()
		{
			auto eMs = p_wPrivate->globalClock.getElapsedTime().asMilliSeconds();
			if ((eMs - p_wPrivate->lastTimeFps) > 1000)
			{
				p_wPrivate->lastTimeFps = eMs;
				p_wPrivate->lastFps = p_wPrivate->currentFps;
				p_wPrivate->currentFps = 0;
				p_wPrivate->m_renderWindow->setTitle(std::string(_title + " FPS:" + std::to_string(p_wPrivate->lastFps) ).c_str());
			}
			++(p_wPrivate->currentFps);
			p_wPrivate->m_renderWindow->clear();
			p_wPrivate->m_renderWindow->receiveEvent(this);
			/*
			sf::Event event;
			while (p_wPrivate->m_renderWindow->pollEvent(event))
			{
				if (event.type == sf::Event::Closed)
				{
					return true;
				}
				else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)
				{
					keyEvent(event);
				}
			}
			*/

			return _shouldClose;
		}

		bool Window::postLoop()
		{
			p_wPrivate->m_renderWindow->display();
			return _shouldClose;
		}

		void Window::onCreate()
		{
			LOG_DEBUG("Window created");
		}

		void Window::onDestroy()
		{
			LOG_DEBUG("Going to close Window");
//			p_wPrivate->m_renderWindow->close();
			LOG_DEBUG("Window closed");
		}

		void Window::receiveKeyEvent(const events::KeyEvent &e)
		{
			appController->eventManager()->addEvent(uptr<events::InputEvent>(new events::KeyEvent(e)));
		}

		void Window::wantsClose()
		{
			_shouldClose = true;
		}

		void Window::exitProgram()
		{
			_shouldClose = true;
		}

		void Window::updateCamera(const draw::Camera &camera)
		{
			p_wPrivate->m_renderWindow->setViewRectangle(camera.target());
		}

		sptr<RenderTarget> Window::renderTarget()
		{
			return p_wPrivate->m_renderWindow;
		}
	}
}
<commit_msg>Deleted unused include<commit_after>#include <locale>
#include "window.hpp"
#include "compileconfig.hpp"
#include "log.hpp"
#include "timer.hpp"
#include "appcontroller.hpp"
#include <lib/include/iapp.hpp>
#include "events/event.hpp"
#include "events/inputevent.hpp"
#include "eventmanager.hpp"
#include <lib/draw/camera.hpp>
#include <lib/driv_impl/sfml/wwindow_impl.hpp>
#include "appcontroller.hpp"
#include "driver.hpp"

namespace lib
{
	namespace core
	{
		namespace
		{
			sf::String getAsString(const std::string &other)
			{
				std::wstring wsTmp(other.begin(), other.end());
				sf::String temp(wsTmp);
				return temp;
			}
		}
		struct WindowPrivate
		{
			Timer globalClock;
			u64 lastTimeFps{ 0 };
			s32 lastFps{ 0 };
			s32 currentFps{ 0 };
			sptr<drivers::window::IWWindow> m_renderWindow{ nullptr };
		};
		Window::Window(AppController *const appController, const WindowCreationParams &wcp)
			: p_wPrivate{ new WindowPrivate() }, AppService{ appController }, _title(wcp.windowTitle)
		{
			LOG_CONSTRUCT_NOPARAMS;
			create(wcp);
		}

		Window::~Window()
		{
			LOG_DESTRUCT_NOPARAMS;
		}

		void Window::create(const WindowCreationParams &wcp)
		{
			LOG_DEBUG("Going to create Window");
			LOG_DEBUG("Resolution:" << wcp.width << "x" << wcp.height << "x" << std::to_string(wcp.bpp));
			LOG_DEBUG("Fullscreen:" << wcp.fullScreen);
			LOG_DEBUG("Antialiasing:" << wcp.antialiasing);

			sf::Uint32 style{ sf::Style::Titlebar | sf::Style::Close };
			if (wcp.fullScreen)
				style = sf::Style::Fullscreen;

			p_wPrivate->m_renderWindow = appController->driver()->newWindow(); //sptr<drivers::window>{new RenderWindow()};
			p_wPrivate->m_renderWindow->create(wcp.width, wcp.height, wcp.bpp, _title.c_str(), 0, 0, 0, 0, 0, 0);

			p_wPrivate->m_renderWindow->setVerticalSync(wcp.vsync);
		}

		bool Window::preLoop()
		{
			auto eMs = p_wPrivate->globalClock.getElapsedTime().asMilliSeconds();
			if ((eMs - p_wPrivate->lastTimeFps) > 1000)
			{
				p_wPrivate->lastTimeFps = eMs;
				p_wPrivate->lastFps = p_wPrivate->currentFps;
				p_wPrivate->currentFps = 0;
				p_wPrivate->m_renderWindow->setTitle(std::string(_title + " FPS:" + std::to_string(p_wPrivate->lastFps) ).c_str());
			}
			++(p_wPrivate->currentFps);
			p_wPrivate->m_renderWindow->clear();
			p_wPrivate->m_renderWindow->receiveEvent(this);
			/*
			sf::Event event;
			while (p_wPrivate->m_renderWindow->pollEvent(event))
			{
				if (event.type == sf::Event::Closed)
				{
					return true;
				}
				else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)
				{
					keyEvent(event);
				}
			}
			*/

			return _shouldClose;
		}

		bool Window::postLoop()
		{
			p_wPrivate->m_renderWindow->display();
			return _shouldClose;
		}

		void Window::onCreate()
		{
			LOG_DEBUG("Window created");
		}

		void Window::onDestroy()
		{
			LOG_DEBUG("Going to close Window");
//			p_wPrivate->m_renderWindow->close();
			LOG_DEBUG("Window closed");
		}

		void Window::receiveKeyEvent(const events::KeyEvent &e)
		{
			appController->eventManager()->addEvent(uptr<events::InputEvent>(new events::KeyEvent(e)));
		}

		void Window::wantsClose()
		{
			_shouldClose = true;
		}

		void Window::exitProgram()
		{
			_shouldClose = true;
		}

		void Window::updateCamera(const draw::Camera &camera)
		{
			p_wPrivate->m_renderWindow->setViewRectangle(camera.target());
		}

		sptr<RenderTarget> Window::renderTarget()
		{
			return p_wPrivate->m_renderWindow;
		}
	}
}
<|endoftext|>


<commit_before>/*!
 * \page InventoryTestSuite_cpp Command-Line Test to Demonstrate How To Test the AirInv Project
 * \code
 */
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE InventoryTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// Airinv
//#include <airinv/AIRINV_Types.hpp>
#include <airinv/AIRINV_Master_Service.hpp>
#include <airinv/config/airinv-paths.hpp>

namespace boost_utf = boost::unit_test;

// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("InventoryTestSuite_utfresults.xml");

/**
 * Configuration for the Boost Unit Test Framework (UTF)
 */
struct UnitTestConfig {
  /** Constructor. */
  UnitTestConfig() {
    boost_utf::unit_test_log.set_stream (utfReportStream);
    boost_utf::unit_test_log.set_format (boost_utf::XML);
    boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
    //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
  }

  /** Destructor. */
  ~UnitTestConfig() {
  }
};

// /////////////// Main: Unit Test Suite //////////////

// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);

// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)

/**
 * Test a simple inventory sell
 */
BOOST_AUTO_TEST_CASE (airinv_simple_inventory_sell) {

  // Input file name
  const stdair::Filename_T lInventoryInputFilename (STDAIR_SAMPLE_DIR
                                                    "/invdump01.csv");

  // Check that the file path given as input corresponds to an actual file
  bool doesExistAndIsReadable =
    stdair::BasFileMgr::doesExistAndIsReadable (lInventoryInputFilename);
  BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
                       "The '" << lInventoryInputFilename
                       << "' input file can not be open and read");

  // Output log File
  const stdair::Filename_T lLogFilename ("InventoryTestSuite.log");

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the list of classes/buckets
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  AIRINV::AIRINV_Master_Service airinvService (lLogParams,
                                               lInventoryInputFilename);

  // Make a booking
  const std::string lSegmentDateKey ("SV, 5, 2010-03-11, KBP.JFK, 08:00:00");
  const stdair::ClassCode_T lClassCode ("J");
  const stdair::PartySize_T lPartySize (2);
  const bool hasSaleBeenSuccessful =
    airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

  // DEBUG: Display the list of travel solutions
  const std::string& lCSVDump = airinvService.csvDisplay();
  STDAIR_LOG_DEBUG (lCSVDump);

  // TODO: check why the booking-class cannot be retrieved, and reverse the test
  STDAIR_LOG_ERROR ("!!!!!!!!! The test fails. Please correct it !!!!!!!!!");
  BOOST_CHECK_EQUAL (hasSaleBeenSuccessful, false);
  BOOST_CHECK_MESSAGE (hasSaleBeenSuccessful == false,
                       "No sale can be made for '" << lSegmentDateKey
                       << "'");

  // Close the log file
  logOutputFile.close();
}

// End the test suite
BOOST_AUTO_TEST_SUITE_END()

/*!
 * \endcode
 */

<commit_msg>[AirInv][Test] Fixed the default segment-date key for the AirInv test suite.<commit_after>/*!
 * \page InventoryTestSuite_cpp Command-Line Test to Demonstrate How To Test the AirInv Project
 * \code
 */
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE InventoryTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// Airinv
//#include <airinv/AIRINV_Types.hpp>
#include <airinv/AIRINV_Master_Service.hpp>
#include <airinv/config/airinv-paths.hpp>

namespace boost_utf = boost::unit_test;

// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("InventoryTestSuite_utfresults.xml");

/**
 * Configuration for the Boost Unit Test Framework (UTF)
 */
struct UnitTestConfig {
  /** Constructor. */
  UnitTestConfig() {
    boost_utf::unit_test_log.set_stream (utfReportStream);
    boost_utf::unit_test_log.set_format (boost_utf::XML);
    boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
    //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
  }

  /** Destructor. */
  ~UnitTestConfig() {
  }
};

// /////////////// Main: Unit Test Suite //////////////

// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);

// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)

/**
 * Test a simple inventory sell
 */
BOOST_AUTO_TEST_CASE (airinv_simple_inventory_sell) {

  // Input file name
  const stdair::Filename_T lInventoryInputFilename (STDAIR_SAMPLE_DIR
                                                    "/invdump01.csv");

  // Check that the file path given as input corresponds to an actual file
  bool doesExistAndIsReadable =
    stdair::BasFileMgr::doesExistAndIsReadable (lInventoryInputFilename);
  BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
                       "The '" << lInventoryInputFilename
                       << "' input file can not be open and read");

  // Output log File
  const stdair::Filename_T lLogFilename ("InventoryTestSuite.log");

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the list of classes/buckets
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  AIRINV::AIRINV_Master_Service airinvService (lLogParams,
                                               lInventoryInputFilename);

  // Make a booking
  const std::string lSegmentDateKey ("SV, 5, 2010-03-11, KBP, JFK, 08:00:00");
  const stdair::ClassCode_T lClassCode ("J");
  const stdair::PartySize_T lPartySize (2);
  const bool hasSaleBeenSuccessful =
    airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);

  // DEBUG: Display the list of travel solutions
  const std::string& lCSVDump = airinvService.csvDisplay();
  STDAIR_LOG_DEBUG (lCSVDump);

  BOOST_CHECK_EQUAL (hasSaleBeenSuccessful, true);
  BOOST_CHECK_MESSAGE (hasSaleBeenSuccessful == true,
                       "No sale can be made for '" << lSegmentDateKey
                       << "'");

  // Close the log file
  logOutputFile.close();
}

// End the test suite
BOOST_AUTO_TEST_SUITE_END()

/*!
 * \endcode
 */

<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2017 Ryo Suzuki
//	Copyright (c) 2016-2017 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include "KeyConjunction.hpp"

namespace s3d
{
	class KeyGroup
	{
	private:

		Array<Key> m_keys;

		Array<KeyConjunction> m_keyConjunctions;

	public:

	};
}
<commit_msg>KeyGroup 準備<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2017 Ryo Suzuki
//	Copyright (c) 2016-2017 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include "KeyConjunction.hpp"

namespace s3d
{
	class KeyGroup
	{
	private:

		Array<Key> m_keys;

		Array<KeyConjunction> m_keyConjunctions;

		template <class Type, class ...Args>
		void append(const Type& key, const Args&... args)
		{
			append(key);
			append(args...);
		}

		void append();

		void append(const Key& key);

		void append(const KeyConjunction& conjunction);

		void append(const KeyGroup& group);

	public:

		template <class ...Args>
		explicit KeyGroup(const Args&... args)
		{
			append(args...);
		}

		template <class Type>
		KeyGroup& operator |=(const Type& key)
		{
			append(key);
			return *this;
		}

		bool down() const;

		bool pressed() const;

		bool up() const;

		int32 num_pressed() const;

		MillisecondsF pressedDuration() const;

		const Array<Key>& keys() const
		{
			return m_keys;
		}

		const Array<KeyConjunction>& keyConjunctions() const
		{
			return m_keyConjunctions;
		}
	};
}
<|endoftext|>


<commit_before>/*======================================================================

  This file is part of the elastix software.

  Copyright (c) University Medical Center Utrecht. All rights reserved.
  See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
  details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE. See the above copyright notices for more information.

======================================================================*/

#ifndef __elxNormalizedGradientCorrelationMetric_HXX__
#define __elxNormalizedGradientCorrelationMetric_HXX__

#include "elxNormalizedGradientCorrelationMetric.h"
#include "itkImageFileReader.h"

namespace elastix
{
using namespace itk;

/**
 * ******************* Initialize ***********************
 */

template <class TElastix>
void
NormalizedGradientCorrelationMetric<TElastix>
::Initialize( void ) throw ( ExceptionObject )
{
  TimerPointer timer = TimerType::New();
  timer->StartTimer();
  this->Superclass1::Initialize();
  timer->StopTimer();
  elxout << "Initialization of NormalizedGradientCorrelation metric took: "
    << static_cast<long>( timer->GetElapsedClockSec() * 1000 ) << " ms." << std::endl;

} // end Initialize()

/**
 * ***************** BeforeEachResolution ***********************
 */

template <class TElastix>
void NormalizedGradientCorrelationMetric<TElastix>
::BeforeEachResolution( void )
{
  /** Set moving image derivative scales. */
  this->SetUseMovingImageDerivativeScales( false );
  MovingImageDerivativeScalesType movingImageDerivativeScales;
  bool usescales = true;

  for ( unsigned int i = 0; i < MovingImageDimension; ++i )
  {
    usescales &= this->GetConfiguration()->ReadParameter(
    movingImageDerivativeScales[ i ], "MovingImageDerivativeScales",
    this->GetComponentLabel(), i, -1, false );
  }
  if ( usescales )
  {
    this->SetUseMovingImageDerivativeScales( true );
    this->SetMovingImageDerivativeScales( movingImageDerivativeScales );
    elxout << "Multiplying moving image derivatives by: "
      << movingImageDerivativeScales << std::endl;
   }

  typedef typename elastix::OptimizerBase<TElastix>::ITKBaseType::ScalesType  ScalesType;
  ScalesType scales = this->m_Elastix->GetElxOptimizerBase()->GetAsITKBaseType()->GetScales();
  this->SetScales( scales );

} // end BeforeEachResolution()

} // end namespace elastix

#endif // end #ifndef __elxNormalizedGradientCorrelationMetric_HXX__
<commit_msg>style<commit_after>/*======================================================================

  This file is part of the elastix software.

  Copyright (c) University Medical Center Utrecht. All rights reserved.
  See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
  details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE. See the above copyright notices for more information.

======================================================================*/
#ifndef __elxNormalizedGradientCorrelationMetric_HXX__
#define __elxNormalizedGradientCorrelationMetric_HXX__

#include "elxNormalizedGradientCorrelationMetric.h"

namespace elastix
{
using namespace itk;

/**
 * ******************* Initialize ***********************
 */

template <class TElastix>
void NormalizedGradientCorrelationMetric<TElastix>
::Initialize( void ) throw ( ExceptionObject )
{
  TimerPointer timer = TimerType::New();
  timer->StartTimer();
  this->Superclass1::Initialize();
  timer->StopTimer();
  elxout << "Initialization of NormalizedGradientCorrelation metric took: "
    << static_cast<long>( timer->GetElapsedClockSec() * 1000 ) << " ms." << std::endl;

} // end Initialize()

/**
 * ***************** BeforeEachResolution ***********************
 */

template <class TElastix>
void NormalizedGradientCorrelationMetric<TElastix>
::BeforeEachResolution( void )
{
  /** Set moving image derivative scales. */
  this->SetUseMovingImageDerivativeScales( false );
  MovingImageDerivativeScalesType movingImageDerivativeScales;
  bool usescales = true;

  for ( unsigned int i = 0; i < MovingImageDimension; ++i )
  {
    usescales &= this->GetConfiguration()->ReadParameter(
    movingImageDerivativeScales[ i ], "MovingImageDerivativeScales",
    this->GetComponentLabel(), i, -1, false );
  }
  if ( usescales )
  {
    this->SetUseMovingImageDerivativeScales( true );
    this->SetMovingImageDerivativeScales( movingImageDerivativeScales );
    elxout << "Multiplying moving image derivatives by: "
      << movingImageDerivativeScales << std::endl;
   }

  typedef typename elastix::OptimizerBase<TElastix>::ITKBaseType::ScalesType  ScalesType;
  ScalesType scales = this->m_Elastix->GetElxOptimizerBase()->GetAsITKBaseType()->GetScales();
  this->SetScales( scales );

} // end BeforeEachResolution()

} // end namespace elastix

#endif // end #ifndef __elxNormalizedGradientCorrelationMetric_HXX__
<|endoftext|>


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

#include "src/core/lib/iomgr/executor/threadpool.h"

#include "test/core/util/test_config.h"

const int kSmallThreadPoolSize = 20;
const int kLargeThreadPoolSize = 100;
const int kThreadSmallIter = 100;
const int kThreadLargeIter = 10000;

// Simple functor for testing. It will count how many times being called.
class SimpleFunctorForAdd : public grpc_experimental_completion_queue_functor {
 public:
  friend class SimpleFunctorCheckForAdd;
  SimpleFunctorForAdd() {
    functor_run = &SimpleFunctorForAdd::Run;
    internal_next = this;
    internal_success = 0;
  }
  ~SimpleFunctorForAdd() {}
  static void Run(struct grpc_experimental_completion_queue_functor* cb,
                  int ok) {
    auto* callback = static_cast<SimpleFunctorForAdd*>(cb);
    callback->count_.FetchAdd(1, grpc_core::MemoryOrder::RELAXED);
  }

  int count() { return count_.Load(grpc_core::MemoryOrder::RELAXED); }

 private:
  grpc_core::Atomic<int> count_{0};
};

// Checks the given SimpleFunctorForAdd's count with a given number.
class SimpleFunctorCheckForAdd
    : public grpc_experimental_completion_queue_functor {
 public:
  SimpleFunctorCheckForAdd(int ok, int* count) : count_(count) {
    functor_run = &SimpleFunctorCheckForAdd::Run;
    internal_success = ok;
  }
  ~SimpleFunctorCheckForAdd() {}
  static void Run(struct grpc_experimental_completion_queue_functor* cb,
                  int ok) {
    auto* callback = static_cast<SimpleFunctorCheckForAdd*>(cb);
    (*callback->count_)++;
    GPR_ASSERT(*callback->count_ == callback->internal_success);
  }
 private:
  int* count_;
};

static void test_add(void) {
  gpr_log(GPR_INFO, "test_add");
  grpc_core::ThreadPool* pool =
      grpc_core::New<grpc_core::ThreadPool>(kSmallThreadPoolSize, "test_add");

  SimpleFunctorForAdd* functor = grpc_core::New<SimpleFunctorForAdd>();
  for (int i = 0; i < kThreadSmallIter; ++i) {
    pool->Add(functor);
  }
  grpc_core::Delete(pool);
  GPR_ASSERT(functor->count() == kThreadSmallIter);
  grpc_core::Delete(functor);
  gpr_log(GPR_DEBUG, "Done.");
}

// Thread that adds closures to pool
class WorkThread {
 public:
  WorkThread(grpc_core::ThreadPool* pool, SimpleFunctorForAdd* cb, int num_add)
      : num_add_(num_add), cb_(cb), pool_(pool) {
    thd_ = grpc_core::Thread(
        "thread_pool_test_add_thd",
        [](void* th) { static_cast<WorkThread*>(th)->Run(); }, this);
  }
  ~WorkThread() {}

  void Start() { thd_.Start(); }
  void Join() { thd_.Join(); }

 private:
  void Run() {
    for (int i = 0; i < num_add_; ++i) {
      pool_->Add(cb_);
    }
  }

  int num_add_;
  SimpleFunctorForAdd* cb_;
  grpc_core::ThreadPool* pool_;
  grpc_core::Thread thd_;
};

static void test_constructor(void) {
  // Size is 0 case
  grpc_core::ThreadPool* pool_size_zero =
      grpc_core::New<grpc_core::ThreadPool>(0);
  GPR_ASSERT(pool_size_zero->pool_capacity() == 0);
  Delete(pool_size_zero);
  // Tests options
  grpc_core::Thread::Options options;
  options.set_stack_size(192 * 1024);  // Random non-default value
  grpc_core::ThreadPool* pool =
      grpc_core::New<grpc_core::ThreadPool>(0, "test_constructor", options);
  GPR_ASSERT(pool->thread_options().stack_size() == options.stack_size());
  Delete(pool);
}

static void test_multi_add(void) {
  gpr_log(GPR_INFO, "test_multi_add");
  const int num_work_thds = 10;
  grpc_core::ThreadPool* pool = grpc_core::New<grpc_core::ThreadPool>(
      kLargeThreadPoolSize, "test_multi_add");
  SimpleFunctorForAdd* functor = grpc_core::New<SimpleFunctorForAdd>();
  WorkThread** work_thds = static_cast<WorkThread**>(
      gpr_zalloc(sizeof(WorkThread*) * num_work_thds));
  gpr_log(GPR_DEBUG, "Fork threads for adding...");
  for (int i = 0; i < num_work_thds; ++i) {
    work_thds[i] = grpc_core::New<WorkThread>(pool, functor, kThreadLargeIter);
    work_thds[i]->Start();
  }
  // Wait for all threads finish
  gpr_log(GPR_DEBUG, "Waiting for all work threads finish...");
  for (int i = 0; i < num_work_thds; ++i) {
    work_thds[i]->Join();
    grpc_core::Delete(work_thds[i]);
  }
  gpr_free(work_thds);
  gpr_log(GPR_DEBUG, "Done.");
  gpr_log(GPR_DEBUG, "Waiting for all closures finish...");
  // Destructor of thread pool will wait for all closures to finish
  grpc_core::Delete(pool);
  GPR_ASSERT(functor->count() == kThreadLargeIter * num_work_thds);
  grpc_core::Delete(functor);
  gpr_log(GPR_DEBUG, "Done.");
}

static void test_one_thread_FIFO(void) {
  gpr_log(GPR_INFO, "test_one_thread_FIFO");
  int counter = 0;
  grpc_core::ThreadPool* pool =
      grpc_core::New<grpc_core::ThreadPool>(1, "test_one_thread_FIFO");
  SimpleFunctorCheckForAdd** check_functors =
      static_cast<SimpleFunctorCheckForAdd**>(
          gpr_zalloc(sizeof(SimpleFunctorCheckForAdd*) * kThreadSmallIter));
  for (int i = 0; i < kThreadSmallIter; ++i) {
    check_functors[i] =
        grpc_core::New<SimpleFunctorCheckForAdd>(i + 1, &counter);
    pool->Add(check_functors[i]);
  }
  // Destructor of pool will wait until all closures finished.
  grpc_core::Delete(pool);
  for (int i = 0; i < kThreadSmallIter; ++i) {
    grpc_core::Delete(check_functors[i]);
  }
  gpr_free(check_functors);
  gpr_log(GPR_DEBUG, "Done.");
}

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(argc, argv);
  grpc_init();
  test_constructor();
  test_add();
  test_multi_add();
  test_one_thread_FIFO();
  grpc_shutdown();
  return 0;
}
<commit_msg>reformat<commit_after>/*
 *
 * Copyright 2019 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/core/lib/iomgr/executor/threadpool.h"

#include "test/core/util/test_config.h"

const int kSmallThreadPoolSize = 20;
const int kLargeThreadPoolSize = 100;
const int kThreadSmallIter = 100;
const int kThreadLargeIter = 10000;

// Simple functor for testing. It will count how many times being called.
class SimpleFunctorForAdd : public grpc_experimental_completion_queue_functor {
 public:
  friend class SimpleFunctorCheckForAdd;
  SimpleFunctorForAdd() {
    functor_run = &SimpleFunctorForAdd::Run;
    internal_next = this;
    internal_success = 0;
  }
  ~SimpleFunctorForAdd() {}
  static void Run(struct grpc_experimental_completion_queue_functor* cb,
                  int ok) {
    auto* callback = static_cast<SimpleFunctorForAdd*>(cb);
    callback->count_.FetchAdd(1, grpc_core::MemoryOrder::RELAXED);
  }

  int count() { return count_.Load(grpc_core::MemoryOrder::RELAXED); }

 private:
  grpc_core::Atomic<int> count_{0};
};

// Checks the given SimpleFunctorForAdd's count with a given number.
class SimpleFunctorCheckForAdd
    : public grpc_experimental_completion_queue_functor {
 public:
  SimpleFunctorCheckForAdd(int ok, int* count) : count_(count) {
    functor_run = &SimpleFunctorCheckForAdd::Run;
    internal_success = ok;
  }
  ~SimpleFunctorCheckForAdd() {}
  static void Run(struct grpc_experimental_completion_queue_functor* cb,
                  int ok) {
    auto* callback = static_cast<SimpleFunctorCheckForAdd*>(cb);
    (*callback->count_)++;
    GPR_ASSERT(*callback->count_ == callback->internal_success);
  }

 private:
  int* count_;
};

static void test_add(void) {
  gpr_log(GPR_INFO, "test_add");
  grpc_core::ThreadPool* pool =
      grpc_core::New<grpc_core::ThreadPool>(kSmallThreadPoolSize, "test_add");

  SimpleFunctorForAdd* functor = grpc_core::New<SimpleFunctorForAdd>();
  for (int i = 0; i < kThreadSmallIter; ++i) {
    pool->Add(functor);
  }
  grpc_core::Delete(pool);
  GPR_ASSERT(functor->count() == kThreadSmallIter);
  grpc_core::Delete(functor);
  gpr_log(GPR_DEBUG, "Done.");
}

// Thread that adds closures to pool
class WorkThread {
 public:
  WorkThread(grpc_core::ThreadPool* pool, SimpleFunctorForAdd* cb, int num_add)
      : num_add_(num_add), cb_(cb), pool_(pool) {
    thd_ = grpc_core::Thread(
        "thread_pool_test_add_thd",
        [](void* th) { static_cast<WorkThread*>(th)->Run(); }, this);
  }
  ~WorkThread() {}

  void Start() { thd_.Start(); }
  void Join() { thd_.Join(); }

 private:
  void Run() {
    for (int i = 0; i < num_add_; ++i) {
      pool_->Add(cb_);
    }
  }

  int num_add_;
  SimpleFunctorForAdd* cb_;
  grpc_core::ThreadPool* pool_;
  grpc_core::Thread thd_;
};

static void test_constructor(void) {
  // Size is 0 case
  grpc_core::ThreadPool* pool_size_zero =
      grpc_core::New<grpc_core::ThreadPool>(0);
  GPR_ASSERT(pool_size_zero->pool_capacity() == 0);
  Delete(pool_size_zero);
  // Tests options
  grpc_core::Thread::Options options;
  options.set_stack_size(192 * 1024);  // Random non-default value
  grpc_core::ThreadPool* pool =
      grpc_core::New<grpc_core::ThreadPool>(0, "test_constructor", options);
  GPR_ASSERT(pool->thread_options().stack_size() == options.stack_size());
  Delete(pool);
}

static void test_multi_add(void) {
  gpr_log(GPR_INFO, "test_multi_add");
  const int num_work_thds = 10;
  grpc_core::ThreadPool* pool = grpc_core::New<grpc_core::ThreadPool>(
      kLargeThreadPoolSize, "test_multi_add");
  SimpleFunctorForAdd* functor = grpc_core::New<SimpleFunctorForAdd>();
  WorkThread** work_thds = static_cast<WorkThread**>(
      gpr_zalloc(sizeof(WorkThread*) * num_work_thds));
  gpr_log(GPR_DEBUG, "Fork threads for adding...");
  for (int i = 0; i < num_work_thds; ++i) {
    work_thds[i] = grpc_core::New<WorkThread>(pool, functor, kThreadLargeIter);
    work_thds[i]->Start();
  }
  // Wait for all threads finish
  gpr_log(GPR_DEBUG, "Waiting for all work threads finish...");
  for (int i = 0; i < num_work_thds; ++i) {
    work_thds[i]->Join();
    grpc_core::Delete(work_thds[i]);
  }
  gpr_free(work_thds);
  gpr_log(GPR_DEBUG, "Done.");
  gpr_log(GPR_DEBUG, "Waiting for all closures finish...");
  // Destructor of thread pool will wait for all closures to finish
  grpc_core::Delete(pool);
  GPR_ASSERT(functor->count() == kThreadLargeIter * num_work_thds);
  grpc_core::Delete(functor);
  gpr_log(GPR_DEBUG, "Done.");
}

static void test_one_thread_FIFO(void) {
  gpr_log(GPR_INFO, "test_one_thread_FIFO");
  int counter = 0;
  grpc_core::ThreadPool* pool =
      grpc_core::New<grpc_core::ThreadPool>(1, "test_one_thread_FIFO");
  SimpleFunctorCheckForAdd** check_functors =
      static_cast<SimpleFunctorCheckForAdd**>(
          gpr_zalloc(sizeof(SimpleFunctorCheckForAdd*) * kThreadSmallIter));
  for (int i = 0; i < kThreadSmallIter; ++i) {
    check_functors[i] =
        grpc_core::New<SimpleFunctorCheckForAdd>(i + 1, &counter);
    pool->Add(check_functors[i]);
  }
  // Destructor of pool will wait until all closures finished.
  grpc_core::Delete(pool);
  for (int i = 0; i < kThreadSmallIter; ++i) {
    grpc_core::Delete(check_functors[i]);
  }
  gpr_free(check_functors);
  gpr_log(GPR_DEBUG, "Done.");
}

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(argc, argv);
  grpc_init();
  test_constructor();
  test_add();
  test_multi_add();
  test_one_thread_FIFO();
  grpc_shutdown();
  return 0;
}
<|endoftext|>


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

#include <stdio.h>
#include <string.h>

#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>

#include "grpcpp/security/credentials_impl.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/util/json_util.h"
#include "src/cpp/client/secure_credentials.h"
#include "test/core/security/oauth2_utils.h"
#include "test/core/util/cmdline.h"

static grpc_call_credentials* create_sts_creds(const char* json_file_path) {
  grpc_impl::experimental::StsCredentialsOptions options;
  if (strlen(json_file_path) == 0) {
    auto status =
        grpc_impl::experimental::StsCredentialsOptionsFromEnv(&options);
    if (!status.ok()) {
      gpr_log(GPR_ERROR, "%s", status.error_message().c_str());
      return nullptr;
    }
  } else {
    grpc_slice sts_options_slice;
    GPR_ASSERT(GRPC_LOG_IF_ERROR(
        "load_file", grpc_load_file(json_file_path, 1, &sts_options_slice)));
    auto status = grpc_impl::experimental::StsCredentialsOptionsFromJson(
        reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(sts_options_slice)),
        &options);
    gpr_slice_unref(sts_options_slice);
    if (!status.ok()) {
      gpr_log(GPR_ERROR, "%s", status.error_message().c_str());
      return nullptr;
    }
  }
  grpc_sts_credentials_options opts =
      grpc_impl::experimental::StsCredentialsCppToCoreOptions(options);
  grpc_call_credentials* result = grpc_sts_credentials_create(&opts, nullptr);
  return result;
}

static grpc_call_credentials* create_refresh_token_creds(
    const char* json_refresh_token_file_path) {
  grpc_slice refresh_token;
  GPR_ASSERT(GRPC_LOG_IF_ERROR(
      "load_file",
      grpc_load_file(json_refresh_token_file_path, 1, &refresh_token)));
  grpc_call_credentials* result = grpc_google_refresh_token_credentials_create(
      reinterpret_cast<const char*> GRPC_SLICE_START_PTR(refresh_token),
      nullptr);
  gpr_slice_unref(refresh_token);
  return result;
}

int main(int argc, char** argv) {
  grpc_call_credentials* creds = nullptr;
  const char* json_sts_options_file_path = nullptr;
  const char* json_refresh_token_file_path = nullptr;
  char* token = nullptr;
  int use_gce = 0;
  gpr_cmdline* cl = gpr_cmdline_create("fetch_oauth2");
  gpr_cmdline_add_string(cl, "json_refresh_token",
                         "File path of the json refresh token.",
                         &json_refresh_token_file_path);
  gpr_cmdline_add_string(
      cl, "json_sts_options",
      "File path of the json sts options. If the path is empty, the program "
      "will attempt to use the $STS_CREDENTIALS environment variable to access "
      "a file containing the options.",
      &json_sts_options_file_path);
  gpr_cmdline_add_flag(
      cl, "gce",
      "Get a token from the GCE metadata server (only works in GCE).",
      &use_gce);
  gpr_cmdline_parse(cl, argc, argv);

  grpc_init();

  if (json_sts_options_file_path != nullptr &&
      json_refresh_token_file_path != nullptr) {
    gpr_log(
        GPR_ERROR,
        "--json_sts_options and --json_refresh_token are mutually exclusive.");
    exit(1);
  }

  if (use_gce) {
    if (json_sts_options_file_path != nullptr ||
        json_refresh_token_file_path != nullptr) {
      gpr_log(GPR_INFO,
              "Ignoring json refresh token or sts options to get a token from "
              "the GCE metadata server.");
    }
    creds = grpc_google_compute_engine_credentials_create(nullptr);
    if (creds == nullptr) {
      gpr_log(GPR_ERROR, "Could not create gce credentials.");
      exit(1);
    }
  } else if (json_refresh_token_file_path != nullptr) {
    creds = create_refresh_token_creds(json_refresh_token_file_path);
    if (creds == nullptr) {
      gpr_log(GPR_ERROR,
              "Could not create refresh token creds. %s does probably not "
              "contain a valid json refresh token.",
              json_refresh_token_file_path);
      exit(1);
    }
  } else if (json_sts_options_file_path != nullptr) {
    creds = create_sts_creds(json_sts_options_file_path);
    if (creds == nullptr) {
      gpr_log(GPR_ERROR,
              "Could not create sts creds. %s does probably not contain a "
              "valid json for sts options.",
              json_sts_options_file_path);
      exit(1);
    }
  } else {
    gpr_log(
        GPR_ERROR,
        "Missing --gce, --json_sts_options, or --json_refresh_token option.");
    exit(1);
  }
  GPR_ASSERT(creds != nullptr);

  token = grpc_test_fetch_oauth2_token_with_credentials(creds);
  if (token != nullptr) {
    printf("Got token: %s.\n", token);
    gpr_free(token);
  }
  grpc_call_credentials_release(creds);
  gpr_cmdline_destroy(cl);
  grpc_shutdown();
  return 0;
}
<commit_msg>Fix fetch oauth2 test<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <stdio.h>
#include <string.h>

#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>

#include "grpcpp/security/credentials.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/security/util/json_util.h"
#include "src/cpp/client/secure_credentials.h"
#include "test/core/security/oauth2_utils.h"
#include "test/core/util/cmdline.h"

static grpc_call_credentials* create_sts_creds(const char* json_file_path) {
  grpc::experimental::StsCredentialsOptions options;
  if (strlen(json_file_path) == 0) {
    auto status =
        grpc::experimental::StsCredentialsOptionsFromEnv(&options);
    if (!status.ok()) {
      gpr_log(GPR_ERROR, "%s", status.error_message().c_str());
      return nullptr;
    }
  } else {
    grpc_slice sts_options_slice;
    GPR_ASSERT(GRPC_LOG_IF_ERROR(
        "load_file", grpc_load_file(json_file_path, 1, &sts_options_slice)));
    auto status = grpc::experimental::StsCredentialsOptionsFromJson(
        reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(sts_options_slice)),
        &options);
    gpr_slice_unref(sts_options_slice);
    if (!status.ok()) {
      gpr_log(GPR_ERROR, "%s", status.error_message().c_str());
      return nullptr;
    }
  }
  grpc_sts_credentials_options opts =
      grpc::experimental::StsCredentialsCppToCoreOptions(options);
  grpc_call_credentials* result = grpc_sts_credentials_create(&opts, nullptr);
  return result;
}

static grpc_call_credentials* create_refresh_token_creds(
    const char* json_refresh_token_file_path) {
  grpc_slice refresh_token;
  GPR_ASSERT(GRPC_LOG_IF_ERROR(
      "load_file",
      grpc_load_file(json_refresh_token_file_path, 1, &refresh_token)));
  grpc_call_credentials* result = grpc_google_refresh_token_credentials_create(
      reinterpret_cast<const char*> GRPC_SLICE_START_PTR(refresh_token),
      nullptr);
  gpr_slice_unref(refresh_token);
  return result;
}

int main(int argc, char** argv) {
  grpc_call_credentials* creds = nullptr;
  const char* json_sts_options_file_path = nullptr;
  const char* json_refresh_token_file_path = nullptr;
  char* token = nullptr;
  int use_gce = 0;
  gpr_cmdline* cl = gpr_cmdline_create("fetch_oauth2");
  gpr_cmdline_add_string(cl, "json_refresh_token",
                         "File path of the json refresh token.",
                         &json_refresh_token_file_path);
  gpr_cmdline_add_string(
      cl, "json_sts_options",
      "File path of the json sts options. If the path is empty, the program "
      "will attempt to use the $STS_CREDENTIALS environment variable to access "
      "a file containing the options.",
      &json_sts_options_file_path);
  gpr_cmdline_add_flag(
      cl, "gce",
      "Get a token from the GCE metadata server (only works in GCE).",
      &use_gce);
  gpr_cmdline_parse(cl, argc, argv);

  grpc_init();

  if (json_sts_options_file_path != nullptr &&
      json_refresh_token_file_path != nullptr) {
    gpr_log(
        GPR_ERROR,
        "--json_sts_options and --json_refresh_token are mutually exclusive.");
    exit(1);
  }

  if (use_gce) {
    if (json_sts_options_file_path != nullptr ||
        json_refresh_token_file_path != nullptr) {
      gpr_log(GPR_INFO,
              "Ignoring json refresh token or sts options to get a token from "
              "the GCE metadata server.");
    }
    creds = grpc_google_compute_engine_credentials_create(nullptr);
    if (creds == nullptr) {
      gpr_log(GPR_ERROR, "Could not create gce credentials.");
      exit(1);
    }
  } else if (json_refresh_token_file_path != nullptr) {
    creds = create_refresh_token_creds(json_refresh_token_file_path);
    if (creds == nullptr) {
      gpr_log(GPR_ERROR,
              "Could not create refresh token creds. %s does probably not "
              "contain a valid json refresh token.",
              json_refresh_token_file_path);
      exit(1);
    }
  } else if (json_sts_options_file_path != nullptr) {
    creds = create_sts_creds(json_sts_options_file_path);
    if (creds == nullptr) {
      gpr_log(GPR_ERROR,
              "Could not create sts creds. %s does probably not contain a "
              "valid json for sts options.",
              json_sts_options_file_path);
      exit(1);
    }
  } else {
    gpr_log(
        GPR_ERROR,
        "Missing --gce, --json_sts_options, or --json_refresh_token option.");
    exit(1);
  }
  GPR_ASSERT(creds != nullptr);

  token = grpc_test_fetch_oauth2_token_with_credentials(creds);
  if (token != nullptr) {
    printf("Got token: %s.\n", token);
    gpr_free(token);
  }
  grpc_call_credentials_release(creds);
  gpr_cmdline_destroy(cl);
  grpc_shutdown();
  return 0;
}
<|endoftext|>


<commit_before>#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/add.hpp>
#include <gtest/gtest.h>
#include <algorithm>

TEST(MathMatrixGPU, add_v_exception_pass) {
  stan::math::vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_zero) {
  stan::math::vector_d d1, d2;
  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 0);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_rv_exception_pass) {
  stan::math::row_vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_pass_zero) {
  stan::math::row_vector_d d1, d2;

  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_fail_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_m_exception_pass_simple) {
  stan::math::matrix_d d1, d2;

  d1.resize(2, 3);
  d2.resize(2, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_pass_zero) {
  stan::math::matrix_d d1, d2;
  d1.resize(0, 0);
  d2.resize(0, 0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_fail_invalid_arg) {
  stan::math::matrix_d d1, d2;
  d1.resize(2, 3);
  d2.resize(3, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_non_matching_sizes_exception) {
  stan::math::vector_d v1(2);
  v1 << 1, 2;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;

  stan::math::row_vector_d rv1(2);
  rv1 << 1, 2;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;

  stan::math::matrix_d m1(2, 3);
  m1 << 1, 2, 3, 4, 5, 6;
  stan::math::matrix_d m2(3, 2);
  m2 << 10, 100, 1000, 0, -10, -12;

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(v1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(rv1);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(m1);

  EXPECT_THROW(v33 = v11 + v22, std::invalid_argument);
  EXPECT_THROW(rv33 = rv11 + rv22, std::invalid_argument);
  EXPECT_THROW(m33 = m11 + m22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_value_check) {
  stan::math::vector_d v1(3);
  v1 << 1, 2, 3;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;
  stan::math::vector_d v3(3);

  stan::math::row_vector_d rv1(3);
  rv1 << 1, 2, 3;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;
  stan::math::row_vector_d rv3(3);

  stan::math::matrix_d m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  stan::math::matrix_d m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;
  stan::math::matrix_d m3(3, 3);

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(3, 1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(1, 3);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(3, 3);

  EXPECT_NO_THROW(v33 = v11 + v22);
  EXPECT_NO_THROW(rv33 = rv11 + rv22);
  EXPECT_NO_THROW(m33 = m11 + m22);

  stan::math::copy(v3, v33);
  EXPECT_EQ(11, v3(0));
  EXPECT_EQ(102, v3(1));
  EXPECT_EQ(1003, v3(2));

  stan::math::copy(rv3, rv33);
  EXPECT_EQ(11, rv3(0));
  EXPECT_EQ(102, rv3(1));
  EXPECT_EQ(1003, rv3(2));

  stan::math::copy(m3, m33);
  EXPECT_EQ(11, m3(0, 0));
  EXPECT_EQ(102, m3(0, 1));
  EXPECT_EQ(1003, m3(0, 2));
  EXPECT_EQ(4, m3(1, 0));
  EXPECT_EQ(-5, m3(1, 1));
  EXPECT_EQ(-6, m3(1, 2));
  EXPECT_EQ(9, m3(2, 0));
  EXPECT_EQ(12, m3(2, 1));
  EXPECT_EQ(17, m3(2, 2));
}

TEST(MathMatrixGPU, add_batch) {
  // used to represent 5 matrices of size 10x10
  const int batch_size = 11;
  const int size = 13;
  stan::math::matrix_d a(size, size * batch_size);
  stan::math::matrix_d a_res(size, size);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, k * size + j) = k;
      }
  }
  stan::math::matrix_cl a_cl(a);
  stan::math::matrix_cl a_cl_res(size, size);
  stan::math::opencl_kernels::add_batch(cl::NDRange(size, size), a_cl.buffer(),
                                        size, size, batch_size);
  a_cl_res.sub_block(a_cl, 0, 0, 0, 0, size, size);
  copy(a_res, a_cl_res);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, j) += a(i, k * size + j);
      }
  }
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      EXPECT_EQ(a(i, j), a_res(i, j));
    }
  }
}
#endif
<commit_msg>fix for the add_batch test<commit_after>#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/add.hpp>
#include <gtest/gtest.h>
#include <algorithm>

TEST(MathMatrixGPU, add_v_exception_pass) {
  stan::math::vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_zero) {
  stan::math::vector_d d1, d2;
  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 1);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_v_exception_pass_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 0);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_rv_exception_pass) {
  stan::math::row_vector_d d1, d2;

  d1.resize(3);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_pass_zero) {
  stan::math::row_vector_d d1, d2;

  d1.resize(0);
  d2.resize(0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(1, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_rv_exception_fail_invalid_arg) {
  stan::math::row_vector_d d1, d2;

  d1.resize(2);
  d2.resize(3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(3, 1);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_m_exception_pass_simple) {
  stan::math::matrix_d d1, d2;

  d1.resize(2, 3);
  d2.resize(2, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_pass_zero) {
  stan::math::matrix_d d1, d2;
  d1.resize(0, 0);
  d2.resize(0, 0);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(0, 0);
  EXPECT_NO_THROW(d33 = d11 + d22);
}

TEST(MathMatrixGPU, add_m_exception_fail_invalid_arg) {
  stan::math::matrix_d d1, d2;
  d1.resize(2, 3);
  d2.resize(3, 3);
  stan::math::matrix_cl d11(d1);
  stan::math::matrix_cl d22(d2);
  stan::math::matrix_cl d33(2, 3);
  EXPECT_THROW(d33 = d11 + d22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_non_matching_sizes_exception) {
  stan::math::vector_d v1(2);
  v1 << 1, 2;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;

  stan::math::row_vector_d rv1(2);
  rv1 << 1, 2;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;

  stan::math::matrix_d m1(2, 3);
  m1 << 1, 2, 3, 4, 5, 6;
  stan::math::matrix_d m2(3, 2);
  m2 << 10, 100, 1000, 0, -10, -12;

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(v1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(rv1);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(m1);

  EXPECT_THROW(v33 = v11 + v22, std::invalid_argument);
  EXPECT_THROW(rv33 = rv11 + rv22, std::invalid_argument);
  EXPECT_THROW(m33 = m11 + m22, std::invalid_argument);
}

TEST(MathMatrixGPU, add_value_check) {
  stan::math::vector_d v1(3);
  v1 << 1, 2, 3;
  stan::math::vector_d v2(3);
  v2 << 10, 100, 1000;
  stan::math::vector_d v3(3);

  stan::math::row_vector_d rv1(3);
  rv1 << 1, 2, 3;
  stan::math::row_vector_d rv2(3);
  rv2 << 10, 100, 1000;
  stan::math::row_vector_d rv3(3);

  stan::math::matrix_d m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  stan::math::matrix_d m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;
  stan::math::matrix_d m3(3, 3);

  using stan::math::add;
  using stan::math::matrix_cl;
  matrix_cl v11(v1);
  matrix_cl v22(v2);
  matrix_cl v33(3, 1);
  matrix_cl rv11(rv1);
  matrix_cl rv22(rv2);
  matrix_cl rv33(1, 3);
  matrix_cl m11(m1);
  matrix_cl m22(m2);
  matrix_cl m33(3, 3);

  EXPECT_NO_THROW(v33 = v11 + v22);
  EXPECT_NO_THROW(rv33 = rv11 + rv22);
  EXPECT_NO_THROW(m33 = m11 + m22);

  stan::math::copy(v3, v33);
  EXPECT_EQ(11, v3(0));
  EXPECT_EQ(102, v3(1));
  EXPECT_EQ(1003, v3(2));

  stan::math::copy(rv3, rv33);
  EXPECT_EQ(11, rv3(0));
  EXPECT_EQ(102, rv3(1));
  EXPECT_EQ(1003, rv3(2));

  stan::math::copy(m3, m33);
  EXPECT_EQ(11, m3(0, 0));
  EXPECT_EQ(102, m3(0, 1));
  EXPECT_EQ(1003, m3(0, 2));
  EXPECT_EQ(4, m3(1, 0));
  EXPECT_EQ(-5, m3(1, 1));
  EXPECT_EQ(-6, m3(1, 2));
  EXPECT_EQ(9, m3(2, 0));
  EXPECT_EQ(12, m3(2, 1));
  EXPECT_EQ(17, m3(2, 2));
}

TEST(MathMatrixGPU, add_batch) {
  // used to represent 5 matrices of size 10x10
  const int batch_size = 11;
  const int size = 13;
  stan::math::matrix_d a(size, size * batch_size);
  stan::math::matrix_d a_res(size, size);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, k * size + j) = k;
      }
  }
  stan::math::matrix_cl a_cl(a);
  stan::math::matrix_cl a_cl_res(size, size);
  stan::math::opencl_kernels::add_batch(cl::NDRange(size, size), a_cl_res.buffer(),
                                        a_cl.buffer(), size, size, batch_size);
  copy(a_res, a_cl_res);
  for (int k = 0; k < batch_size; k++) {
    for (int i = 0; i < size; i++)
      for (int j = 0; j < size; j++) {
        a(i, j) += a(i, k * size + j);
      }
  }
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      EXPECT_EQ(a(i, j), a_res(i, j));
    }
  }
}
#endif
<|endoftext|>