text:
// This file is auto-generated, don't edit it. Thanks.

#ifndef ALIBABACLOUD_VIDEORECOG20200320_H_
#define ALIBABACLOUD_VIDEORECOG20200320_H_

#include <alibabacloud/open_api.hpp>
#include <boost/any.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>
#include <vector>

using namespace std;

namespace Alibabacloud_Videorecog20200320 {
class GetAsyncJobResultRequest : public Darabonba::Model {
public:
  shared_ptr<bool> async{};
  shared_ptr<string> jobId{};

  GetAsyncJobResultRequest() {}

  explicit GetAsyncJobResultRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (async) {
      res["Async"] = boost::any(*async);
    }
    if (jobId) {
      res["JobId"] = boost::any(*jobId);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
    if (m.find("JobId") != m.end() && !m["JobId"].empty()) {
      jobId = make_shared<string>(boost::any_cast<string>(m["JobId"]));
    }
  }

  virtual ~GetAsyncJobResultRequest() = default;
};
class GetAsyncJobResultResponseBodyData : public Darabonba::Model {
public:
  shared_ptr<string> status{};
  shared_ptr<string> errorMessage{};
  shared_ptr<string> result{};
  shared_ptr<string> errorCode{};
  shared_ptr<string> jobId{};

  GetAsyncJobResultResponseBodyData() {}

  explicit GetAsyncJobResultResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (status) {
      res["Status"] = boost::any(*status);
    }
    if (errorMessage) {
      res["ErrorMessage"] = boost::any(*errorMessage);
    }
    if (result) {
      res["Result"] = boost::any(*result);
    }
    if (errorCode) {
      res["ErrorCode"] = boost::any(*errorCode);
    }
    if (jobId) {
      res["JobId"] = boost::any(*jobId);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("Status") != m.end() && !m["Status"].empty()) {
      status = make_shared<string>(boost::any_cast<string>(m["Status"]));
    }
    if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
      errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
    }
    if (m.find("Result") != m.end() && !m["Result"].empty()) {
      result = make_shared<string>(boost::any_cast<string>(m["Result"]));
    }
    if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
      errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"]));
    }
    if (m.find("JobId") != m.end() && !m["JobId"].empty()) {
      jobId = make_shared<string>(boost::any_cast<string>(m["JobId"]));
    }
  }

  virtual ~GetAsyncJobResultResponseBodyData() = default;
};
class GetAsyncJobResultResponseBody : public Darabonba::Model {
public:
  shared_ptr<string> requestId{};
  shared_ptr<GetAsyncJobResultResponseBodyData> data{};

  GetAsyncJobResultResponseBody() {}

  explicit GetAsyncJobResultResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (requestId) {
      res["RequestId"] = boost::any(*requestId);
    }
    if (data) {
      res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
      requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
    }
    if (m.find("Data") != m.end() && !m["Data"].empty()) {
      if (typeid(map<string, boost::any>) == m["Data"].type()) {
        GetAsyncJobResultResponseBodyData model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
        data = make_shared<GetAsyncJobResultResponseBodyData>(model1);
      }
    }
  }

  virtual ~GetAsyncJobResultResponseBody() = default;
};
class GetAsyncJobResultResponse : public Darabonba::Model {
public:
  shared_ptr<map<string, string>> headers{};
  shared_ptr<GetAsyncJobResultResponseBody> body{};

  GetAsyncJobResultResponse() {}

  explicit GetAsyncJobResultResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!headers) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
    }
    if (!body) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (headers) {
      res["headers"] = boost::any(*headers);
    }
    if (body) {
      res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("headers") != m.end() && !m["headers"].empty()) {
      map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
      map<string, string> toMap1;
      for (auto item:map1) {
         toMap1[item.first] = item.second;
      }
      headers = make_shared<map<string, string>>(toMap1);
    }
    if (m.find("body") != m.end() && !m["body"].empty()) {
      if (typeid(map<string, boost::any>) == m["body"].type()) {
        GetAsyncJobResultResponseBody model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
        body = make_shared<GetAsyncJobResultResponseBody>(model1);
      }
    }
  }

  virtual ~GetAsyncJobResultResponse() = default;
};
class DetectVideoShotRequest : public Darabonba::Model {
public:
  shared_ptr<string> videoUrl{};
  shared_ptr<bool> async{};

  DetectVideoShotRequest() {}

  explicit DetectVideoShotRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (videoUrl) {
      res["VideoUrl"] = boost::any(*videoUrl);
    }
    if (async) {
      res["Async"] = boost::any(*async);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("VideoUrl") != m.end() && !m["VideoUrl"].empty()) {
      videoUrl = make_shared<string>(boost::any_cast<string>(m["VideoUrl"]));
    }
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
  }

  virtual ~DetectVideoShotRequest() = default;
};
class DetectVideoShotAdvanceRequest : public Darabonba::Model {
public:
  shared_ptr<Darabonba::Stream> videoUrlObject{};
  shared_ptr<bool> async{};

  DetectVideoShotAdvanceRequest() {}

  explicit DetectVideoShotAdvanceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!videoUrlObject) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("videoUrlObject is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (videoUrlObject) {
      res["VideoUrlObject"] = boost::any(*videoUrlObject);
    }
    if (async) {
      res["Async"] = boost::any(*async);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("VideoUrlObject") != m.end() && !m["VideoUrlObject"].empty()) {
      videoUrlObject = make_shared<Darabonba::Stream>(boost::any_cast<Darabonba::Stream>(m["VideoUrlObject"]));
    }
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
  }

  virtual ~DetectVideoShotAdvanceRequest() = default;
};
class DetectVideoShotResponseBodyData : public Darabonba::Model {
public:
  shared_ptr<vector<long>> shotFrameIds{};

  DetectVideoShotResponseBodyData() {}

  explicit DetectVideoShotResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (shotFrameIds) {
      res["ShotFrameIds"] = boost::any(*shotFrameIds);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("ShotFrameIds") != m.end() && !m["ShotFrameIds"].empty()) {
      vector<long> toVec1;
      if (typeid(vector<boost::any>) == m["ShotFrameIds"].type()) {
        vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ShotFrameIds"]);
        for (auto item:vec1) {
           toVec1.push_back(boost::any_cast<long>(item));
        }
      }
      shotFrameIds = make_shared<vector<long>>(toVec1);
    }
  }

  virtual ~DetectVideoShotResponseBodyData() = default;
};
class DetectVideoShotResponseBody : public Darabonba::Model {
public:
  shared_ptr<string> requestId{};
  shared_ptr<DetectVideoShotResponseBodyData> data{};

  DetectVideoShotResponseBody() {}

  explicit DetectVideoShotResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (requestId) {
      res["RequestId"] = boost::any(*requestId);
    }
    if (data) {
      res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
      requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
    }
    if (m.find("Data") != m.end() && !m["Data"].empty()) {
      if (typeid(map<string, boost::any>) == m["Data"].type()) {
        DetectVideoShotResponseBodyData model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
        data = make_shared<DetectVideoShotResponseBodyData>(model1);
      }
    }
  }

  virtual ~DetectVideoShotResponseBody() = default;
};
class DetectVideoShotResponse : public Darabonba::Model {
public:
  shared_ptr<map<string, string>> headers{};
  shared_ptr<DetectVideoShotResponseBody> body{};

  DetectVideoShotResponse() {}

  explicit DetectVideoShotResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!headers) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
    }
    if (!body) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (headers) {
      res["headers"] = boost::any(*headers);
    }
    if (body) {
      res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("headers") != m.end() && !m["headers"].empty()) {
      map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
      map<string, string> toMap1;
      for (auto item:map1) {
         toMap1[item.first] = item.second;
      }
      headers = make_shared<map<string, string>>(toMap1);
    }
    if (m.find("body") != m.end() && !m["body"].empty()) {
      if (typeid(map<string, boost::any>) == m["body"].type()) {
        DetectVideoShotResponseBody model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
        body = make_shared<DetectVideoShotResponseBody>(model1);
      }
    }
  }

  virtual ~DetectVideoShotResponse() = default;
};
class GenerateVideoCoverRequest : public Darabonba::Model {
public:
  shared_ptr<string> videoUrl{};
  shared_ptr<bool> async{};
  shared_ptr<bool> isGif{};

  GenerateVideoCoverRequest() {}

  explicit GenerateVideoCoverRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (videoUrl) {
      res["VideoUrl"] = boost::any(*videoUrl);
    }
    if (async) {
      res["Async"] = boost::any(*async);
    }
    if (isGif) {
      res["IsGif"] = boost::any(*isGif);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("VideoUrl") != m.end() && !m["VideoUrl"].empty()) {
      videoUrl = make_shared<string>(boost::any_cast<string>(m["VideoUrl"]));
    }
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
    if (m.find("IsGif") != m.end() && !m["IsGif"].empty()) {
      isGif = make_shared<bool>(boost::any_cast<bool>(m["IsGif"]));
    }
  }

  virtual ~GenerateVideoCoverRequest() = default;
};
class GenerateVideoCoverAdvanceRequest : public Darabonba::Model {
public:
  shared_ptr<Darabonba::Stream> videoUrlObject{};
  shared_ptr<bool> async{};
  shared_ptr<bool> isGif{};

  GenerateVideoCoverAdvanceRequest() {}

  explicit GenerateVideoCoverAdvanceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!videoUrlObject) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("videoUrlObject is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (videoUrlObject) {
      res["VideoUrlObject"] = boost::any(*videoUrlObject);
    }
    if (async) {
      res["Async"] = boost::any(*async);
    }
    if (isGif) {
      res["IsGif"] = boost::any(*isGif);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("VideoUrlObject") != m.end() && !m["VideoUrlObject"].empty()) {
      videoUrlObject = make_shared<Darabonba::Stream>(boost::any_cast<Darabonba::Stream>(m["VideoUrlObject"]));
    }
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
    if (m.find("IsGif") != m.end() && !m["IsGif"].empty()) {
      isGif = make_shared<bool>(boost::any_cast<bool>(m["IsGif"]));
    }
  }

  virtual ~GenerateVideoCoverAdvanceRequest() = default;
};
class GenerateVideoCoverResponseBodyDataOutputs : public Darabonba::Model {
public:
  shared_ptr<string> imageURL{};
  shared_ptr<double> confidence{};

  GenerateVideoCoverResponseBodyDataOutputs() {}

  explicit GenerateVideoCoverResponseBodyDataOutputs(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (imageURL) {
      res["ImageURL"] = boost::any(*imageURL);
    }
    if (confidence) {
      res["Confidence"] = boost::any(*confidence);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("ImageURL") != m.end() && !m["ImageURL"].empty()) {
      imageURL = make_shared<string>(boost::any_cast<string>(m["ImageURL"]));
    }
    if (m.find("Confidence") != m.end() && !m["Confidence"].empty()) {
      confidence = make_shared<double>(boost::any_cast<double>(m["Confidence"]));
    }
  }

  virtual ~GenerateVideoCoverResponseBodyDataOutputs() = default;
};
class GenerateVideoCoverResponseBodyData : public Darabonba::Model {
public:
  shared_ptr<vector<GenerateVideoCoverResponseBodyDataOutputs>> outputs{};

  GenerateVideoCoverResponseBodyData() {}

  explicit GenerateVideoCoverResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (outputs) {
      vector<boost::any> temp1;
      for(auto item1:*outputs){
        temp1.push_back(boost::any(item1.toMap()));
      }
      res["Outputs"] = boost::any(temp1);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("Outputs") != m.end() && !m["Outputs"].empty()) {
      if (typeid(vector<boost::any>) == m["Outputs"].type()) {
        vector<GenerateVideoCoverResponseBodyDataOutputs> expect1;
        for(auto item1:boost::any_cast<vector<boost::any>>(m["Outputs"])){
          if (typeid(map<string, boost::any>) == item1.type()) {
            GenerateVideoCoverResponseBodyDataOutputs model2;
            model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
            expect1.push_back(model2);
          }
        }
        outputs = make_shared<vector<GenerateVideoCoverResponseBodyDataOutputs>>(expect1);
      }
    }
  }

  virtual ~GenerateVideoCoverResponseBodyData() = default;
};
class GenerateVideoCoverResponseBody : public Darabonba::Model {
public:
  shared_ptr<string> requestId{};
  shared_ptr<GenerateVideoCoverResponseBodyData> data{};

  GenerateVideoCoverResponseBody() {}

  explicit GenerateVideoCoverResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (requestId) {
      res["RequestId"] = boost::any(*requestId);
    }
    if (data) {
      res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
      requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
    }
    if (m.find("Data") != m.end() && !m["Data"].empty()) {
      if (typeid(map<string, boost::any>) == m["Data"].type()) {
        GenerateVideoCoverResponseBodyData model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
        data = make_shared<GenerateVideoCoverResponseBodyData>(model1);
      }
    }
  }

  virtual ~GenerateVideoCoverResponseBody() = default;
};
class GenerateVideoCoverResponse : public Darabonba::Model {
public:
  shared_ptr<map<string, string>> headers{};
  shared_ptr<GenerateVideoCoverResponseBody> body{};

  GenerateVideoCoverResponse() {}

  explicit GenerateVideoCoverResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!headers) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
    }
    if (!body) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (headers) {
      res["headers"] = boost::any(*headers);
    }
    if (body) {
      res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("headers") != m.end() && !m["headers"].empty()) {
      map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
      map<string, string> toMap1;
      for (auto item:map1) {
         toMap1[item.first] = item.second;
      }
      headers = make_shared<map<string, string>>(toMap1);
    }
    if (m.find("body") != m.end() && !m["body"].empty()) {
      if (typeid(map<string, boost::any>) == m["body"].type()) {
        GenerateVideoCoverResponseBody model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
        body = make_shared<GenerateVideoCoverResponseBody>(model1);
      }
    }
  }

  virtual ~GenerateVideoCoverResponse() = default;
};
class UnderstandVideoContentRequest : public Darabonba::Model {
public:
  shared_ptr<string> videoURL{};
  shared_ptr<bool> async{};

  UnderstandVideoContentRequest() {}

  explicit UnderstandVideoContentRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (videoURL) {
      res["VideoURL"] = boost::any(*videoURL);
    }
    if (async) {
      res["Async"] = boost::any(*async);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("VideoURL") != m.end() && !m["VideoURL"].empty()) {
      videoURL = make_shared<string>(boost::any_cast<string>(m["VideoURL"]));
    }
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
  }

  virtual ~UnderstandVideoContentRequest() = default;
};
class UnderstandVideoContentAdvanceRequest : public Darabonba::Model {
public:
  shared_ptr<Darabonba::Stream> videoURLObject{};
  shared_ptr<bool> async{};

  UnderstandVideoContentAdvanceRequest() {}

  explicit UnderstandVideoContentAdvanceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!videoURLObject) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("videoURLObject is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (videoURLObject) {
      res["VideoURLObject"] = boost::any(*videoURLObject);
    }
    if (async) {
      res["Async"] = boost::any(*async);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("VideoURLObject") != m.end() && !m["VideoURLObject"].empty()) {
      videoURLObject = make_shared<Darabonba::Stream>(boost::any_cast<Darabonba::Stream>(m["VideoURLObject"]));
    }
    if (m.find("Async") != m.end() && !m["Async"].empty()) {
      async = make_shared<bool>(boost::any_cast<bool>(m["Async"]));
    }
  }

  virtual ~UnderstandVideoContentAdvanceRequest() = default;
};
class UnderstandVideoContentResponseBodyDataVideoInfo : public Darabonba::Model {
public:
  shared_ptr<long> width{};
  shared_ptr<long> height{};
  shared_ptr<long> duration{};
  shared_ptr<double> fps{};

  UnderstandVideoContentResponseBodyDataVideoInfo() {}

  explicit UnderstandVideoContentResponseBodyDataVideoInfo(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (width) {
      res["Width"] = boost::any(*width);
    }
    if (height) {
      res["Height"] = boost::any(*height);
    }
    if (duration) {
      res["Duration"] = boost::any(*duration);
    }
    if (fps) {
      res["Fps"] = boost::any(*fps);
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("Width") != m.end() && !m["Width"].empty()) {
      width = make_shared<long>(boost::any_cast<long>(m["Width"]));
    }
    if (m.find("Height") != m.end() && !m["Height"].empty()) {
      height = make_shared<long>(boost::any_cast<long>(m["Height"]));
    }
    if (m.find("Duration") != m.end() && !m["Duration"].empty()) {
      duration = make_shared<long>(boost::any_cast<long>(m["Duration"]));
    }
    if (m.find("Fps") != m.end() && !m["Fps"].empty()) {
      fps = make_shared<double>(boost::any_cast<double>(m["Fps"]));
    }
  }

  virtual ~UnderstandVideoContentResponseBodyDataVideoInfo() = default;
};
class UnderstandVideoContentResponseBodyData : public Darabonba::Model {
public:
  shared_ptr<map<string, boost::any>> tagInfo{};
  shared_ptr<UnderstandVideoContentResponseBodyDataVideoInfo> videoInfo{};

  UnderstandVideoContentResponseBodyData() {}

  explicit UnderstandVideoContentResponseBodyData(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (tagInfo) {
      res["TagInfo"] = boost::any(*tagInfo);
    }
    if (videoInfo) {
      res["VideoInfo"] = videoInfo ? boost::any(videoInfo->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("TagInfo") != m.end() && !m["TagInfo"].empty()) {
      map<string, boost::any> map1 = boost::any_cast<map<string, boost::any>>(m["TagInfo"]);
      map<string, boost::any> toMap1;
      for (auto item:map1) {
         toMap1[item.first] = item.second;
      }
      tagInfo = make_shared<map<string, boost::any>>(toMap1);
    }
    if (m.find("VideoInfo") != m.end() && !m["VideoInfo"].empty()) {
      if (typeid(map<string, boost::any>) == m["VideoInfo"].type()) {
        UnderstandVideoContentResponseBodyDataVideoInfo model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["VideoInfo"]));
        videoInfo = make_shared<UnderstandVideoContentResponseBodyDataVideoInfo>(model1);
      }
    }
  }

  virtual ~UnderstandVideoContentResponseBodyData() = default;
};
class UnderstandVideoContentResponseBody : public Darabonba::Model {
public:
  shared_ptr<string> requestId{};
  shared_ptr<UnderstandVideoContentResponseBodyData> data{};

  UnderstandVideoContentResponseBody() {}

  explicit UnderstandVideoContentResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {}

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (requestId) {
      res["RequestId"] = boost::any(*requestId);
    }
    if (data) {
      res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
      requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
    }
    if (m.find("Data") != m.end() && !m["Data"].empty()) {
      if (typeid(map<string, boost::any>) == m["Data"].type()) {
        UnderstandVideoContentResponseBodyData model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
        data = make_shared<UnderstandVideoContentResponseBodyData>(model1);
      }
    }
  }

  virtual ~UnderstandVideoContentResponseBody() = default;
};
class UnderstandVideoContentResponse : public Darabonba::Model {
public:
  shared_ptr<map<string, string>> headers{};
  shared_ptr<UnderstandVideoContentResponseBody> body{};

  UnderstandVideoContentResponse() {}

  explicit UnderstandVideoContentResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
    fromMap(config);
  };

  void validate() override {
    if (!headers) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
    }
    if (!body) {
      BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
    }
  }

  map<string, boost::any> toMap() override {
    map<string, boost::any> res;
    if (headers) {
      res["headers"] = boost::any(*headers);
    }
    if (body) {
      res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
    }
    return res;
  }

  void fromMap(map<string, boost::any> m) override {
    if (m.find("headers") != m.end() && !m["headers"].empty()) {
      map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
      map<string, string> toMap1;
      for (auto item:map1) {
         toMap1[item.first] = item.second;
      }
      headers = make_shared<map<string, string>>(toMap1);
    }
    if (m.find("body") != m.end() && !m["body"].empty()) {
      if (typeid(map<string, boost::any>) == m["body"].type()) {
        UnderstandVideoContentResponseBody model1;
        model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
        body = make_shared<UnderstandVideoContentResponseBody>(model1);
      }
    }
  }

  virtual ~UnderstandVideoContentResponse() = default;
};
class Client : Alibabacloud_OpenApi::Client {
public:
  explicit Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config);
  string getEndpoint(shared_ptr<string> productId,
                     shared_ptr<string> regionId,
                     shared_ptr<string> endpointRule,
                     shared_ptr<string> network,
                     shared_ptr<string> suffix,
                     shared_ptr<map<string, string>> endpointMap,
                     shared_ptr<string> endpoint);
  GetAsyncJobResultResponse getAsyncJobResultWithOptions(shared_ptr<GetAsyncJobResultRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
  GetAsyncJobResultResponse getAsyncJobResult(shared_ptr<GetAsyncJobResultRequest> request);
  DetectVideoShotResponse detectVideoShotWithOptions(shared_ptr<DetectVideoShotRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
  DetectVideoShotResponse detectVideoShot(shared_ptr<DetectVideoShotRequest> request);
  DetectVideoShotResponse detectVideoShotAdvance(shared_ptr<DetectVideoShotAdvanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
  GenerateVideoCoverResponse generateVideoCoverWithOptions(shared_ptr<GenerateVideoCoverRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
  GenerateVideoCoverResponse generateVideoCover(shared_ptr<GenerateVideoCoverRequest> request);
  GenerateVideoCoverResponse generateVideoCoverAdvance(shared_ptr<GenerateVideoCoverAdvanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
  UnderstandVideoContentResponse understandVideoContentWithOptions(shared_ptr<UnderstandVideoContentRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
  UnderstandVideoContentResponse understandVideoContent(shared_ptr<UnderstandVideoContentRequest> request);
  UnderstandVideoContentResponse understandVideoContentAdvance(shared_ptr<UnderstandVideoContentAdvanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);

  virtual ~Client() = default;
};
} // namespace Alibabacloud_Videorecog20200320

#endif

max_stars_repo_name: aliyun/alibabacloud-cpp-sdk

max_issues_repo_name: aliyun/alibabacloud-cpp-sdk

max_forks_repo_name: aliyun/alibabacloud-cpp-sdk


text:
//============================================================================
// Name         : dnatemplatedatetimefuncs.hpp
// Author       : Roger Fraser
// Contributors :
// Version      : 1.00
// Copyright    : Copyright 2017 Geoscience Australia
//
//                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.
//
// Description  : Advanced and common calculation functions involving date and
//				  time
//============================================================================

#ifndef DNATEMPLATEDATETIMEFUNCS_H_
#define DNATEMPLATEDATETIMEFUNCS_H_

#if defined(_MSC_VER)
	#if defined(LIST_INCLUDES_ON_BUILD)
		#pragma message("  " __FILE__)
	#endif
#endif

#include <boost/timer/timer.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <include/functions/dnastrmanipfuncs.hpp>

const UINT32 TIME_IMMEMORIAL = 1900;

using namespace std;
using namespace boost::timer;
using namespace boost::posix_time;
using namespace boost::gregorian;

// Boost implementation of gregorian calendar supports dates in the range 1400-Jan-01 to 9999-Dec-31.
// Integer representation of these dates is 2232400 and 5373484, which appears to be the Julian Date.
// GPS time begins on 6 January 1980 (2444245)

//date::date_int_type dit(2444245);
////date d(dit);
//date gpsday(1980, 1, 6);
//date today(day_clock::local_day());
//UINT32 id = gpsday.day_number();
//UINT32 itoday = today.day_number();

//stringstream str;
//const std::locale fmt(locale::classic(), new date_facet("%m/%d/%Y"));
//str.imbue(fmt);
//str << gpsday << endl;
//str << "Today:   " << today.day_number() << endl;
//str <<
//	static_cast<short>(today.year()) << endl <<
//	static_cast<short>(today.month()) << endl <<
//	static_cast<short>(today.day()) << endl << endl;
//str << "GPS day: " << gpsday.day_number() << endl;
//str <<
//	static_cast<short>(gpsday.year()) << endl <<
//	static_cast<short>(gpsday.month()) << endl <<
//	static_cast<short>(gpsday.day()) << endl;

//cout << str.str().c_str() << endl;

//TRACE("%s", str.str().c_str());

//days duration_since_gps(today- gpsday);
//
//str.str("");
//str << duration_since_gps;
//TRACE("Today is %d days since the beginning of GPS time\n", str.str().c_str());

template <class T>
void dateSINEXFormat(T* os, const date& theDate, bool calculateSeconds=false)
{
	// Time stamps must be in the following format:  YY:DOY:SECOD
	// where:
	//	 YY     : year
	//	 DOY    : day of year
	//	 SECOD  : sec of day (e.g. the epoch)
	// Example:
	//		95:120:86399 denotes April 30, 1995 (23:59:59UT).
	//

	stringstream year;
	time_facet* facet(new time_facet("%y"));

	year.imbue(locale(year.getloc(), facet));
	ptime dateTime(theDate);
	year << dateTime;

	stringstream dayofyear;
	dayofyear << right << setw(3) << theDate.day_of_year();
	string dayofyearstr(dayofyear.str());
	dayofyearstr = findandreplace<string>(dayofyearstr, " ", "0");

	*os <<
		right << setw(2) <<
			year.str() << ":" <<		// year (YY)
		right << setw(3) <<
			dayofyearstr << ":";		// day of year

	if (calculateSeconds)
	{
		ptime currentTime(second_clock::local_time());
		time_duration timeInterval(currentTime - dateTime);

		stringstream secondsofday;
		secondsofday << left << setw(5) << timeInterval.total_seconds();
		*os << left << setw(5) << secondsofday.str();
		return;
	}

	*os << "00000";
}

template <class U>
U dateYear(const date& theDate)
{
	return theDate.year();
}

template <class U>
U dateDOY(const date& theDate)
{
	return theDate.day_of_year();
}

template <class U>
U dateMonth(const date& theDate)
{
	return theDate.month();
}

template <class U>
U dateDay(const date& theDate)
{
	return theDate.day();
}

template <class U>
U dateDaynumber(const date& theDate)
{
	return theDate.day_number();
}

template <class U>
U todayYear()
{
	return dateYear<U>(day_clock::local_day());
}

template <class U>
U todayMonth()
{
	return dateMonth<U>(day_clock::local_day());
}

template <class U>
U todayDay()
{
	return dateDay<U>(day_clock::local_day());
}

template <class U>
U todayDaynumber()
{
	return dateDaynumber<U>(day_clock::local_day());
}

template <class U, class T>
T integerToDate(const U& integer)
{
	return date(integer);
}

template <class U, class T>
T dateToInteger(const T& theDate)
{
	return dateDaynumber(theDate);
}

template <class U, class T>
T ymdToDate(const U& year, const U& month, const U& day)
{
	return date(year, month, day);
}

template <class T>
T timeImmemorial()
{
	return T(TIME_IMMEMORIAL, 1, 1);
}

template <class T>
bool isTimeImmemorial(const T& theDate)
{
	return theDate < T(TIME_IMMEMORIAL, 1, 2);
}

// cumulative days in a year required for determining decimal year
template <class P>
struct _cumulative_days_in_year_
{
	static const short cumulativeDays[2][12];
};

template <class P>
short const _cumulative_days_in_year_<P>::cumulativeDays[2][12] =
	// normal year
	{{
		0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
	},
	// leap year
	{
		0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
	}};

class CUMULATIVE_DAY_YEAR
	: public _cumulative_days_in_year_<void>
{
public:
};

// calendar month names
template <class P>
struct _month_names_
{
	static const char monthNames[12][12];
};

template <class P>
const char _month_names_<P>::monthNames[12][12] =
	{
		{"January"},
		{"February"},
		{"March"},
		{"April"},
		{"May"},
		{"June"},
		{"July"},
		{"August"},
		{"September"},
		{"October"},
		{"November"},
		{"December"}
	};

class MONTH_NAMES
	: public _month_names_<void>
{
public:
};

template <class T>
// calculate average and test for year cross over
void year_doy_Average(const T& start_year, const T& end_year,
	const T& start_doy, const T& end_doy,
	T& average_year, T& average_doy)
{
	if (start_year != end_year)
	{
		average_doy = average(start_doy, start_doy + end_doy);
		if (average_doy > DAYS_PER_YEAR)
		{
			average_year = end_year;
			average_doy -= static_cast<T>(DAYS_PER_YEAR);
		}
		else
			average_year = start_year;
		return;
	}

	average_year = start_year;

	if (start_doy != end_doy)
		average_doy = average(start_doy, end_doy);
	else
		average_doy = start_doy;
}

template <class T>
// epochFrom -> epochTo
T yearFraction(const date& epoch)
{
	// Day of year, less 0.5 day correction to
	// bring to middle of day, divided by number
	// of days in a year
	//return (dateDOY<T>(epoch) - 0.5) / DAYS_PER_YEAR;

	short leap(0);
	T days_in_year(365);

	if (fmod((T)epoch.year(), 400.) == 0)
	{
		leap = 1;
		days_in_year = 366;
	}
	else if (fmod((T)epoch.year(), 100.) == 0)
		leap = 0;
	else if (fmod((T)epoch.year(), 4.) == 0)
	{
		leap = 1;
		days_in_year = 366;
	}
	else
		leap = 0;

	T day_of_year(CUMULATIVE_DAY_YEAR::cumulativeDays[leap][epoch.month() - 1] + epoch.day());

	return (day_of_year - (T)0.5) / days_in_year;
}

template <class T>
// Return as a double or float the decimal year
T referenceEpoch(const date& theDate)
{
	// Epoch of interest
	return yearFraction<T>(theDate) + theDate.year();
}

template <class T>
// elapsedTime = current_epoch - reference_epoch
T elapsedTime(const T& current_epoch, const T& reference_epoch)
{
	// Elapsed time
	return (current_epoch - reference_epoch);
}

template <class T>
// elapsedTime = current_epoch - reference_epoch
T elapsedTime(const T& current_epoch, const date& reference_epoch)
{
	return elapsedTime(current_epoch, referenceEpoch<T>(reference_epoch));
}

template <class T>
// elapsedTime = current_epoch - reference_epoch
T elapsedTime(const date& current_epoch, const T& reference_epoch)
{
	return elapsedTime(referenceEpoch<T>(current_epoch), reference_epoch);
}

template <class T>
// elapsedTime = current_epoch - reference_epoch
T elapsedTime(const date& current_epoch, const date& reference_epoch)
{
	return elapsedTime(referenceEpoch<T>(current_epoch), referenceEpoch<T>(reference_epoch));
}

template <class T>
// dateString = dd.mm.yyyy
date dateFromString_safe(const string& dateString)
{
	vector<string> vdateList;
	SplitDelimitedString<string>(dateString, string("."), &vdateList);

	try {
		// boost date requires input in the following order: year, month, day
		return date(
			LongFromString<UINT32>(vdateList.at(2)),	// year
			LongFromString<UINT32>(vdateList.at(1)),	// month
			LongFromString<UINT32>(vdateList.at(0)));	// day
	}
	catch (runtime_error& e)
	{
		stringstream ss;
		ss << "dateFromString_safe(): Could not parse the date string \"" << dateString << "\"" << endl <<
			"  Details: " << e.what() << endl;
		throw boost::enable_current_exception(runtime_error(ss.str()));
	}
	catch (...)
	{
		stringstream ss;
		ss << "dateFromString_safe(): Could not parse the date string \"" << dateString << "\"." << endl <<
			"  Check that the epoch is formatted as dd.mm.yyyy" << endl;
		throw boost::enable_current_exception(runtime_error(ss.str()));
	}
}

template <class T, class S>
// dateString = ddd yyyy
T dateFromStringstream_doy_year(S& date)
{
	T parsedDate;
	// From boost_1_54_0/doc/html/date_time/date_time_io.html
	// %j :	Day of year as decimal from 001 to 366 for leap years, 001 - 365 for non-leap years.
	//		"060" => Feb-29
	// %y : Two digit year
	//		"05" => 2005
	// %Y : Four digit year
	// 		"2005" => 2005
	// But! 94 => 2094!
	// So use %Y"
	date.imbue(locale(date.getloc(), new date_input_facet("%j %Y")));
	date >> parsedDate;
	return parsedDate;
}

template <class T, class S>
// dateString = ddd yyyy
T dateFromString_doy_year(S& date)
{
	T parsedDate;
	// From boost_1_54_0/doc/html/date_time/date_time_io.html
	// %j :	Day of year as decimal from 001 to 366 for leap years, 001 - 365 for non-leap years.
	//		"060" => Feb-29
	// %y : Two digit year
	//		"05" => 2005
	// %Y : Four digit year
	// 		"2005" => 2005
	// But! 94 => 2094!
	// So use %Y"
	stringstream ss_date;
	ss_date << date;
	ss_date.imbue(locale(ss_date.getloc(), new date_input_facet("%j %Y")));
	ss_date >> parsedDate;
	return parsedDate;
}

template <class T, class D>
// date = yyyy.yyyyy
T dateFromDouble_doy_year(const D& date)
{
	T parsedDate;
	D year(floor(date));
	D year_fraction(date - year);
	D days_in_year(365.0);

	if (fmod(year, 400.) == 0)
		days_in_year += 1.0;
	else if (fmod(year, 4.) == 0)
		days_in_year += 1.0;

	// Calculate integer day from floating point.
	// If this rounds up or down, the net result is a day before
	// or a day after.  For some applications, this might cause
	// one some concern.  But for reference frame geodesy and plate
	// tectonics, not a lot happens in a day so this is quite acceptable.
	D doy = year_fraction * days_in_year;
	size_t idoy = static_cast<size_t>(doy);
	if (idoy < 1)
		idoy = 1;

	// From boost_1_54_0/doc/html/date_time/date_time_io.html
	// %j :	Day of year as decimal from 001 to 366 for leap years, 001 - 365 for non-leap years.
	//		"060" => Feb-29
	// %y : Two digit year
	//		"05" => 2005
	// %Y : Four digit year
	// 		"2005" => 2005
	// But! 94 => 2094!
	// So use %Y"
	stringstream strdate;
	if (idoy < 10.)
		strdate << "00";
	else if (idoy < 100.)
		strdate << "0";
	strdate << idoy << " " << fixed << setprecision(0) << year;
	strdate.imbue(locale(strdate.getloc(), new date_input_facet("%j %Y")));
	strdate >> parsedDate;
	return parsedDate;
}

template <class T>
// dateString = dd.mm.yyyy
string stringFromDate(const T& date)
{
	stringstream ss;
	ss.imbue(locale(ss.getloc(), new date_facet("%d.%m.%Y")));

	ss << date;
	return ss.str();
}

template <class T>
// dateString = dd.mm.yyyy
string stringFromToday()
{
	stringstream ss;
	ss.imbue(locale(ss.getloc(), new date_facet("%d.%m.%Y")));

	ss << date(day_clock::local_day());
	return ss.str();
}

template <class T>
// dateString = dd.mm.yyyy
string stringFromDate(const T& date, const string& format)
{
	stringstream ss;
	ss.imbue(locale(ss.getloc(), new date_facet(format.c_str())));

	ss << date;
	return ss.str();
}

template <class T>
// dateString = dd.mm.yyyy
T dateFromString(const string& dateString)
{
	// The following works well when dateString is "03.02.2013", but fails
	// if dateString is "3.2.2013".
	//
	//istringstream ss(dateString);
	//ss.imbue(locale(std::locale::classic(), new gregorian::date_input_facet("%e.%m.%Y")));
	//T date;
	//ss >> date;
	//return date;
	//
	// The Boost.Gregorian documentation specifies that:
	//  %d      Day of the month as decimal 01 to 31
	//  %e #    Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space
	//	The top part of the documentation states the following warning:
	//	The flags marked with a hash sign (#) are implemented by system locale and are known to be missing on some platforms

	// Is today's date required?
	if (iequals(dateString, "today"))
		return dateFromString_safe<T>(stringFromDate<T>(T(day_clock::local_day())));

	// Parse manually.
	return dateFromString_safe<T>(dateString);

}

template <class T>
// dateString = dd.mm.yyyy
string formattedDateStringFromNumericString(const string& dateString)
{
	date date(dateFromString<T>(dateString));

	stringstream ss;
	ss.imbue(locale(ss.getloc(), new date_facet("%A, %d %B %Y")));

	ss << date;
	return ss.str();
}

template <typename T>
T formattedDateTimeStringFromDate(const date& theDate)
{
	stringstream datetime_ss, stream;
	time_facet* p_time_output = new time_facet;
	locale special_locale (locale(""), p_time_output);

	// special_locale takes ownership of the p_time_output facet
	datetime_ss.imbue (special_locale);
	(*p_time_output).format("%d-%m-%Y %X");
	datetime_ss << second_clock::local_time();
	stream << datetime_ss.str().c_str();

	return stream.str();
}

template <typename S>
S formatedElapsedTime(milliseconds* elapsed_time, S app_message)
{
	ostringstream ss_time;
	ptime pt(ptime(gregorian::day_clock::local_day(), *elapsed_time));

	if (*elapsed_time < seconds(3))
	{
		time_facet* facet(new time_facet("%s"));
		ss_time.imbue(locale(ss_time.getloc(), facet));
		ss_time.str("");
		ss_time << pt << "s";
	}
	else if (*elapsed_time < seconds(61))
	{
		time_facet* facet(new time_facet("%S"));
		ss_time.imbue(locale(ss_time.getloc(), facet));
		ss_time.str("");
		ss_time << pt << "s";
	}
	else
		ss_time << seconds(static_cast<long>(elapsed_time->total_seconds()));

	size_t pos = string::npos;
	string time_message = ss_time.str();
	while ((pos = time_message.find("0s")) != string::npos)
		time_message = time_message.substr(0, pos) + "s";

	time_message = app_message + time_message + ".";

	if ((pos = time_message.find(" 00.")) != string::npos)
		time_message = time_message.replace(pos, 4, " 0.");
	if ((pos = time_message.find(" 0.s")) != string::npos)
		time_message = time_message.replace(pos, 4, " 0s");

	return time_message;
}

#endif /* DNATEMPLATEDATETIMEFUNCS_H_ */

ext: hpp

max_stars_repo_name: nicgowans/DynAdjust

max_issues_repo_name: nicgowans/DynAdjust

max_forks_repo_name: nicgowans/DynAdjust


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/swar/include/functions/cummax.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/include/constants/one.hpp>
#include <boost/simd/include/constants/two.hpp>
#include <boost/simd/include/constants/mone.hpp>
#include <boost/simd/include/constants/inf.hpp>
#include <boost/simd/include/constants/minf.hpp>
#include <boost/simd/include/constants/nan.hpp>
#include <boost/simd/include/constants/valmax.hpp>
#include <boost/simd/include/constants/valmax.hpp>
#include <boost/simd/include/functions/simd/max.hpp>
#include <boost/simd/include/functions/enumerate.hpp>
#include <boost/simd/sdk/config.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <boost/simd/sdk/meta/cardinal_of.hpp>

template < class vT > vT byhands(const vT & a)
{
  vT that = a;
  for(size_t i=1; i!= boost::simd::meta::cardinal_of<vT>::value; ++i)
    that[i] = boost::simd::max(that[i-1], that[i]);
  return that;
}

NT2_TEST_CASE_TPL ( cummax_real,  BOOST_SIMD_SIMD_REAL_TYPES)
{
  using boost::simd::cummax;
  using boost::simd::tag::cummax_;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                  vT;

  // specific values tests
  NT2_TEST_EQUAL(cummax(boost::simd::Mone<vT>()), byhands(boost::simd::Mone<vT>()));
  NT2_TEST_EQUAL(cummax(boost::simd::One<vT>()) , byhands(boost::simd::One<vT>()) );
  NT2_TEST_EQUAL(cummax(boost::simd::enumerate < vT>(0, 1)), byhands(boost::simd::enumerate < vT>(0, 1)));
  NT2_TEST_EQUAL(cummax(boost::simd::enumerate < vT>(0, -1)), byhands(boost::simd::enumerate < vT>(0, -1)));
} // end of test for floating_

NT2_TEST_CASE_TPL ( cummax_signed_int__1_0,  BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES)
{
  using boost::simd::cummax;
  using boost::simd::tag::cummax_;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                  vT;

  // specific values tests
  NT2_TEST_EQUAL(cummax(boost::simd::Mone<vT>()),byhands(boost::simd::Mone<vT>()) );
  NT2_TEST_EQUAL(cummax(boost::simd::One<vT>()) ,byhands(boost::simd::One<vT>())  );
  NT2_TEST_EQUAL(cummax(boost::simd::enumerate < vT>(0, 1)), byhands(boost::simd::enumerate < vT>(0, 1)));
  NT2_TEST_EQUAL(cummax(boost::simd::enumerate < vT>(0, -1)), byhands(boost::simd::enumerate < vT>(0, -1)));
} // end of test for signed_int_

NT2_TEST_CASE_TPL ( cummax_unsigned_int__1_0,  BOOST_SIMD_SIMD_UNSIGNED_TYPES)
{
  using boost::simd::cummax;
  using boost::simd::tag::cummax_;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                  vT;

  // specific values tests
  NT2_TEST_EQUAL(cummax(boost::simd::One<vT>()) ,byhands(boost::simd::One<vT>())  );
  NT2_TEST_EQUAL(cummax(boost::simd::enumerate < vT>(0, 1)), byhands(boost::simd::enumerate < vT>(0, 1)));
  NT2_TEST_EQUAL(cummax(boost::simd::enumerate < vT>(0, -1)), byhands(boost::simd::enumerate < vT>(0, -1)));
} // end of test for unsigned_int_

ext: cpp


text:
#pragma once

#include <futurehead/lib/alarm.hpp>
#include <futurehead/lib/stats.hpp>
#include <futurehead/lib/work.hpp>
#include <futurehead/lib/worker.hpp>
#include <futurehead/node/active_transactions.hpp>
#include <futurehead/node/blockprocessor.hpp>
#include <futurehead/node/bootstrap/bootstrap.hpp>
#include <futurehead/node/bootstrap/bootstrap_attempt.hpp>
#include <futurehead/node/bootstrap/bootstrap_server.hpp>
#include <futurehead/node/confirmation_height_processor.hpp>
#include <futurehead/node/distributed_work_factory.hpp>
#include <futurehead/node/election.hpp>
#include <futurehead/node/gap_cache.hpp>
#include <futurehead/node/network.hpp>
#include <futurehead/node/node_observers.hpp>
#include <futurehead/node/nodeconfig.hpp>
#include <futurehead/node/online_reps.hpp>
#include <futurehead/node/payment_observer_processor.hpp>
#include <futurehead/node/portmapping.hpp>
#include <futurehead/node/repcrawler.hpp>
#include <futurehead/node/request_aggregator.hpp>
#include <futurehead/node/signatures.hpp>
#include <futurehead/node/telemetry.hpp>
#include <futurehead/node/vote_processor.hpp>
#include <futurehead/node/wallet.hpp>
#include <futurehead/node/write_database_queue.hpp>
#include <futurehead/secure/ledger.hpp>
#include <futurehead/secure/utility.hpp>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/program_options.hpp>
#include <boost/thread/latch.hpp>

#include <atomic>
#include <memory>
#include <thread>
#include <vector>

namespace futurehead
{
namespace websocket
{
	class listener;
}
class node;
class telemetry;
class work_pool;
class block_arrival_info final
{
public:
	std::chrono::steady_clock::time_point arrival;
	futurehead::block_hash hash;
};
// This class tracks blocks that are probably live because they arrived in a UDP packet
// This gives a fairly reliable way to differentiate between blocks being inserted via bootstrap or new, live blocks.
class block_arrival final
{
public:
	// Return `true' to indicated an error if the block has already been inserted
	bool add (futurehead::block_hash const &);
	bool recent (futurehead::block_hash const &);
	// clang-format off
	class tag_sequence {};
	class tag_hash {};
	boost::multi_index_container<futurehead::block_arrival_info,
		boost::multi_index::indexed_by<
			boost::multi_index::sequenced<boost::multi_index::tag<tag_sequence>>,
			boost::multi_index::hashed_unique<boost::multi_index::tag<tag_hash>,
				boost::multi_index::member<futurehead::block_arrival_info, futurehead::block_hash, &futurehead::block_arrival_info::hash>>>>
	arrival;
	// clang-format on
	std::mutex mutex;
	static size_t constexpr arrival_size_min = 8 * 1024;
	static std::chrono::seconds constexpr arrival_time_min = std::chrono::seconds (300);
};

std::unique_ptr<container_info_component> collect_container_info (block_arrival & block_arrival, const std::string & name);

std::unique_ptr<container_info_component> collect_container_info (rep_crawler & rep_crawler, const std::string & name);

class node final : public std::enable_shared_from_this<futurehead::node>
{
public:
	node (boost::asio::io_context &, uint16_t, boost::filesystem::path const &, futurehead::alarm &, futurehead::logging const &, futurehead::work_pool &, futurehead::node_flags = futurehead::node_flags (), unsigned seq = 0);
	node (boost::asio::io_context &, boost::filesystem::path const &, futurehead::alarm &, futurehead::node_config const &, futurehead::work_pool &, futurehead::node_flags = futurehead::node_flags (), unsigned seq = 0);
	~node ();
	template <typename T>
	void background (T action_a)
	{
		alarm.io_ctx.post (action_a);
	}
	bool copy_with_compaction (boost::filesystem::path const &);
	void keepalive (std::string const &, uint16_t);
	void start ();
	void stop ();
	std::shared_ptr<futurehead::node> shared ();
	int store_version ();
	void receive_confirmed (futurehead::transaction const &, std::shared_ptr<futurehead::block>, futurehead::block_hash const &);
	void process_confirmed_data (futurehead::transaction const &, std::shared_ptr<futurehead::block>, futurehead::block_hash const &, futurehead::account &, futurehead::uint128_t &, bool &, futurehead::account &);
	void process_confirmed (futurehead::election_status const &, uint64_t = 0);
	void process_active (std::shared_ptr<futurehead::block>);
	futurehead::process_return process (futurehead::block &);
	futurehead::process_return process_local (std::shared_ptr<futurehead::block>, bool const = false);
	void keepalive_preconfigured (std::vector<std::string> const &);
	futurehead::block_hash latest (futurehead::account const &);
	futurehead::uint128_t balance (futurehead::account const &);
	std::shared_ptr<futurehead::block> block (futurehead::block_hash const &);
	std::pair<futurehead::uint128_t, futurehead::uint128_t> balance_pending (futurehead::account const &);
	futurehead::uint128_t weight (futurehead::account const &);
	futurehead::block_hash rep_block (futurehead::account const &);
	futurehead::uint128_t minimum_principal_weight ();
	futurehead::uint128_t minimum_principal_weight (futurehead::uint128_t const &);
	void ongoing_rep_calculation ();
	void ongoing_bootstrap ();
	void ongoing_store_flush ();
	void ongoing_peer_store ();
	void ongoing_unchecked_cleanup ();
	void backup_wallet ();
	void search_pending ();
	void bootstrap_wallet ();
	void unchecked_cleanup ();
	int price (futurehead::uint128_t const &, int);
	// The default difficulty updates to base only when the first epoch_2 block is processed
	uint64_t default_difficulty (futurehead::work_version const) const;
	uint64_t max_work_generate_difficulty (futurehead::work_version const) const;
	bool local_work_generation_enabled () const;
	bool work_generation_enabled () const;
	bool work_generation_enabled (std::vector<std::pair<std::string, uint16_t>> const &) const;
	boost::optional<uint64_t> work_generate_blocking (futurehead::block &, uint64_t);
	boost::optional<uint64_t> work_generate_blocking (futurehead::work_version const, futurehead::root const &, uint64_t, boost::optional<futurehead::account> const & = boost::none);
	void work_generate (futurehead::work_version const, futurehead::root const &, uint64_t, std::function<void(boost::optional<uint64_t>)>, boost::optional<futurehead::account> const & = boost::none, bool const = false);
	void add_initial_peers ();
	void block_confirm (std::shared_ptr<futurehead::block>);
	bool block_confirmed (futurehead::block_hash const &);
	bool block_confirmed_or_being_confirmed (futurehead::transaction const &, futurehead::block_hash const &);
	void process_fork (futurehead::transaction const &, std::shared_ptr<futurehead::block>, uint64_t);
	void do_rpc_callback (boost::asio::ip::tcp::resolver::iterator i_a, std::string const &, uint16_t, std::shared_ptr<std::string>, std::shared_ptr<std::string>, std::shared_ptr<boost::asio::ip::tcp::resolver>);
	futurehead::uint128_t delta () const;
	void ongoing_online_weight_calculation ();
	void ongoing_online_weight_calculation_queue ();
	bool online () const;
	bool init_error () const;
	bool epoch_upgrader (futurehead::private_key const &, futurehead::epoch, uint64_t, uint64_t);
	std::pair<uint64_t, decltype (futurehead::ledger::bootstrap_weights)> get_bootstrap_weights () const;
	futurehead::worker worker;
	futurehead::write_database_queue write_database_queue;
	boost::asio::io_context & io_ctx;
	boost::latch node_initialized_latch;
	futurehead::network_params network_params;
	futurehead::node_config config;
	futurehead::stat stats;
	std::shared_ptr<futurehead::websocket::listener> websocket_server;
	futurehead::node_flags flags;
	futurehead::alarm & alarm;
	futurehead::work_pool & work;
	futurehead::distributed_work_factory distributed_work;
	futurehead::logger_mt logger;
	std::unique_ptr<futurehead::block_store> store_impl;
	futurehead::block_store & store;
	std::unique_ptr<futurehead::wallets_store> wallets_store_impl;
	futurehead::wallets_store & wallets_store;
	futurehead::gap_cache gap_cache;
	futurehead::ledger ledger;
	futurehead::signature_checker checker;
	futurehead::network network;
	std::shared_ptr<futurehead::telemetry> telemetry;
	futurehead::bootstrap_initiator bootstrap_initiator;
	futurehead::bootstrap_listener bootstrap;
	boost::filesystem::path application_path;
	futurehead::node_observers observers;
	futurehead::port_mapping port_mapping;
	futurehead::vote_processor vote_processor;
	futurehead::rep_crawler rep_crawler;
	unsigned warmed_up;
	futurehead::block_processor block_processor;
	std::thread block_processor_thread;
	futurehead::block_arrival block_arrival;
	futurehead::online_reps online_reps;
	futurehead::votes_cache votes_cache;
	futurehead::keypair node_id;
	futurehead::block_uniquer block_uniquer;
	futurehead::vote_uniquer vote_uniquer;
	futurehead::confirmation_height_processor confirmation_height_processor;
	futurehead::active_transactions active;
	futurehead::request_aggregator aggregator;
	futurehead::payment_observer_processor payment_observer_processor;
	futurehead::wallets wallets;
	const std::chrono::steady_clock::time_point startup_time;
	std::chrono::seconds unchecked_cutoff = std::chrono::seconds (7 * 24 * 60 * 60); // Week
	std::atomic<bool> unresponsive_work_peers{ false };
	std::atomic<bool> stopped{ false };
	static double constexpr price_max = 16.0;
	static double constexpr free_cutoff = 1024.0;
	// For tests only
	unsigned node_seq;
	// For tests only
	boost::optional<uint64_t> work_generate_blocking (futurehead::block &);
	// For tests only
	boost::optional<uint64_t> work_generate_blocking (futurehead::root const &, uint64_t);
	// For tests only
	boost::optional<uint64_t> work_generate_blocking (futurehead::root const &);

private:
	void long_inactivity_cleanup ();
	void epoch_upgrader_impl (futurehead::private_key const &, futurehead::epoch, uint64_t, uint64_t);
	futurehead::locked<std::future<void>> epoch_upgrading;
};

std::unique_ptr<container_info_component> collect_container_info (node & node, const std::string & name);

futurehead::node_flags const & inactive_node_flag_defaults ();

class inactive_node final
{
public:
	inactive_node (boost::filesystem::path const & path_a, futurehead::node_flags const & node_flags_a = futurehead::inactive_node_flag_defaults ());
	~inactive_node ();
	std::shared_ptr<boost::asio::io_context> io_context;
	futurehead::alarm alarm;
	futurehead::work_pool work;
	std::shared_ptr<futurehead::node> node;
};
std::unique_ptr<futurehead::inactive_node> default_inactive_node (boost::filesystem::path const &, boost::program_options::variables_map const &);
}

max_stars_repo_name: futureheadgroup/futurehead-node

max_issues_repo_name: FutureHeadCoin/futurehead-node

max_forks_repo_name: FutureHeadCoin/futurehead-node


text:
/*!
 * mintex.
 * app_account
 *
 * \date 02.05.19
 * \author Eduard Maximovich (edward.vstock@gmail.com)
 * \link   https://github.com/edwardstock
 */
#include <boost/locale.hpp>
#include <rang.hpp>
#include <fort.hpp>
#include "wallet/term.h"
#include "wallet/app/account_controller.h"
#include "wallet/gate/repository.h"
#include "wallet/explorer/repository.h"
#include "wallet/liquidity/repository.h"
#include <minter/tx/utils.h>
#include <wallet/liquidity/base.h>

wallet::cmd::account_controller::account_controller(std::shared_ptr<wallet::app> app)
    : command_controller(app) {

    ACTION_BIND(account_controller, balance);
    ACTION_BIND(account_controller, lastx);
}

bool wallet::cmd::account_controller::before_action(const std::string &action, int argc, char **argv) {
    // todo: unify
    if (wallet::command_controller::before_action(action, argc, argv)) {
        m_storage = wallet::secret_storage::create(false, get_app()->get_settings());
        return true;
    }

    return false;
}

std::string wallet::cmd::account_controller::usage() const {
    return "Minter Text Wallet";
}

void wallet::cmd::account_controller::action_balance_options(boost::program_options::options_description &options) {
    options.add_options()
               ("index,i", po::value<size_t>(), "Account index")
               ("all", "Count balance for all existed accounts");
}

void wallet::cmd::account_controller::action_balance(const po::variables_map &opts) {
    using namespace minter;
    using namespace minter::utils;
    using namespace wallet::explorer;
    using namespace wallet::term;

    progress_indeterminate p;
    repository repo;
    wallet::gate::repository gate_repo;
    wallet::liquidity::repository lp_repo;

    std::unordered_map<address_t, std::vector<balance_item>> balance_data;
    delegations_result_t delegations_data;

    dev::bigdec18 all_actives_in_bip = dev::bigdec18("0");

    std::vector<address_t> addresses;

    if (opts.count("index")) {
        size_t index = opts.at("index").as<size_t>();
        addresses.push_back(m_storage->get_address(index));
    } else {
        auto all_addresses = m_storage->get_addresses();
        addresses.insert(addresses.begin(), all_addresses.begin(), all_addresses.end());
    }

    p.start();

    dev::bigdec18 coin_price("0.32");
    coin_price.precision(2);

    auto get_coin_price_task = lp_repo.get_price()
        ->success([&coin_price](wallet::liquidity::base_result<wallet::liquidity::bip_price> res) {
            coin_price = dev::bigdec18(res.data.price) / dev::bigdec18("10000");
        })
        ->error([](httb::response resp, wallet::liquidity::base_result<wallet::liquidity::bip_price> res) {
          std::cerr << "error " << resp.statusMessage << "\n";
        });

    get_coin_price_task->execute()->handle().run();

    for (const auto &address: addresses) {
        auto balance_task = repo.get_balance(address.to_string())
                                ->success([&p, &balance_data](wallet::explorer::base_result<wallet::explorer::balance_items> result) {
                                  balance_data.emplace(result.data.address, result.data.balances);
                                })
                                ->error([&p](httb::response response,
                                             wallet::explorer::base_result<wallet::explorer::balance_items> result) {
                                  std::cout << "error " << response.statusMessage << "\n";
                                });

        auto delegated_task = repo.get_delegated(address.to_string())
                                  ->success([&delegations_data](base_result<delegations_result_t> res) {
                                    delegations_data.insert(delegations_data.begin(), res.data.begin(), res.data.end());
                                  })
                                  ->error([&delegations_data](httb::response response,
                                                              base_result<delegations_result_t> res) {
                                    std::cout << "error " << response.statusMessage << "\n";
                                  });

        wallet::net::pair_task<
            base_result<balance_items>,
            base_result<delegations_result_t>
        > executor(balance_task, delegated_task);

        executor.execute();
    }

    // Balances
    fort::table balance_table;
    balance_table << fort::header;
    balance_table << "Coin" << "Balance" << fort::endr;
    {
        for (auto &balances: balance_data) {
            balance_table << balances.first.to_string() << "" << fort::endr;

            for (const auto &item: balances.second) {
                balance_table << item.coin;

                if (!toolboxpp::strings::equalsIgnoreCase(std::string(MINTER_COIN), item.coin)) {
                    gate_repo.get_exchange_sell_currency(item.coin, item.amount, std::string(MINTER_COIN))
                             ->success([&item, &balance_table, &all_actives_in_bip](wallet::gate::base_result<wallet::gate::exchange_sell_value> result) {
                               all_actives_in_bip += minter::utils::humanize_value(result.data.will_get);
                               balance_table
                                   << fmt::format("{0} (~{1} {2})",
                                                  to_string(item.amount),
                                                  minter::utils::to_string_lp(minter::utils::humanize_value(result.data
                                                                                .will_get)),
                                                  std::string(MINTER_COIN)
                                   );
                             })
                             ->error([&balance_table, &item](httb::response resp,
                                                             wallet::gate::base_result<wallet::gate::exchange_sell_value> result) {
                               std::cerr << resp.getBody() << std::endl;
                               balance_table << to_string(item.amount);
                             })
                             ->execute()->handle().run();
                } else {
                    all_actives_in_bip += item.amount;
                    balance_table << to_string(item.amount);
                }

                balance_table << fort::endr;
            }
        }
    }

    // Delegated
    std::unordered_map<std::string, delegated_item> delegated_stakes;
    fort::table validators_table;
    validators_table << fort::header;
    validators_table << "Pub Key" << "Coin" << "Delegated Stake" << fort::endr;
    {
        for (const auto &item: delegations_data) {
            if (!delegated_stakes.count(item.pub_key.to_string())) {
                delegated_stakes.emplace(item.pub_key.to_string(), item);
            } else {
                delegated_stakes.at(item.pub_key.to_string()).value += item.value;
            }
        }
        for (const auto &item: delegated_stakes) {
            validators_table << item.first << item.second.coin << to_string(item.second.value) << fort::endr;
        }
    }

    // Summary delegated
    std::unordered_map<std::string, dev::bigdec18> summary_stake;
    fort::table validators_sum_table;
    validators_sum_table << fort::header;
    validators_sum_table << "Coin" << "Delegated Stake" << fort::endr;
    {
        for (const auto &item: delegations_data) {
            if (!summary_stake.count(item.coin)) {
                summary_stake.emplace(item.coin, item.value);
            } else {
                summary_stake.at(item.coin) += item.value;
            }
        }

        for (const auto &item: summary_stake) {

            validators_sum_table << item.first;
            if (!toolboxpp::strings::equalsIgnoreCase(std::string(MINTER_COIN), item.first)) {
                gate_repo.get_exchange_sell_currency(item.first, item.second, std::string(MINTER_COIN))
                         ->success([&item, &validators_sum_table, &all_actives_in_bip](wallet::gate::base_result<wallet::gate::exchange_sell_value> result) {
                           all_actives_in_bip += minter::utils::humanize_value(result.data.will_get);
                           validators_sum_table
                               << fmt::format("{0} (~{1} {2})",
                                              to_string(item.second),
                                              minter::utils::to_string_lp(minter::utils::humanize_value(result.data
                                                                                .will_get)),
                                              std::string(MINTER_COIN)
                               );
                         })
                         ->error([&validators_sum_table, &item](httb::response resp,
                                                                wallet::gate::base_result<wallet::gate::exchange_sell_value> result) {
                           std::cerr << resp.getBody() << std::endl;
                           validators_sum_table << to_string(item.second);
                         })
                         ->execute()->handle().run();
            } else {
                validators_sum_table << to_string(item.second);
                all_actives_in_bip += item.second;
            }

            validators_sum_table << fort::endr;
        }
    }

    p.stop();

    // Common
    wallet::term::print_success_message("Balance");
    std::cout << balance_table.to_string();

    // Delegated
    wallet::term::print_success_message("Validators");
    if (delegated_stakes.size()) {
        std::cout << validators_table.to_string();
    } else {
        validators_table << "Nothing to show" << fort::endr;
        validators_table.cell(1, 0).set_cell_span(3);
        validators_table.cell(1, 0).set_cell_text_align(fort::text_align::center);
        std::cout << validators_table.to_string();
    }

    // Summary delegated
    wallet::term::print_success_message("Summary Delegated");
    if (summary_stake.size()) {
        std::cout << validators_sum_table.to_string();
    } else {
        validators_sum_table << "Nothing to show" << fort::endr;
        validators_sum_table.cell(1, 0).set_cell_span(3);
        validators_sum_table.cell(1, 0).set_cell_text_align(fort::text_align::center);
        std::cout << validators_sum_table.to_string();
    }

    // All actives
    fort::table all_actives_table;
    all_actives_table << fort::header << "Coin" << "Volume" << fort::endr;
    all_actives_table << MINTER_COIN << to_string_lp(all_actives_in_bip) << fort::endr;
    all_actives_table << "USD" << to_string_lp(all_actives_in_bip * dev::bigdec18(coin_price)) << fort::endr;
    all_actives_table << "RUB" << to_string_lp(((all_actives_in_bip * dev::bigdec18(coin_price)) * dev::bigdec18("64"))) << fort::endr;

    all_actives_table.cell(0, 1).set_cell_text_align(fort::text_align::right);
    all_actives_table.cell(1, 1).set_cell_text_align(fort::text_align::right);
    all_actives_table.cell(2, 1).set_cell_text_align(fort::text_align::right);

    wallet::term::print_success_message("All volumes (including frozen) in " + std::string(MINTER_COIN) + "s");
    std::cout << all_actives_table.to_string();

}

void wallet::cmd::account_controller::action_lastx_options(boost::program_options::options_description &options) {
    options.add_options()
               ("index,i", po::value<size_t>()->default_value(0), "Account index")
               ("limit,l", po::value<uint32_t>()->default_value(10), "List size")
               ("page,p", po::value<uint32_t>()->default_value(1), "Page number")
               ("short", "show in oneline format");
}

void wallet::cmd::account_controller::action_lastx(const po::variables_map &opts) {
    using namespace wallet::explorer;
    using namespace minter;
    using namespace minter::utils;
    using namespace wallet::term;

    progress_indeterminate p;
    p.start();

    repository repo;

    uint32_t page = 1;
    uint32_t limit = 10;

    if (opts.count("page")) {
        page = opts.at("page").as<uint32_t>();
    }
    if (opts.count("limit")) {
        limit = opts.at("limit").as<uint32_t>();
    }

    size_t index = opts.at("index").as<size_t>();
    const address_t address = m_storage->get_address(index);

    auto tx_list_task = repo.get_transactions(address, page, limit);
    tx_list_task
        ->error([](httb::response response, base_result<tx_list_t> result) {
          std::cout << "error " << response.statusMessage << "\n";
        })
        ->complete([&p] {
          p.stop();
        });

    try {
        wallet::explorer::base_result<wallet::explorer::tx_list_t> result;
        tx_list_task->success([&result](wallet::explorer::base_result<wallet::explorer::tx_list_t> res){
            result = res;
        })->execute()->handle().run();

        if (opts.count("short")) {
            for (const transaction_item &item: result.data) {
                std::cout << rang::fgB::yellow << item.hash;
                std::cout << " ";
                std::cout << rang::fgB::green << item.type;
                std::cout << " ";
                std::cout << rang::fgB::yellow << item.timestamp;
                std::cout << "\n" << rang::style::reset;
            }

        } else {
            for (const transaction_item &item: result.data) {
                std::cout << "\n==================================";
                print_field("#", item.txn, 13);
                print_field("sender", item.from, 13);
                print_field("hash", item.hash, 13);
                print_field("nonce", item.nonce, 13);
                print_field("block", item.block, 13);
                print_field("timestamp", item.timestamp, 13);
                print_field("fee", item.fee, 13);
                print_field("type", minter::tx_type_names.at(item.type), 13);
                print_field("payload", item.payload, 13);
                print_field("data", "", 13);

                switch (item.type) {
                    case tx_type_val::send_coin: {
                        auto data = std::static_pointer_cast<tx_send_result>(item.data);
                        print_tab_field("Coin", data->coin, 11);
                        print_tab_field("Value", to_string(data->value), 11);
                        print_tab_field("Recipient", data->to, 11);
                        break;
                    }
                    case tx_type_val::sell_coin:
                    case tx_type_val::sell_all_coins:
                    case tx_type_val::buy_coin: {
                        auto data = std::static_pointer_cast<tx_convert_result>(item.data);
                        print_tab_field("Sell coin", data->coin_to_sell, 19);
                        print_tab_field("Buy coin", data->coin_to_buy, 19);
                        print_tab_field("Value buy", to_string(data->value_to_buy), 19);
                        print_tab_field("Value sell", to_string(data->value_to_sell), 19);
                        print_tab_field("Max value to sell", to_string(data->maximum_value_to_sell), 19);
                        print_tab_field("Min value to buy", to_string(data->minimum_value_to_buy), 19);
                        break;
                    }
                    case tx_type_val::create_coin: {
                        auto data = std::static_pointer_cast<tx_create_coin_result>(item.data);\
                        print_tab_field("Coin name", data->name, 17);
                        print_tab_field("Ticker", data->symbol, 17);
                        print_tab_field("Initial amount", to_string(data->initial_amount), 17);
                        print_tab_field("Initial reserve", to_string(data->initial_reserve), 17);
                        print_tab_field("CRR", data->symbol, 17);
                        break;
                    }
                    case tx_type_val::declare_candidacy: {
                        auto data = std::static_pointer_cast<tx_declare_candidacy_result>(item.data);
                        print_tab_field("Address", data->address, 12);
                        print_tab_field("Pub Key", data->pub_key, 12);
                        print_tab_field("Commission", data->commission, 12);
                        print_tab_field("Coin", data->coin, 12);
                        print_tab_field("Stake", to_string(data->stake), 12);
                        break;
                    }
                    case tx_type_val::delegate:
                    case tx_type_val::unbond: {
                        auto data = std::static_pointer_cast<tx_delegate_unbond_result>(item.data);
                        print_tab_field("Pub Key", data->pub_key, 9);
                        print_tab_field("Coin", data->coin, 9);
                        print_tab_field("Stake", to_string(data->stake), 9);
                        print_tab_field("Value", to_string(data->value), 9);
                        break;
                    }
                    case tx_type_val::redeem_check: {
                        auto data = std::static_pointer_cast<tx_redeem_check_result>(item.data);
                        print_tab_field("Raw Check", (data->raw_check), 11);
                        print_tab_field("Proof", (data->raw_check), 11);
                        print_tab_field("Stake", to_string(data->stake), 11);
                        print_tab_field("Value", to_string(data->value), 11);

                        print_tab_field("Check Data:", "", 11);

                        print_tab_field("Nonce", data->check.nonce, 7, 2);
                        print_tab_field("Nonce", data->check.due_block, 7, 2);
                        print_tab_field("Coin", data->check.coin, 7, 2);
                        print_tab_field("Value", to_string(data->check.value), 7, 2);
                        print_tab_field("Sender", data->check.sender, 7, 2);
                        break;
                    }
                    case tx_type_val::set_candidate_on:
                    case tx_type_val::set_candidate_off: {
                        auto data = std::static_pointer_cast<tx_set_candidate_on_off_result>(item.data);
                        print_tab_field("Pub Key", data->pub_key, 11);
                        break;
                    }
                    case tx_type_val::create_multisig: {
//                        auto pre = std::static_pointer_cast<tx_create_multisig_result>(item.data);
                        break;
                    }
                    case tx_type_val::multisend: {
                        auto base = std::static_pointer_cast<tx_multisend_result>(item.data);
                        print_tab_field("Recipients", base->items.size(), 12);
                        size_t i = 0;
                        for (const auto &data: base->items) {
                            print_tab_field("#", i + 1, 11, 2);
                            print_tab_field("Coin", data.coin, 11, 2);
                            print_tab_field("Value", to_string(data.value), 11, 2);
                            print_tab_field("Recipient", data.to, 11, 2);

                            i++;
                        }
                        break;
                    }
                    case tx_type_val::edit_candidate: {
                        auto data = std::static_pointer_cast<tx_edit_candidate_result>(item.data);
                        print_tab_field("Pub Key", data->pub_key, 16);
                        print_tab_field("Reward Address", data->reward_address, 16);
                        print_tab_field("Owner Address", data->owner_address, 16);
                        break;
                    }
                }

                std::cout << "\n";
            }
        }

        std::cout << "Printed count: " << result.data.size() << "\n";
        std::cout << "Page: " << result.meta.current_page << "\n";
        std::cout << "Total pages:" << result.meta.last_page << "\n";

    } catch (nlohmann::detail::exception &e) {
        std::cerr << e.what() << std::endl;
    }
}

std::string wallet::cmd::account_controller::get_command_name() const {
    return "account";
}
std::unordered_map<std::string, std::string> wallet::cmd::account_controller::get_actions_descriptions() const {
    return std::unordered_map<std::string, std::string>{
        {"balance", "Print account balance"},
        {"lastx",   "Print last account transactions"}
    };
}

max_stars_repo_name: edwardstock/mintex

max_issues_repo_name: edwardstock/mintex

max_forks_repo_name: edwardstock/mintex


text:
// Copyright 2005-2009 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// Force use of assert.
#if defined(NDEBUG)
#undef NDEBUG
#endif

#include <boost/container_hash/hash.hpp>
#include <cassert>

// This example illustrates how to customise boost::hash portably, so that
// it'll work on both compilers that don't implement argument dependent lookup
// and compilers that implement strict two-phase template instantiation.

namespace foo
{
    template <class T>
    class custom_type
    {
        T value;
    public:
        custom_type(T x) : value(x) {}

        std::size_t hash() const
        {
            boost::hash<T> hasher;
            return hasher(value);
        }
    };
}

#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
namespace boost
#else
namespace foo
#endif
{
    template <class T>
    std::size_t hash_value(foo::custom_type<T> x)
    {
        return x.hash();
    }
}

int main()
{
    foo::custom_type<int> x(1), y(2), z(1);

    boost::hash<foo::custom_type<int> > hasher;

    assert(hasher(x) == hasher(x));
    assert(hasher(x) != hasher(y));
    assert(hasher(x) == hasher(z));

    return 0;
}


text:
/*
   Copyright (C) 2019-2022 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>

   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.
*/

#ifndef LATTICE_GRAPH_XML_HPP
#define LATTICE_GRAPH_XML_HPP

#include <sstream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "graph.hpp"
#include "unitcell_xml.hpp"
#include "basis_xml.hpp"

namespace lattice {

using boost::property_tree::ptree;

inline ptree& operator>>(ptree& pt, graph& lat) {
  std::size_t dim = 0;
  if (auto str = pt.get_optional<std::string>("<xmlattr>.dimension")) {
    dim = stoi(str.get());
  }
  lat = graph(dim);

  std::size_t ns = 0;
  if (auto str = pt.get_optional<std::string>("<xmlattr>.vertices")) ns = stoi(str.get());

  for (auto& v : pt) {
    if (v.first == "VERTEX") {
      bool found_pos = false;
      coordinate_t pos = coordinate_t::Zero(dim);
      int tp = 0;
      if (lat.dimension() > 0) {
        for (auto& c : v.second) {
          if (c.first == "COORDINATE") {
            if (found_pos) throw std::invalid_argument("duplicated <COORDINATE> tag");
            std::istringstream is(c.second.data());
            std::string sin;
            for (std::size_t m = 0; m < dim; ++m) {
              is >> sin;
              pos(m) = stod(sin);
            }
            found_pos = true;
          }
        }
      }
      if (auto str = v.second.get_optional<std::string>("<xmlattr>.type")) tp = stoi(str.get());
      lat.add_site(pos, tp);
    }
  }

  if (lat.num_sites() > 0) {
    if (ns > 0 && lat.num_sites() != ns)
      throw std::invalid_argument("inconsistent number of sites");
  } else {
    coordinate_t pos = coordinate_t::Zero(dim);
    for (std::size_t i = 0; i < ns; ++i) lat.add_site(pos, 0);
  }

  for (auto& e : pt) {
    if (e.first == "EDGE") {
      std::size_t source, target; // offset one
      int tp = 0;
      if (auto str = e.second.get_optional<std::string>("<xmlattr>.source")) {
        source = stoi(str.get());
      } else {
        throw std::invalid_argument("source attribute not found");
      }
      if (auto str = e.second.get_optional<std::string>("<xmlattr>.target")) {
        target = stoi(str.get());
      } else {
        throw std::invalid_argument("target attribute not found");
      }
      if (auto str = e.second.get_optional<std::string>("<xmlattr>.type")) tp = stoi(str.get());
      lat.add_bond(source - 1, target - 1, tp);
    }
  }
  return pt;
}

inline ptree& write_xml(ptree& pt, const std::string& name, const graph& lat) {
  ptree& root = pt.add("GRAPH", "");
  root.put("<xmlattr>.name", name);
  if (lat.dimension() > 0) root.put("<xmlattr>.dimension", lat.dimension());
  root.put("<xmlattr>.vertices", lat.num_sites());
  for (std::size_t s = 0; s < lat.num_sites(); ++s) {
    ptree& vertex = root.add("VERTEX", "");
    vertex.put("<xmlattr>.type", lat.site_type(s));
    if (lat.dimension() > 0) {
      std::ostringstream os;
      os << std::setprecision(std::numeric_limits<double>::max_digits10);
      auto pos = lat.coordinate(s);
      for (std::size_t m = 0; m < lat.dimension(); ++m) os << (m ? " " : "") << pos(m);
      vertex.add("COORDINATE", os.str());
    }
  }
  for (std::size_t b = 0; b < lat.num_bonds(); ++b) {
    ptree& edge = root.add("EDGE", "");
    edge.put("<xmlattr>.type", lat.bond_type(b));
    edge.put("<xmlattr>.source", lat.source(b) + 1);
    edge.put("<xmlattr>.target", lat.target(b) + 1);
  }
  return pt;
}

inline bool read_xml(ptree& pt, const std::string& name, graph& lat) {
  for (auto& child : pt.get_child("LATTICES")) {
    if (child.first == "GRAPH") {
      if (auto str = child.second.get_optional<std::string>("<xmlattr>.name")) {
        if (str.get() == name) {
          child.second >> lat;
          return true;
        }
      }
    }
  }
  return false;
}

} // end namespace lattice

#endif

max_stars_repo_name: todo-group/lattice

max_issues_repo_name: todo-group/lattice

max_forks_repo_name: todo-group/lattice