<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.
//
// Note that although this is not a "browser" test, it runs as part of
// browser_tests.  This is because WebKit does not work properly if it is
// shutdown and re-initialized.  Since browser_tests runs each test in a
// new process, this avoids the problem.

#include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h"

#include "base/callback.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "chrome/renderer/safe_browsing/features.h"
#include "chrome/renderer/safe_browsing/mock_feature_extractor_clock.h"
#include "chrome/renderer/safe_browsing/render_view_fake_resources_test.h"
#include "testing/gmock/include/gmock/gmock.h"

using ::testing::ContainerEq;
using ::testing::Return;

namespace safe_browsing {

class PhishingDOMFeatureExtractorTest : public RenderViewFakeResourcesTest {
 protected:
  virtual void SetUp() {
    // Set up WebKit and the RenderView.
    RenderViewFakeResourcesTest::SetUp();
    extractor_.reset(new PhishingDOMFeatureExtractor(view_, &clock_));
  }

  virtual void TearDown() {
    RenderViewFakeResourcesTest::TearDown();
  }

  // Runs the DOMFeatureExtractor on the RenderView, waiting for the
  // completion callback.  Returns the success boolean from the callback.
  bool ExtractFeatures(FeatureMap* features) {
    success_ = false;
    extractor_->ExtractFeatures(
        features,
        NewCallback(this, &PhishingDOMFeatureExtractorTest::ExtractionDone));
    message_loop_.Run();
    return success_;
  }

  // Completion callback for feature extraction.
  void ExtractionDone(bool success) {
    success_ = success;
    message_loop_.Quit();
  }

  MockFeatureExtractorClock clock_;
  scoped_ptr<PhishingDOMFeatureExtractor> extractor_;
  bool success_;  // holds the success value from ExtractFeatures
};

TEST_F(PhishingDOMFeatureExtractorTest, FormFeatures) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));
  responses_["http://host.com/"] =
      ""
      "<form action=\"query\"><input type=text><input type=checkbox></form>"
      "<form action=\"http://cgi.host.com/submit\"></form>"
      "<form action=\"http://other.com/\"></form>"
      "<form action=\"query\"></form>"
      "<form></form>";

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageHasForms);
  expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.25);
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);
  expected_features.AddBooleanFeature(features::kPageHasCheckInputs);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      ""
      "<input type=\"radio\"><input type=password>";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageHasRadioInputs);
  expected_features.AddBooleanFeature(features::kPageHasPswdInputs);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      "<input>";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      "<input type=\"invalid\">";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, LinkFeatures) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));
  responses_["http://www.host.com/"] =
      ""
      "link"
      ""
      "chromium"
      "</html";

  FeatureMap expected_features;
  expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.5);
  expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.0);
  expected_features.AddBooleanFeature(features::kPageLinkDomain +
                                      std::string("chromium.org"));

  FeatureMap features;
  LoadURL("http://www.host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_.clear();
  responses_["https://www.host.com/"] =
      ""
      "this is secure"
      "not secure"
      "also secure"
      "also not secure"
      "";

  expected_features.Clear();
  expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25);
  expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.5);
  expected_features.AddBooleanFeature(features::kPageLinkDomain +
                                      std::string("chromium.org"));

  features.Clear();
  LoadURL("https://www.host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, ScriptAndImageFeatures) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));
  responses_["http://host.com/"] =
      "";

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      ""
      ""
      ""
      "";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne);
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTSix);
  expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 0.5);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, SubFrames) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));

  // Test that features are aggregated across all frames.
  responses_["http://host.com/"] =
      "<input type=text>link"
      ""
      ""
      "";

  responses_["http://host2.com/"] =
      ""
      "<form action=\"http://host4.com/\"><input type=checkbox></form>"
      "<form action=\"http://host2.com/submit\"></form>"
      "link"
      ""
      "";

  responses_["http://host2.com/nested.html"] =
      "<input type=password>"
      "link"
      "another"
      "";

  responses_["http://host3.com/"] =
      ""
      ""
      "";

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageHasForms);
  // Form action domains are compared to the URL of the document they're in,
  // not the URL of the toplevel page.  So http://host2.com/ has two form
  // actions, one of which is external.
  expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5);
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);
  expected_features.AddBooleanFeature(features::kPageHasPswdInputs);
  expected_features.AddBooleanFeature(features::kPageHasCheckInputs);
  expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25);
  expected_features.AddBooleanFeature(features::kPageLinkDomain +
                                      std::string("host4.com"));
  expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.25);
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne);
  expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 1.0);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, Continuation) {
  // For this test, we'll cause the feature extraction to run multiple
  // iterations by incrementing the clock.

  // This page has a total of 50 elements.  For the external forms feature to
  // be computed correctly, the extractor has to examine the whole document.
  // Note: the empty HEAD is important -- WebKit will synthesize a HEAD if
  // there isn't one present, which can be confusing for the element counts.
  std::string response = ""
      "<form action=\"ondomain\"></form>";
  for (int i = 0; i < 45; ++i) {
    response.append("
");
  }
  response.append("<form action=\"http://host2.com/\"></form>");
  responses_["http://host.com/"] = response;

  // Advance the clock 8 ms every 10 elements processed, 10 ms between chunks.
  // Note that this assumes kClockCheckGranularity = 10 and
  // kMaxTimePerChunkMs = 20.
  base::TimeTicks now = base::TimeTicks::Now();
  EXPECT_CALL(clock_, Now())
      // Time check at the start of extraction.
      .WillOnce(Return(now))
      // Time check at the start of the first chunk of work.
      .WillOnce(Return(now))
      // Time check after the first 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(8)))
      // Time check after the next 10 elements.  This is over the chunk
      // time limit, so a continuation task will be posted.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(16)))
      // Time check at the start of the second chunk of work.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(26)))
      // Time check after resuming iteration for the second chunk.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(28)))
      // Time check after the next 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(36)))
      // Time check after the next 10 elements.  This will trigger another
      // continuation task.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(44)))
      // Time check at the start of the third chunk of work.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(54)))
      // Time check after resuming iteration for the third chunk.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(56)))
      // Time check after the last 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(64)))
      // A final time check for the histograms.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(66)));

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageHasForms);
  expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
  // Make sure none of the mock expectations carry over to the next test.
  ::testing::Mock::VerifyAndClearExpectations(&clock_);

  // Now repeat the test with the same page, but advance the clock faster so
  // that the extraction time exceeds the maximum total time for the feature
  // extractor.  Extraction should fail.  Note that this assumes
  // kMaxTotalTimeMs = 500.
  EXPECT_CALL(clock_, Now())
      // Time check at the start of extraction.
      .WillOnce(Return(now))
      // Time check at the start of the first chunk of work.
      .WillOnce(Return(now))
      // Time check after the first 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(300)))
      // Time check at the start of the second chunk of work.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(350)))
      // Time check after resuming iteration for the second chunk.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(360)))
      // Time check after the next 10 elements.  This is over the limit.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(600)))
      // A final time check for the histograms.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(620)));

  features.Clear();
  EXPECT_FALSE(ExtractFeatures(&features));
}

}  // namespace safe_browsing
<commit_msg>Fix the clock values in PhishingDOMFeatureExtractorTest.Continuation.<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.
//
// Note that although this is not a "browser" test, it runs as part of
// browser_tests.  This is because WebKit does not work properly if it is
// shutdown and re-initialized.  Since browser_tests runs each test in a
// new process, this avoids the problem.

#include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h"

#include "base/callback.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "chrome/renderer/safe_browsing/features.h"
#include "chrome/renderer/safe_browsing/mock_feature_extractor_clock.h"
#include "chrome/renderer/safe_browsing/render_view_fake_resources_test.h"
#include "testing/gmock/include/gmock/gmock.h"

using ::testing::ContainerEq;
using ::testing::Return;

namespace safe_browsing {

class PhishingDOMFeatureExtractorTest : public RenderViewFakeResourcesTest {
 protected:
  virtual void SetUp() {
    // Set up WebKit and the RenderView.
    RenderViewFakeResourcesTest::SetUp();
    extractor_.reset(new PhishingDOMFeatureExtractor(view_, &clock_));
  }

  virtual void TearDown() {
    RenderViewFakeResourcesTest::TearDown();
  }

  // Runs the DOMFeatureExtractor on the RenderView, waiting for the
  // completion callback.  Returns the success boolean from the callback.
  bool ExtractFeatures(FeatureMap* features) {
    success_ = false;
    extractor_->ExtractFeatures(
        features,
        NewCallback(this, &PhishingDOMFeatureExtractorTest::ExtractionDone));
    message_loop_.Run();
    return success_;
  }

  // Completion callback for feature extraction.
  void ExtractionDone(bool success) {
    success_ = success;
    message_loop_.Quit();
  }

  MockFeatureExtractorClock clock_;
  scoped_ptr<PhishingDOMFeatureExtractor> extractor_;
  bool success_;  // holds the success value from ExtractFeatures
};

TEST_F(PhishingDOMFeatureExtractorTest, FormFeatures) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));
  responses_["http://host.com/"] =
      ""
      "<form action=\"query\"><input type=text><input type=checkbox></form>"
      "<form action=\"http://cgi.host.com/submit\"></form>"
      "<form action=\"http://other.com/\"></form>"
      "<form action=\"query\"></form>"
      "<form></form>";

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageHasForms);
  expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.25);
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);
  expected_features.AddBooleanFeature(features::kPageHasCheckInputs);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      ""
      "<input type=\"radio\"><input type=password>";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageHasRadioInputs);
  expected_features.AddBooleanFeature(features::kPageHasPswdInputs);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      "<input>";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      "<input type=\"invalid\">";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, LinkFeatures) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));
  responses_["http://www.host.com/"] =
      ""
      "link"
      ""
      "chromium"
      "</html";

  FeatureMap expected_features;
  expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.5);
  expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.0);
  expected_features.AddBooleanFeature(features::kPageLinkDomain +
                                      std::string("chromium.org"));

  FeatureMap features;
  LoadURL("http://www.host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_.clear();
  responses_["https://www.host.com/"] =
      ""
      "this is secure"
      "not secure"
      "also secure"
      "also not secure"
      "";

  expected_features.Clear();
  expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25);
  expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.5);
  expected_features.AddBooleanFeature(features::kPageLinkDomain +
                                      std::string("chromium.org"));

  features.Clear();
  LoadURL("https://www.host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, ScriptAndImageFeatures) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));
  responses_["http://host.com/"] =
      "";

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));

  responses_["http://host.com/"] =
      ""
      ""
      ""
      "";

  expected_features.Clear();
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne);
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTSix);
  expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 0.5);

  features.Clear();
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, SubFrames) {
  // This test doesn't exercise the extraction timing.
  EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now()));

  // Test that features are aggregated across all frames.
  responses_["http://host.com/"] =
      "<input type=text>link"
      ""
      ""
      "";

  responses_["http://host2.com/"] =
      ""
      "<form action=\"http://host4.com/\"><input type=checkbox></form>"
      "<form action=\"http://host2.com/submit\"></form>"
      "link"
      ""
      "";

  responses_["http://host2.com/nested.html"] =
      "<input type=password>"
      "link"
      "another"
      "";

  responses_["http://host3.com/"] =
      ""
      ""
      "";

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageHasForms);
  // Form action domains are compared to the URL of the document they're in,
  // not the URL of the toplevel page.  So http://host2.com/ has two form
  // actions, one of which is external.
  expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5);
  expected_features.AddBooleanFeature(features::kPageHasTextInputs);
  expected_features.AddBooleanFeature(features::kPageHasPswdInputs);
  expected_features.AddBooleanFeature(features::kPageHasCheckInputs);
  expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25);
  expected_features.AddBooleanFeature(features::kPageLinkDomain +
                                      std::string("host4.com"));
  expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.25);
  expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne);
  expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 1.0);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
}

TEST_F(PhishingDOMFeatureExtractorTest, Continuation) {
  // For this test, we'll cause the feature extraction to run multiple
  // iterations by incrementing the clock.

  // This page has a total of 50 elements.  For the external forms feature to
  // be computed correctly, the extractor has to examine the whole document.
  // Note: the empty HEAD is important -- WebKit will synthesize a HEAD if
  // there isn't one present, which can be confusing for the element counts.
  std::string response = ""
      "<form action=\"ondomain\"></form>";
  for (int i = 0; i < 45; ++i) {
    response.append("
");
  }
  response.append("<form action=\"http://host2.com/\"></form>");
  responses_["http://host.com/"] = response;

  // Advance the clock 12 ms every 10 elements processed, 10 ms between chunks.
  // Note that this assumes kClockCheckGranularity = 10 and
  // kMaxTimePerChunkMs = 20.
  base::TimeTicks now = base::TimeTicks::Now();
  EXPECT_CALL(clock_, Now())
      // Time check at the start of extraction.
      .WillOnce(Return(now))
      // Time check at the start of the first chunk of work.
      .WillOnce(Return(now))
      // Time check after the first 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(12)))
      // Time check after the next 10 elements.  This is over the chunk
      // time limit, so a continuation task will be posted.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(24)))
      // Time check at the start of the second chunk of work.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(34)))
      // Time check after resuming iteration for the second chunk.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(36)))
      // Time check after the next 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(48)))
      // Time check after the next 10 elements.  This will trigger another
      // continuation task.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(60)))
      // Time check at the start of the third chunk of work.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(70)))
      // Time check after resuming iteration for the third chunk.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(72)))
      // Time check after the last 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(84)))
      // A final time check for the histograms.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(86)));

  FeatureMap expected_features;
  expected_features.AddBooleanFeature(features::kPageHasForms);
  expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5);

  FeatureMap features;
  LoadURL("http://host.com/");
  ASSERT_TRUE(ExtractFeatures(&features));
  EXPECT_THAT(features.features(), ContainerEq(expected_features.features()));
  // Make sure none of the mock expectations carry over to the next test.
  ::testing::Mock::VerifyAndClearExpectations(&clock_);

  // Now repeat the test with the same page, but advance the clock faster so
  // that the extraction time exceeds the maximum total time for the feature
  // extractor.  Extraction should fail.  Note that this assumes
  // kMaxTotalTimeMs = 500.
  EXPECT_CALL(clock_, Now())
      // Time check at the start of extraction.
      .WillOnce(Return(now))
      // Time check at the start of the first chunk of work.
      .WillOnce(Return(now))
      // Time check after the first 10 elements.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(300)))
      // Time check at the start of the second chunk of work.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(350)))
      // Time check after resuming iteration for the second chunk.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(360)))
      // Time check after the next 10 elements.  This is over the limit.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(600)))
      // A final time check for the histograms.
      .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(620)));

  features.Clear();
  EXPECT_FALSE(ExtractFeatures(&features));
}

}  // namespace safe_browsing
<|endoftext|>


<commit_before><commit_msg>Added methods for index ptr in python<commit_after><|endoftext|>


<commit_before><commit_msg>ocl: support empty "ptr only" UMat in Kernel::set()<commit_after><|endoftext|>


<commit_before>/******************************************************************************
*	Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/

#include "Mapper.h"

// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>

// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005				// timestep; make sure this is equal to 1/SAMPLE_RATE!

// Conversion Factors
#define UNITS_KPA 0.1		// converts pressure from mbar to kPa

/******************************************************************************
* Controller Gains
******************************************************************************/

// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1

// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0

// Saturation Constants
#define YAW_SAT 1			// upper limit of yaw controller
#define DEPTH_SAT 1		// upper limit of depth controller
#define INT_SAT 10		// upper limit of integral windup
#define DINT_SAT 10		// upper limit of depth integral windup

// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029

// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81

// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)

// Stop Timer
#define STOP_TIME 10		// seconds

// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27		// connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board

/******************************************************************************
 * Declare Threads
******************************************************************************/

void *navigation_thread(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);

/******************************************************************************
 * Global Variables
******************************************************************************/

// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;

// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;

// Holds the latest temperature value from the temperature temperature sensor
float temperature;

// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;

// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;

// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};

// Ignoring sstate
float depth = 0;

// setmotor intialization
float motor_percent = 0;

// Start time for stop timer
time_t start;

/******************************************************************************
* Main Function
******************************************************************************/

int main()
{
	// Set up RasPi GPIO pins through wiringPi
	wiringPiSetupGpio();

	// Check if AUV is initialized correctly
	if( initialize_sensors() < 0 )
	{
		return -1;
	}
	printf("\nAll components are initialized\n");
	substate.mode = INITIALIZING;
  substate.laserarmed = ARMED;

	printf("Starting Threads\n");
	initializeTAttr();

	// Thread handles
	//pthread_t navigationThread;
	pthread_t depthThread;
	//pthread_t safetyThread;
	//pthread_t disarmlaserThread;
	pthread_t uiThread;

	// Create threads using modified attributes
	//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
	//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
	//pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
	//pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL);
	pthread_create (&uiThread, &tattrmed, userInterface, NULL);

  // Destroy the thread attributes
 	destroyTAttr();

  printf("Threads started\n");

	// Start timer!
	start = time(0);

	// Run main while loop, wait until it's time to stop
	while(substate.mode != STOPPED)
	{
		// Check if we've passed the stop time
		if(difftime(time(0),start) > STOP_TIME)
			substate.mode = PAUSED;

		// Sleep a little
		auv_usleep(100000);
	}

	// Exit cleanly
	cleanup_auv();
	return 0;
}

/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or not
******************************************************************************/

void *depth_thread(void* arg)
{
	printf("Depth Thread Started\n");

	while(substate.mode!=STOPPED)
	{
		ms5837 = read_pressure_fifo();

		printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n", ms5837.depth, ms5837.water_temp);

		printf("Current battery temp:\t %.2f\n", read_temp_fifo());

		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

		// Write IMU data
		printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: "
			"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
			 substate.imu.yaw,	substate.imu.roll,	substate.imu.pitch,
			 substate.imu.p, 		substate.imu.q,			substate.imu.r,
			 substate.imu.sys,	substate.imu.gyro,	substate.imu.accel,
			 substate.imu.mag,	substate.imu.x_acc,	substate.imu.y_acc,
			 substate.imu.z_acc);

		auv_usleep(1000000);
	 	//printf("\nYawPID_perr: %f Motor Percent: %f ", yaw_pid.perr, motor_percent);
	}

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Navigation Thread
 *
 * For yaw control
 *****************************************************************************/
void *navigation_thread(void* arg)
{
	printf("Nav Thread Started\n");

	initialize_motors(motor_channels, HERTZ);

	float yaw = 0; 			  //Local variable for if statements

  ////////////////////////////////
  // Yaw Control Initialization //
  ////////////////////////////////
	yaw_pid.old 			= 0;	 	// Initialize old imu data
	yaw_pid.setpoint 	= 0;		// Initialize setpoint

	yaw_pid.derr = 0;
	yaw_pid.ierr = 0;					// Initialize error values
	yaw_pid.perr = 0;

	yaw_pid.kp = KP_YAW;
	yaw_pid.kd = KD_YAW;			// Initialize gain values
	yaw_pid.ki = KI_YAW;

	yaw_pid.isat = INT_SAT;		// Initialize saturation values
	yaw_pid.sat  = YAW_SAT;

	yaw_pid.dt   = DT;				// initialize time step

  //////////////////////////////////
  // Depth Control Initialization //
  //////////////////////////////////
	depth_pid.setpoint	= 2;		// Range-from-bottom setpoint (meters)
	depth_pid.old				= 0;		// Initialize old depth
	depth_pid.dt				= DT;		// Initialize depth controller time step

	depth_pid.kp = KP_DEPTH;
	depth_pid.kd = KD_DEPTH;		// Depth controller gain initialization
	depth_pid.ki = KI_DEPTH;

	depth_pid.perr = 0;
	depth_pid.ierr = 0;					// Initialize depth controller error values
	depth_pid.derr = 0;

	depth_pid.isat = INT_SAT;		// Depth controller saturation values
	depth_pid.sat  = DEPTH_SAT;

	while(substate.mode!=STOPPED)
	{
		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

	  if (substate.imu.yaw < 180) // AUV pointed right
		{
			yaw = substate.imu.yaw;
		}
		else // AUV pointed left
		{
			yaw =(substate.imu.yaw-360);
		}

    // Only tell motors to run if we are RUNNING
    if( substate.mode == RUNNING)
    {
      //calculate yaw controller output
      motor_percent = marchPID(yaw_pid, yaw);

      // Set port motor
      set_motor(0, motor_percent);

      // Set starboard motor
      set_motor(1, motor_percent);

		} // end if RUNNING
		else if( substate.mode == PAUSED)
		{
		  // Stop horizontal motors
		  set_motor(0, 0);
		  set_motor(1, 0);

		  // Wipe integral error
		  yaw_pid.ierr = 0;

		  // Sleep a while (we're not doing anything anyways)
		  auv_usleep(100000);

		} // end if PAUSED

		// Sleep for 5 ms
		auv_usleep(DT);
	}

	// Turn motors off
	set_motor(0, 0);
	set_motor(1, 0);
	set_motor(2, 0);

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Safety Thread
 *
 * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
 * water intrusion is detected
 *****************************************************************************/
/*void *safety_thread(void* arg)
{
	printf("Safety Thread Started\n");

	// Set up WiringPi for use // (not sure if actually needed)
	wiringPiSetup();

	// Leak detection pins
	pinMode(LEAKPIN, INPUT);					// set LEAKPIN as an INPUT
	pinMode(LEAKPOWERPIN, OUTPUT);		// set as output to provide Vcc
	digitalWrite(LEAKPOWERPIN, HIGH);	// write high to provide Vcc

	// Leak checking variables
	int leakState;	// holds the state (HIGH or LOW) of the LEAKPIN

	// Test if temp sensor reads anything
	temperature = read_temp_fifo();
	printf("Temperature: %f degC\n", temperature);

	while( substate.mode != STOPPED )
	{
		// Check if depth threshold has been exceeded
		if( substate.fdepth > DEPTH_STOP )
		{
			substate.mode = STOPPED;
			printf("We're too deep! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check temperature
		// Shut down AUV if housing temperature gets too high

		if( temperature > TEMP_STOP )
		{
			substate.mode = STOPPED;
			printf("It's too hot! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check for leak
		leakState = digitalRead(LEAKPIN);	// check the state of LEAKPIN
		if( leakState == HIGH )
		{
			substate.mode = STOPPED;
			printf("LEAK DETECTED! Shutting down...\n");
			continue;
		}
		else if (leakState == LOW)
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check IMU accelerometer for collision (1+ g detected)
		if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
		{
			substate.mode = STOPPED;
			printf("Collision detected. Shutting down...");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

	}
    pthread_exit(NULL);

}//*/

/******************************************************************************
 * Logging Thread
 *
 * Logs the sensor output data into a file
 *****************************************************************************/
/*
PI_THREAD (logging_thread)
{
	while(substate.mode!=STOPPED){
		FILE *fd = fopen("log.txt", "a");
		char buffer[100] = {0};
		// add logging values to the next line
		sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
		sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
		fputs(buffer, fd);
		fclose(fd);
		//sleep for 100 ms

		usleep(100000);
	}
	return 0;
}
*/

/******************************************************************************
 * User Interface Thread
 * void* userInterface(void* arg)
 *
 * Interfaces with the user, asks for input
 *****************************************************************************/
 void* userInterface(void* arg)
 {
  // Declare local constant variables
  float _kp, _ki, _kd;

  // Wait a until everything is initialized before starting
  while(substate.mode == INITIALIZING)
  {
    // Waiting...
    auv_usleep(100000);
  }

  // Prompt user for values continuously until the program exits
  while(substate.mode != STOPPED)
  {
    // Prompt for kp
    std::cout << "Kp: ";
    std::cin >> _kp;

    // Prompt for ki
    std::cout << "Ki: ";
    std::cin >> _ki;

    // Prompt for kd
    std::cout << "Kd: ";
    std::cin >> _kp;

    // Give a newline
    std::cout << std::endl;

    // Reset gain values
    yaw_pid.kp = _kp;
    yaw_pid.kd = _ki;
    yaw_pid.ki = _kd;

    // Clear errors
    yaw_pid.derr = 0;
    yaw_pid.ierr = 0;
    yaw_pid.perr = 0;

    // Start RUNNING again
    substate.mode = RUNNING;

    // Restart timer!
	  start = time(0);
  }

  // Exit thread
  pthread_exit(NULL);
 }<commit_msg>fixed typos, turned on nav thread<commit_after>/******************************************************************************
*	Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/

#include "Mapper.h"

// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>

// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005				// timestep; make sure this is equal to 1/SAMPLE_RATE!

// Conversion Factors
#define UNITS_KPA 0.1		// converts pressure from mbar to kPa

/******************************************************************************
* Controller Gains
******************************************************************************/

// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1

// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0

// Saturation Constants
#define YAW_SAT 1			// upper limit of yaw controller
#define DEPTH_SAT 1		// upper limit of depth controller
#define INT_SAT 10		// upper limit of integral windup
#define DINT_SAT 10		// upper limit of depth integral windup

// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029

// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81

// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)

// Stop Timer
#define STOP_TIME 10		// seconds

// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27		// connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board

/******************************************************************************
 * Declare Threads
******************************************************************************/

void *navigation_thread(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
void *userInterface(void* arg);

/******************************************************************************
 * Global Variables
******************************************************************************/

// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;

// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;

// Holds the latest temperature value from the temperature temperature sensor
float temperature;

// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;

// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;

// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};

// Ignoring sstate
float depth = 0;

// setmotor intialization
float motor_percent = 0;

// Start time for stop timer
time_t start;

/******************************************************************************
* Main Function
******************************************************************************/

int main()
{
	// Set up RasPi GPIO pins through wiringPi
	wiringPiSetupGpio();

	// Check if AUV is initialized correctly
	if( initialize_sensors() < 0 )
	{
		return -1;
	}
	printf("\nAll components are initialized\n");
	substate.mode = INITIALIZING;
  substate.laserarmed = ARMED;

	printf("Starting Threads\n");
	initializeTAttr();

	// Thread handles
	pthread_t navigationThread;
	pthread_t depthThread;
	//pthread_t safetyThread;
	//pthread_t disarmlaserThread;
	pthread_t uiThread;

	// Create threads using modified attributes
	//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
	//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
	//pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
	pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL);
	pthread_create (&uiThread, &tattrmed, userInterface, NULL);

  // Destroy the thread attributes
 	destroyTAttr();

  printf("Threads started\n");

	// Start timer!
	start = time(0);

	// Run main while loop, wait until it's time to stop
	while(substate.mode != STOPPED)
	{
		// Check if we've passed the stop time
		if(difftime(time(0),start) > STOP_TIME)
			substate.mode = PAUSED;

		// Sleep a little
		auv_usleep(100000);
	}

	// Exit cleanly
	cleanup_auv();
	return 0;
}

/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or not
******************************************************************************/

void *depth_thread(void* arg)
{
	printf("Depth Thread Started\n");

	while(substate.mode!=STOPPED)
	{
		ms5837 = read_pressure_fifo();

		printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n", ms5837.depth, ms5837.water_temp);

		printf("Current battery temp:\t %.2f\n", read_temp_fifo());

		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

		// Write IMU data
		printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: "
			"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
			 substate.imu.yaw,	substate.imu.roll,	substate.imu.pitch,
			 substate.imu.p, 		substate.imu.q,			substate.imu.r,
			 substate.imu.sys,	substate.imu.gyro,	substate.imu.accel,
			 substate.imu.mag,	substate.imu.x_acc,	substate.imu.y_acc,
			 substate.imu.z_acc);

		auv_usleep(1000000);
	 	//printf("\nYawPID_perr: %f Motor Percent: %f ", yaw_pid.perr, motor_percent);
	}

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Navigation Thread
 *
 * For yaw control
 *****************************************************************************/
void *navigation_thread(void* arg)
{
	printf("Nav Thread Started\n");

	initialize_motors(motor_channels, HERTZ);

	float yaw = 0; 			  //Local variable for if statements

  ////////////////////////////////
  // Yaw Control Initialization //
  ////////////////////////////////
	yaw_pid.old 			= 0;	 	// Initialize old imu data
	yaw_pid.setpoint 	= 0;		// Initialize setpoint

	yaw_pid.derr = 0;
	yaw_pid.ierr = 0;					// Initialize error values
	yaw_pid.perr = 0;

	yaw_pid.kp = KP_YAW;
	yaw_pid.kd = KD_YAW;			// Initialize gain values
	yaw_pid.ki = KI_YAW;

	yaw_pid.isat = INT_SAT;		// Initialize saturation values
	yaw_pid.sat  = YAW_SAT;

	yaw_pid.dt   = DT;				// initialize time step

  //////////////////////////////////
  // Depth Control Initialization //
  //////////////////////////////////
	depth_pid.setpoint	= 2;		// Range-from-bottom setpoint (meters)
	depth_pid.old				= 0;		// Initialize old depth
	depth_pid.dt				= DT;		// Initialize depth controller time step

	depth_pid.kp = KP_DEPTH;
	depth_pid.kd = KD_DEPTH;		// Depth controller gain initialization
	depth_pid.ki = KI_DEPTH;

	depth_pid.perr = 0;
	depth_pid.ierr = 0;					// Initialize depth controller error values
	depth_pid.derr = 0;

	depth_pid.isat = INT_SAT;		// Depth controller saturation values
	depth_pid.sat  = DEPTH_SAT;

	while(substate.mode!=STOPPED)
	{
		// read IMU values from fifo file
		substate.imu = read_imu_fifo();

	  if (substate.imu.yaw < 180) // AUV pointed right
		{
			yaw = substate.imu.yaw;
		}
		else // AUV pointed left
		{
			yaw =(substate.imu.yaw-360);
		}

    // Only tell motors to run if we are RUNNING
    if( substate.mode == RUNNING)
    {
      //calculate yaw controller output
      motor_percent = marchPID(yaw_pid, yaw);

      // Set port motor
      set_motor(0, motor_percent);

      // Set starboard motor
      set_motor(1, motor_percent);

		} // end if RUNNING
		else if( substate.mode == PAUSED)
		{
		  // Stop horizontal motors
		  set_motor(0, 0);
		  set_motor(1, 0);

		  // Wipe integral error
		  yaw_pid.ierr = 0;

		  // Sleep a while (we're not doing anything anyways)
		  auv_usleep(100000);

		} // end if PAUSED

		// Sleep for 5 ms
		auv_usleep(DT);
	}

	// Turn motors off
	set_motor(0, 0);
	set_motor(1, 0);
	set_motor(2, 0);

	pthread_exit(NULL);
}//*/

/******************************************************************************
 * Safety Thread
 *
 * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
 * water intrusion is detected
 *****************************************************************************/
/*void *safety_thread(void* arg)
{
	printf("Safety Thread Started\n");

	// Set up WiringPi for use // (not sure if actually needed)
	wiringPiSetup();

	// Leak detection pins
	pinMode(LEAKPIN, INPUT);					// set LEAKPIN as an INPUT
	pinMode(LEAKPOWERPIN, OUTPUT);		// set as output to provide Vcc
	digitalWrite(LEAKPOWERPIN, HIGH);	// write high to provide Vcc

	// Leak checking variables
	int leakState;	// holds the state (HIGH or LOW) of the LEAKPIN

	// Test if temp sensor reads anything
	temperature = read_temp_fifo();
	printf("Temperature: %f degC\n", temperature);

	while( substate.mode != STOPPED )
	{
		// Check if depth threshold has been exceeded
		if( substate.fdepth > DEPTH_STOP )
		{
			substate.mode = STOPPED;
			printf("We're too deep! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check temperature
		// Shut down AUV if housing temperature gets too high

		if( temperature > TEMP_STOP )
		{
			substate.mode = STOPPED;
			printf("It's too hot! Shutting down...\n");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check for leak
		leakState = digitalRead(LEAKPIN);	// check the state of LEAKPIN
		if( leakState == HIGH )
		{
			substate.mode = STOPPED;
			printf("LEAK DETECTED! Shutting down...\n");
			continue;
		}
		else if (leakState == LOW)
		{
			// We're still good
			substate.mode = RUNNING;
		}

		// Check IMU accelerometer for collision (1+ g detected)
		if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
			|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
		{
			substate.mode = STOPPED;
			printf("Collision detected. Shutting down...");
			continue;
		}
		else
		{
			// We're still good
			substate.mode = RUNNING;
		}

	}
    pthread_exit(NULL);

}//*/

/******************************************************************************
 * Logging Thread
 *
 * Logs the sensor output data into a file
 *****************************************************************************/
/*
PI_THREAD (logging_thread)
{
	while(substate.mode!=STOPPED){
		FILE *fd = fopen("log.txt", "a");
		char buffer[100] = {0};
		// add logging values to the next line
		sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
		sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
		fputs(buffer, fd);
		fclose(fd);
		//sleep for 100 ms

		usleep(100000);
	}
	return 0;
}
*/

/******************************************************************************
 * User Interface Thread
 * void* userInterface(void* arg)
 *
 * Interfaces with the user, asks for input
 *****************************************************************************/
 void* userInterface(void* arg)
 {
  // Declare local constant variables
  float _kp, _ki, _kd;

  // Wait a until everything is initialized before starting
  while(substate.mode == INITIALIZING)
  {
    // Waiting...
    auv_usleep(100000);
  }

  // Prompt user for values continuously until the program exits
  while(substate.mode != STOPPED)
  {
    // Prompt for kp
    std::cout << "Kp: ";
    std::cin >> _kp;

    // Prompt for ki
    std::cout << "Ki: ";
    std::cin >> _ki;

    // Prompt for kd
    std::cout << "Kd: ";
    std::cin >> _kd;

    // Give a newline
    std::cout << std::endl;

    // Reset gain values
    yaw_pid.kp = _kp;
    yaw_pid.ki = _ki;
    yaw_pid.kd = _kd;

    // Clear errors
    yaw_pid.perr = 0;
    yaw_pid.ierr = 0;
    yaw_pid.derr = 0;

    // Start RUNNING again
    substate.mode = RUNNING;

    // Restart timer!
	  start = time(0);
  }

  // Exit thread
  pthread_exit(NULL);
 }
<|endoftext|>


<commit_before>#include <mp/wavy.h>
#include <mp/functional.h>
#include <mp/signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>

using namespace mp::placeholders;

bool signal_handler(int signo, int* count, mp::wavy::loop* lo)
{
	std::cout << "signal" << std::endl;

	if(++(*count) >= 3) {
		lo->end();
		return false;
	}

	return true;
}

int main(void)
{
	mp::scoped_sigprocmask mask(
			mp::sigset().add(SIGUSR1));

	mp::wavy::loop lo;

	int count = 0;
	lo.add_signal(SIGUSR1, mp::bind(
				&signal_handler, _1, &count, &lo));

	lo.start(3);

	pid_t pid = getpid();

	usleep(50*1e3);
	kill(pid, SIGUSR1);
	usleep(50*1e3);
	kill(pid, SIGUSR1);
	usleep(50*1e3);
	kill(pid, SIGUSR1);

	lo.join();
}

<commit_msg>fixes test/signal<commit_after>#include <mp/wavy.h>
#include <mp/functional.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>

using namespace mp::placeholders;

bool signal_handler(int signo, int* count, mp::wavy::loop* lo)
{
	std::cout << "signal" << std::endl;

	if(++(*count) >= 3) {
		lo->end();
		return false;
	}

	return true;
}

int main(void)
{
	signal(SIGUSR1, SIG_IGN);

	mp::wavy::loop lo;

	int count = 0;
	lo.add_signal(SIGUSR1, mp::bind(
				&signal_handler, _1, &count, &lo));

	lo.start(3);

	pid_t pid = getpid();

	usleep(50*1e3);
	kill(pid, SIGUSR1);
	usleep(50*1e3);
	kill(pid, SIGUSR1);
	usleep(50*1e3);
	kill(pid, SIGUSR1);

	lo.join();
}

<|endoftext|>


<commit_before>#include "test_macros.hpp"
#include <matrix/math.hpp>

using namespace matrix;

int main()
{
    float data[9] = {0, 2, 3,
                     4, 5, 6,
                     7, 8, 10
                    };
    float data_check[6] = {
        4, 5, 6,
        7, 8, 10
    };
    SquareMatrix<float, 3> A(data);
    Matrix<float, 2, 3> B_check(data_check);
    Matrix<float, 2, 3> B(A.slice<2, 3>(1, 0));
    TEST(isEqual(B, B_check));

    float data_2[4] = {
        11, 12,
        13, 14
    };

    Matrix<float, 2, 2> C(data_2);
    A.set(C, 1, 1);

    float data_2_check[9] = {
        0, 2, 3,
        4, 11, 12,
        7, 13, 14
    };
    Matrix<float, 3, 3> D(data_2_check);
    TEST(isEqual(A, D));

    return 0;
}

/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Add slicing tests that are not pure row slicing<commit_after>#include "test_macros.hpp"
#include <matrix/math.hpp>

using namespace matrix;

int main()
{
    float data[9] = {0, 2, 3,
                     4, 5, 6,
                     7, 8, 10
                    };
    SquareMatrix<float, 3> A(data);

    // Test row slicing
    Matrix<float, 2, 3> B_rowslice(A.slice<2, 3>(1, 0));
    float data_check_rowslice[6] = {
        4, 5, 6,
        7, 8, 10
    };
    Matrix<float, 2, 3> B_check_rowslice(data_check_rowslice);
    TEST(isEqual(B_rowslice, B_check_rowslice));

    // Test column slicing
    Matrix<float, 3, 2> B_colslice(A.slice<3, 2>(0, 1));
    float data_check_colslice[6] = {
        2, 3,
        5, 6,
        8, 10
    };
    Matrix<float, 3, 2> B_check_colslice(data_check_colslice);
    TEST(isEqual(B_colslice, B_check_colslice));

    // Test slicing both
    Matrix<float, 3, 2> B_bothslice(A.slice<2, 2>(1, 1));
    float data_check_bothslice[4] = {
        5, 6,
        8, 10
    };
    Matrix<float, 2, 2> B_check_bothslice(data_check_bothslice);
    TEST(isEqual(B_bothslice, B_check_bothslice));

    //Test block writing
    float data_2[4] = {
        11, 12,
        13, 14
    };

    Matrix<float, 2, 2> C(data_2);
    A.set(C, 1, 1);

    float data_2_check[9] = {
        0, 2, 3,
        4, 11, 12,
        7, 13, 14
    };
    Matrix<float, 3, 3> D(data_2_check);
    TEST(isEqual(A, D));

    return 0;
}

/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
 * @author Christoph Jentzsch <cj@ethdev.com>
 * @date 2014
 * State test functions.
 */

#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/ExtVM.h>
#include <libethereum/Defaults.h>
#include <libevm/VM.h>
#include "TestHelper.h"

using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;

namespace dev {  namespace test {

void doStateTests(json_spirit::mValue& v, bool _fillin)
{
	processCommandLineOptions();

	for (auto& i: v.get_obj())
	{
		cerr << i.first << endl;
		mObject& o = i.second.get_obj();

		BOOST_REQUIRE(o.count("env") > 0);
		BOOST_REQUIRE(o.count("pre") > 0);
		BOOST_REQUIRE(o.count("transaction") > 0);

		ImportTest importer(o, _fillin);

		State theState = importer.m_statePre;
		bytes tx = importer.m_transaction.rlp();
		bytes output;

		try
		{
			theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);
		}
		catch (Exception const& _e)
		{
			cnote << "state execution did throw an exception: " << diagnostic_information(_e);
		}
		catch (std::exception const& _e)
		{
			cnote << "state execution did throw an exception: " << _e.what();
		}

		if (_fillin)
			importer.exportTest(output, theState);
		else
		{
			BOOST_REQUIRE(o.count("post") > 0);
			BOOST_REQUIRE(o.count("out") > 0);

			// check output
			checkOutput(output, o);

			// check logs
			checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);

			// check addresses
			auto expectedAddrs = importer.m_statePost.addresses();
			auto resultAddrs = theState.addresses();
			for (auto& expectedPair : expectedAddrs)
			{
				auto& expectedAddr = expectedPair.first;
				auto resultAddrIt = resultAddrs.find(expectedAddr);
				if (resultAddrIt == resultAddrs.end())
					BOOST_ERROR("Missing expected address " << expectedAddr);
				else
				{
					BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) ==  theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr));
					BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) ==  theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr));
					BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code");

					checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);
				}
			}
			checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);
		}
	}
}
} }// Namespace Close

BOOST_AUTO_TEST_SUITE(StateTests)

BOOST_AUTO_TEST_CASE(stExample)
{
	dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stSystemOperationsTest)
{
	dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stPreCompiledContracts)
{
	dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stLogTests)
{
	dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stRecursiveCreate)
{
	dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stInitCodeTest)
{
	dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stTransactionTest)
{
	dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stSpecialTest)
{
	dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stRefundTest)
{
	dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stBlockHashTest)
{
	dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stSolidityTest)
{
	dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stCreateTest)
{
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
	{
		string arg = boost::unit_test::framework::master_test_suite().argv[i];
		if (arg == "--createtest")
		{
			if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
			{
				cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
				return;
			}
			try
			{
				cnote << "Populating tests...";
				json_spirit::mValue v;
				string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
				BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
				json_spirit::read_string(s, v);
				dev::test::doStateTests(v, true);
				writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
			}
			catch (Exception const& _e)
			{
				BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e));
			}
			catch (std::exception const& _e)
			{
				BOOST_ERROR("Failed state test with Exception: " << _e.what());
			}
		}
	}
}

BOOST_AUTO_TEST_CASE(userDefinedFileState)
{
	dev::test::userDefinedTest("--statetest", dev::test::doStateTests);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>only check rootHash of state if FATDB is off<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file state.cpp
 * @author Christoph Jentzsch <cj@ethdev.com>
 * @date 2014
 * State test functions.
 */

#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/ExtVM.h>
#include <libethereum/Defaults.h>
#include <libevm/VM.h>
#include "TestHelper.h"

using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;

namespace dev {  namespace test {

void doStateTests(json_spirit::mValue& v, bool _fillin)
{
	processCommandLineOptions();

	for (auto& i: v.get_obj())
	{
		cerr << i.first << endl;
		mObject& o = i.second.get_obj();

		BOOST_REQUIRE(o.count("env") > 0);
		BOOST_REQUIRE(o.count("pre") > 0);
		BOOST_REQUIRE(o.count("transaction") > 0);

		ImportTest importer(o, _fillin);

		State theState = importer.m_statePre;
		bytes tx = importer.m_transaction.rlp();
		bytes output;

		try
		{
			theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output);
		}
		catch (Exception const& _e)
		{
			cnote << "state execution did throw an exception: " << diagnostic_information(_e);
		}
		catch (std::exception const& _e)
		{
			cnote << "state execution did throw an exception: " << _e.what();
		}

		if (_fillin)
		{
#if ETH_FATDB
			importer.exportTest(output, theState);
#else
			BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("You can not fill tests when FATDB is switched off"));
#endif
		}
		else
		{
			BOOST_REQUIRE(o.count("post") > 0);
			BOOST_REQUIRE(o.count("out") > 0);

			// check output
			checkOutput(output, o);

			// check logs
			checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs);

			// check addresses
#if ETH_FATDB
			cout << "fatDB is defined\n";
			auto expectedAddrs = importer.m_statePost.addresses();
			auto resultAddrs = theState.addresses();
			for (auto& expectedPair : expectedAddrs)
			{
				auto& expectedAddr = expectedPair.first;
				auto resultAddrIt = resultAddrs.find(expectedAddr);
				if (resultAddrIt == resultAddrs.end())
					BOOST_ERROR("Missing expected address " << expectedAddr);
				else
				{
					BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) ==  theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr));
					BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) ==  theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr));
					BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code");

					checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr);
				}
			}
			checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs);
#endif
			BOOST_CHECK_MESSAGE(theState.rootHash() == h256(o["postStateRoot"].get_str()), "wrong post state root");
		}
	}
}
} }// Namespace Close

BOOST_AUTO_TEST_SUITE(StateTests)

BOOST_AUTO_TEST_CASE(stExample)
{
	dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stSystemOperationsTest)
{
	dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stPreCompiledContracts)
{
	dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stLogTests)
{
	dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stRecursiveCreate)
{
	dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stInitCodeTest)
{
	dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stTransactionTest)
{
	dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stSpecialTest)
{
	dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stRefundTest)
{
	dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stBlockHashTest)
{
	dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stSolidityTest)
{
	dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests);
}

BOOST_AUTO_TEST_CASE(stCreateTest)
{
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
	{
		string arg = boost::unit_test::framework::master_test_suite().argv[i];
		if (arg == "--createtest")
		{
			if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
			{
				cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
				return;
			}
			try
			{
				cnote << "Populating tests...";
				json_spirit::mValue v;
				string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
				BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
				json_spirit::read_string(s, v);
				dev::test::doStateTests(v, true);
				writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
			}
			catch (Exception const& _e)
			{
				BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e));
			}
			catch (std::exception const& _e)
			{
				BOOST_ERROR("Failed state test with Exception: " << _e.what());
			}
		}
	}
}

BOOST_AUTO_TEST_CASE(userDefinedFileState)
{
	dev::test::userDefinedTest("--statetest", dev::test::doStateTests);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "MinVRSettings.h"

string
MinVRSettings::getValueString(string settingName)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = STRING;

        // save it in the settingValues map
        settingValues[settingName] = value_column;
        return value_column;
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == STRING)
        {
            return settingValues[settingName];
        }
        else
        {
            cout << " getValueString (" << settingName << ") is not a string."
                 << endl;
            //exit(1);
        }
    }
    return string();
}

int
MinVRSettings::getValueStringVector(string settingName,vector<string>& stringValues)
{
    //
    return SUCCESS;
}

int
MinVRSettings::getValueInt(string settingName)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = INT;

        int tmp_int = atoi(value_column.c_str());
        // save it in the settingValues map
        settingIntValues[settingName] = tmp_int;
        return tmp_int;
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == INT)
        {
            return settingIntValues[settingName];
        }
        else
        {
            cout << " getValueInt (" << settingName << ") is not an Int."
                 << endl;
            //exit(1);
        }
    }
    return FAILURE;
}

int
MinVRSettings::getValueIntVector(string settingName,vector<int>& intValues)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = VEC_INT;

        intValues = string_int_vec(value_column);
        // save it in the settingValues map
        settingIntValuesVector[settingName] = intValues;
        return intValues.size();
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == VEC_INT)
        {
            intValues = settingIntValuesVector[settingName];
            return intValues.size();
        }
        else
        {
            cout << " getValueIntVector (" << settingName << ",intValues) is not a vector of integers."
                 << endl;
            //exit(1);
        }
    }
    return SUCCESS;
}

vector<int>
MinVRSettings::string_int_vec(const string& value_column)
{
    vector<int> i_tmp;
    char *pch, *dup = strdup(value_column.c_str());
    pch = strtok(dup," \t,()");
    while(pch != NULL)
    {
        i_tmp.push_back(atoi(pch));
        pch = strtok(NULL," \t,()");
    }
    return i_tmp;

}

float
MinVRSettings::getValueFloat(string settingName)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = FLOAT;

        float tmp_float = (float)strtod(value_column.c_str(),NULL);
        // save it in the settingValues map
        settingFloatValues[settingName] = tmp_float;
        return tmp_float;
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == FLOAT)
        {
            return settingFloatValues[settingName];
        }
        else
        {
            cout << " getValueFloat (" << settingName << ") is not an Float."
                 << endl;
            //exit(1);
        }
    }
    return FAILURE;
}

int
MinVRSettings::getValueFloatVector(string settingName,vector<float>& floatValues)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = VEC_FLOAT;

        floatValues = string_float_vec(value_column);

        // save it in the settingValues map
        settingFloatValuesVector[settingName] = floatValues;
        return floatValues.size();
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == VEC_FLOAT)
        {
            floatValues = settingFloatValuesVector[settingName];
            return floatValues.size();
        }
        else
        {
            cout << " getValueFloatVector (" << settingName << ",floatValues) is not a vector of floats."
                 << endl;
            //exit(1);
        }
    }
    return SUCCESS;
}

vector<float> MinVRSettings::string_float_vec(const string& value_column)
{
    vector<float> f_tmp;
    char *pch, *dup = strdup(value_column.c_str());
    pch = strtok(dup," \t,()");
    while(pch != NULL)
    {
        f_tmp.push_back(static_cast<float>(strtod(pch,NULL)));
        pch = strtok(NULL," \t,()");
    }
    return f_tmp;
}

int
MinVRSettings::setValueString(string settingName, string settingValue)
{
    settingValues[settingName]=settingValue;
    keyword_to_type[settingName] = STRING;
    return SUCCESS;
}

int
MinVRSettings::setValueStringVector(string settingName, const vector<string>& settingValues)
{
//    settingValues[settingName]=settingValue;
//    keyword_to_type[settingName] = STRING;
    return SUCCESS;
}

int
MinVRSettings::setValueInt(string settingName, int settingValue)
{
    char str_tmp[128];
    sprintf(str_tmp,"%d",settingValue);
    settingsToValues[settingName]=str_tmp;
    settingIntValues[settingName]=settingValue;
    keyword_to_type[settingName] = INT;
    return SUCCESS;
}

int
MinVRSettings::setValueIntVector(string settingName, const vector<int>& settingValues)
{
    string tmp;
    char str_tmp[128];
    for (int j = 0; j < settingValues.size(); j++)
    {
        sprintf(str_tmp,"%d",settingValues[j]);
        tmp+=str_tmp;
    }
    settingsToValues[settingName]=tmp;

    settingIntValuesVector[settingName]=settingValues;
    keyword_to_type[settingName] = VEC_INT;
    return SUCCESS;
}

int
MinVRSettings::setValueFloat(string settingName, float settingValue)
{
    char str_tmp[128];
    sprintf(str_tmp,"%f",settingValue);
    settingsToValues[settingName]=str_tmp;
    settingFloatValues[settingName]=settingValue;
    keyword_to_type[settingName] = FLOAT;
    return SUCCESS;
}

int
MinVRSettings::setValueFloatVector(string settingName, const vector<float>& settingValues)
{
    string tmp;
    char str_tmp[128];
    memset(str_tmp, 0,128);
    for (int j = 0; j < settingValues.size(); j++)
    {
        sprintf(str_tmp,"%f",settingValues[j]);
        tmp+=str_tmp;
    }
    settingsToValues[settingName]=tmp;

    settingFloatValuesVector[settingName]=settingValues;
    keyword_to_type[settingName] = VEC_FLOAT;
    return SUCCESS;
}

int
MinVRSettings::readValues(string settingFileName)
{
    // Read config settings from a file
    ifstream file(settingFileName.c_str());
    int i;
    char *pch, *str;
    string line, the_key, the_val;

    if (file.is_open())
    {
        while (!file.eof())
        {
            getline(file, line);
            i = line.find("#");
            if (i>=0)
                continue;

            str=(char*)line.c_str();
            pch = strtok (str," \t,()");
            if(pch)
            {
                the_key = string(pch);
                pch = strtok (NULL, "");
                if(pch)
                {
                    the_val = string(pch);
                    settingsToValues[the_key] = the_val;
                }
                else
                    settingsToValues[the_key] = "";
            }
        }
    }
    else
    {
        cout << "File " << settingFileName << "cannot be openned" << endl;
        return FAILURE;
    }
    return SUCCESS;
}

int
MinVRSettings::writeValues(string settingFileName)
{
    ofstream m_file;
    m_file.open(settingFileName.c_str());
    if (m_file.is_open())
    {
        map<string, string>::iterator i;
        for(i=settingsToValues.begin(); i!= settingsToValues.end(); i++)
        {
            string tmp = i->second;
            tmp.erase(tmp.begin(), std::find_if(tmp.begin(), tmp.end(), std::bind1st(std::not_equal_to<char>(), ' ')));
            m_file << setw(25) << left << i->first << " " << tmp << endl;
        }
        m_file.close();
    }
    else
    {
        cout << "File " << settingFileName << "cannot be openned for writing." << endl;
        return FAILURE;
    }
    return SUCCESS;
}

<commit_msg>Inserted space into vector setValue() functions string concats.<commit_after>#include "MinVRSettings.h"

string
MinVRSettings::getValueString(string settingName)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = STRING;

        // save it in the settingValues map
        settingValues[settingName] = value_column;
        return value_column;
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == STRING)
        {
            return settingValues[settingName];
        }
        else
        {
            cout << " getValueString (" << settingName << ") is not a string."
                 << endl;
            //exit(1);
        }
    }
    return string();
}

int
MinVRSettings::getValueStringVector(string settingName,vector<string>& stringValues)
{
    //
    return SUCCESS;
}

int
MinVRSettings::getValueInt(string settingName)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = INT;

        int tmp_int = atoi(value_column.c_str());
        // save it in the settingValues map
        settingIntValues[settingName] = tmp_int;
        return tmp_int;
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == INT)
        {
            return settingIntValues[settingName];
        }
        else
        {
            cout << " getValueInt (" << settingName << ") is not an Int."
                 << endl;
            //exit(1);
        }
    }
    return FAILURE;
}

int
MinVRSettings::getValueIntVector(string settingName,vector<int>& intValues)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = VEC_INT;

        intValues = string_int_vec(value_column);
        // save it in the settingValues map
        settingIntValuesVector[settingName] = intValues;
        return intValues.size();
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == VEC_INT)
        {
            intValues = settingIntValuesVector[settingName];
            return intValues.size();
        }
        else
        {
            cout << " getValueIntVector (" << settingName << ",intValues) is not a vector of integers."
                 << endl;
            //exit(1);
        }
    }
    return SUCCESS;
}

vector<int>
MinVRSettings::string_int_vec(const string& value_column)
{
    vector<int> i_tmp;
    char *pch, *dup = strdup(value_column.c_str());
    pch = strtok(dup," \t,()");
    while(pch != NULL)
    {
        i_tmp.push_back(atoi(pch));
        pch = strtok(NULL," \t,()");
    }
    return i_tmp;

}

float
MinVRSettings::getValueFloat(string settingName)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = FLOAT;

        float tmp_float = (float)strtod(value_column.c_str(),NULL);
        // save it in the settingValues map
        settingFloatValues[settingName] = tmp_float;
        return tmp_float;
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == FLOAT)
        {
            return settingFloatValues[settingName];
        }
        else
        {
            cout << " getValueFloat (" << settingName << ") is not an Float."
                 << endl;
            //exit(1);
        }
    }
    return FAILURE;
}

int
MinVRSettings::getValueFloatVector(string settingName,vector<float>& floatValues)
{
    map<string, TYPE_ID>::iterator i;
    i = keyword_to_type.find(settingName);
    if (i == keyword_to_type.end())
    {
        // translate input into a string
        string value_column = settingsToValues[settingName];

        // save it in the keyword_to_type lookup
        keyword_to_type[settingName] = VEC_FLOAT;

        floatValues = string_float_vec(value_column);

        // save it in the settingValues map
        settingFloatValuesVector[settingName] = floatValues;
        return floatValues.size();
    }
    else
    {
        // return saved value
        TYPE_ID t = i->second;
        if (t == VEC_FLOAT)
        {
            floatValues = settingFloatValuesVector[settingName];
            return floatValues.size();
        }
        else
        {
            cout << " getValueFloatVector (" << settingName << ",floatValues) is not a vector of floats."
                 << endl;
            //exit(1);
        }
    }
    return SUCCESS;
}

vector<float>
MinVRSettings::string_float_vec(const string& value_column)
{
    vector<float> f_tmp;
    char *pch, *dup = strdup(value_column.c_str());
    pch = strtok(dup," \t,()");
    while(pch != NULL)
    {
        f_tmp.push_back(static_cast<float>(strtod(pch,NULL)));
        pch = strtok(NULL," \t,()");
    }
    return f_tmp;
}

int
MinVRSettings::setValueString(string settingName, string settingValue)
{
    settingValues[settingName]=settingValue;
    keyword_to_type[settingName] = STRING;
    return SUCCESS;
}

int
MinVRSettings::setValueStringVector(string settingName, const vector<string>& settingValues)
{
//    settingValues[settingName]=settingValue;
//    keyword_to_type[settingName] = STRING;
    return SUCCESS;
}

int
MinVRSettings::setValueInt(string settingName, int settingValue)
{
    char str_tmp[128];
    sprintf(str_tmp,"%d",settingValue);
    settingsToValues[settingName]=str_tmp;
    settingIntValues[settingName]=settingValue;
    keyword_to_type[settingName] = INT;
    return SUCCESS;
}

int
MinVRSettings::setValueIntVector(string settingName, const vector<int>& settingValues)
{
    string tmp;
    char str_tmp[128];
    for (int j=0; j<settingValues.size(); j++)
    {
        sprintf(str_tmp,"%d",settingValues[j]);
        tmp += str_tmp;
        tmp += " ";
    }
    settingsToValues[settingName]=tmp;

    settingIntValuesVector[settingName]=settingValues;
    keyword_to_type[settingName] = VEC_INT;
    return SUCCESS;
}

int
MinVRSettings::setValueFloat(string settingName, float settingValue)
{
    char str_tmp[128];
    sprintf(str_tmp,"%f",settingValue);
    settingsToValues[settingName]=str_tmp;
    settingFloatValues[settingName]=settingValue;
    keyword_to_type[settingName] = FLOAT;
    return SUCCESS;
}

int
MinVRSettings::setValueFloatVector(string settingName, const vector<float>& settingValues)
{
    string tmp;
    char str_tmp[128];
    for (int j=0; j<settingValues.size(); j++)
    {
        sprintf(str_tmp,"%f",settingValues[j]);
        tmp += str_tmp;
        tmp += " ";
    }
    settingsToValues[settingName]=tmp;

    settingFloatValuesVector[settingName]=settingValues;
    keyword_to_type[settingName] = VEC_FLOAT;
    return SUCCESS;
}

int
MinVRSettings::readValues(string settingFileName)
{
    // Read config settings from a file
    ifstream file(settingFileName.c_str());
    int i;
    char *pch, *str;
    string line, the_key, the_val;

    if (file.is_open())
    {
        while (!file.eof())
        {
            getline(file, line);
            i = line.find("#");
            if (i>=0)
                continue;

            str=(char*)line.c_str();
            pch = strtok (str," \t,()");
            if(pch)
            {
                the_key = string(pch);
                pch = strtok (NULL, "");
                if(pch)
                {
                    the_val = string(pch);
                    settingsToValues[the_key] = the_val;
                }
                else
                    settingsToValues[the_key] = "";
            }
        }
    }
    else
    {
        cout << "File " << settingFileName << "cannot be openned" << endl;
        return FAILURE;
    }
    return SUCCESS;
}

int
MinVRSettings::writeValues(string settingFileName)
{
    ofstream m_file;
    m_file.open(settingFileName.c_str());
    if (m_file.is_open())
    {
        map<string, string>::iterator i;
        for(i=settingsToValues.begin(); i!= settingsToValues.end(); i++)
        {
            string tmp = i->second;
            tmp.erase(tmp.begin(), std::find_if(tmp.begin(), tmp.end(), std::bind1st(std::not_equal_to<char>(), ' ')));
            m_file << setw(25) << left << i->first << " " << tmp << endl;
        }
        m_file.close();
    }
    else
    {
        cout << "File " << settingFileName << "cannot be openned for writing." << endl;
        return FAILURE;
    }
    return SUCCESS;
}

<|endoftext|>