<commit_before>// Copyright (c) 2010 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 "testing/gtest/include/gtest/gtest.h"

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/i18n/time_formatting.h"
#include "chrome/browser/bookmarks/bookmark_html_writer.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/importer/firefox2_importer.h"
#include "chrome/test/testing_profile.h"
#include "gfx/codec/png_codec.h"
#include "grit/generated_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

namespace {

static const int kIconWidth = 16;
static const int kIconHeight = 16;

void MakeTestSkBitmap(int w, int h, SkBitmap* bmp) {
  bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h);
  bmp->allocPixels();

  uint32_t* src_data = bmp->getAddr32(0, 0);
  for (int i = 0; i < w * h; i++) {
    src_data[i] = SkPreMultiplyARGB(i % 255, i % 250, i % 245, i % 240);
  }
}

}  // namespace

class BookmarkHTMLWriterTest : public testing::Test {
 protected:
  virtual void SetUp() {
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_));
    path_ = path_.AppendASCII("bookmarks.html");
    file_util::Delete(path_, true);
  }

  virtual void TearDown() {
    if (!path_.empty())
      file_util::Delete(path_, true);
  }

  // Converts a BookmarkEntry to a string suitable for assertion testing.
  string16 BookmarkEntryToString(
      const ProfileWriter::BookmarkEntry& entry) {
    string16 result;
    result.append(ASCIIToUTF16("on_toolbar="));
    if (entry.in_toolbar)
      result.append(ASCIIToUTF16("false"));
    else
      result.append(ASCIIToUTF16("true"));

    result.append(ASCIIToUTF16(" url=") + UTF8ToUTF16(entry.url.spec()));

    result.append(ASCIIToUTF16(" path="));
    for (size_t i = 0; i < entry.path.size(); ++i) {
      if (i != 0)
        result.append(ASCIIToUTF16("/"));
      result.append(WideToUTF16Hack(entry.path[i]));
    }

    result.append(ASCIIToUTF16(" title="));
    result.append(WideToUTF16Hack(entry.title));

    result.append(ASCIIToUTF16(" time="));
    result.append(WideToUTF16Hack(
        base::TimeFormatFriendlyDateAndTime(entry.creation_time)));
    return result;
  }

  // Creates a set of bookmark values to a string for assertion testing.
  string16 BookmarkValuesToString(bool on_toolbar,
                                  const GURL& url,
                                  const string16& title,
                                  base::Time creation_time,
                                  const string16& f1,
                                  const string16& f2,
                                  const string16& f3) {
    ProfileWriter::BookmarkEntry entry;
    entry.in_toolbar = on_toolbar;
    entry.url = url;
    // The first path element should always be 'x', as that is what we passed
    // to the importer.
    entry.path.push_back(L"x");
    if (!f1.empty()) {
      entry.path.push_back(UTF16ToWideHack(f1));
      if (!f2.empty()) {
        entry.path.push_back(UTF16ToWideHack(f2));
        if (!f3.empty())
          entry.path.push_back(UTF16ToWideHack(f3));
      }
    }
    entry.title = UTF16ToWideHack(title);
    entry.creation_time = creation_time;
    return BookmarkEntryToString(entry);
  }

  void AssertBookmarkEntryEquals(const ProfileWriter::BookmarkEntry& entry,
                                 bool on_toolbar,
                                 const GURL& url,
                                 const string16& title,
                                 base::Time creation_time,
                                 const string16& f1,
                                 const string16& f2,
                                 const string16& f3) {
    EXPECT_EQ(BookmarkValuesToString(on_toolbar, url, title, creation_time,
                                     f1, f2, f3),
              BookmarkEntryToString(entry));
  }

  FilePath path_;
};

// Class that will notify message loop when file is written.
class BookmarksObserver : public BookmarksExportObserver {
 public:
  explicit BookmarksObserver(MessageLoop* loop) : loop_(loop) {
    DCHECK(loop);
  }

  virtual void OnExportFinished() {
    loop_->Quit();
  }

 private:
  MessageLoop* loop_;
  DISALLOW_COPY_AND_ASSIGN(BookmarksObserver);
};

// Tests bookmark_html_writer by populating a BookmarkModel, writing it out by
// way of bookmark_html_writer, then using the importer to read it back in.
TEST_F(BookmarkHTMLWriterTest, Test) {
  MessageLoop message_loop;
  ChromeThread fake_ui_thread(ChromeThread::UI, &message_loop);
  ChromeThread fake_file_thread(ChromeThread::FILE, &message_loop);

  TestingProfile profile;
  profile.CreateHistoryService(true, false);
  profile.BlockUntilHistoryProcessesPendingRequests();
  profile.CreateFaviconService();
  profile.CreateBookmarkModel(true);
  profile.BlockUntilBookmarkModelLoaded();
  BookmarkModel* model = profile.GetBookmarkModel();

  // Create test PNG representing favicon for url1.
  SkBitmap bitmap;
  MakeTestSkBitmap(kIconWidth, kIconHeight, &bitmap);
  std::vector<unsigned char> icon_data;
  gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &icon_data);

  // Populate the BookmarkModel. This creates the following bookmark structure:
  // Bookmarks bar
  //   F1
  //     url1
  //     F2
  //       url2
  //   url3
  //   url4
  // Other
  //   url1
  //   url2
  //   F3
  //     F4
  //       url1
  string16 f1_title = ASCIIToUTF16("F\"&;<1\"");
  string16 f2_title = ASCIIToUTF16("F2");
  string16 f3_title = ASCIIToUTF16("F 3");
  string16 f4_title = ASCIIToUTF16("F4");
  string16 url1_title = ASCIIToUTF16("url 1");
  string16 url2_title = ASCIIToUTF16("url&2");
  string16 url3_title = ASCIIToUTF16("url\"3");
  string16 url4_title = ASCIIToUTF16("url\"&;");
  GURL url1("http://url1");
  GURL url1_favicon("http://url1/icon.ico");
  GURL url2("http://url2");
  GURL url3("http://url3");
  GURL url4("http://\"&;\"");
  base::Time t1(base::Time::Now());
  base::Time t2(t1 + base::TimeDelta::FromHours(1));
  base::Time t3(t1 + base::TimeDelta::FromHours(1));
  base::Time t4(t1 + base::TimeDelta::FromHours(1));
  const BookmarkNode* f1 = model->AddGroup(
      model->GetBookmarkBarNode(), 0, f1_title);
  model->AddURLWithCreationTime(f1, 0, url1_title, url1, t1);
  profile.GetHistoryService(Profile::EXPLICIT_ACCESS)->AddPage(url1,
      history::SOURCE_BROWSED);
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  icon_data);
  message_loop.RunAllPending();
  const BookmarkNode* f2 = model->AddGroup(f1, 1, f2_title);
  model->AddURLWithCreationTime(f2, 0, url2_title, url2, t2);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(),
                                1, url3_title, url3, t3);

  model->AddURLWithCreationTime(model->other_node(), 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->other_node(), 1, url2_title, url2, t2);
  const BookmarkNode* f3 = model->AddGroup(model->other_node(), 2, f3_title);
  const BookmarkNode* f4 = model->AddGroup(f3, 0, f4_title);
  model->AddURLWithCreationTime(f4, 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(), 2, url4_title,
                                url4, t4);

  // Write to a temp file.
  BookmarksObserver observer(&message_loop);
  bookmark_html_writer::WriteBookmarks(&profile, path_, &observer);
  message_loop.Run();

  // Clear favicon so that it would be read from file.
  std::vector<unsigned char> empty_data;
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  empty_data);
  message_loop.RunAllPending();

  // Read the bookmarks back in.
  std::vector<ProfileWriter::BookmarkEntry> parsed_bookmarks;
  std::vector<history::ImportedFavIconUsage> favicons;
  Firefox2Importer::ImportBookmarksFile(path_, std::set<GURL>(),
                                        false, L"x", NULL, &parsed_bookmarks,
                                        NULL, &favicons);

  // Check loaded favicon (url1 is represents by 3 separate bookmarks).
  EXPECT_EQ(3U, favicons.size());
  for (size_t i = 0; i < favicons.size(); i++) {
    if (url1_favicon == favicons[i].favicon_url) {
      EXPECT_EQ(1U, favicons[i].urls.size());
      std::set<GURL>::const_iterator iter = favicons[i].urls.find(url1);
      ASSERT_TRUE(iter != favicons[i].urls.end());
      ASSERT_TRUE(*iter == url1);
      ASSERT_TRUE(favicons[i].png_data == icon_data);
    }
  }

  // Verify we got back what we wrote.
  ASSERT_EQ(7U, parsed_bookmarks.size());
  // Windows and ChromeOS builds use Sentence case.
  string16 bookmark_folder_name =
      l10n_util::GetStringUTF16(IDS_BOOMARK_BAR_FOLDER_NAME);
  AssertBookmarkEntryEquals(parsed_bookmarks[0], false, url1, url1_title, t1,
                            bookmark_folder_name, f1_title, string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[1], false, url2, url2_title, t2,
                            bookmark_folder_name, f1_title, f2_title);
  AssertBookmarkEntryEquals(parsed_bookmarks[2], false, url3, url3_title, t3,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[3], false, url4, url4_title, t4,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[4], false, url1, url1_title, t1,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[5], false, url2, url2_title, t2,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[6], false, url1, url1_title, t1,
                            f3_title, f4_title, string16());
}
<commit_msg>Temporarily disable a test that's failing a CHECK so the suite will keep running.<commit_after>// Copyright (c) 2010 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 "testing/gtest/include/gtest/gtest.h"

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/i18n/time_formatting.h"
#include "chrome/browser/bookmarks/bookmark_html_writer.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/importer/firefox2_importer.h"
#include "chrome/test/testing_profile.h"
#include "gfx/codec/png_codec.h"
#include "grit/generated_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

namespace {

static const int kIconWidth = 16;
static const int kIconHeight = 16;

void MakeTestSkBitmap(int w, int h, SkBitmap* bmp) {
  bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h);
  bmp->allocPixels();

  uint32_t* src_data = bmp->getAddr32(0, 0);
  for (int i = 0; i < w * h; i++) {
    src_data[i] = SkPreMultiplyARGB(i % 255, i % 250, i % 245, i % 240);
  }
}

}  // namespace

class BookmarkHTMLWriterTest : public testing::Test {
 protected:
  virtual void SetUp() {
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_));
    path_ = path_.AppendASCII("bookmarks.html");
    file_util::Delete(path_, true);
  }

  virtual void TearDown() {
    if (!path_.empty())
      file_util::Delete(path_, true);
  }

  // Converts a BookmarkEntry to a string suitable for assertion testing.
  string16 BookmarkEntryToString(
      const ProfileWriter::BookmarkEntry& entry) {
    string16 result;
    result.append(ASCIIToUTF16("on_toolbar="));
    if (entry.in_toolbar)
      result.append(ASCIIToUTF16("false"));
    else
      result.append(ASCIIToUTF16("true"));

    result.append(ASCIIToUTF16(" url=") + UTF8ToUTF16(entry.url.spec()));

    result.append(ASCIIToUTF16(" path="));
    for (size_t i = 0; i < entry.path.size(); ++i) {
      if (i != 0)
        result.append(ASCIIToUTF16("/"));
      result.append(WideToUTF16Hack(entry.path[i]));
    }

    result.append(ASCIIToUTF16(" title="));
    result.append(WideToUTF16Hack(entry.title));

    result.append(ASCIIToUTF16(" time="));
    result.append(WideToUTF16Hack(
        base::TimeFormatFriendlyDateAndTime(entry.creation_time)));
    return result;
  }

  // Creates a set of bookmark values to a string for assertion testing.
  string16 BookmarkValuesToString(bool on_toolbar,
                                  const GURL& url,
                                  const string16& title,
                                  base::Time creation_time,
                                  const string16& f1,
                                  const string16& f2,
                                  const string16& f3) {
    ProfileWriter::BookmarkEntry entry;
    entry.in_toolbar = on_toolbar;
    entry.url = url;
    // The first path element should always be 'x', as that is what we passed
    // to the importer.
    entry.path.push_back(L"x");
    if (!f1.empty()) {
      entry.path.push_back(UTF16ToWideHack(f1));
      if (!f2.empty()) {
        entry.path.push_back(UTF16ToWideHack(f2));
        if (!f3.empty())
          entry.path.push_back(UTF16ToWideHack(f3));
      }
    }
    entry.title = UTF16ToWideHack(title);
    entry.creation_time = creation_time;
    return BookmarkEntryToString(entry);
  }

  void AssertBookmarkEntryEquals(const ProfileWriter::BookmarkEntry& entry,
                                 bool on_toolbar,
                                 const GURL& url,
                                 const string16& title,
                                 base::Time creation_time,
                                 const string16& f1,
                                 const string16& f2,
                                 const string16& f3) {
    EXPECT_EQ(BookmarkValuesToString(on_toolbar, url, title, creation_time,
                                     f1, f2, f3),
              BookmarkEntryToString(entry));
  }

  FilePath path_;
};

// Class that will notify message loop when file is written.
class BookmarksObserver : public BookmarksExportObserver {
 public:
  explicit BookmarksObserver(MessageLoop* loop) : loop_(loop) {
    DCHECK(loop);
  }

  virtual void OnExportFinished() {
    loop_->Quit();
  }

 private:
  MessageLoop* loop_;
  DISALLOW_COPY_AND_ASSIGN(BookmarksObserver);
};

// Tests bookmark_html_writer by populating a BookmarkModel, writing it out by
// way of bookmark_html_writer, then using the importer to read it back in.
TEST_F(BookmarkHTMLWriterTest, DISABLED_Test) {
  MessageLoop message_loop;
  ChromeThread fake_ui_thread(ChromeThread::UI, &message_loop);
  ChromeThread fake_file_thread(ChromeThread::FILE, &message_loop);

  TestingProfile profile;
  profile.CreateHistoryService(true, false);
  profile.BlockUntilHistoryProcessesPendingRequests();
  profile.CreateFaviconService();
  profile.CreateBookmarkModel(true);
  profile.BlockUntilBookmarkModelLoaded();
  BookmarkModel* model = profile.GetBookmarkModel();

  // Create test PNG representing favicon for url1.
  SkBitmap bitmap;
  MakeTestSkBitmap(kIconWidth, kIconHeight, &bitmap);
  std::vector<unsigned char> icon_data;
  gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &icon_data);

  // Populate the BookmarkModel. This creates the following bookmark structure:
  // Bookmarks bar
  //   F1
  //     url1
  //     F2
  //       url2
  //   url3
  //   url4
  // Other
  //   url1
  //   url2
  //   F3
  //     F4
  //       url1
  string16 f1_title = ASCIIToUTF16("F\"&;<1\"");
  string16 f2_title = ASCIIToUTF16("F2");
  string16 f3_title = ASCIIToUTF16("F 3");
  string16 f4_title = ASCIIToUTF16("F4");
  string16 url1_title = ASCIIToUTF16("url 1");
  string16 url2_title = ASCIIToUTF16("url&2");
  string16 url3_title = ASCIIToUTF16("url\"3");
  string16 url4_title = ASCIIToUTF16("url\"&;");
  GURL url1("http://url1");
  GURL url1_favicon("http://url1/icon.ico");
  GURL url2("http://url2");
  GURL url3("http://url3");
  GURL url4("http://\"&;\"");
  base::Time t1(base::Time::Now());
  base::Time t2(t1 + base::TimeDelta::FromHours(1));
  base::Time t3(t1 + base::TimeDelta::FromHours(1));
  base::Time t4(t1 + base::TimeDelta::FromHours(1));
  const BookmarkNode* f1 = model->AddGroup(
      model->GetBookmarkBarNode(), 0, f1_title);
  model->AddURLWithCreationTime(f1, 0, url1_title, url1, t1);
  profile.GetHistoryService(Profile::EXPLICIT_ACCESS)->AddPage(url1,
      history::SOURCE_BROWSED);
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  icon_data);
  message_loop.RunAllPending();
  const BookmarkNode* f2 = model->AddGroup(f1, 1, f2_title);
  model->AddURLWithCreationTime(f2, 0, url2_title, url2, t2);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(),
                                1, url3_title, url3, t3);

  model->AddURLWithCreationTime(model->other_node(), 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->other_node(), 1, url2_title, url2, t2);
  const BookmarkNode* f3 = model->AddGroup(model->other_node(), 2, f3_title);
  const BookmarkNode* f4 = model->AddGroup(f3, 0, f4_title);
  model->AddURLWithCreationTime(f4, 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(), 2, url4_title,
                                url4, t4);

  // Write to a temp file.
  BookmarksObserver observer(&message_loop);
  bookmark_html_writer::WriteBookmarks(&profile, path_, &observer);
  message_loop.Run();

  // Clear favicon so that it would be read from file.
  std::vector<unsigned char> empty_data;
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  empty_data);
  message_loop.RunAllPending();

  // Read the bookmarks back in.
  std::vector<ProfileWriter::BookmarkEntry> parsed_bookmarks;
  std::vector<history::ImportedFavIconUsage> favicons;
  Firefox2Importer::ImportBookmarksFile(path_, std::set<GURL>(),
                                        false, L"x", NULL, &parsed_bookmarks,
                                        NULL, &favicons);

  // Check loaded favicon (url1 is represents by 3 separate bookmarks).
  EXPECT_EQ(3U, favicons.size());
  for (size_t i = 0; i < favicons.size(); i++) {
    if (url1_favicon == favicons[i].favicon_url) {
      EXPECT_EQ(1U, favicons[i].urls.size());
      std::set<GURL>::const_iterator iter = favicons[i].urls.find(url1);
      ASSERT_TRUE(iter != favicons[i].urls.end());
      ASSERT_TRUE(*iter == url1);
      ASSERT_TRUE(favicons[i].png_data == icon_data);
    }
  }

  // Verify we got back what we wrote.
  ASSERT_EQ(7U, parsed_bookmarks.size());
  // Windows and ChromeOS builds use Sentence case.
  string16 bookmark_folder_name =
      l10n_util::GetStringUTF16(IDS_BOOMARK_BAR_FOLDER_NAME);
  AssertBookmarkEntryEquals(parsed_bookmarks[0], false, url1, url1_title, t1,
                            bookmark_folder_name, f1_title, string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[1], false, url2, url2_title, t2,
                            bookmark_folder_name, f1_title, f2_title);
  AssertBookmarkEntryEquals(parsed_bookmarks[2], false, url3, url3_title, t3,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[3], false, url4, url4_title, t4,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[4], false, url1, url1_title, t1,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[5], false, url2, url2_title, t2,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[6], false, url1, url1_title, t1,
                            f3_title, f4_title, string16());
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "uORBTest_UnitTest.hpp"
#include "uORBCommon.hpp"
#include <px4_config.h>
#include <px4_time.h>
#include <stdio.h>

uORBTest::UnitTest &uORBTest::UnitTest::instance()
{
	static uORBTest::UnitTest t;
	return t;
}

int uORBTest::UnitTest::pubsublatency_main(void)
{
  /* poll on test topic and output latency */
  float latency_integral = 0.0f;

  /* wakeup source(s) */
  px4_pollfd_struct_t fds[3];

  int test_multi_sub = orb_subscribe_multi(ORB_ID(orb_test), 0);
  int test_multi_sub_medium = orb_subscribe_multi(ORB_ID(orb_test_medium), 0);
  int test_multi_sub_large = orb_subscribe_multi(ORB_ID(orb_test_large), 0);

  struct orb_test_large t;

  /* clear all ready flags */
  orb_copy(ORB_ID(orb_test), test_multi_sub, &t);
  orb_copy(ORB_ID(orb_test_medium), test_multi_sub_medium, &t);
  orb_copy(ORB_ID(orb_test_large), test_multi_sub_large, &t);

  fds[0].fd = test_multi_sub;
  fds[0].events = POLLIN;
  fds[1].fd = test_multi_sub_medium;
  fds[1].events = POLLIN;
  fds[2].fd = test_multi_sub_large;
  fds[2].events = POLLIN;

  const unsigned maxruns = 1000;
  unsigned timingsgroup = 0;

  unsigned *timings = new unsigned[maxruns];

  for (unsigned i = 0; i < maxruns; i++) {
    /* wait for up to 500ms for data */
    int pret = px4_poll(&fds[0], (sizeof(fds) / sizeof(fds[0])), 500);
    if (fds[0].revents & POLLIN) {
      orb_copy(ORB_ID(orb_test), test_multi_sub, &t);
      timingsgroup = 0;
    } else if (fds[1].revents & POLLIN) {
      orb_copy(ORB_ID(orb_test_medium), test_multi_sub_medium, &t);
      timingsgroup = 1;
    } else if (fds[2].revents & POLLIN) {
      orb_copy(ORB_ID(orb_test_large), test_multi_sub_large, &t);
      timingsgroup = 2;
    }

    if (pret < 0) {
      warn("poll error %d, %d", pret, errno);
      continue;
    }

    hrt_abstime elt = hrt_elapsed_time(&t.time);
    latency_integral += elt;
    timings[i] = elt;
  }

  orb_unsubscribe(test_multi_sub);
  orb_unsubscribe(test_multi_sub_medium);
  orb_unsubscribe(test_multi_sub_large);

  if (pubsubtest_print) {
    char fname[32];
    sprintf(fname, PX4_ROOTFSDIR"/fs/microsd/timings%u.txt", timingsgroup);
    FILE *f = fopen(fname, "w");
    if (f == NULL) {
      warnx("Error opening file!\n");
      return uORB::ERROR;
        }

    for (unsigned i = 0; i < maxruns; i++) {
      fprintf(f, "%u\n", timings[i]);
    }

    fclose(f);
  }

  delete[] timings;

  warnx("mean: %8.4f", static_cast<double>(latency_integral / maxruns));

  pubsubtest_passed = true;

  if (static_cast<float>(latency_integral / maxruns) > 30.0f) {
    pubsubtest_res = uORB::ERROR;
  } else {
    pubsubtest_res = PX4_OK;
  }

  return pubsubtest_res;
}

int uORBTest::UnitTest::test()
{
  struct orb_test t, u;
  int sfd;
  orb_advert_t ptopic;
  bool updated;

  t.val = 0;
  ptopic = orb_advertise(ORB_ID(orb_test), &t);

  if (ptopic == nullptr)
    return test_fail("advertise failed: %d", errno);

  test_note("publish handle 0x%08x", ptopic);
  sfd = orb_subscribe(ORB_ID(orb_test));

  if (sfd < 0)
    return test_fail("subscribe failed: %d", errno);

  test_note("subscribe fd %d", sfd);
  u.val = 1;

  if (PX4_OK != orb_copy(ORB_ID(orb_test), sfd, &u))
    return test_fail("copy(1) failed: %d", errno);

  if (u.val != t.val)
    return test_fail("copy(1) mismatch: %d expected %d", u.val, t.val);

  if (PX4_OK != orb_check(sfd, &updated))
    return test_fail("check(1) failed");

  if (updated)
    return test_fail("spurious updated flag");

  t.val = 2;
  test_note("try publish");

  if (PX4_OK != orb_publish(ORB_ID(orb_test), ptopic, &t))
    return test_fail("publish failed");

  if (PX4_OK != orb_check(sfd, &updated))
    return test_fail("check(2) failed");

  if (!updated)
    return test_fail("missing updated flag");

  if (PX4_OK != orb_copy(ORB_ID(orb_test), sfd, &u))
    return test_fail("copy(2) failed: %d", errno);

  if (u.val != t.val)
    return test_fail("copy(2) mismatch: %d expected %d", u.val, t.val);

  orb_unsubscribe(sfd);

  /* this routine tests the multi-topic support */
  test_note("try multi-topic support");

  int instance0;
  orb_advert_t pfd0 = orb_advertise_multi(ORB_ID(orb_multitest), &t, &instance0, ORB_PRIO_MAX);

  test_note("advertised");

  int instance1;
  orb_advert_t pfd1 = orb_advertise_multi(ORB_ID(orb_multitest), &t, &instance1, ORB_PRIO_MIN);

  if (instance0 != 0)
    return test_fail("mult. id0: %d", instance0);

  if (instance1 != 1)
    return test_fail("mult. id1: %d", instance1);

  t.val = 103;
  if (PX4_OK != orb_publish(ORB_ID(orb_multitest), pfd0, &t))
    return test_fail("mult. pub0 fail");

  test_note("published");

  t.val = 203;
  if (PX4_OK != orb_publish(ORB_ID(orb_multitest), pfd1, &t))
    return test_fail("mult. pub1 fail");

  /* subscribe to both topics and ensure valid data is received */
  int sfd0 = orb_subscribe_multi(ORB_ID(orb_multitest), 0);

  if (PX4_OK != orb_copy(ORB_ID(orb_multitest), sfd0, &u))
    return test_fail("sub #0 copy failed: %d", errno);

  if (u.val != 103)
    return test_fail("sub #0 val. mismatch: %d", u.val);

  int sfd1 = orb_subscribe_multi(ORB_ID(orb_multitest), 1);

  if (PX4_OK != orb_copy(ORB_ID(orb_multitest), sfd1, &u))
    return test_fail("sub #1 copy failed: %d", errno);

  if (u.val != 203)
    return test_fail("sub #1 val. mismatch: %d", u.val);

  /* test priorities */
  int prio;
  if (PX4_OK != orb_priority(sfd0, &prio))
    return test_fail("prio #0");

  if (prio != ORB_PRIO_MAX)
    return test_fail("prio: %d", prio);

  if (PX4_OK != orb_priority(sfd1, &prio))
    return test_fail("prio #1");

  if (prio != ORB_PRIO_MIN)
    return test_fail("prio: %d", prio);

  if (PX4_OK != latency_test<struct orb_test>(ORB_ID(orb_test), false))
    return test_fail("latency test failed");

  return test_note("PASS");
}

int uORBTest::UnitTest::info()
{
  return OK;
}

int uORBTest::UnitTest::test_fail(const char *fmt, ...)
{
  va_list ap;

  fprintf(stderr, "FAIL: ");
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
  fprintf(stderr, "\n");
  fflush(stderr);
  return uORB::ERROR;
}

int uORBTest::UnitTest::test_note(const char *fmt, ...)
{
  va_list ap;

  fprintf(stderr, "note: ");
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
  fprintf(stderr, "\n");
  fflush(stderr);
  return OK;
}

int uORBTest::UnitTest::pubsubtest_threadEntry(char* const argv[])
{
  uORBTest::UnitTest &t = uORBTest::UnitTest::instance();
  return t.pubsublatency_main();
}
<commit_msg>uORBTest_UnitTest: say who you are in the printf<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "uORBTest_UnitTest.hpp"
#include "uORBCommon.hpp"
#include <px4_config.h>
#include <px4_time.h>
#include <stdio.h>

uORBTest::UnitTest &uORBTest::UnitTest::instance()
{
	static uORBTest::UnitTest t;
	return t;
}

int uORBTest::UnitTest::pubsublatency_main(void)
{
  /* poll on test topic and output latency */
  float latency_integral = 0.0f;

  /* wakeup source(s) */
  px4_pollfd_struct_t fds[3];

  int test_multi_sub = orb_subscribe_multi(ORB_ID(orb_test), 0);
  int test_multi_sub_medium = orb_subscribe_multi(ORB_ID(orb_test_medium), 0);
  int test_multi_sub_large = orb_subscribe_multi(ORB_ID(orb_test_large), 0);

  struct orb_test_large t;

  /* clear all ready flags */
  orb_copy(ORB_ID(orb_test), test_multi_sub, &t);
  orb_copy(ORB_ID(orb_test_medium), test_multi_sub_medium, &t);
  orb_copy(ORB_ID(orb_test_large), test_multi_sub_large, &t);

  fds[0].fd = test_multi_sub;
  fds[0].events = POLLIN;
  fds[1].fd = test_multi_sub_medium;
  fds[1].events = POLLIN;
  fds[2].fd = test_multi_sub_large;
  fds[2].events = POLLIN;

  const unsigned maxruns = 1000;
  unsigned timingsgroup = 0;

  unsigned *timings = new unsigned[maxruns];

  for (unsigned i = 0; i < maxruns; i++) {
    /* wait for up to 500ms for data */
    int pret = px4_poll(&fds[0], (sizeof(fds) / sizeof(fds[0])), 500);
    if (fds[0].revents & POLLIN) {
      orb_copy(ORB_ID(orb_test), test_multi_sub, &t);
      timingsgroup = 0;
    } else if (fds[1].revents & POLLIN) {
      orb_copy(ORB_ID(orb_test_medium), test_multi_sub_medium, &t);
      timingsgroup = 1;
    } else if (fds[2].revents & POLLIN) {
      orb_copy(ORB_ID(orb_test_large), test_multi_sub_large, &t);
      timingsgroup = 2;
    }

    if (pret < 0) {
      warn("poll error %d, %d", pret, errno);
      continue;
    }

    hrt_abstime elt = hrt_elapsed_time(&t.time);
    latency_integral += elt;
    timings[i] = elt;
  }

  orb_unsubscribe(test_multi_sub);
  orb_unsubscribe(test_multi_sub_medium);
  orb_unsubscribe(test_multi_sub_large);

  if (pubsubtest_print) {
    char fname[32];
    sprintf(fname, PX4_ROOTFSDIR"/fs/microsd/timings%u.txt", timingsgroup);
    FILE *f = fopen(fname, "w");
    if (f == NULL) {
      warnx("Error opening file!\n");
      return uORB::ERROR;
        }

    for (unsigned i = 0; i < maxruns; i++) {
      fprintf(f, "%u\n", timings[i]);
    }

    fclose(f);
  }

  delete[] timings;

  warnx("mean: %8.4f", static_cast<double>(latency_integral / maxruns));

  pubsubtest_passed = true;

  if (static_cast<float>(latency_integral / maxruns) > 30.0f) {
    pubsubtest_res = uORB::ERROR;
  } else {
    pubsubtest_res = PX4_OK;
  }

  return pubsubtest_res;
}

int uORBTest::UnitTest::test()
{
  struct orb_test t, u;
  int sfd;
  orb_advert_t ptopic;
  bool updated;

  t.val = 0;
  ptopic = orb_advertise(ORB_ID(orb_test), &t);

  if (ptopic == nullptr)
    return test_fail("advertise failed: %d", errno);

  test_note("publish handle 0x%08x", ptopic);
  sfd = orb_subscribe(ORB_ID(orb_test));

  if (sfd < 0)
    return test_fail("subscribe failed: %d", errno);

  test_note("subscribe fd %d", sfd);
  u.val = 1;

  if (PX4_OK != orb_copy(ORB_ID(orb_test), sfd, &u))
    return test_fail("copy(1) failed: %d", errno);

  if (u.val != t.val)
    return test_fail("copy(1) mismatch: %d expected %d", u.val, t.val);

  if (PX4_OK != orb_check(sfd, &updated))
    return test_fail("check(1) failed");

  if (updated)
    return test_fail("spurious updated flag");

  t.val = 2;
  test_note("try publish");

  if (PX4_OK != orb_publish(ORB_ID(orb_test), ptopic, &t))
    return test_fail("publish failed");

  if (PX4_OK != orb_check(sfd, &updated))
    return test_fail("check(2) failed");

  if (!updated)
    return test_fail("missing updated flag");

  if (PX4_OK != orb_copy(ORB_ID(orb_test), sfd, &u))
    return test_fail("copy(2) failed: %d", errno);

  if (u.val != t.val)
    return test_fail("copy(2) mismatch: %d expected %d", u.val, t.val);

  orb_unsubscribe(sfd);

  /* this routine tests the multi-topic support */
  test_note("try multi-topic support");

  int instance0;
  orb_advert_t pfd0 = orb_advertise_multi(ORB_ID(orb_multitest), &t, &instance0, ORB_PRIO_MAX);

  test_note("advertised");

  int instance1;
  orb_advert_t pfd1 = orb_advertise_multi(ORB_ID(orb_multitest), &t, &instance1, ORB_PRIO_MIN);

  if (instance0 != 0)
    return test_fail("mult. id0: %d", instance0);

  if (instance1 != 1)
    return test_fail("mult. id1: %d", instance1);

  t.val = 103;
  if (PX4_OK != orb_publish(ORB_ID(orb_multitest), pfd0, &t))
    return test_fail("mult. pub0 fail");

  test_note("published");

  t.val = 203;
  if (PX4_OK != orb_publish(ORB_ID(orb_multitest), pfd1, &t))
    return test_fail("mult. pub1 fail");

  /* subscribe to both topics and ensure valid data is received */
  int sfd0 = orb_subscribe_multi(ORB_ID(orb_multitest), 0);

  if (PX4_OK != orb_copy(ORB_ID(orb_multitest), sfd0, &u))
    return test_fail("sub #0 copy failed: %d", errno);

  if (u.val != 103)
    return test_fail("sub #0 val. mismatch: %d", u.val);

  int sfd1 = orb_subscribe_multi(ORB_ID(orb_multitest), 1);

  if (PX4_OK != orb_copy(ORB_ID(orb_multitest), sfd1, &u))
    return test_fail("sub #1 copy failed: %d", errno);

  if (u.val != 203)
    return test_fail("sub #1 val. mismatch: %d", u.val);

  /* test priorities */
  int prio;
  if (PX4_OK != orb_priority(sfd0, &prio))
    return test_fail("prio #0");

  if (prio != ORB_PRIO_MAX)
    return test_fail("prio: %d", prio);

  if (PX4_OK != orb_priority(sfd1, &prio))
    return test_fail("prio #1");

  if (prio != ORB_PRIO_MIN)
    return test_fail("prio: %d", prio);

  if (PX4_OK != latency_test<struct orb_test>(ORB_ID(orb_test), false))
    return test_fail("latency test failed");

  return test_note("PASS");
}

int uORBTest::UnitTest::info()
{
  return OK;
}

int uORBTest::UnitTest::test_fail(const char *fmt, ...)
{
  va_list ap;

  fprintf(stderr, "uORB FAIL: ");
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
  fprintf(stderr, "\n");
  fflush(stderr);
  return uORB::ERROR;
}

int uORBTest::UnitTest::test_note(const char *fmt, ...)
{
  va_list ap;

  fprintf(stderr, "uORB note: ");
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
  fprintf(stderr, "\n");
  fflush(stderr);
  return OK;
}

int uORBTest::UnitTest::pubsubtest_threadEntry(char* const argv[])
{
  uORBTest::UnitTest &t = uORBTest::UnitTest::instance();
  return t.pubsublatency_main();
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "chrome/browser/dom_ui/options/personal_options_handler.h"

#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/path_service.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/options/options_managed_banner_handler.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif  // defined(TOOLKIT_GTK)
#include "chrome/browser/options_page_base.h"
#include "chrome/browser/options_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/chrome_paths.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"

PersonalOptionsHandler::PersonalOptionsHandler() {
}

PersonalOptionsHandler::~PersonalOptionsHandler() {
  ProfileSyncService* sync_service =
      dom_ui_->GetProfile()->GetProfileSyncService();
  if (sync_service)
    sync_service->RemoveObserver(this);
}

void PersonalOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  localized_strings->SetString("sync_disabled_info",
      l10n_util::GetStringUTF16(IDS_SYNC_IS_DISABLED_INFO));
  localized_strings->SetString("sync_section",
      l10n_util::GetStringUTF16(IDS_SYNC_OPTIONS_GROUP_NAME));
  localized_strings->SetString("sync_not_setup_info",
      l10n_util::GetStringFUTF16(IDS_SYNC_NOT_SET_UP_INFO,
          l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  localized_strings->SetString("start_sync",
      l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL));
  localized_strings->SetString("sync_customize",
      l10n_util::GetStringUTF16(IDS_SYNC_CUSTOMIZE_BUTTON_LABEL));
  localized_strings->SetString("stop_sync",
      l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_BUTTON_LABEL));
  localized_strings->SetString("stop_syncing_explanation",
      l10n_util::GetStringFUTF16(IDS_SYNC_STOP_SYNCING_EXPLANATION_LABEL,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  localized_strings->SetString("stop_syncing_title",
      l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_DIALOG_TITLE));
  localized_strings->SetString("stop_syncing_confirm_button_label",
      l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_CONFIRM_BUTTON_LABEL));
  localized_strings->SetString("privacy_dashboard_link",
      l10n_util::GetStringUTF16(IDS_SYNC_PRIVACY_DASHBOARD_LINK_LABEL));

  localized_strings->SetString("passwords",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_GROUP_NAME));
  localized_strings->SetString("passwords_asktosave",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_ASKTOSAVE));
  localized_strings->SetString("passwords_neversave",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_NEVERSAVE));
  localized_strings->SetString("showpasswords",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_SHOWPASSWORDS));

  localized_strings->SetString("autofill",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME));
  localized_strings->SetString("autofill_options",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS));

  localized_strings->SetString("browsing_data",
      l10n_util::GetStringUTF16(IDS_OPTIONS_BROWSING_DATA_GROUP_NAME));
  localized_strings->SetString("import_data",
      l10n_util::GetStringUTF16(IDS_OPTIONS_IMPORT_DATA_BUTTON));

#if defined(TOOLKIT_GTK)
  localized_strings->SetString("appearance",
      l10n_util::GetStringUTF16(IDS_APPEARANCE_GROUP_NAME));
  localized_strings->SetString("themes_GTK_button",
      l10n_util::GetStringUTF16(IDS_THEMES_GTK_BUTTON));
  localized_strings->SetString("themes_set_classic",
      l10n_util::GetStringUTF16(IDS_THEMES_SET_CLASSIC));
  localized_strings->SetString("showWindow_decorations_radio",
      l10n_util::GetStringUTF16(IDS_SHOW_WINDOW_DECORATIONS_RADIO));
  localized_strings->SetString("hideWindow_decorations_radio",
      l10n_util::GetStringUTF16(IDS_HIDE_WINDOW_DECORATIONS_RADIO));
  localized_strings->SetString("themes_gallery",
      l10n_util::GetStringUTF16(IDS_THEMES_GALLERY_BUTTON));
#else
  localized_strings->SetString("themes",
      l10n_util::GetStringUTF16(IDS_THEMES_GROUP_NAME));
  localized_strings->SetString("themes_reset",
      l10n_util::GetStringUTF16(IDS_THEMES_RESET_BUTTON));
  localized_strings->SetString("themes_gallery",
      l10n_util::GetStringUTF16(IDS_THEMES_GALLERY_BUTTON));
  localized_strings->SetString("themes_default",
      l10n_util::GetStringUTF16(IDS_THEMES_DEFAULT_THEME_LABEL));
#endif
}

void PersonalOptionsHandler::RegisterMessages() {
  DCHECK(dom_ui_);
  dom_ui_->RegisterMessageCallback(
      "showSyncLoginDialog",
      NewCallback(this, &PersonalOptionsHandler::ShowSyncLoginDialog));
  dom_ui_->RegisterMessageCallback(
      "openPrivacyDashboardTabAndActivate",
      NewCallback(this,
                  &PersonalOptionsHandler::OpenPrivacyDashboardTabAndActivate));
  dom_ui_->RegisterMessageCallback(
      "themesReset",
      NewCallback(this, &PersonalOptionsHandler::ThemesReset));
  dom_ui_->RegisterMessageCallback(
      "themesGallery",
      NewCallback(this, &PersonalOptionsHandler::ThemesGallery));
#if defined(TOOLKIT_GTK)
  dom_ui_->RegisterMessageCallback(
      "themesSetGTK",
      NewCallback(this, &PersonalOptionsHandler::ThemesSetGTK));
#endif
}

void PersonalOptionsHandler::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  if (type == NotificationType::BROWSER_THEME_CHANGED)
    ObserveThemeChanged();
  else
    OptionsPageUIHandler::Observe(type, source, details);
}

void PersonalOptionsHandler::OnStateChanged() {
  string16 status_label;
  string16 link_label;
  ProfileSyncService* service = dom_ui_->GetProfile()->GetProfileSyncService();
  bool managed = service->IsManaged();
  bool sync_setup_completed = service->HasSyncSetupCompleted();
  bool status_has_error = sync_ui_util::GetStatusLabels(service,
      &status_label, &link_label) == sync_ui_util::SYNC_ERROR;

  string16 start_stop_button_label;
  bool is_start_stop_button_visible = false;
  bool is_start_stop_button_enabled = false;
  if (sync_setup_completed) {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_BUTTON_LABEL);
#if defined(OS_CHROMEOS)
    is_start_stop_button_visible = false;
#else
    is_start_stop_button_visible = true;
#endif
    is_start_stop_button_enabled = !managed;
  } else if (service->SetupInProgress()) {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_NTP_SETUP_IN_PROGRESS);
    is_start_stop_button_visible = true;
    is_start_stop_button_enabled = false;
  } else {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL);
    is_start_stop_button_visible = true;
    is_start_stop_button_enabled = !managed;
  }

  scoped_ptr<Value> completed(Value::CreateBooleanValue(sync_setup_completed));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncSetupCompleted",
                                  *completed);

  scoped_ptr<Value> label(Value::CreateStringValue(status_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncStatus",
                                  *label);

  scoped_ptr<Value> enabled(
      Value::CreateBooleanValue(is_start_stop_button_enabled));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setStartStopButtonEnabled",
                                  *enabled);

  scoped_ptr<Value> visible(
      Value::CreateBooleanValue(is_start_stop_button_visible));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setStartStopButtonVisible",
                                  *visible);

  label.reset(Value::CreateStringValue(start_stop_button_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setStartStopButtonLabel",
                                  *label);

  visible.reset(Value::CreateBooleanValue(
      sync_setup_completed && !status_has_error));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setCustomizeButtonVisible",
                                  *visible);

  enabled.reset(Value::CreateBooleanValue(!managed));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setCustomizeButtonEnabled",
                                  *enabled);

  string16 customize_button_label =
    l10n_util::GetStringUTF16(IDS_SYNC_CUSTOMIZE_BUTTON_LABEL);
  label.reset(Value::CreateStringValue(customize_button_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setCustomizeButtonLabel",
                                  *label);

#if !defined(OS_CHROMEOS)
  label.reset(Value::CreateStringValue(link_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncActionLinkLabel",
                                  *label);

  enabled.reset(Value::CreateBooleanValue(!managed));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncActionLinkEnabled",
                                  *enabled);
#endif

  visible.reset(Value::CreateBooleanValue(status_has_error));
  dom_ui_->CallJavascriptFunction(
    L"PersonalOptions.setSyncStatusErrorVisible", *visible);
#if !defined(OS_CHROMEOS)
  dom_ui_->CallJavascriptFunction(
    L"PersonalOptions.setSyncActionLinkErrorVisible", *visible);
#endif
}

void PersonalOptionsHandler::ObserveThemeChanged() {
  Profile* profile = dom_ui_->GetProfile();
#if defined(TOOLKIT_GTK)
  GtkThemeProvider* provider = GtkThemeProvider::GetFrom(profile);
  bool is_gtk_theme = provider->UseGtkTheme();
  FundamentalValue gtk_enabled(!is_gtk_theme);
  dom_ui_->CallJavascriptFunction(
      L"options.PersonalOptions.setGtkThemeButtonEnabled", gtk_enabled);
#else
  BrowserThemeProvider* provider =
      reinterpret_cast<BrowserThemeProvider*>(profile->GetThemeProvider());
  bool is_gtk_theme = false;
#endif

  bool is_classic_theme = !is_gtk_theme && provider->GetThemeID().empty();
  FundamentalValue classic_enabled(!is_classic_theme);
  dom_ui_->CallJavascriptFunction(
      L"options.PersonalOptions.setClassicThemeButtonEnabled", classic_enabled);
}

void PersonalOptionsHandler::Initialize() {
  banner_handler_.reset(
      new OptionsManagedBannerHandler(dom_ui_,
                                      ASCIIToUTF16("PersonalOptions"),
                                      OPTIONS_PAGE_CONTENT));

  // Listen for theme installation.
  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());
  ObserveThemeChanged();

  // Explicitly enable synchronization option if needed.
  scoped_ptr<Value> is_sync_enabled(
      Value::CreateBooleanValue(ProfileSyncService::IsSyncEnabled()));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.enableSync",
                                  *is_sync_enabled);

  ProfileSyncService* sync_service =
      dom_ui_->GetProfile()->GetProfileSyncService();
  if (sync_service) {
    sync_service->AddObserver(this);
    OnStateChanged();
  }
}

void PersonalOptionsHandler::ShowSyncLoginDialog(const ListValue* args) {
  ProfileSyncService* service = dom_ui_->GetProfile()->GetProfileSyncService();
  service->ShowLoginDialog(NULL);
  ProfileSyncService::SyncEvent(ProfileSyncService::START_FROM_OPTIONS);
}

void PersonalOptionsHandler::OpenPrivacyDashboardTabAndActivate(
    const ListValue* args) {
  BrowserList::GetLastActive()->OpenPrivacyDashboardTabAndActivate();
}

void PersonalOptionsHandler::ThemesReset(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_ThemesReset"));
  dom_ui_->GetProfile()->ClearTheme();
}

void PersonalOptionsHandler::ThemesGallery(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_ThemesGallery"));
  BrowserList::GetLastActive()->OpenThemeGalleryTabAndActivate();
}

#if defined(TOOLKIT_GTK)
void PersonalOptionsHandler::ThemesSetGTK(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_GtkThemeSet"));
  dom_ui_->GetProfile()->SetNativeTheme();
}
#endif
<commit_msg>DOMUI: Remove a call to the sync JS that no longer exists.<commit_after>// Copyright (c) 2010 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 "chrome/browser/dom_ui/options/personal_options_handler.h"

#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/path_service.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/options/options_managed_banner_handler.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif  // defined(TOOLKIT_GTK)
#include "chrome/browser/options_page_base.h"
#include "chrome/browser/options_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/chrome_paths.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"

PersonalOptionsHandler::PersonalOptionsHandler() {
}

PersonalOptionsHandler::~PersonalOptionsHandler() {
  ProfileSyncService* sync_service =
      dom_ui_->GetProfile()->GetProfileSyncService();
  if (sync_service)
    sync_service->RemoveObserver(this);
}

void PersonalOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  localized_strings->SetString("sync_disabled_info",
      l10n_util::GetStringUTF16(IDS_SYNC_IS_DISABLED_INFO));
  localized_strings->SetString("sync_section",
      l10n_util::GetStringUTF16(IDS_SYNC_OPTIONS_GROUP_NAME));
  localized_strings->SetString("sync_not_setup_info",
      l10n_util::GetStringFUTF16(IDS_SYNC_NOT_SET_UP_INFO,
          l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  localized_strings->SetString("start_sync",
      l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL));
  localized_strings->SetString("sync_customize",
      l10n_util::GetStringUTF16(IDS_SYNC_CUSTOMIZE_BUTTON_LABEL));
  localized_strings->SetString("stop_sync",
      l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_BUTTON_LABEL));
  localized_strings->SetString("stop_syncing_explanation",
      l10n_util::GetStringFUTF16(IDS_SYNC_STOP_SYNCING_EXPLANATION_LABEL,
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
  localized_strings->SetString("stop_syncing_title",
      l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_DIALOG_TITLE));
  localized_strings->SetString("stop_syncing_confirm_button_label",
      l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_CONFIRM_BUTTON_LABEL));
  localized_strings->SetString("privacy_dashboard_link",
      l10n_util::GetStringUTF16(IDS_SYNC_PRIVACY_DASHBOARD_LINK_LABEL));

  localized_strings->SetString("passwords",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_GROUP_NAME));
  localized_strings->SetString("passwords_asktosave",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_ASKTOSAVE));
  localized_strings->SetString("passwords_neversave",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_NEVERSAVE));
  localized_strings->SetString("showpasswords",
      l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_SHOWPASSWORDS));

  localized_strings->SetString("autofill",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME));
  localized_strings->SetString("autofill_options",
      l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS));

  localized_strings->SetString("browsing_data",
      l10n_util::GetStringUTF16(IDS_OPTIONS_BROWSING_DATA_GROUP_NAME));
  localized_strings->SetString("import_data",
      l10n_util::GetStringUTF16(IDS_OPTIONS_IMPORT_DATA_BUTTON));

#if defined(TOOLKIT_GTK)
  localized_strings->SetString("appearance",
      l10n_util::GetStringUTF16(IDS_APPEARANCE_GROUP_NAME));
  localized_strings->SetString("themes_GTK_button",
      l10n_util::GetStringUTF16(IDS_THEMES_GTK_BUTTON));
  localized_strings->SetString("themes_set_classic",
      l10n_util::GetStringUTF16(IDS_THEMES_SET_CLASSIC));
  localized_strings->SetString("showWindow_decorations_radio",
      l10n_util::GetStringUTF16(IDS_SHOW_WINDOW_DECORATIONS_RADIO));
  localized_strings->SetString("hideWindow_decorations_radio",
      l10n_util::GetStringUTF16(IDS_HIDE_WINDOW_DECORATIONS_RADIO));
  localized_strings->SetString("themes_gallery",
      l10n_util::GetStringUTF16(IDS_THEMES_GALLERY_BUTTON));
#else
  localized_strings->SetString("themes",
      l10n_util::GetStringUTF16(IDS_THEMES_GROUP_NAME));
  localized_strings->SetString("themes_reset",
      l10n_util::GetStringUTF16(IDS_THEMES_RESET_BUTTON));
  localized_strings->SetString("themes_gallery",
      l10n_util::GetStringUTF16(IDS_THEMES_GALLERY_BUTTON));
  localized_strings->SetString("themes_default",
      l10n_util::GetStringUTF16(IDS_THEMES_DEFAULT_THEME_LABEL));
#endif
}

void PersonalOptionsHandler::RegisterMessages() {
  DCHECK(dom_ui_);
  dom_ui_->RegisterMessageCallback(
      "showSyncLoginDialog",
      NewCallback(this, &PersonalOptionsHandler::ShowSyncLoginDialog));
  dom_ui_->RegisterMessageCallback(
      "openPrivacyDashboardTabAndActivate",
      NewCallback(this,
                  &PersonalOptionsHandler::OpenPrivacyDashboardTabAndActivate));
  dom_ui_->RegisterMessageCallback(
      "themesReset",
      NewCallback(this, &PersonalOptionsHandler::ThemesReset));
  dom_ui_->RegisterMessageCallback(
      "themesGallery",
      NewCallback(this, &PersonalOptionsHandler::ThemesGallery));
#if defined(TOOLKIT_GTK)
  dom_ui_->RegisterMessageCallback(
      "themesSetGTK",
      NewCallback(this, &PersonalOptionsHandler::ThemesSetGTK));
#endif
}

void PersonalOptionsHandler::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  if (type == NotificationType::BROWSER_THEME_CHANGED)
    ObserveThemeChanged();
  else
    OptionsPageUIHandler::Observe(type, source, details);
}

void PersonalOptionsHandler::OnStateChanged() {
  string16 status_label;
  string16 link_label;
  ProfileSyncService* service = dom_ui_->GetProfile()->GetProfileSyncService();
  bool managed = service->IsManaged();
  bool sync_setup_completed = service->HasSyncSetupCompleted();
  bool status_has_error = sync_ui_util::GetStatusLabels(service,
      &status_label, &link_label) == sync_ui_util::SYNC_ERROR;

  string16 start_stop_button_label;
  bool is_start_stop_button_visible = false;
  bool is_start_stop_button_enabled = false;
  if (sync_setup_completed) {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_STOP_SYNCING_BUTTON_LABEL);
#if defined(OS_CHROMEOS)
    is_start_stop_button_visible = false;
#else
    is_start_stop_button_visible = true;
#endif
    is_start_stop_button_enabled = !managed;
  } else if (service->SetupInProgress()) {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_NTP_SETUP_IN_PROGRESS);
    is_start_stop_button_visible = true;
    is_start_stop_button_enabled = false;
  } else {
    start_stop_button_label =
        l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL);
    is_start_stop_button_visible = true;
    is_start_stop_button_enabled = !managed;
  }

  scoped_ptr<Value> completed(Value::CreateBooleanValue(sync_setup_completed));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncSetupCompleted",
                                  *completed);

  scoped_ptr<Value> label(Value::CreateStringValue(status_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncStatus",
                                  *label);

  scoped_ptr<Value> enabled(
      Value::CreateBooleanValue(is_start_stop_button_enabled));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setStartStopButtonEnabled",
                                  *enabled);

  scoped_ptr<Value> visible(
      Value::CreateBooleanValue(is_start_stop_button_visible));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setStartStopButtonVisible",
                                  *visible);

  label.reset(Value::CreateStringValue(start_stop_button_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setStartStopButtonLabel",
                                  *label);

  visible.reset(Value::CreateBooleanValue(
      sync_setup_completed && !status_has_error));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setCustomizeButtonVisible",
                                  *visible);

  enabled.reset(Value::CreateBooleanValue(!managed));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setCustomizeButtonEnabled",
                                  *enabled);

  string16 customize_button_label =
    l10n_util::GetStringUTF16(IDS_SYNC_CUSTOMIZE_BUTTON_LABEL);
  label.reset(Value::CreateStringValue(customize_button_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setCustomizeButtonLabel",
                                  *label);

#if !defined(OS_CHROMEOS)
  label.reset(Value::CreateStringValue(link_label));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncActionLinkLabel",
                                  *label);

  enabled.reset(Value::CreateBooleanValue(!managed));
  dom_ui_->CallJavascriptFunction(L"PersonalOptions.setSyncActionLinkEnabled",
                                  *enabled);
#endif

  visible.reset(Value::CreateBooleanValue(status_has_error));
  dom_ui_->CallJavascriptFunction(
    L"PersonalOptions.setSyncStatusErrorVisible", *visible);
#if !defined(OS_CHROMEOS)
  dom_ui_->CallJavascriptFunction(
    L"PersonalOptions.setSyncActionLinkErrorVisible", *visible);
#endif
}

void PersonalOptionsHandler::ObserveThemeChanged() {
  Profile* profile = dom_ui_->GetProfile();
#if defined(TOOLKIT_GTK)
  GtkThemeProvider* provider = GtkThemeProvider::GetFrom(profile);
  bool is_gtk_theme = provider->UseGtkTheme();
  FundamentalValue gtk_enabled(!is_gtk_theme);
  dom_ui_->CallJavascriptFunction(
      L"options.PersonalOptions.setGtkThemeButtonEnabled", gtk_enabled);
#else
  BrowserThemeProvider* provider =
      reinterpret_cast<BrowserThemeProvider*>(profile->GetThemeProvider());
  bool is_gtk_theme = false;
#endif

  bool is_classic_theme = !is_gtk_theme && provider->GetThemeID().empty();
  FundamentalValue classic_enabled(!is_classic_theme);
  dom_ui_->CallJavascriptFunction(
      L"options.PersonalOptions.setClassicThemeButtonEnabled", classic_enabled);
}

void PersonalOptionsHandler::Initialize() {
  banner_handler_.reset(
      new OptionsManagedBannerHandler(dom_ui_,
                                      ASCIIToUTF16("PersonalOptions"),
                                      OPTIONS_PAGE_CONTENT));

  // Listen for theme installation.
  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());
  ObserveThemeChanged();

  ProfileSyncService* sync_service =
      dom_ui_->GetProfile()->GetProfileSyncService();
  if (sync_service) {
    sync_service->AddObserver(this);
    OnStateChanged();
  }
}

void PersonalOptionsHandler::ShowSyncLoginDialog(const ListValue* args) {
  ProfileSyncService* service = dom_ui_->GetProfile()->GetProfileSyncService();
  service->ShowLoginDialog(NULL);
  ProfileSyncService::SyncEvent(ProfileSyncService::START_FROM_OPTIONS);
}

void PersonalOptionsHandler::OpenPrivacyDashboardTabAndActivate(
    const ListValue* args) {
  BrowserList::GetLastActive()->OpenPrivacyDashboardTabAndActivate();
}

void PersonalOptionsHandler::ThemesReset(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_ThemesReset"));
  dom_ui_->GetProfile()->ClearTheme();
}

void PersonalOptionsHandler::ThemesGallery(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_ThemesGallery"));
  BrowserList::GetLastActive()->OpenThemeGalleryTabAndActivate();
}

#if defined(TOOLKIT_GTK)
void PersonalOptionsHandler::ThemesSetGTK(const ListValue* args) {
  UserMetricsRecordAction(UserMetricsAction("Options_GtkThemeSet"));
  dom_ui_->GetProfile()->SetNativeTheme();
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ZipPackageStream.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:20:13 $
 *
 *  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 _ZIP_PACKAGE_STREAM_HXX
#define _ZIP_PACKAGE_STREAM_HXX

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_
#include <com/sun/star/io/XActiveDataSink.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_XDATASINKENCRSUPPORT_HPP_
#include <com/sun/star/packages/XDataSinkEncrSupport.hpp>
#endif

#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _VOS_REF_H_
#include <vos/ref.hxx>
#endif
#ifndef _ENCRYPTION_DATA_HXX_
#include <EncryptionData.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef __MUTEXHOLDER_HXX_
#include <mutexholder.hxx>
#endif

#define PACKAGE_STREAM_NOTSET           0
#define PACKAGE_STREAM_PACKAGEMEMBER    1
#define PACKAGE_STREAM_DETECT           2
#define PACKAGE_STREAM_DATA             3
#define PACKAGE_STREAM_RAW              4

class ZipPackage;
struct ZipEntry;
class ZipPackageStream : public cppu::ImplInheritanceHelper2
<
    ZipPackageEntry,
    ::com::sun::star::io::XActiveDataSink,
    ::com::sun::star::packages::XDataSinkEncrSupport
>
{
    static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;
protected:
    com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
    const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > m_xFactory;
    ZipPackage          &rZipPackage;
    sal_Bool            bToBeCompressed, bToBeEncrypted, bHaveOwnKey, bIsEncrypted;
    vos::ORef < EncryptionData > xEncryptionData;

    sal_uInt8   m_nStreamMode;
    sal_uInt32  m_nMagicalHackPos;
    sal_uInt32  m_nMagicalHackSize;

    SotMutexHolderRef m_aSharedMutexRef;

public:
    sal_Bool HasOwnKey ()        { return bHaveOwnKey;}
    sal_Bool IsToBeCompressed () { return bToBeCompressed;}
    sal_Bool IsToBeEncrypted ()  { return bToBeEncrypted;}
    sal_Bool IsEncrypted ()      { return bIsEncrypted;}
    sal_Bool IsPackageMember ()  { return m_nStreamMode == PACKAGE_STREAM_PACKAGEMEMBER;}
    vos::ORef < EncryptionData > & getEncryptionData ()
    { return xEncryptionData;}
    const com::sun::star::uno::Sequence < sal_Int8 >& getKey ()
    { return xEncryptionData->aKey;}
    const com::sun::star::uno::Sequence < sal_uInt8 >& getInitialisationVector ()
    { return xEncryptionData->aInitVector;}
    const com::sun::star::uno::Sequence < sal_uInt8 >& getDigest ()
    { return xEncryptionData->aDigest;}
    const com::sun::star::uno::Sequence < sal_uInt8 >& getSalt ()
    { return xEncryptionData->aSalt;}
    const sal_Int32 getIterationCount ()
    { return xEncryptionData->nIterationCount;}
    const sal_Int32 getSize ()
    { return aEntry.nSize;}

    sal_uInt8 GetStreamMode() { return m_nStreamMode; }
    sal_uInt32 GetMagicalHackPos() { return m_nMagicalHackPos; }
    sal_uInt32 GetMagicalHackSize() { return m_nMagicalHackSize; }

    void SetToBeCompressed (sal_Bool bNewValue) { bToBeCompressed = bNewValue;}
    void SetIsEncrypted (sal_Bool bNewValue) { bIsEncrypted = bNewValue;}
    void SetToBeEncrypted (sal_Bool bNewValue)
    {
        bToBeEncrypted  = bNewValue;
        if ( bToBeEncrypted && xEncryptionData.isEmpty())
            xEncryptionData = new EncryptionData;
        else if ( !bToBeEncrypted && !xEncryptionData.isEmpty() )
            xEncryptionData.unbind();
    }
    void SetPackageMember (sal_Bool bNewValue);
    void setKey (const com::sun::star::uno::Sequence < sal_Int8 >& rNewKey )
    { xEncryptionData->aKey = rNewKey;}
    void setInitialisationVector (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewVector )
    { xEncryptionData->aInitVector = rNewVector;}
    void setSalt (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewSalt )
    { xEncryptionData->aSalt = rNewSalt;}
    void setDigest (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewDigest )
    { xEncryptionData->aDigest = rNewDigest;}
    void setIterationCount (const sal_Int32 nNewCount)
    { xEncryptionData->nIterationCount = nNewCount;}
    void setSize (const sal_Int32 nNewSize);

    ZipPackageStream ( ZipPackage & rNewPackage,
                        const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& xFactory,
                        sal_Bool bAllowRemoveOnInsert );
    virtual ~ZipPackageStream( void );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetRawEncrStreamNoHeaderCopy();
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > TryToGetRawFromDataStream(
                                                                                sal_Bool bAddHeaderForEncr );

    sal_Bool ParsePackageRawStream();

    void setZipEntry( const ZipEntry &rInEntry);
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawData()
        throw(::com::sun::star::uno::RuntimeException);

    static ::com::sun::star::uno::Sequence < sal_Int8 >& static_getImplementationId()
    {
        return aImplementationId;
    }

    // XActiveDataSink
    virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XDataSinkEncrSupport
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getDataStream()
        throw ( ::com::sun::star::packages::WrongPasswordException,
                ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream()
        throw ( ::com::sun::star::packages::NoEncryptionException,
                ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setDataStream(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw ( ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setRawStream(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw ( ::com::sun::star::packages::EncryptionNotAllowedException,
                ::com::sun::star::packages::NoRawFormatException,
                ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getPlainRawStream()
        throw ( ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw(::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS fwk20 (1.18.4); FILE MERGED 2005/08/03 08:38:09 mav 1.18.4.1: #i51806# close used streams in time<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ZipPackageStream.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-23 15:56:24 $
 *
 *  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 _ZIP_PACKAGE_STREAM_HXX
#define _ZIP_PACKAGE_STREAM_HXX

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_
#include <com/sun/star/io/XActiveDataSink.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_XDATASINKENCRSUPPORT_HPP_
#include <com/sun/star/packages/XDataSinkEncrSupport.hpp>
#endif

#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _VOS_REF_H_
#include <vos/ref.hxx>
#endif
#ifndef _ENCRYPTION_DATA_HXX_
#include <EncryptionData.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef __MUTEXHOLDER_HXX_
#include <mutexholder.hxx>
#endif

#define PACKAGE_STREAM_NOTSET           0
#define PACKAGE_STREAM_PACKAGEMEMBER    1
#define PACKAGE_STREAM_DETECT           2
#define PACKAGE_STREAM_DATA             3
#define PACKAGE_STREAM_RAW              4

class ZipPackage;
struct ZipEntry;
class ZipPackageStream : public cppu::ImplInheritanceHelper2
<
    ZipPackageEntry,
    ::com::sun::star::io::XActiveDataSink,
    ::com::sun::star::packages::XDataSinkEncrSupport
>
{
    static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;
protected:
    com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
    const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > m_xFactory;
    ZipPackage          &rZipPackage;
    sal_Bool            bToBeCompressed, bToBeEncrypted, bHaveOwnKey, bIsEncrypted;
    vos::ORef < EncryptionData > xEncryptionData;

    sal_uInt8   m_nStreamMode;
    sal_uInt32  m_nMagicalHackPos;
    sal_uInt32  m_nMagicalHackSize;

    SotMutexHolderRef m_aSharedMutexRef;

public:
    sal_Bool HasOwnKey ()        { return bHaveOwnKey;}
    sal_Bool IsToBeCompressed () { return bToBeCompressed;}
    sal_Bool IsToBeEncrypted ()  { return bToBeEncrypted;}
    sal_Bool IsEncrypted ()      { return bIsEncrypted;}
    sal_Bool IsPackageMember ()  { return m_nStreamMode == PACKAGE_STREAM_PACKAGEMEMBER;}
    vos::ORef < EncryptionData > & getEncryptionData ()
    { return xEncryptionData;}
    const com::sun::star::uno::Sequence < sal_Int8 >& getKey ()
    { return xEncryptionData->aKey;}
    const com::sun::star::uno::Sequence < sal_uInt8 >& getInitialisationVector ()
    { return xEncryptionData->aInitVector;}
    const com::sun::star::uno::Sequence < sal_uInt8 >& getDigest ()
    { return xEncryptionData->aDigest;}
    const com::sun::star::uno::Sequence < sal_uInt8 >& getSalt ()
    { return xEncryptionData->aSalt;}
    const sal_Int32 getIterationCount ()
    { return xEncryptionData->nIterationCount;}
    const sal_Int32 getSize ()
    { return aEntry.nSize;}

    sal_uInt8 GetStreamMode() { return m_nStreamMode; }
    sal_uInt32 GetMagicalHackPos() { return m_nMagicalHackPos; }
    sal_uInt32 GetMagicalHackSize() { return m_nMagicalHackSize; }

    void SetToBeCompressed (sal_Bool bNewValue) { bToBeCompressed = bNewValue;}
    void SetIsEncrypted (sal_Bool bNewValue) { bIsEncrypted = bNewValue;}
    void SetToBeEncrypted (sal_Bool bNewValue)
    {
        bToBeEncrypted  = bNewValue;
        if ( bToBeEncrypted && xEncryptionData.isEmpty())
            xEncryptionData = new EncryptionData;
        else if ( !bToBeEncrypted && !xEncryptionData.isEmpty() )
            xEncryptionData.unbind();
    }
    void SetPackageMember (sal_Bool bNewValue);
    void setKey (const com::sun::star::uno::Sequence < sal_Int8 >& rNewKey )
    { xEncryptionData->aKey = rNewKey;}
    void setInitialisationVector (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewVector )
    { xEncryptionData->aInitVector = rNewVector;}
    void setSalt (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewSalt )
    { xEncryptionData->aSalt = rNewSalt;}
    void setDigest (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewDigest )
    { xEncryptionData->aDigest = rNewDigest;}
    void setIterationCount (const sal_Int32 nNewCount)
    { xEncryptionData->nIterationCount = nNewCount;}
    void setSize (const sal_Int32 nNewSize);

    void CloseOwnStreamIfAny();

    ZipPackageStream ( ZipPackage & rNewPackage,
                        const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& xFactory,
                        sal_Bool bAllowRemoveOnInsert );
    virtual ~ZipPackageStream( void );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetRawEncrStreamNoHeaderCopy();
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > TryToGetRawFromDataStream(
                                                                                sal_Bool bAddHeaderForEncr );

    sal_Bool ParsePackageRawStream();

    void setZipEntry( const ZipEntry &rInEntry);
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawData()
        throw(::com::sun::star::uno::RuntimeException);

    static ::com::sun::star::uno::Sequence < sal_Int8 >& static_getImplementationId()
    {
        return aImplementationId;
    }

    // XActiveDataSink
    virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XDataSinkEncrSupport
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getDataStream()
        throw ( ::com::sun::star::packages::WrongPasswordException,
                ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream()
        throw ( ::com::sun::star::packages::NoEncryptionException,
                ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setDataStream(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw ( ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setRawStream(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw ( ::com::sun::star::packages::EncryptionNotAllowedException,
                ::com::sun::star::packages::NoRawFormatException,
                ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getPlainRawStream()
        throw ( ::com::sun::star::io::IOException,
                ::com::sun::star::uno::RuntimeException );

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw(::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2016, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program 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 Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Definitions for the SDRClassifier.
 */

#ifndef NTA_SDR_CLASSIFIER_HPP
#define NTA_SDR_CLASSIFIER_HPP

#include <deque>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#include <nupic/math/DenseMatrix.hpp>
#include <nupic/proto/SdrClassifier.capnp.h>
#include <nupic/types/Serializable.hpp>
#include <nupic/types/Types.hpp>

namespace nupic {
namespace algorithms {

typedef cla_classifier::ClassifierResult ClassifierResult;

namespace sdr_classifier {

const UInt sdrClassifierVersion = 1;

typedef Dense<UInt, Real64> Matrix;

class SDRClassifier : public Serializable<SdrClassifierProto> {
public:
  /**
   * Constructor for use when deserializing.
   */
  SDRClassifier() {}

  /**
   * Constructor.
   *
   * @param steps The different number of steps to learn and predict.
   * @param alpha The alpha to use when decaying the duty cycles.
   * @param actValueAlpha The alpha to use when decaying the actual
   *                      values for each bucket.
   * @param verbosity The logging verbosity.
   */
  SDRClassifier(const vector<UInt> &steps, Real64 alpha, Real64 actValueAlpha,
                UInt verbosity);

  /**
   * Destructor.
   */
  virtual ~SDRClassifier();

  /**
   * Compute the likelihoods for each bucket.
   *
   * @param recordNum An incrementing integer for each record. Gaps in
   *                  numbers correspond to missing records.
   * @param patternNZ The active input bit indices.
   * @param bucketIdx The current value bucket index.
   * @param actValue The current scalar value.
   * @param category Whether the actual values represent categories.
   * @param learn Whether or not to perform learning.
   * @param infer Whether or not to perform inference.
   * @param result A mapping from prediction step to a vector of
   *               likelihoods where the value at an index corresponds
   *               to the bucket with the same index. In addition, the
   *               values for key 0 correspond to the actual values to
   *               used when predicting each bucket.
   */
  virtual void compute(UInt recordNum, const vector<UInt> &patternNZ,
                       const vector<UInt> &bucketIdxList,
                       const vector<Real64> &actValueList, bool category,
                       bool learn, bool infer, ClassifierResult *result);

  /**
   * Gets the version number
   */
  UInt version() const;

  /**
   * Getter and setter for verbosity level.
   */
  UInt getVerbosity() const;
  void setVerbosity(UInt verbosity);

  /**
   * Gets the learning rate
   */
  UInt getAlpha() const;

  /**
   * Get the size of the string needed for the serialized state.
   */
  UInt persistentSize() const;

  /**
   * Save the state to the ostream.
   */
  void save(std::ostream &outStream) const;

  /**
   * Load state from istream.
   */
  void load(std::istream &inStream);

  /**
   * Save the state to the builder.
   */
  void write(SdrClassifierProto::Builder &proto) const override;

  /**
   * Save the state to the stream.
   */
  using Serializable::write;

  /**
   * Load state from reader.
   */
  void read(SdrClassifierProto::Reader &proto) override;

  /**
   * Load state from stream.
   */
  using Serializable::read;

  /**
   * Compare the other instance to this one.
   *
   * @param other Another instance of SDRClassifier to compare to.
   * @returns true iff other is identical to this instance.
   */
  virtual bool operator==(const SDRClassifier &other) const;

private:
  // Helper function for inference mode
  void infer_(const vector<UInt> &patternNZ, const vector<Real64> &actValue,
              ClassifierResult *result);

  // Helper function to compute the error signal in learning mode
  vector<Real64> calculateError_(const vector<UInt> &bucketIdxList,
                                 const vector<UInt> patternNZ, UInt step);

  // The list of prediction steps to learn and infer.
  vector<UInt> steps_;

  // The alpha used to decay the duty cycles in the BitHistorys.
  Real64 alpha_;

  // The alpha used to decay the actual values used for each bucket.
  Real64 actValueAlpha_;

  // The maximum number of the prediction steps.
  UInt maxSteps_;

  // Stores the input pattern history, starting with the previous input
  // and containing _maxSteps total input patterns.
  deque<vector<UInt>> patternNZHistory_;
  deque<UInt> recordNumHistory_;

  // Weight matrices for the classifier (one per prediction step)
  map<UInt, Matrix> weightMatrix_;

  // The highest input bit that the classifier has seen so far.
  UInt maxInputIdx_;

  // The highest bucket index that the classifier has been seen so far.
  UInt maxBucketIdx_;

  // The current actual values used for each bucket index. The index of
  // the actual value matches the index of the bucket.
  vector<Real64> actualValues_;

  // A boolean that distinguishes between actual values that have been
  // seen and those that have not.
  vector<bool> actualValuesSet_;

  // Version and verbosity.
  UInt version_;
  UInt verbosity_;
}; // end of SDRClassifier class

} // end of namespace sdr_classifier
} // end of namespace algorithms
} // namespace nupic

#endif
<commit_msg>Fix not include ClassifierResult.hpp error<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2016, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program 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 Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Definitions for the SDRClassifier.
 */

#ifndef NTA_SDR_CLASSIFIER_HPP
#define NTA_SDR_CLASSIFIER_HPP

#include <deque>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#include <nupic/math/DenseMatrix.hpp>
#include <nupic/algorithms/ClassifierResult.hpp>
#include <nupic/proto/SdrClassifier.capnp.h>
#include <nupic/types/Serializable.hpp>
#include <nupic/types/Types.hpp>

namespace nupic {
namespace algorithms {

typedef cla_classifier::ClassifierResult ClassifierResult;

namespace sdr_classifier {

const UInt sdrClassifierVersion = 1;

typedef Dense<UInt, Real64> Matrix;

class SDRClassifier : public Serializable<SdrClassifierProto> {
public:
  /**
   * Constructor for use when deserializing.
   */
  SDRClassifier() {}

  /**
   * Constructor.
   *
   * @param steps The different number of steps to learn and predict.
   * @param alpha The alpha to use when decaying the duty cycles.
   * @param actValueAlpha The alpha to use when decaying the actual
   *                      values for each bucket.
   * @param verbosity The logging verbosity.
   */
  SDRClassifier(const vector<UInt> &steps, Real64 alpha, Real64 actValueAlpha,
                UInt verbosity);

  /**
   * Destructor.
   */
  virtual ~SDRClassifier();

  /**
   * Compute the likelihoods for each bucket.
   *
   * @param recordNum An incrementing integer for each record. Gaps in
   *                  numbers correspond to missing records.
   * @param patternNZ The active input bit indices.
   * @param bucketIdx The current value bucket index.
   * @param actValue The current scalar value.
   * @param category Whether the actual values represent categories.
   * @param learn Whether or not to perform learning.
   * @param infer Whether or not to perform inference.
   * @param result A mapping from prediction step to a vector of
   *               likelihoods where the value at an index corresponds
   *               to the bucket with the same index. In addition, the
   *               values for key 0 correspond to the actual values to
   *               used when predicting each bucket.
   */
  virtual void compute(UInt recordNum, const vector<UInt> &patternNZ,
                       const vector<UInt> &bucketIdxList,
                       const vector<Real64> &actValueList, bool category,
                       bool learn, bool infer, ClassifierResult *result);

  /**
   * Gets the version number
   */
  UInt version() const;

  /**
   * Getter and setter for verbosity level.
   */
  UInt getVerbosity() const;
  void setVerbosity(UInt verbosity);

  /**
   * Gets the learning rate
   */
  UInt getAlpha() const;

  /**
   * Get the size of the string needed for the serialized state.
   */
  UInt persistentSize() const;

  /**
   * Save the state to the ostream.
   */
  void save(std::ostream &outStream) const;

  /**
   * Load state from istream.
   */
  void load(std::istream &inStream);

  /**
   * Save the state to the builder.
   */
  void write(SdrClassifierProto::Builder &proto) const override;

  /**
   * Save the state to the stream.
   */
  using Serializable::write;

  /**
   * Load state from reader.
   */
  void read(SdrClassifierProto::Reader &proto) override;

  /**
   * Load state from stream.
   */
  using Serializable::read;

  /**
   * Compare the other instance to this one.
   *
   * @param other Another instance of SDRClassifier to compare to.
   * @returns true iff other is identical to this instance.
   */
  virtual bool operator==(const SDRClassifier &other) const;

private:
  // Helper function for inference mode
  void infer_(const vector<UInt> &patternNZ, const vector<Real64> &actValue,
              ClassifierResult *result);

  // Helper function to compute the error signal in learning mode
  vector<Real64> calculateError_(const vector<UInt> &bucketIdxList,
                                 const vector<UInt> patternNZ, UInt step);

  // The list of prediction steps to learn and infer.
  vector<UInt> steps_;

  // The alpha used to decay the duty cycles in the BitHistorys.
  Real64 alpha_;

  // The alpha used to decay the actual values used for each bucket.
  Real64 actValueAlpha_;

  // The maximum number of the prediction steps.
  UInt maxSteps_;

  // Stores the input pattern history, starting with the previous input
  // and containing _maxSteps total input patterns.
  deque<vector<UInt>> patternNZHistory_;
  deque<UInt> recordNumHistory_;

  // Weight matrices for the classifier (one per prediction step)
  map<UInt, Matrix> weightMatrix_;

  // The highest input bit that the classifier has seen so far.
  UInt maxInputIdx_;

  // The highest bucket index that the classifier has been seen so far.
  UInt maxBucketIdx_;

  // The current actual values used for each bucket index. The index of
  // the actual value matches the index of the bucket.
  vector<Real64> actualValues_;

  // A boolean that distinguishes between actual values that have been
  // seen and those that have not.
  vector<bool> actualValuesSet_;

  // Version and verbosity.
  UInt version_;
  UInt verbosity_;
}; // end of SDRClassifier class

} // end of namespace sdr_classifier
} // end of namespace algorithms
} // namespace nupic

#endif
<|endoftext|>