<commit_before>#include "command_executor_object.h"

#include <boost/log/trivial.hpp>
#include <json/json.hpp>
#include <algorithm>

#include <patlms/type/time.h>

using namespace std;
using namespace nlohmann;

namespace apache
{

namespace web
{

CommandExecutorObjectPtr CommandExecutorObject::Create(::database::DatabasePtr database) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::Create: Function call";
  auto p = CommandExecutorObjectPtr(new CommandExecutorObject(database));
  return p;
}

const ::web::type::JsonMessage CommandExecutorObject::Execute(const ::web::type::JsonMessage &message) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::Execute: Function call";
  auto json_object = json::parse(message);
  auto command = json_object["command"];
  auto result = GetUnknownCommandErrorJson();

  if (command == "get_apache_agent_names") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_agent_names' command";
    result = GetHostnames();
  }
  else if (command == "get_apache_virtualhosts_names") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_virtualhosts_names' command";

    auto args = json_object["args"];
    if (args.size() != 1) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: get_apache_virtualhosts_names require one argument";
      return GetInvalidArgumentErrorJson();
    }

    auto agent_name = args.at(0);
    result = GetVirtualhostsNames(agent_name);
  }
  else if (command == "get_apache_sessions") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_sessions' command";

    auto args = json_object["args"];
    if (args.size() != 4) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: get_apache_sessions require four arguments";
      return GetInvalidArgumentErrorJson();
    }

    result = GetSessions(args.at(0), args.at(1), args.at(2), args.at(3));
  }
  else if (command == "set_apache_sessions_as_anomaly") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'set_apache_sessions_as_anomaly' command";

    auto args = json_object["args"];
    if (args.size() != 2) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: set_apache_sessions_as_anomaly require two arguments";
      return GetInvalidArgumentErrorJson();
    }

    result = SetApacheSessionsAsAnomaly(args.at(0), args.at(1));
  }
  else if (command == "get_apache_anomaly_detection_configuration") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_anomaly_detection_configuration' command";

    result = GetApacheAnomalyDetectionConfiguration();
  }
  else if (command == "set_apache_anomaly_detection_configuration") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'set_apache_anomaly_detection_configuration' command";

    auto args = json_object["args"];
    if (args.size() != 4) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: set_apache_anomaly_detection_configuration require four arguments";
      return GetInvalidArgumentErrorJson();
    }

    result = SetApacheAnomalyDetectionConfiguration(args.at(0), args.at(1), args.at(2), args.at(3));
  }

  return result;
}

bool CommandExecutorObject::IsCommandSupported(const ::web::type::Command &command) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::IsCommandSupported: Function call";
  return (command == "get_apache_agent_names")
      || (command == "get_apache_virtualhosts_names")
      || (command == "get_apache_sessions")
      || (command == "set_apache_sessions_as_anomaly")
      || (command == "get_apache_anomaly_detection_configuration")
      || (command == "set_apache_anomaly_detection_configuration");
}

CommandExecutorObject::CommandExecutorObject(::database::DatabasePtr database)
: database_(database) {
}

const ::web::type::JsonMessage CommandExecutorObject::GetHostnames() {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetHostnames: Function call";

  json j;
  j["status"] = "ok";
  j["result"] = database_->GetApacheAgentNames();

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::GetVirtualhostsNames(const std::string &agent_name) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetVirtualhostsNames: Function call";

  json j;
  j["status"] = "ok";
  j["result"] = database_->GetApacheVirtualhostNames(agent_name);

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::GetSessions(const std::string &agent_name,
                                                                  const std::string &virtualhost_name,
                                                                  const std::string &begin_date,
                                                                  const std::string &end_date) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetSessions: Function call";

  auto tbegin = ::type::Timestamp::Create(::type::Time(),
                                          ::type::Date::Create(begin_date));
  auto tend = ::type::Timestamp::Create(::type::Time(24, 59, 59),
                                        ::type::Date::Create(end_date));
  auto count = database_->GetApacheSessionStatisticsCount(agent_name, virtualhost_name,
                                                          tbegin, tend);

  ::apache::type::ApacheSessions sessions = database_->GetApacheSessionStatistics(agent_name, virtualhost_name,
                                                                                tbegin, tend,
                                                                                count, 0);

  json j, r = json::array();
  for (::apache::type::ApacheSessionEntry s : sessions) {
    json t;
    t["id"] = s.id;
    t["agent_name"] = s.agent_name;
    t["virtualhost"] = s.virtualhost;
    t["client_ip"] = s.client_ip;
    t["session_start"] = s.session_start.ToString();
    t["session_length"] = s.session_length;
    t["bandwidth_usage"] = s.bandwidth_usage;
    t["requests_count"] = s.requests_count;
    t["error_percentage"] = s.error_percentage;
    t["useragent"] = s.useragent;
    t["is_anomaly"] = s.is_anomaly;

    r.push_back(t);
  }

  j["status"] = "ok";
  j["result"] = r;

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::SetApacheSessionsAsAnomaly(const std::vector<long long> &all,
                                                                                const std::vector<long long> &anomalies) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::SetApacheSessionsAsAnomaly: Function call";

  database_->SetApacheSessionAsAnomaly(all, anomalies);

  json j;
  j["status"] = "ok";

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::GetApacheAnomalyDetectionConfiguration() {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetApacheAnomalyDetectionConfiguration: Function call";

  auto conf = database_->GetApacheAnomalyDetectionConfiguration();

  json r = json::array();
  for (auto c : conf) {
    json t;
    t["id"] = c.id;
    t["agent_name"] = c.agent_name;
    t["virtualhost_name"] = c.virtualhost_name;
    t["begin_date"] = to_string(c.begin_date.GetYear()) + "-" + to_string(c.begin_date.GetMonth()) + "-" + to_string(c.begin_date.GetDay());
    t["end_date"] = to_string(c.end_date.GetYear()) + "-" + to_string(c.end_date.GetMonth()) + "-" + to_string(c.end_date.GetDay());

    r.push_back(t);
  }

  json j;
  j["status"] = "ok";
  j["result"] = r;

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::SetApacheAnomalyDetectionConfiguration(const std::string &agent_name,
                                                                                const std::string &virtualhost_name,
                                                                                const std::string &begin_date,
                                                                                const std::string &end_date) {
  ::apache::type::AnomalyDetectionConfigurationEntry c;
  c.agent_name = agent_name;
  c.virtualhost_name = virtualhost_name;
  c.begin_date = ::type::Date::Create(begin_date);
  c.end_date = ::type::Date::Create(end_date);

  database_->AddDate(c.begin_date.GetDay(), c.begin_date.GetMonth(), c.begin_date.GetYear());
  database_->AddDate(c.end_date.GetDay(), c.end_date.GetMonth(), c.end_date.GetYear());
  database_->SetApacheAnomalyDetectionConfiguration(c);

  json j;
  j["status"] = "ok";

  return j.dump();
}

}

}
<commit_msg>Fix Time creation in CommandExecutorObject<commit_after>#include "command_executor_object.h"

#include <boost/log/trivial.hpp>
#include <json/json.hpp>
#include <algorithm>

#include <patlms/type/time.h>

using namespace std;
using namespace nlohmann;

namespace apache
{

namespace web
{

CommandExecutorObjectPtr CommandExecutorObject::Create(::database::DatabasePtr database) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::Create: Function call";
  auto p = CommandExecutorObjectPtr(new CommandExecutorObject(database));
  return p;
}

const ::web::type::JsonMessage CommandExecutorObject::Execute(const ::web::type::JsonMessage &message) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::Execute: Function call";
  auto json_object = json::parse(message);
  auto command = json_object["command"];
  auto result = GetUnknownCommandErrorJson();

  if (command == "get_apache_agent_names") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_agent_names' command";
    result = GetHostnames();
  }
  else if (command == "get_apache_virtualhosts_names") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_virtualhosts_names' command";

    auto args = json_object["args"];
    if (args.size() != 1) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: get_apache_virtualhosts_names require one argument";
      return GetInvalidArgumentErrorJson();
    }

    auto agent_name = args.at(0);
    result = GetVirtualhostsNames(agent_name);
  }
  else if (command == "get_apache_sessions") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_sessions' command";

    auto args = json_object["args"];
    if (args.size() != 4) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: get_apache_sessions require four arguments";
      return GetInvalidArgumentErrorJson();
    }

    result = GetSessions(args.at(0), args.at(1), args.at(2), args.at(3));
  }
  else if (command == "set_apache_sessions_as_anomaly") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'set_apache_sessions_as_anomaly' command";

    auto args = json_object["args"];
    if (args.size() != 2) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: set_apache_sessions_as_anomaly require two arguments";
      return GetInvalidArgumentErrorJson();
    }

    result = SetApacheSessionsAsAnomaly(args.at(0), args.at(1));
  }
  else if (command == "get_apache_anomaly_detection_configuration") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'get_apache_anomaly_detection_configuration' command";

    result = GetApacheAnomalyDetectionConfiguration();
  }
  else if (command == "set_apache_anomaly_detection_configuration") {
    BOOST_LOG_TRIVIAL(info) << "apache::web::CommandExecutorObject::Execute: Found 'set_apache_anomaly_detection_configuration' command";

    auto args = json_object["args"];
    if (args.size() != 4) {
      BOOST_LOG_TRIVIAL(warning) << "apache::web::CommandExecutorObject::Execute: set_apache_anomaly_detection_configuration require four arguments";
      return GetInvalidArgumentErrorJson();
    }

    result = SetApacheAnomalyDetectionConfiguration(args.at(0), args.at(1), args.at(2), args.at(3));
  }

  return result;
}

bool CommandExecutorObject::IsCommandSupported(const ::web::type::Command &command) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::IsCommandSupported: Function call";
  return (command == "get_apache_agent_names")
      || (command == "get_apache_virtualhosts_names")
      || (command == "get_apache_sessions")
      || (command == "set_apache_sessions_as_anomaly")
      || (command == "get_apache_anomaly_detection_configuration")
      || (command == "set_apache_anomaly_detection_configuration");
}

CommandExecutorObject::CommandExecutorObject(::database::DatabasePtr database)
: database_(database) {
}

const ::web::type::JsonMessage CommandExecutorObject::GetHostnames() {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetHostnames: Function call";

  json j;
  j["status"] = "ok";
  j["result"] = database_->GetApacheAgentNames();

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::GetVirtualhostsNames(const std::string &agent_name) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetVirtualhostsNames: Function call";

  json j;
  j["status"] = "ok";
  j["result"] = database_->GetApacheVirtualhostNames(agent_name);

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::GetSessions(const std::string &agent_name,
                                                                  const std::string &virtualhost_name,
                                                                  const std::string &begin_date,
                                                                  const std::string &end_date) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetSessions: Function call";

  auto tbegin = ::type::Timestamp::Create(::type::Time(),
                                          ::type::Date::Create(begin_date));
  auto tend = ::type::Timestamp::Create(::type::Time::Create(24, 59, 59),
                                        ::type::Date::Create(end_date));
  auto count = database_->GetApacheSessionStatisticsCount(agent_name, virtualhost_name,
                                                          tbegin, tend);

  ::apache::type::ApacheSessions sessions = database_->GetApacheSessionStatistics(agent_name, virtualhost_name,
                                                                                tbegin, tend,
                                                                                count, 0);

  json j, r = json::array();
  for (::apache::type::ApacheSessionEntry s : sessions) {
    json t;
    t["id"] = s.id;
    t["agent_name"] = s.agent_name;
    t["virtualhost"] = s.virtualhost;
    t["client_ip"] = s.client_ip;
    t["session_start"] = s.session_start.ToString();
    t["session_length"] = s.session_length;
    t["bandwidth_usage"] = s.bandwidth_usage;
    t["requests_count"] = s.requests_count;
    t["error_percentage"] = s.error_percentage;
    t["useragent"] = s.useragent;
    t["is_anomaly"] = s.is_anomaly;

    r.push_back(t);
  }

  j["status"] = "ok";
  j["result"] = r;

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::SetApacheSessionsAsAnomaly(const std::vector<long long> &all,
                                                                                const std::vector<long long> &anomalies) {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::SetApacheSessionsAsAnomaly: Function call";

  database_->SetApacheSessionAsAnomaly(all, anomalies);

  json j;
  j["status"] = "ok";

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::GetApacheAnomalyDetectionConfiguration() {
  BOOST_LOG_TRIVIAL(debug) << "apache::web::CommandExecutorObject::GetApacheAnomalyDetectionConfiguration: Function call";

  auto conf = database_->GetApacheAnomalyDetectionConfiguration();

  json r = json::array();
  for (auto c : conf) {
    json t;
    t["id"] = c.id;
    t["agent_name"] = c.agent_name;
    t["virtualhost_name"] = c.virtualhost_name;
    t["begin_date"] = to_string(c.begin_date.GetYear()) + "-" + to_string(c.begin_date.GetMonth()) + "-" + to_string(c.begin_date.GetDay());
    t["end_date"] = to_string(c.end_date.GetYear()) + "-" + to_string(c.end_date.GetMonth()) + "-" + to_string(c.end_date.GetDay());

    r.push_back(t);
  }

  json j;
  j["status"] = "ok";
  j["result"] = r;

  return j.dump();
}

const ::web::type::JsonMessage CommandExecutorObject::SetApacheAnomalyDetectionConfiguration(const std::string &agent_name,
                                                                                const std::string &virtualhost_name,
                                                                                const std::string &begin_date,
                                                                                const std::string &end_date) {
  ::apache::type::AnomalyDetectionConfigurationEntry c;
  c.agent_name = agent_name;
  c.virtualhost_name = virtualhost_name;
  c.begin_date = ::type::Date::Create(begin_date);
  c.end_date = ::type::Date::Create(end_date);

  database_->AddDate(c.begin_date.GetDay(), c.begin_date.GetMonth(), c.begin_date.GetYear());
  database_->AddDate(c.end_date.GetDay(), c.end_date.GetMonth(), c.end_date.GetYear());
  database_->SetApacheAnomalyDetectionConfiguration(c);

  json j;
  j["status"] = "ok";

  return j.dump();
}

}

}
<|endoftext|>


<commit_before>/**
 * @brief Executor for index scan node.
 *
 * Copyright(c) 2015, CMU
 */

#include "backend/executor/index_scan_executor.h"

#include <memory>
#include <utility>
#include <vector>

#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"

#include "backend/common/logger.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for indexscan executor.
 * @param node Indexscan node corresponding to this executor.
 */
IndexScanExecutor::IndexScanExecutor(planner::AbstractPlanNode *node,
                                     ExecutorContext *executor_context)
    : AbstractScanExecutor(node, executor_context) {}

/**
 * @brief Let base class Dinit() first, then do my job.
 * @return true on success, false otherwise.
 */
bool IndexScanExecutor::DInit() {

  auto status = AbstractScanExecutor::DInit();

  if(!status)
    return false;

  assert(children_.size() == 0);
  LOG_INFO("Index Scan executor :: 0 child \n");

  // Grab info from plan node and check it
  const planner::IndexScanNode &node = GetPlanNode<planner::IndexScanNode>();

  index_ = node.GetIndex();
  assert(index_ != nullptr);

  result_itr = START_OID;
  done_ = false;

  column_ids_ = node.GetColumnIds();
  key_column_ids_ = node.GetKeyColumnIds();
  expr_types_ = node.GetExprTypes();
  values_ = node.GetValues();

  auto table = node.GetTable();

  if(table != nullptr){
    if(column_ids_.empty()){
      column_ids_.resize(table->GetSchema()->GetColumnCount());
      std::iota(column_ids_.begin(), column_ids_.end(), 0);
    }
  }

  return true;
}

/**
 * @brief Creates logical tile(s) after scanning index.
 * @return true on success, false otherwise.
 */
bool IndexScanExecutor::DExecute() {

  if(!done_){
    auto status = ExecIndexLookup();
    if(status == false)
      return false;
  }

  // Already performed the index lookup
  assert(done_);

  while(result_itr < result.size()){  // Avoid returning empty tiles
    // In order to be as lazy as possible,
    // the generic predicate is checked here (instead of upfront)
    if(nullptr != predicate_){
      for (oid_t tuple_id : *result[result_itr]) {
        expression::ContainerTuple<LogicalTile> tuple(result[result_itr], tuple_id);
        if (predicate_->Evaluate(&tuple, nullptr, executor_context_).IsFalse()) {
          result[result_itr]->RemoveVisibility(tuple_id);
        }
      }
    }

    if(result[result_itr]->GetTupleCount() == 0){
      result_itr++;
      continue;
    }
    else{
      SetOutput(result[result_itr]);
      result_itr++;
      return true;
    }

  } // end while

  return false;
}

bool IndexScanExecutor::ExecIndexLookup(){
  assert(!done_);

  std::vector<ItemPointer> tuple_locations;

  LOG_INFO("Tuple locations : %lu \n", tuple_locations.size());

  tuple_locations = index_->Scan(values_,
                                 key_column_ids_,
                                 expr_types_);

  LOG_INFO("Tuple locations : %lu \n", tuple_locations.size());

  if (tuple_locations.size() == 0) return false;

  auto transaction_ = executor_context_->GetTransaction();
  txn_id_t txn_id = transaction_->GetTransactionId();
  cid_t commit_id = transaction_->GetLastCommitId();

  // Get the logical tiles corresponding to the given tuple locations
  result = LogicalTileFactory::WrapTileGroups(tuple_locations, column_ids_,
                                              txn_id, commit_id);
  done_ = true;

  LOG_INFO("Result tiles : %lu \n", result.size());

  return true;
}

}  // namespace executor
}  // namespace peloton
<commit_msg>Reduce logging<commit_after>/**
 * @brief Executor for index scan node.
 *
 * Copyright(c) 2015, CMU
 */

#include "backend/executor/index_scan_executor.h"

#include <memory>
#include <utility>
#include <vector>

#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"

#include "backend/common/logger.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for indexscan executor.
 * @param node Indexscan node corresponding to this executor.
 */
IndexScanExecutor::IndexScanExecutor(planner::AbstractPlanNode *node,
                                     ExecutorContext *executor_context)
    : AbstractScanExecutor(node, executor_context) {}

/**
 * @brief Let base class Dinit() first, then do my job.
 * @return true on success, false otherwise.
 */
bool IndexScanExecutor::DInit() {

  auto status = AbstractScanExecutor::DInit();

  if(!status)
    return false;

  assert(children_.size() == 0);
  LOG_TRACE("Index Scan executor :: 0 child");

  // Grab info from plan node and check it
  const planner::IndexScanNode &node = GetPlanNode<planner::IndexScanNode>();

  index_ = node.GetIndex();
  assert(index_ != nullptr);

  result_itr = START_OID;
  done_ = false;

  column_ids_ = node.GetColumnIds();
  key_column_ids_ = node.GetKeyColumnIds();
  expr_types_ = node.GetExprTypes();
  values_ = node.GetValues();

  auto table = node.GetTable();

  if(table != nullptr){
    if(column_ids_.empty()){
      column_ids_.resize(table->GetSchema()->GetColumnCount());
      std::iota(column_ids_.begin(), column_ids_.end(), 0);
    }
  }

  return true;
}

/**
 * @brief Creates logical tile(s) after scanning index.
 * @return true on success, false otherwise.
 */
bool IndexScanExecutor::DExecute() {

  if(!done_){
    auto status = ExecIndexLookup();
    if(status == false)
      return false;
  }

  // Already performed the index lookup
  assert(done_);

  while(result_itr < result.size()){  // Avoid returning empty tiles
    // In order to be as lazy as possible,
    // the generic predicate is checked here (instead of upfront)
    if(nullptr != predicate_){
      for (oid_t tuple_id : *result[result_itr]) {
        expression::ContainerTuple<LogicalTile> tuple(result[result_itr], tuple_id);
        if (predicate_->Evaluate(&tuple, nullptr, executor_context_).IsFalse()) {
          result[result_itr]->RemoveVisibility(tuple_id);
        }
      }
    }

    if(result[result_itr]->GetTupleCount() == 0){
      result_itr++;
      continue;
    }
    else{
      SetOutput(result[result_itr]);
      result_itr++;
      return true;
    }

  } // end while

  return false;
}

bool IndexScanExecutor::ExecIndexLookup(){
  assert(!done_);

  std::vector<ItemPointer> tuple_locations;

  tuple_locations = index_->Scan(values_,
                                 key_column_ids_,
                                 expr_types_);

  LOG_INFO("Tuple locations : %lu", tuple_locations.size());

  if (tuple_locations.size() == 0) return false;

  auto transaction_ = executor_context_->GetTransaction();
  txn_id_t txn_id = transaction_->GetTransactionId();
  cid_t commit_id = transaction_->GetLastCommitId();

  // Get the logical tiles corresponding to the given tuple locations
  result = LogicalTileFactory::WrapTileGroups(tuple_locations, column_ids_,
                                              txn_id, commit_id);
  done_ = true;

  LOG_TRACE("Result tiles : %lu", result.size());

  return true;
}

}  // namespace executor
}  // namespace peloton
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   DoubleIntegratorWithDampingAndCoulumbFriction.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2011-08-03
//!
//! @brief Contiains a second order integrator utility with provision for some damping and coulumb friction
//!
//$Id$

#include <iostream>
#include <cassert>
#include "../HopsanCore.h"
#include "DoubleIntegratorWithDampingAndCoulumbFriction.h"

using namespace hopsan;

DoubleIntegratorWithDampingAndCoulumbFriction::DoubleIntegratorWithDampingAndCoulumbFriction()
{
}

void DoubleIntegratorWithDampingAndCoulumbFriction::initialize(double timestep, double w0, double mass, double Fs, double Fk, double u0, double y0, double sy0)
{
    mW0 = w0;
    mUs = Fs/mass;
    mUk = Fk/mass;
    mDelayU = u0;
    mDelayY = y0;
    mDelaySY = sy0;
    mTimeStep = timestep;
}

void DoubleIntegratorWithDampingAndCoulumbFriction::initializeValues(double u0, double y0, double sy0)
{
    mDelayU = u0;
    mDelayY = y0;
    mDelaySY = sy0;
}

void DoubleIntegratorWithDampingAndCoulumbFriction::setDamping(double w0)
{
    mW0 = w0;
}

void DoubleIntegratorWithDampingAndCoulumbFriction::integrate(double u)
{
    double tempDelaySY = mDelaySY;
    double ue;    //Effective acceleration
    double ues = -(2-mW0)/mTimeStep*tempDelaySY-mDelayU;

    if(ues>(u-mUs) && ues<(u+mUs))
    {
      ue = ues;           //No movement
      mDelaySY = 0;
      mDelayY = mDelayY;
    }
    else
    {
        if(ues<(u-mUs))   //Movement
        {
            ue = u-mUk;
        }
        else if(ues>(u+mUs))
        {
            ue = u+mUk;
        }
        mDelaySY = (2-mW0)/(2+mW0)*tempDelaySY + mTimeStep/(2+mW0)*(ue+mDelayU);
        mDelayY = mDelayY + mTimeStep/2*(mDelaySY+tempDelaySY);
    }
}

//! @brief Integrates one step, but saves previous step in case step has to be re-integrated
void DoubleIntegratorWithDampingAndCoulumbFriction::integrateWithUndo(double u)
{
    mDelaySYbackup = mDelaySY;
    mDelayYbackup = mDelayY;
    mDelayUbackup = mDelayU;

    integrate(u);
}

//! @brief Re-integrates last step
//! Last step must have been called with integrateWithUndo() for this to work.
void DoubleIntegratorWithDampingAndCoulumbFriction::redoIntegrate(double u)
{
    mDelaySY = (2-mW0)/(2+mW0)*mDelaySYbackup + mTimeStep/(2.0+mW0)*(u + mDelayUbackup);
    mDelayY = mDelayYbackup + mTimeStep/2.0*(mDelaySY+mDelaySYbackup);
    mDelayU = u;
}

//! Returns first primitive from double integration
double DoubleIntegratorWithDampingAndCoulumbFriction::valueFirst()
{
    return mDelaySY;
}

//! Returns second primitive from double integration
double DoubleIntegratorWithDampingAndCoulumbFriction::valueSecond()
{
    return mDelayY;
}
<commit_msg>Minor fix to integrator with friction utility<commit_after>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   DoubleIntegratorWithDampingAndCoulumbFriction.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2011-08-03
//!
//! @brief Contiains a second order integrator utility with provision for some damping and coulumb friction
//!
//$Id$

#include <iostream>
#include <cassert>
#include "../HopsanCore.h"
#include "DoubleIntegratorWithDampingAndCoulumbFriction.h"

using namespace hopsan;

DoubleIntegratorWithDampingAndCoulumbFriction::DoubleIntegratorWithDampingAndCoulumbFriction()
{
}

void DoubleIntegratorWithDampingAndCoulumbFriction::initialize(double timestep, double w0, double mass, double Fs, double Fk, double u0, double y0, double sy0)
{
    mW0 = w0;
    mUs = Fs/mass;
    mUk = Fk/mass;
    mDelayU = u0;
    mDelayY = y0;
    mDelaySY = sy0;
    mTimeStep = timestep;
}

void DoubleIntegratorWithDampingAndCoulumbFriction::initializeValues(double u0, double y0, double sy0)
{
    mDelayU = u0;
    mDelayY = y0;
    mDelaySY = sy0;
}

void DoubleIntegratorWithDampingAndCoulumbFriction::setDamping(double w0)
{
    mW0 = w0;
}

void DoubleIntegratorWithDampingAndCoulumbFriction::integrate(double u)
{
    double tempDelaySY = mDelaySY;
    double ue;    //Effective acceleration
    double ues = -(2-mW0)/mTimeStep*tempDelaySY-mDelayU;

    if(ues>(u-mUs) && ues<(u+mUs))
    {
      ue = ues;           //No movement
      mDelaySY = 0;
      mDelayY = mDelayY;
    }
    else
    {
        if(ues<(u-mUs))   //Movement
        {
            ue = u-mUk;
        }
        else if(ues>=(u+mUs))
        {
            ue = u+mUk;
        }
        mDelaySY = (2-mW0)/(2+mW0)*tempDelaySY + mTimeStep/(2+mW0)*(ue+mDelayU);
        mDelayY = mDelayY + mTimeStep/2*(mDelaySY+tempDelaySY);
    }
}

//! @brief Integrates one step, but saves previous step in case step has to be re-integrated
void DoubleIntegratorWithDampingAndCoulumbFriction::integrateWithUndo(double u)
{
    mDelaySYbackup = mDelaySY;
    mDelayYbackup = mDelayY;
    mDelayUbackup = mDelayU;

    integrate(u);
}

//! @brief Re-integrates last step
//! Last step must have been called with integrateWithUndo() for this to work.
void DoubleIntegratorWithDampingAndCoulumbFriction::redoIntegrate(double u)
{
    mDelaySY = (2-mW0)/(2+mW0)*mDelaySYbackup + mTimeStep/(2.0+mW0)*(u + mDelayUbackup);
    mDelayY = mDelayYbackup + mTimeStep/2.0*(mDelaySY+mDelaySYbackup);
    mDelayU = u;
}

//! Returns first primitive from double integration
double DoubleIntegratorWithDampingAndCoulumbFriction::valueFirst()
{
    return mDelaySY;
}

//! Returns second primitive from double integration
double DoubleIntegratorWithDampingAndCoulumbFriction::valueSecond()
{
    return mDelayY;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2011 The QXmpp developers
 *
 * Author:
 *  Manjeet Dahiya
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants.h"

/// Constructs a QXmppPresence.
///
/// \param type
/// \param status

QXmppPresence::QXmppPresence(QXmppPresence::Type type,
                             const QXmppPresence::Status& status)
    : QXmppStanza(),
    m_type(type),
    m_status(status),
    m_vCardUpdateType(VCardUpdateNone)
{

}

/// Destroys a QXmppPresence.

QXmppPresence::~QXmppPresence()
{

}

/// Returns the presence type.
///
/// You can use this method to determine the action which needs to be
/// taken in response to receiving the presence. For instance, if the type is
/// QXmppPresence::Available or QXmppPresence::Unavailable, you could update
/// the icon representing a contact's availability.

QXmppPresence::Type QXmppPresence::type() const
{
    return m_type;
}

/// Sets the presence type.
///
/// \param type

void QXmppPresence::setType(QXmppPresence::Type type)
{
    m_type = type;
}

/// Returns the presence status.

const QXmppPresence::Status& QXmppPresence::status() const
{
    return m_status;
}

/// Returns a reference to the presence status, allowing you to change it.

QXmppPresence::Status& QXmppPresence::status()
{
    return m_status;
}

/// Sets the presence status.
///
/// \param status

void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
    m_status = status;
}

void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    setTypeFromStr(element.attribute("type"));
    m_status.parse(element);

    QXmppElementList extensions;
    QDomElement xElement = element.firstChildElement();
    m_vCardUpdateType = VCardUpdateNone;
    while(!xElement.isNull())
    {
        // XEP-0045: Multi-User Chat
        if(xElement.namespaceURI() == ns_muc_user)
        {
            QDomElement itemElement = xElement.firstChildElement("item");
            m_mucItem.parse(itemElement);
            QDomElement statusElement = xElement.firstChildElement("status");
            m_mucStatusCodes.clear();
            while (!statusElement.isNull()) {
                m_mucStatusCodes << statusElement.attribute("code").toInt();
                statusElement = statusElement.nextSiblingElement("status");
            }
        }
        // XEP-0153: vCard-Based Avatars
        else if(xElement.namespaceURI() == ns_vcard_update)
        {
            QDomElement photoElement = xElement.firstChildElement("photo");
            if(!photoElement.isNull())
            {
                m_photoHash = QByteArray::fromHex(photoElement.text().toAscii());
                if(m_photoHash.isEmpty())
                    m_vCardUpdateType = VCardUpdateNoPhoto;
                else
                    m_vCardUpdateType = VCardUpdateValidPhoto;
            }
            else
            {
                m_photoHash = QByteArray();
                m_vCardUpdateType = VCardUpdateNotReady;
            }
        }
        // XEP-0115: Entity Capabilities
        else if(xElement.tagName() == "c" && xElement.namespaceURI() == ns_capabilities)
        {
            m_capabilityNode = xElement.attribute("node");
            m_capabilityVer = QByteArray::fromBase64(xElement.attribute("ver").toAscii());
            m_capabilityHash = xElement.attribute("hash");
            m_capabilityExt = xElement.attribute("ext").split(" ", QString::SkipEmptyParts);
        }
        else if (xElement.tagName() == "error")
        {
        }
        else if (xElement.tagName() == "show")
        {
        }
        else if (xElement.tagName() == "status")
        {
        }
        else if (xElement.tagName() == "priority")
        {
        }
        else
        {
            // other extensions
            extensions << QXmppElement(xElement);
        }
        xElement = xElement.nextSiblingElement();
    }
    setExtensions(extensions);
}

void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
    xmlWriter->writeStartElement("presence");
    helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
    helperToXmlAddAttribute(xmlWriter,"id", id());
    helperToXmlAddAttribute(xmlWriter,"to", to());
    helperToXmlAddAttribute(xmlWriter,"from", from());
    helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
    m_status.toXml(xmlWriter);

    error().toXml(xmlWriter);

    // XEP-0045: Multi-User Chat
    if(!m_mucItem.isNull() || !m_mucStatusCodes.isEmpty())
    {
        xmlWriter->writeStartElement("x");
        xmlWriter->writeAttribute("xmlns", ns_muc_user);
        if (!m_mucItem.isNull())
            m_mucItem.toXml(xmlWriter);
        foreach (int code, m_mucStatusCodes) {
            xmlWriter->writeStartElement("status");
            xmlWriter->writeAttribute("code", QString::number(code));
            xmlWriter->writeEndElement();
        }
        xmlWriter->writeEndElement();
    }

    // XEP-0153: vCard-Based Avatars
    if(m_vCardUpdateType != VCardUpdateNone)
    {
        xmlWriter->writeStartElement("x");
        xmlWriter->writeAttribute("xmlns", ns_vcard_update);
        switch(m_vCardUpdateType)
        {
        case VCardUpdateNoPhoto:
            helperToXmlAddTextElement(xmlWriter, "photo", "");
            break;
        case VCardUpdateValidPhoto:
            helperToXmlAddTextElement(xmlWriter, "photo", m_photoHash.toHex());
            break;
        case VCardUpdateNotReady:
            break;
        default:
            break;
        }
        xmlWriter->writeEndElement();
    }

    if(!m_capabilityNode.isEmpty() && !m_capabilityVer.isEmpty()
        && !m_capabilityHash.isEmpty())
    {
        xmlWriter->writeStartElement("c");
        xmlWriter->writeAttribute("xmlns", ns_capabilities);
        helperToXmlAddAttribute(xmlWriter, "hash", m_capabilityHash);
        helperToXmlAddAttribute(xmlWriter, "node", m_capabilityNode);
        helperToXmlAddAttribute(xmlWriter, "ver", m_capabilityVer.toBase64());
        xmlWriter->writeEndElement();
    }

    foreach (const QXmppElement &extension, extensions())
        extension.toXml(xmlWriter);

    xmlWriter->writeEndElement();
}

QString QXmppPresence::getTypeStr() const
{
    switch(m_type) {
    case QXmppPresence::Error:
        return "error";
    case QXmppPresence::Available:
        return "";
    case QXmppPresence::Unavailable:
        return "unavailable";
    case QXmppPresence::Subscribe:
        return "subscribe";
    case QXmppPresence::Subscribed:
        return "subscribed";
    case QXmppPresence::Unsubscribe:
        return "unsubscribe";
    case QXmppPresence::Unsubscribed:
        return "unsubscribed";
    case QXmppPresence::Probe:
        return "probe";
    default:
        qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
        return "";
    }
}

void QXmppPresence::setTypeFromStr(const QString& str)
{
    if(str == "error")
        m_type = QXmppPresence::Error;
    else if(str == "")
        m_type = QXmppPresence::Available;
    else if(str == "unavailable")
        m_type = QXmppPresence::Unavailable;
    else if(str == "subscribe")
        m_type = QXmppPresence::Subscribe;
    else if(str == "subscribed")
        m_type = QXmppPresence::Subscribed;
    else if(str == "unsubscribe")
        m_type = QXmppPresence::Unsubscribe;
    else if(str == "unsubscribed")
        m_type = QXmppPresence::Unsubscribed;
    else if(str == "probe")
        m_type = QXmppPresence::Probe;
    else {
        qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        m_type = QXmppPresence::Error;
    }
}

/// Constructs a presence status.

QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
                             const QString statusText, int priority) :
                                m_type(type),
                                m_statusText(statusText), m_priority(priority)
{
}

/// Returns the status type, for instance busy or away.

QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
    return m_type;
}

/// Sets the status type.

void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
    m_type = type;
}

void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
    // FIXME: there is no keyword for Offline
    if(str == "")
        m_type = QXmppPresence::Status::Online;
    else if(str == "away")
        m_type = QXmppPresence::Status::Away;
    else if(str == "chat")
        m_type = QXmppPresence::Status::Chat;
    else if(str == "dnd")
        m_type = QXmppPresence::Status::DND;
    else if(str == "xa")
        m_type = QXmppPresence::Status::XA;
    else {
        qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
            qPrintable(str));
        m_type = QXmppPresence::Status::Online;
    }
}

QString QXmppPresence::Status::getTypeStr() const
{
    switch(m_type)
    {
    case QXmppPresence::Status::Online:
        return "";
    case QXmppPresence::Status::Offline:
        // FIXME: there is no keyword for Offline
        return "";
    case QXmppPresence::Status::Away:
        return "away";
    case QXmppPresence::Status::XA:
        return "xa";
    case QXmppPresence::Status::DND:
        return "dnd";
    case QXmppPresence::Status::Chat:
        return "chat";
    default:
        qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
                 (int)m_type);
        return "";
    }
}

/// Returns the status text, a textual description of the user's status.

QString QXmppPresence::Status::statusText() const
{
    return m_statusText;
}

/// Sets the status text, a textual description of the user's status.
///
/// \param str The status text, for example "Gone fishing".

void QXmppPresence::Status::setStatusText(const QString& str)
{
    m_statusText = str;
}

/// Returns the priority level of the resource.

int QXmppPresence::Status::priority() const
{
    return m_priority;
}

/// Sets the priority level of the resource.
///
/// \param priority

void QXmppPresence::Status::setPriority(int priority)
{
    m_priority = priority;
}

void QXmppPresence::Status::parse(const QDomElement &element)
{
    setTypeFromStr(element.firstChildElement("show").text());
    m_statusText = element.firstChildElement("status").text();
    m_priority = element.firstChildElement("priority").text().toInt();
}

void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
    const QString show = getTypeStr();
    if (!show.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
    if (!m_statusText.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
    if (m_priority != 0)
        helperToXmlAddTextElement(xmlWriter, "priority", QString::number(m_priority));
}

/// Returns the photo-hash of the VCardUpdate.
///
/// \return QByteArray

QByteArray QXmppPresence::photoHash() const
{
    return m_photoHash;
}

/// Sets the photo-hash of the VCardUpdate.
///
/// \param photoHash as QByteArray

void QXmppPresence::setPhotoHash(const QByteArray& photoHash)
{
    m_photoHash = photoHash;
}

/// Returns the type of VCardUpdate
///
/// \return VCardUpdateType

QXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType() const
{
    return m_vCardUpdateType;
}

/// Sets the type of VCardUpdate
///
/// \param type VCardUpdateType

void QXmppPresence::setVCardUpdateType(VCardUpdateType type)
{
    m_vCardUpdateType = type;
}

/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityHash() const
{
    return m_capabilityHash;
}

/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityHash(const QString& hash)
{
    m_capabilityHash = hash;
}

/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityNode() const
{
    return m_capabilityNode;
}

/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityNode(const QString& node)
{
    m_capabilityNode = node;
}

/// XEP-0115: Entity Capabilities
QByteArray QXmppPresence::capabilityVer() const
{
    return m_capabilityVer;
}

/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityVer(const QByteArray& ver)
{
    m_capabilityVer = ver;
}

/// Legacy XEP-0115: Entity Capabilities
QStringList QXmppPresence::capabilityExt() const
{
    return m_capabilityExt;
}

/// Returns the MUC item.

QXmppMucItem QXmppPresence::mucItem() const
{
    return m_mucItem;
}

/// Sets the MUC item.
///
/// \param item

void QXmppPresence::setMucItem(const QXmppMucItem &item)
{
    m_mucItem = item;
}

/// Returns the MUC status codes.

QList<int> QXmppPresence::mucStatusCodes() const
{
    return m_mucStatusCodes;
}

/// Sets the MUC status codes.
///
/// \param codes

void QXmppPresence::setMucStatusCodes(const QList<int> &codes)
{
    m_mucStatusCodes = codes;
}

<commit_msg>trailing whitespace cleanup<commit_after>/*
 * Copyright (C) 2008-2011 The QXmpp developers
 *
 * Author:
 *  Manjeet Dahiya
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants.h"

/// Constructs a QXmppPresence.
///
/// \param type
/// \param status

QXmppPresence::QXmppPresence(QXmppPresence::Type type,
                             const QXmppPresence::Status& status)
    : QXmppStanza(),
    m_type(type),
    m_status(status),
    m_vCardUpdateType(VCardUpdateNone)
{

}

/// Destroys a QXmppPresence.

QXmppPresence::~QXmppPresence()
{

}

/// Returns the presence type.
///
/// You can use this method to determine the action which needs to be
/// taken in response to receiving the presence. For instance, if the type is
/// QXmppPresence::Available or QXmppPresence::Unavailable, you could update
/// the icon representing a contact's availability.

QXmppPresence::Type QXmppPresence::type() const
{
    return m_type;
}

/// Sets the presence type.
///
/// \param type

void QXmppPresence::setType(QXmppPresence::Type type)
{
    m_type = type;
}

/// Returns the presence status.

const QXmppPresence::Status& QXmppPresence::status() const
{
    return m_status;
}

/// Returns a reference to the presence status, allowing you to change it.

QXmppPresence::Status& QXmppPresence::status()
{
    return m_status;
}

/// Sets the presence status.
///
/// \param status

void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
    m_status = status;
}

void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    setTypeFromStr(element.attribute("type"));
    m_status.parse(element);

    QXmppElementList extensions;
    QDomElement xElement = element.firstChildElement();
    m_vCardUpdateType = VCardUpdateNone;
    while(!xElement.isNull())
    {
        // XEP-0045: Multi-User Chat
        if(xElement.namespaceURI() == ns_muc_user)
        {
            QDomElement itemElement = xElement.firstChildElement("item");
            m_mucItem.parse(itemElement);
            QDomElement statusElement = xElement.firstChildElement("status");
            m_mucStatusCodes.clear();
            while (!statusElement.isNull()) {
                m_mucStatusCodes << statusElement.attribute("code").toInt();
                statusElement = statusElement.nextSiblingElement("status");
            }
        }
        // XEP-0153: vCard-Based Avatars
        else if(xElement.namespaceURI() == ns_vcard_update)
        {
            QDomElement photoElement = xElement.firstChildElement("photo");
            if(!photoElement.isNull())
            {
                m_photoHash = QByteArray::fromHex(photoElement.text().toAscii());
                if(m_photoHash.isEmpty())
                    m_vCardUpdateType = VCardUpdateNoPhoto;
                else
                    m_vCardUpdateType = VCardUpdateValidPhoto;
            }
            else
            {
                m_photoHash = QByteArray();
                m_vCardUpdateType = VCardUpdateNotReady;
            }
        }
        // XEP-0115: Entity Capabilities
        else if(xElement.tagName() == "c" && xElement.namespaceURI() == ns_capabilities)
        {
            m_capabilityNode = xElement.attribute("node");
            m_capabilityVer = QByteArray::fromBase64(xElement.attribute("ver").toAscii());
            m_capabilityHash = xElement.attribute("hash");
            m_capabilityExt = xElement.attribute("ext").split(" ", QString::SkipEmptyParts);
        }
        else if (xElement.tagName() == "error")
        {
        }
        else if (xElement.tagName() == "show")
        {
        }
        else if (xElement.tagName() == "status")
        {
        }
        else if (xElement.tagName() == "priority")
        {
        }
        else
        {
            // other extensions
            extensions << QXmppElement(xElement);
        }
        xElement = xElement.nextSiblingElement();
    }
    setExtensions(extensions);
}

void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
    xmlWriter->writeStartElement("presence");
    helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
    helperToXmlAddAttribute(xmlWriter,"id", id());
    helperToXmlAddAttribute(xmlWriter,"to", to());
    helperToXmlAddAttribute(xmlWriter,"from", from());
    helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
    m_status.toXml(xmlWriter);

    error().toXml(xmlWriter);

    // XEP-0045: Multi-User Chat
    if(!m_mucItem.isNull() || !m_mucStatusCodes.isEmpty())
    {
        xmlWriter->writeStartElement("x");
        xmlWriter->writeAttribute("xmlns", ns_muc_user);
        if (!m_mucItem.isNull())
            m_mucItem.toXml(xmlWriter);
        foreach (int code, m_mucStatusCodes) {
            xmlWriter->writeStartElement("status");
            xmlWriter->writeAttribute("code", QString::number(code));
            xmlWriter->writeEndElement();
        }
        xmlWriter->writeEndElement();
    }

    // XEP-0153: vCard-Based Avatars
    if(m_vCardUpdateType != VCardUpdateNone)
    {
        xmlWriter->writeStartElement("x");
        xmlWriter->writeAttribute("xmlns", ns_vcard_update);
        switch(m_vCardUpdateType)
        {
        case VCardUpdateNoPhoto:
            helperToXmlAddTextElement(xmlWriter, "photo", "");
            break;
        case VCardUpdateValidPhoto:
            helperToXmlAddTextElement(xmlWriter, "photo", m_photoHash.toHex());
            break;
        case VCardUpdateNotReady:
            break;
        default:
            break;
        }
        xmlWriter->writeEndElement();
    }

    if(!m_capabilityNode.isEmpty() && !m_capabilityVer.isEmpty()
        && !m_capabilityHash.isEmpty())
    {
        xmlWriter->writeStartElement("c");
        xmlWriter->writeAttribute("xmlns", ns_capabilities);
        helperToXmlAddAttribute(xmlWriter, "hash", m_capabilityHash);
        helperToXmlAddAttribute(xmlWriter, "node", m_capabilityNode);
        helperToXmlAddAttribute(xmlWriter, "ver", m_capabilityVer.toBase64());
        xmlWriter->writeEndElement();
    }

    foreach (const QXmppElement &extension, extensions())
        extension.toXml(xmlWriter);

    xmlWriter->writeEndElement();
}

QString QXmppPresence::getTypeStr() const
{
    switch(m_type) {
    case QXmppPresence::Error:
        return "error";
    case QXmppPresence::Available:
        return "";
    case QXmppPresence::Unavailable:
        return "unavailable";
    case QXmppPresence::Subscribe:
        return "subscribe";
    case QXmppPresence::Subscribed:
        return "subscribed";
    case QXmppPresence::Unsubscribe:
        return "unsubscribe";
    case QXmppPresence::Unsubscribed:
        return "unsubscribed";
    case QXmppPresence::Probe:
        return "probe";
    default:
        qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
        return "";
    }
}

void QXmppPresence::setTypeFromStr(const QString& str)
{
    if(str == "error")
        m_type = QXmppPresence::Error;
    else if(str == "")
        m_type = QXmppPresence::Available;
    else if(str == "unavailable")
        m_type = QXmppPresence::Unavailable;
    else if(str == "subscribe")
        m_type = QXmppPresence::Subscribe;
    else if(str == "subscribed")
        m_type = QXmppPresence::Subscribed;
    else if(str == "unsubscribe")
        m_type = QXmppPresence::Unsubscribe;
    else if(str == "unsubscribed")
        m_type = QXmppPresence::Unsubscribed;
    else if(str == "probe")
        m_type = QXmppPresence::Probe;
    else {
        qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
                 qPrintable(str));
        m_type = QXmppPresence::Error;
    }
}

/// Constructs a presence status.

QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
                             const QString statusText, int priority) :
                                m_type(type),
                                m_statusText(statusText), m_priority(priority)
{
}

/// Returns the status type, for instance busy or away.

QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
    return m_type;
}

/// Sets the status type.

void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
    m_type = type;
}

void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
    // FIXME: there is no keyword for Offline
    if(str == "")
        m_type = QXmppPresence::Status::Online;
    else if(str == "away")
        m_type = QXmppPresence::Status::Away;
    else if(str == "chat")
        m_type = QXmppPresence::Status::Chat;
    else if(str == "dnd")
        m_type = QXmppPresence::Status::DND;
    else if(str == "xa")
        m_type = QXmppPresence::Status::XA;
    else {
        qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
            qPrintable(str));
        m_type = QXmppPresence::Status::Online;
    }
}

QString QXmppPresence::Status::getTypeStr() const
{
    switch(m_type) {
    case QXmppPresence::Status::Online:
        return "";
    case QXmppPresence::Status::Offline:
        // FIXME: there is no keyword for Offline
        return "";
    case QXmppPresence::Status::Away:
        return "away";
    case QXmppPresence::Status::XA:
        return "xa";
    case QXmppPresence::Status::DND:
        return "dnd";
    case QXmppPresence::Status::Chat:
        return "chat";
    default:
        qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
                 (int)m_type);
        return "";
    }
}

/// Returns the status text, a textual description of the user's status.

QString QXmppPresence::Status::statusText() const
{
    return m_statusText;
}

/// Sets the status text, a textual description of the user's status.
///
/// \param str The status text, for example "Gone fishing".

void QXmppPresence::Status::setStatusText(const QString& str)
{
    m_statusText = str;
}

/// Returns the priority level of the resource.

int QXmppPresence::Status::priority() const
{
    return m_priority;
}

/// Sets the priority level of the resource.
///
/// \param priority

void QXmppPresence::Status::setPriority(int priority)
{
    m_priority = priority;
}

void QXmppPresence::Status::parse(const QDomElement &element)
{
    setTypeFromStr(element.firstChildElement("show").text());
    m_statusText = element.firstChildElement("status").text();
    m_priority = element.firstChildElement("priority").text().toInt();
}

void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
    const QString show = getTypeStr();
    if (!show.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
    if (!m_statusText.isEmpty())
        helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
    if (m_priority != 0)
        helperToXmlAddTextElement(xmlWriter, "priority", QString::number(m_priority));
}

/// Returns the photo-hash of the VCardUpdate.
///
/// \return QByteArray

QByteArray QXmppPresence::photoHash() const
{
    return m_photoHash;
}

/// Sets the photo-hash of the VCardUpdate.
///
/// \param photoHash as QByteArray

void QXmppPresence::setPhotoHash(const QByteArray& photoHash)
{
    m_photoHash = photoHash;
}

/// Returns the type of VCardUpdate
///
/// \return VCardUpdateType

QXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType() const
{
    return m_vCardUpdateType;
}

/// Sets the type of VCardUpdate
///
/// \param type VCardUpdateType

void QXmppPresence::setVCardUpdateType(VCardUpdateType type)
{
    m_vCardUpdateType = type;
}

/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityHash() const
{
    return m_capabilityHash;
}

/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityHash(const QString& hash)
{
    m_capabilityHash = hash;
}

/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityNode() const
{
    return m_capabilityNode;
}

/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityNode(const QString& node)
{
    m_capabilityNode = node;
}

/// XEP-0115: Entity Capabilities
QByteArray QXmppPresence::capabilityVer() const
{
    return m_capabilityVer;
}

/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityVer(const QByteArray& ver)
{
    m_capabilityVer = ver;
}

/// Legacy XEP-0115: Entity Capabilities
QStringList QXmppPresence::capabilityExt() const
{
    return m_capabilityExt;
}

/// Returns the MUC item.

QXmppMucItem QXmppPresence::mucItem() const
{
    return m_mucItem;
}

/// Sets the MUC item.
///
/// \param item

void QXmppPresence::setMucItem(const QXmppMucItem &item)
{
    m_mucItem = item;
}

/// Returns the MUC status codes.

QList<int> QXmppPresence::mucStatusCodes() const
{
    return m_mucStatusCodes;
}

/// Sets the MUC status codes.
///
/// \param codes

void QXmppPresence::setMucStatusCodes(const QList<int> &codes)
{
    m_mucStatusCodes = codes;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "arch/x86/insts/microregop.hh"
#include "arch/x86/miscregs.hh"
#include "base/condcodes.hh"
#include <string>

namespace X86ISA
{
    uint64_t RegOpBase::genFlags(uint64_t oldFlags, uint64_t flagMask,
            uint64_t _dest, uint64_t _src1, uint64_t _src2,
            bool subtract) const
    {
        DPRINTF(Sparc, "flagMask = %#x\n", flagMask);
        uint64_t flags = oldFlags & ~flagMask;
        if(flagMask & (ECFBit | CFBit))
        {
            if(findCarry(dataSize*8, _dest, _src1, _src2))
                flags |= (flagMask & (ECFBit | CFBit));
            if(subtract)
                flags ^= (flagMask & (ECFBit | CFBit));
        }
        if(flagMask & PFBit && findParity(dataSize*8, _dest))
            flags |= PFBit;
        if(flagMask & AFBit)
        {
            if(findCarry(4, _dest, _src1, _src2))
                flags |= AFBit;
            if(subtract)
                flags ^= AFBit;
        }
        if(flagMask & (EZFBit | ZFBit) && findZero(dataSize*8, _dest))
            flags |= (flagMask & (EZFBit | ZFBit));
        if(flagMask & SFBit && findNegative(dataSize*8, _dest))
            flags |= SFBit;
        if(flagMask & OFBit && findOverflow(dataSize*8, _dest, _src1, _src2))
            flags |= OFBit;
        return flags;
    }

    std::string RegOp::generateDisassembly(Addr pc,
            const SymbolTable *symtab) const
    {
        std::stringstream response;

        printMnemonic(response, instMnem, mnemonic);
        printDestReg(response, 0, dataSize);
        response << ", ";
        printSrcReg(response, 0, dataSize);
        response << ", ";
        printSrcReg(response, 1, dataSize);
        return response.str();
    }

    std::string RegOpImm::generateDisassembly(Addr pc,
            const SymbolTable *symtab) const
    {
        std::stringstream response;

        printMnemonic(response, instMnem, mnemonic);
        printDestReg(response, 0, dataSize);
        response << ", ";
        printSrcReg(response, 0, dataSize);
        ccprintf(response, ", %#x", imm8);
        return response.str();
    }
}
<commit_msg>X86: Get rid of stray Sparc DPRINTF<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#include "arch/x86/insts/microregop.hh"
#include "arch/x86/miscregs.hh"
#include "base/condcodes.hh"
#include <string>

namespace X86ISA
{
    uint64_t RegOpBase::genFlags(uint64_t oldFlags, uint64_t flagMask,
            uint64_t _dest, uint64_t _src1, uint64_t _src2,
            bool subtract) const
    {
        DPRINTF(X86, "flagMask = %#x\n", flagMask);
        uint64_t flags = oldFlags & ~flagMask;
        if(flagMask & (ECFBit | CFBit))
        {
            if(findCarry(dataSize*8, _dest, _src1, _src2))
                flags |= (flagMask & (ECFBit | CFBit));
            if(subtract)
                flags ^= (flagMask & (ECFBit | CFBit));
        }
        if(flagMask & PFBit && findParity(dataSize*8, _dest))
            flags |= PFBit;
        if(flagMask & AFBit)
        {
            if(findCarry(4, _dest, _src1, _src2))
                flags |= AFBit;
            if(subtract)
                flags ^= AFBit;
        }
        if(flagMask & (EZFBit | ZFBit) && findZero(dataSize*8, _dest))
            flags |= (flagMask & (EZFBit | ZFBit));
        if(flagMask & SFBit && findNegative(dataSize*8, _dest))
            flags |= SFBit;
        if(flagMask & OFBit && findOverflow(dataSize*8, _dest, _src1, _src2))
            flags |= OFBit;
        return flags;
    }

    std::string RegOp::generateDisassembly(Addr pc,
            const SymbolTable *symtab) const
    {
        std::stringstream response;

        printMnemonic(response, instMnem, mnemonic);
        printDestReg(response, 0, dataSize);
        response << ", ";
        printSrcReg(response, 0, dataSize);
        response << ", ";
        printSrcReg(response, 1, dataSize);
        return response.str();
    }

    std::string RegOpImm::generateDisassembly(Addr pc,
            const SymbolTable *symtab) const
    {
        std::stringstream response;

        printMnemonic(response, instMnem, mnemonic);
        printDestReg(response, 0, dataSize);
        response << ", ";
        printSrcReg(response, 0, dataSize);
        ccprintf(response, ", %#x", imm8);
        return response.str();
    }
}
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <algorithm>
#include <cassert>
#include <miopen/errors.hpp>
#include <miopen/logger.hpp>
#include <miopen/tensor.hpp>
#include <numeric>
#include <string>

namespace miopen {

TensorDescriptor::TensorDescriptor() {}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens)
    : lens(plens), type(t)
{
    this->CalculateStrides();
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   std::initializer_list<std::size_t> plens,
                                   std::initializer_list<std::size_t> pstrides)
    : lens(plens), strides(pstrides), type(t)
{
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size)
    : lens(plens, plens + size), type(t)
{
    this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   const int* plens,
                                   const int* pstrides,
                                   int size)
    : lens(plens, plens + size), strides(pstrides, pstrides + size), type(t)
{
}

void TensorDescriptor::CalculateStrides()
{
    strides.clear();
    strides.resize(lens.size(), 0);
    strides.back() = 1;
    std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>());
}

const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; }
const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; }
int TensorDescriptor::GetSize() const
{
    assert(lens.size() == strides.size());
    return lens.size();
}
std::size_t TensorDescriptor::GetElementSize() const
{
    assert(lens.size() == strides.size());
    return std::accumulate(
        lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}
miopenDataType_t TensorDescriptor::GetType() const { return this->type; }

std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
    assert(l.size() <= this->GetSize());
    return std::inner_product(l.begin(), l.end(), strides.begin(), 0);
}

bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const
{
    assert(this->lens.size() == rhs.strides.size());
    return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides;
}

bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); }

std::string TensorDescriptor::ToString() const
{
    std::string result;
    for(auto i : this->lens)
    {
        result += std::to_string(i) + ", ";
    }
    return result.substr(0, result.length() - 2);
}

std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t)
{
    return LogRange(stream, t.lens, ", ");
}

} // namespace miopen

// TODO(paul): Remove
MIOPEN_EXPORT
int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
    return miopen::deref(tensorDesc).GetIndex(indices);
}
<commit_msg>Fix folding version problem with clang tidy<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include <algorithm>
#include <cassert>
#include <miopen/errors.hpp>
#include <miopen/logger.hpp>
#include <miopen/tensor.hpp>
#include <numeric>
#include <string>

namespace miopen {

TensorDescriptor::TensorDescriptor() {}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens)
    : lens(plens), type(t)
{
    this->CalculateStrides();
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   std::initializer_list<std::size_t> plens,
                                   std::initializer_list<std::size_t> pstrides)
    : lens(plens), strides(pstrides), type(t)
{
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size)
    : lens(plens, plens + size), type(t)
{
    this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   const int* plens,
                                   const int* pstrides,
                                   int size)
    : lens(plens, plens + size), strides(pstrides, pstrides + size), type(t)
{
}

void TensorDescriptor::CalculateStrides()
{
    strides.clear();
    strides.resize(lens.size(), 0);
    strides.back() = 1;
    std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>());
}

const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; }
const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; }
int TensorDescriptor::GetSize() const
{
    assert(lens.size() == strides.size());
    return lens.size();
}
std::size_t TensorDescriptor::GetElementSize() const
{
    assert(lens.size() == strides.size());
    return std::accumulate(
        lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}
miopenDataType_t TensorDescriptor::GetType() const { return this->type; }

std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
    assert(l.size() <= this->GetSize());
    return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0});
}

bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const
{
    assert(this->lens.size() == rhs.strides.size());
    return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides;
}

bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); }

std::string TensorDescriptor::ToString() const
{
    std::string result;
    for(auto i : this->lens)
    {
        result += std::to_string(i) + ", ";
    }
    return result.substr(0, result.length() - 2);
}

std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t)
{
    return LogRange(stream, t.lens, ", ");
}

} // namespace miopen

// TODO(paul): Remove
MIOPEN_EXPORT
int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
    return miopen::deref(tensorDesc).GetIndex(indices);
}
<|endoftext|>


<commit_before>
#include "server/zone/managers/mission/DestroyMissionLairObserver.h"
#include "server/zone/templates/mobile/LairTemplate.h"
#include "server/zone/managers/creature/HealLairObserverEvent.h"
#include "server/zone/templates/mobile/CreatureTemplate.h"
#include "server/zone/managers/creature/CreatureManager.h"
#include "server/zone/managers/creature/CreatureTemplateManager.h"
#include "server/zone/objects/creature/Creature.h"
#include "server/zone/managers/creature/LairAggroTask.h"

void DestroyMissionLairObserverImplementation::checkForHeal(TangibleObject* lair, TangibleObject* attacker, bool forceNewUpdate) {
	if (getMobType() == LairTemplate::NPC)
		return;

	LairObserverImplementation::checkForHeal(lair, attacker, forceNewUpdate);
}

bool DestroyMissionLairObserverImplementation::checkForNewSpawns(TangibleObject* lair, TangibleObject* attacker, bool forceSpawn) {
	if (lair->getZone() == NULL)
		return false;

	int spawnLimitAdjustment = 0;

	if (difficulty == 0) {
		spawnLimitAdjustment = -3;
	} else if (difficulty == 4) {
		spawnLimitAdjustment = 3;
	}

	int spawnLimit = lairTemplate->getSpawnLimit() + spawnLimitAdjustment;

	if (forceSpawn) {
		spawnNumber++;
	} else if (getMobType() == LairTemplate::NPC) {
		return false;
	} else {
		if (spawnedCreatures.size() >= spawnLimit && !lairTemplate->hasBossMobs())
			return true;

		int conditionDamage = lair->getConditionDamage();
		int maxCondition = lair->getMaxCondition();

		switch (spawnNumber) {
		case 0:
			spawnNumber++;
			break;
		case 1:
			if (conditionDamage > (maxCondition / 10)) {
				spawnNumber++;
			} else {
				return false;
			}
			break;
		case 2:
			if (conditionDamage > (maxCondition / 2)) {
				spawnNumber++;
			} else {
				return false;
			}
			break;
		case 3:
			if (lairTemplate->hasBossMobs() && conditionDamage > ((maxCondition * 9) / 10)) {
				spawnNumber++;
			} else {
				return false;
			}
			break;
		default:
			return false;
			break;
		}
	}

	VectorMap<String, int> objectsToSpawn; // String mobileTemplate, int number to spawn

	if (spawnNumber == 4) {
		if (System::random(100) > 4)
			return false;

		VectorMap<String, int>* mobs = lairTemplate->getBossMobiles();

		for (int i = 0; i < mobs->size(); i++) {
			objectsToSpawn.put(mobs->elementAt(i).getKey(), mobs->elementAt(i).getValue());
		}

	} else {
		Vector<String>* mobiles = lairTemplate->getWeightedMobiles();
		int amountToSpawn = 0;

		if (getMobType() == LairTemplate::CREATURE) {
			amountToSpawn = spawnLimit / 3;
		} else {
			amountToSpawn = System::random(2) + (spawnLimit / 3);
		}

		if (amountToSpawn < 1)
			amountToSpawn = 1;

		for (int i = 0; i < amountToSpawn; i++) {
			int num = System::random(mobiles->size() - 1);
			String mob = mobiles->get(num);

			if (objectsToSpawn.contains(mob)) {
				int value = objectsToSpawn.get(mob);
				objectsToSpawn.drop(mob);
				objectsToSpawn.put(mob, value + 1);
			} else {
				objectsToSpawn.put(mob, 1);
			}
		}
	}

	for(int i = 0; i < objectsToSpawn.size(); ++i) {

		if (spawnNumber != 4 && spawnedCreatures.size() >= spawnLimit)
			return true;

		String templateToSpawn = objectsToSpawn.elementAt(i).getKey();
		int numberToSpawn = objectsToSpawn.get(templateToSpawn);

		CreatureTemplate* creatureTemplate = CreatureTemplateManager::instance()->getTemplate(templateToSpawn);

		if (creatureTemplate == NULL)
			continue;

		float tamingChance = creatureTemplate->getTame();

		CreatureManager* creatureManager = lair->getZone()->getCreatureManager();

		for (int j = 0; j < numberToSpawn; j++) {

			float x = lair->getPositionX() + (size - System::random(size * 20) / 10.0f);
			float y = lair->getPositionY() + (size - System::random(size * 20) / 10.0f);
			float z = lair->getZone()->getHeight(x, y);

			ManagedReference<CreatureObject*> creo = NULL;

			if (creatureManager->checkSpawnAsBaby(tamingChance, babiesSpawned, 1000)) {
				creo = creatureManager->spawnCreatureAsBaby(templateToSpawn.hashCode(), x, z, y);
				babiesSpawned++;
			}

			if (creo == NULL)
				creo = creatureManager->spawnCreatureWithAi(templateToSpawn.hashCode(), x, z, y);

			if (creo == NULL)
				continue;

			if (!creo->isAiAgent()) {
				error("spawned non player creature with template " + templateToSpawn);
			} else {
				AiAgent* ai = cast<AiAgent*>( creo.get());

				Locker clocker(ai, lair);

				ai->setDespawnOnNoPlayerInRange(false);
				ai->setHomeLocation(x, z, y);
				ai->setRespawnTimer(0);
				ai->setHomeObject(lair);

				spawnedCreatures.add(creo);

			}
		}
	}

	if (spawnNumber == 4) {
		Reference<LairAggroTask*> task = new LairAggroTask(lair, attacker, _this.getReferenceUnsafeStaticCast(), true);
		task->schedule(1000);
	}

	return objectsToSpawn.size() > 0;
}

<commit_msg>[fixed] stability issue<commit_after>
#include "server/zone/managers/mission/DestroyMissionLairObserver.h"
#include "server/zone/templates/mobile/LairTemplate.h"
#include "server/zone/managers/creature/HealLairObserverEvent.h"
#include "server/zone/templates/mobile/CreatureTemplate.h"
#include "server/zone/managers/creature/CreatureManager.h"
#include "server/zone/managers/creature/CreatureTemplateManager.h"
#include "server/zone/objects/creature/Creature.h"
#include "server/zone/managers/creature/LairAggroTask.h"

void DestroyMissionLairObserverImplementation::checkForHeal(TangibleObject* lair, TangibleObject* attacker, bool forceNewUpdate) {
	if (getMobType() == LairTemplate::NPC)
		return;

	LairObserverImplementation::checkForHeal(lair, attacker, forceNewUpdate);
}

bool DestroyMissionLairObserverImplementation::checkForNewSpawns(TangibleObject* lair, TangibleObject* attacker, bool forceSpawn) {
	Zone* zone = lair->getZone();

	if (zone == NULL)
		return false;

	int spawnLimitAdjustment = 0;

	if (difficulty == 0) {
		spawnLimitAdjustment = -3;
	} else if (difficulty == 4) {
		spawnLimitAdjustment = 3;
	}

	int spawnLimit = lairTemplate->getSpawnLimit() + spawnLimitAdjustment;

	if (forceSpawn) {
		spawnNumber++;
	} else if (getMobType() == LairTemplate::NPC) {
		return false;
	} else {
		if (spawnedCreatures.size() >= spawnLimit && !lairTemplate->hasBossMobs())
			return true;

		int conditionDamage = lair->getConditionDamage();
		int maxCondition = lair->getMaxCondition();

		switch (spawnNumber) {
		case 0:
			spawnNumber++;
			break;
		case 1:
			if (conditionDamage > (maxCondition / 10)) {
				spawnNumber++;
			} else {
				return false;
			}
			break;
		case 2:
			if (conditionDamage > (maxCondition / 2)) {
				spawnNumber++;
			} else {
				return false;
			}
			break;
		case 3:
			if (lairTemplate->hasBossMobs() && conditionDamage > ((maxCondition * 9) / 10)) {
				spawnNumber++;
			} else {
				return false;
			}
			break;
		default:
			return false;
			break;
		}
	}

	VectorMap<String, int> objectsToSpawn; // String mobileTemplate, int number to spawn

	if (spawnNumber == 4) {
		if (System::random(100) > 4)
			return false;

		VectorMap<String, int>* mobs = lairTemplate->getBossMobiles();

		for (int i = 0; i < mobs->size(); i++) {
			objectsToSpawn.put(mobs->elementAt(i).getKey(), mobs->elementAt(i).getValue());
		}

	} else {
		Vector<String>* mobiles = lairTemplate->getWeightedMobiles();
		int amountToSpawn = 0;

		if (getMobType() == LairTemplate::CREATURE) {
			amountToSpawn = spawnLimit / 3;
		} else {
			amountToSpawn = System::random(2) + (spawnLimit / 3);
		}

		if (amountToSpawn < 1)
			amountToSpawn = 1;

		for (int i = 0; i < amountToSpawn; i++) {
			int num = System::random(mobiles->size() - 1);
			String mob = mobiles->get(num);

			if (objectsToSpawn.contains(mob)) {
				int value = objectsToSpawn.get(mob);
				objectsToSpawn.drop(mob);
				objectsToSpawn.put(mob, value + 1);
			} else {
				objectsToSpawn.put(mob, 1);
			}
		}
	}

	for(int i = 0; i < objectsToSpawn.size(); ++i) {

		if (spawnNumber != 4 && spawnedCreatures.size() >= spawnLimit)
			return true;

		String templateToSpawn = objectsToSpawn.elementAt(i).getKey();
		int numberToSpawn = objectsToSpawn.get(templateToSpawn);

		CreatureTemplate* creatureTemplate = CreatureTemplateManager::instance()->getTemplate(templateToSpawn);

		if (creatureTemplate == NULL)
			continue;

		float tamingChance = creatureTemplate->getTame();

		CreatureManager* creatureManager = zone->getCreatureManager();

		for (int j = 0; j < numberToSpawn; j++) {
			if (lair->getZone() == NULL)
				break;

			float x = lair->getPositionX() + (size - System::random(size * 20) / 10.0f);
			float y = lair->getPositionY() + (size - System::random(size * 20) / 10.0f);
			float z = zone->getHeight(x, y);

			ManagedReference<CreatureObject*> creo = NULL;

			if (creatureManager->checkSpawnAsBaby(tamingChance, babiesSpawned, 1000)) {
				creo = creatureManager->spawnCreatureAsBaby(templateToSpawn.hashCode(), x, z, y);
				babiesSpawned++;
			}

			if (creo == NULL)
				creo = creatureManager->spawnCreatureWithAi(templateToSpawn.hashCode(), x, z, y);

			if (creo == NULL)
				continue;

			if (!creo->isAiAgent()) {
				error("spawned non player creature with template " + templateToSpawn);
			} else {
				AiAgent* ai = cast<AiAgent*>( creo.get());

				Locker clocker(ai, lair);

				ai->setDespawnOnNoPlayerInRange(false);
				ai->setHomeLocation(x, z, y);
				ai->setRespawnTimer(0);
				ai->setHomeObject(lair);

				spawnedCreatures.add(creo);

			}
		}
	}

	if (spawnNumber == 4) {
		Reference<LairAggroTask*> task = new LairAggroTask(lair, attacker, _this.getReferenceUnsafeStaticCast(), true);
		task->schedule(1000);
	}

	return objectsToSpawn.size() > 0;
}

<|endoftext|>