<commit_before>#include "../interface/MuonsFiller.h"

#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/MuonReco/interface/MuonSelectors.h"
#include "DataFormats/Math/interface/deltaR.h"
#include "DataFormats/PatCandidates/interface/Muon.h"
#include "DataFormats/PatCandidates/interface/TriggerObjectStandAlone.h"
#include "DataFormats/Common/interface/RefToPtr.h"

MuonsFiller::MuonsFiller(std::string const& _name, edm::ParameterSet const& _cfg, edm::ConsumesCollector& _coll) :
  FillerBase(_name, _cfg),
  minPt_(getParameter_<double>(_cfg, "minPt", -1.)),
  maxEta_(getParameter_<double>(_cfg, "maxEta", 10.))
{
  getToken_(muonsToken_, _cfg, _coll, "muons");
  getToken_(verticesToken_, _cfg, _coll, "vertices", "vertices");

  if (useTrigger_) {
    for (unsigned iT(0); iT != panda::nMuonTriggerObjects; ++iT) {
      std::string name(panda::MuonTriggerObjectName[iT]); // "f<trigger filter name>"
      auto filters(getParameter_<VString>(_cfg, "triggerObjects." + name.substr(1)));
      triggerObjects_[iT].insert(filters.begin(), filters.end());
    }
  }
}

void
MuonsFiller::addOutput(TFile& _outputFile)
{
  TDirectory::TContext context(&_outputFile);
  auto* t(panda::makeMuonTriggerObjectTree());
  t->Write();
  delete t;
}

void
MuonsFiller::branchNames(panda::utils::BranchList& _eventBranches, panda::utils::BranchList&) const
{
  _eventBranches.emplace_back("muons");

  if (isRealData_)
    _eventBranches.emplace_back("!muons.matchedGen_");
  if (!useTrigger_)
    _eventBranches.emplace_back("!muons.triggerMatch");
}

void
MuonsFiller::fill(panda::Event& _outEvent, edm::Event const& _inEvent, edm::EventSetup const& _setup)
{
  auto& inMuons(getProduct_(_inEvent, muonsToken_));
  auto& vertices(getProduct_(_inEvent, verticesToken_));

  auto& outMuons(_outEvent.muons);

  std::vector<edm::Ptr<reco::Muon>> ptrList;

  unsigned iMu(-1);
  for (auto& inMuon : inMuons) {
    ++iMu;

    if (inMuon.pt() < minPt_)
      continue;
    if (std::abs(inMuon.eta()) > maxEta_)
      continue;

    auto& outMuon(outMuons.create_back());

    fillP4(outMuon, inMuon);

    outMuon.q = inMuon.charge();

    auto& pfIso(inMuon.pfIsolationR04());

    outMuon.chiso = pfIso.sumChargedHadronPt;
    outMuon.nhiso = pfIso.sumNeutralHadronEt;
    outMuon.phoiso = pfIso.sumPhotonEt;
    outMuon.puiso = pfIso.sumPUPt;

    if (dynamic_cast<pat::Muon const*>(&inMuon)) {
      auto& patMuon(static_cast<pat::Muon const&>(inMuon));

      outMuon.loose = patMuon.isLooseMuon();
      outMuon.medium = patMuon.isMediumMuon();
      if (vertices.size() == 0)
        outMuon.tight = false;
      else
        outMuon.tight = patMuon.isTightMuon(vertices.at(0));
    }
    else {
      outMuon.loose = muon::isLooseMuon(inMuon);
      outMuon.medium = muon::isMediumMuon(inMuon);
      if (vertices.size() == 0)
        outMuon.tight = false;
      else
        outMuon.tight = muon::isTightMuon(inMuon, vertices.at(0));
    }

    ptrList.push_back(inMuons.ptrAt(iMu));
  }

  auto originalIndices(outMuons.sort(panda::Particle::PtGreater));

  // export panda <-> reco mapping

  auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>());
  auto& genMuMap(objectMap_->get<reco::GenParticle, panda::Muon>());

  for (unsigned iP(0); iP != outMuons.size(); ++iP) {
    auto& outMuon(outMuons[iP]);
    unsigned idx(originalIndices[iP]);
    muMuMap.add(ptrList[idx], outMuon);

    if (!isRealData_) {
      auto& inMuon(*ptrList[idx]);

      if (dynamic_cast<pat::Muon const*>(&inMuon)) {
        auto& patMuon(static_cast<pat::Muon const&>(inMuon));
        auto ref(patMuon.genParticleRef());
        if (ref.isNonnull())
          genMuMap.add(edm::refToPtr(ref), outMuon);
      }
    }
  }
}

void
MuonsFiller::setRefs(ObjectMapStore const& _objectMaps)
{
  if (!isRealData_) {
    auto& genMuMap(objectMap_->get<reco::GenParticle, panda::Muon>());

    auto& genMap(_objectMaps.at("genParticles").get<reco::GenParticle, panda::GenParticle>().fwdMap);

    for (auto& link : genMuMap.bwdMap) {
      auto& genPtr(link.second);
      if (genMap.find(genPtr) == genMap.end())
        continue;

      auto& outMuon(*link.first);
      outMuon.matchedGen = genMap.at(genPtr);
    }
  }

  if (useTrigger_) {
    auto& objMap(_objectMaps.at("global").get<pat::TriggerObjectStandAlone, VString>().fwdMap);

    std::vector<pat::TriggerObjectStandAlone const*> triggerObjects[panda::nMuonTriggerObjects];

    // loop over the trigger filters we are interested in
    for (unsigned iT(0); iT != panda::nMuonTriggerObjects; ++iT) {
      // loop over all trigger objects (and their associated filter names)
      for (auto& objAndNames : objMap) { // (TO ptr, VString)
        VString const& names(*objAndNames.second);
        // loop over the associated filter names
        for (auto& name : names) {
          if (triggerObjects_[iT].find(name) != triggerObjects_[iT].end()) {
            triggerObjects[iT].push_back(&*objAndNames.first);
            break;
          }
        }
      }
    }

    auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>().fwdMap);

    for (auto& link : muMuMap) { // edm -> panda
      auto& inMuon(*link.first);
      auto& outMuon(*link.second);

      for (unsigned iT(0); iT != panda::nMuonTriggerObjects; ++iT) {
        for (auto* obj : triggerObjects[iT]) {
          if (reco::deltaR(inMuon, *obj) < 0.3) {
            outMuon.triggerMatch[iT] = true;
            break;
          }
        }
      }
    }
  }
}

DEFINE_TREEFILLER(MuonsFiller);
<commit_msg>added new muon medium id<commit_after>#include "../interface/MuonsFiller.h"

#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/MuonReco/interface/MuonSelectors.h"
#include "DataFormats/Math/interface/deltaR.h"
#include "DataFormats/PatCandidates/interface/Muon.h"
#include "DataFormats/PatCandidates/interface/TriggerObjectStandAlone.h"
#include "DataFormats/Common/interface/RefToPtr.h"

MuonsFiller::MuonsFiller(std::string const& _name, edm::ParameterSet const& _cfg, edm::ConsumesCollector& _coll) :
  FillerBase(_name, _cfg),
  minPt_(getParameter_<double>(_cfg, "minPt", -1.)),
  maxEta_(getParameter_<double>(_cfg, "maxEta", 10.))
{
  getToken_(muonsToken_, _cfg, _coll, "muons");
  getToken_(verticesToken_, _cfg, _coll, "vertices", "vertices");

  if (useTrigger_) {
    for (unsigned iT(0); iT != panda::nMuonTriggerObjects; ++iT) {
      std::string name(panda::MuonTriggerObjectName[iT]); // "f<trigger filter name>"
      auto filters(getParameter_<VString>(_cfg, "triggerObjects." + name.substr(1)));
      triggerObjects_[iT].insert(filters.begin(), filters.end());
    }
  }
}

void
MuonsFiller::addOutput(TFile& _outputFile)
{
  TDirectory::TContext context(&_outputFile);
  auto* t(panda::makeMuonTriggerObjectTree());
  t->Write();
  delete t;
}

void
MuonsFiller::branchNames(panda::utils::BranchList& _eventBranches, panda::utils::BranchList&) const
{
  _eventBranches.emplace_back("muons");

  if (isRealData_)
    _eventBranches.emplace_back("!muons.matchedGen_");
  if (!useTrigger_)
    _eventBranches.emplace_back("!muons.triggerMatch");
}

void
MuonsFiller::fill(panda::Event& _outEvent, edm::Event const& _inEvent, edm::EventSetup const& _setup)
{
  auto& inMuons(getProduct_(_inEvent, muonsToken_));
  auto& vertices(getProduct_(_inEvent, verticesToken_));

  auto& outMuons(_outEvent.muons);

  std::vector<edm::Ptr<reco::Muon>> ptrList;

  unsigned iMu(-1);
  for (auto& inMuon : inMuons) {
    ++iMu;

    if (inMuon.pt() < minPt_)
      continue;
    if (std::abs(inMuon.eta()) > maxEta_)
      continue;

    auto& outMuon(outMuons.create_back());

    fillP4(outMuon, inMuon);

    outMuon.q = inMuon.charge();

    auto& pfIso(inMuon.pfIsolationR04());

    outMuon.chiso = pfIso.sumChargedHadronPt;
    outMuon.nhiso = pfIso.sumNeutralHadronEt;
    outMuon.phoiso = pfIso.sumPhotonEt;
    outMuon.puiso = pfIso.sumPUPt;

    if (dynamic_cast<pat::Muon const*>(&inMuon)) {
      auto& patMuon(static_cast<pat::Muon const&>(inMuon));

      outMuon.loose = patMuon.isLooseMuon();
      outMuon.medium = patMuon.isMediumMuon();
      // Following the "short-term instruction for Moriond 2017" given in https://twiki.cern.ch/twiki/bin/viewauth/CMS/SWGuideMuonIdRun2#MediumID2016_to_be_used_with_Run
      // Valid only for runs B-F
      outMuon.mediumBtoF = outMuon.loose && inMuon.innerTrack()->validFraction() > 0.49 &&
        ((inMuon.isGlobalMuon() &&
          inMuon.globalTrack()->normalizedChi2() < 3. &&
          inMuon.combinedQuality().chi2LocalPosition < 12. &&
          inMuon.combinedQuality().trkKink < 20. &&
          muon::segmentCompatibility(inMuon) > 0.303) ||
         muon::segmentCompatibility(inMuon) > 0.451);

      if (vertices.size() == 0)
        outMuon.tight = false;
      else
        outMuon.tight = patMuon.isTightMuon(vertices.at(0));
    }
    else {
      outMuon.loose = muon::isLooseMuon(inMuon);
      outMuon.medium = muon::isMediumMuon(inMuon);
      if (vertices.size() == 0)
        outMuon.tight = false;
      else
        outMuon.tight = muon::isTightMuon(inMuon, vertices.at(0));
    }

    ptrList.push_back(inMuons.ptrAt(iMu));
  }

  auto originalIndices(outMuons.sort(panda::Particle::PtGreater));

  // export panda <-> reco mapping

  auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>());
  auto& genMuMap(objectMap_->get<reco::GenParticle, panda::Muon>());

  for (unsigned iP(0); iP != outMuons.size(); ++iP) {
    auto& outMuon(outMuons[iP]);
    unsigned idx(originalIndices[iP]);
    muMuMap.add(ptrList[idx], outMuon);

    if (!isRealData_) {
      auto& inMuon(*ptrList[idx]);

      if (dynamic_cast<pat::Muon const*>(&inMuon)) {
        auto& patMuon(static_cast<pat::Muon const&>(inMuon));
        auto ref(patMuon.genParticleRef());
        if (ref.isNonnull())
          genMuMap.add(edm::refToPtr(ref), outMuon);
      }
    }
  }
}

void
MuonsFiller::setRefs(ObjectMapStore const& _objectMaps)
{
  if (!isRealData_) {
    auto& genMuMap(objectMap_->get<reco::GenParticle, panda::Muon>());

    auto& genMap(_objectMaps.at("genParticles").get<reco::GenParticle, panda::GenParticle>().fwdMap);

    for (auto& link : genMuMap.bwdMap) {
      auto& genPtr(link.second);
      if (genMap.find(genPtr) == genMap.end())
        continue;

      auto& outMuon(*link.first);
      outMuon.matchedGen = genMap.at(genPtr);
    }
  }

  if (useTrigger_) {
    auto& objMap(_objectMaps.at("global").get<pat::TriggerObjectStandAlone, VString>().fwdMap);

    std::vector<pat::TriggerObjectStandAlone const*> triggerObjects[panda::nMuonTriggerObjects];

    // loop over the trigger filters we are interested in
    for (unsigned iT(0); iT != panda::nMuonTriggerObjects; ++iT) {
      // loop over all trigger objects (and their associated filter names)
      for (auto& objAndNames : objMap) { // (TO ptr, VString)
        VString const& names(*objAndNames.second);
        // loop over the associated filter names
        for (auto& name : names) {
          if (triggerObjects_[iT].find(name) != triggerObjects_[iT].end()) {
            triggerObjects[iT].push_back(&*objAndNames.first);
            break;
          }
        }
      }
    }

    auto& muMuMap(objectMap_->get<reco::Muon, panda::Muon>().fwdMap);

    for (auto& link : muMuMap) { // edm -> panda
      auto& inMuon(*link.first);
      auto& outMuon(*link.second);

      for (unsigned iT(0); iT != panda::nMuonTriggerObjects; ++iT) {
        for (auto* obj : triggerObjects[iT]) {
          if (reco::deltaR(inMuon, *obj) < 0.3) {
            outMuon.triggerMatch[iT] = true;
            break;
          }
        }
      }
    }
  }
}

DEFINE_TREEFILLER(MuonsFiller);
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_signin.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/net/gaia/token_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"

using chrome::kHttpScheme;
using chrome::kStandardSchemeSeparator;

namespace {

const char kTestUrlHostname[] = "www.example.com";

}  // namespace

// A fake version of ProfileSyncService used for testing.
class FakeProfileSyncService : public ProfileSyncService {
 public:
  FakeProfileSyncService()
      : ProfileSyncService(NULL, NULL, ""),
        setup_(false) {
  }
  virtual ~FakeProfileSyncService() {}

  // Overrides of virtual methods in ProfileSyncService.
  virtual bool HasSyncSetupCompleted() const {
    return setup_;
  }
  virtual void ChangePreferredDataTypes(const syncable::ModelTypeSet& types) {
    types_ = types;
  }
  virtual void GetPreferredDataTypes(syncable::ModelTypeSet* types) const {
    *types = types_;
  }
  virtual void SetSyncSetupCompleted() {
    setup_ = true;
  }

 private:
  bool setup_;
  syncable::ModelTypeSet types_;
};

class FakeBrowserSignin : public BrowserSignin {
 public:
  // The |username_after_login| parameter determines what this fake
  // BrowserSignin will set the username to when ShowLoginDialog is called.
  FakeBrowserSignin(bool should_succeed,
                    const std::string& initial_username,
                    const std::string& username_after_login)
      : BrowserSignin(NULL),
        should_succeed_(should_succeed),
        username_(initial_username),
        username_after_login_(username_after_login) {
  }
  virtual ~FakeBrowserSignin() {}

  virtual std::string GetSignedInUsername() const {
    return username_;
  }

  virtual void RequestSignin(TabContents* tab_contents,
                             const string16& preferred_email,
                             const string16& message,
                             SigninDelegate* delegate) {
    if (should_succeed_) {
      // Simulate valid login.
      username_ = username_after_login_;
      delegate->OnLoginSuccess();

      // Fake a token available notification.
      Profile* profile = tab_contents->profile();
      if (profile->IsOffTheRecord()) {
        profile = g_browser_process->profile_manager()->GetDefaultProfile();
      }
      TokenService* token_service = profile->GetTokenService();
      token_service->IssueAuthTokenForTest(GaiaConstants::kGaiaService,
                                           "new_token");
    } else {
      delegate->OnLoginFailure(GoogleServiceAuthError(
        GoogleServiceAuthError::REQUEST_CANCELED));
    }
  }

 private:
  bool should_succeed_;
  std::string username_;
  std::string username_after_login_;
};

class ExtensionWebstorePrivateBrowserTest : public ExtensionBrowserTest {
 public:
  ExtensionWebstorePrivateBrowserTest() {
    test_url_base_ = std::string() + kHttpScheme + kStandardSchemeSeparator +
                     kTestUrlHostname;
  }

  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL, test_url_base_);
  }

  // This generates a regular test server url pointing to a test file at
  // |relative_path|, but replaces the hostname with kTestUrlHostname so that
  // we get the webstore private APIs injected (this happens because of the
  // command line switch we added in SetupCommandLine).
  GURL GetUrl(const std::string& relative_path) {
    GURL base_url = test_server()->GetURL(
        "files/extensions/webstore_private/" + relative_path);
    GURL::Replacements replacements;
    std::string replacement_host = std::string(kTestUrlHostname);
    replacements.SetHostStr(replacement_host);
    return base_url.ReplaceComponents(replacements);
  }

  void RunLoginTestImpl(bool incognito,
                        const std::string& relative_path,
                        const std::string& initial_login,
                        bool login_succeeds,
                        const std::string& login_result) {
    // Clear the token service so previous tests don't affect things.
    TokenService* token_service = browser()->profile()->GetTokenService();
    token_service->ResetCredentialsInMemory();
    if (!initial_login.empty()) {
      // Initialize the token service with an existing token.
      token_service->IssueAuthTokenForTest(GaiaConstants::kGaiaService,
                                           "existing_token");
    }

    FakeProfileSyncService sync_service;
    FakeBrowserSignin signin(login_succeeds, initial_login, login_result);
    WebstorePrivateApi::SetTestingProfileSyncService(&sync_service);
    WebstorePrivateApi::SetTestingBrowserSignin(&signin);

    ExtensionTestMessageListener listener("success", false);
    GURL url = GetUrl(relative_path);
    if (incognito) {
      ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url);
    } else {
      ui_test_utils::NavigateToURL(browser(), url);
    }
    EXPECT_TRUE(listener.WaitUntilSatisfied());

    WebstorePrivateApi::SetTestingBrowserSignin(NULL);
    WebstorePrivateApi::SetTestingProfileSyncService(NULL);
  }

  void RunLoginTest(const std::string& relative_path,
                    const std::string& initial_login,
                    bool login_succeeds,
                    const std::string& login_result) {
    RunLoginTestImpl(true,
                     relative_path,
                     initial_login,
                     login_succeeds,
                     login_result);
    RunLoginTestImpl(false,
                     relative_path,
                     initial_login,
                     login_succeeds,
                     login_result);
  }

 protected:
  std::string test_url_base_;
};

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBrowserTest, BrowserLogin) {
  host_resolver()->AddRule(kTestUrlHostname, "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  RunLoginTest("browser_login/expect_nonempty.html",
               "foo@bar.com", false, "");

  RunLoginTest("browser_login/prompt_no_preferred.html", "", true, "");

  RunLoginTest("browser_login/prompt_preferred.html", "", true, "foo@bar.com");

  RunLoginTest("browser_login/prompt_login_fails.html",
               "", false, "foo@bar.com");
}
<commit_msg>Use the original non-incognito profile instead of backing off to the default profile when we're in incognito mode.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_signin.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/net/gaia/token_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"

using chrome::kHttpScheme;
using chrome::kStandardSchemeSeparator;

namespace {

const char kTestUrlHostname[] = "www.example.com";

}  // namespace

// A fake version of ProfileSyncService used for testing.
class FakeProfileSyncService : public ProfileSyncService {
 public:
  FakeProfileSyncService()
      : ProfileSyncService(NULL, NULL, ""),
        setup_(false) {
  }
  virtual ~FakeProfileSyncService() {}

  // Overrides of virtual methods in ProfileSyncService.
  virtual bool HasSyncSetupCompleted() const {
    return setup_;
  }
  virtual void ChangePreferredDataTypes(const syncable::ModelTypeSet& types) {
    types_ = types;
  }
  virtual void GetPreferredDataTypes(syncable::ModelTypeSet* types) const {
    *types = types_;
  }
  virtual void SetSyncSetupCompleted() {
    setup_ = true;
  }

 private:
  bool setup_;
  syncable::ModelTypeSet types_;
};

class FakeBrowserSignin : public BrowserSignin {
 public:
  // The |username_after_login| parameter determines what this fake
  // BrowserSignin will set the username to when ShowLoginDialog is called.
  FakeBrowserSignin(bool should_succeed,
                    const std::string& initial_username,
                    const std::string& username_after_login)
      : BrowserSignin(NULL),
        should_succeed_(should_succeed),
        username_(initial_username),
        username_after_login_(username_after_login) {
  }
  virtual ~FakeBrowserSignin() {}

  virtual std::string GetSignedInUsername() const {
    return username_;
  }

  virtual void RequestSignin(TabContents* tab_contents,
                             const string16& preferred_email,
                             const string16& message,
                             SigninDelegate* delegate) {
    if (should_succeed_) {
      // Simulate valid login.
      username_ = username_after_login_;
      delegate->OnLoginSuccess();

      // Fake a token available notification.
      Profile* profile = tab_contents->profile()->GetOriginalProfile();
      TokenService* token_service = profile->GetTokenService();
      token_service->IssueAuthTokenForTest(GaiaConstants::kGaiaService,
                                           "new_token");
    } else {
      delegate->OnLoginFailure(GoogleServiceAuthError(
        GoogleServiceAuthError::REQUEST_CANCELED));
    }
  }

 private:
  bool should_succeed_;
  std::string username_;
  std::string username_after_login_;
};

class ExtensionWebstorePrivateBrowserTest : public ExtensionBrowserTest {
 public:
  ExtensionWebstorePrivateBrowserTest() {
    test_url_base_ = std::string() + kHttpScheme + kStandardSchemeSeparator +
                     kTestUrlHostname;
  }

  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL, test_url_base_);
  }

  // This generates a regular test server url pointing to a test file at
  // |relative_path|, but replaces the hostname with kTestUrlHostname so that
  // we get the webstore private APIs injected (this happens because of the
  // command line switch we added in SetupCommandLine).
  GURL GetUrl(const std::string& relative_path) {
    GURL base_url = test_server()->GetURL(
        "files/extensions/webstore_private/" + relative_path);
    GURL::Replacements replacements;
    std::string replacement_host = std::string(kTestUrlHostname);
    replacements.SetHostStr(replacement_host);
    return base_url.ReplaceComponents(replacements);
  }

  void RunLoginTestImpl(bool incognito,
                        const std::string& relative_path,
                        const std::string& initial_login,
                        bool login_succeeds,
                        const std::string& login_result) {
    // Clear the token service so previous tests don't affect things.
    TokenService* token_service = browser()->profile()->GetTokenService();
    token_service->ResetCredentialsInMemory();
    if (!initial_login.empty()) {
      // Initialize the token service with an existing token.
      token_service->IssueAuthTokenForTest(GaiaConstants::kGaiaService,
                                           "existing_token");
    }

    FakeProfileSyncService sync_service;
    FakeBrowserSignin signin(login_succeeds, initial_login, login_result);
    WebstorePrivateApi::SetTestingProfileSyncService(&sync_service);
    WebstorePrivateApi::SetTestingBrowserSignin(&signin);

    ExtensionTestMessageListener listener("success", false);
    GURL url = GetUrl(relative_path);
    if (incognito) {
      ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url);
    } else {
      ui_test_utils::NavigateToURL(browser(), url);
    }
    EXPECT_TRUE(listener.WaitUntilSatisfied());

    WebstorePrivateApi::SetTestingBrowserSignin(NULL);
    WebstorePrivateApi::SetTestingProfileSyncService(NULL);
  }

  void RunLoginTest(const std::string& relative_path,
                    const std::string& initial_login,
                    bool login_succeeds,
                    const std::string& login_result) {
    RunLoginTestImpl(true,
                     relative_path,
                     initial_login,
                     login_succeeds,
                     login_result);
    RunLoginTestImpl(false,
                     relative_path,
                     initial_login,
                     login_succeeds,
                     login_result);
  }

 protected:
  std::string test_url_base_;
};

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBrowserTest, BrowserLogin) {
  host_resolver()->AddRule(kTestUrlHostname, "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  RunLoginTest("browser_login/expect_nonempty.html",
               "foo@bar.com", false, "");

  RunLoginTest("browser_login/prompt_no_preferred.html", "", true, "");

  RunLoginTest("browser_login/prompt_preferred.html", "", true, "foo@bar.com");

  RunLoginTest("browser_login/prompt_login_fails.html",
               "", false, "foo@bar.com");
}
<|endoftext|>


<commit_before>
#pragma once

#include <cinttypes>
#include <cstdarg>
#include <cstdio>

#include "LogMessage.hpp"

#include "Werk/OS/Time.hpp"

namespace werk {

class Logger
{
public:

	//Clock used for timestamping messages (may not be real time, e.g. in a simulation)
	Logger(werk::Clock *clock) : _clock(clock) { }
	virtual ~Logger() { }

	const werk::Clock *clock() const { return _clock; }

	virtual void logRaw(LogLevel level, const char *message) = 0;
	virtual void log(LogLevel level, const char *format, ...) = 0;

private:
	werk::Clock *_clock;
};

class SyncLogger : public Logger
{
public:

	SyncLogger(werk::Clock *clock, FILE *file=stdout) :
		Logger(clock), _file(file) { }
	virtual ~SyncLogger() { }

	virtual void log(LogLevel level, const char *format, ...) override {
		va_list args;
		va_start(args, format);
		std::fprintf(_file, "%" PRIu64 " [%10s] ", clock()->time(), logLevels[static_cast<size_t>(level)]);
		std::vfprintf(_file, format, args);
		std::fprintf(_file, "\n");
		va_end(args);
	}
	virtual void logRaw(LogLevel level, const char *rawMessage) override {
		std::fprintf(_file, "%" PRIu64 " [%10s] %s\n", clock()->time(), logLevels[static_cast<size_t>(level)], rawMessage);
	}

private:
	FILE *_file;
};

}
<commit_msg>Null logger<commit_after>
#pragma once

#include <cinttypes>
#include <cstdarg>
#include <cstdio>

#include "LogMessage.hpp"

#include "Werk/OS/Time.hpp"

namespace werk {

class Logger
{
public:

	//Clock used for timestamping messages (may not be real time, e.g. in a simulation)
	Logger(werk::Clock *clock) : _clock(clock) { }
	virtual ~Logger() { }

	const werk::Clock *clock() const { return _clock; }

	virtual void logRaw(LogLevel level, const char *message) = 0;
	virtual void log(LogLevel level, const char *format, ...) = 0;

private:
	werk::Clock *_clock;
};

class NullLogger : public Logger
{
public:

	NullLogger() : Logger(nullptr) { }

	virtual void logRaw(LogLevel /*level*/, const char * /*message*/) override { }
	virtual void log(LogLevel /*level*/, const char * /*format*/, ...) override { }
};

class SyncLogger : public Logger
{
public:

	SyncLogger(werk::Clock *clock, FILE *file=stdout) :
		Logger(clock), _file(file) { }
	virtual ~SyncLogger() { }

	virtual void log(LogLevel level, const char *format, ...) override {
		va_list args;
		va_start(args, format);
		std::fprintf(_file, "%" PRIu64 " [%10s] ", clock()->time(), logLevels[static_cast<size_t>(level)]);
		std::vfprintf(_file, format, args);
		std::fprintf(_file, "\n");
		va_end(args);
	}
	virtual void logRaw(LogLevel level, const char *rawMessage) override {
		std::fprintf(_file, "%" PRIu64 " [%10s] %s\n", clock()->time(), logLevels[static_cast<size_t>(level)], rawMessage);
	}

private:
	FILE *_file;
};

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: undoanim.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-10-19 11:44:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_
#include <com/sun/star/util/XCloneable.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_
#include <com/sun/star/animations/XAnimationNode.hpp>
#endif
#ifndef _SD_CUSTOMANIMATIONCLONER_HXX
#include "CustomAnimationCloner.hxx"
#endif

#include "undoanim.hxx"
#include "glob.hrc"
#include "sdpage.hxx"
#include "sdresid.hxx"
#include "CustomAnimationEffect.hxx"
#include "drawdoc.hxx"

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::util::XCloneable;
using namespace ::com::sun::star::animations;

namespace sd
{

struct UndoAnimationImpl
{
    SdPage*         mpPage;
    Reference< XAnimationNode > mxOldNode;
    Reference< XAnimationNode > mxNewNode;
    bool            mbNewNodeSet;
};

UndoAnimation::UndoAnimation( SdDrawDocument* pDoc, SdPage* pThePage )
: SdrUndoAction( *pDoc ), mpImpl( new UndoAnimationImpl )
{
    mpImpl->mpPage = pThePage;
    mpImpl->mbNewNodeSet = false;

    try
    {
        if( pThePage->mxAnimationNode.is() )
            mpImpl->mxOldNode = ::sd::Clone( pThePage->getAnimationNode() );
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR("sd::UndoAnimation::UndoAnimation(), exception caught!");
    }
}

UndoAnimation::~UndoAnimation()
{
    delete mpImpl;
}

void UndoAnimation::Undo()
{
    try
    {
        if( !mpImpl->mbNewNodeSet )
        {
            if( mpImpl->mpPage->mxAnimationNode.is() )
                mpImpl->mxNewNode.set( ::sd::Clone( mpImpl->mpPage->mxAnimationNode ) );
            mpImpl->mbNewNodeSet = true;
        }

        Reference< XAnimationNode > xOldNode;
        if( mpImpl->mxOldNode.is() )
            xOldNode = ::sd::Clone( mpImpl->mxOldNode );

        mpImpl->mpPage->setAnimationNode( xOldNode );
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR("sd::UndoAnimation::Undo(), exception caught!");
    }
}

void UndoAnimation::Redo()
{
    try
    {
        Reference< XAnimationNode > xNewNode;
        if( mpImpl->mxNewNode.is() )
            xNewNode = ::sd::Clone( mpImpl->mxNewNode );
        mpImpl->mpPage->setAnimationNode( xNewNode );
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR("sd::UndoAnimation::Redo(), exception caught!");
    }
}

void UndoAnimation::Repeat()
{
}

String UndoAnimation::GetComment() const
{
    return String(SdResId(STR_UNDO_ANIMATION));
}

BOOL UndoAnimation::CanRepeat(SfxRepeatTarget&) const
{
    return FALSE;
}

struct UndoTransitionImpl
{
    SdPage*         mpPage;

    sal_Int16 mnNewTransitionType;
    sal_Int16 mnNewTransitionSubtype;
    sal_Bool mbNewTransitionDirection;
    sal_Int32 mnNewTransitionFadeColor;
    double mfNewTransitionDuration;

    sal_Int16 mnOldTransitionType;
    sal_Int16 mnOldTransitionSubtype;
    sal_Bool mbOldTransitionDirection;
    sal_Int32 mnOldTransitionFadeColor;
    double mfOldTransitionDuration;
};

UndoTransition::UndoTransition( SdDrawDocument* pDoc, SdPage* pThePage )
: SdUndoAction( pDoc ), mpImpl( new UndoTransitionImpl )
{
    mpImpl->mpPage = pThePage;

    mpImpl->mnNewTransitionType = -1;
    mpImpl->mnOldTransitionType = pThePage->mnTransitionType;
    mpImpl->mnOldTransitionSubtype = pThePage->mnTransitionSubtype;
    mpImpl->mbOldTransitionDirection = pThePage->mbTransitionDirection;
    mpImpl->mnOldTransitionFadeColor = pThePage->mnTransitionFadeColor;
    mpImpl->mfOldTransitionDuration = pThePage->mfTransitionDuration;
}

UndoTransition::~UndoTransition()
{
    delete mpImpl;
}

void UndoTransition::Undo()
{
    if( mpImpl->mnNewTransitionType == -1 )
    {
        mpImpl->mnNewTransitionType = mpImpl->mpPage->mnTransitionType;
        mpImpl->mnNewTransitionSubtype = mpImpl->mpPage->mnTransitionSubtype;
        mpImpl->mbNewTransitionDirection = mpImpl->mpPage->mbTransitionDirection;
        mpImpl->mnNewTransitionFadeColor = mpImpl->mpPage->mnTransitionFadeColor;
        mpImpl->mfNewTransitionDuration = mpImpl->mpPage->mfTransitionDuration;
    }

    mpImpl->mpPage->mnTransitionType = mpImpl->mnOldTransitionType;
    mpImpl->mpPage->mnTransitionSubtype = mpImpl->mnOldTransitionSubtype;
    mpImpl->mpPage->mbTransitionDirection = mpImpl->mbOldTransitionDirection;
    mpImpl->mpPage->mnTransitionFadeColor = mpImpl->mnOldTransitionFadeColor;
    mpImpl->mpPage->mfTransitionDuration = mpImpl->mfOldTransitionDuration;
}

void UndoTransition::Redo()
{
    mpImpl->mpPage->mnTransitionType = mpImpl->mnNewTransitionType;
    mpImpl->mpPage->mnTransitionSubtype = mpImpl->mnNewTransitionSubtype;
    mpImpl->mpPage->mbTransitionDirection = mpImpl->mbNewTransitionDirection;
    mpImpl->mpPage->mnTransitionFadeColor = mpImpl->mnNewTransitionFadeColor;
    mpImpl->mpPage->mfTransitionDuration = mpImpl->mfNewTransitionDuration;
}

void UndoTransition::Repeat()
{
}

String UndoTransition::GetComment() const
{
    return String(SdResId(STR_UNDO_SLIDE_PARAMS));
}

BOOL UndoTransition::CanRepeat(SfxRepeatTarget&) const
{
    return FALSE;
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.252); FILE MERGED 2006/09/01 17:36:44 kaib 1.9.252.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: undoanim.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:17:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_
#include <com/sun/star/util/XCloneable.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_
#include <com/sun/star/animations/XAnimationNode.hpp>
#endif
#ifndef _SD_CUSTOMANIMATIONCLONER_HXX
#include "CustomAnimationCloner.hxx"
#endif

#include "undoanim.hxx"
#include "glob.hrc"
#include "sdpage.hxx"
#include "sdresid.hxx"
#include "CustomAnimationEffect.hxx"
#include "drawdoc.hxx"

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::util::XCloneable;
using namespace ::com::sun::star::animations;

namespace sd
{

struct UndoAnimationImpl
{
    SdPage*         mpPage;
    Reference< XAnimationNode > mxOldNode;
    Reference< XAnimationNode > mxNewNode;
    bool            mbNewNodeSet;
};

UndoAnimation::UndoAnimation( SdDrawDocument* pDoc, SdPage* pThePage )
: SdrUndoAction( *pDoc ), mpImpl( new UndoAnimationImpl )
{
    mpImpl->mpPage = pThePage;
    mpImpl->mbNewNodeSet = false;

    try
    {
        if( pThePage->mxAnimationNode.is() )
            mpImpl->mxOldNode = ::sd::Clone( pThePage->getAnimationNode() );
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR("sd::UndoAnimation::UndoAnimation(), exception caught!");
    }
}

UndoAnimation::~UndoAnimation()
{
    delete mpImpl;
}

void UndoAnimation::Undo()
{
    try
    {
        if( !mpImpl->mbNewNodeSet )
        {
            if( mpImpl->mpPage->mxAnimationNode.is() )
                mpImpl->mxNewNode.set( ::sd::Clone( mpImpl->mpPage->mxAnimationNode ) );
            mpImpl->mbNewNodeSet = true;
        }

        Reference< XAnimationNode > xOldNode;
        if( mpImpl->mxOldNode.is() )
            xOldNode = ::sd::Clone( mpImpl->mxOldNode );

        mpImpl->mpPage->setAnimationNode( xOldNode );
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR("sd::UndoAnimation::Undo(), exception caught!");
    }
}

void UndoAnimation::Redo()
{
    try
    {
        Reference< XAnimationNode > xNewNode;
        if( mpImpl->mxNewNode.is() )
            xNewNode = ::sd::Clone( mpImpl->mxNewNode );
        mpImpl->mpPage->setAnimationNode( xNewNode );
    }
    catch( Exception& e )
    {
        (void)e;
        DBG_ERROR("sd::UndoAnimation::Redo(), exception caught!");
    }
}

void UndoAnimation::Repeat()
{
}

String UndoAnimation::GetComment() const
{
    return String(SdResId(STR_UNDO_ANIMATION));
}

BOOL UndoAnimation::CanRepeat(SfxRepeatTarget&) const
{
    return FALSE;
}

struct UndoTransitionImpl
{
    SdPage*         mpPage;

    sal_Int16 mnNewTransitionType;
    sal_Int16 mnNewTransitionSubtype;
    sal_Bool mbNewTransitionDirection;
    sal_Int32 mnNewTransitionFadeColor;
    double mfNewTransitionDuration;

    sal_Int16 mnOldTransitionType;
    sal_Int16 mnOldTransitionSubtype;
    sal_Bool mbOldTransitionDirection;
    sal_Int32 mnOldTransitionFadeColor;
    double mfOldTransitionDuration;
};

UndoTransition::UndoTransition( SdDrawDocument* pDoc, SdPage* pThePage )
: SdUndoAction( pDoc ), mpImpl( new UndoTransitionImpl )
{
    mpImpl->mpPage = pThePage;

    mpImpl->mnNewTransitionType = -1;
    mpImpl->mnOldTransitionType = pThePage->mnTransitionType;
    mpImpl->mnOldTransitionSubtype = pThePage->mnTransitionSubtype;
    mpImpl->mbOldTransitionDirection = pThePage->mbTransitionDirection;
    mpImpl->mnOldTransitionFadeColor = pThePage->mnTransitionFadeColor;
    mpImpl->mfOldTransitionDuration = pThePage->mfTransitionDuration;
}

UndoTransition::~UndoTransition()
{
    delete mpImpl;
}

void UndoTransition::Undo()
{
    if( mpImpl->mnNewTransitionType == -1 )
    {
        mpImpl->mnNewTransitionType = mpImpl->mpPage->mnTransitionType;
        mpImpl->mnNewTransitionSubtype = mpImpl->mpPage->mnTransitionSubtype;
        mpImpl->mbNewTransitionDirection = mpImpl->mpPage->mbTransitionDirection;
        mpImpl->mnNewTransitionFadeColor = mpImpl->mpPage->mnTransitionFadeColor;
        mpImpl->mfNewTransitionDuration = mpImpl->mpPage->mfTransitionDuration;
    }

    mpImpl->mpPage->mnTransitionType = mpImpl->mnOldTransitionType;
    mpImpl->mpPage->mnTransitionSubtype = mpImpl->mnOldTransitionSubtype;
    mpImpl->mpPage->mbTransitionDirection = mpImpl->mbOldTransitionDirection;
    mpImpl->mpPage->mnTransitionFadeColor = mpImpl->mnOldTransitionFadeColor;
    mpImpl->mpPage->mfTransitionDuration = mpImpl->mfOldTransitionDuration;
}

void UndoTransition::Redo()
{
    mpImpl->mpPage->mnTransitionType = mpImpl->mnNewTransitionType;
    mpImpl->mpPage->mnTransitionSubtype = mpImpl->mnNewTransitionSubtype;
    mpImpl->mpPage->mbTransitionDirection = mpImpl->mbNewTransitionDirection;
    mpImpl->mpPage->mnTransitionFadeColor = mpImpl->mnNewTransitionFadeColor;
    mpImpl->mpPage->mfTransitionDuration = mpImpl->mfNewTransitionDuration;
}

void UndoTransition::Repeat()
{
}

String UndoTransition::GetComment() const
{
    return String(SdResId(STR_UNDO_SLIDE_PARAMS));
}

BOOL UndoTransition::CanRepeat(SfxRepeatTarget&) const
{
    return FALSE;
}

}
<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup foundationDataspaceLib
 *
 * @brief The #SpeedDataspace converts between different measurement untis describing velocity.
 *
 * @details The neutral unit of the speed dataspace is _m/s_.
 *
 * @authors Nils Peters, Trond Lossius, Tim Peters, ...
 *
 * @copyright Copyright © 2011 by Nils Peters @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "SpeedDataspace.h"

/*************************************************************************/

#pragma mark -
#pragma mark MilesPerHourUnit unit

#define thisTTClass			MilesPerHourUnit
#define thisTTClassName		"unit.milesPerHour"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

MilesPerHourUnit::~MilesPerHourUnit(){;}

void MilesPerHourUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 0.44704;
}

void MilesPerHourUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 2.236936;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark KilometerPerHourUnit unit

#define thisTTClass			KilometerPerHourUnit
#define thisTTClassName		"unit.kilometerPerHour"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

KilometerPerHourUnit::~KilometerPerHourUnit(){;}

void KilometerPerHourUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) / 3.6;
}

void KilometerPerHourUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 3.6;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark FootPerSecondUnit unit

#define thisTTClass			FootPerSecondUnit
#define thisTTClassName		"unit.footPerSecond"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

FootPerSecondUnit::~FootPerSecondUnit(){;}

void FootPerSecondUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 0.3048;
}

void FootPerSecondUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 3.2808399;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark KnotUnit unit

#define thisTTClass			KnotUnit
#define thisTTClassName		"unit.knot"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

KnotUnit::~KnotUnit(){;}

void KnotUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 0.514444; //not exact
}

void KnotUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 1.943844;//not exact
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark MeterPerSecondUnit unit

#define thisTTClass			MeterPerSecondUnit
#define thisTTClassName		"unit.meterPerSecond"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

MeterPerSecondUnit::~MeterPerSecondUnit(){;}

void MeterPerSecondUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = input;
}

void MeterPerSecondUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = input;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark SpeedDataspace

#define thisTTClass			SpeedDataspace
#define thisTTClassName		"dataspace.speed"
#define thisTTClassTags		"foundationDataspaceLib, dataspace, speed"

TT_OBJECT_CONSTRUCTOR
{
	// Create one of each kind of unit, and cache them in a hash
	registerUnit(TT("unit.milesPerHour"),			TT("mph"));
	registerUnit(TT("unit.milesPerHour"),			TT("mi/h"));
	registerUnit(TT("unit.kilometerPerHour"),		TT("km/h"));
	registerUnit(TT("unit.kilometerPerHour"),		TT("kmph"));
	registerUnit(TT("unit.meterPerSecond"),			TT("m/s"));
	registerUnit(TT("unit.knot"),					TT("kn"));
	registerUnit(TT("unit.footPerSecond"),			TT("ft/s"));
	registerUnit(TT("unit.footPerSecond"),			TT("fps"));
	// Set our neutral unit (the unit through which all conversions are made)
	neutralUnit = TT("m/s");

	// Now that the cache is created, we can create a set of default units
	setInputUnit(neutralUnit);
	setOutputUnit(neutralUnit);
}

SpeedDataspace::~SpeedDataspace()
{
	;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags
<commit_msg>DataspaceLib: Removing “fps” unit from Speed dataspace, use “ft/s” instead.<commit_after>/** @file
 *
 * @ingroup foundationDataspaceLib
 *
 * @brief The #SpeedDataspace converts between different measurement untis describing velocity.
 *
 * @details The neutral unit of the speed dataspace is _m/s_.
 *
 * @authors Nils Peters, Trond Lossius, Tim Peters, ...
 *
 * @copyright Copyright © 2011 by Nils Peters @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "SpeedDataspace.h"

/*************************************************************************/

#pragma mark -
#pragma mark MilesPerHourUnit unit

#define thisTTClass			MilesPerHourUnit
#define thisTTClassName		"unit.milesPerHour"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

MilesPerHourUnit::~MilesPerHourUnit(){;}

void MilesPerHourUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 0.44704;
}

void MilesPerHourUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 2.236936;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark KilometerPerHourUnit unit

#define thisTTClass			KilometerPerHourUnit
#define thisTTClassName		"unit.kilometerPerHour"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

KilometerPerHourUnit::~KilometerPerHourUnit(){;}

void KilometerPerHourUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) / 3.6;
}

void KilometerPerHourUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 3.6;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark FootPerSecondUnit unit

#define thisTTClass			FootPerSecondUnit
#define thisTTClassName		"unit.footPerSecond"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

FootPerSecondUnit::~FootPerSecondUnit(){;}

void FootPerSecondUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 0.3048;
}

void FootPerSecondUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 3.2808399;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark KnotUnit unit

#define thisTTClass			KnotUnit
#define thisTTClassName		"unit.knot"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

KnotUnit::~KnotUnit(){;}

void KnotUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 0.514444; //not exact
}

void KnotUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = TTFloat64(input) * 1.943844;//not exact
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark MeterPerSecondUnit unit

#define thisTTClass			MeterPerSecondUnit
#define thisTTClassName		"unit.meterPerSecond"
#define thisTTClassTags		"dataspace.unit, speed"

TT_OBJECT_CONSTRUCTOR,
TTDataspaceUnit(arguments)
{;}

MeterPerSecondUnit::~MeterPerSecondUnit(){;}

void MeterPerSecondUnit::convertToNeutral(const TTValue& input, TTValue& output)
{
	output = input;
}

void MeterPerSecondUnit::convertFromNeutral(const TTValue& input, TTValue& output)
{
	output = input;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags

/***********************************************************************************************/

#pragma mark -
#pragma mark SpeedDataspace

#define thisTTClass			SpeedDataspace
#define thisTTClassName		"dataspace.speed"
#define thisTTClassTags		"foundationDataspaceLib, dataspace, speed"

TT_OBJECT_CONSTRUCTOR
{
	// Create one of each kind of unit, and cache them in a hash
	registerUnit(TT("unit.milesPerHour"),			TT("mph"));
	registerUnit(TT("unit.milesPerHour"),			TT("mi/h"));
	registerUnit(TT("unit.kilometerPerHour"),		TT("km/h"));
	registerUnit(TT("unit.kilometerPerHour"),		TT("kmph"));
	registerUnit(TT("unit.meterPerSecond"),			TT("m/s"));
	registerUnit(TT("unit.knot"),					TT("kn"));
	registerUnit(TT("unit.footPerSecond"),			TT("ft/s"));
	// Set our neutral unit (the unit through which all conversions are made)
	neutralUnit = TT("m/s");

	// Now that the cache is created, we can create a set of default units
	setInputUnit(neutralUnit);
	setOutputUnit(neutralUnit);
}

SpeedDataspace::~SpeedDataspace()
{
	;
}

#undef thisTTClass
#undef thisTTClassName
#undef thisTTClassTags
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkNavigationDataTransformFilter.h"

mitk::NavigationDataTransformFilter::NavigationDataTransformFilter()
: mitk::NavigationDataToNavigationDataFilter()
{
  m_Transform = NULL;

  //transform to rotate orientation
  m_QuatOrgRigidTransform = itk::QuaternionRigidTransform<double>::New();
  m_QuatTmpTransform = itk::QuaternionRigidTransform<double>::New();
}

mitk::NavigationDataTransformFilter::~NavigationDataTransformFilter()
{
  m_Transform = NULL;
}

void mitk::NavigationDataTransformFilter::SetRigid3DTransform( TransformType::Pointer transform )
{
  m_Transform = transform;
  this->Modified();
}

void mitk::NavigationDataTransformFilter::GenerateData()
{

  // only update data if m_Transform was set
  if(m_Transform.IsNull())
  {
    itkExceptionMacro("Invalid parameter: Transform was not set!  Use SetRigid3DTransform() before updating the filter.");
    return;
  }
  else
  {
    this->CreateOutputsForAllInputs(); // make sure that we have the same number of outputs as inputs

    /* update outputs with tracking data from tools */
    for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs() ; ++i)
    {
      mitk::NavigationData* output = this->GetOutput(i);
      assert(output);
      const mitk::NavigationData* input = this->GetInput(i);
      assert(input);

      if (input->IsDataValid() == false)
      {
        output->SetDataValid(false);
        continue;
      }

      mitk::NavigationData::PositionType tempCoordinateIn, tempCoordinateOut;
      tempCoordinateIn = input->GetPosition();

      itk::Point<float,3> itkPointIn, itkPointOut;
      itkPointIn[0] = tempCoordinateIn[0];
      itkPointIn[1] = tempCoordinateIn[1];
      itkPointIn[2] = tempCoordinateIn[2];

      //do the transform
      itkPointOut = m_Transform->TransformPoint( itkPointIn );

      tempCoordinateOut[0] = itkPointOut[0];
      tempCoordinateOut[1] = itkPointOut[1];
      tempCoordinateOut[2] = itkPointOut[2];

      output->Graft(input); // First, copy all information from input to output
      output->SetPosition(tempCoordinateOut);// Then change the member(s): add new position of navigation data after tranformation
      output->SetDataValid(true); // operation was successful, therefore data of output is valid.

      //---transform orientation
      NavigationData::OrientationType  quatIn = input->GetOrientation();
      vnl_quaternion<double> const vnlQuatIn(quatIn.x(), quatIn.y(), quatIn.z(), quatIn.r());

      TransformType::MatrixType rotMatrixD = m_Transform->GetMatrix();

      vnl_quaternion<double> vnlQ = vnl_quaternion<double>(rotMatrixD.GetVnlMatrix());

      m_QuatOrgRigidTransform->SetRotation(vnlQ);
      m_QuatTmpTransform->SetRotation(vnlQuatIn);
      m_QuatTmpTransform->Compose(m_QuatOrgRigidTransform,false);

      vnl_quaternion<double> vnlQuatOut = m_QuatTmpTransform->GetRotation();
      NavigationData::OrientationType quatOut(vnlQuatOut[0], vnlQuatOut[1], vnlQuatOut[2], vnlQuatOut[3]);

      output->SetOrientation(quatOut);

    }
  }
}

<commit_msg>First errors due to the quaternion problem fixed. As in bug 15021, there is no need to do the workaround with a quaternion<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkNavigationDataTransformFilter.h"

mitk::NavigationDataTransformFilter::NavigationDataTransformFilter()
: mitk::NavigationDataToNavigationDataFilter()
{
  m_Transform = NULL;

  //transform to rotate orientation
  m_QuatOrgRigidTransform = itk::QuaternionRigidTransform<double>::New();
  m_QuatTmpTransform = itk::QuaternionRigidTransform<double>::New();
}

mitk::NavigationDataTransformFilter::~NavigationDataTransformFilter()
{
  m_Transform = NULL;
}

void mitk::NavigationDataTransformFilter::SetRigid3DTransform( TransformType::Pointer transform )
{
  m_Transform = transform;
  this->Modified();
}

void mitk::NavigationDataTransformFilter::GenerateData()
{

  // only update data if m_Transform was set
  if(m_Transform.IsNull())
  {
    itkExceptionMacro("Invalid parameter: Transform was not set!  Use SetRigid3DTransform() before updating the filter.");
    return;
  }
  else
  {
    this->CreateOutputsForAllInputs(); // make sure that we have the same number of outputs as inputs

    /* update outputs with tracking data from tools */
    for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs() ; ++i)
    {
      mitk::NavigationData* output = this->GetOutput(i);
      assert(output);
      const mitk::NavigationData* input = this->GetInput(i);
      assert(input);

      if (input->IsDataValid() == false)
      {
        output->SetDataValid(false);
        continue;
      }

      mitk::NavigationData::PositionType tempCoordinateIn, tempCoordinateOut;
      tempCoordinateIn = input->GetPosition();

      itk::Point<float,3> itkPointIn, itkPointOut;
      itkPointIn[0] = tempCoordinateIn[0];
      itkPointIn[1] = tempCoordinateIn[1];
      itkPointIn[2] = tempCoordinateIn[2];

      //do the transform
      itkPointOut = m_Transform->TransformPoint( itkPointIn );

      tempCoordinateOut[0] = itkPointOut[0];
      tempCoordinateOut[1] = itkPointOut[1];
      tempCoordinateOut[2] = itkPointOut[2];

      output->Graft(input); // First, copy all information from input to output
      output->SetPosition(tempCoordinateOut);// Then change the member(s): add new position of navigation data after tranformation
      output->SetDataValid(true); // operation was successful, therefore data of output is valid.

      //---transform orientation
      NavigationData::OrientationType  quatIn = input->GetOrientation();
      vnl_quaternion<double> const vnlQuatIn(quatIn.x(), quatIn.y(), quatIn.z(), quatIn.r());

      TransformType::MatrixType rotMatrixD = m_Transform->GetMatrix();

      //vnl_quaternion<double> vnlQ = vnl_quaternion<double>(rotMatrixD.GetVnlMatrix());

      //m_QuatOrgRigidTransform->SetRotation(vnlQ);
      m_QuatOrgRigidTransform->SetMatrix(rotMatrixD);//SetRotation(vnlQ);
      m_QuatTmpTransform->SetRotation(vnlQuatIn);
      m_QuatTmpTransform->Compose(m_QuatOrgRigidTransform,false);

      vnl_quaternion<double> vnlQuatOut = m_QuatTmpTransform->GetRotation();
      NavigationData::OrientationType quatOut(vnlQuatOut[0], vnlQuatOut[1], vnlQuatOut[2], vnlQuatOut[3]);

      output->SetOrientation(quatOut);

    }
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef ACCESS_LOG_DATAGRAM_HXX
#define ACCESS_LOG_DATAGRAM_HXX

#include "http/Method.h"
#include "http/Status.h"
#include "util/StringView.hxx"

#include <chrono>

#include <stdint.h>

struct AccessLogDatagram {
    uint64_t timestamp;

    const char *remote_host, *host, *site;

    http_method_t http_method;

    const char *http_uri, *http_referer, *user_agent;

    StringView message;

    http_status_t http_status;

    uint64_t length;

    uint64_t traffic_received, traffic_sent;

    uint64_t duration;

    bool valid_timestamp, valid_http_method, valid_http_status;
    bool valid_length, valid_traffic;
    bool valid_duration;

    AccessLogDatagram() = default;

    AccessLogDatagram(std::chrono::system_clock::time_point _timestamp,
                      http_method_t _method, const char *_uri,
                      const char *_remote_host,
                      const char *_host, const char *_site,
                      const char *_referer, const char *_user_agent,
                      http_status_t _status, int64_t _length,
                      uint64_t _traffic_received, uint64_t _traffic_sent,
                      std::chrono::steady_clock::duration _duration)
        :timestamp(std::chrono::duration_cast<std::chrono::microseconds>(_timestamp.time_since_epoch()).count()),
         remote_host(_remote_host), host(_host), site(_site),
         http_method(_method),
         http_uri(_uri), http_referer(_referer), user_agent(_user_agent),
         message(nullptr),
         http_status(_status),
         length(_length),
         traffic_received(_traffic_received), traffic_sent(_traffic_sent),
         duration(std::chrono::duration_cast<std::chrono::microseconds>(_duration).count()),
         valid_timestamp(true),
         valid_http_method(true), valid_http_status(true),
         valid_length(_length >= 0), valid_traffic(true),
         valid_duration(true) {}

    explicit AccessLogDatagram(StringView _message)
        :remote_host(nullptr), host(nullptr), site(nullptr),
         http_uri(nullptr), http_referer(nullptr), user_agent(nullptr),
         message(_message),
         valid_timestamp(false),
         valid_http_method(false), valid_http_status(false),
         valid_length(false), valid_traffic(false),
         valid_duration(false) {}
};

#endif
<commit_msg>access_log/Datagram: move std::chrono conversion code to ExportTimestamp()<commit_after>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef ACCESS_LOG_DATAGRAM_HXX
#define ACCESS_LOG_DATAGRAM_HXX

#include "http/Method.h"
#include "http/Status.h"
#include "util/StringView.hxx"

#include <chrono>

#include <stdint.h>

struct AccessLogDatagram {
    uint64_t timestamp;

    const char *remote_host, *host, *site;

    http_method_t http_method;

    const char *http_uri, *http_referer, *user_agent;

    StringView message;

    http_status_t http_status;

    uint64_t length;

    uint64_t traffic_received, traffic_sent;

    uint64_t duration;

    bool valid_timestamp, valid_http_method, valid_http_status;
    bool valid_length, valid_traffic;
    bool valid_duration;

    AccessLogDatagram() = default;

    AccessLogDatagram(std::chrono::system_clock::time_point _timestamp,
                      http_method_t _method, const char *_uri,
                      const char *_remote_host,
                      const char *_host, const char *_site,
                      const char *_referer, const char *_user_agent,
                      http_status_t _status, int64_t _length,
                      uint64_t _traffic_received, uint64_t _traffic_sent,
                      std::chrono::steady_clock::duration _duration)
        :timestamp(ExportTimestamp(_timestamp)),
         remote_host(_remote_host), host(_host), site(_site),
         http_method(_method),
         http_uri(_uri), http_referer(_referer), user_agent(_user_agent),
         message(nullptr),
         http_status(_status),
         length(_length),
         traffic_received(_traffic_received), traffic_sent(_traffic_sent),
         duration(std::chrono::duration_cast<std::chrono::microseconds>(_duration).count()),
         valid_timestamp(true),
         valid_http_method(true), valid_http_status(true),
         valid_length(_length >= 0), valid_traffic(true),
         valid_duration(true) {}

    explicit AccessLogDatagram(StringView _message)
        :remote_host(nullptr), host(nullptr), site(nullptr),
         http_uri(nullptr), http_referer(nullptr), user_agent(nullptr),
         message(_message),
         valid_timestamp(false),
         valid_http_method(false), valid_http_status(false),
         valid_length(false), valid_traffic(false),
         valid_duration(false) {}

    static constexpr uint64_t ExportTimestamp(std::chrono::system_clock::time_point t) noexcept {
        return std::chrono::duration_cast<std::chrono::microseconds>(t.time_since_epoch()).count();
    }
};

#endif
<|endoftext|>


<commit_before>
int *global_ptr;
const char *global_string = "hello, world";

void test1(int *ptr, int &ref)
{
	const char *str;
	int v, *p;
	char c;

	v = *ptr; // `ptr` dereferenced
	v = ptr[0]; // `ptr` dereferenced
	p = ptr;

	*ptr = 0; // `ptr` dereferenced
	ptr[0] = 0; // `ptr` dereferenced
	ptr = 0;

	(*ptr)++; // `ptr` dereferenced
	*(ptr++); // `ptr++` dereferenced
	ptr++;

	v = ref; // (`ref` implicitly dereferenced, not detected)
	p = &ref;
	ref = 0; // (`ref` implicitly dereferenced, not detected)
	ref++; // (`ref` implicitly dereferenced, not detected)

	*global_ptr; // `global_ptr` dereferenced
	str = global_string;
	c = global_string[5]; // `global_string` dereferenced
}

struct myStruct
{
	int x;
	void f() {};
	void (*g)();
};

void test1(myStruct *ms)
{
	void (*h)();

	ms;
	ms->x; // `ms` dereferenced
	ms->f(); // `ms` dereferenced
	ms->g(); // `ms` dereferenced
	h = ms->g; // `ms` dereferenced
}
<commit_msg>Update cpp/ql/test/library-tests/controlflow/dereferenced/dereferenced.cpp<commit_after>
int *global_ptr;
const char *global_string = "hello, world";

void test1(int *ptr, int &ref)
{
	const char *str;
	int v, *p;
	char c;

	v = *ptr; // `ptr` dereferenced
	v = ptr[0]; // `ptr` dereferenced
	p = ptr;

	*ptr = 0; // `ptr` dereferenced
	ptr[0] = 0; // `ptr` dereferenced
	ptr = 0;

	(*ptr)++; // `ptr`, `*ptr` dereferenced
	*(ptr++); // `ptr++` dereferenced
	ptr++;

	v = ref; // (`ref` implicitly dereferenced, not detected)
	p = &ref;
	ref = 0; // (`ref` implicitly dereferenced, not detected)
	ref++; // (`ref` implicitly dereferenced, not detected)

	*global_ptr; // `global_ptr` dereferenced
	str = global_string;
	c = global_string[5]; // `global_string` dereferenced
}

struct myStruct
{
	int x;
	void f() {};
	void (*g)();
};

void test1(myStruct *ms)
{
	void (*h)();

	ms;
	ms->x; // `ms` dereferenced
	ms->f(); // `ms` dereferenced
	ms->g(); // `ms` dereferenced
	h = ms->g; // `ms` dereferenced
}
<|endoftext|>


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

#include <cctype>
#include <sstream>
#include "as/serial_value/xml.hpp"

#define ASMITH_SERIAL_PTR "as::serial_value::pointer_t="
#define ASMITH_SERIAL_XML "__as_serial_xml_element"

bool write_attribute(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {
	//! \todo Remove chars illegal in XML
	switch (aValue.get_type()) {
	case as::serial_value::NULL_T:
		aStream << aName << '=' << '"' << "null" << '"';
		return true;
	case as::serial_value::CHAR_T:
		aStream << aName << '=' << '"' << aValue.get_char() << '"';
		return true;
	case as::serial_value::BOOL_T:
		aStream << aName << '=' << '"' << (aValue.get_bool() ? "true" : "false") << '"';
		return true;
	case as::serial_value::UNSIGNED_T:
		aStream << aName << '=' << '"' << aValue.get_unsigned() << '"';
		return true;
	case as::serial_value::SIGNED_T:
		aStream << aName << '=' << '"' << aValue.get_signed() << '"';
		return true;
	case as::serial_value::FLOAT_T:
		aStream << aName << '=' << '"' << aValue.get_float() << '"';
		return true;
	case as::serial_value::POINTER_T:
		aStream << aName << '=' << '"' << ASMITH_SERIAL_PTR  << aValue.get_pointer() << '"';
		return true;
	case as::serial_value::STRING_T:
		aStream << aName << '=' << '"' << aValue.get_string() << '"';
		return true;
	default:
		return false;
	}
}

void write_element(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {
	//! \todo Remove chars illegal in XML
	switch (aValue.get_type()) {
	case as::serial_value::NULL_T:
		aStream << '<' << aName << '/' << '>';
		break;
	case as::serial_value::CHAR_T:
		aStream << '<' << aName << '>' << aValue.get_char() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::BOOL_T:
		aStream << '<' << aName << '>' << (aValue.get_bool() ? "true" : "false") << '<' << '/' << aName << '>';
		break;
	case as::serial_value::UNSIGNED_T:
		aStream << '<' << aName << '>' << aValue.get_unsigned() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::SIGNED_T:
		aStream << '<' << aName << '>' << aValue.get_signed() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::FLOAT_T:
		aStream << '<' << aName << '>' << aValue.get_float() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::POINTER_T:
		aStream << '<' << aName << '>' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::STRING_T:
		aStream << '<' << aName << '>' << aValue.get_string() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::ARRAY_T:
		{
			aStream << '<' << aName << '>';
			const as::serial_value::array_t& array_ = aValue.get_array();
			const size_t s = array_.size();
			for(size_t i = 0; i < s; ++i) write_element(aStream, std::to_string(i), array_[i]);
			aStream << '<' << '/' << aName << '>';
		}
		break;
	case as::serial_value::OBJECT_T:
		{
			const as::serial_value::object_t& object = aValue.get_object();
			aStream << '<' << aName;
			size_t attributes = 0;
			for(const auto& i : object) {
				const as::serial_value::type t = i.second.get_type();
				if(t != as::serial_value::ARRAY_T && t != as::serial_value::OBJECT_T) {
					write_attribute(aStream, i.first, i.second);
					++attributes;
				}
			}

			if(attributes == object.size()) {
				aStream << '/' << '>';
			}else {
				aStream << '>';
				for(const auto& i : object) {
					const as::serial_value::type t = i.second.get_type();
					if(t == as::serial_value::ARRAY_T || t == as::serial_value::OBJECT_T) {
						write_element(aStream, i.first, i.second);
						++attributes;
					}
				}
				aStream << '<' << '/' << aName << '>';
			}
		}
		break;
	}
}

struct element {
	std::string name;
	std::string body;
	std::map<std::string, std::string> attributes;
	std::vector<element> elements;
};

void ignore_whitespace_x(std::istream& aStream) {
	char c = aStream.peek();
	while (std::isspace(c)) {
		aStream >> c;
		c = aStream.peek();
	}
}

void close_closing_tag(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c;
	aStream >> c;
	if(c != '>') throw std::runtime_error("as::deserialise_xml : Expected closing tag to end with '>'");
}

void read_closing_name(std::istream& aStream, element& e) {
	char c;
	ignore_whitespace_x(aStream);
	c = aStream.peek();
	std::string name;
	while(c != '>' && ! std::isspace(c)) {
		name += c;
		aStream >> c;
		c = aStream.peek();
	}
	if(name != e.name) throw std::runtime_error("as::deserialise_xml : Expected closing tag to have same name as opening tag");
	// Next state
	close_closing_tag(aStream, e);
}

void open_closing_tag(std::istream& aStream, element& e) {
	read_closing_name(aStream, e);
	char c;
	aStream >> c;
	if(c != '<') throw std::runtime_error("as::deserialise_xml : Expected closing tag to begin with '</'");
	aStream >> c;
	if(c != '/') throw std::runtime_error("as::deserialise_xml : Expected closing tag to begin with '</'");
	// Next state
	read_closing_name(aStream, e);
}

void open_opening_tag(std::istream&, element&);

void read_elements(std::istream& aStream, element& e) {
	const auto pos = aStream.tellg();
	char c;
	c = aStream.peek();
	if(c != '<') throw std::runtime_error("as::deserialise_xml : Expected element to begin with '<'");
	c = aStream.peek();
	aStream.seekg(pos);
	if(c == '/') {
		// Closing tag of e
		aStream.seekg(pos);
	}else {
		element e2;
		open_opening_tag(aStream, e2);
		e.elements.push_back(e2);
		// Next state
		read_elements(aStream, e);
	}
}

void read_body(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c;

	c = aStream.peek();
	if(c == '<') {
		read_elements(aStream, e);
	}else {
		 while (c != '<') {
			 e.body += c;
			 aStream >> c;
			 c = aStream.peek();
		 }
	}

	// Next state
	open_closing_tag(aStream, e);
}

void close_opening_tag(std::istream&, element&);

void read_attribute(std::istream& aStream, element& e) {
	std::string name;
	std::string value;
	char c;

	// Read name
	ignore_whitespace_x(aStream);
	aStream >> c;
	while(c != '='){
		name += c;
		aStream >> c;
	}

	// Read value
	ignore_whitespace_x(aStream);
	aStream >> c;
	if(c != '"') throw std::runtime_error("as::deserialise_xml : Expected attribute value to begin with '\"'");
	aStream >> c;
	while(c != '"') {
		value += c;
		aStream >> c;
	}

	// Next state
	e.attributes.emplace(name, value);
	close_opening_tag(aStream, e);
}

void close_opening_tag(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c = aStream.peek();
	if(c == '/') {
		// End element
		aStream >> c;
		aStream >> c;
		if(c != '>') throw std::runtime_error("as::deserialise_xml : Expected closing tag to end with '>'");
	}else if (c == '>') {
		// Next state
		read_body(aStream, e);
	}else {
		read_attribute(aStream, e);
	}
}

void read_opening_tag_name(std::istream& aStream, element& e) {
	char c;
	ignore_whitespace_x(aStream);
	c = aStream.peek();
	while(c != '>' && c != '/' && !std::isspace(c)) {
		e.name += c;
		aStream >> c;
		c = aStream.peek();
	}
	// Next state
	close_opening_tag(aStream, e);
}

void open_opening_tag(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c;
	aStream >> c;
	if(c != '<') throw std::runtime_error("as::deserialise_xml : Expected opening tag to begin with '<'");
	// Next state
	read_opening_tag_name(aStream, e);
}

as::serial_value convert_element(const element& aElement) {
	// Check if array
	size_t contiguousNames = 0;
	const size_t eCount = aElement.elements.size();
	for(size_t i = 0; i < eCount; ++i) if(aElement.elements[i].name == std::to_string(i)) ++contiguousNames;
	if(eCount > 0 && contiguousNames == eCount) {
		// Element is an array
		as::serial_value tmp;
		as::serial_value::array_t& array_ = tmp.set_array();
		for(size_t i = 0; i < eCount; ++i) array_.push_back(convert_element(aElement.elements[i]));
		return tmp;
	}

	// Check if value
	if(aElement.elements.empty() && aElement.attributes.empty()) {
		// Element is a value
		if(aElement.body.empty()) return as::serial_value();
		else return as::serial_value(aElement.body);
	}

	// Element is an object
	as::serial_value tmp;
	as::serial_value::object_t& object = tmp.set_object();
	if(! aElement.body.empty()) {
		//! \todo Handle body
	}
	for(const auto& i : aElement.attributes) {
		object.emplace(i.first, as::serial_value(i.second));
	}
	for(const auto& i : aElement.elements) {
		//! \todo Handle for name conflicts
		object.emplace(i.name, convert_element(i));
	}
	return tmp;
}

namespace as {
	void serialise_xml(std::ostream& aStream, const serial_value& aValue) {
		write_element(aStream, ASMITH_SERIAL_XML, aValue);
	}

	serial_value deserialise_xml(std::istream& aStream) {
		//! \todo Handle XML header
		//! \todo Handle XML comments
		element e;
		open_opening_tag(aStream, e);
		return convert_element(e);
	}

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

#include <cctype>
#include <sstream>
#include "as/serial_value/xml.hpp"

#define ASMITH_SERIAL_PTR "as::serial_value::pointer_t="
#define ASMITH_SERIAL_XML "__as_serial_xml_element"

bool write_attribute(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {
	//! \todo Remove chars illegal in XML
	switch (aValue.get_type()) {
	case as::serial_value::NULL_T:
		aStream << aName << '=' << '"' << "null" << '"';
		return true;
	case as::serial_value::CHAR_T:
		aStream << aName << '=' << '"' << aValue.get_char() << '"';
		return true;
	case as::serial_value::BOOL_T:
		aStream << aName << '=' << '"' << (aValue.get_bool() ? "true" : "false") << '"';
		return true;
	case as::serial_value::UNSIGNED_T:
		aStream << aName << '=' << '"' << aValue.get_unsigned() << '"';
		return true;
	case as::serial_value::SIGNED_T:
		aStream << aName << '=' << '"' << aValue.get_signed() << '"';
		return true;
	case as::serial_value::FLOAT_T:
		aStream << aName << '=' << '"' << aValue.get_float() << '"';
		return true;
	case as::serial_value::POINTER_T:
		aStream << aName << '=' << '"' << ASMITH_SERIAL_PTR  << aValue.get_pointer() << '"';
		return true;
	case as::serial_value::STRING_T:
		aStream << aName << '=' << '"' << aValue.get_string() << '"';
		return true;
	default:
		return false;
	}
}

void write_element(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {
	//! \todo Remove chars illegal in XML
	switch (aValue.get_type()) {
	case as::serial_value::NULL_T:
		aStream << '<' << aName << '/' << '>';
		break;
	case as::serial_value::CHAR_T:
		aStream << '<' << aName << '>' << aValue.get_char() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::BOOL_T:
		aStream << '<' << aName << '>' << (aValue.get_bool() ? "true" : "false") << '<' << '/' << aName << '>';
		break;
	case as::serial_value::UNSIGNED_T:
		aStream << '<' << aName << '>' << aValue.get_unsigned() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::SIGNED_T:
		aStream << '<' << aName << '>' << aValue.get_signed() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::FLOAT_T:
		aStream << '<' << aName << '>' << aValue.get_float() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::POINTER_T:
		aStream << '<' << aName << '>' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::STRING_T:
		aStream << '<' << aName << '>' << aValue.get_string() << '<' << '/' << aName << '>';
		break;
	case as::serial_value::ARRAY_T:
		{
			aStream << '<' << aName << '>';
			const as::serial_value::array_t& array_ = aValue.get_array();
			const size_t s = array_.size();
			for(size_t i = 0; i < s; ++i) write_element(aStream, std::to_string(i), array_[i]);
			aStream << '<' << '/' << aName << '>';
		}
		break;
	case as::serial_value::OBJECT_T:
		{
			const as::serial_value::object_t& object = aValue.get_object();
			aStream << '<' << aName;
			size_t attributes = 0;
			for(const auto& i : object) {
				const as::serial_value::type t = i.second.get_type();
				if(t != as::serial_value::ARRAY_T && t != as::serial_value::OBJECT_T) {
					write_attribute(aStream, i.first, i.second);
					++attributes;
				}
			}

			if(attributes == object.size()) {
				aStream << '/' << '>';
			}else {
				aStream << '>';
				for(const auto& i : object) {
					const as::serial_value::type t = i.second.get_type();
					if(t == as::serial_value::ARRAY_T || t == as::serial_value::OBJECT_T) {
						write_element(aStream, i.first, i.second);
						++attributes;
					}
				}
				aStream << '<' << '/' << aName << '>';
			}
		}
		break;
	}
}

struct element {
	std::string name;
	std::string body;
	std::map<std::string, std::string> attributes;
	std::vector<element> elements;
};

void ignore_whitespace_x(std::istream& aStream) {
	char c = aStream.peek();
	while (std::isspace(c)) {
		aStream >> c;
		c = aStream.peek();
	}
}

void close_closing_tag(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c;
	aStream >> c;
	if(c != '>') throw std::runtime_error("as::deserialise_xml : Expected closing tag to end with '>'");
}

void read_closing_name(std::istream& aStream, element& e) {
	char c;
	ignore_whitespace_x(aStream);
	c = aStream.peek();
	std::string name;
	while(c != '>' && ! std::isspace(c)) {
		name += c;
		aStream >> c;
		c = aStream.peek();
	}
	if(name != e.name) throw std::runtime_error("as::deserialise_xml : Expected closing tag to have same name as opening tag");
	// Next state
	close_closing_tag(aStream, e);
}

void open_closing_tag(std::istream& aStream, element& e) {
	char c;
	aStream >> c;
	if(c != '<') throw std::runtime_error("as::deserialise_xml : Expected closing tag to begin with '</'");
	aStream >> c;
	if(c != '/') throw std::runtime_error("as::deserialise_xml : Expected closing tag to begin with '</'");
	// Next state
	read_closing_name(aStream, e);
}

void open_opening_tag(std::istream&, element&);

void read_elements(std::istream& aStream, element& e) {
	const auto pos = aStream.tellg();
	char c;
	c = aStream.peek();
	if(c != '<') throw std::runtime_error("as::deserialise_xml : Expected element to begin with '<'");
	c = aStream.peek();
	aStream >> c;
	c = aStream.peek();
	aStream.seekg(pos);
	if(c != '/') {
		element e2;
		open_opening_tag(aStream, e2);
		e.elements.push_back(e2);
		// Next state
		read_elements(aStream, e);
	}
}

void read_body(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c;

	c = aStream.peek();
	if(c == '<') {
		read_elements(aStream, e);
	}else {
		 while (c != '<') {
			 e.body += c;
			 aStream >> c;
			 c = aStream.peek();
		 }
	}

	// Next state
	open_closing_tag(aStream, e);
}

void close_opening_tag(std::istream&, element&);

void read_attribute(std::istream& aStream, element& e) {
	std::string name;
	std::string value;
	char c;

	// Read name
	ignore_whitespace_x(aStream);
	aStream >> c;
	while(c != '='){
		name += c;
		aStream >> c;
	}

	// Read value
	ignore_whitespace_x(aStream);
	aStream >> c;
	if(c != '"') throw std::runtime_error("as::deserialise_xml : Expected attribute value to begin with '\"'");
	aStream >> c;
	while(c != '"') {
		value += c;
		aStream >> c;
	}

	// Next state
	e.attributes.emplace(name, value);
	close_opening_tag(aStream, e);
}

void close_opening_tag(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c = aStream.peek();
	if(c == '/') {
		// End element
		aStream >> c;
		aStream >> c;
		if(c != '>') throw std::runtime_error("as::deserialise_xml : Expected opening tag to end with '>'");
	}else if(c == '>') {
		aStream >> c;
		// Next state
		read_body(aStream, e);
	}else {
		read_attribute(aStream, e);
	}
}

void read_opening_tag_name(std::istream& aStream, element& e) {
	char c;
	ignore_whitespace_x(aStream);
	c = aStream.peek();
	while(c != '>' && c != '/' && !std::isspace(c)) {
		e.name += c;
		aStream >> c;
		c = aStream.peek();
	}
	// Next state
	close_opening_tag(aStream, e);
}

void open_opening_tag(std::istream& aStream, element& e) {
	ignore_whitespace_x(aStream);
	char c;
	aStream >> c;
	if(c != '<') throw std::runtime_error("as::deserialise_xml : Expected opening tag to begin with '<'");
	// Next state
	read_opening_tag_name(aStream, e);
}

as::serial_value convert_element(const element& aElement) {
	// Check if array
	size_t contiguousNames = 0;
	const size_t eCount = aElement.elements.size();
	for(size_t i = 0; i < eCount; ++i) if(aElement.elements[i].name == std::to_string(i)) ++contiguousNames;
	if(eCount > 0 && contiguousNames == eCount) {
		// Element is an array
		as::serial_value tmp;
		as::serial_value::array_t& array_ = tmp.set_array();
		for(size_t i = 0; i < eCount; ++i) array_.push_back(convert_element(aElement.elements[i]));
		return tmp;
	}

	// Check if value
	if(aElement.elements.empty() && aElement.attributes.empty()) {
		// Element is a value
		if(aElement.body.empty()) return as::serial_value();
		else return as::serial_value(aElement.body);
	}

	// Element is an object
	as::serial_value tmp;
	as::serial_value::object_t& object = tmp.set_object();
	if(! aElement.body.empty()) {
		//! \todo Handle body
	}
	for(const auto& i : aElement.attributes) {
		object.emplace(i.first, as::serial_value(i.second));
	}
	for(const auto& i : aElement.elements) {
		//! \todo Handle for name conflicts
		object.emplace(i.name, convert_element(i));
	}
	return tmp;
}

namespace as {
	void serialise_xml(std::ostream& aStream, const serial_value& aValue) {
		write_element(aStream, ASMITH_SERIAL_XML, aValue);
	}

	serial_value deserialise_xml(std::istream& aStream) {
		//! \todo Handle XML header
		//! \todo Handle XML comments
		element e;
		open_opening_tag(aStream, e);
		return convert_element(e);
	}

}<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2020.  All rights reserved
 */
#ifndef _Stroika_Foundation_Configuration_Version_inl_
#define _Stroika_Foundation_Configuration_Version_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#if defined(__cplusplus)
namespace Stroika::Foundation::Configuration {
#endif

    /*
     ********************************************************************************
     *********************************** Version ************************************
     ********************************************************************************
     */
    constexpr Version::Version ()
        : fMajorVer{0}
        , fMinorVer{0}
        , fVerStage{VersionStage::eSTART}
        , fVerSubStage{0}
        , fFinalBuild{0}
    {
    }
    constexpr Version::Version (Binary32BitFullVersionType fullVersionNumber)
        : fMajorVer{static_cast<uint8_t> ((fullVersionNumber >> 24) & 0x8f)}
        , fMinorVer{static_cast<uint8_t> ((fullVersionNumber >> 16) & 0xff)}
        , fVerStage{static_cast<VersionStage> ((fullVersionNumber >> 13) & 0x07)}
        , fVerSubStage{static_cast<uint16_t> ((fullVersionNumber >> 1) & 0xfff)}
        , fFinalBuild{static_cast<bool> (fullVersionNumber & 1)}
    {
        Assert (fVerSubStage < kMaxVersionSubStage); // we got shift/mask right above
    }
    constexpr Version::Version (uint8_t majorVer, uint8_t minorVer, VersionStage verStage, uint16_t verSubStage, bool finalBuild)
        : fMajorVer{majorVer}
        , fMinorVer{minorVer}
        , fVerStage{verStage}
        , fVerSubStage{verSubStage}
        , fFinalBuild{finalBuild}
    {
        // @todo validate arg verSubStage < kMaxVersionSubStage
    }
    constexpr Binary32BitFullVersionType Version::AsFullVersionNum () const
    {
        // @todo validate arg verSubStage < kMaxVersionSubStage
        return Stroika_Make_FULL_VERSION (fMajorVer, fMinorVer, ((uint8_t)fVerStage), fVerSubStage, static_cast<int> (fFinalBuild));
    }
    inline Characters::String Version::ToString () const
    {
        return AsPrettyVersionString ();
    }
#if __cpp_lib_three_way_comparison >= 201711
public:
    constexpr std::strong_ordering Version::operator<=> (const Version& rhs) const
    {
        return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) <=> make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
    }
#endif

    /*
     ********************************************************************************
     *********************** Version::ThreeWayComparer ******************************
     ********************************************************************************
     */
    constexpr int Version::ThreeWayComparer::operator() (const Version& lhs, const Version& rhs) const
    {
        return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) - make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
    }

#if __cpp_lib_three_way_comparison < 201711
    /*
     ********************************************************************************
     ***************************** Version operators ********************************
     ********************************************************************************
     */
    constexpr bool operator< (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) < 0;
    }
    constexpr bool operator<= (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) <= 0;
    }
    constexpr bool operator== (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) == 0;
    }
    constexpr bool operator!= (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) != 0;
    }
    constexpr bool operator>= (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) >= 0;
    }
    constexpr bool operator> (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) > 0;
    }
#endif

#if defined(__cplusplus)
}
#endif

#endif /*_Stroika_Foundation_Configuration_Version_inl_*/
<commit_msg>fixed typo C++2a<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2020.  All rights reserved
 */
#ifndef _Stroika_Foundation_Configuration_Version_inl_
#define _Stroika_Foundation_Configuration_Version_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#if defined(__cplusplus)
namespace Stroika::Foundation::Configuration {
#endif

    /*
     ********************************************************************************
     *********************************** Version ************************************
     ********************************************************************************
     */
    constexpr Version::Version ()
        : fMajorVer{0}
        , fMinorVer{0}
        , fVerStage{VersionStage::eSTART}
        , fVerSubStage{0}
        , fFinalBuild{0}
    {
    }
    constexpr Version::Version (Binary32BitFullVersionType fullVersionNumber)
        : fMajorVer{static_cast<uint8_t> ((fullVersionNumber >> 24) & 0x8f)}
        , fMinorVer{static_cast<uint8_t> ((fullVersionNumber >> 16) & 0xff)}
        , fVerStage{static_cast<VersionStage> ((fullVersionNumber >> 13) & 0x07)}
        , fVerSubStage{static_cast<uint16_t> ((fullVersionNumber >> 1) & 0xfff)}
        , fFinalBuild{static_cast<bool> (fullVersionNumber & 1)}
    {
        Assert (fVerSubStage < kMaxVersionSubStage); // we got shift/mask right above
    }
    constexpr Version::Version (uint8_t majorVer, uint8_t minorVer, VersionStage verStage, uint16_t verSubStage, bool finalBuild)
        : fMajorVer{majorVer}
        , fMinorVer{minorVer}
        , fVerStage{verStage}
        , fVerSubStage{verSubStage}
        , fFinalBuild{finalBuild}
    {
        // @todo validate arg verSubStage < kMaxVersionSubStage
    }
    constexpr Binary32BitFullVersionType Version::AsFullVersionNum () const
    {
        // @todo validate arg verSubStage < kMaxVersionSubStage
        return Stroika_Make_FULL_VERSION (fMajorVer, fMinorVer, ((uint8_t)fVerStage), fVerSubStage, static_cast<int> (fFinalBuild));
    }
    inline Characters::String Version::ToString () const
    {
        return AsPrettyVersionString ();
    }
#if __cpp_lib_three_way_comparison >= 201711
    constexpr std::strong_ordering Version::operator<=> (const Version& rhs) const
    {
        return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) <=> make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
    }
#endif

    /*
     ********************************************************************************
     *********************** Version::ThreeWayComparer ******************************
     ********************************************************************************
     */
    constexpr int Version::ThreeWayComparer::operator() (const Version& lhs, const Version& rhs) const
    {
        return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) - make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
    }

#if __cpp_lib_three_way_comparison < 201711
    /*
     ********************************************************************************
     ***************************** Version operators ********************************
     ********************************************************************************
     */
    constexpr bool operator< (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) < 0;
    }
    constexpr bool operator<= (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) <= 0;
    }
    constexpr bool operator== (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) == 0;
    }
    constexpr bool operator!= (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) != 0;
    }
    constexpr bool operator>= (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) >= 0;
    }
    constexpr bool operator> (const Version& lhs, const Version& rhs)
    {
        return Common::ThreeWayCompare (lhs, rhs) > 0;
    }
#endif

#if defined(__cplusplus)
}
#endif

#endif /*_Stroika_Foundation_Configuration_Version_inl_*/
<|endoftext|>


<commit_before><commit_msg>unify access to texture / global memory<commit_after><|endoftext|>