<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include "read_line.hpp"

/**
 * Command-line interface for talking to the oblelisk server.
 */
class cli
{
public:
    ~cli();
    cli();

    int run();

private:
    void command();
    void cmd_exit();
    void cmd_help();

    bool done_;

    zmq::context_t context_;
    read_line terminal_;
};

cli::~cli()
{
}

cli::cli()
  : done_(false), terminal_(context_)
{
}

/**
 * The main loop for the example application. This loop can be woken up
 * by either events from the network or by input from the terminal.
 */
int cli::run()
{
    std::cout << "type \"help\" for instructions" << std::endl;
    terminal_.show_prompt();

    while (!done_)
    {
        auto pollitem = terminal_.pollitem();
        zmq::poll(&pollitem, 1, -1);
        command();
    }
    return 0;
}

/**
 * Reads a command from the terminal thread, and processes it appropriately.
 */
void cli::command()
{
    std::stringstream reader(terminal_.get_line());
    std::string command;
    reader >> command;

    if (command == "exit")              cmd_exit();
    else if (command == "help")         cmd_help();
    else
        std::cout << "unknown command " << command << std::endl;

    // Display another prompt, if needed:
    if (!done_)
        terminal_.show_prompt();
}

void cli::cmd_exit()
{
    done_ = true;
}

void cli::cmd_help()
{
    std::cout << "commands:" << std::endl;
    std::cout << "  exit              - leave the program" << std::endl;
    std::cout << "  help              - this menu" << std::endl;
}

int main()
{
    cli c;
    return c.run();
}
<commit_msg>examples: Start work on an event loop<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <zmq.hpp>
#include "read_line.hpp"

/**
 * A dynamically-allocated structure holding the resources needed for a
 * connection to a bitcoin server.
 */
class connection
{
public:
    connection(zmq::context_t& context, const std::string& server)
      : socket(context, ZMQ_DEALER)
    {
        // Do not wait for unsent messages when shutting down:
        int linger = 0;
        socket.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
        socket.connect(server.c_str());
    }

    zmq::socket_t socket;
};

/**
 * Command-line interface for talking to the oblelisk server.
 */
class cli
{
public:
    ~cli();
    cli();

    int run();

private:
    void command();
    void cmd_exit();
    void cmd_help();
    void cmd_connect(std::stringstream& args);
    void cmd_disconnect(std::stringstream& args);

    bool check_connection();
    bool read_string(std::stringstream& args, std::string& out,
        const std::string& error_message);

    bool done_;

    zmq::context_t context_;
    read_line terminal_;
    connection *connection_;
};

cli::~cli()
{
    delete connection_;
}

cli::cli()
  : done_(false), terminal_(context_), connection_(nullptr)
{
}

/**
 * The main loop for the example application. This loop can be woken up
 * by either events from the network or by input from the terminal.
 */
int cli::run()
{
    std::cout << "type \"help\" for instructions" << std::endl;
    terminal_.show_prompt();

    while (!done_)
    {
        std::vector<zmq_pollitem_t> items;
        items.reserve(2);
        items.push_back(terminal_.pollitem());
        if (connection_)
            items.push_back(zmq_pollitem_t
                {connection_->socket, 0, ZMQ_POLLIN});
        zmq::poll(items.data(), items.size(), -1);

        if (items[0].revents)
            command();
        if (connection_ && items[1].revents)
            ; // Server
    }
    return 0;
}

/**
 * Reads a command from the terminal thread, and processes it appropriately.
 */
void cli::command()
{
    std::stringstream reader(terminal_.get_line());
    std::string command;
    reader >> command;

    if (command == "exit")              cmd_exit();
    else if (command == "help")         cmd_help();
    else if (command == "connect")      cmd_connect(reader);
    else if (command == "disconnect")   cmd_disconnect(reader);
    else
        std::cout << "unknown command " << command << std::endl;

    // Display another prompt, if needed:
    if (!done_)
        terminal_.show_prompt();
}

void cli::cmd_exit()
{
    done_ = true;
}

void cli::cmd_help()
{
    std::cout << "commands:" << std::endl;
    std::cout << "  exit              - leave the program" << std::endl;
    std::cout << "  help              - this menu" << std::endl;
    std::cout << "  connect <server>  - connect to a server" << std::endl;
    std::cout << "  disconnect        - disconnect from the server" << std::endl;
}

void cli::cmd_connect(std::stringstream& args)
{
    std::string server;
    if (!read_string(args, server, "error: no server given"))
        return;
    std::cout << "connecting to " << server << std::endl;

    delete connection_;
    connection_ = nullptr;
    try
    {
        connection_ = new connection(context_, server);
    }
    catch (zmq::error_t)
    {
        std::cout << "error: failed to connect" << std::endl;
    }
}

void cli::cmd_disconnect(std::stringstream& args)
{
    if (!check_connection())
        return;
    delete connection_;
    connection_ = nullptr;
}

/**
 * Verifies that a connection exists, and prints an error message otherwise.
 */
bool cli::check_connection()
{
    if (!connection_)
    {
        std::cout << "error: no connection" << std::endl;
        return false;
    }
    return true;
}

/**
 * Parses a string argument out of the command line,
 * or prints an error message if there is none.
 */
bool cli::read_string(std::stringstream& args, std::string& out,
    const std::string& error_message)
{
    args >> out;
    if (!out.size())
    {
        std::cout << error_message << std::endl;
        return false;
    }
    return true;
}

int main()
{
    cli c;
    return c.run();
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/ui/chrome_pages.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/app_launch_params.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
#include "chrome/browser/ui/settings_window_manager.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/options/content_settings_handler.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "extensions/common/constants.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/url_util.h"
#include "ui/base/window_open_disposition.h"

#if defined(OS_WIN)
#include "chrome/browser/enumerate_modules_model_win.h"
#endif

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/genius_app/app_id.h"
#include "extensions/browser/extension_registry.h"
#endif

#if !defined(OS_ANDROID) && !defined(OS_IOS)
#include "chrome/browser/signin/signin_manager_factory.h"
#include "components/signin/core/browser/signin_manager.h"
#endif

using base::UserMetricsAction;

namespace chrome {
namespace {

const char kHashMark[] = "#";

void OpenBookmarkManagerWithHash(Browser* browser,
                                 const std::string& action,
                                 int64 node_id) {
  content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
  content::RecordAction(UserMetricsAction("ShowBookmarks"));
  NavigateParams params(GetSingletonTabNavigateParams(
      browser,
      GURL(kChromeUIBookmarksURL).Resolve(base::StringPrintf(
          "/#%s%s", action.c_str(), base::Int64ToString(node_id).c_str()))));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void NavigateToSingletonTab(Browser* browser, const GURL& url) {
  NavigateParams params(GetSingletonTabNavigateParams(browser, url));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

// Shows either the help app or the appropriate help page for |source|. If
// |browser| is NULL and the help page is used (vs the app), the help page is
// shown in the last active browser. If there is no such browser, a new browser
// is created.
void ShowHelpImpl(Browser* browser,
                  Profile* profile,
                  HostDesktopType host_desktop_type,
                  HelpSource source) {
  content::RecordAction(UserMetricsAction("ShowHelpTab"));
#if defined(OS_CHROMEOS) && defined(OFFICIAL_BUILD)
  const extensions::Extension* extension =
      extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
          genius_app::kGeniusAppId,
          extensions::ExtensionRegistry::EVERYTHING);
  extensions::AppLaunchSource app_launch_source(extensions::SOURCE_UNTRACKED);
  switch (source) {
    case HELP_SOURCE_KEYBOARD:
      app_launch_source = extensions::SOURCE_KEYBOARD;
      break;
    case HELP_SOURCE_MENU:
      app_launch_source = extensions::SOURCE_SYSTEM_TRAY;
      break;
    case HELP_SOURCE_WEBUI:
      app_launch_source = extensions::SOURCE_ABOUT_PAGE;
      break;
    default:
      NOTREACHED() << "Unhandled help source" << source;
  }
  AppLaunchParams params(profile, extension, CURRENT_TAB, host_desktop_type,
                         app_launch_source);
  OpenApplication(params);
#else
  GURL url;
  switch (source) {
    case HELP_SOURCE_KEYBOARD:
      url = GURL(kChromeHelpViaKeyboardURL);
      break;
    case HELP_SOURCE_MENU:
      url = GURL(kChromeHelpViaMenuURL);
      break;
    case HELP_SOURCE_WEBUI:
      url = GURL(kChromeHelpViaWebUIURL);
      break;
    default:
      NOTREACHED() << "Unhandled help source " << source;
  }
  scoped_ptr<ScopedTabbedBrowserDisplayer> displayer;
  if (!browser) {
    displayer.reset(
        new ScopedTabbedBrowserDisplayer(profile, host_desktop_type));
    browser = displayer->browser();
  }
  ShowSingletonTab(browser, url);
#endif
}

}  // namespace

void ShowBookmarkManager(Browser* browser) {
  content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
  content::RecordAction(UserMetricsAction("ShowBookmarks"));
  ShowSingletonTabOverwritingNTP(
      browser,
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIBookmarksURL)));
}

void ShowBookmarkManagerForNode(Browser* browser, int64 node_id) {
  OpenBookmarkManagerWithHash(browser, std::string(), node_id);
}

void ShowHistory(Browser* browser) {
  content::RecordAction(UserMetricsAction("ShowHistory"));
  NavigateParams params(
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIHistoryURL)));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowDownloads(Browser* browser) {
  content::RecordAction(UserMetricsAction("ShowDownloads"));
  if (browser->window()) {
    DownloadShelf* shelf = browser->window()->GetDownloadShelf();
    // The downloads page is always shown in response to a user action.
    if (shelf->IsShowing())
      shelf->Close(DownloadShelf::USER_ACTION);
  }
  ShowSingletonTabOverwritingNTP(
      browser,
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIDownloadsURL)));
}

void ShowExtensions(Browser* browser,
                    const std::string& extension_to_highlight) {
  content::RecordAction(UserMetricsAction("ShowExtensions"));
  NavigateParams params(
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIExtensionsURL)));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  if (!extension_to_highlight.empty()) {
    GURL::Replacements replacements;
    std::string query("id=");
    query += extension_to_highlight;
    replacements.SetQueryStr(query);
    params.url = params.url.ReplaceComponents(replacements);
  }
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowConflicts(Browser* browser) {
#if defined(OS_WIN)
  EnumerateModulesModel* model = EnumerateModulesModel::GetInstance();
  if (model->modules_to_notify_about() > 0) {
    GURL help_center_url = model->GetFirstNotableConflict();
    if (help_center_url.is_valid()) {
      ShowSingletonTab(browser, help_center_url);
      model->AcknowledgeConflictNotification();
      return;
    }
  }
#endif

  content::RecordAction(UserMetricsAction("AboutConflicts"));
  ShowSingletonTab(browser, GURL(kChromeUIConflictsURL));
}

void ShowHelp(Browser* browser, HelpSource source) {
  ShowHelpImpl(
      browser, browser->profile(), browser->host_desktop_type(), source);
}

void ShowHelpForProfile(Profile* profile,
                        HostDesktopType host_desktop_type,
                        HelpSource source) {
  ShowHelpImpl(NULL, profile, host_desktop_type, source);
}

void ShowPolicy(Browser* browser) {
  ShowSingletonTab(browser, GURL(kChromeUIPolicyURL));
}

void ShowSlow(Browser* browser) {
#if defined(OS_CHROMEOS)
  ShowSingletonTab(browser, GURL(kChromeUISlowURL));
#endif
}

void ShowMemory(Browser* browser) {
  ShowSingletonTab(browser, GURL(kChromeUIMemoryURL));
}

GURL GetSettingsUrl(const std::string& sub_page) {
  std::string url = std::string(kChromeUISettingsURL) + sub_page;
#if defined(OS_CHROMEOS)
  if (sub_page.find(kInternetOptionsSubPage, 0) != std::string::npos) {
    std::string::size_type loc = sub_page.find("?", 0);
    std::string network_page =
        loc != std::string::npos ? sub_page.substr(loc) : std::string();
    url = std::string(kChromeUISettingsURL) + network_page;
  }
#endif
  return GURL(url);
}

bool IsTrustedPopupWindowWithScheme(const Browser* browser,
                                    const std::string& scheme) {
  if (!browser->is_type_popup() || !browser->is_trusted_source())
    return false;
  if (scheme.empty())  // Any trusted popup window
    return true;
  const content::WebContents* web_contents =
      browser->tab_strip_model()->GetWebContentsAt(0);
  if (!web_contents)
    return false;
  GURL url(web_contents->GetURL());
  return url.SchemeIs(scheme.c_str());
}

void ShowSettings(Browser* browser) {
  ShowSettingsSubPage(browser, std::string());
}

void ShowSettingsSubPage(Browser* browser, const std::string& sub_page) {
  if (::switches::SettingsWindowEnabled()) {
    ShowSettingsSubPageForProfile(browser->profile(), sub_page);
    return;
  }
  ShowSettingsSubPageInTabbedBrowser(browser, sub_page);
}

void ShowSettingsSubPageForProfile(Profile* profile,
                                   const std::string& sub_page) {
  if (::switches::SettingsWindowEnabled()) {
    content::RecordAction(base::UserMetricsAction("ShowOptions"));
    SettingsWindowManager::GetInstance()->ShowChromePageForProfile(
        profile, GetSettingsUrl(sub_page));
    return;
  }
  Browser* browser =
      chrome::FindTabbedBrowser(profile, false, HOST_DESKTOP_TYPE_NATIVE);
  if (!browser) {
    browser = new Browser(
        Browser::CreateParams(profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
  }
  ShowSettingsSubPageInTabbedBrowser(browser, sub_page);
}

void ShowSettingsSubPageInTabbedBrowser(Browser* browser,
                                        const std::string& sub_page) {
  content::RecordAction(UserMetricsAction("ShowOptions"));
  GURL gurl = GetSettingsUrl(sub_page);
  NavigateParams params(GetSingletonTabNavigateParams(browser, gurl));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowContentSettings(Browser* browser,
                         ContentSettingsType content_settings_type) {
  ShowSettingsSubPage(
      browser,
      kContentSettingsExceptionsSubPage + std::string(kHashMark) +
          options::ContentSettingsHandler::ContentSettingsTypeToGroupName(
              content_settings_type));
}

void ShowClearBrowsingDataDialog(Browser* browser) {
  content::RecordAction(UserMetricsAction("ClearBrowsingData_ShowDlg"));
  ShowSettingsSubPage(browser, kClearBrowserDataSubPage);
}

void ShowPasswordManager(Browser* browser) {
  content::RecordAction(UserMetricsAction("Options_ShowPasswordManager"));
  ShowSettingsSubPage(browser, kPasswordManagerSubPage);
}

void ShowImportDialog(Browser* browser) {
  content::RecordAction(UserMetricsAction("Import_ShowDlg"));
  ShowSettingsSubPage(browser, kImportDataSubPage);
}

void ShowAboutChrome(Browser* browser) {
  content::RecordAction(UserMetricsAction("AboutChrome"));
  if (::switches::SettingsWindowEnabled()) {
    SettingsWindowManager::GetInstance()->ShowChromePageForProfile(
        browser->profile(), GURL(kChromeUIUberURL));
    return;
  }
  NavigateParams params(
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIUberURL)));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowSearchEngineSettings(Browser* browser) {
  content::RecordAction(UserMetricsAction("EditSearchEngines"));
  ShowSettingsSubPage(browser, kSearchEnginesSubPage);
}

#if !defined(OS_ANDROID) && !defined(OS_IOS)
void ShowBrowserSignin(Browser* browser, signin_metrics::Source source) {
  Profile* original_profile = browser->profile()->GetOriginalProfile();
  SigninManagerBase* manager =
      SigninManagerFactory::GetForProfile(original_profile);
  DCHECK(manager->IsSigninAllowed());
  // If the browser's profile is an incognito profile, make sure to use
  // a browser window from the original profile.  The user cannot sign in
  // from an incognito window.
  scoped_ptr<ScopedTabbedBrowserDisplayer> displayer;
  if (browser->profile()->IsOffTheRecord()) {
    displayer.reset(new ScopedTabbedBrowserDisplayer(
        original_profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
    browser = displayer->browser();
  }

  signin_metrics::LogSigninSource(source);

  // Since the app launcher is a separate application, it might steal focus
  // away from Chrome, and accidentally close the avatar bubble. In this case,
  // fallback to the full-tab signin page.
  if (switches::IsNewAvatarMenu() &&
      source != signin_metrics::SOURCE_APP_LAUNCHER) {
    browser->window()->ShowAvatarBubbleFromAvatarButton(
        BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN,
        signin::ManageAccountsParams());
  } else {
    NavigateToSingletonTab(browser, GURL(signin::GetPromoURL(source, false)));
    DCHECK_GT(browser->tab_strip_model()->count(), 0);
  }
}

void ShowBrowserSigninOrSettings(
    Browser* browser,
    signin_metrics::Source source) {
  Profile* original_profile = browser->profile()->GetOriginalProfile();
  SigninManagerBase* manager =
      SigninManagerFactory::GetForProfile(original_profile);
  DCHECK(manager->IsSigninAllowed());
  if (manager->IsAuthenticated())
    ShowSettings(browser);
  else
    ShowBrowserSignin(browser, source);
}
#endif

}  // namespace chrome
<commit_msg>Open the full-tab signin page if trying to sign in from an incognito window<commit_after>// Copyright (c) 2012 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/ui/chrome_pages.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/app_launch_params.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
#include "chrome/browser/ui/settings_window_manager.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/options/content_settings_handler.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "extensions/common/constants.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/url_util.h"
#include "ui/base/window_open_disposition.h"

#if defined(OS_WIN)
#include "chrome/browser/enumerate_modules_model_win.h"
#endif

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/genius_app/app_id.h"
#include "extensions/browser/extension_registry.h"
#endif

#if !defined(OS_ANDROID) && !defined(OS_IOS)
#include "chrome/browser/signin/signin_manager_factory.h"
#include "components/signin/core/browser/signin_manager.h"
#endif

using base::UserMetricsAction;

namespace chrome {
namespace {

const char kHashMark[] = "#";

void OpenBookmarkManagerWithHash(Browser* browser,
                                 const std::string& action,
                                 int64 node_id) {
  content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
  content::RecordAction(UserMetricsAction("ShowBookmarks"));
  NavigateParams params(GetSingletonTabNavigateParams(
      browser,
      GURL(kChromeUIBookmarksURL).Resolve(base::StringPrintf(
          "/#%s%s", action.c_str(), base::Int64ToString(node_id).c_str()))));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void NavigateToSingletonTab(Browser* browser, const GURL& url) {
  NavigateParams params(GetSingletonTabNavigateParams(browser, url));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

// Shows either the help app or the appropriate help page for |source|. If
// |browser| is NULL and the help page is used (vs the app), the help page is
// shown in the last active browser. If there is no such browser, a new browser
// is created.
void ShowHelpImpl(Browser* browser,
                  Profile* profile,
                  HostDesktopType host_desktop_type,
                  HelpSource source) {
  content::RecordAction(UserMetricsAction("ShowHelpTab"));
#if defined(OS_CHROMEOS) && defined(OFFICIAL_BUILD)
  const extensions::Extension* extension =
      extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
          genius_app::kGeniusAppId,
          extensions::ExtensionRegistry::EVERYTHING);
  extensions::AppLaunchSource app_launch_source(extensions::SOURCE_UNTRACKED);
  switch (source) {
    case HELP_SOURCE_KEYBOARD:
      app_launch_source = extensions::SOURCE_KEYBOARD;
      break;
    case HELP_SOURCE_MENU:
      app_launch_source = extensions::SOURCE_SYSTEM_TRAY;
      break;
    case HELP_SOURCE_WEBUI:
      app_launch_source = extensions::SOURCE_ABOUT_PAGE;
      break;
    default:
      NOTREACHED() << "Unhandled help source" << source;
  }
  AppLaunchParams params(profile, extension, CURRENT_TAB, host_desktop_type,
                         app_launch_source);
  OpenApplication(params);
#else
  GURL url;
  switch (source) {
    case HELP_SOURCE_KEYBOARD:
      url = GURL(kChromeHelpViaKeyboardURL);
      break;
    case HELP_SOURCE_MENU:
      url = GURL(kChromeHelpViaMenuURL);
      break;
    case HELP_SOURCE_WEBUI:
      url = GURL(kChromeHelpViaWebUIURL);
      break;
    default:
      NOTREACHED() << "Unhandled help source " << source;
  }
  scoped_ptr<ScopedTabbedBrowserDisplayer> displayer;
  if (!browser) {
    displayer.reset(
        new ScopedTabbedBrowserDisplayer(profile, host_desktop_type));
    browser = displayer->browser();
  }
  ShowSingletonTab(browser, url);
#endif
}

}  // namespace

void ShowBookmarkManager(Browser* browser) {
  content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
  content::RecordAction(UserMetricsAction("ShowBookmarks"));
  ShowSingletonTabOverwritingNTP(
      browser,
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIBookmarksURL)));
}

void ShowBookmarkManagerForNode(Browser* browser, int64 node_id) {
  OpenBookmarkManagerWithHash(browser, std::string(), node_id);
}

void ShowHistory(Browser* browser) {
  content::RecordAction(UserMetricsAction("ShowHistory"));
  NavigateParams params(
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIHistoryURL)));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowDownloads(Browser* browser) {
  content::RecordAction(UserMetricsAction("ShowDownloads"));
  if (browser->window()) {
    DownloadShelf* shelf = browser->window()->GetDownloadShelf();
    // The downloads page is always shown in response to a user action.
    if (shelf->IsShowing())
      shelf->Close(DownloadShelf::USER_ACTION);
  }
  ShowSingletonTabOverwritingNTP(
      browser,
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIDownloadsURL)));
}

void ShowExtensions(Browser* browser,
                    const std::string& extension_to_highlight) {
  content::RecordAction(UserMetricsAction("ShowExtensions"));
  NavigateParams params(
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIExtensionsURL)));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  if (!extension_to_highlight.empty()) {
    GURL::Replacements replacements;
    std::string query("id=");
    query += extension_to_highlight;
    replacements.SetQueryStr(query);
    params.url = params.url.ReplaceComponents(replacements);
  }
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowConflicts(Browser* browser) {
#if defined(OS_WIN)
  EnumerateModulesModel* model = EnumerateModulesModel::GetInstance();
  if (model->modules_to_notify_about() > 0) {
    GURL help_center_url = model->GetFirstNotableConflict();
    if (help_center_url.is_valid()) {
      ShowSingletonTab(browser, help_center_url);
      model->AcknowledgeConflictNotification();
      return;
    }
  }
#endif

  content::RecordAction(UserMetricsAction("AboutConflicts"));
  ShowSingletonTab(browser, GURL(kChromeUIConflictsURL));
}

void ShowHelp(Browser* browser, HelpSource source) {
  ShowHelpImpl(
      browser, browser->profile(), browser->host_desktop_type(), source);
}

void ShowHelpForProfile(Profile* profile,
                        HostDesktopType host_desktop_type,
                        HelpSource source) {
  ShowHelpImpl(NULL, profile, host_desktop_type, source);
}

void ShowPolicy(Browser* browser) {
  ShowSingletonTab(browser, GURL(kChromeUIPolicyURL));
}

void ShowSlow(Browser* browser) {
#if defined(OS_CHROMEOS)
  ShowSingletonTab(browser, GURL(kChromeUISlowURL));
#endif
}

void ShowMemory(Browser* browser) {
  ShowSingletonTab(browser, GURL(kChromeUIMemoryURL));
}

GURL GetSettingsUrl(const std::string& sub_page) {
  std::string url = std::string(kChromeUISettingsURL) + sub_page;
#if defined(OS_CHROMEOS)
  if (sub_page.find(kInternetOptionsSubPage, 0) != std::string::npos) {
    std::string::size_type loc = sub_page.find("?", 0);
    std::string network_page =
        loc != std::string::npos ? sub_page.substr(loc) : std::string();
    url = std::string(kChromeUISettingsURL) + network_page;
  }
#endif
  return GURL(url);
}

bool IsTrustedPopupWindowWithScheme(const Browser* browser,
                                    const std::string& scheme) {
  if (!browser->is_type_popup() || !browser->is_trusted_source())
    return false;
  if (scheme.empty())  // Any trusted popup window
    return true;
  const content::WebContents* web_contents =
      browser->tab_strip_model()->GetWebContentsAt(0);
  if (!web_contents)
    return false;
  GURL url(web_contents->GetURL());
  return url.SchemeIs(scheme.c_str());
}

void ShowSettings(Browser* browser) {
  ShowSettingsSubPage(browser, std::string());
}

void ShowSettingsSubPage(Browser* browser, const std::string& sub_page) {
  if (::switches::SettingsWindowEnabled()) {
    ShowSettingsSubPageForProfile(browser->profile(), sub_page);
    return;
  }
  ShowSettingsSubPageInTabbedBrowser(browser, sub_page);
}

void ShowSettingsSubPageForProfile(Profile* profile,
                                   const std::string& sub_page) {
  if (::switches::SettingsWindowEnabled()) {
    content::RecordAction(base::UserMetricsAction("ShowOptions"));
    SettingsWindowManager::GetInstance()->ShowChromePageForProfile(
        profile, GetSettingsUrl(sub_page));
    return;
  }
  Browser* browser =
      chrome::FindTabbedBrowser(profile, false, HOST_DESKTOP_TYPE_NATIVE);
  if (!browser) {
    browser = new Browser(
        Browser::CreateParams(profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
  }
  ShowSettingsSubPageInTabbedBrowser(browser, sub_page);
}

void ShowSettingsSubPageInTabbedBrowser(Browser* browser,
                                        const std::string& sub_page) {
  content::RecordAction(UserMetricsAction("ShowOptions"));
  GURL gurl = GetSettingsUrl(sub_page);
  NavigateParams params(GetSingletonTabNavigateParams(browser, gurl));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowContentSettings(Browser* browser,
                         ContentSettingsType content_settings_type) {
  ShowSettingsSubPage(
      browser,
      kContentSettingsExceptionsSubPage + std::string(kHashMark) +
          options::ContentSettingsHandler::ContentSettingsTypeToGroupName(
              content_settings_type));
}

void ShowClearBrowsingDataDialog(Browser* browser) {
  content::RecordAction(UserMetricsAction("ClearBrowsingData_ShowDlg"));
  ShowSettingsSubPage(browser, kClearBrowserDataSubPage);
}

void ShowPasswordManager(Browser* browser) {
  content::RecordAction(UserMetricsAction("Options_ShowPasswordManager"));
  ShowSettingsSubPage(browser, kPasswordManagerSubPage);
}

void ShowImportDialog(Browser* browser) {
  content::RecordAction(UserMetricsAction("Import_ShowDlg"));
  ShowSettingsSubPage(browser, kImportDataSubPage);
}

void ShowAboutChrome(Browser* browser) {
  content::RecordAction(UserMetricsAction("AboutChrome"));
  if (::switches::SettingsWindowEnabled()) {
    SettingsWindowManager::GetInstance()->ShowChromePageForProfile(
        browser->profile(), GURL(kChromeUIUberURL));
    return;
  }
  NavigateParams params(
      GetSingletonTabNavigateParams(browser, GURL(kChromeUIUberURL)));
  params.path_behavior = NavigateParams::IGNORE_AND_NAVIGATE;
  ShowSingletonTabOverwritingNTP(browser, params);
}

void ShowSearchEngineSettings(Browser* browser) {
  content::RecordAction(UserMetricsAction("EditSearchEngines"));
  ShowSettingsSubPage(browser, kSearchEnginesSubPage);
}

#if !defined(OS_ANDROID) && !defined(OS_IOS)
void ShowBrowserSignin(Browser* browser, signin_metrics::Source source) {
  Profile* original_profile = browser->profile()->GetOriginalProfile();
  SigninManagerBase* manager =
      SigninManagerFactory::GetForProfile(original_profile);
  DCHECK(manager->IsSigninAllowed());
  // If the browser's profile is an incognito profile, make sure to use
  // a browser window from the original profile.  The user cannot sign in
  // from an incognito window.
  bool switched_browser = false;
  scoped_ptr<ScopedTabbedBrowserDisplayer> displayer;
  if (browser->profile()->IsOffTheRecord()) {
    switched_browser = true;
    displayer.reset(new ScopedTabbedBrowserDisplayer(
        original_profile, chrome::HOST_DESKTOP_TYPE_NATIVE));
    browser = displayer->browser();
  }

  signin_metrics::LogSigninSource(source);

  // Since the app launcher is a separate application, it might steal focus
  // away from Chrome, and accidentally close the avatar bubble. The same will
  // happen if we had to switch browser windows to show the sign in page. In
  // this case, fallback to the full-tab signin page.
  if (switches::IsNewAvatarMenu() &&
      source != signin_metrics::SOURCE_APP_LAUNCHER && !switched_browser) {
    browser->window()->ShowAvatarBubbleFromAvatarButton(
        BrowserWindow::AVATAR_BUBBLE_MODE_SIGNIN,
        signin::ManageAccountsParams());
  } else {
    NavigateToSingletonTab(browser, GURL(signin::GetPromoURL(source, false)));
    DCHECK_GT(browser->tab_strip_model()->count(), 0);
  }
}

void ShowBrowserSigninOrSettings(
    Browser* browser,
    signin_metrics::Source source) {
  Profile* original_profile = browser->profile()->GetOriginalProfile();
  SigninManagerBase* manager =
      SigninManagerFactory::GetForProfile(original_profile);
  DCHECK(manager->IsSigninAllowed());
  if (manager->IsAuthenticated())
    ShowSettings(browser);
  else
    ShowBrowserSignin(browser, source);
}
#endif

}  // namespace chrome
<|endoftext|>


<commit_before>#include "util.h"

#include <mysql++.h>
#include <custom.h>

#include <iostream>
#include <string>
#include <vector>

using namespace std;
using namespace mysqlpp;

sql_create_5(stock,
			1, 5,
			string, item,
			longlong, num,
			double, weight,
			double, price,
			Date, sdate)

int
main(int argc, char *argv[])
{
	try {
		Connection con(use_exceptions);
		if (!connect_sample_db(argc, argv, con)) {
			return 1;
		}

		Query query = con.query();
		query << "select * from stock where item = \"Hotdogs' Buns\" ";

		// Is the query was successful?  If not throw a bad query.
		Result res = query.store();
		if (res.empty()) {
			throw BadQuery("Hotdogs' Buns not found in table, run reset-db");
		}

		// because there should only be one row in this query we don't
		// need to use a vector.  Just store the first row directly in
		// "row".  We can do this because one of the constructors for
		// stock takes a Row as an parameter.
		stock row = res[0];

		// Now we need to create a copy so that the replace query knows
		// what the original values are.
		stock row2 = row;

		row.item = "Hotdog Buns";	// now change item

		// form the query to replace the row
		// the table name is the name of the struct by default
		query.update(row2, row);

		// show the query about to be executed
		cout << "Query : " << query.preview() << endl;

		// execute a query that does not return a result set
		query.execute();

		// now print the new table;
		print_stock_table(query);
	}
	catch (BadQuery& er) {
		// handle any connection or query errors that may come up
#ifdef USE_STANDARD_EXCEPTION
		cerr << "Error: " << er.what() << endl;
#else
		cerr << "Error: " << er.error << endl;
#endif
		return -1;
	}
	catch (BadConversion& er) {
		// handle bad conversions
#ifdef USE_STANDARD_EXCEPTION
		cerr << "Error: " << er.what() << "\"." << endl
			<< "retrieved data size: " << er.retrieved
			<< " actual data size: " << er.actual_size << endl;
#else
		cerr << "Error: Tried to convert \"" << er.data << "\" to a \""
			<< er.type_name << "\"." << endl;
#endif
		return -1;
	}
#ifdef USE_STANDARD_EXCEPTION
	catch (exception& er) {
		cerr << "Error: " << er.what() << endl;
		return -1;
	}
#endif

	return 0;
}

<commit_msg>Code style improvements.<commit_after>#include "util.h"

#include <mysql++.h>
#include <custom.h>

#include <iostream>
#include <string>
#include <vector>

using namespace std;
using namespace mysqlpp;

sql_create_5(stock,
			1, 5,
			string, item,
			longlong, num,
			double, weight,
			double, price,
			Date, sdate)

int
main(int argc, char *argv[])
{
	try {
		Connection con(use_exceptions);
		if (!connect_sample_db(argc, argv, con)) {
			return 1;
		}

		Query query = con.query();
		query << "select * from stock where item = \"Hotdogs' Buns\" ";

		// Is the query was successful?  If not throw a bad query.
		Result res = query.store();
		if (res.empty()) {
			throw BadQuery("Hotdogs' Buns not found in table, run resetdb");
		}

		// Because there should only be one row in the result set, we
		// don't need to use a vector.  Just store the first row
		// directly in "row".  We can do this because one of the
		// constructors for stock takes a Row as a parameter.
		stock row = res[0];

		// Create a copy so that the replace query knows what the
		// original values are.
		stock row2 = row;

		// Change item column, fixing the spelling.
		row.item = "Hotdog Buns";

		// Form the query to replace the row.  The table name is the
		// name of the struct by default.
		query.update(row2, row);

		// Show the query about to be executed.
		cout << "Query : " << query.preview() << endl;

		// Call execute(), since the query won't return a result set.
		query.execute();

		// Now print the new table
		print_stock_table(query);
	}
	catch (BadQuery& er) {
		// handle any connection or query errors that may come up
#ifdef USE_STANDARD_EXCEPTION
		cerr << "Error: " << er.what() << endl;
#else
		cerr << "Error: " << er.error << endl;
#endif
		return -1;
	}
	catch (BadConversion& er) {
		// handle bad conversions
#ifdef USE_STANDARD_EXCEPTION
		cerr << "Error: " << er.what() << "\"." << endl
			<< "retrieved data size: " << er.retrieved
			<< " actual data size: " << er.actual_size << endl;
#else
		cerr << "Error: Tried to convert \"" << er.data << "\" to a \""
			<< er.type_name << "\"." << endl;
#endif
		return -1;
	}
#ifdef USE_STANDARD_EXCEPTION
	catch (exception& er) {
		cerr << "Error: " << er.what() << endl;
		return -1;
	}
#endif

	return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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/common/chrome_constants.h"

#include "base/file_path.h"

#define FPL FILE_PATH_LITERAL

#if defined(OS_MACOSX)
#if defined(GOOGLE_CHROME_BUILD)
#define PRODUCT_STRING L"Google Chrome"
#else
#define PRODUCT_STRING L"Chromium"
#endif
#endif  // OS_MACOSX

namespace chrome {

// The following should not be used for UI strings; they are meant
// for system strings only. UI changes should be made in the GRD.
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe";
const wchar_t kHelperProcessExecutableName[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutableName[] = L"chrome";
const wchar_t kHelperProcessExecutableName[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutableName[] = PRODUCT_STRING;
const wchar_t kHelperProcessExecutableName[] = PRODUCT_STRING L" Helper";
#endif  // OS_*
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome.exe";
const wchar_t kHelperProcessExecutablePath[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome";
const wchar_t kHelperProcessExecutablePath[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutablePath[] =
    PRODUCT_STRING L".app/Contents/MacOS/" PRODUCT_STRING;
const wchar_t kHelperProcessExecutablePath[] =
    PRODUCT_STRING L".app/Contents/Resources/"
    PRODUCT_STRING L" Helper.app/Contents/MacOS/" PRODUCT_STRING L" Helper";
#endif  // OS_*
#if defined(GOOGLE_CHROME_BUILD)
const wchar_t kBrowserAppName[] = L"Chrome";
const char    kStatsFilename[] = "ChromeStats2";
#else
const wchar_t kBrowserAppName[] = L"Chromium";
const char    kStatsFilename[] = "ChromiumStats2";
#endif
const wchar_t kMessageWindowClass[] = L"Chrome_MessageWindow";
const wchar_t kCrashReportLog[] = L"Reported Crashes.txt";
const wchar_t kTestingInterfaceDLL[] = L"testing_interface.dll";
const wchar_t kNotSignedInProfile[] = L"Default";
const wchar_t kNotSignedInID[] = L"not-signed-in";
const wchar_t kBrowserResourcesDll[] = L"chrome.dll";
const FilePath::CharType kExtensionFileExtension[] = FPL("crx");

// filenames
const FilePath::CharType kArchivedHistoryFilename[] = FPL("Archived History");
const FilePath::CharType kCacheDirname[] = FPL("Cache");
const FilePath::CharType kMediaCacheDirname[] = FPL("Media Cache");
const FilePath::CharType kOffTheRecordMediaCacheDirname[] =
    FPL("Incognito Media Cache");
const FilePath::CharType kAppCacheDirname[] = FPL("Application Cache");
const wchar_t kChromePluginDataDirname[] = L"Plugin Data";
const FilePath::CharType kThemeImagesDirname[] = FPL("Cached Theme Images");
const FilePath::CharType kCookieFilename[] = FPL("Cookies");
const FilePath::CharType kExtensionsCookieFilename[] = FPL("Extension Cookies");
const FilePath::CharType kHistoryFilename[] = FPL("History");
const FilePath::CharType kLocalStateFilename[] = FPL("Local State");
const FilePath::CharType kPreferencesFilename[] = FPL("Preferences");
const FilePath::CharType kSafeBrowsingFilename[] = FPL("Safe Browsing");
// WARNING: SingletonSocket can't contain spaces, because otherwise
// chrome_process_util_linux would be broken.
const FilePath::CharType kSingletonSocketFilename[] = FPL("SingletonSocket");
const FilePath::CharType kSingletonLockFilename[] = FPL("SingletonLock");
const FilePath::CharType kThumbnailsFilename[] = FPL("Thumbnails");
const FilePath::CharType kNewTabThumbnailsFilename[] = FPL("Top Thumbnails");
const wchar_t kUserDataDirname[] = L"User Data";
const FilePath::CharType kUserScriptsDirname[] = FPL("User Scripts");
const FilePath::CharType kWebDataFilename[] = FPL("Web Data");
const FilePath::CharType kBookmarksFileName[] = FPL("Bookmarks");
const FilePath::CharType kHistoryBookmarksFileName[] =
    FPL("Bookmarks From History");
const FilePath::CharType kCustomDictionaryFileName[] =
    FPL("Custom Dictionary.txt");
const FilePath::CharType kLoginDataFileName[] = FPL("Login Data");
const FilePath::CharType kJumpListIconDirname[] = FPL("JumpListIcons");

// This number used to be limited to 32 in the past (see b/535234).
const unsigned int kMaxRendererProcessCount = 42;
const int kStatsMaxThreads = 32;
const int kStatsMaxCounters = 300;

const size_t kMaxTitleChars = 4 * 1024;

// We don't enable record mode in the released product because users could
// potentially be tricked into running a product in record mode without
// knowing it.  Enable in debug builds.  Playback mode is allowed always,
// because it is useful for testing and not hazardous by itself.
#ifndef NDEBUG
const bool kRecordModeEnabled = true;
#else
const bool kRecordModeEnabled = false;
#endif

}  // namespace chrome

#undef FPL
<commit_msg>Changing the Chrome browser app name when CHROME_EXP_BUILD is defined. <commit_after>// Copyright (c) 2006-2008 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/common/chrome_constants.h"

#include "base/file_path.h"

#define FPL FILE_PATH_LITERAL

#if defined(OS_MACOSX)
#if defined(GOOGLE_CHROME_BUILD)
#define PRODUCT_STRING L"Google Chrome"
#else
#define PRODUCT_STRING L"Chromium"
#endif
#endif  // OS_MACOSX

namespace chrome {

// The following should not be used for UI strings; they are meant
// for system strings only. UI changes should be made in the GRD.
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe";
const wchar_t kHelperProcessExecutableName[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutableName[] = L"chrome";
const wchar_t kHelperProcessExecutableName[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutableName[] = PRODUCT_STRING;
const wchar_t kHelperProcessExecutableName[] = PRODUCT_STRING L" Helper";
#endif  // OS_*
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome.exe";
const wchar_t kHelperProcessExecutablePath[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome";
const wchar_t kHelperProcessExecutablePath[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutablePath[] =
    PRODUCT_STRING L".app/Contents/MacOS/" PRODUCT_STRING;
const wchar_t kHelperProcessExecutablePath[] =
    PRODUCT_STRING L".app/Contents/Resources/"
    PRODUCT_STRING L" Helper.app/Contents/MacOS/" PRODUCT_STRING L" Helper";
#endif  // OS_*
#if defined(CHROME_EXP_BUILD)
const wchar_t kBrowserAppName[] = L"ChromeExp";
const char    kStatsFilename[] = "ChromeExpStats2";
#elif defined(GOOGLE_CHROME_BUILD)
const wchar_t kBrowserAppName[] = L"Chrome";
const char    kStatsFilename[] = "ChromeStats2";
#else
const wchar_t kBrowserAppName[] = L"Chromium";
const char    kStatsFilename[] = "ChromiumStats2";
#endif
const wchar_t kMessageWindowClass[] = L"Chrome_MessageWindow";
const wchar_t kCrashReportLog[] = L"Reported Crashes.txt";
const wchar_t kTestingInterfaceDLL[] = L"testing_interface.dll";
const wchar_t kNotSignedInProfile[] = L"Default";
const wchar_t kNotSignedInID[] = L"not-signed-in";
const wchar_t kBrowserResourcesDll[] = L"chrome.dll";
const FilePath::CharType kExtensionFileExtension[] = FPL("crx");

// filenames
const FilePath::CharType kArchivedHistoryFilename[] = FPL("Archived History");
const FilePath::CharType kCacheDirname[] = FPL("Cache");
const FilePath::CharType kMediaCacheDirname[] = FPL("Media Cache");
const FilePath::CharType kOffTheRecordMediaCacheDirname[] =
    FPL("Incognito Media Cache");
const FilePath::CharType kAppCacheDirname[] = FPL("Application Cache");
const wchar_t kChromePluginDataDirname[] = L"Plugin Data";
const FilePath::CharType kThemeImagesDirname[] = FPL("Cached Theme Images");
const FilePath::CharType kCookieFilename[] = FPL("Cookies");
const FilePath::CharType kExtensionsCookieFilename[] = FPL("Extension Cookies");
const FilePath::CharType kHistoryFilename[] = FPL("History");
const FilePath::CharType kLocalStateFilename[] = FPL("Local State");
const FilePath::CharType kPreferencesFilename[] = FPL("Preferences");
const FilePath::CharType kSafeBrowsingFilename[] = FPL("Safe Browsing");
// WARNING: SingletonSocket can't contain spaces, because otherwise
// chrome_process_util_linux would be broken.
const FilePath::CharType kSingletonSocketFilename[] = FPL("SingletonSocket");
const FilePath::CharType kSingletonLockFilename[] = FPL("SingletonLock");
const FilePath::CharType kThumbnailsFilename[] = FPL("Thumbnails");
const FilePath::CharType kNewTabThumbnailsFilename[] = FPL("Top Thumbnails");
const wchar_t kUserDataDirname[] = L"User Data";
const FilePath::CharType kUserScriptsDirname[] = FPL("User Scripts");
const FilePath::CharType kWebDataFilename[] = FPL("Web Data");
const FilePath::CharType kBookmarksFileName[] = FPL("Bookmarks");
const FilePath::CharType kHistoryBookmarksFileName[] =
    FPL("Bookmarks From History");
const FilePath::CharType kCustomDictionaryFileName[] =
    FPL("Custom Dictionary.txt");
const FilePath::CharType kLoginDataFileName[] = FPL("Login Data");
const FilePath::CharType kJumpListIconDirname[] = FPL("JumpListIcons");

// This number used to be limited to 32 in the past (see b/535234).
const unsigned int kMaxRendererProcessCount = 42;
const int kStatsMaxThreads = 32;
const int kStatsMaxCounters = 300;

const size_t kMaxTitleChars = 4 * 1024;

// We don't enable record mode in the released product because users could
// potentially be tricked into running a product in record mode without
// knowing it.  Enable in debug builds.  Playback mode is allowed always,
// because it is useful for testing and not hazardous by itself.
#ifndef NDEBUG
const bool kRecordModeEnabled = true;
#else
const bool kRecordModeEnabled = false;
#endif

}  // namespace chrome

#undef FPL
<|endoftext|>


<commit_before><commit_msg>Revert of Use the new Mojo EDK in chrome. (patchset #3 id:180001 of https://codereview.chromium.org/1511023006/ )<commit_after><|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2015, 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 General 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Definition of the RegionImplWapper
 *
 * A RegionImplWrapper is an object that can instantiate a subclass of
 * RegionImpl and get its spec.
 */

#ifndef NTA_REGION_IMPL_WRAPPER_HPP
#define NTA_REGION_IMPL_WRAPPER_HPP

#include <string>

namespace nupic
{
  struct Spec;
  class BundleIO;
  class RegionImpl;
  class Region;
  class ValueMap;

  class GenericRegisteredRegionImpl {
    public:
      GenericRegisteredRegionImpl() {
      }
      virtual ~GenericRegisteredRegionImpl() {
      }
      virtual RegionImpl* createRegionImpl(const ValueMap& params, Region *region) {
      }
      virtual RegionImpl* deserializeRegionImpl(BundleIO& params, Region *region) {
      }
      virtual Spec* createSpec() {
      }
  };

  template <class T>
  class RegisteredRegionImpl: public GenericRegisteredRegionImpl {
    public:
      RegisteredRegionImpl() {
      }
      ~RegisteredRegionImpl() {
      }
      T* createRegionImpl(const ValueMap& params, Region *region) {
        return new T(params, region);
      }
      T* deserializeRegionImpl(BundleIO& params, Region *region) {
        return new T(params, region);
      }
      Spec* createSpec()
      {
        return T::createSpec();
      }
  };
}

#endif // NTA_REGION_IMPL_WRAPPER_HPP
<commit_msg>fixes for Appveyor. returning null<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2015, 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 General 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
 * Definition of the RegionImplWapper
 *
 * A RegionImplWrapper is an object that can instantiate a subclass of
 * RegionImpl and get its spec.
 */

#ifndef NTA_REGION_IMPL_WRAPPER_HPP
#define NTA_REGION_IMPL_WRAPPER_HPP

#include <string>

namespace nupic
{
  struct Spec;
  class BundleIO;
  class RegionImpl;
  class Region;
  class ValueMap;

  class GenericRegisteredRegionImpl {
    public:
      GenericRegisteredRegionImpl() {
      }
      virtual ~GenericRegisteredRegionImpl() {
      }
      virtual RegionImpl* createRegionImpl(const ValueMap& params, Region *region) {
        return nullptr;
      }
      virtual RegionImpl* deserializeRegionImpl(BundleIO& params, Region *region) {
        return nullptr;
      }
      virtual Spec* createSpec() {
        return nullptr;
      }
  };

  template <class T>
  class RegisteredRegionImpl: public GenericRegisteredRegionImpl {
    public:
      RegisteredRegionImpl() {
      }
      ~RegisteredRegionImpl() {
      }
      T* createRegionImpl(const ValueMap& params, Region *region) {
        return new T(params, region);
      }
      T* deserializeRegionImpl(BundleIO& params, Region *region) {
        return new T(params, region);
      }
      Spec* createSpec()
      {
        return T::createSpec();
      }
  };
}

#endif // NTA_REGION_IMPL_WRAPPER_HPP
<|endoftext|>


<commit_before>#include "NodePlaylistContainer.h"
#include "NodePlaylist.h"
#include "NodePlaylistFolder.h"
#include "NodeUser.h"
#include "../../exceptions.h"
#include "../../common_macros.h"
#include "../../utils/V8Utils.h"

NodePlaylistContainer::NodePlaylistContainer(std::shared_ptr<PlaylistContainer> _playlistContainer) : playlistContainer(_playlistContainer),
  playlistContainerCallbacksHolder(playlistContainer->playlistContainer, this) {
}

NodePlaylistContainer::~NodePlaylistContainer() {
}

Handle<Value> NodePlaylistContainer::getOwner(Local<String> property, const AccessorInfo& info) {
  HandleScope scope;
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(info.Holder());
  NodeUser* nodeUser = new NodeUser(nodePlaylistContainer->playlistContainer->owner());
  return scope.Close(nodeUser->getV8Object());
}

Handle<Value> NodePlaylistContainer::getNumPlaylists(Local<String> property, const AccessorInfo& info) {
  HandleScope scope;
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(info.Holder());
  return scope.Close(Integer::New(nodePlaylistContainer->playlistContainer->numPlaylists()));
}

Handle<Value> NodePlaylistContainer::getPlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsNumber()) {
    return scope.Close(V8_EXCEPTION("getPlaylist needs an interger as its first argument."));
  }
  int index = args[0]->ToNumber()->IntegerValue();
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  std::shared_ptr<PlaylistBase> playlist = nodePlaylistContainer->playlistContainer->getPlaylist(index);

  Handle<Value> outNodePlaylist;
  if(!playlist->isFolder) {
    NodePlaylist* nodePlaylist = new NodePlaylist(std::static_pointer_cast<Playlist>(playlist));
    outNodePlaylist = nodePlaylist->getV8Object();
  } else {
    NodePlaylistFolder* nodePlaylistFolder = new NodePlaylistFolder(std::static_pointer_cast<PlaylistFolder>(playlist));
    outNodePlaylist = nodePlaylistFolder->getV8Object();
  }

  return scope.Close(outNodePlaylist);
}

Handle<Value> NodePlaylistContainer::addPlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsString()) {
    return scope.Close(V8_EXCEPTION("addPlaylist needs a string as its argument"));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  String::Utf8Value playlistName(args[0]->ToString());
  try {
    nodePlaylistContainer->playlistContainer->addPlaylist(std::string(*playlistName));
  } catch(const PlaylistCreationException& e) {
    return scope.Close(V8_EXCEPTION("Playlist creation failed"));
  }
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::addFolder(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 2 || !args[0]->IsNumber() || !args[1]->IsString()) {
    return scope.Close(V8_EXCEPTION("addFolder needs a number and a string as arguments."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  int index = args[0]->ToNumber()->IntegerValue();
  String::Utf8Value folderName(args[1]->ToString());
  try {
    nodePlaylistContainer->playlistContainer->addFolder(index, std::string(*folderName));
  } catch(const PlaylistCreationException& e) {
    return scope.Close(V8_EXCEPTION("Folder creation failed"));
  }
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::deletePlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsNumber()) {
    return scope.Close(V8_EXCEPTION("deletePlaylist needs an integer as its first argument."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  int position = args[0]->ToNumber()->IntegerValue();
  nodePlaylistContainer->playlistContainer->removePlaylist(position);
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::movePlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 2 || !args[0]->IsNumber() || !args[1]->IsNumber()) {
    return scope.Close(V8_EXCEPTION("Move playlist needs 2 numbers as its first arguments."));
  }
  int index = args[0]->ToNumber()->IntegerValue();
  int newPosition = args[1]->ToNumber()->IntegerValue();
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  try {
    nodePlaylistContainer->playlistContainer->movePlaylist(index, newPosition);
  } catch(const PlaylistNotMoveableException& e) {
    return scope.Close(V8_EXCEPTION(e.message.c_str()));
  }
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::isLoaded(Local<String> property, const AccessorInfo& info) {
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(info.Holder());
  return Boolean::New(nodePlaylistContainer->playlistContainer->isLoaded());
}

Handle<Value> NodePlaylistContainer::on(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsObject()) {
    return scope.Close(V8_EXCEPTION("on needs an object as its first argument."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  Handle<Object> callbacks = args[0]->ToObject();
  Handle<String> playlistAddedKey = String::New("playlistAdded");
  Handle<String> playlistMovedKey = String::New("playlistMoved");
  Handle<String> playlistRemovedKey = String::New("playlistRemoved");
  nodePlaylistContainer->playlistContainerCallbacksHolder.playlistAddedCallback = V8Utils::getFunctionFromObject(callbacks, playlistAddedKey);
  nodePlaylistContainer->playlistContainerCallbacksHolder.playlistMovedCallback = V8Utils::getFunctionFromObject(callbacks, playlistMovedKey);
  nodePlaylistContainer->playlistContainerCallbacksHolder.playlistRemovedCallback = V8Utils::getFunctionFromObject(callbacks, playlistRemovedKey);
  nodePlaylistContainer->playlistContainerCallbacksHolder.setCallbacks();
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::off(const Arguments& args) {
  HandleScope scope;
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  nodePlaylistContainer->playlistContainerCallbacksHolder.unsetCallbacks();
  return scope.Close(Undefined());
}

void NodePlaylistContainer::init() {
  HandleScope scope;
  Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New();
  constructorTemplate->SetClassName(String::NewSymbol("PlaylistContainer"));
  constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "on", on);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "off", off);
  constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol("owner"), getOwner);
  constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol("numPlaylists"), getNumPlaylists);
  constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol("isLoaded"), isLoaded);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "getPlaylist", getPlaylist);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "addPlaylist", addPlaylist);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "addFolder", addFolder);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "deletePlaylist", deletePlaylist);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "movePlaylist", movePlaylist);

  constructor = Persistent<Function>::New(constructorTemplate->GetFunction());
  scope.Close(Undefined());
}<commit_msg>Error handling in NodePlaylistContainer.getPlaylist().<commit_after>#include "NodePlaylistContainer.h"
#include "NodePlaylist.h"
#include "NodePlaylistFolder.h"
#include "NodeUser.h"
#include "../../exceptions.h"
#include "../../common_macros.h"
#include "../../utils/V8Utils.h"

NodePlaylistContainer::NodePlaylistContainer(std::shared_ptr<PlaylistContainer> _playlistContainer) : playlistContainer(_playlistContainer),
  playlistContainerCallbacksHolder(playlistContainer->playlistContainer, this) {
}

NodePlaylistContainer::~NodePlaylistContainer() {
}

Handle<Value> NodePlaylistContainer::getOwner(Local<String> property, const AccessorInfo& info) {
  HandleScope scope;
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(info.Holder());
  NodeUser* nodeUser = new NodeUser(nodePlaylistContainer->playlistContainer->owner());
  return scope.Close(nodeUser->getV8Object());
}

Handle<Value> NodePlaylistContainer::getNumPlaylists(Local<String> property, const AccessorInfo& info) {
  HandleScope scope;
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(info.Holder());
  return scope.Close(Integer::New(nodePlaylistContainer->playlistContainer->numPlaylists()));
}

Handle<Value> NodePlaylistContainer::getPlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsNumber()) {
    return scope.Close(V8_EXCEPTION("getPlaylist needs an interger as its first argument."));
  }
  int index = args[0]->ToNumber()->IntegerValue();
  if(index < 0 || index > nodePlaylistContainer->playlistContainer->numPlaylists()) {
    return scope.Close(V8_EXCEPTION("Index out of range."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  std::shared_ptr<PlaylistBase> playlist = nodePlaylistContainer->playlistContainer->getPlaylist(index);

  Handle<Value> outNodePlaylist;
  if(!playlist->isFolder) {
    NodePlaylist* nodePlaylist = new NodePlaylist(std::static_pointer_cast<Playlist>(playlist));
    outNodePlaylist = nodePlaylist->getV8Object();
  } else {
    NodePlaylistFolder* nodePlaylistFolder = new NodePlaylistFolder(std::static_pointer_cast<PlaylistFolder>(playlist));
    outNodePlaylist = nodePlaylistFolder->getV8Object();
  }

  return scope.Close(outNodePlaylist);
}

Handle<Value> NodePlaylistContainer::addPlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsString()) {
    return scope.Close(V8_EXCEPTION("addPlaylist needs a string as its argument"));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  String::Utf8Value playlistName(args[0]->ToString());
  try {
    nodePlaylistContainer->playlistContainer->addPlaylist(std::string(*playlistName));
  } catch(const PlaylistCreationException& e) {
    return scope.Close(V8_EXCEPTION("Playlist creation failed"));
  }
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::addFolder(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 2 || !args[0]->IsNumber() || !args[1]->IsString()) {
    return scope.Close(V8_EXCEPTION("addFolder needs a number and a string as arguments."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  int index = args[0]->ToNumber()->IntegerValue();
  String::Utf8Value folderName(args[1]->ToString());
  try {
    nodePlaylistContainer->playlistContainer->addFolder(index, std::string(*folderName));
  } catch(const PlaylistCreationException& e) {
    return scope.Close(V8_EXCEPTION("Folder creation failed"));
  }
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::deletePlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsNumber()) {
    return scope.Close(V8_EXCEPTION("deletePlaylist needs an integer as its first argument."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  int position = args[0]->ToNumber()->IntegerValue();
  nodePlaylistContainer->playlistContainer->removePlaylist(position);
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::movePlaylist(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 2 || !args[0]->IsNumber() || !args[1]->IsNumber()) {
    return scope.Close(V8_EXCEPTION("Move playlist needs 2 numbers as its first arguments."));
  }
  int index = args[0]->ToNumber()->IntegerValue();
  int newPosition = args[1]->ToNumber()->IntegerValue();
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  try {
    nodePlaylistContainer->playlistContainer->movePlaylist(index, newPosition);
  } catch(const PlaylistNotMoveableException& e) {
    return scope.Close(V8_EXCEPTION(e.message.c_str()));
  }
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::isLoaded(Local<String> property, const AccessorInfo& info) {
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(info.Holder());
  return Boolean::New(nodePlaylistContainer->playlistContainer->isLoaded());
}

Handle<Value> NodePlaylistContainer::on(const Arguments& args) {
  HandleScope scope;
  if(args.Length() < 1 || !args[0]->IsObject()) {
    return scope.Close(V8_EXCEPTION("on needs an object as its first argument."));
  }
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  Handle<Object> callbacks = args[0]->ToObject();
  Handle<String> playlistAddedKey = String::New("playlistAdded");
  Handle<String> playlistMovedKey = String::New("playlistMoved");
  Handle<String> playlistRemovedKey = String::New("playlistRemoved");
  nodePlaylistContainer->playlistContainerCallbacksHolder.playlistAddedCallback = V8Utils::getFunctionFromObject(callbacks, playlistAddedKey);
  nodePlaylistContainer->playlistContainerCallbacksHolder.playlistMovedCallback = V8Utils::getFunctionFromObject(callbacks, playlistMovedKey);
  nodePlaylistContainer->playlistContainerCallbacksHolder.playlistRemovedCallback = V8Utils::getFunctionFromObject(callbacks, playlistRemovedKey);
  nodePlaylistContainer->playlistContainerCallbacksHolder.setCallbacks();
  return scope.Close(Undefined());
}

Handle<Value> NodePlaylistContainer::off(const Arguments& args) {
  HandleScope scope;
  NodePlaylistContainer* nodePlaylistContainer = node::ObjectWrap::Unwrap<NodePlaylistContainer>(args.This());
  nodePlaylistContainer->playlistContainerCallbacksHolder.unsetCallbacks();
  return scope.Close(Undefined());
}

void NodePlaylistContainer::init() {
  HandleScope scope;
  Local<FunctionTemplate> constructorTemplate = FunctionTemplate::New();
  constructorTemplate->SetClassName(String::NewSymbol("PlaylistContainer"));
  constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "on", on);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "off", off);
  constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol("owner"), getOwner);
  constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol("numPlaylists"), getNumPlaylists);
  constructorTemplate->InstanceTemplate()->SetAccessor(String::NewSymbol("isLoaded"), isLoaded);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "getPlaylist", getPlaylist);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "addPlaylist", addPlaylist);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "addFolder", addFolder);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "deletePlaylist", deletePlaylist);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "movePlaylist", movePlaylist);

  constructor = Persistent<Function>::New(constructorTemplate->GetFunction());
  scope.Close(Undefined());
}<|endoftext|>


<commit_before>/* Copyright (c) 2009-2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "LogCabinHelper.h"

namespace RAMCloud {

/**
 * Append a new entry to the LogCabin.
 * The "message" is serialized to get data for this entry, and it atomically
 * removes the entries indicated in "invalidates".
 *
 * \param message
 *      The ProtoBuf message to be serialized and appended to log.
 * \param invalidates
 *      A list of previous entries to be removed as part of this operation.
 * \param expectedId
 *      Makes the operation conditional on this being the ID assigned to
 *      this log entry. For example, 0 would indicate the log must be empty
 *      for the operation to succeed. Use NO_ID to unconditionally append.
 * \return
 *      The created entry ID, or NO_ID if the condition given by expectedId
 *      failed.
 * \throw LogDisappearedException
 *      If this log no longer exists because someone deleted it.
 */
EntryId
LogCabinHelper::appendProtoBuf(
    const google::protobuf::Message& message,
    const vector<EntryId>& invalidates, EntryId expectedId)
{
    string data;
    message.SerializeToString(&data);

    Entry stateEntry(data.c_str(),
                     uint32_t(data.length() + 1),
                     invalidates);
    EntryId entryId = logCabinLog.append(stateEntry, expectedId);

    return entryId;
}

/**
 * Given a LogCabin entry that was used to stored the coordinator state,
 * get the value in the entry_type field (that indicates the type of
 * state being stored).
 *
 * \param entryRead
 *      The entry whose entry_type is to be determined.
 * \return
 *      The entry_type of "entryRead".
 */
string
LogCabinHelper::getEntryType(Entry& entryRead)
{
    ProtoBuf::EntryType message;
    parseProtoBufFromEntry(entryRead, message);
    return message.entry_type();
}

/**
 * Given a LogCabin entry, parse it into a ProtoBuf.
 *
 * \param entryRead
 *      The entry to be parsed.
 * \param message
 *      The location where the parsed entry will be stored.
 */
void
LogCabinHelper::parseProtoBufFromEntry(
    Entry& entryRead, google::protobuf::Message& message)
{
    message.ParseFromArray(entryRead.getData(),
                           entryRead.getLength());
}

/**
 * Read valid entries starting from the beginning through head of the log.
 *
 * Currently, read() function in the LogCabin client API returns all the
 * entries, including the ones that were invalidated.
 * Once ongaro implements a cleaner in LogCabin, the read() in LogCabin client
 * API will return only valid entries and this function will not be needed
 * anymore.
 * This function is a temporary (and inefficient) work-around.
 *
 * \return
 *      The valid entries starting at the beginning through head of the log.
 * \throw LogDisappearedException
 *      If this log no longer exists because someone deleted it.
 */
vector<Entry>
LogCabinHelper::readValidEntries()
{
    // Assumption: The position of an entry in "entries" is the same as
    // its entryId. This is true currently since LogCabin doesn't do
    // any cleaning. Once it starts doing cleaning, this function will
    // not be needed anyway.
    vector<Entry> entries = logCabinLog.read(0);
    vector<EntryId> allInvalidatedEntries;

    // Store all the entry ids to the erased in allInvalidatedEntries.
    // We can't erase it directly here since if we do, then the position
    // of an entry in "entries" may not correspond to its entry id
    // anymore.
    for (vector<Entry>::iterator it = entries.begin();
            it < entries.end(); it++) {
        vector<EntryId> invalidates = it->getInvalidates();
        foreach (EntryId entryId, invalidates) {
            RAMCLOUD_LOG(DEBUG, "Want to erase entry with id %lu", entryId);
            allInvalidatedEntries.push_back(entryId);
        }
    }

    // Sort "allInvalidatedEntries" such that the entry ids are arranged
    // in descending order. Then when we actually erase entries from
    // "entries", it will happen from the end towards the begining
    // so that deleting an entry doesn't change the position of the
    // entry to be deleted after it.
    sort(allInvalidatedEntries.begin(), allInvalidatedEntries.end(),
         std::greater<EntryId>());

    foreach (EntryId entryId, allInvalidatedEntries) {
        RAMCLOUD_LOG(DEBUG, "Erasing entry with id %lu", entryId);
        entries.erase(entries.begin() + entryId);
    }

    return entries;
}

} // namespace RAMCloud

<commit_msg>Fixed LogCabinHelper method that worked under the (wrong) old assumption that read() provided by LogCabin client API returned log entries such that their location in the returned vector corresponded to the entryId.<commit_after>/* Copyright (c) 2009-2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "LogCabinHelper.h"

namespace RAMCloud {

/**
 * Append a new entry to the LogCabin.
 * The "message" is serialized to get data for this entry, and it atomically
 * removes the entries indicated in "invalidates".
 *
 * \param message
 *      The ProtoBuf message to be serialized and appended to log.
 * \param invalidates
 *      A list of previous entries to be removed as part of this operation.
 * \param expectedId
 *      Makes the operation conditional on this being the ID assigned to
 *      this log entry. For example, 0 would indicate the log must be empty
 *      for the operation to succeed. Use NO_ID to unconditionally append.
 * \return
 *      The created entry ID, or NO_ID if the condition given by expectedId
 *      failed.
 * \throw LogDisappearedException
 *      If this log no longer exists because someone deleted it.
 */
EntryId
LogCabinHelper::appendProtoBuf(
    const google::protobuf::Message& message,
    const vector<EntryId>& invalidates, EntryId expectedId)
{
    string data;
    message.SerializeToString(&data);

    Entry stateEntry(data.c_str(),
                     uint32_t(data.length() + 1),
                     invalidates);
    EntryId entryId = logCabinLog.append(stateEntry, expectedId);

    return entryId;
}

/**
 * Given a LogCabin entry that was used to stored the coordinator state,
 * get the value in the entry_type field (that indicates the type of
 * state being stored).
 *
 * \param entryRead
 *      The entry whose entry_type is to be determined.
 * \return
 *      The entry_type of "entryRead".
 */
string
LogCabinHelper::getEntryType(Entry& entryRead)
{
    ProtoBuf::EntryType message;
    parseProtoBufFromEntry(entryRead, message);
    return message.entry_type();
}

/**
 * Given a LogCabin entry, parse it into a ProtoBuf.
 *
 * \param entryRead
 *      The entry to be parsed.
 * \param message
 *      The location where the parsed entry will be stored.
 */
void
LogCabinHelper::parseProtoBufFromEntry(
    Entry& entryRead, google::protobuf::Message& message)
{
    message.ParseFromArray(entryRead.getData(),
                           entryRead.getLength());
}

/**
 * Read valid entries starting from the beginning through head of the log.
 *
 * Currently, read() function in the LogCabin client API returns all the
 * entries, including the ones that were invalidated.
 * Once ongaro implements a cleaner in LogCabin, the read() in LogCabin client
 * API will return only valid entries and this function will not be needed
 * anymore.
 * This function is a temporary (and inefficient) work-around.
 *
 * \return
 *      The valid entries starting at the beginning through head of the log.
 * \throw LogDisappearedException
 *      If this log no longer exists because someone deleted it.
 */
vector<Entry>
LogCabinHelper::readValidEntries()
{
    vector<Entry> entries = logCabinLog.read(0);
    vector<EntryId> allInvalidatedEntries;

    for (auto it = entries.begin(); it < entries.end(); it++) {
        vector<EntryId> invalidates = it->getInvalidates();
        foreach (EntryId entryId, invalidates) {
            allInvalidatedEntries.push_back(entryId);
        }
     }

    // Sort "allInvalidatedEntries" such that the entry ids are arranged
    // in descending order. Then when we actually erase entries from
    // "entries", it will happen from the end towards the begining
    // so that deleting an entry doesn't change the position of the
    // entry to be deleted after it.
    sort(allInvalidatedEntries.begin(), allInvalidatedEntries.end(),
         std::greater<EntryId>());

    // The position of an entry in "entries" is *not* the same as its entryId.
    // So for every entry to be invalidated, I have to search through the entire
    // vector to find an entry with that id.
    foreach (EntryId entryId, allInvalidatedEntries) {
        for (auto it = entries.end(); it >= entries.begin(); it--) {
            if (it->getId() == entryId) {
                RAMCLOUD_LOG(DEBUG, "Erasing entry with id %lu", entryId);
                entries.erase(it);
            }
        }
    }

    return entries;
}

} // namespace RAMCloud
<|endoftext|>


<commit_before>#include "PlanarX.h"
using namespace GEFICA;

void PlanarX::SetVoltage(double anode_voltage, double cathode_voltage)
{
   double stepLength=Thickness/(n-1);
   CreateGridWithFixedStepLength(stepLength);
   fIsFixed[0]=true;
   fIsFixed[n-1]=true;
   double slope = (cathode_voltage-anode_voltage)/n;
   for (int i=0; i<n; i++) {
      fPotential[i]=anode_voltage+slope*i;
   }
}

bool PlanarX::Analyic()
{
   double cnst1=fPotential[0];
   double cnst2=(fPotential[n-1]-fImpurity[n-1]*1.6e-19/2/epsilon*Thickness*Thickness-cnst1)/Thickness;
   for (int i=0; i<n; i++) {
      fPotential[i] = fImpurity[i]*1.6e-19/2/epsilon*fC1[i]*fC1[i]+cnst2*fC1[i]+cnst1;
      fE1[i]=(fPotential[i+1]-fPotential[i-1])/(fDistanceToNext[i]+fDistanceToPrevious[i]);
   }
   return true;
}
<commit_msg>fixed n bug<commit_after>#include "PlanarX.h"
using namespace GEFICA;

void PlanarX::SetVoltage(double anode_voltage, double cathode_voltage)
{
   double stepLength=Thickness/(n-1);
   CreateGridWithFixedStepLength(stepLength);
   fIsFixed[0]=true;
   fIsFixed[n-1]=true;
   double slope = (cathode_voltage-anode_voltage)/(n-1);
   for (int i=0; i<n; i++) fPotential[i]=anode_voltage+slope*i;
}

bool PlanarX::Analyic()
{
   double cnst1=fPotential[0];
   double cnst2=(fPotential[n-1]-fImpurity[n-1]*1.6e-19/2/epsilon*Thickness*Thickness-cnst1)/Thickness;
   for (int i=0; i<n; i++) {
      fPotential[i] = fImpurity[i]*1.6e-19/2/epsilon*fC1[i]*fC1[i]+cnst2*fC1[i]+cnst1;
      fE1[i]=(fPotential[i+1]-fPotential[i-1])/(fDistanceToNext[i]+fDistanceToPrevious[i]);
   }
   return true;
}
<|endoftext|>