<commit_before>#include "AnimationControllerEditor.hpp"
#include <Engine/Animation/AnimationController.hpp>
#include <imgui.h>

AnimationControllerEditor::AnimationControllerEditor() {
}

AnimationControllerEditor::~AnimationControllerEditor() {
}

void AnimationControllerEditor::Show() {
    if (ImGui::Begin("Animation controller", &visible)) {
        // Get the draw list.
        ImDrawList* drawList = ImGui::GetWindowDrawList();
        drawList->ChannelsSplit(2);

        // Draw animation actions.
        for (unsigned int id = 0; id < animationController->animationAction.size(); ++id) {
            Animation::AnimationController::AnimationAction * action = animationController->animationAction[id];
            ImGui::PushID(id);

            drawList->ChannelsSetCurrent(1); // Foreground
            ImGui::BeginGroup(); // Lock horizontal position
            ImGui::Text("%s", action->nodeName);
            //   ImGui::SliderFloat("##value", &node->Value, 0.0f, 1.0f, "Alpha %.2f");
            ImGui::EndGroup();

            // Display node box
            drawList->ChannelsSetCurrent(0); // Background
            ImGui::SetCursorScreenPos(ImVec2(100, 200));
            ImGui::InvisibleButton("node", ImVec2(100, 200));
            //if (ImGui::IsItemHovered()) {
            //    node_hovered_in_scene = node->ID;
            //    open_context_menu |= ImGui::IsMouseClicked(1);
            //}

            ImU32 node_bg_color = ImColor(75, 75, 75);
            drawList->AddRectFilled(ImVec2(100, 200), ImVec2(100, 200), node_bg_color, 4.0f);
            drawList->AddRect(ImVec2(100, 200), ImVec2(100, 200), ImColor(100, 100, 100), 4.0f);
            drawList->AddCircleFilled(ImVec2(10.0f, 20.0f), 1, ImColor(150, 150, 150, 150));
            drawList->AddCircleFilled(ImVec2(10.0f, 20.0f), 1, ImColor(150, 150, 150, 150));

            ImGui::PopID();
        }

        for (unsigned int id = 0; id < animationController->animationAction.size(); ++id) {
            Animation::AnimationController::AnimationAction * action = animationController->animationAction[id];
            ImGui::PushID(id + animationController->animationTransitions.size());

            ImGui::PopID();
        }

        drawList->ChannelsMerge();

        // Draw context menu
        if (ImGui::BeginPopupContextWindow()) {
            if (ImGui::MenuItem("Add animation action")) {
                Animation::AnimationController::AnimationAction* newAction = new Animation::AnimationController::AnimationAction;
                std::string name = "Animation Action: " + std::to_string(animationController->animationAction.size());
                memcpy(newAction->nodeName, name.c_str(), name.size() + 1);
                animationController->animationAction.push_back(newAction);
            }

            if (ImGui::MenuItem("Add animation transition")) {
                Animation::AnimationController::AnimationAction* newAction = new Animation::AnimationController::AnimationAction;
                std::string name = "Animation Action: " + std::to_string(animationController->animationAction.size());
                memcpy(newAction->nodeName, name.c_str(), name.size() + 1);
                animationController->animationAction.push_back(newAction);
            }

            ImGui::EndPopup();
        }

    }
    ImGui::End();
}

void AnimationControllerEditor::SetAnimationController(Animation::AnimationController * animationController) {
    this->animationController = animationController;
}

bool AnimationControllerEditor::IsVisible() const {
    return visible;
}

void AnimationControllerEditor::SetVisible(bool visible) {
    this->visible = visible;
}
<commit_msg>Name fixing.<commit_after>#include "AnimationControllerEditor.hpp"
#include <Engine/Animation/AnimationController.hpp>
#include <imgui.h>

AnimationControllerEditor::AnimationControllerEditor() {
}

AnimationControllerEditor::~AnimationControllerEditor() {
}

void AnimationControllerEditor::Show() {
    if (ImGui::Begin("Animation controller", &visible)) {
        // Get the draw list.
        ImDrawList* drawList = ImGui::GetWindowDrawList();
        drawList->ChannelsSplit(2);

        // Draw animation actions.
        for (unsigned int id = 0; id < animationController->animationAction.size(); ++id) {
            Animation::AnimationController::AnimationAction * action = animationController->animationAction[id];
            ImGui::PushID(id);

            drawList->ChannelsSetCurrent(1); // Foreground
            ImGui::BeginGroup(); // Lock horizontal position
            ImGui::Text("%s", action->nodeName);
            //   ImGui::SliderFloat("##value", &node->Value, 0.0f, 1.0f, "Alpha %.2f");
            ImGui::EndGroup();

            // Display node box
            drawList->ChannelsSetCurrent(0); // Background
            ImGui::SetCursorScreenPos(ImVec2(100, 200));
            ImGui::InvisibleButton("node", ImVec2(100, 200));
            //if (ImGui::IsItemHovered()) {
            //    node_hovered_in_scene = node->ID;
            //    open_context_menu |= ImGui::IsMouseClicked(1);
            //}

            ImU32 node_bg_color = ImColor(75, 75, 75);
            drawList->AddRectFilled(ImVec2(100, 200), ImVec2(100, 200), node_bg_color, 4.0f);
            drawList->AddRect(ImVec2(100, 200), ImVec2(100, 200), ImColor(100, 100, 100), 4.0f);
            drawList->AddCircleFilled(ImVec2(10.0f, 20.0f), 1, ImColor(150, 150, 150, 150));
            drawList->AddCircleFilled(ImVec2(10.0f, 20.0f), 1, ImColor(150, 150, 150, 150));

            ImGui::PopID();
        }

        for (unsigned int id = 0; id < animationController->animationAction.size(); ++id) {
            Animation::AnimationController::AnimationAction * action = animationController->animationAction[id];
            ImGui::PushID(id + animationController->animationTransitions.size());

            ImGui::PopID();
        }

        drawList->ChannelsMerge();

        // Draw context menu
        if (ImGui::BeginPopupContextWindow()) {
            if (ImGui::MenuItem("Add animation action")) {
                Animation::AnimationController::AnimationAction* newAction = new Animation::AnimationController::AnimationAction;
                std::string name = "Animation action: " + std::to_string(animationController->animationAction.size());
                memcpy(newAction->nodeName, name.c_str(), name.size() + 1);
                animationController->animationAction.push_back(newAction);
            }

            if (ImGui::MenuItem("Add animation transition")) {
                Animation::AnimationController::AnimationAction* newAction = new Animation::AnimationController::AnimationAction;
                std::string name = "Animation transition: " + std::to_string(animationController->animationAction.size());
                memcpy(newAction->nodeName, name.c_str(), name.size() + 1);
                animationController->animationAction.push_back(newAction);
            }

            ImGui::EndPopup();
        }

    }
    ImGui::End();
}

void AnimationControllerEditor::SetAnimationController(Animation::AnimationController * animationController) {
    this->animationController = animationController;
}

bool AnimationControllerEditor::IsVisible() const {
    return visible;
}

void AnimationControllerEditor::SetVisible(bool visible) {
    this->visible = visible;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 */
/**
 * @file        src/admin/logic/OnlineLogic.cpp
 * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
 * @author      Aleksander Zdyb <a.zdyb@samsung.com>
 * @version     1.0
 * @brief       This file contains implementation of online version of Logic class
 */

#include <cinttypes>
#include <memory>

#include <cynara-error.h>
#include <common.h>
#include <config/PathConfig.h>
#include <exceptions/Exception.h>
#include <exceptions/UnexpectedErrorException.h>
#include <log/log.h>
#include <protocol/Protocol.h>
#include <protocol/ProtocolAdmin.h>
#include <request/AdminCheckRequest.h>
#include <request/EraseRequest.h>
#include <request/InsertOrUpdateBucketRequest.h>
#include <request/ListRequest.h>
#include <request/pointers.h>
#include <request/RemoveBucketRequest.h>
#include <request/SetPoliciesRequest.h>
#include <response/AdminCheckResponse.h>
#include <response/CodeResponse.h>
#include <response/ListResponse.h>
#include <response/pointers.h>
#include <sockets/SocketClient.h>
#include <types/ProtocolFields.h>

#include "OnlineLogic.h"

namespace Cynara {

OnlineLogic::OnlineLogic() {
    m_socketClient = std::make_shared<SocketClient>(PathConfig::SocketPath::admin,
                                                    std::make_shared<ProtocolAdmin>());
}

ProtocolFrameSequenceNumber generateSequenceNumber(void) {
    static ProtocolFrameSequenceNumber sequenceNumber = 0;
    return ++sequenceNumber;
}

bool OnlineLogic::ensureConnection(void) {
    return m_socketClient->isConnected() || m_socketClient->connect();
}

template<typename Req, typename Res, typename... ReqArgs>
int OnlineLogic::getResponse(std::shared_ptr<Res> &retResponse, ReqArgs... args) {
    if (!ensureConnection()) {
        LOGE("Cannot connect to cynara. Service not available.");
        return CYNARA_API_SERVICE_NOT_AVAILABLE;
    }

    ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber();

    RequestPtr request = std::make_shared<Req>(args..., sequenceNumber);
    ResponsePtr response;
    while (!(response = m_socketClient->askCynaraServer(request))) {
        if (!m_socketClient->connect())
            return CYNARA_API_SERVICE_NOT_AVAILABLE;
    }

    retResponse = std::dynamic_pointer_cast<Res>(response);
    if (!retResponse) {
        LOGC("Critical error. Casting Response failed.");
        return CYNARA_API_UNKNOWN_ERROR;
    }

    return CYNARA_API_SUCCESS;
}

static int interpretCodeResponse(const CodeResponse::Code &code) {
    LOGD("codeResponse: code [%" PRIu16 "]", code);
    switch (code) {
        case CodeResponse::Code::OK:
            LOGI("Cynara command finished successfully.");
            return CYNARA_API_SUCCESS;
        case CodeResponse::Code::NOT_ALLOWED:
            LOGE("Cynara service answered: Operation not allowed.");
            return CYNARA_API_OPERATION_NOT_ALLOWED;
        case CodeResponse::Code::NO_BUCKET:
            LOGE("Trying to use unexisting bucket.");
            return CYNARA_API_BUCKET_NOT_FOUND;
        case CodeResponse::Code::FAILED:
            LOGC("Cynara service answered: Operation failed.");
            return CYNARA_API_OPERATION_FAILED;
        default:
            LOGE("Unexpected response code from server: [%d]",
                 static_cast<int>(code));
            return CYNARA_API_UNKNOWN_ERROR;
    }
}

int OnlineLogic::setPolicies(const ApiInterface::PoliciesByBucket &insertOrUpdate,
                       const ApiInterface::KeysByBucket &remove) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<SetPoliciesRequest>(codeResponse, insertOrUpdate, remove);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::insertOrUpdateBucket(const PolicyBucketId &bucket,
                                const PolicyResult &policyResult) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<InsertOrUpdateBucketRequest>(codeResponse, bucket, policyResult);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::removeBucket(const PolicyBucketId &bucket) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<RemoveBucketRequest>(codeResponse, bucket);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const PolicyKey &key,
                      PolicyResult &result) {
    AdminCheckResponsePtr adminCheckResponse;
    int ret = getResponse<AdminCheckRequest>(adminCheckResponse, key, startBucket, recursive);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    LOGD("AdminCheckResponse: policyType [%" PRIu16 "], metadata <%s>, bucketValid [%d]",
         adminCheckResponse->result().policyType(), adminCheckResponse->result().metadata().c_str(),
         static_cast<int>(adminCheckResponse->isBucketValid()));

    if (!adminCheckResponse->isBucketValid()) {
        LOGE("Bucket <%s> provided as startBucket in adminCheck does not exist in cynara database",
             startBucket.c_str());
        return CYNARA_API_BUCKET_NOT_FOUND;
    }

    result = adminCheckResponse->result();
    return CYNARA_API_SUCCESS;
}

int OnlineLogic::listPolicies(const PolicyBucketId &bucket, const PolicyKey &filter,
                        std::vector<Policy> &policies) {
    ListResponsePtr listResponse;
    int ret = getResponse<ListRequest>(listResponse, bucket, filter);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    LOGD("listResponse: number of policies [%zu], bucketValid [%d]",
         listResponse->policies().size(), listResponse->isBucketValid());

    if (!listResponse->isBucketValid()) {
        return CYNARA_API_BUCKET_NOT_FOUND;
    }

    policies = listResponse->policies();
    return CYNARA_API_SUCCESS;
}

int OnlineLogic::erasePolicies(const PolicyBucketId &startBucket, bool recursive,
                         const PolicyKey &filter) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<EraseRequest>(codeResponse, startBucket, recursive, filter);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::listDescriptions(std::vector<PolicyDescription> &descriptions) {
    (void) descriptions;
    return CYNARA_API_SUCCESS;
}

} // namespace Cynara
<commit_msg>Implement plugin description listing in admin logic<commit_after>/*
 *  Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 */
/**
 * @file        src/admin/logic/OnlineLogic.cpp
 * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
 * @author      Aleksander Zdyb <a.zdyb@samsung.com>
 * @author      Zofia Abramowska <z.abramowska@samsung.com>
 * @version     1.0
 * @brief       This file contains implementation of online version of Logic class
 */

#include <cinttypes>
#include <memory>

#include <cynara-error.h>
#include <common.h>
#include <config/PathConfig.h>
#include <exceptions/Exception.h>
#include <exceptions/UnexpectedErrorException.h>
#include <log/log.h>
#include <protocol/Protocol.h>
#include <protocol/ProtocolAdmin.h>
#include <request/AdminCheckRequest.h>
#include <request/DescriptionListRequest.h>
#include <request/EraseRequest.h>
#include <request/InsertOrUpdateBucketRequest.h>
#include <request/ListRequest.h>
#include <request/pointers.h>
#include <request/RemoveBucketRequest.h>
#include <request/SetPoliciesRequest.h>
#include <response/AdminCheckResponse.h>
#include <response/CodeResponse.h>
#include <response/DescriptionListResponse.h>
#include <response/ListResponse.h>
#include <response/pointers.h>
#include <sockets/SocketClient.h>
#include <types/ProtocolFields.h>

#include "OnlineLogic.h"

namespace Cynara {

OnlineLogic::OnlineLogic() {
    m_socketClient = std::make_shared<SocketClient>(PathConfig::SocketPath::admin,
                                                    std::make_shared<ProtocolAdmin>());
}

ProtocolFrameSequenceNumber generateSequenceNumber(void) {
    static ProtocolFrameSequenceNumber sequenceNumber = 0;
    return ++sequenceNumber;
}

bool OnlineLogic::ensureConnection(void) {
    return m_socketClient->isConnected() || m_socketClient->connect();
}

template<typename Req, typename Res, typename... ReqArgs>
int OnlineLogic::getResponse(std::shared_ptr<Res> &retResponse, ReqArgs... args) {
    if (!ensureConnection()) {
        LOGE("Cannot connect to cynara. Service not available.");
        return CYNARA_API_SERVICE_NOT_AVAILABLE;
    }

    ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber();

    RequestPtr request = std::make_shared<Req>(args..., sequenceNumber);
    ResponsePtr response;
    while (!(response = m_socketClient->askCynaraServer(request))) {
        if (!m_socketClient->connect())
            return CYNARA_API_SERVICE_NOT_AVAILABLE;
    }

    retResponse = std::dynamic_pointer_cast<Res>(response);
    if (!retResponse) {
        LOGC("Critical error. Casting Response failed.");
        return CYNARA_API_UNKNOWN_ERROR;
    }

    return CYNARA_API_SUCCESS;
}

static int interpretCodeResponse(const CodeResponse::Code &code) {
    LOGD("codeResponse: code [%" PRIu16 "]", code);
    switch (code) {
        case CodeResponse::Code::OK:
            LOGI("Cynara command finished successfully.");
            return CYNARA_API_SUCCESS;
        case CodeResponse::Code::NOT_ALLOWED:
            LOGE("Cynara service answered: Operation not allowed.");
            return CYNARA_API_OPERATION_NOT_ALLOWED;
        case CodeResponse::Code::NO_BUCKET:
            LOGE("Trying to use unexisting bucket.");
            return CYNARA_API_BUCKET_NOT_FOUND;
        case CodeResponse::Code::FAILED:
            LOGC("Cynara service answered: Operation failed.");
            return CYNARA_API_OPERATION_FAILED;
        default:
            LOGE("Unexpected response code from server: [%d]",
                 static_cast<int>(code));
            return CYNARA_API_UNKNOWN_ERROR;
    }
}

int OnlineLogic::setPolicies(const ApiInterface::PoliciesByBucket &insertOrUpdate,
                       const ApiInterface::KeysByBucket &remove) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<SetPoliciesRequest>(codeResponse, insertOrUpdate, remove);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::insertOrUpdateBucket(const PolicyBucketId &bucket,
                                const PolicyResult &policyResult) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<InsertOrUpdateBucketRequest>(codeResponse, bucket, policyResult);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::removeBucket(const PolicyBucketId &bucket) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<RemoveBucketRequest>(codeResponse, bucket);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const PolicyKey &key,
                      PolicyResult &result) {
    AdminCheckResponsePtr adminCheckResponse;
    int ret = getResponse<AdminCheckRequest>(adminCheckResponse, key, startBucket, recursive);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    LOGD("AdminCheckResponse: policyType [%" PRIu16 "], metadata <%s>, bucketValid [%d]",
         adminCheckResponse->result().policyType(), adminCheckResponse->result().metadata().c_str(),
         static_cast<int>(adminCheckResponse->isBucketValid()));

    if (!adminCheckResponse->isBucketValid()) {
        LOGE("Bucket <%s> provided as startBucket in adminCheck does not exist in cynara database",
             startBucket.c_str());
        return CYNARA_API_BUCKET_NOT_FOUND;
    }

    result = adminCheckResponse->result();
    return CYNARA_API_SUCCESS;
}

int OnlineLogic::listPolicies(const PolicyBucketId &bucket, const PolicyKey &filter,
                        std::vector<Policy> &policies) {
    ListResponsePtr listResponse;
    int ret = getResponse<ListRequest>(listResponse, bucket, filter);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    LOGD("listResponse: number of policies [%zu], bucketValid [%d]",
         listResponse->policies().size(), listResponse->isBucketValid());

    if (!listResponse->isBucketValid()) {
        return CYNARA_API_BUCKET_NOT_FOUND;
    }

    policies = listResponse->policies();
    return CYNARA_API_SUCCESS;
}

int OnlineLogic::erasePolicies(const PolicyBucketId &startBucket, bool recursive,
                         const PolicyKey &filter) {
    CodeResponsePtr codeResponse;
    int ret = getResponse<EraseRequest>(codeResponse, startBucket, recursive, filter);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    return interpretCodeResponse(codeResponse->m_code);
}

int OnlineLogic::listDescriptions(std::vector<PolicyDescription> &descriptions) {
    DescriptionListResponsePtr descrResponse;
    int ret = getResponse<DescriptionListRequest>(descrResponse);
    if (ret != CYNARA_API_SUCCESS) {
        return ret;
    }

    LOGD("descriptionListResponse: number of plugin descriptions [%zu]",
         descrResponse->descriptions().size());

    descriptions = descrResponse->descriptions();
    return CYNARA_API_SUCCESS;
}

} // namespace Cynara
<|endoftext|>


<commit_before>/*
C++ implementation of the PCA fitter

L.Storchi, A.Modak, S.R.Chowdhury : 2016
*/
#include "../interface/PCATrackFitter.h"
#include "../interface/pcaconst.hpp"

namespace
{
  /* quick and very dirty */
  void dump_element (const pca::matrixpcaconst<double> & in, std::ostream & out)
  {
    out.precision(6);
    for (unsigned int i = 0; i<in.n_rows(); ++i)
    {
      for (unsigned int j = 0; j<in.n_cols(); ++j)
        out << std::scientific << in(i, j) << " ";
      out << std::endl;
    }
  }

  bool import_pca_const (const std::string & cfname,
      pca::matrixpcaconst<double> & cmtx_rz,
      pca::matrixpcaconst<double> & qvec_rz,
      pca::matrixpcaconst<double> & amtx_rz,
      pca::matrixpcaconst<double> & kvec_rz,
      pca::matrixpcaconst<double> & cmtx_rphi,
      pca::matrixpcaconst<double> & qvec_rphi,
      pca::matrixpcaconst<double> & amtx_rphi,
      pca::matrixpcaconst<double> & kvec_rphi,
      double eta, double pt,
      int chargesignin)
  {
    std::vector<pca::matrixpcaconst<double> > vct;
    if (pca::read_pcacosnt_from_file (vct, cfname.c_str()))
    {
      int hwmanygot = 0;
      std::vector<pca::matrixpcaconst<double> >::const_iterator it =
        vct.begin();
      for (; it != vct.end(); ++it)
      {
        double ptmin, ptmax, etamin, etamax;
        int chargesign;

        it->get_ptrange(ptmin, ptmax);
        it->get_etarange(etamin, etamax);
        chargesign = it->get_chargesign();

        if (it->get_plane_type() == pca::matrixpcaconst<double>::RZ)
        {
          if ((eta >= etamin) && (eta <= etamax))
          {
            switch(it->get_const_type())
            {
              case pca::matrixpcaconst<double>::QVEC :
                qvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::KVEC :
                kvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::CMTX :
                cmtx_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::AMTX :
                amtx_rz = *it;
                hwmanygot++;
                break;
              default:
                break;
            }
          }
        }
        else if (it->get_plane_type() == pca::matrixpcaconst<double>::RPHI)
        {
          if (chargesignin == chargesign)
          {
            if ((pt >= ptmin) && (pt <= ptmax))
            {
              switch(it->get_const_type())
              {
                case pca::matrixpcaconst<double>::QVEC :
                  qvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::KVEC :
                  kvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::CMTX :
                  cmtx_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::AMTX :
                  amtx_rphi = *it;
                  hwmanygot++;
                  break;
                default:
                  break;
              }
            }
          }
        }
      }

      if (hwmanygot == 8)
        return true;
      else
      {
        std::cerr << "Found " << hwmanygot << " const instead of 8" << std::endl;
        return false;
      }
    }

    // TODO add consistency check for dims

    return false;
  }
}

PCATrackFitter::PCATrackFitter():TrackFitter(0)
{
}

PCATrackFitter::PCATrackFitter(int nb):TrackFitter(nb)
{
}

PCATrackFitter::~PCATrackFitter()
{
}

void PCATrackFitter::initialize()
{
}

void PCATrackFitter::mergePatterns()
{
}

// Tentative duplicate removal
// Not used for the moment

void PCATrackFitter::mergeTracks()
{
  unsigned int index = 0;
  vector<Track*>::iterator it = tracks.begin();

  while(it!=tracks.end())
  {
    Track* newTrack = *it;
    bool found = false;
    for(unsigned int i=0;i<index;i++)
    {
      Track* ref = tracks[i];
      float dpt,dphi,dz,deta;
      dpt = fabs(newTrack->getCurve()-ref->getCurve());
      dphi = fabs(newTrack->getPhi0()-ref->getPhi0());
      dz = fabs(newTrack->getZ0()-ref->getZ0());
      deta = fabs(newTrack->getEta0()-ref->getEta0());
      found = (deta<0.02) &&
	(dphi<0.005) &&
	(dpt<0.1) &&
	(dz<0.3);

      if(found)
	break;
    }

    if(found)
      tracks.erase(it);
    else
    {
      index++;
      it++;
    }
  }
}

void PCATrackFitter::setTracks(const std::vector<Track*> & intc)
{
  tracks_ = intc;
}

void PCATrackFitter::fit(vector<Hit*> hits)
{
  int tow = sector_id; // The tower ID, necessary to get the phi shift

  std::cout << "In PCA::fit tow: " << tow << std::endl;

  double sec_phi = 0;
  switch (tow%8)
  {
    case 0:
      sec_phi = 0.4;
      break;
    case 1:
      sec_phi = 1.2;
      break;
    case 3:
      sec_phi = 2.0;
      break;
    case 4:
      sec_phi = 2.7;
      break;
    case 5:
      sec_phi = -2.0;
      break;
    case 6:
      sec_phi = -1.2;
      break;
    case 7:
      sec_phi = -0.4;
      break;
  }

  double ci = cos(sec_phi);
  double si = sin(sec_phi);

  //std::cout << "tracks_.size() : " << tracks_.size() << std::endl;

  /*
  std::ofstream xyzfile;
  xyzfile.open ("PCAxyzfile.txt");

  std::ofstream rpzfile;
  rpzfile.open ("PCArphizfile.txt");
  */

  for(unsigned int tt=0; tt<tracks_.size(); ++tt)
  {
    //vector<int> stubids = tracks_[tt]->getStubs(); // TODO are they the hits idx ?

    //std::cout << "hits.size() : " << hits.size() << std::endl;

    if (hits.size() == 6)
    {
      pca::matrixpcaconst<double> zrv(2, 6), phirv(2, 6);

      for(unsigned int idx = 0; idx < hits.size(); ++idx)
      {
        double xi =  hits[idx]->getX()*ci+ hits[idx]->getY()*si;
        double yi = -hits[idx]->getX()*si+ hits[idx]->getY()*ci;

        double zi = hits[idx]->getZ();
        double ri = sqrt(xi*xi+yi*yi);
        double pi = atan2(yi,xi);

        std::cout << "PCAxyz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        std::cout << "PCArpz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        /*
        xyzfile << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        rpzfile << ri << " " << pi << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;
        */

        zrv(0, idx) = zi;
        zrv(1, idx) = ri;

        phirv(0, idx) = pi;
        phirv(1, idx) = ri;
      }

      int charge;
      double pt_est, eta_est, z0_est, phi_est;
      charge = tracks_[tt]->getCharge();
      pt_est = tracks_[tt]->getCurve();
      eta_est = tracks_[tt]->getEta0();
      z0_est = tracks_[tt]->getZ0 ();
      phi_est = tracks_[tt]->getPhi0();

      /* */
      zrv(0, 0) = -16.1314; zrv(1, 0) = 23.3135;
      zrv(0, 1) = -22.7054; zrv(1, 1) = 34.8367;
      zrv(0, 2) = -32.6362; zrv(1, 2) = 51.9131;
      eta_est = -0.580448;
      z0_est = -2.65203;

      phirv(0, 0) = 2.74588; phirv(0, 0) = 23.2105;
      phirv(0, 1) = 2.76857; phirv(0, 1) = 37.0286;
      phirv(0, 2) = 2.79267; phirv(0, 2) = 51.2692;
      phirv(0, 3) = 2.82109; phirv(0, 3) = 67.7289;
      phirv(0, 4) = 2.85643; phirv(0, 4) = 87.8179;
      phirv(0, 5) = 2.89452; phirv(0, 5) = 109.012;
      pt_est = 1.0/0.315806;
      phi_est = 2.70006;
      charge = +1;

      std::string cfname = "./barrel_tow18_pca_const.txt";

      pca::matrixpcaconst<double> cmtx_rz(0, 0);
      pca::matrixpcaconst<double> qvec_rz(0, 0);
      pca::matrixpcaconst<double> amtx_rz(0, 0);
      pca::matrixpcaconst<double> kvec_rz(0, 0);
      pca::matrixpcaconst<double> cmtx_rphi(0, 0);
      pca::matrixpcaconst<double> qvec_rphi(0, 0);
      pca::matrixpcaconst<double> amtx_rphi(0, 0);
      pca::matrixpcaconst<double> kvec_rphi(0, 0);

      if (import_pca_const (cfname,
                            cmtx_rz,
                            qvec_rz,
                            amtx_rz,
                            kvec_rz,
                            cmtx_rphi,
                            qvec_rphi,
                            amtx_rphi,
                            kvec_rphi,
                            eta_est,
                            pt_est,
                            charge))
      {
        std::cout << "CMTX RZ: " << std::endl;
        dump_element(cmtx_rz, std::cout);

        std::cout << "QVEC RZ: " << std::endl;
        dump_element(cmtx_rz, std::cout);

        std::cout << "CMTX RPHI: " << std::endl;
        dump_element(cmtx_rphi, std::cout);

        std::cout << "QVEC RPHI: " << std::endl;
        dump_element(cmtx_rphi, std::cout);

        double cottheta = 0.0; // eta
        double z0 = 0.0;

        cottheta = qvec_rz(0,0);
        z0 = qvec_rz(0,1);
        for (int i=0; i<(int)cmtx_rz.n_cols(); ++i)
        {
          cottheta += cmtx_rz(0, i) * zrv(0, i);
          z0 += cmtx_rz(1, i) * zrv(1, i);
        }

        double coverpt = 0.0; // pt
        double phi = 0.0;

        coverpt = qvec_rphi(0,0);
        phi = qvec_rphi(0,1);
        for (int i=0; i<(int)cmtx_rphi.n_cols(); ++i)
        {
          /*
          coverpt += cmtx_rphi(0, i) * phirv(0, i);
          phi += cmtx_rphi(1, i) * phirv(1, i);
          */
        }

        double pt = (double)(charge)/coverpt;

        // TODO: checkit theta to eta
        double eta = 0.0e0;
        double theta = atan(1.0e0 / cottheta);
        double tantheta2 = tan (theta/2.0e0);
        if (tantheta2 < 0.0)
          eta = 1.0e0 * log (-1.0e0 * tantheta2);
        else
          eta = -1.0e0 * log (tantheta2);

        Track* fit_track = new Track();

        std::cout << " pt : " << pt << " ==> " << pt_est << std::endl;
        std::cout << " eta: " << eta << " ==> " << eta_est << std::endl;
        std::cout << " z0 : " << z0 << " ==> " << z0_est << std::endl;
        std::cout << " phi: " << phi << " ==> " << phi_est << std::endl;

        fit_track->setCurve(pt);
        fit_track->setPhi0(phi);
        fit_track->setEta0(eta);
        fit_track->setZ0(z0);

        for(unsigned int idx = 0; idx < hits.size(); ++idx)
          fit_track->addStubIndex(idx);

        tracks.push_back(fit_track);
      }
      else
      {
        std::cerr << "error while reading PCA const" << std::endl;
        std::cout << "error while reading PCA const" << std::endl;
      }

    }
    else
    {
      // TODO non 6 layers
    }
  }

  /*
  xyzfile.close();
  rpzfile.close();

  std::cout << "Close files" << std::endl;
  */
}

void PCATrackFitter::fit()
{

  vector<Hit*> activatedHits;

  //////// Get the list of unique stubs from the tracks ///////////

  // TODO not sure will work as it is now need to deal with given
  //      tracks

  set<int> ids;
  int total=0;
  for (unsigned int i=0; i<patterns.size(); ++i)
  {
    vector<Hit*> allHits = patterns[i]->getHits();
    total+=allHits.size();
    for(unsigned int j=0; j<allHits.size(); ++j)
    {
      pair<set<int>::iterator,bool> result = ids.insert(allHits[j]->getID());
      if (result.second == true )
        activatedHits.push_back(allHits[j]);
    }
  }

  fit(activatedHits);
}

TrackFitter* PCATrackFitter::clone()
{
  PCATrackFitter* fit = new PCATrackFitter(nb_layers);

  // TODO

  return fit;
}

<commit_msg>backup<commit_after>/*
C++ implementation of the PCA fitter

L.Storchi, A.Modak, S.R.Chowdhury : 2016
*/
#include "../interface/PCATrackFitter.h"
#include "../interface/pcaconst.hpp"

namespace
{
  /* quick and very dirty */
  void dump_element (const pca::matrixpcaconst<double> & in, std::ostream & out)
  {
    out.precision(6);
    for (unsigned int i = 0; i<in.n_rows(); ++i)
    {
      for (unsigned int j = 0; j<in.n_cols(); ++j)
        out << std::scientific << in(i, j) << " ";
      out << std::endl;
    }
  }

  bool import_pca_const (const std::string & cfname,
      pca::matrixpcaconst<double> & cmtx_rz,
      pca::matrixpcaconst<double> & qvec_rz,
      pca::matrixpcaconst<double> & amtx_rz,
      pca::matrixpcaconst<double> & kvec_rz,
      pca::matrixpcaconst<double> & cmtx_rphi,
      pca::matrixpcaconst<double> & qvec_rphi,
      pca::matrixpcaconst<double> & amtx_rphi,
      pca::matrixpcaconst<double> & kvec_rphi,
      double eta, double pt,
      int chargesignin)
  {
    std::vector<pca::matrixpcaconst<double> > vct;
    if (pca::read_pcacosnt_from_file (vct, cfname.c_str()))
    {
      int hwmanygot = 0;
      std::vector<pca::matrixpcaconst<double> >::const_iterator it =
        vct.begin();
      for (; it != vct.end(); ++it)
      {
        double ptmin, ptmax, etamin, etamax;
        int chargesign;

        it->get_ptrange(ptmin, ptmax);
        it->get_etarange(etamin, etamax);
        chargesign = it->get_chargesign();

        if (it->get_plane_type() == pca::matrixpcaconst<double>::RZ)
        {
          if ((eta >= etamin) && (eta <= etamax))
          {
            switch(it->get_const_type())
            {
              case pca::matrixpcaconst<double>::QVEC :
                qvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::KVEC :
                kvec_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::CMTX :
                cmtx_rz = *it;
                hwmanygot++;
                break;
              case pca::matrixpcaconst<double>::AMTX :
                amtx_rz = *it;
                hwmanygot++;
                break;
              default:
                break;
            }
          }
        }
        else if (it->get_plane_type() == pca::matrixpcaconst<double>::RPHI)
        {
          if (chargesignin == chargesign)
          {
            if ((pt >= ptmin) && (pt <= ptmax))
            {
              switch(it->get_const_type())
              {
                case pca::matrixpcaconst<double>::QVEC :
                  qvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::KVEC :
                  kvec_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::CMTX :
                  cmtx_rphi = *it;
                  hwmanygot++;
                  break;
                case pca::matrixpcaconst<double>::AMTX :
                  amtx_rphi = *it;
                  hwmanygot++;
                  break;
                default:
                  break;
              }
            }
          }
        }
      }

      if (hwmanygot == 8)
        return true;
      else
      {
        std::cerr << "Found " << hwmanygot << " const instead of 8" << std::endl;
        return false;
      }
    }

    // TODO add consistency check for dims

    return false;
  }
}

PCATrackFitter::PCATrackFitter():TrackFitter(0)
{
}

PCATrackFitter::PCATrackFitter(int nb):TrackFitter(nb)
{
}

PCATrackFitter::~PCATrackFitter()
{
}

void PCATrackFitter::initialize()
{
}

void PCATrackFitter::mergePatterns()
{
}

// Tentative duplicate removal
// Not used for the moment

void PCATrackFitter::mergeTracks()
{
  unsigned int index = 0;
  vector<Track*>::iterator it = tracks.begin();

  while(it!=tracks.end())
  {
    Track* newTrack = *it;
    bool found = false;
    for(unsigned int i=0;i<index;i++)
    {
      Track* ref = tracks[i];
      float dpt,dphi,dz,deta;
      dpt = fabs(newTrack->getCurve()-ref->getCurve());
      dphi = fabs(newTrack->getPhi0()-ref->getPhi0());
      dz = fabs(newTrack->getZ0()-ref->getZ0());
      deta = fabs(newTrack->getEta0()-ref->getEta0());
      found = (deta<0.02) &&
	(dphi<0.005) &&
	(dpt<0.1) &&
	(dz<0.3);

      if(found)
	break;
    }

    if(found)
      tracks.erase(it);
    else
    {
      index++;
      it++;
    }
  }
}

void PCATrackFitter::setTracks(const std::vector<Track*> & intc)
{
  tracks_ = intc;
}

void PCATrackFitter::fit(vector<Hit*> hits)
{
  int tow = sector_id; // The tower ID, necessary to get the phi shift

  std::cout << "In PCA::fit tow: " << tow << std::endl;

  double sec_phi = 0;
  switch (tow%8)
  {
    case 0:
      sec_phi = 0.4;
      break;
    case 1:
      sec_phi = 1.2;
      break;
    case 3:
      sec_phi = 2.0;
      break;
    case 4:
      sec_phi = 2.7;
      break;
    case 5:
      sec_phi = -2.0;
      break;
    case 6:
      sec_phi = -1.2;
      break;
    case 7:
      sec_phi = -0.4;
      break;
  }

  double ci = cos(sec_phi);
  double si = sin(sec_phi);

  //std::cout << "tracks_.size() : " << tracks_.size() << std::endl;

  /*
  std::ofstream xyzfile;
  xyzfile.open ("PCAxyzfile.txt");

  std::ofstream rpzfile;
  rpzfile.open ("PCArphizfile.txt");
  */

  for(unsigned int tt=0; tt<tracks_.size(); ++tt)
  {
    //vector<int> stubids = tracks_[tt]->getStubs(); // TODO are they the hits idx ?

    //std::cout << "hits.size() : " << hits.size() << std::endl;

    if (hits.size() == 6)
    {
      pca::matrixpcaconst<double> zrv(2, 6), phirv(2, 6);

      for(unsigned int idx = 0; idx < hits.size(); ++idx)
      {
        double xi =  hits[idx]->getX()*ci+ hits[idx]->getY()*si;
        double yi = -hits[idx]->getX()*si+ hits[idx]->getY()*ci;

        double zi = hits[idx]->getZ();
        double ri = sqrt(xi*xi+yi*yi);
        double pi = atan2(yi,xi);

        std::cout << "PCAxyz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        std::cout << "PCArpz " << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        /*
        xyzfile << xi << " " << yi << " " << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;

        rpzfile << ri << " " << pi << zi << " " <<
          (int) hits[idx]->getLayer() << std::endl;
        */

        zrv(0, idx) = zi;
        zrv(1, idx) = ri;

        phirv(0, idx) = pi;
        phirv(1, idx) = ri;
      }

      int charge;
      double pt_est, eta_est, z0_est, phi_est;
      charge = tracks_[tt]->getCharge();
      pt_est = tracks_[tt]->getCurve();
      eta_est = tracks_[tt]->getEta0();
      z0_est = tracks_[tt]->getZ0 ();
      phi_est = tracks_[tt]->getPhi0();

      /* */
      zrv(0, 0) = -16.1314; zrv(1, 0) = 23.3135;
      zrv(0, 1) = -22.7054; zrv(1, 1) = 34.8367;
      zrv(0, 2) = -32.6362; zrv(1, 2) = 51.9131;
      eta_est = -0.580448;
      z0_est = -2.65203;

      phirv(0, 0) = 2.74588; phirv(0, 0) = 23.2105;
      phirv(0, 1) = 2.76857; phirv(0, 1) = 37.0286;
      phirv(0, 2) = 2.79267; phirv(0, 2) = 51.2692;
      phirv(0, 3) = 2.82109; phirv(0, 3) = 67.7289;
      phirv(0, 4) = 2.85643; phirv(0, 4) = 87.8179;
      phirv(0, 5) = 2.89452; phirv(0, 5) = 109.012;
      pt_est = 1.0/0.315806;
      phi_est = 2.70006;
      charge = +1;

      std::string cfname = "./barrel_tow18_pca_const.txt";

      pca::matrixpcaconst<double> cmtx_rz(0, 0);
      pca::matrixpcaconst<double> qvec_rz(0, 0);
      pca::matrixpcaconst<double> amtx_rz(0, 0);
      pca::matrixpcaconst<double> kvec_rz(0, 0);
      pca::matrixpcaconst<double> cmtx_rphi(0, 0);
      pca::matrixpcaconst<double> qvec_rphi(0, 0);
      pca::matrixpcaconst<double> amtx_rphi(0, 0);
      pca::matrixpcaconst<double> kvec_rphi(0, 0);

      if (import_pca_const (cfname,
                            cmtx_rz,
                            qvec_rz,
                            amtx_rz,
                            kvec_rz,
                            cmtx_rphi,
                            qvec_rphi,
                            amtx_rphi,
                            kvec_rphi,
                            eta_est,
                            pt_est,
                            charge))
      {
        std::cout << "CMTX RZ: " << std::endl;
        dump_element(cmtx_rz, std::cout);

        std::cout << "QVEC RZ: " << std::endl;
        dump_element(qvec_rz, std::cout);

        std::cout << "CMTX RPHI: " << std::endl;
        dump_element(cmtx_rphi, std::cout);

        std::cout << "QVEC RPHI: " << std::endl;
        dump_element(qvec_rphi, std::cout);

        double cottheta = 0.0; // eta
        double z0 = 0.0;

        cottheta = qvec_rz(0,0);
        z0 = qvec_rz(0,1);
        for (int i=0; i<(int)cmtx_rz.n_cols(); ++i)
        {
          cottheta += cmtx_rz(0, i) * zrv(0, i);
          z0 += cmtx_rz(1, i) * zrv(1, i);
        }

        double coverpt = 0.0; // pt
        double phi = 0.0;

        coverpt = qvec_rphi(0,0);
        phi = qvec_rphi(0,1);
        for (int i=0; i<(int)cmtx_rphi.n_cols(); ++i)
        {
          std::cout << i
          coverpt += cmtx_rphi(0, i) * phirv(0, i);
          phi += cmtx_rphi(1, i) * phirv(1, i);
        }

        double pt = (double)(charge)/coverpt;

        // TODO: checkit theta to eta
        double eta = 0.0e0;
        double theta = atan(1.0e0 / cottheta);
        double tantheta2 = tan (theta/2.0e0);
        if (tantheta2 < 0.0)
          eta = 1.0e0 * log (-1.0e0 * tantheta2);
        else
          eta = -1.0e0 * log (tantheta2);

        Track* fit_track = new Track();

        std::cout << " pt : " << pt << " ==> " << pt_est << std::endl;
        std::cout << " eta: " << eta << " ==> " << eta_est << std::endl;
        std::cout << " z0 : " << z0 << " ==> " << z0_est << std::endl;
        std::cout << " phi: " << phi << " ==> " << phi_est << std::endl;

        fit_track->setCurve(pt);
        fit_track->setPhi0(phi);
        fit_track->setEta0(eta);
        fit_track->setZ0(z0);

        for(unsigned int idx = 0; idx < hits.size(); ++idx)
          fit_track->addStubIndex(idx);

        tracks.push_back(fit_track);
      }
      else
      {
        std::cerr << "error while reading PCA const" << std::endl;
        std::cout << "error while reading PCA const" << std::endl;
      }

    }
    else
    {
      // TODO non 6 layers
    }
  }

  /*
  xyzfile.close();
  rpzfile.close();

  std::cout << "Close files" << std::endl;
  */
}

void PCATrackFitter::fit()
{

  vector<Hit*> activatedHits;

  //////// Get the list of unique stubs from the tracks ///////////

  // TODO not sure will work as it is now need to deal with given
  //      tracks

  set<int> ids;
  int total=0;
  for (unsigned int i=0; i<patterns.size(); ++i)
  {
    vector<Hit*> allHits = patterns[i]->getHits();
    total+=allHits.size();
    for(unsigned int j=0; j<allHits.size(); ++j)
    {
      pair<set<int>::iterator,bool> result = ids.insert(allHits[j]->getID());
      if (result.second == true )
        activatedHits.push_back(allHits[j]);
    }
  }

  fit(activatedHits);
}

TrackFitter* PCATrackFitter::clone()
{
  PCATrackFitter* fit = new PCATrackFitter(nb_layers);

  // TODO

  return fit;
}

<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

using namespace NNCPU;

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training	= 60000;
	int number_test		= 10000;
	int time_step		= 28;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double decay_rate	 = 0.977;
	double learning_rate = 0.005;
	double noise		 = 0.001;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch **************************
	Neural_Networks NN = Neural_Networks(time_step);

	layer.push_back(NN.Add(new Layer("MNIST", 784 / time_step)));
	layer.push_back(NN.Add(new Layer("BN,LSTM", 100)));			 // batch normalization, LSTM forward direction
	layer.push_back(NN.Add(new Layer("BN,LSTM,backward", 100))); // batch normalization, LSTM backward direction
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));		 // cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W");			// fully connected
	layer[1]->Connect(layer[1], "W,recurrent"); // fully connected
	layer[2]->Connect(layer[0], "W");			// fully connected
	layer[2]->Connect(layer[2], "W,recurrent"); // fully connected
	layer[3]->Connect(layer[1], "W");			// fully connected
	layer[3]->Connect(layer[2], "W");			// fully connected

	srand(0); NN.Initialize(0.1, 0.1);

	{
		bool *time_mask = new bool[time_step];

		for (int t = 0; t < time_step; t++) {
			time_mask[t] = (t == 0 || t == time_step - 1);
		}
		layer.back()->Set_Time_Mask(time_mask);
	}
	// *********************************************

	// load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_BLSTM.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	omp_set_num_threads(number_threads);

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[time_step * number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	for (int h = 0; h < number_training + number_test; h++) {
		memcpy(&target_output[h][(time_step - 1) * number_nodes.back()], target_output[h], sizeof(float) * number_nodes.back());
	}
	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon, noise);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[time_step * number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax, index = (time_step - 1) * number_nodes.back(); g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j] + output[g][index + j]) {
							max = output[g][argmax = j] + output[g][index + j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<commit_msg>Update MNIST_BLSTM.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <time.h>

#include "../Neural_Networks.h"

void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **target_output) {
	ifstream file(training_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
	}

	file.open(training_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = 0; h < number_training; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
	}

	file.open(test_set_images, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 4; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char pixel;

			for (int j = 0; j < 28 * 28; j++) {
				file.read((char*)(&pixel), 1);
				input[h][j] = pixel / 255.0;
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
	}

	file.open(test_set_labels, ifstream::binary);

	if (file.is_open()) {
		for (int h = 0, value; h < 2; h++) {
			file.read((char*)(&value), sizeof(int));
		}
		for (int h = number_training; h < number_training + number_test; h++) {
			unsigned char label;

			file.read((char*)(&label), 1);

			for (int j = 0; j < 10; j++) {
				target_output[h][j] = (j == label);
			}
		}
		file.close();
	}
	else {
		cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
	}
}

int main() {
	int batch_size		= 60;
	int number_iterations = 50;
	int number_threads;
	int number_training	= 60000;
	int number_test		= 10000;
	int time_step		= 28;

	float **input = new float*[number_training + number_test];
	float **target_output = new float*[number_training + number_test];

	double epsilon		 = 0.001;
	double decay_rate	 = 0.977;
	double learning_rate = 0.005;
	double noise		 = 0.001;

	string path;

	vector<int> number_nodes = { 784, 10 };

	vector<Layer*> layer;

	// train from scratch **************************
	Neural_Networks NN = Neural_Networks(time_step);

	layer.push_back(NN.Add(new Layer("MNIST", 784 / time_step)));
	layer.push_back(NN.Add(new Layer("BN,LSTM", 100)));			 // batch normalization, LSTM forward direction
	layer.push_back(NN.Add(new Layer("BN,LSTM,backward", 100))); // batch normalization, LSTM backward direction
	layer.push_back(NN.Add(new Layer("CE,softmax", 10)));		 // cross-entropy loss, softmax activation

	layer[1]->Connect(layer[0], "W");			// fully connected
	layer[1]->Connect(layer[1], "W,recurrent"); // fully connected
	layer[2]->Connect(layer[0], "W");			// fully connected
	layer[2]->Connect(layer[2], "W,recurrent"); // fully connected
	layer[3]->Connect(layer[1], "W");			// fully connected
	layer[3]->Connect(layer[2], "W");			// fully connected

	srand(0); NN.Initialize(0.1, 0.1);

	{
		bool *time_mask = new bool[time_step];

		for (int t = 0; t < time_step; t++) {
			time_mask[t] = (t == 0 || t == time_step - 1);
		}
		layer.back()->Set_Time_Mask(time_mask);
	}
	// *********************************************

	// load pretrained model
	// Neural_Networks NN = Neural_Networks("MNIST_BLSTM.txt");

	cout << "The number of threads : ";
	cin >> number_threads;
	cin.ignore();

	omp_set_num_threads(number_threads);

	cout << "path where MNIST handwritten digits dataset is : ";
	getline(cin, path);

	for (int h = 0; h < number_training + number_test; h++) {
		input[h] = new float[number_nodes.front()];
		target_output[h] = new float[time_step * number_nodes.back()];
	}
	Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output);

	for (int h = 0; h < number_training + number_test; h++) {
		memcpy(&target_output[h][(time_step - 1) * number_nodes.back()], target_output[h], sizeof(float) * number_nodes.back());
	}
	for (int g = 0, time = clock(); g < number_iterations; g++) {
		int score[2] = { 0, };

		float **output = new float*[batch_size];

		double loss = NN.Train(batch_size, number_training, input, target_output, learning_rate, epsilon, noise);

		for (int h = 0; h < batch_size; h++) {
			output[h] = new float[time_step * number_nodes.back()];
		}
		for (int i = 0, h = 0; i < number_training + number_test; i++) {
			if (++h == batch_size || i == number_training + number_test - 1) {
				NN.Test(h, &input[i - h + 1], output);

				for (int g = 0, argmax, index = (time_step - 1) * number_nodes.back(); g < h; g++) {
					double max = 0;

					for (int j = 0; j < number_nodes.back(); j++) {
						if (max < output[g][j] + output[g][index + j]) {
							max = output[g][argmax = j] + output[g][index + j];
						}
					}
					score[(i - h + g + 1 < number_training) ? (0) : (1)] += (int)target_output[i - h + g + 1][argmax];
				}
				h = 0;
			}
		}
		printf("."); NN.Save("NN.txt");

		printf("score: %d / %d, %d / %d  loss: %lf  step %d  %.2lf sec\n", score[0], number_training, score[1], number_test, loss, g + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
		learning_rate *= decay_rate;

		for (int h = 0; h < batch_size; h++) {
			delete[] output[h];
		}
		delete[] output;
	}

	for (int h = 0; h < number_training + number_test; h++) {
		delete[] input[h];
		delete[] target_output[h];
	}
	delete[] input;
	delete[] target_output;

	return 0;
}
<|endoftext|>


<commit_before>// $Header: /home/cvsroot/yaz++/zoom/zexcept.cpp,v 1.1 2002-08-08 16:06:08 mike Exp $

// Z39.50 Exception classes

#include <errno.h>
#include <string.h>		// for strerror(), strlen(), strcpy()
#include <stdio.h>		// for sprintf()
#include <yaz/diagbib1.h>
#include "zoom++.h"

namespace ZOOM {
    exception::exception(int errcode) {
	code = errcode;
    }

    int exception::errcode() const {
	return code;
    }

    const char *exception::errmsg() const {
	static char buf[40];
	sprintf(buf, "error #%d", code);
	return buf;
    }

    systemException::systemException() : exception::exception(errno){
	code = errno;
    }

    int systemException::errcode() const {
	return code;
    }

    const char *systemException::errmsg() const {
	return strerror(code);
    }

    bib1Exception::bib1Exception(int errcode, const char *addinfo) :
	exception::exception(errcode) {
	info = new char[strlen(addinfo)+1];
	strcpy((char*) info, addinfo);
    }

    bib1Exception::~bib1Exception() {
	delete info;
    }

    int bib1Exception::errcode() const {
	return code;
    }

    const char *bib1Exception::errmsg() const {
	return diagbib1_str(code);
    }

    const char *bib1Exception::addinfo() const {
	return info;
    }

    queryException::queryException(int qtype, const char *source) :
	exception::exception(qtype) {
	q = new char[strlen(source)+1];
	strcpy((char*) q, source);
    }

    queryException::~queryException() {
	delete q;
    }

    int queryException::errcode() const {
	return code;
    }

    const char *queryException::errmsg() const {
	switch (code) {
	case PREFIX: return "bad prefix search";
	case CCL: return "bad CCL search";
	default: break;
	}
	return "bad search (unknown type)";
    }

    const char *queryException::addinfo() const {
	return q;
    }
}
<commit_msg>Add lots of commented-out debugging code, all to try to catch screwy memory-management semantics.  Since I couldn't find the real problem, in the end I just made ~bib1Exception() a no-op.<commit_after>// $Header: /home/cvsroot/yaz++/zoom/zexcept.cpp,v 1.2 2002-10-08 23:57:29 mike Exp $

// Z39.50 Exception classes

#include <errno.h>
#include <string.h>		// for strerror(), strlen(), strcpy()
#include <stdio.h>		// for sprintf()
#include <yaz/diagbib1.h>
#include "zoom++.h"

namespace ZOOM {
    exception::exception(int errcode) {
	code = errcode;
    }

    int exception::errcode() const {
	return code;
    }

    const char *exception::errmsg() const {
	static char buf[40];
	sprintf(buf, "error #%d", code);
	return buf;
    }

    systemException::systemException() : exception::exception(errno){
	code = errno;
    }

    int systemException::errcode() const {
	return code;
    }

    const char *systemException::errmsg() const {
	return strerror(code);
    }

    bib1Exception::bib1Exception(int errcode, const char *addinfo) :
	exception::exception(errcode) {
	info = new char[strlen(addinfo)+1];
	strcpy((char*) info, addinfo);
	//fprintf(stderr, "made new bib1Exception 0x%lx (%d, 0x%lx=%s)\n",
		//(long) this, code, (long) info, info);
    }

#if 0
    bib1Exception::bib1Exception(bib1Exception& src) :
	exception::exception(src) {
        code = src.code;
	info = new char[strlen(src.info)+1];
	strcpy((char*) info, src.info);
	//fprintf(stderr, "copied bib1Exception 0x%lx to 0x%lx (%d, 0x%lx=%s)\n",
		//(long) &src, (long) this, code, (long) info, info);
    }
#endif

    bib1Exception::~bib1Exception() {
	//fprintf(stderr, "deleting bib1Exception 0x%lx (%d, 0x%lx=%s)\n",
		//(long) this, code, (long) info, info);
	//delete info;
	//  ###	Don't actually do the deletion for now.  Exception
	//  reference semantics are too weird for me to grok so I'm
	//  doing The Wrong Thing in the knowledge that it will more
	//  or less work -- it just leaks memory.
    }

    int bib1Exception::errcode() const {
	return code;
    }

    const char *bib1Exception::errmsg() const {
	return diagbib1_str(code);
    }

    const char *bib1Exception::addinfo() const {
	return info;
    }

    queryException::queryException(int qtype, const char *source) :
	exception::exception(qtype) {
	q = new char[strlen(source)+1];
	strcpy((char*) q, source);
    }

    queryException::~queryException() {
	delete q;
    }

    int queryException::errcode() const {
	return code;
    }

    const char *queryException::errmsg() const {
	switch (code) {
	case PREFIX: return "bad prefix search";
	case CCL: return "bad CCL search";
	default: break;
	}
	return "bad search (unknown type)";
    }

    const char *queryException::addinfo() const {
	return q;
    }
}
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// 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 "google/cloud/storage/internal/curl_client.h"
#include "google/cloud/internal/make_unique.h"
#include "google/cloud/internal/setenv.h"
#include "google/cloud/storage/internal/curl_request_builder.h"
#include "google/cloud/storage/oauth2/credentials.h"
#include "google/cloud/storage/oauth2/google_credentials.h"
#include "google/cloud/testing_util/environment_variable_restore.h"
#include <gmock/gmock.h>
#include <memory>
#include <utility>
#include <vector>

namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
namespace {

using ::google::cloud::storage::oauth2::Credentials;
using ::testing::HasSubstr;

StatusCode const STATUS_ERROR_CODE = StatusCode::kUnavailable;
std::string const STATUS_ERROR_MSG =
    "FailingCredentials doing its job, failing";

// We create a credential class that always fails to fetch an access token; this
// allows us to check that CurlClient methods fail early when their setup steps
// (which include adding the authorization header) return a failure Status.
// Note that if the methods performing the setup steps were not templated, we
// could simply mock those out instead via MOCK_METHOD<N> macros.
class FailingCredentials : public Credentials {
 public:
  StatusOr<std::string> AuthorizationHeader() override {
    return Status(STATUS_ERROR_CODE, STATUS_ERROR_MSG);
  }
};

class CurlClientTest : public ::testing::Test,
                       public ::testing::WithParamInterface<std::string> {
 protected:
  CurlClientTest() : endpoint_("CLOUD_STORAGE_TESTBENCH_ENDPOINT") {}
  ~CurlClientTest() override { endpoint_.TearDown(); }

  void SetUp() override {
    std::string const error_type = GetParam();
    if (error_type == "credentials-failure") {
      client_ = CurlClient::Create(std::make_shared<FailingCredentials>());
      // We know exactly what error to expect, so setup the assertions to be
      // very strict.
      check_status_ = [](Status const& actual) {
        EXPECT_EQ(STATUS_ERROR_CODE, actual.code());
        EXPECT_THAT(actual.message(), HasSubstr(STATUS_ERROR_MSG));
      };
    } else if (error_type == "libcurl-failure") {
      google::cloud::internal::SetEnv("CLOUD_STORAGE_TESTBENCH_ENDPOINT",
                                      "http://localhost:0");
      client_ =
          CurlClient::Create(ClientOptions(oauth2::CreateAnonymousCredentials())
                                 .set_endpoint("http://localhost:0"));
      // We do not know what libcurl will return. Some kind of error, but varies
      // by version of libcurl. Just make sure it is an error and the CURL
      // details are included in the error message.
      check_status_ = [](Status const& actual) {
        EXPECT_FALSE(actual.ok());
        EXPECT_THAT(actual.message(), HasSubstr("CURL error"));
      };
    } else {
      FAIL() << "Invalid test parameter value: " << error_type
             << ", expected either credentials-failure or libcurl-failure";
    }
  }

  void CheckStatus(Status const& actual) { check_status_(actual); }

  void TearDown() override { client_.reset(); }

  std::shared_ptr<CurlClient> client_;
  std::function<void(Status const& status)> check_status_;
  testing_util::EnvironmentVariableRestore endpoint_;
};

TEST_P(CurlClientTest, UploadChunk) {
  // Use an invalid port (0) to force a libcurl failure
  auto actual =
      client_
          ->UploadChunk(UploadChunkRequest(
              "http://localhost:0/invalid-session-id", 0U, std::string{}, 0U))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, QueryResumableUpload) {
  // Use http://localhost:0 to force a libcurl failure
  auto actual = client_
                    ->QueryResumableUpload(QueryResumableUploadRequest(
                        "http://localhost:9/invalid-session-id"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListBuckets) {
  auto actual = client_->ListBuckets(ListBucketsRequest{"project_id"}).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateBucket) {
  auto actual = client_
                    ->CreateBucket(CreateBucketRequest(
                        "bkt", BucketMetadata().set_name("bkt")))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetBucketMetadata) {
  auto actual =
      client_->GetBucketMetadata(GetBucketMetadataRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteBucket) {
  auto actual = client_->DeleteBucket(DeleteBucketRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateBucket) {
  auto actual =
      client_
          ->UpdateBucket(UpdateBucketRequest(BucketMetadata().set_name("bkt")))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchBucket) {
  auto actual = client_
                    ->PatchBucket(PatchBucketRequest(
                        "bkt", BucketMetadata().set_name("bkt"),
                        BucketMetadata().set_name("bkt")))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetBucketIamPolicy) {
  auto actual =
      client_->GetBucketIamPolicy(GetBucketIamPolicyRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, SetBucketIamPolicy) {
  auto actual = client_
                    ->SetBucketIamPolicy(SetBucketIamPolicyRequest(
                        "bkt", google::cloud::IamPolicy{}))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, TestBucketIamPermissions) {
  auto actual =
      client_
          ->TestBucketIamPermissions(TestBucketIamPermissionsRequest("bkt", {}))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, LockBucketRetentionPolicy) {
  auto actual = client_
                    ->LockBucketRetentionPolicy(
                        LockBucketRetentionPolicyRequest("bkt", 0U))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, InsertObjectMediaSimple) {
  auto actual = client_
                    ->InsertObjectMedia(
                        InsertObjectMediaRequest("bkt", "obj", "contents")
                            .set_multiple_options(DisableMD5Hash(true),
                                                  DisableCrc32cChecksum(true)))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, InsertObjectMediaMultipart) {
  auto actual = client_
                    ->InsertObjectMedia(
                        InsertObjectMediaRequest("bkt", "obj", "contents"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, InsertObjectMediaXml) {
  auto actual =
      client_
          ->InsertObjectMedia(InsertObjectMediaRequest("bkt", "obj", "contents")
                                  .set_multiple_options(Fields("")))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetObjectMetadata) {
  auto actual =
      client_->GetObjectMetadata(GetObjectMetadataRequest("bkt", "obj"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ReadObjectXml) {
  auto actual =
      client_->ReadObject(ReadObjectRangeRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ReadObjectJson) {
  auto actual =
      client_
          ->ReadObject(ReadObjectRangeRequest("bkt", "obj")
                           .set_multiple_options(IfGenerationNotMatch(0)))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, WriteObject) {
  std::string const error_type = GetParam();
  if (error_type != "credentials-failure") {
    // TODO(#1735) - enable this test when ObjectWriteStream uses StatusOr.
    return;
  }
  auto actual =
      client_->WriteObject(InsertObjectStreamingRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListObjects) {
  auto actual = client_->ListObjects(ListObjectsRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteObject) {
  auto actual =
      client_->DeleteObject(DeleteObjectRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateObject) {
  auto actual =
      client_->UpdateObject(UpdateObjectRequest("bkt", "obj", ObjectMetadata()))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchObject) {
  auto actual = client_
                    ->PatchObject(PatchObjectRequest(
                        "bkt", "obj", ObjectMetadata(), ObjectMetadata()))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ComposeObject) {
  auto actual =
      client_->ComposeObject(ComposeObjectRequest("bkt", {}, "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListBucketAcl) {
  auto actual = client_->ListBucketAcl(ListBucketAclRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CopyObject) {
  auto actual =
      client_->CopyObject(CopyObjectRequest("bkt", "obj1", "bkt", "obj2"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateBucketAcl) {
  auto actual =
      client_->CreateBucketAcl(CreateBucketAclRequest("bkt", "entity", "role"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetBucketAcl) {
  auto actual =
      client_->GetBucketAcl(GetBucketAclRequest("bkt", "entity")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteBucketAcl) {
  auto actual =
      client_->DeleteBucketAcl(DeleteBucketAclRequest("bkt", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateBucketAcl) {
  auto actual =
      client_->UpdateBucketAcl(UpdateBucketAclRequest("bkt", "entity", "role"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchBucketAcl) {
  auto actual =
      client_
          ->PatchBucketAcl(PatchBucketAclRequest(
              "bkt", "entity", BucketAccessControl(), BucketAccessControl()))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListObjectAcl) {
  auto actual =
      client_->ListObjectAcl(ListObjectAclRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateObjectAcl) {
  auto actual = client_
                    ->CreateObjectAcl(
                        CreateObjectAclRequest("bkt", "obj", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteObjectAcl) {
  auto actual =
      client_->DeleteObjectAcl(DeleteObjectAclRequest("bkt", "obj", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetObjectAcl) {
  auto actual =
      client_->GetObjectAcl(GetObjectAclRequest("bkt", "obj", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateObjectAcl) {
  auto actual = client_
                    ->UpdateObjectAcl(
                        UpdateObjectAclRequest("bkt", "obj", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchObjectAcl) {
  auto actual = client_
                    ->PatchObjectAcl(PatchObjectAclRequest(
                        "bkt", "obj", "entity", ObjectAccessControl(),
                        ObjectAccessControl()))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, RewriteObject) {
  auto actual = client_
                    ->RewriteObject(RewriteObjectRequest("bkt", "obj", "bkt2",
                                                         "obj2", "token"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateResumableSession) {
  auto actual = client_
                    ->CreateResumableSession(
                        ResumableUploadRequest("test-bucket", "test-object"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListDefaultObjectAcl) {
  auto actual =
      client_->ListDefaultObjectAcl(ListDefaultObjectAclRequest("bkt"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateDefaultObjectAcl) {
  auto actual = client_
                    ->CreateDefaultObjectAcl(
                        CreateDefaultObjectAclRequest("bkt", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteDefaultObjectAcl) {
  auto actual = client_
                    ->DeleteDefaultObjectAcl(
                        DeleteDefaultObjectAclRequest("bkt", "entity"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetDefaultObjectAcl) {
  auto actual =
      client_->GetDefaultObjectAcl(GetDefaultObjectAclRequest("bkt", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateDefaultObjectAcl) {
  auto actual = client_
                    ->UpdateDefaultObjectAcl(
                        UpdateDefaultObjectAclRequest("bkt", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchDefaultObjectAcl) {
  auto actual =
      client_
          ->PatchDefaultObjectAcl(PatchDefaultObjectAclRequest(
              "bkt", "entity", ObjectAccessControl(), ObjectAccessControl()))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetServiceAccount) {
  auto actual =
      client_->GetServiceAccount(GetProjectServiceAccountRequest("project_id"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListHmacKeyRequest) {
  auto status =
      client_->ListHmacKeys(ListHmacKeysRequest("project_id")).status();
  CheckStatus(status);
}

TEST_P(CurlClientTest, CreateHmacKeyRequest) {
  auto actual =
      client_
          ->CreateHmacKey(CreateHmacKeyRequest("project_id", "service-account"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, SignBlob) {
  auto actual =
      client_
          ->SignBlob(SignBlobRequest("test-service-account", "test-blob", {}))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListNotifications) {
  auto actual =
      client_->ListNotifications(ListNotificationsRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateNotification) {
  auto actual = client_
                    ->CreateNotification(CreateNotificationRequest(
                        "bkt", NotificationMetadata()))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetNotification) {
  auto actual =
      client_->GetNotification(GetNotificationRequest("bkt", "notification_id"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteNotification) {
  auto actual = client_
                    ->DeleteNotification(
                        DeleteNotificationRequest("bkt", "notification_id"))
                    .status();
  CheckStatus(actual);
}

INSTANTIATE_TEST_SUITE_P(CredentialsFailure, CurlClientTest,
                         ::testing::Values("credentials-failure"));

INSTANTIATE_TEST_SUITE_P(LibCurlFailure, CurlClientTest,
                         ::testing::Values("libcurl-failure"));

}  // namespace
}  // namespace internal
}  // namespace STORAGE_CLIENT_NS
}  // namespace storage
}  // namespace cloud
}  // namespace google
<commit_msg>Enable unit test for WriteObject. (#2684)<commit_after>// Copyright 2018 Google LLC
//
// 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 "google/cloud/storage/internal/curl_client.h"
#include "google/cloud/internal/make_unique.h"
#include "google/cloud/internal/setenv.h"
#include "google/cloud/storage/internal/curl_request_builder.h"
#include "google/cloud/storage/oauth2/credentials.h"
#include "google/cloud/storage/oauth2/google_credentials.h"
#include "google/cloud/testing_util/environment_variable_restore.h"
#include <gmock/gmock.h>
#include <memory>
#include <utility>
#include <vector>

namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
namespace {

using ::google::cloud::storage::oauth2::Credentials;
using ::testing::HasSubstr;

StatusCode const STATUS_ERROR_CODE = StatusCode::kUnavailable;
std::string const STATUS_ERROR_MSG =
    "FailingCredentials doing its job, failing";

// We create a credential class that always fails to fetch an access token; this
// allows us to check that CurlClient methods fail early when their setup steps
// (which include adding the authorization header) return a failure Status.
// Note that if the methods performing the setup steps were not templated, we
// could simply mock those out instead via MOCK_METHOD<N> macros.
class FailingCredentials : public Credentials {
 public:
  StatusOr<std::string> AuthorizationHeader() override {
    return Status(STATUS_ERROR_CODE, STATUS_ERROR_MSG);
  }
};

class CurlClientTest : public ::testing::Test,
                       public ::testing::WithParamInterface<std::string> {
 protected:
  CurlClientTest() : endpoint_("CLOUD_STORAGE_TESTBENCH_ENDPOINT") {}
  ~CurlClientTest() override { endpoint_.TearDown(); }

  void SetUp() override {
    std::string const error_type = GetParam();
    if (error_type == "credentials-failure") {
      client_ = CurlClient::Create(std::make_shared<FailingCredentials>());
      // We know exactly what error to expect, so setup the assertions to be
      // very strict.
      check_status_ = [](Status const& actual) {
        EXPECT_EQ(STATUS_ERROR_CODE, actual.code());
        EXPECT_THAT(actual.message(), HasSubstr(STATUS_ERROR_MSG));
      };
    } else if (error_type == "libcurl-failure") {
      google::cloud::internal::SetEnv("CLOUD_STORAGE_TESTBENCH_ENDPOINT",
                                      "http://localhost:0");
      client_ =
          CurlClient::Create(ClientOptions(oauth2::CreateAnonymousCredentials())
                                 .set_endpoint("http://localhost:0"));
      // We do not know what libcurl will return. Some kind of error, but varies
      // by version of libcurl. Just make sure it is an error and the CURL
      // details are included in the error message.
      check_status_ = [](Status const& actual) {
        EXPECT_FALSE(actual.ok());
        EXPECT_THAT(actual.message(), HasSubstr("CURL error"));
      };
    } else {
      FAIL() << "Invalid test parameter value: " << error_type
             << ", expected either credentials-failure or libcurl-failure";
    }
  }

  void CheckStatus(Status const& actual) { check_status_(actual); }

  void TearDown() override { client_.reset(); }

  std::shared_ptr<CurlClient> client_;
  std::function<void(Status const& status)> check_status_;
  testing_util::EnvironmentVariableRestore endpoint_;
};

TEST_P(CurlClientTest, UploadChunk) {
  // Use an invalid port (0) to force a libcurl failure
  auto actual =
      client_
          ->UploadChunk(UploadChunkRequest(
              "http://localhost:0/invalid-session-id", 0U, std::string{}, 0U))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, QueryResumableUpload) {
  // Use http://localhost:0 to force a libcurl failure
  auto actual = client_
                    ->QueryResumableUpload(QueryResumableUploadRequest(
                        "http://localhost:9/invalid-session-id"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListBuckets) {
  auto actual = client_->ListBuckets(ListBucketsRequest{"project_id"}).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateBucket) {
  auto actual = client_
                    ->CreateBucket(CreateBucketRequest(
                        "bkt", BucketMetadata().set_name("bkt")))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetBucketMetadata) {
  auto actual =
      client_->GetBucketMetadata(GetBucketMetadataRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteBucket) {
  auto actual = client_->DeleteBucket(DeleteBucketRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateBucket) {
  auto actual =
      client_
          ->UpdateBucket(UpdateBucketRequest(BucketMetadata().set_name("bkt")))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchBucket) {
  auto actual = client_
                    ->PatchBucket(PatchBucketRequest(
                        "bkt", BucketMetadata().set_name("bkt"),
                        BucketMetadata().set_name("bkt")))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetBucketIamPolicy) {
  auto actual =
      client_->GetBucketIamPolicy(GetBucketIamPolicyRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, SetBucketIamPolicy) {
  auto actual = client_
                    ->SetBucketIamPolicy(SetBucketIamPolicyRequest(
                        "bkt", google::cloud::IamPolicy{}))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, TestBucketIamPermissions) {
  auto actual =
      client_
          ->TestBucketIamPermissions(TestBucketIamPermissionsRequest("bkt", {}))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, LockBucketRetentionPolicy) {
  auto actual = client_
                    ->LockBucketRetentionPolicy(
                        LockBucketRetentionPolicyRequest("bkt", 0U))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, InsertObjectMediaSimple) {
  auto actual = client_
                    ->InsertObjectMedia(
                        InsertObjectMediaRequest("bkt", "obj", "contents")
                            .set_multiple_options(DisableMD5Hash(true),
                                                  DisableCrc32cChecksum(true)))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, InsertObjectMediaMultipart) {
  auto actual = client_
                    ->InsertObjectMedia(
                        InsertObjectMediaRequest("bkt", "obj", "contents"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, InsertObjectMediaXml) {
  auto actual =
      client_
          ->InsertObjectMedia(InsertObjectMediaRequest("bkt", "obj", "contents")
                                  .set_multiple_options(Fields("")))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetObjectMetadata) {
  auto actual =
      client_->GetObjectMetadata(GetObjectMetadataRequest("bkt", "obj"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ReadObjectXml) {
  auto actual =
      client_->ReadObject(ReadObjectRangeRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ReadObjectJson) {
  auto actual =
      client_
          ->ReadObject(ReadObjectRangeRequest("bkt", "obj")
                           .set_multiple_options(IfGenerationNotMatch(0)))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, WriteObject) {
  auto actual =
      client_->WriteObject(InsertObjectStreamingRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListObjects) {
  auto actual = client_->ListObjects(ListObjectsRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteObject) {
  auto actual =
      client_->DeleteObject(DeleteObjectRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateObject) {
  auto actual =
      client_->UpdateObject(UpdateObjectRequest("bkt", "obj", ObjectMetadata()))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchObject) {
  auto actual = client_
                    ->PatchObject(PatchObjectRequest(
                        "bkt", "obj", ObjectMetadata(), ObjectMetadata()))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ComposeObject) {
  auto actual =
      client_->ComposeObject(ComposeObjectRequest("bkt", {}, "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListBucketAcl) {
  auto actual = client_->ListBucketAcl(ListBucketAclRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CopyObject) {
  auto actual =
      client_->CopyObject(CopyObjectRequest("bkt", "obj1", "bkt", "obj2"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateBucketAcl) {
  auto actual =
      client_->CreateBucketAcl(CreateBucketAclRequest("bkt", "entity", "role"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetBucketAcl) {
  auto actual =
      client_->GetBucketAcl(GetBucketAclRequest("bkt", "entity")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteBucketAcl) {
  auto actual =
      client_->DeleteBucketAcl(DeleteBucketAclRequest("bkt", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateBucketAcl) {
  auto actual =
      client_->UpdateBucketAcl(UpdateBucketAclRequest("bkt", "entity", "role"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchBucketAcl) {
  auto actual =
      client_
          ->PatchBucketAcl(PatchBucketAclRequest(
              "bkt", "entity", BucketAccessControl(), BucketAccessControl()))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListObjectAcl) {
  auto actual =
      client_->ListObjectAcl(ListObjectAclRequest("bkt", "obj")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateObjectAcl) {
  auto actual = client_
                    ->CreateObjectAcl(
                        CreateObjectAclRequest("bkt", "obj", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteObjectAcl) {
  auto actual =
      client_->DeleteObjectAcl(DeleteObjectAclRequest("bkt", "obj", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetObjectAcl) {
  auto actual =
      client_->GetObjectAcl(GetObjectAclRequest("bkt", "obj", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateObjectAcl) {
  auto actual = client_
                    ->UpdateObjectAcl(
                        UpdateObjectAclRequest("bkt", "obj", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchObjectAcl) {
  auto actual = client_
                    ->PatchObjectAcl(PatchObjectAclRequest(
                        "bkt", "obj", "entity", ObjectAccessControl(),
                        ObjectAccessControl()))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, RewriteObject) {
  auto actual = client_
                    ->RewriteObject(RewriteObjectRequest("bkt", "obj", "bkt2",
                                                         "obj2", "token"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateResumableSession) {
  auto actual = client_
                    ->CreateResumableSession(
                        ResumableUploadRequest("test-bucket", "test-object"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListDefaultObjectAcl) {
  auto actual =
      client_->ListDefaultObjectAcl(ListDefaultObjectAclRequest("bkt"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateDefaultObjectAcl) {
  auto actual = client_
                    ->CreateDefaultObjectAcl(
                        CreateDefaultObjectAclRequest("bkt", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteDefaultObjectAcl) {
  auto actual = client_
                    ->DeleteDefaultObjectAcl(
                        DeleteDefaultObjectAclRequest("bkt", "entity"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetDefaultObjectAcl) {
  auto actual =
      client_->GetDefaultObjectAcl(GetDefaultObjectAclRequest("bkt", "entity"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, UpdateDefaultObjectAcl) {
  auto actual = client_
                    ->UpdateDefaultObjectAcl(
                        UpdateDefaultObjectAclRequest("bkt", "entity", "role"))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, PatchDefaultObjectAcl) {
  auto actual =
      client_
          ->PatchDefaultObjectAcl(PatchDefaultObjectAclRequest(
              "bkt", "entity", ObjectAccessControl(), ObjectAccessControl()))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetServiceAccount) {
  auto actual =
      client_->GetServiceAccount(GetProjectServiceAccountRequest("project_id"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListHmacKeyRequest) {
  auto status =
      client_->ListHmacKeys(ListHmacKeysRequest("project_id")).status();
  CheckStatus(status);
}

TEST_P(CurlClientTest, CreateHmacKeyRequest) {
  auto actual =
      client_
          ->CreateHmacKey(CreateHmacKeyRequest("project_id", "service-account"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, SignBlob) {
  auto actual =
      client_
          ->SignBlob(SignBlobRequest("test-service-account", "test-blob", {}))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, ListNotifications) {
  auto actual =
      client_->ListNotifications(ListNotificationsRequest("bkt")).status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, CreateNotification) {
  auto actual = client_
                    ->CreateNotification(CreateNotificationRequest(
                        "bkt", NotificationMetadata()))
                    .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, GetNotification) {
  auto actual =
      client_->GetNotification(GetNotificationRequest("bkt", "notification_id"))
          .status();
  CheckStatus(actual);
}

TEST_P(CurlClientTest, DeleteNotification) {
  auto actual = client_
                    ->DeleteNotification(
                        DeleteNotificationRequest("bkt", "notification_id"))
                    .status();
  CheckStatus(actual);
}

INSTANTIATE_TEST_SUITE_P(CredentialsFailure, CurlClientTest,
                         ::testing::Values("credentials-failure"));

INSTANTIATE_TEST_SUITE_P(LibCurlFailure, CurlClientTest,
                         ::testing::Values("libcurl-failure"));

}  // namespace
}  // namespace internal
}  // namespace STORAGE_CLIENT_NS
}  // namespace storage
}  // namespace cloud
}  // namespace google
<|endoftext|>


<commit_before>//============================================================================
// Name        : SimpleSpreadsheet.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	return 0;
}
<commit_msg>Delete initial main created by Eclipse<commit_after><|endoftext|>


<commit_before>#ifndef STACK_HPP
#define STACK_HPP
#include <cstdlib>
#include <iostream>
#include <memory>
using namespace std;

template <typename T>
class stack
{
public:
	stack();
	size_t count() const;
	void push(T const &);
	T pop();
	const T& top();
	~stack();
	stack(const stack &b);
	stack & operator=(const stack &b);
	bool operator==(stack const & _s);
	bool empty() const noexcept;
private:
	size_t array_size_;
	size_t count_;
	T * array_;
};
template<typename T>
T*copy_new(const T*arr,size_t count,size_t array_size)
{

	T*l= new T[array_size];
	try
	{
		std::copy(arr,arr+count,l);
	}
	catch(...)
	{
		delete[] l;
		throw;
	}
	return l;

}
#include "stack.cpp"
#endif
<commit_msg>Update stack.hpp<commit_after>#ifndef STACK_HPP
#define STACK_HPP
#include <cstdlib>
#include <iostream>
#include <memory>
using namespace std;

template <typename T>
class stack
{
public:
	stack();
	size_t count() const;
	void push(T const &);
	T pop();
	const T& top();
	~stack();
	stack(const stack &b);
	stack & operator=(const stack &b);
	bool operator==(stack const & _s);
	bool empty() const noexcept;
	void swap(stack &tmp);
private:
	size_t array_size_;
	size_t count_;
	T * array_;
};
template<typename T>
T*copy_new(const T*arr,size_t count,size_t array_size)
{

	T*l= new T[array_size];
	try
	{
		std::copy(arr,arr+count,l);
	}
	catch(...)
	{
		delete[] l;
		throw;
	}
	return l;

}
#include "stack.cpp"
#endif
<|endoftext|>


<commit_before><commit_msg>Init the player to null before we try to see who he is, so that we don't read garbage thinking he's legit if we don't find him<commit_after><|endoftext|>