<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2014 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// 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.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "nearest_neighbor_classifier.hpp"

#include <cfloat>
#include <string>
#include <vector>
#include <map>
#include <utility>
#include "../framework/mixable_versioned_table.hpp"
#include "../common/unordered_map.hpp"
#include "../storage/column_table.hpp"
#include "jubatus/util/concurrent/lock.h"
#include "nearest_neighbor_classifier_util.hpp"
#include "jubatus/util/lang/bind.h"
#include "jubatus/util/lang/function.h"

using jubatus::util::lang::shared_ptr;
using jubatus::util::concurrent::scoped_lock;

namespace jubatus {
namespace core {
namespace classifier {

class nearest_neighbor_classifier::unlearning_callback {
 public:
  explicit unlearning_callback(nearest_neighbor_classifier* classifier)
      : classifier_(classifier) {
  }

  void operator()(const std::string& id) {
    classifier_->unlearn_id(id);
    classifier_->decrement_label_counter(get_label_from_id(id));
  }

 private:
  nearest_neighbor_classifier* classifier_;
};

nearest_neighbor_classifier::nearest_neighbor_classifier(
    shared_ptr<nearest_neighbor::nearest_neighbor_base> engine,
    size_t k,
    float alpha)
    : nearest_neighbor_engine_(engine), k_(k), alpha_(alpha) {
  if (!(alpha >= 0)) {
    throw JUBATUS_EXCEPTION(common::invalid_parameter(
        "local_sensitivity should >= 0"));
  }
  dynamic_cast<framework::mixable_versioned_table*>
      (nearest_neighbor_engine_->get_mixable())->set_update_callback(
          util::lang::bind(
              &nearest_neighbor_classifier::regenerate_label_counter, this));
}

void nearest_neighbor_classifier::train(
    const common::sfv_t& fv, const std::string& label) {
  std::string id;
  {
    util::concurrent::scoped_lock lk(rand_mutex_);
    id = make_id_from_label(label, rand_);
  }
  if (unlearner_) {
    util::concurrent::scoped_lock unlearner_lk(unlearner_mutex_);
    if (!unlearner_->touch(id)) {
      throw JUBATUS_EXCEPTION(common::exception::runtime_error(
          "cannot add new ID as number of sticky IDs reached "
          "the maximum size of unlearner: " + id));
    }
  }
  nearest_neighbor_engine_->set_row(id, fv);
  set_label(label);

  util::concurrent::scoped_lock lk(label_mutex_);
  labels_[label] += 1;
}

void nearest_neighbor_classifier::set_label_unlearner(
    shared_ptr<unlearner::unlearner_base> label_unlearner) {
  label_unlearner->set_callback(unlearning_callback(this));
  unlearner_ = label_unlearner;
  // Support unlearning in MIX
  dynamic_cast<framework::mixable_versioned_table*>
      (nearest_neighbor_engine_->get_mixable())->set_unlearner(unlearner_);
}

std::string nearest_neighbor_classifier::classify(
    const common::sfv_t& fv) const {
  classify_result result;
  classify_with_scores(fv, result);
  float max_score = -FLT_MAX;
  std::string max_class;
  for (std::vector<classify_result_elem>::const_iterator it = result.begin();
      it != result.end(); ++it) {
    if (it == result.begin() || it->score > max_score) {
      max_score = it->score;
      max_class = it->label;
    }
  }
  return max_class;
}

void nearest_neighbor_classifier::classify_with_scores(
    const common::sfv_t& fv, classify_result& scores) const {
  std::vector<std::pair<std::string, float> > ids;
  nearest_neighbor_engine_->neighbor_row(fv, ids, k_);

  std::map<std::string, float> m;
  {
    util::concurrent::scoped_lock lk(label_mutex_);
    for (labels_t::const_iterator iter = labels_.begin();
         iter != labels_.end(); ++iter) {
      m.insert(std::make_pair(iter->first, 0));
    }
  }
  for (size_t i = 0; i < ids.size(); ++i) {
    std::string label = get_label_from_id(ids[i].first);
    m[label] += std::exp(-alpha_ * ids[i].second);
  }

  scores.clear();
  for (std::map<std::string, float>::const_iterator iter = m.begin();
       iter != m.end(); ++iter) {
    classify_result_elem elem(iter->first, iter->second);
    scores.push_back(elem);
  }
}

bool nearest_neighbor_classifier::delete_label(const std::string& label) {
  {
    util::concurrent::scoped_lock lk(label_mutex_);
    if (labels_.erase(label) == 0) {
      return false;
    }
  }

  shared_ptr<storage::column_table> table =
      nearest_neighbor_engine_->get_table();

  std::vector<std::string> ids_to_be_deleted;
  for (size_t i = 0, n = table->size(); i < n; ++i) {
    std::string id = table->get_key(i);
    std::string l = get_label_from_id(id);
    if (l == label) {
      ids_to_be_deleted.push_back(id);
    }
  }

  for (size_t i = 0, n = ids_to_be_deleted.size(); i < n; ++i) {
    const std::string& id = ids_to_be_deleted[i];
    table->delete_row(id);
    if (unlearner_) {
      unlearner_->remove(id);
    }
  }

  return true;
}

void nearest_neighbor_classifier::clear() {
  nearest_neighbor_engine_->clear();
  {
    util::concurrent::scoped_lock lk(label_mutex_);
    labels_.clear();
  }
  if (unlearner_) {
    unlearner_->clear();
  }
}

std::vector<std::string> nearest_neighbor_classifier::get_labels() const {
  util::concurrent::scoped_lock lk(label_mutex_);
  std::vector<std::string> result;
  for (labels_t::const_iterator iter = labels_.begin();
       iter != labels_.end(); ++iter) {
    result.push_back(iter->first);
  }
  return result;
}

bool nearest_neighbor_classifier::set_label(const std::string& label) {
  util::concurrent::scoped_lock lk(label_mutex_);
  if (labels_.find(label) == labels_.end()) {
    labels_[label] = 0;
    return true;
  } else {
    return false;
  }
}

std::string nearest_neighbor_classifier::name() const {
  return "nearest_neighbor_classifier:" + nearest_neighbor_engine_->type();
}

void nearest_neighbor_classifier::get_status(
    std::map<std::string, std::string>& status) const {
  // unimplemented
}

void nearest_neighbor_classifier::pack(framework::packer& pk) const {
  pk.pack_array(2);
  nearest_neighbor_engine_->pack(pk);

  util::concurrent::scoped_lock lk(label_mutex_);
  pk.pack(labels_);
}

void nearest_neighbor_classifier::unpack(msgpack::object o) {
  if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {
    throw msgpack::type_error();
  }
  nearest_neighbor_engine_->unpack(o.via.array.ptr[0]);
  util::concurrent::scoped_lock lk(label_mutex_);
  o.via.array.ptr[1].convert(&labels_);
}

framework::mixable* nearest_neighbor_classifier::get_mixable() {
  return nearest_neighbor_engine_->get_mixable();
}

void nearest_neighbor_classifier::unlearn_id(const std::string& id) {
  nearest_neighbor_engine_->get_table()->delete_row(id);
}

void nearest_neighbor_classifier::decrement_label_counter(
    const std::string& label) {
  util::concurrent::scoped_lock lk(label_mutex_);
  labels_[label] -= 1;
  if (labels_[label] <= 0) {
    labels_.erase(label);
  }
}

void nearest_neighbor_classifier::regenerate_label_counter() {
  labels_t labels;

  {
    shared_ptr<const storage::column_table> table =
        nearest_neighbor_engine_->get_const_table();
    util::concurrent::scoped_rlock table_lk(table->get_mutex());

    for (size_t i = 0, n = table->size(); i < n; ++i) {
      std::string id = table->get_key(i);
      std::string label = get_label_from_id(id);
      labels[label] += 1;
    }
  }

  util::concurrent::scoped_lock lk(label_mutex_);
  for (labels_t::const_iterator iter = labels_.begin();
       iter != labels_.end(); ++iter) {
    if (labels.find(iter->first) == labels.end()) {
      // labels registered by set_label are exist
      labels[iter->first] = iter->second;
    }
  }
  labels_.swap(labels);
}

}  // namespace classifier
}  // namespace core
}  // namespace jubatus
<commit_msg>Rename variable name<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2014 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// 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.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "nearest_neighbor_classifier.hpp"

#include <cfloat>
#include <string>
#include <vector>
#include <map>
#include <utility>
#include "../framework/mixable_versioned_table.hpp"
#include "../common/unordered_map.hpp"
#include "../storage/column_table.hpp"
#include "jubatus/util/concurrent/lock.h"
#include "nearest_neighbor_classifier_util.hpp"
#include "jubatus/util/lang/bind.h"
#include "jubatus/util/lang/function.h"

using jubatus::util::lang::shared_ptr;
using jubatus::util::concurrent::scoped_lock;

namespace jubatus {
namespace core {
namespace classifier {

class nearest_neighbor_classifier::unlearning_callback {
 public:
  explicit unlearning_callback(nearest_neighbor_classifier* classifier)
      : classifier_(classifier) {
  }

  void operator()(const std::string& id) {
    classifier_->unlearn_id(id);
    classifier_->decrement_label_counter(get_label_from_id(id));
  }

 private:
  nearest_neighbor_classifier* classifier_;
};

nearest_neighbor_classifier::nearest_neighbor_classifier(
    shared_ptr<nearest_neighbor::nearest_neighbor_base> engine,
    size_t k,
    float alpha)
    : nearest_neighbor_engine_(engine), k_(k), alpha_(alpha) {
  if (!(alpha >= 0)) {
    throw JUBATUS_EXCEPTION(common::invalid_parameter(
        "local_sensitivity should >= 0"));
  }
  dynamic_cast<framework::mixable_versioned_table*>
      (nearest_neighbor_engine_->get_mixable())->set_update_callback(
          util::lang::bind(
              &nearest_neighbor_classifier::regenerate_label_counter, this));
}

void nearest_neighbor_classifier::train(
    const common::sfv_t& fv, const std::string& label) {
  std::string id;
  {
    util::concurrent::scoped_lock lk(rand_mutex_);
    id = make_id_from_label(label, rand_);
  }
  if (unlearner_) {
    util::concurrent::scoped_lock unlearner_lk(unlearner_mutex_);
    if (!unlearner_->touch(id)) {
      throw JUBATUS_EXCEPTION(common::exception::runtime_error(
          "cannot add new ID as number of sticky IDs reached "
          "the maximum size of unlearner: " + id));
    }
  }
  nearest_neighbor_engine_->set_row(id, fv);
  set_label(label);

  util::concurrent::scoped_lock lk(label_mutex_);
  labels_[label] += 1;
}

void nearest_neighbor_classifier::set_label_unlearner(
    shared_ptr<unlearner::unlearner_base> label_unlearner) {
  label_unlearner->set_callback(unlearning_callback(this));
  unlearner_ = label_unlearner;
  // Support unlearning in MIX
  dynamic_cast<framework::mixable_versioned_table*>
      (nearest_neighbor_engine_->get_mixable())->set_unlearner(unlearner_);
}

std::string nearest_neighbor_classifier::classify(
    const common::sfv_t& fv) const {
  classify_result result;
  classify_with_scores(fv, result);
  float max_score = -FLT_MAX;
  std::string max_class;
  for (std::vector<classify_result_elem>::const_iterator it = result.begin();
      it != result.end(); ++it) {
    if (it == result.begin() || it->score > max_score) {
      max_score = it->score;
      max_class = it->label;
    }
  }
  return max_class;
}

void nearest_neighbor_classifier::classify_with_scores(
    const common::sfv_t& fv, classify_result& scores) const {
  std::vector<std::pair<std::string, float> > ids;
  nearest_neighbor_engine_->neighbor_row(fv, ids, k_);

  std::map<std::string, float> m;
  {
    util::concurrent::scoped_lock lk(label_mutex_);
    for (labels_t::const_iterator iter = labels_.begin();
         iter != labels_.end(); ++iter) {
      m.insert(std::make_pair(iter->first, 0));
    }
  }
  for (size_t i = 0; i < ids.size(); ++i) {
    std::string label = get_label_from_id(ids[i].first);
    m[label] += std::exp(-alpha_ * ids[i].second);
  }

  scores.clear();
  for (std::map<std::string, float>::const_iterator iter = m.begin();
       iter != m.end(); ++iter) {
    classify_result_elem elem(iter->first, iter->second);
    scores.push_back(elem);
  }
}

bool nearest_neighbor_classifier::delete_label(const std::string& label) {
  {
    util::concurrent::scoped_lock lk(label_mutex_);
    if (labels_.erase(label) == 0) {
      return false;
    }
  }

  shared_ptr<storage::column_table> table =
      nearest_neighbor_engine_->get_table();

  std::vector<std::string> ids_to_be_deleted;
  for (size_t i = 0, n = table->size(); i < n; ++i) {
    std::string id = table->get_key(i);
    std::string l = get_label_from_id(id);
    if (l == label) {
      ids_to_be_deleted.push_back(id);
    }
  }

  for (size_t i = 0, n = ids_to_be_deleted.size(); i < n; ++i) {
    const std::string& id = ids_to_be_deleted[i];
    table->delete_row(id);
    if (unlearner_) {
      unlearner_->remove(id);
    }
  }

  return true;
}

void nearest_neighbor_classifier::clear() {
  nearest_neighbor_engine_->clear();
  {
    util::concurrent::scoped_lock lk(label_mutex_);
    labels_.clear();
  }
  if (unlearner_) {
    unlearner_->clear();
  }
}

std::vector<std::string> nearest_neighbor_classifier::get_labels() const {
  util::concurrent::scoped_lock lk(label_mutex_);
  std::vector<std::string> result;
  for (labels_t::const_iterator iter = labels_.begin();
       iter != labels_.end(); ++iter) {
    result.push_back(iter->first);
  }
  return result;
}

bool nearest_neighbor_classifier::set_label(const std::string& label) {
  util::concurrent::scoped_lock lk(label_mutex_);
  if (labels_.find(label) == labels_.end()) {
    labels_[label] = 0;
    return true;
  } else {
    return false;
  }
}

std::string nearest_neighbor_classifier::name() const {
  return "nearest_neighbor_classifier:" + nearest_neighbor_engine_->type();
}

void nearest_neighbor_classifier::get_status(
    std::map<std::string, std::string>& status) const {
  // unimplemented
}

void nearest_neighbor_classifier::pack(framework::packer& pk) const {
  pk.pack_array(2);
  nearest_neighbor_engine_->pack(pk);

  util::concurrent::scoped_lock lk(label_mutex_);
  pk.pack(labels_);
}

void nearest_neighbor_classifier::unpack(msgpack::object o) {
  if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {
    throw msgpack::type_error();
  }
  nearest_neighbor_engine_->unpack(o.via.array.ptr[0]);
  util::concurrent::scoped_lock lk(label_mutex_);
  o.via.array.ptr[1].convert(&labels_);
}

framework::mixable* nearest_neighbor_classifier::get_mixable() {
  return nearest_neighbor_engine_->get_mixable();
}

void nearest_neighbor_classifier::unlearn_id(const std::string& id) {
  nearest_neighbor_engine_->get_table()->delete_row(id);
}

void nearest_neighbor_classifier::decrement_label_counter(
    const std::string& label) {
  util::concurrent::scoped_lock lk(label_mutex_);
  labels_[label] -= 1;
  if (labels_[label] <= 0) {
    labels_.erase(label);
  }
}

void nearest_neighbor_classifier::regenerate_label_counter() {
  labels_t new_labels;

  {
    shared_ptr<const storage::column_table> table =
        nearest_neighbor_engine_->get_const_table();
    util::concurrent::scoped_rlock table_lk(table->get_mutex());

    for (size_t i = 0, n = table->size(); i < n; ++i) {
      std::string id = table->get_key(i);
      std::string label = get_label_from_id(id);
      new_labels[label] += 1;
    }
  }

  util::concurrent::scoped_lock lk(label_mutex_);
  for (labels_t::const_iterator iter = labels_.begin();
       iter != labels_.end(); ++iter) {
    if (labels.find(iter->first) == labels.end()) {
      // labels registered by set_label are exist
      new_labels[iter->first] = iter->second;
    }
  }
  labels_.swap(new_labels);
}

}  // namespace classifier
}  // namespace core
}  // namespace jubatus
<|endoftext|>


<commit_before>void LoadLibraries(Bool_t useParFiles=kFALSE) {

  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libPhysics.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libSTEERBase.so");
  gSystem->Load("libESD.so");
  gSystem->Load("libAOD.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libCORRFW.so");
  gSystem->Load("libPWG3base.so");
  gSystem->Load("libPWG3vertexingHF.so");

  if(useParFiles) {
    setupPar("STEERBase");
    setupPar("ESD");
    setupPar("AOD");
    setupPar("ANALYSIS");
    setupPar("ANALYSISalice");
    setupPar("CORRFW");
    setupPar("PWG3vertexingHF");
  }

  return;
}
//------------------------------------------------------------------------
Int_t setupPar(const char* pararchivename) {
  ///////////////////
  // Setup PAR File//
  ///////////////////

  if (pararchivename) {
    char processline[1024];
    TString base = gSystem->BaseName(pararchivename);
    TString dir  = gSystem->DirName(pararchivename);
    TString ocwd = gSystem->WorkingDirectory();
    // Move to dir where the par files are and unpack
    gSystem->ChangeDirectory(dir.Data());
    sprintf(processline,".! tar xvzf %s.par",base.Data());
    gROOT->ProcessLine(processline);
    // Move to par folder
    gSystem->ChangeDirectory(base.Data());

    // check for BUILD.sh and execute
    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
      printf("*******************************\n");
      printf("*** Building PAR archive    ***\n");
      printf("*******************************\n");

      if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
        Error("runAnalysis","Cannot Build the PAR Archive! - Abort!");
	gSystem->ChangeDirectory(ocwd.Data());
        return -1;
      }
    }
    // check for SETUP.C and execute
    if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
      printf("*******************************\n");
      printf("*** Setup PAR archive       ***\n");
      printf("*******************************\n");
      // If dir not empty, set the full include path
      if (dir.Length()) {
	sprintf(processline, ".include %s", pararchivename);
	gROOT->ProcessLine(processline);
      }
      gROOT->Macro("PROOF-INF/SETUP.C");
    }
    gSystem->ChangeDirectory(ocwd.Data());
  }
  return 1;
}<commit_msg>Load some PWG4 and PWG3muon libraries needed to read the AOD from the Analysis Train<commit_after>void LoadLibraries(Bool_t useParFiles=kFALSE) {

  gSystem->Load("libTree.so");
  gSystem->Load("libGeom.so");
  gSystem->Load("libPhysics.so");
  gSystem->Load("libVMC.so");
  gSystem->Load("libSTEERBase.so");
  gSystem->Load("libESD.so");
  gSystem->Load("libAOD.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libCORRFW.so");
  gSystem->Load("libPWG3base.so");
  gSystem->Load("libPWG3vertexingHF.so");
  if(!useParFiles) {
    gSystem->Load("libJETAN");
    gSystem->Load("libPWG3base");
    gSystem->Load("libPWG3muon");
    gSystem->Load("libPWG4PartCorrBase");
    gSystem->Load("libPWG4PartCorrDep");
  }

  if(useParFiles) {
    setupPar("STEERBase");
    setupPar("ESD");
    setupPar("AOD");
    setupPar("ANALYSIS");
    setupPar("ANALYSISalice");
    setupPar("CORRFW");
    setupPar("PWG3vertexingHF");
  }

  return;
}
//------------------------------------------------------------------------
Int_t setupPar(const char* pararchivename) {
  ///////////////////
  // Setup PAR File//
  ///////////////////

  if (pararchivename) {
    char processline[1024];
    TString base = gSystem->BaseName(pararchivename);
    TString dir  = gSystem->DirName(pararchivename);
    TString ocwd = gSystem->WorkingDirectory();
    // Move to dir where the par files are and unpack
    gSystem->ChangeDirectory(dir.Data());
    sprintf(processline,".! tar xvzf %s.par",base.Data());
    gROOT->ProcessLine(processline);
    // Move to par folder
    gSystem->ChangeDirectory(base.Data());

    // check for BUILD.sh and execute
    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
      printf("*******************************\n");
      printf("*** Building PAR archive    ***\n");
      printf("*******************************\n");

      if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
        Error("runAnalysis","Cannot Build the PAR Archive! - Abort!");
	gSystem->ChangeDirectory(ocwd.Data());
        return -1;
      }
    }
    // check for SETUP.C and execute
    if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
      printf("*******************************\n");
      printf("*** Setup PAR archive       ***\n");
      printf("*******************************\n");
      // If dir not empty, set the full include path
      if (dir.Length()) {
	sprintf(processline, ".include %s", pararchivename);
	gROOT->ProcessLine(processline);
      }
      gROOT->Macro("PROOF-INF/SETUP.C");
    }
    gSystem->ChangeDirectory(ocwd.Data());
  }
  return 1;
}
<|endoftext|>


<commit_before>//===-- HexagonMCTargetDesc.cpp - Hexagon Target Descriptions -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Hexagon specific target descriptions.
//
//===----------------------------------------------------------------------===//

#include "HexagonTargetStreamer.h"
#include "MCTargetDesc/HexagonInstPrinter.h"
#include "MCTargetDesc/HexagonMCAsmInfo.h"
#include "MCTargetDesc/HexagonMCELFStreamer.h"
#include "MCTargetDesc/HexagonMCInstrInfo.h"
#include "MCTargetDesc/HexagonMCTargetDesc.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCELFStreamer.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetRegistry.h"
#include <cassert>
#include <cstdint>
#include <new>
#include <string>

using namespace llvm;

#define GET_INSTRINFO_MC_DESC
#include "HexagonGenInstrInfo.inc"

#define GET_SUBTARGETINFO_MC_DESC
#include "HexagonGenSubtargetInfo.inc"

#define GET_REGINFO_MC_DESC
#include "HexagonGenRegisterInfo.inc"

cl::opt<bool> llvm::HexagonDisableCompound
  ("mno-compound",
   cl::desc("Disable looking for compound instructions for Hexagon"));

cl::opt<bool> llvm::HexagonDisableDuplex
  ("mno-pairing",
   cl::desc("Disable looking for duplex instructions for Hexagon"));

static cl::opt<bool> HexagonV4ArchVariant("mv4", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V4"));

static cl::opt<bool> HexagonV5ArchVariant("mv5", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V5"));

static cl::opt<bool> HexagonV55ArchVariant("mv55", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V55"));

static cl::opt<bool> HexagonV60ArchVariant("mv60", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V60"));

static StringRef DefaultArch = "hexagonv60";

static StringRef HexagonGetArchVariant() {
  if (HexagonV4ArchVariant)
    return "hexagonv4";
  if (HexagonV5ArchVariant)
    return "hexagonv5";
  if (HexagonV55ArchVariant)
    return "hexagonv55";
  if (HexagonV60ArchVariant)
    return "hexagonv60";
  return "";
}

StringRef Hexagon_MC::selectHexagonCPU(const Triple &TT, StringRef CPU) {
  StringRef ArchV = HexagonGetArchVariant();
  if (!ArchV.empty() && !CPU.empty()) {
    if (ArchV != CPU)
      report_fatal_error("conflicting architectures specified.");
    return CPU;
  }
  if (ArchV.empty()) {
    if (CPU.empty())
      CPU = DefaultArch;
    return CPU;
  }
  return ArchV;
}

MCInstrInfo *llvm::createHexagonMCInstrInfo() {
  MCInstrInfo *X = new MCInstrInfo();
  InitHexagonMCInstrInfo(X);
  return X;
}

static MCRegisterInfo *createHexagonMCRegisterInfo(const Triple &TT) {
  MCRegisterInfo *X = new MCRegisterInfo();
  InitHexagonMCRegisterInfo(X, Hexagon::R31);
  return X;
}

static MCSubtargetInfo *
createHexagonMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS) {
  CPU = Hexagon_MC::selectHexagonCPU(TT, CPU);
  return createHexagonMCSubtargetInfoImpl(TT, CPU, FS);
}

namespace {

class HexagonTargetAsmStreamer : public HexagonTargetStreamer {
public:
  HexagonTargetAsmStreamer(MCStreamer &S,
                           formatted_raw_ostream &, bool,
                           MCInstPrinter &)
      : HexagonTargetStreamer(S) {}

  void prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS,
                      const MCInst &Inst, const MCSubtargetInfo &STI) override {
    assert(HexagonMCInstrInfo::isBundle(Inst));
    assert(HexagonMCInstrInfo::bundleSize(Inst) <= HEXAGON_PACKET_SIZE);
    std::string Buffer;
    {
      raw_string_ostream TempStream(Buffer);
      InstPrinter.printInst(&Inst, TempStream, "", STI);
    }
    StringRef Contents(Buffer);
    auto PacketBundle = Contents.rsplit('\n');
    auto HeadTail = PacketBundle.first.split('\n');
    StringRef Separator = "\n";
    StringRef Indent = "\t\t";
    OS << "\t{\n";
    while (!HeadTail.first.empty()) {
      StringRef InstTxt;
      auto Duplex = HeadTail.first.split('\v');
      if (!Duplex.second.empty()) {
        OS << Indent << Duplex.first << Separator;
        InstTxt = Duplex.second;
      } else if (!HeadTail.first.trim().startswith("immext")) {
        InstTxt = Duplex.first;
      }
      if (!InstTxt.empty())
        OS << Indent << InstTxt << Separator;
      HeadTail = HeadTail.second.split('\n');
    }
    OS << "\t}" << PacketBundle.second;
  }
};

class HexagonTargetELFStreamer : public HexagonTargetStreamer {
public:
  HexagonTargetELFStreamer(MCStreamer &S, MCSubtargetInfo const &STI)
      : HexagonTargetStreamer(S) {
    auto Bits = STI.getFeatureBits();
    unsigned Flags = 0;
    if (Bits[Hexagon::ArchV60])
      Flags = ELF::EF_HEXAGON_MACH_V60;
    else if (Bits[Hexagon::ArchV55])
      Flags = ELF::EF_HEXAGON_MACH_V55;
    else if (Bits[Hexagon::ArchV5])
      Flags = ELF::EF_HEXAGON_MACH_V5;
    else if (Bits[Hexagon::ArchV4])
      Flags = ELF::EF_HEXAGON_MACH_V4;
    getStreamer().getAssembler().setELFHeaderEFlags(Flags);
  }

  MCELFStreamer &getStreamer() {
    return static_cast<MCELFStreamer &>(Streamer);
  }

  void EmitCommonSymbolSorted(MCSymbol *Symbol, uint64_t Size,
                              unsigned ByteAlignment,
                              unsigned AccessSize) override {
    HexagonMCELFStreamer &HexagonELFStreamer =
        static_cast<HexagonMCELFStreamer &>(getStreamer());
    HexagonELFStreamer.HexagonMCEmitCommonSymbol(Symbol, Size, ByteAlignment,
                                                 AccessSize);
  }

  void EmitLocalCommonSymbolSorted(MCSymbol *Symbol, uint64_t Size,
                                   unsigned ByteAlignment,
                                   unsigned AccessSize) override {
    HexagonMCELFStreamer &HexagonELFStreamer =
        static_cast<HexagonMCELFStreamer &>(getStreamer());
    HexagonELFStreamer.HexagonMCEmitLocalCommonSymbol(
        Symbol, Size, ByteAlignment, AccessSize);
  }
};

} // end anonymous namespace

static MCAsmInfo *createHexagonMCAsmInfo(const MCRegisterInfo &MRI,
                                         const Triple &TT) {
  MCAsmInfo *MAI = new HexagonMCAsmInfo(TT);

  // VirtualFP = (R30 + #0).
  MCCFIInstruction Inst =
      MCCFIInstruction::createDefCfa(nullptr, Hexagon::R30, 0);
  MAI->addInitialFrameState(Inst);

  return MAI;
}

static MCInstPrinter *createHexagonMCInstPrinter(const Triple &T,
                                                 unsigned SyntaxVariant,
                                                 const MCAsmInfo &MAI,
                                                 const MCInstrInfo &MII,
                                                 const MCRegisterInfo &MRI) {
  if (SyntaxVariant == 0)
    return (new HexagonInstPrinter(MAI, MII, MRI));
  else
    return nullptr;
}

static MCTargetStreamer *createMCAsmTargetStreamer(MCStreamer &S,
                                                   formatted_raw_ostream &OS,
                                                   MCInstPrinter *InstPrint,
                                                   bool IsVerboseAsm) {
  return new HexagonTargetAsmStreamer(S,  OS, IsVerboseAsm, *InstPrint);
}

static MCStreamer *createMCStreamer(Triple const &T, MCContext &Context,
                                    MCAsmBackend &MAB, raw_pwrite_stream &OS,
                                    MCCodeEmitter *Emitter, bool RelaxAll) {
  return createHexagonELFStreamer(Context, MAB, OS, Emitter);
}

static MCTargetStreamer *
createHexagonObjectTargetStreamer(MCStreamer &S, MCSubtargetInfo const &STI) {
  return new HexagonTargetELFStreamer(S, STI);
}

// Force static initialization.
extern "C" void LLVMInitializeHexagonTargetMC() {
  // Register the MC asm info.
  RegisterMCAsmInfoFn X(getTheHexagonTarget(), createHexagonMCAsmInfo);

  // Register the MC instruction info.
  TargetRegistry::RegisterMCInstrInfo(getTheHexagonTarget(),
                                      createHexagonMCInstrInfo);

  // Register the MC register info.
  TargetRegistry::RegisterMCRegInfo(getTheHexagonTarget(),
                                    createHexagonMCRegisterInfo);

  // Register the MC subtarget info.
  TargetRegistry::RegisterMCSubtargetInfo(getTheHexagonTarget(),
                                          createHexagonMCSubtargetInfo);

  // Register the MC Code Emitter
  TargetRegistry::RegisterMCCodeEmitter(getTheHexagonTarget(),
                                        createHexagonMCCodeEmitter);

  // Register the asm backend
  TargetRegistry::RegisterMCAsmBackend(getTheHexagonTarget(),
                                       createHexagonAsmBackend);

  // Register the obj streamer
  TargetRegistry::RegisterELFStreamer(getTheHexagonTarget(), createMCStreamer);

  // Register the asm streamer
  TargetRegistry::RegisterAsmTargetStreamer(getTheHexagonTarget(),
                                            createMCAsmTargetStreamer);

  // Register the MC Inst Printer
  TargetRegistry::RegisterMCInstPrinter(getTheHexagonTarget(),
                                        createHexagonMCInstPrinter);

  TargetRegistry::RegisterObjectTargetStreamer(
      getTheHexagonTarget(), createHexagonObjectTargetStreamer);
}
<commit_msg>[Hexagon] Other attempt to fix build with enabled asserts broken in 290024 (NFC).<commit_after>//===-- HexagonMCTargetDesc.cpp - Hexagon Target Descriptions -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Hexagon specific target descriptions.
//
//===----------------------------------------------------------------------===//

#include "Hexagon.h"
#include "HexagonTargetStreamer.h"
#include "MCTargetDesc/HexagonInstPrinter.h"
#include "MCTargetDesc/HexagonMCAsmInfo.h"
#include "MCTargetDesc/HexagonMCELFStreamer.h"
#include "MCTargetDesc/HexagonMCInstrInfo.h"
#include "MCTargetDesc/HexagonMCTargetDesc.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCELFStreamer.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetRegistry.h"
#include <cassert>
#include <cstdint>
#include <new>
#include <string>

using namespace llvm;

#define GET_INSTRINFO_MC_DESC
#include "HexagonGenInstrInfo.inc"

#define GET_SUBTARGETINFO_MC_DESC
#include "HexagonGenSubtargetInfo.inc"

#define GET_REGINFO_MC_DESC
#include "HexagonGenRegisterInfo.inc"

cl::opt<bool> llvm::HexagonDisableCompound
  ("mno-compound",
   cl::desc("Disable looking for compound instructions for Hexagon"));

cl::opt<bool> llvm::HexagonDisableDuplex
  ("mno-pairing",
   cl::desc("Disable looking for duplex instructions for Hexagon"));

static cl::opt<bool> HexagonV4ArchVariant("mv4", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V4"));

static cl::opt<bool> HexagonV5ArchVariant("mv5", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V5"));

static cl::opt<bool> HexagonV55ArchVariant("mv55", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V55"));

static cl::opt<bool> HexagonV60ArchVariant("mv60", cl::Hidden, cl::init(false),
  cl::desc("Build for Hexagon V60"));

static StringRef DefaultArch = "hexagonv60";

static StringRef HexagonGetArchVariant() {
  if (HexagonV4ArchVariant)
    return "hexagonv4";
  if (HexagonV5ArchVariant)
    return "hexagonv5";
  if (HexagonV55ArchVariant)
    return "hexagonv55";
  if (HexagonV60ArchVariant)
    return "hexagonv60";
  return "";
}

StringRef Hexagon_MC::selectHexagonCPU(const Triple &TT, StringRef CPU) {
  StringRef ArchV = HexagonGetArchVariant();
  if (!ArchV.empty() && !CPU.empty()) {
    if (ArchV != CPU)
      report_fatal_error("conflicting architectures specified.");
    return CPU;
  }
  if (ArchV.empty()) {
    if (CPU.empty())
      CPU = DefaultArch;
    return CPU;
  }
  return ArchV;
}

MCInstrInfo *llvm::createHexagonMCInstrInfo() {
  MCInstrInfo *X = new MCInstrInfo();
  InitHexagonMCInstrInfo(X);
  return X;
}

static MCRegisterInfo *createHexagonMCRegisterInfo(const Triple &TT) {
  MCRegisterInfo *X = new MCRegisterInfo();
  InitHexagonMCRegisterInfo(X, Hexagon::R31);
  return X;
}

static MCSubtargetInfo *
createHexagonMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS) {
  CPU = Hexagon_MC::selectHexagonCPU(TT, CPU);
  return createHexagonMCSubtargetInfoImpl(TT, CPU, FS);
}

namespace {

class HexagonTargetAsmStreamer : public HexagonTargetStreamer {
public:
  HexagonTargetAsmStreamer(MCStreamer &S,
                           formatted_raw_ostream &, bool,
                           MCInstPrinter &)
      : HexagonTargetStreamer(S) {}

  void prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS,
                      const MCInst &Inst, const MCSubtargetInfo &STI) override {
    assert(HexagonMCInstrInfo::isBundle(Inst));
    assert(HexagonMCInstrInfo::bundleSize(Inst) <= HEXAGON_PACKET_SIZE);
    std::string Buffer;
    {
      raw_string_ostream TempStream(Buffer);
      InstPrinter.printInst(&Inst, TempStream, "", STI);
    }
    StringRef Contents(Buffer);
    auto PacketBundle = Contents.rsplit('\n');
    auto HeadTail = PacketBundle.first.split('\n');
    StringRef Separator = "\n";
    StringRef Indent = "\t\t";
    OS << "\t{\n";
    while (!HeadTail.first.empty()) {
      StringRef InstTxt;
      auto Duplex = HeadTail.first.split('\v');
      if (!Duplex.second.empty()) {
        OS << Indent << Duplex.first << Separator;
        InstTxt = Duplex.second;
      } else if (!HeadTail.first.trim().startswith("immext")) {
        InstTxt = Duplex.first;
      }
      if (!InstTxt.empty())
        OS << Indent << InstTxt << Separator;
      HeadTail = HeadTail.second.split('\n');
    }
    OS << "\t}" << PacketBundle.second;
  }
};

class HexagonTargetELFStreamer : public HexagonTargetStreamer {
public:
  HexagonTargetELFStreamer(MCStreamer &S, MCSubtargetInfo const &STI)
      : HexagonTargetStreamer(S) {
    auto Bits = STI.getFeatureBits();
    unsigned Flags = 0;
    if (Bits[Hexagon::ArchV60])
      Flags = ELF::EF_HEXAGON_MACH_V60;
    else if (Bits[Hexagon::ArchV55])
      Flags = ELF::EF_HEXAGON_MACH_V55;
    else if (Bits[Hexagon::ArchV5])
      Flags = ELF::EF_HEXAGON_MACH_V5;
    else if (Bits[Hexagon::ArchV4])
      Flags = ELF::EF_HEXAGON_MACH_V4;
    getStreamer().getAssembler().setELFHeaderEFlags(Flags);
  }

  MCELFStreamer &getStreamer() {
    return static_cast<MCELFStreamer &>(Streamer);
  }

  void EmitCommonSymbolSorted(MCSymbol *Symbol, uint64_t Size,
                              unsigned ByteAlignment,
                              unsigned AccessSize) override {
    HexagonMCELFStreamer &HexagonELFStreamer =
        static_cast<HexagonMCELFStreamer &>(getStreamer());
    HexagonELFStreamer.HexagonMCEmitCommonSymbol(Symbol, Size, ByteAlignment,
                                                 AccessSize);
  }

  void EmitLocalCommonSymbolSorted(MCSymbol *Symbol, uint64_t Size,
                                   unsigned ByteAlignment,
                                   unsigned AccessSize) override {
    HexagonMCELFStreamer &HexagonELFStreamer =
        static_cast<HexagonMCELFStreamer &>(getStreamer());
    HexagonELFStreamer.HexagonMCEmitLocalCommonSymbol(
        Symbol, Size, ByteAlignment, AccessSize);
  }
};

} // end anonymous namespace

static MCAsmInfo *createHexagonMCAsmInfo(const MCRegisterInfo &MRI,
                                         const Triple &TT) {
  MCAsmInfo *MAI = new HexagonMCAsmInfo(TT);

  // VirtualFP = (R30 + #0).
  MCCFIInstruction Inst =
      MCCFIInstruction::createDefCfa(nullptr, Hexagon::R30, 0);
  MAI->addInitialFrameState(Inst);

  return MAI;
}

static MCInstPrinter *createHexagonMCInstPrinter(const Triple &T,
                                                 unsigned SyntaxVariant,
                                                 const MCAsmInfo &MAI,
                                                 const MCInstrInfo &MII,
                                                 const MCRegisterInfo &MRI) {
  if (SyntaxVariant == 0)
    return (new HexagonInstPrinter(MAI, MII, MRI));
  else
    return nullptr;
}

static MCTargetStreamer *createMCAsmTargetStreamer(MCStreamer &S,
                                                   formatted_raw_ostream &OS,
                                                   MCInstPrinter *InstPrint,
                                                   bool IsVerboseAsm) {
  return new HexagonTargetAsmStreamer(S,  OS, IsVerboseAsm, *InstPrint);
}

static MCStreamer *createMCStreamer(Triple const &T, MCContext &Context,
                                    MCAsmBackend &MAB, raw_pwrite_stream &OS,
                                    MCCodeEmitter *Emitter, bool RelaxAll) {
  return createHexagonELFStreamer(Context, MAB, OS, Emitter);
}

static MCTargetStreamer *
createHexagonObjectTargetStreamer(MCStreamer &S, MCSubtargetInfo const &STI) {
  return new HexagonTargetELFStreamer(S, STI);
}

// Force static initialization.
extern "C" void LLVMInitializeHexagonTargetMC() {
  // Register the MC asm info.
  RegisterMCAsmInfoFn X(getTheHexagonTarget(), createHexagonMCAsmInfo);

  // Register the MC instruction info.
  TargetRegistry::RegisterMCInstrInfo(getTheHexagonTarget(),
                                      createHexagonMCInstrInfo);

  // Register the MC register info.
  TargetRegistry::RegisterMCRegInfo(getTheHexagonTarget(),
                                    createHexagonMCRegisterInfo);

  // Register the MC subtarget info.
  TargetRegistry::RegisterMCSubtargetInfo(getTheHexagonTarget(),
                                          createHexagonMCSubtargetInfo);

  // Register the MC Code Emitter
  TargetRegistry::RegisterMCCodeEmitter(getTheHexagonTarget(),
                                        createHexagonMCCodeEmitter);

  // Register the asm backend
  TargetRegistry::RegisterMCAsmBackend(getTheHexagonTarget(),
                                       createHexagonAsmBackend);

  // Register the obj streamer
  TargetRegistry::RegisterELFStreamer(getTheHexagonTarget(), createMCStreamer);

  // Register the asm streamer
  TargetRegistry::RegisterAsmTargetStreamer(getTheHexagonTarget(),
                                            createMCAsmTargetStreamer);

  // Register the MC Inst Printer
  TargetRegistry::RegisterMCInstPrinter(getTheHexagonTarget(),
                                        createHexagonMCInstPrinter);

  TargetRegistry::RegisterObjectTargetStreamer(
      getTheHexagonTarget(), createHexagonObjectTargetStreamer);
}
<|endoftext|>


<commit_before>#include <hypno_eye.h>

HypnoEye::HypnoEye(uint8_t pin, uint8_t brightness) {
	strip = Adafruit_NeoPixel(19, pin, NEO_GRB + NEO_KHZ800);
	rotation = 0;
	for(uint8_t i = 0; i < OUTER_LEDS; ++i)
	{
		outerLeds[i] = strip.Color(0,0,0);
	}
	for(size_t i = 0; i < INNER_LEDS; ++i)
	{
		innerLeds[i] = strip.Color(0,0,0);
	}
	centerLed = HypnoEye::strip.Color(0,0,0);
	strip.begin();
	strip.setBrightness(brightness);
}

HypnoEye::~HypnoEye() {

}

void HypnoEye::setOuterLeds(uint32_t *leds) {
	for(size_t i = 0; i < OUTER_LEDS; ++i)
	{
		outerLeds[i] = leds[i];
	}
}

void HypnoEye::setInnerLeds(uint32_t *leds) {
	for(size_t i = 0; i < INNER_LEDS; ++i)
	{
		innerLeds[i] = leds[i];
	}
}

void HypnoEye::setCenterLed(uint32_t led) {
	centerLed = led;
}

void HypnoEye::show() {
	for(size_t i = 0; i < OUTER_LEDS; ++i)
	{
		strip.setPixelColor(i, outerLeds[(i + 11 + rotation) % OUTER_LEDS]);
	}
	for(size_t i = 0; i < INNER_LEDS; ++i)
	{
		strip.setPixelColor((i+OUTER_LEDS+1), innerLeds[(i + 1 + (rotation/2)) % INNER_LEDS]);
	}
	strip.setPixelColor(OUTER_LEDS, centerLed);
	strip.show();
}

void HypnoEye::rotateCW() {
	rotation = (rotation + 1) % OUTER_LEDS;
}

void HypnoEye::rotateCW(uint8_t steps) {
	rotation = (rotation + steps) % OUTER_LEDS;
}

void HypnoEye::rotateCCW() {
	if (rotation == 0) {
		rotation = OUTER_LEDS - 1;
	} else {
		rotation -= 1;
	}
}

void HypnoEye::rotateCCW(uint8_t steps) {
	if (rotation < steps) {
		steps -= rotation;
		rotation = OUTER_LEDS - (steps % OUTER_LEDS)
	} else {
		rotation -= steps;
	}
}

void HypnoEye::clear() {
	strip.clear();
}

void HypnoEye::setAll(uint32_t color) {
	for(size_t i = 0; i < OUTER_LEDS + INNER_LEDS + 1; ++i)
	{
		strip.setPixelColor(i, color);
	}
}
<commit_msg>Add missing semicolon<commit_after>#include <hypno_eye.h>

HypnoEye::HypnoEye(uint8_t pin, uint8_t brightness) {
	strip = Adafruit_NeoPixel(19, pin, NEO_GRB + NEO_KHZ800);
	rotation = 0;
	for(uint8_t i = 0; i < OUTER_LEDS; ++i)
	{
		outerLeds[i] = strip.Color(0,0,0);
	}
	for(size_t i = 0; i < INNER_LEDS; ++i)
	{
		innerLeds[i] = strip.Color(0,0,0);
	}
	centerLed = HypnoEye::strip.Color(0,0,0);
	strip.begin();
	strip.setBrightness(brightness);
}

HypnoEye::~HypnoEye() {

}

void HypnoEye::setOuterLeds(uint32_t *leds) {
	for(size_t i = 0; i < OUTER_LEDS; ++i)
	{
		outerLeds[i] = leds[i];
	}
}

void HypnoEye::setInnerLeds(uint32_t *leds) {
	for(size_t i = 0; i < INNER_LEDS; ++i)
	{
		innerLeds[i] = leds[i];
	}
}

void HypnoEye::setCenterLed(uint32_t led) {
	centerLed = led;
}

void HypnoEye::show() {
	for(size_t i = 0; i < OUTER_LEDS; ++i)
	{
		strip.setPixelColor(i, outerLeds[(i + 11 + rotation) % OUTER_LEDS]);
	}
	for(size_t i = 0; i < INNER_LEDS; ++i)
	{
		strip.setPixelColor((i+OUTER_LEDS+1), innerLeds[(i + 1 + (rotation/2)) % INNER_LEDS]);
	}
	strip.setPixelColor(OUTER_LEDS, centerLed);
	strip.show();
}

void HypnoEye::rotateCW() {
	rotation = (rotation + 1) % OUTER_LEDS;
}

void HypnoEye::rotateCW(uint8_t steps) {
	rotation = (rotation + steps) % OUTER_LEDS;
}

void HypnoEye::rotateCCW() {
	if (rotation == 0) {
		rotation = OUTER_LEDS - 1;
	} else {
		rotation -= 1;
	}
}

void HypnoEye::rotateCCW(uint8_t steps) {
	if (rotation < steps) {
		steps -= rotation;
		rotation = OUTER_LEDS - (steps % OUTER_LEDS);
	} else {
		rotation -= steps;
	}
}

void HypnoEye::clear() {
	strip.clear();
}

void HypnoEye::setAll(uint32_t color) {
	for(size_t i = 0; i < OUTER_LEDS + INNER_LEDS + 1; ++i)
	{
		strip.setPixelColor(i, color);
	}
}
<|endoftext|>


<commit_before>/*
 * pv.cpp
 *
 */

#include <iostream>
#include <sstream>
#include <mpi.h>
#include <columns/buildandrun.hpp>

#undef MAIN_USES_CUSTOMGROUPS

int customexit(HyPerCol * hc, int argc, char * argv[]);

int main(int argc, char * argv[]) {
   const char * paramfile1 = "input/RandStateSystemTest1.params";
   const char * paramfile2 = "input/RandStateSystemTest2.params";

   int rank=0;
#ifdef PV_USE_MPI
   MPI_Init(&argc, &argv);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif // PV_USE_MPI

   if (pv_getopt(argc, argv, "-p", NULL)==0) {
      if (rank==0) {
         fprintf(stderr, "%s does not take -p as an option.  Instead the necessary params files are hard-coded.\n", argv[0]);
      }
#ifdef PV_USE_MPI
      MPI_Barrier(MPI_COMM_WORLD);
#endif // PV_USE_MPI
      exit(EXIT_FAILURE);
   }

   int cl_argc = argc + 2;
   char ** cl_argv = (char **) calloc(sizeof(cl_argc+1),sizeof(char *));
   assert(cl_argv);
   for (int k=0; k<argc; k++) {
      cl_argv[k] = strdup(argv[k]);
      assert(cl_argv[k]);
   }
   int paramfile_argnum = argc+1;
   cl_argv[paramfile_argnum-1] = strdup("-p");
   cl_argv[paramfile_argnum] = strdup(paramfile1);
   cl_argv[paramfile_argnum+1] = NULL;

   int status1 = buildandrun(cl_argc, cl_argv, NULL, NULL, NULL);
   if (status1 != PV_SUCCESS) {
      fprintf(stderr, "%s failed on param file %s with return code %d.\n", cl_argv[0], cl_argv[2], status1);
      return EXIT_FAILURE;
   }

   free(cl_argv[paramfile_argnum]);
   cl_argv[paramfile_argnum] = strdup(paramfile2);
   int status2 = buildandrun(cl_argc, cl_argv, NULL, &customexit, NULL);
   if (status2 != PV_SUCCESS) {
      fprintf(stderr, "%s failed on param file %s.\n", cl_argv[0], cl_argv[paramfile_argnum]);
   }
   int status = status1==PV_SUCCESS && status2==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;

#ifdef PV_USE_MPI
   MPI_Finalize();
   if (status == EXIT_SUCCESS) {
      printf("Test complete.  %s passed on process rank %d.\n", cl_argv[0], rank);
   }
   else {
      fprintf(stderr, "Test complete.  %s FAILED on process rank %d.\n", cl_argv[0], rank);
   }
#else
   if (status == EXIT_SUCCESS) {
      printf("Test complete.  %s passed.\n", cl_argv[0]);
   }
   else {
      fprintf(stderr, "Test complete.  %s FAILED.\n", cl_argv[0]);
   }
#endif // PV_USE_MPI

   for (int k=0; k<argc; k++) {
      free(cl_argv[k]);
   }
   free(cl_argv[paramfile_argnum-1]);
   free(cl_argv[paramfile_argnum]);
   free(cl_argv);

   return status;
}

int customexit(HyPerCol * hc, int argc, char * argv[]) {
   int status = PV_SUCCESS;
   if (hc->columnId()==0) {
      std::string cmd("diff -r -q -x timers.txt -x pv.params checkpoints*/Checkpoint");
      std::stringstream stepnumber;
      stepnumber << hc->getFinalStep();
      cmd += stepnumber.str();
      const char * cmdstr = cmd.c_str();
      status = system(cmdstr);
      if (status != 0) {
         fprintf(stderr, "%s failed: system command \"%s\" returned %d\n", argv[0], cmdstr, status);
      }
   }
   return status;
}
<commit_msg>Fixed a bug in RandStateSystemTest with main, allocating wrong size for cl_argv<commit_after>/*
 * pv.cpp
 *
 */

#include <iostream>
#include <sstream>
#include <mpi.h>
#include <columns/buildandrun.hpp>

#undef MAIN_USES_CUSTOMGROUPS

int customexit(HyPerCol * hc, int argc, char * argv[]);

int main(int argc, char * argv[]) {
   const char * paramfile1 = "input/RandStateSystemTest1.params";
   const char * paramfile2 = "input/RandStateSystemTest2.params";

   int rank=0;
#ifdef PV_USE_MPI
   MPI_Init(&argc, &argv);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif // PV_USE_MPI

   if (pv_getopt(argc, argv, "-p", NULL)==0) {
      if (rank==0) {
         fprintf(stderr, "%s does not take -p as an option.  Instead the necessary params files are hard-coded.\n", argv[0]);
      }
#ifdef PV_USE_MPI
      MPI_Barrier(MPI_COMM_WORLD);
#endif // PV_USE_MPI
      exit(EXIT_FAILURE);
   }

   int cl_argc = argc + 2;
   char ** cl_argv = (char **) calloc(cl_argc+1,sizeof(char *));
   assert(cl_argv);
   for (int k=0; k<argc; k++) {
      cl_argv[k] = strdup(argv[k]);
      assert(cl_argv[k]);
   }
   int paramfile_argnum = argc+1;
   cl_argv[paramfile_argnum-1] = strdup("-p");
   cl_argv[paramfile_argnum] = strdup(paramfile1);
   cl_argv[paramfile_argnum+1] = NULL;

   int status1 = buildandrun(cl_argc, cl_argv, NULL, NULL, NULL);
   if (status1 != PV_SUCCESS) {
      fprintf(stderr, "%s failed on param file %s with return code %d.\n", cl_argv[0], cl_argv[2], status1);
      return EXIT_FAILURE;
   }

   free(cl_argv[paramfile_argnum]);
   cl_argv[paramfile_argnum] = strdup(paramfile2);
   int status2 = buildandrun(cl_argc, cl_argv, NULL, &customexit, NULL);
   if (status2 != PV_SUCCESS) {
      fprintf(stderr, "%s failed on param file %s.\n", cl_argv[0], cl_argv[paramfile_argnum]);
   }
   int status = status1==PV_SUCCESS && status2==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;

#ifdef PV_USE_MPI
   MPI_Finalize();
   if (status == EXIT_SUCCESS) {
      printf("Test complete.  %s passed on process rank %d.\n", cl_argv[0], rank);
   }
   else {
      fprintf(stderr, "Test complete.  %s FAILED on process rank %d.\n", cl_argv[0], rank);
   }
#else
   if (status == EXIT_SUCCESS) {
      printf("Test complete.  %s passed.\n", cl_argv[0]);
   }
   else {
      fprintf(stderr, "Test complete.  %s FAILED.\n", cl_argv[0]);
   }
#endif // PV_USE_MPI

   for (int k=0; k<argc; k++) {
      free(cl_argv[k]);
   }
   free(cl_argv[paramfile_argnum-1]);
   free(cl_argv[paramfile_argnum]);
   free(cl_argv);

   return status;
}

int customexit(HyPerCol * hc, int argc, char * argv[]) {
   int status = PV_SUCCESS;
   if (hc->columnId()==0) {
      std::string cmd("diff -r -q -x timers.txt -x pv.params checkpoints*/Checkpoint");
      std::stringstream stepnumber;
      stepnumber << hc->getFinalStep();
      cmd += stepnumber.str();
      const char * cmdstr = cmd.c_str();
      status = system(cmdstr);
      if (status != 0) {
         fprintf(stderr, "%s failed: system command \"%s\" returned %d\n", argv[0], cmdstr, status);
      }
   }
   return status;
}
<|endoftext|>


<commit_before>/*
** Author(s):
**  - Pierre Roullon <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <qimessaging/c/api_c.h>
#include <qimessaging/c/qi_c.h>
#include <gtest/gtest.h>

TEST(TestMessage, SimpleOperation)
{
  qi_message_t*  m = qi_message_create();

  // Yeah, laugh, sounds easy...Beware.
  qi_message_destroy(m);
}

TEST(TestMessage, SimpleWrite)
{
  qi_message_t* m = qi_message_create();
  int magic = 0x42DEAD42;

  // SIGNED TYPES
  qi_message_write_bool(m, true);
  qi_message_write_int8(m, 'a');
  qi_message_write_int8(m, -64);
  qi_message_write_int16(m, 19);
  qi_message_write_int16(m, -19);
  qi_message_write_int32(m, 1123132123);
  qi_message_write_int32(m, -1123132123);
  qi_message_write_int64(m, 4294967297);
  qi_message_write_int64(m, -4294967297);

  // UNSIGNED TYPES
  qi_message_write_uint8(m, 'a');
  qi_message_write_uint16(m, 19);
  qi_message_write_uint32(m, 1123132123);
  qi_message_write_uint64(m, 4294967297);

  // SPECIAL ONES
  qi_message_write_float(m, 3.14957f);
  qi_message_write_double(m, 2.42);
  qi_message_write_string(m, "Easter Egg\t");
  qi_message_write_raw(m, (char *) &magic, 4);

  qi_message_destroy(m);
}

TEST(TestMessage, SimpleRead)
{
  qi_message_t* m = qi_message_create();
  int magic = 0x42DEAD42;
  unsigned int size = 0;
  char *data = (char *) malloc(4);
  memcpy(data, &magic, 4);
  magic = 0;
  ASSERT_TRUE(data != 0);

  // SIGNED TYPES
  qi_message_write_bool(m, true);
  qi_message_write_int8(m, 97);
  qi_message_write_int8(m, -64);
  qi_message_write_int16(m, 19);
  qi_message_write_int16(m, -19);
  qi_message_write_int32(m, 1123132123);
  qi_message_write_int32(m, -1123132123);
  qi_message_write_int64(m, 4294967297);
  qi_message_write_int64(m, -4294967297);
  // UNSIGNED TYPES
  qi_message_write_uint8(m, 'a');
  qi_message_write_uint16(m, 19);
  qi_message_write_uint32(m, 1123132123);
  qi_message_write_uint64(m, 4294967297);
  // SPECIAL ONES
  qi_message_write_float(m, 3.14957f);
  qi_message_write_double(m, 2.42);
  qi_message_write_string(m, "Easter Egg\t");
  qi_message_write_raw(m, data, 4);

  ASSERT_TRUE(qi_message_read_bool(m));
  ASSERT_EQ(97, qi_message_read_int8(m));
  ASSERT_EQ(-64, qi_message_read_int8(m));
  ASSERT_EQ(19, qi_message_read_int16(m));
  ASSERT_EQ(-19, qi_message_read_int16(m));
  ASSERT_EQ(1123132123, qi_message_read_int32(m));
  ASSERT_EQ(-1123132123, qi_message_read_int32(m));
  ASSERT_TRUE(qi_message_read_int64(m) == 4294967297);
  ASSERT_TRUE(qi_message_read_int64(m) == -4294967297);
  ASSERT_TRUE(qi_message_read_int8(m) == 'a');
  ASSERT_TRUE(qi_message_read_uint16(m) == 19);
  ASSERT_TRUE(qi_message_read_uint32(m) == 1123132123);
  ASSERT_TRUE(qi_message_read_uint64(m) == 4294967297);
  ASSERT_EQ(3.14957f, qi_message_read_float(m));
  ASSERT_EQ(2.42, qi_message_read_double(m));
  ASSERT_EQ(0, strcmp(qi_message_read_string(m), "Easter Egg\t"));
  data = qi_message_read_raw(m, &size);
  memcpy(&magic, data, 4);
  ASSERT_EQ(0x42DEAD42, magic);
  ASSERT_EQ(4, size);

  qi_message_destroy(m);
}

TEST(TestMessage, TestList)
{
  ASSERT_TRUE(false);
}

TEST(TestMessage, TestTuple)
{
  ASSERT_TRUE(false);
}

TEST(TestMessage, TestMap)
{
  ASSERT_TRUE(false);
}
<commit_msg>[C bindings] Test auto for map and list serialisation added<commit_after>/*
** Author(s):
**  - Pierre Roullon <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <qimessaging/c/api_c.h>
#include <qimessaging/c/qi_c.h>
#include <qimessaging/datastream.hpp>
#include <c/src/message_c_p.h>
#include <gtest/gtest.h>

qi::IDataStream &get_is(qi_message_data_t *m)
{
  if (!m->is)
    m->is = new qi::IDataStream(*m->buff);
  return *(m->is);
}

qi::ODataStream &get_os(qi_message_data_t *m)
{
  if (!m->os)
    m->os = new qi::ODataStream(*m->buff);
  return *(m->os);
}

TEST(TestMessage, SimpleOperation)
{
  qi_message_t*  m = qi_message_create();

  // Yeah, laugh, sounds easy...Beware.
  qi_message_destroy(m);
}

TEST(TestMessage, SimpleWrite)
{
  qi_message_t* m = qi_message_create();
  int magic = 0x42DEAD42;

  // SIGNED TYPES
  qi_message_write_bool(m, true);
  qi_message_write_int8(m, 'a');
  qi_message_write_int8(m, -64);
  qi_message_write_int16(m, 19);
  qi_message_write_int16(m, -19);
  qi_message_write_int32(m, 1123132123);
  qi_message_write_int32(m, -1123132123);
  qi_message_write_int64(m, 4294967297);
  qi_message_write_int64(m, -4294967297);

  // UNSIGNED TYPES
  qi_message_write_uint8(m, 'a');
  qi_message_write_uint16(m, 19);
  qi_message_write_uint32(m, 1123132123);
  qi_message_write_uint64(m, 4294967297);

  // SPECIAL ONES
  qi_message_write_float(m, 3.14957f);
  qi_message_write_double(m, 2.42);
  qi_message_write_string(m, "Easter Egg\t");
  qi_message_write_raw(m, (char *) &magic, 4);

  qi_message_destroy(m);
}

TEST(TestMessage, SimpleRead)
{
  qi_message_t* m = qi_message_create();
  int magic = 0x42DEAD42;
  unsigned int size = 0;
  char *data = (char *) malloc(4);
  memcpy(data, &magic, 4);
  magic = 0;
  ASSERT_TRUE(data != 0);

  // SIGNED TYPES
  qi_message_write_bool(m, true);
  qi_message_write_int8(m, 97);
  qi_message_write_int8(m, -64);
  qi_message_write_int16(m, 19);
  qi_message_write_int16(m, -19);
  qi_message_write_int32(m, 1123132123);
  qi_message_write_int32(m, -1123132123);
  qi_message_write_int64(m, 4294967297);
  qi_message_write_int64(m, -4294967297);
  // UNSIGNED TYPES
  qi_message_write_uint8(m, 'a');
  qi_message_write_uint16(m, 19);
  qi_message_write_uint32(m, 1123132123);
  qi_message_write_uint64(m, 4294967297);
  // SPECIAL ONES
  qi_message_write_float(m, 3.14957f);
  qi_message_write_double(m, 2.42);
  qi_message_write_string(m, "Easter Egg\t");
  qi_message_write_raw(m, data, 4);

  ASSERT_TRUE(qi_message_read_bool(m));
  ASSERT_EQ(97, qi_message_read_int8(m));
  ASSERT_EQ(-64, qi_message_read_int8(m));
  ASSERT_EQ(19, qi_message_read_int16(m));
  ASSERT_EQ(-19, qi_message_read_int16(m));
  ASSERT_EQ(1123132123, qi_message_read_int32(m));
  ASSERT_EQ(-1123132123, qi_message_read_int32(m));
  ASSERT_TRUE(qi_message_read_int64(m) == 4294967297);
  ASSERT_TRUE(qi_message_read_int64(m) == -4294967297);
  ASSERT_TRUE(qi_message_read_int8(m) == 'a');
  ASSERT_TRUE(qi_message_read_uint16(m) == 19);
  ASSERT_TRUE(qi_message_read_uint32(m) == 1123132123);
  ASSERT_TRUE(qi_message_read_uint64(m) == 4294967297);
  ASSERT_EQ(3.14957f, qi_message_read_float(m));
  ASSERT_EQ(2.42, qi_message_read_double(m));
  ASSERT_EQ(0, strcmp(qi_message_read_string(m), "Easter Egg\t"));
  data = qi_message_read_raw(m, &size);
  memcpy(&magic, data, 4);
  ASSERT_EQ(0x42DEAD42, magic);
  ASSERT_EQ((unsigned int) 4, size);

  qi_message_destroy(m);
}

TEST(TestMessage, TestList)
{
  std::list<int> value;
  std::list<int>::iterator it, it2;

  qi_message_t* m= qi_message_create();

  value.push_back(1);
  value.push_back(2);
  value.push_back(3);
  value.push_back(4);
  value.push_back(5);

  get_os((qi_message_data_t*) m) << value;
  // Our buffer travel around...

  // Toh ! a C client :
  // Get list back
  std::list<int> mirror;
  unsigned int i = 0;
  unsigned int size = qi_message_read_list_size(m);
  ASSERT_EQ(value.size(), size);

  while (i < size)
  {
    mirror.push_back(qi_message_read_int32(m));
    i++;
  }

  // Compare
  ASSERT_EQ(value.size(), mirror.size());
  it2 = mirror.begin();
  for (it = value.begin(); it != value.end(); ++it)
  {
    ASSERT_EQ(*it, *it2);
    ASSERT_TRUE(it2 != mirror.end());
    ++it2;
  }

  qi_message_destroy(m);
}

TEST(TestMessage, TestMap)
{
  std::map<std::string, int> value;
  std::map<std::string, int>::iterator it, it2;

  qi_message_t* m= qi_message_create();

  value["Foo"] = 0;
  value["Bar"] = 1;
  value["Cham"] = 2;
  value["Pion"] = 3;

  get_os((qi_message_data_t *) m) << value;

  // Our buffer travel around...

  // Toh ! a C client :
  // Get list back
  std::map<std::string, int> mirror;
  unsigned int i = 0;
  unsigned int size = qi_message_read_list_size(m);
  ASSERT_EQ(value.size(), size);

  while (i < size)
  {
    mirror[qi_message_read_string(m)] = qi_message_read_int32(m);
    i++;
  }

  // Compare
  ASSERT_EQ(value.size(), mirror.size());
  it2 = mirror.begin();
  for (it = value.begin(); it != value.end(); ++it)
  {
    ASSERT_EQ(*it, *it2);
    ASSERT_TRUE(it2 != mirror.end());
    ++it2;
  }

  qi_message_destroy(m);
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "editorsettingspropertiespage.h"
#include "editorconfiguration.h"
#include "project.h"

#include <QtCore/QTextCodec>

#include <QDebug>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

QString EditorSettingsPanelFactory::id() const
{
    return QLatin1String(EDITORSETTINGS_PANEL_ID);
}

QString EditorSettingsPanelFactory::displayName() const
{
    return QCoreApplication::translate("EditorSettingsPanelFactory", "Editor Settings");
}

bool EditorSettingsPanelFactory::supports(Project *project)
{
    Q_UNUSED(project);
    return true;
}

IPropertiesPanel *EditorSettingsPanelFactory::createPanel(Project *project)
{
    return new EditorSettingsPanel(project);
}

EditorSettingsPanel::EditorSettingsPanel(Project *project) :
    m_widget(new EditorSettingsWidget(project)),
    m_icon(":/projectexplorer/images/EditorSettings.png")
{
}

EditorSettingsPanel::~EditorSettingsPanel()
{
    delete m_widget;
}

QString EditorSettingsPanel::displayName() const
{
    return QCoreApplication::translate("EditorSettingsPanel", "Editor Settings");
}

QWidget *EditorSettingsPanel::widget() const
{
    return m_widget;
}

QIcon EditorSettingsPanel::icon() const
{
    return m_icon;
}

EditorSettingsWidget::EditorSettingsWidget(Project *project)
    : QWidget(),
      m_project(project)
{
    m_ui.setupUi(this);
    QTextCodec *defaultTextCodec = 0;
    m_codecs += defaultTextCodec;
    m_ui.encodingComboBox->addItem(tr("Default"));

    defaultTextCodec = m_project->editorConfiguration()->defaultTextCodec();

    qDebug() << "create editor settings widget for project with encoding" << defaultTextCodec;

    QList<int> mibs = QTextCodec::availableMibs();
    qSort(mibs);
    QList<int> sortedMibs;
    foreach (int mib, mibs)
        if (mib >= 0)
            sortedMibs += mib;
    foreach (int mib, mibs)
        if (mib < 0)
            sortedMibs += mib;
    int i = 1; // 0 is the default
    foreach (int mib, sortedMibs) {
        QTextCodec *codec = QTextCodec::codecForMib(mib);
        m_codecs += codec;
        QString name = codec->name();
        foreach (const QByteArray &alias, codec->aliases()) {
            name += QLatin1String(" / ");
            name += QString::fromLatin1(alias);
        }
        m_ui.encodingComboBox->addItem(name);
        if (defaultTextCodec == codec)
            m_ui.encodingComboBox->setCurrentIndex(i);
        i++;
    }

    connect(m_ui.encodingComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentEncodingChanged(int)));
}

void EditorSettingsWidget::currentEncodingChanged(int index)
{
    m_project->editorConfiguration()->setDefaultTextCodec(m_codecs.at(index));
}

<commit_msg>Clean debug output<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "editorsettingspropertiespage.h"
#include "editorconfiguration.h"
#include "project.h"

#include <QtCore/QTextCodec>

#include <QDebug>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

QString EditorSettingsPanelFactory::id() const
{
    return QLatin1String(EDITORSETTINGS_PANEL_ID);
}

QString EditorSettingsPanelFactory::displayName() const
{
    return QCoreApplication::translate("EditorSettingsPanelFactory", "Editor Settings");
}

bool EditorSettingsPanelFactory::supports(Project *project)
{
    Q_UNUSED(project);
    return true;
}

IPropertiesPanel *EditorSettingsPanelFactory::createPanel(Project *project)
{
    return new EditorSettingsPanel(project);
}

EditorSettingsPanel::EditorSettingsPanel(Project *project) :
    m_widget(new EditorSettingsWidget(project)),
    m_icon(":/projectexplorer/images/EditorSettings.png")
{
}

EditorSettingsPanel::~EditorSettingsPanel()
{
    delete m_widget;
}

QString EditorSettingsPanel::displayName() const
{
    return QCoreApplication::translate("EditorSettingsPanel", "Editor Settings");
}

QWidget *EditorSettingsPanel::widget() const
{
    return m_widget;
}

QIcon EditorSettingsPanel::icon() const
{
    return m_icon;
}

EditorSettingsWidget::EditorSettingsWidget(Project *project)
    : QWidget(),
      m_project(project)
{
    m_ui.setupUi(this);
    QTextCodec *defaultTextCodec = 0;
    m_codecs += defaultTextCodec;
    m_ui.encodingComboBox->addItem(tr("Default"));

    defaultTextCodec = m_project->editorConfiguration()->defaultTextCodec();

    QList<int> mibs = QTextCodec::availableMibs();
    qSort(mibs);
    QList<int> sortedMibs;
    foreach (int mib, mibs)
        if (mib >= 0)
            sortedMibs += mib;
    foreach (int mib, mibs)
        if (mib < 0)
            sortedMibs += mib;
    int i = 1; // 0 is the default
    foreach (int mib, sortedMibs) {
        QTextCodec *codec = QTextCodec::codecForMib(mib);
        m_codecs += codec;
        QString name = codec->name();
        foreach (const QByteArray &alias, codec->aliases()) {
            name += QLatin1String(" / ");
            name += QString::fromLatin1(alias);
        }
        m_ui.encodingComboBox->addItem(name);
        if (defaultTextCodec == codec)
            m_ui.encodingComboBox->setCurrentIndex(i);
        i++;
    }

    connect(m_ui.encodingComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentEncodingChanged(int)));
}

void EditorSettingsWidget::currentEncodingChanged(int index)
{
    m_project->editorConfiguration()->setDefaultTextCodec(m_codecs.at(index));
}

<|endoftext|>


<commit_before>TString names=("TTree_cuts");

TObjArray*  arrNames           = names.Tokenize(";");
const Int_t nDie               = arrNames->GetEntriesFast();
Int_t       selectedCentrality = -1; // not yet implemented
Int_t       selectedPID;
Bool_t      isPrefilterCutset;
Double_t    rejCutMee;
Double_t    rejCutTheta;
Double_t    rejCutPhiV;

//________________________________________________________________
// binning of 3D output histograms
// eta bins
const Double_t EtaMin   = -1.;
const Double_t EtaMax   =  1.;
const Int_t    nBinsEta = 40; //flexible to rebin
// phi bins
const Double_t PhiMin   = 0.;
const Double_t PhiMax   = 6.2832;
const Int_t    nBinsPhi = 60; //flexible to rebin

const Double_t PtBins[] = {0.0, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70,
						   0.75, 0.80, 0.85, 0.90, 1.00, 1.10, 1.15, 1.25, 1.35, 1.55, 1.80,
						   2.05, 2.30, 2.60, 2.90, 3.30, 3.60, 4.00, 5.00, 6.50, 8.00, 10.0};

// Bool_t bUseRelPResolution = kTRUE; //not used
Bool_t bUseEtaResolution      = kTRUE; // use eta or theta resolution?
Bool_t CalcEfficiencyRec      = kTRUE;
Bool_t CalcEfficiencyPoslabel = kFALSE;
Bool_t CalcResolution         = kFALSE;
Bool_t MakeResolutionSparse   = kFALSE;
Bool_t doPairing              = kTRUE;

// resolution binnings
Int_t    NbinsMom        = 2000;
Double_t MomMin          = 0.;
Double_t MomMax          = 10.;
Int_t    NbinsDeltaMom   = 1001;
Double_t DeltaMomMin     = -9.005;
Double_t DeltaMomMax     =  1.005;
Int_t    NbinsRelMom     =  1201;
Double_t RelMomMin       = -0.0005;
Double_t RelMomMax       =  1.2005;
Int_t    NbinsDeltaEta   = 1001;
Double_t DeltaEtaMin     = -0.5005;
Double_t DeltaEtaMax     =  0.5005;
Int_t    NbinsDeltaTheta = 1001;
Double_t DeltaThetaMin   = -0.5005;
Double_t DeltaThetaMax   =  0.5005;
Int_t    NbinsDeltaPhi   = 601;
Double_t DeltaPhiMin     = -0.3005;
Double_t DeltaPhiMax     =  0.3005;
Int_t    NbinsDeltaAngle = 401;
Double_t DeltaAngleMin   = -0.2005;
Double_t DeltaAngleMax   =  0.6005;

//Create mass bins
const Double_t MeeBins[] ={0.00, 0.025, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.12,
                            0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.95, 1.05, 1.25,
														1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 2.9, 3.0, 3.05, 3.1,
														3.3, 3.8, 5.00};
const Int_t nBinsMee  = sizeof(MeeBins)/sizeof(MeeBins[0])-1;

const Double_t PteeBins[] = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,
                             1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
                             2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9,
                             3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5,
														 8.0, 8.5, 9.0, 9.5, 10.0};

const Int_t nBinsPtee = sizeof(PteeBins)/sizeof(PteeBins[0])-1;

// in increasing order
const TString sRuns("265309, 265334, 265335, 265338, 265339,
                     265342, 265343, 265344, 265377, 265378,
                     265381, 265383, 265384, 265385, 265387,
                     265388, 265419, 265420, 265421, 265422,
                     265424, 265427, 265435, 265499, 265500,
                     265501, 265521, 265525");

//
// ^^^^^^^^^^ [/end binning histograms] ^^^^^^^^^^

//________________________________________________________________
// specify if track tree shall be filled and written to file (only recommended for small checks!)
const Bool_t    writeTree = kFALSE;
// specify for which "cutInstance" the support histos should be filled!
const Int_t     supportedCutInstance = 0;
//
//________________________________________________________________
// settings which are identical for all configs that run together
// event cuts
const Bool_t    reqVertex = kTRUE;
const Double_t  vertexZcut = 10.;
//Set centrality in AddTask arguments
// MC cuts
const Double_t  EtaMinGEN = -1.;    // make sure to be within 3D histogram binning (EtaMin, EtaMax, PtBins[]).
const Double_t  EtaMaxGEN =  1.;
const Double_t  PtMinGEN  =  0.100; // 100 MeV as absolute lower limit for any setting.
const Double_t  PtMaxGEN  =  50.;

const Bool_t    CutInjectedSignals = kFALSE;
const UInt_t    NminEleInEventForRej = 2;
// ^^^^^^^^^^ [/end common settings] ^^^^^^^^^^

//________________________________________________________________
AliAnalysisCuts* SetupEventCuts()
{
	// event cuts are identical for all analysis 'cutInstance's that run together!
	AliDielectronEventCuts *eventCuts = new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");

	eventCuts->SetRequireVertex();
	eventCuts->SetMinVtxContributors(1);
	eventCuts->SetVertexZ(-10.,10.);

	return eventCuts;
}

//________________________________________________________________
AliAnalysisFilter* SetupTrackCutsAndSettings(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
	std::cout << "SetupTrackCutsAndSettings()" <<std::endl;
	AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory!
  selectedPID=-1;
  isPrefilterCutset=kFALSE;
  rejCutMee=-1;
  rejCutTheta=-1;
  rejCutPhiV=3.2; // relevant are values below pi, so initialization to 3.2 means disabling.
	// produce analysis filter by using functions in this config:
	anaFilter->AddCuts( SetupTrackCuts(cutInstance, hasITS) );
	anaFilter->AddCuts( SetupPIDcuts(cutInstance) );
	std::cout << "...cuts added!" <<std::endl;

	return anaFilter;
}

// prefilter cuts are not used at the moment
//________________________________________________________________
Int_t SetupPrefilterPairCuts(Int_t cutInstance)
{
  std::cout << "SetupPrefilterPairCuts()" <<std::endl;

  return 1;
}

//________________________________________________________________
AliAnalysisCuts* SetupTrackCuts(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
  std::cout << "SetupTrackCuts()" <<std::endl;
  //AliAnalysisCuts* trackCuts=0x0;

	AliESDtrackCuts *fesdTrackCuts = new AliESDtrackCuts();

	//Cuts implemented in TreeMaker
	if(cutInstance == 0){
		//FilterBit 4 used to filter AODs
		//Set via GetStandardITSTPCTrackCuts 2011(kFALSE, 1)
		fesdTrackCuts->SetMinNCrossedRowsTPC(70);
		//fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
		fesdTrackCuts->SetMaxChi2PerClusterTPC(4);
		fesdTrackCuts->SetAcceptKinkDaughters(kFALSE);
		fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
		fesdTrackCuts->SetRequireTPCRefit(kTRUE);
		fesdTrackCuts->SetRequireITSRefit(kTRUE);
		fesdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
		fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
		fesdTrackCuts->SetMaxChi2PerClusterITS(36);

		//Manually set by fitler bit 4
		////Override setting in TrackCuts2011
		fesdTrackCuts->SetMaxDCAToVertexXY(2.4);
		fesdTrackCuts->SetMaxDCAToVertexZ(3.2);
		fesdTrackCuts->SetDCAToVertex2D(kTRUE);

		//Manually implemented track cuts in TreeMaker
		//General
		fesdTrackCuts->SetPtRange(0.2, 10);
		fesdTrackCuts->SetEtaRange(-0.8, 0.8);
		fesdTrackCuts->SetMaxDCAToVertexZ(3.0);
		fesdTrackCuts->SetMaxDCAToVertexXY(1.0);

		//TPC
		fesdTrackCuts->SetMinNClustersTPC(70);
		//fesdTrackCuts->SetMinNCrossedRowsTPC(60); FilterBit4 stronger cut
		fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.3);
		//fesdTrackCuts->SetMaxChi2PerClusterTPC(4.5);
		fesdTrackCuts->SetMaxFractionSharedTPCClusters(0.4);

		//ITS
		if(hasITS){
			fesdTrackCuts->SetMinNClustersITS(4);
		}else{
			fesdTrackCuts->SetMinNClustersITS(2);
		}
	}

	return fesdTrackCuts;
}

//________________________________________________________________
AliAnalysisCuts* SetupPIDcuts(Int_t cutInstance)
{
	std::cout << "SetupPIDcuts()" <<std::endl;
	AliAnalysisCuts* pidCuts=0x0;

	AliDielectronPID *pid = new AliDielectronPID();

	//The only PID cut applied when creating Trees
	if(cutInstance == 0){
  	pid->AddCut(AliDielectronPID::kTPC, AliPID::kElectron, -4, 4, 0, 1e30, kFALSE, AliDielectronPID::kRequire, AliDielectronVarManager::kPt);
	}

	pidCuts = pid;
	return pidCuts;
}

<commit_msg>Switched of pairing for resolution file run<commit_after>TString names=("TTree_cuts");

TObjArray*  arrNames           = names.Tokenize(";");
const Int_t nDie               = arrNames->GetEntriesFast();
Int_t       selectedCentrality = -1; // not yet implemented
Int_t       selectedPID;
Bool_t      isPrefilterCutset;
Double_t    rejCutMee;
Double_t    rejCutTheta;
Double_t    rejCutPhiV;

//________________________________________________________________
// binning of 3D output histograms
// eta bins
const Double_t EtaMin   = -1.;
const Double_t EtaMax   =  1.;
const Int_t    nBinsEta = 40; //flexible to rebin
// phi bins
const Double_t PhiMin   = 0.;
const Double_t PhiMax   = 6.2832;
const Int_t    nBinsPhi = 60; //flexible to rebin

const Double_t PtBins[] = {0.0, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70,
						   0.75, 0.80, 0.85, 0.90, 1.00, 1.10, 1.15, 1.25, 1.35, 1.55, 1.80,
						   2.05, 2.30, 2.60, 2.90, 3.30, 3.60, 4.00, 5.00, 6.50, 8.00, 10.0};

// Bool_t bUseRelPResolution = kTRUE; //not used
Bool_t bUseEtaResolution      = kTRUE; // use eta or theta resolution?
Bool_t CalcEfficiencyRec      = kTRUE;
Bool_t CalcEfficiencyPoslabel = kFALSE;
Bool_t CalcResolution         = kTRUE;
Bool_t MakeResolutionSparse   = kFALSE;
Bool_t doPairing              = kFALSE;

// resolution binnings
Int_t    NbinsMom        = 2000;
Double_t MomMin          = 0.;
Double_t MomMax          = 10.;
Int_t    NbinsDeltaMom   = 1001;
Double_t DeltaMomMin     = -9.005;
Double_t DeltaMomMax     =  1.005;
Int_t    NbinsRelMom     =  1201;
Double_t RelMomMin       = -0.0005;
Double_t RelMomMax       =  1.2005;
Int_t    NbinsDeltaEta   = 1001;
Double_t DeltaEtaMin     = -0.5005;
Double_t DeltaEtaMax     =  0.5005;
Int_t    NbinsDeltaTheta = 1001;
Double_t DeltaThetaMin   = -0.5005;
Double_t DeltaThetaMax   =  0.5005;
Int_t    NbinsDeltaPhi   = 601;
Double_t DeltaPhiMin     = -0.3005;
Double_t DeltaPhiMax     =  0.3005;
Int_t    NbinsDeltaAngle = 401;
Double_t DeltaAngleMin   = -0.2005;
Double_t DeltaAngleMax   =  0.6005;

//Create mass bins
const Double_t MeeBins[] ={0.00, 0.025, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.12,
                            0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.95, 1.05, 1.25,
														1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 2.9, 3.0, 3.05, 3.1,
														3.3, 3.8, 5.00};
const Int_t nBinsMee  = sizeof(MeeBins)/sizeof(MeeBins[0])-1;

const Double_t PteeBins[] = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,
                             1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9,
                             2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9,
                             3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5,
														 8.0, 8.5, 9.0, 9.5, 10.0};

const Int_t nBinsPtee = sizeof(PteeBins)/sizeof(PteeBins[0])-1;

// in increasing order
const TString sRuns("265309, 265334, 265335, 265338, 265339,
                     265342, 265343, 265344, 265377, 265378,
                     265381, 265383, 265384, 265385, 265387,
                     265388, 265419, 265420, 265421, 265422,
                     265424, 265427, 265435, 265499, 265500,
                     265501, 265521, 265525");

//
// ^^^^^^^^^^ [/end binning histograms] ^^^^^^^^^^

//________________________________________________________________
// specify if track tree shall be filled and written to file (only recommended for small checks!)
const Bool_t    writeTree = kFALSE;
// specify for which "cutInstance" the support histos should be filled!
const Int_t     supportedCutInstance = 0;
//
//________________________________________________________________
// settings which are identical for all configs that run together
// event cuts
const Bool_t    reqVertex = kTRUE;
const Double_t  vertexZcut = 10.;
//Set centrality in AddTask arguments
// MC cuts
const Double_t  EtaMinGEN = -1.;    // make sure to be within 3D histogram binning (EtaMin, EtaMax, PtBins[]).
const Double_t  EtaMaxGEN =  1.;
const Double_t  PtMinGEN  =  0.100; // 100 MeV as absolute lower limit for any setting.
const Double_t  PtMaxGEN  =  50.;

const Bool_t    CutInjectedSignals = kFALSE;
const UInt_t    NminEleInEventForRej = 2;
// ^^^^^^^^^^ [/end common settings] ^^^^^^^^^^

//________________________________________________________________
AliAnalysisCuts* SetupEventCuts()
{
	// event cuts are identical for all analysis 'cutInstance's that run together!
	AliDielectronEventCuts *eventCuts = new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");

	eventCuts->SetRequireVertex();
	eventCuts->SetMinVtxContributors(1);
	eventCuts->SetVertexZ(-10.,10.);

	return eventCuts;
}

//________________________________________________________________
AliAnalysisFilter* SetupTrackCutsAndSettings(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
	std::cout << "SetupTrackCutsAndSettings()" <<std::endl;
	AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory!
  selectedPID=-1;
  isPrefilterCutset=kFALSE;
  rejCutMee=-1;
  rejCutTheta=-1;
  rejCutPhiV=3.2; // relevant are values below pi, so initialization to 3.2 means disabling.
	// produce analysis filter by using functions in this config:
	anaFilter->AddCuts( SetupTrackCuts(cutInstance, hasITS) );
	anaFilter->AddCuts( SetupPIDcuts(cutInstance) );
	std::cout << "...cuts added!" <<std::endl;

	return anaFilter;
}

// prefilter cuts are not used at the moment
//________________________________________________________________
Int_t SetupPrefilterPairCuts(Int_t cutInstance)
{
  std::cout << "SetupPrefilterPairCuts()" <<std::endl;

  return 1;
}

//________________________________________________________________
AliAnalysisCuts* SetupTrackCuts(Int_t cutInstance, Bool_t hasITS = kTRUE)
{
  std::cout << "SetupTrackCuts()" <<std::endl;
  //AliAnalysisCuts* trackCuts=0x0;

	AliESDtrackCuts *fesdTrackCuts = new AliESDtrackCuts();

	//Cuts implemented in TreeMaker
	if(cutInstance == 0){
		//FilterBit 4 used to filter AODs
		//Set via GetStandardITSTPCTrackCuts 2011(kFALSE, 1)
		fesdTrackCuts->SetMinNCrossedRowsTPC(70);
		//fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
		fesdTrackCuts->SetMaxChi2PerClusterTPC(4);
		fesdTrackCuts->SetAcceptKinkDaughters(kFALSE);
		fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
		fesdTrackCuts->SetRequireTPCRefit(kTRUE);
		fesdTrackCuts->SetRequireITSRefit(kTRUE);
		fesdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
		fesdTrackCuts->SetRequireSigmaToVertex(kFALSE);
		fesdTrackCuts->SetMaxChi2PerClusterITS(36);

		//Manually set by fitler bit 4
		////Override setting in TrackCuts2011
		fesdTrackCuts->SetMaxDCAToVertexXY(2.4);
		fesdTrackCuts->SetMaxDCAToVertexZ(3.2);
		fesdTrackCuts->SetDCAToVertex2D(kTRUE);

		//Manually implemented track cuts in TreeMaker
		//General
		fesdTrackCuts->SetPtRange(0.2, 10);
		fesdTrackCuts->SetEtaRange(-0.8, 0.8);
		fesdTrackCuts->SetMaxDCAToVertexZ(3.0);
		fesdTrackCuts->SetMaxDCAToVertexXY(1.0);

		//TPC
		fesdTrackCuts->SetMinNClustersTPC(70);
		//fesdTrackCuts->SetMinNCrossedRowsTPC(60); FilterBit4 stronger cut
		fesdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.3);
		//fesdTrackCuts->SetMaxChi2PerClusterTPC(4.5);
		fesdTrackCuts->SetMaxFractionSharedTPCClusters(0.4);

		//ITS
		if(hasITS){
			fesdTrackCuts->SetMinNClustersITS(4);
		}else{
			fesdTrackCuts->SetMinNClustersITS(2);
		}
	}

	return fesdTrackCuts;
}

//________________________________________________________________
AliAnalysisCuts* SetupPIDcuts(Int_t cutInstance)
{
	std::cout << "SetupPIDcuts()" <<std::endl;
	AliAnalysisCuts* pidCuts=0x0;

	AliDielectronPID *pid = new AliDielectronPID();

	//The only PID cut applied when creating Trees
	if(cutInstance == 0){
  	pid->AddCut(AliDielectronPID::kTPC, AliPID::kElectron, -4, 4, 0, 1e30, kFALSE, AliDielectronPID::kRequire, AliDielectronVarManager::kPt);
	}

	pidCuts = pid;
	return pidCuts;
}

<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/unit.hpp>
#include <agency/detail/unique_ptr.hpp>
#include <type_traits>

namespace agency
{
namespace detail
{

struct unit_ptr : unit
{
  using element_type = unit;

  __AGENCY_ANNOTATION
  unit& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const unit& operator*() const
  {
    return *this;
  }
};

template<class T>
struct state_requires_storage
  : std::integral_constant<
      bool,
      std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
   >
{};

struct construct_ready_t {};
struct construct_not_ready_t {};

constexpr static construct_ready_t     construct_ready{};
constexpr static construct_not_ready_t construct_not_ready{};

// XXX this is suffixed with _impl because of nvbug 1700337
//     eliminate the suffix when that bug is resolved
// XXX should try to collapse the implementation of this as much as possible between the two
template<class T,
         class Alloc = std::allocator<T>,
         bool requires_storage = state_requires_storage<T>::value>
class asynchronous_state_impl
{
  public:
    using value_type = T;
    using pointer = value_type*;
    using storage_type = unique_ptr<T,deleter<Alloc>>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() = default;

    // constructs an immediately ready state
    template<class... Args,
             class = typename std::enable_if<
               std::is_constructible<T,Args...>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, Args&&... ready_args)
      : storage_(allocate_unique<T>(Alloc(), std::forward<Args>(ready_args)...))
    {}

    // constructs a not ready state
    // XXX we should avoid creating an object here
    //     instead, we should just create it uninitialized
    // XXX the destructor should check whether the state requires destruction
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t)
      : asynchronous_state_impl(construct_ready, T{})
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) = default;

    template<class OtherT,
             class OtherAlloc,
             class = typename std::enable_if<
               std::is_constructible<storage_type, typename asynchronous_state_impl<OtherT,OtherAlloc>::storage_type&&>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : storage_(std::move(other.storage_))
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&&) = default;

    __AGENCY_ANNOTATION
    pointer data() const
    {
      return storage_.get();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      T result = std::move(*storage_);

      storage_.reset();

      return std::move(result);
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return storage_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      storage_.swap(other.storage_);
    }

  private:
    template<class, class, bool>
    friend class asynchronous_state_impl;

    storage_type storage_;
};

// when a type is empty, we can create instances on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
  using element_type = T;

  __AGENCY_ANNOTATION
  T& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const T& operator*() const
  {
    return *this;
  }
};

template<>
struct empty_type_ptr<void> : unit_ptr {};

// zero storage optimization
template<class T, class Alloc>
class asynchronous_state_impl<T,Alloc,true>
{
  public:
    using value_type = T;
    using pointer = empty_type_ptr<T>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() : valid_(false) {}

    // constructs an immediately ready state
    template<class OtherT,
             class = typename std::enable_if<
               std::is_constructible<T,OtherT&&>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, OtherT&&) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t) : valid_(true) {}

    // constructs a not ready state
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) : valid_(other.valid_)
    {
      other.valid_ = false;
    }

    // 1. allow moves to void states (this simply discards the state)
    // 2. allow moves to empty types if the type can be constructed from an empty argument list
    // 3. allow upcasts to a base T from a derived U
    template<class OtherT,
             class OtherAlloc,
             class T1 = T,
             class = typename std::enable_if<
               std::is_void<T1>::value ||
               (std::is_empty<T>::value && std::is_void<OtherT>::value && std::is_constructible<T>::value) ||
               std::is_base_of<T,OtherT>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : valid_(other.valid())
    {
      if(valid())
      {
        // invalidate the old state by calling .get() if it was valid when we received it
        other.get();
      }
    }

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&& other)
    {
      valid_ = other.valid_;
      other.valid_ = false;

      return *this;
    }

    __AGENCY_ANNOTATION
    empty_type_ptr<T> data() const
    {
      return empty_type_ptr<T>();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      valid_ = false;

      return get_impl(std::is_void<T>());
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return valid_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      bool other_valid_old = other.valid_;
      other.valid_ = valid_;
      valid_ = other_valid_old;
    }

  private:
    __AGENCY_ANNOTATION
    static T get_impl(std::false_type)
    {
      return T{};
    }

    __AGENCY_ANNOTATION
    static T get_impl(std::true_type)
    {
      return;
    }

    bool valid_;
};

// XXX this extra indirection is due to nvbug 1700337
//     eliminate this class when that bug is resolved
template<class T, class Alloc = std::allocator<T>>
class asynchronous_state : public asynchronous_state_impl<T,Alloc>
{
  public:
    using asynchronous_state_impl<T,Alloc>::asynchronous_state_impl;
};

} // end detail
} // end agency

<commit_msg>Suppress a __host__ __device__ warning in asynchronous_state<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/unit.hpp>
#include <agency/detail/unique_ptr.hpp>
#include <type_traits>

namespace agency
{
namespace detail
{

struct unit_ptr : unit
{
  using element_type = unit;

  __AGENCY_ANNOTATION
  unit& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const unit& operator*() const
  {
    return *this;
  }
};

template<class T>
struct state_requires_storage
  : std::integral_constant<
      bool,
      std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
   >
{};

struct construct_ready_t {};
struct construct_not_ready_t {};

constexpr static construct_ready_t     construct_ready{};
constexpr static construct_not_ready_t construct_not_ready{};

// XXX this is suffixed with _impl because of nvbug 1700337
//     eliminate the suffix when that bug is resolved
// XXX should try to collapse the implementation of this as much as possible between the two
template<class T,
         class Alloc = std::allocator<T>,
         bool requires_storage = state_requires_storage<T>::value>
class asynchronous_state_impl
{
  public:
    using value_type = T;
    using pointer = value_type*;
    using storage_type = unique_ptr<T,deleter<Alloc>>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() = default;

    // constructs an immediately ready state
    __agency_hd_warning_disable__
    template<class... Args,
             class = typename std::enable_if<
               std::is_constructible<T,Args...>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, Args&&... ready_args)
      : storage_(allocate_unique<T>(Alloc(), std::forward<Args>(ready_args)...))
    {}

    // constructs a not ready state
    // XXX we should avoid creating an object here
    //     instead, we should just create it uninitialized
    // XXX the destructor should check whether the state requires destruction
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t)
      : asynchronous_state_impl(construct_ready, T{})
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) = default;

    template<class OtherT,
             class OtherAlloc,
             class = typename std::enable_if<
               std::is_constructible<storage_type, typename asynchronous_state_impl<OtherT,OtherAlloc>::storage_type&&>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : storage_(std::move(other.storage_))
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&&) = default;

    __AGENCY_ANNOTATION
    pointer data() const
    {
      return storage_.get();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      T result = std::move(*storage_);

      storage_.reset();

      return std::move(result);
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return storage_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      storage_.swap(other.storage_);
    }

  private:
    template<class, class, bool>
    friend class asynchronous_state_impl;

    storage_type storage_;
};

// when a type is empty, we can create instances on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
  using element_type = T;

  __AGENCY_ANNOTATION
  T& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const T& operator*() const
  {
    return *this;
  }
};

template<>
struct empty_type_ptr<void> : unit_ptr {};

// zero storage optimization
template<class T, class Alloc>
class asynchronous_state_impl<T,Alloc,true>
{
  public:
    using value_type = T;
    using pointer = empty_type_ptr<T>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() : valid_(false) {}

    // constructs an immediately ready state
    template<class OtherT,
             class = typename std::enable_if<
               std::is_constructible<T,OtherT&&>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, OtherT&&) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t) : valid_(true) {}

    // constructs a not ready state
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) : valid_(other.valid_)
    {
      other.valid_ = false;
    }

    // 1. allow moves to void states (this simply discards the state)
    // 2. allow moves to empty types if the type can be constructed from an empty argument list
    // 3. allow upcasts to a base T from a derived U
    template<class OtherT,
             class OtherAlloc,
             class T1 = T,
             class = typename std::enable_if<
               std::is_void<T1>::value ||
               (std::is_empty<T>::value && std::is_void<OtherT>::value && std::is_constructible<T>::value) ||
               std::is_base_of<T,OtherT>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : valid_(other.valid())
    {
      if(valid())
      {
        // invalidate the old state by calling .get() if it was valid when we received it
        other.get();
      }
    }

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&& other)
    {
      valid_ = other.valid_;
      other.valid_ = false;

      return *this;
    }

    __AGENCY_ANNOTATION
    empty_type_ptr<T> data() const
    {
      return empty_type_ptr<T>();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      valid_ = false;

      return get_impl(std::is_void<T>());
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return valid_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      bool other_valid_old = other.valid_;
      other.valid_ = valid_;
      valid_ = other_valid_old;
    }

  private:
    __AGENCY_ANNOTATION
    static T get_impl(std::false_type)
    {
      return T{};
    }

    __AGENCY_ANNOTATION
    static T get_impl(std::true_type)
    {
      return;
    }

    bool valid_;
};

// XXX this extra indirection is due to nvbug 1700337
//     eliminate this class when that bug is resolved
template<class T, class Alloc = std::allocator<T>>
class asynchronous_state : public asynchronous_state_impl<T,Alloc>
{
  public:
    using asynchronous_state_impl<T,Alloc>::asynchronous_state_impl;
};

} // end detail
} // end agency

<|endoftext|>