<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/io_thread.h"
#include "base/command_line.h"
#include "base/leak_tracker.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/gpu_process_host.h"
#include "chrome/browser/net/chrome_net_log.h"
#include "chrome/browser/net/predictor_api.h"
#include "chrome/browser/net/passive_log_collector.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fetcher.h"
#include "net/base/mapped_host_resolver.h"
#include "net/base/host_cache.h"
#include "net/base/host_resolver.h"
#include "net/base/host_resolver_impl.h"
#include "net/base/net_util.h"
#include "net/http/http_auth_filter.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_handler_negotiate.h"

namespace {

net::HostResolver* CreateGlobalHostResolver() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  net::HostResolver* global_host_resolver = net::CreateSystemHostResolver();

  // Determine if we should disable IPv6 support.
  if (!command_line.HasSwitch(switches::kEnableIPv6)) {
    if (command_line.HasSwitch(switches::kDisableIPv6)) {
      global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
    } else {
      net::HostResolverImpl* host_resolver_impl =
          global_host_resolver->GetAsHostResolverImpl();
      if (host_resolver_impl != NULL) {
        // (optionally) Use probe to decide if support is warranted.
        bool use_ipv6_probe = true;

#if defined(OS_WIN)
        // Measure impact of probing to allow IPv6.
        // Some users report confused OS handling of IPv6, leading to large
        // latency.  If we can show that IPv6 is not supported, then disabliing
        // it will work around such problems. This is the test of the probe.
        const FieldTrial::Probability kDivisor = 100;
        const FieldTrial::Probability kProbability = 50;  // 50% probability.
        FieldTrial* trial = new FieldTrial("IPv6_Probe", kDivisor);
        int skip_group = trial->AppendGroup("_IPv6_probe_skipped",
                                            kProbability);
        trial->AppendGroup("_IPv6_probe_done",
                           FieldTrial::kAllRemainingProbability);
        use_ipv6_probe = (trial->group() != skip_group);
#endif

        if (use_ipv6_probe)
          host_resolver_impl->ProbeIPv6Support();
      }
    }
  }

  // If hostname remappings were specified on the command-line, layer these
  // rules on top of the real host resolver. This allows forwarding all requests
  // through a designated test server.
  if (!command_line.HasSwitch(switches::kHostResolverRules))
    return global_host_resolver;

  net::MappedHostResolver* remapped_resolver =
      new net::MappedHostResolver(global_host_resolver);
  remapped_resolver->SetRulesFromString(
      command_line.GetSwitchValueASCII(switches::kHostResolverRules));
  return remapped_resolver;
}

class LoggingNetworkChangeObserver
    : public net::NetworkChangeNotifier::Observer {
 public:
  // |net_log| must remain valid throughout our lifetime.
  explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
      : net_log_(net_log) {
    net::NetworkChangeNotifier::AddObserver(this);
  }

  ~LoggingNetworkChangeObserver() {
    net::NetworkChangeNotifier::RemoveObserver(this);
  }

  virtual void OnIPAddressChanged() {
    LOG(INFO) << "Observed a change to the network IP addresses";

    net::NetLog::Source global_source;

    // TODO(eroman): We shouldn't need to assign an ID to this source, since
    //               conceptually it is the "global event stream". However
    //               currently the javascript does a grouping on source id, so
    //               the display will look weird if we don't give it one.
    global_source.id = net_log_->NextID();

    net_log_->AddEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSSES_CHANGED,
                       base::TimeTicks::Now(),
                       global_source,
                       net::NetLog::PHASE_NONE,
                       NULL);
  }

 private:
  net::NetLog* net_log_;
  DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
};

}  // namespace

// The IOThread object must outlive any tasks posted to the IO thread before the
// Quit task.
DISABLE_RUNNABLE_METHOD_REFCOUNT(IOThread);

IOThread::IOThread()
    : BrowserProcessSubThread(ChromeThread::IO),
      globals_(NULL),
      speculative_interceptor_(NULL),
      prefetch_observer_(NULL),
      predictor_(NULL) {}

IOThread::~IOThread() {
  // We cannot rely on our base class to stop the thread since we want our
  // CleanUp function to run.
  Stop();
  DCHECK(!globals_);
}

IOThread::Globals* IOThread::globals() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
  return globals_;
}

void IOThread::InitNetworkPredictor(
    bool prefetching_enabled,
    base::TimeDelta max_dns_queue_delay,
    size_t max_concurrent,
    const chrome_common_net::UrlList& startup_urls,
    ListValue* referral_list,
    bool preconnect_enabled) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(
          this,
          &IOThread::InitNetworkPredictorOnIOThread,
          prefetching_enabled, max_dns_queue_delay, max_concurrent,
          startup_urls, referral_list, preconnect_enabled));
}

void IOThread::ChangedToOnTheRecord() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(
          this,
          &IOThread::ChangedToOnTheRecordOnIOThread));
}

void IOThread::Init() {
  BrowserProcessSubThread::Init();

  DCHECK(!globals_);
  globals_ = new Globals;

  globals_->net_log.reset(new ChromeNetLog());

  // Add an observer that will emit network change events to the ChromeNetLog.
  // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
  // logging the network change before other IO thread consumers respond to it.
  network_change_observer_.reset(
      new LoggingNetworkChangeObserver(globals_->net_log.get()));

  globals_->host_resolver = CreateGlobalHostResolver();
  globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
      globals_->host_resolver));
}

void IOThread::CleanUp() {
  // This must be reset before the ChromeNetLog is destroyed.
  network_change_observer_.reset();

  // If any child processes are still running, terminate them and
  // and delete the BrowserChildProcessHost instances to release whatever
  // IO thread only resources they are referencing.
  BrowserChildProcessHost::TerminateAll();

  // Not initialized in Init().  May not be initialized.
  if (predictor_) {
    predictor_->Shutdown();

    // TODO(willchan): Stop reference counting Predictor.  It's owned by
    // IOThread now.
    predictor_->Release();
    predictor_ = NULL;
    chrome_browser_net::FreePredictorResources();
  }

  // Deletion will unregister this interceptor.
  delete speculative_interceptor_;
  speculative_interceptor_ = NULL;

  // Not initialized in Init().  May not be initialized.
  if (prefetch_observer_) {
    globals_->host_resolver->RemoveObserver(prefetch_observer_);
    delete prefetch_observer_;
    prefetch_observer_ = NULL;
  }

  // TODO(eroman): hack for http://crbug.com/15513
  if (globals_->host_resolver->GetAsHostResolverImpl()) {
    globals_->host_resolver.get()->GetAsHostResolverImpl()->Shutdown();
  }

  // We will delete the NetLog as part of CleanUpAfterMessageLoopDestruction()
  // in case any of the message loop destruction observers try to access it.
  deferred_net_log_to_delete_.reset(globals_->net_log.release());

  delete globals_;
  globals_ = NULL;

  // URLRequest instances must NOT outlive the IO thread.
  base::LeakTracker<URLRequest>::CheckForLeaks();

  BrowserProcessSubThread::CleanUp();
}

void IOThread::CleanUpAfterMessageLoopDestruction() {
  // TODO(eroman): get rid of this special case for 39723. If we could instead
  // have a method that runs after the message loop destruction obsevers have
  // run, but before the message loop itself is destroyed, we could safely
  // combine the two cleanups.
  deferred_net_log_to_delete_.reset();
  BrowserProcessSubThread::CleanUpAfterMessageLoopDestruction();
}

net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
    net::HostResolver* resolver) {
  net::HttpAuthFilterWhitelist* auth_filter = NULL;

  // Get the whitelist information from the command line, create an
  // HttpAuthFilterWhitelist, and attach it to the HttpAuthHandlerFactory.
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();

  if (command_line.HasSwitch(switches::kAuthServerWhitelist)) {
    std::string auth_server_whitelist =
        command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist);

    // Create a whitelist filter.
    auth_filter = new net::HttpAuthFilterWhitelist();
    auth_filter->SetWhitelist(auth_server_whitelist);
  }

  // Set the flag that enables or disables the Negotiate auth handler.
#if defined(OS_WIN)
  static const bool kNegotiateAuthEnabledDefault = true;
#else
  static const bool kNegotiateAuthEnabledDefault = false;
#endif
  bool negotiate_auth_enabled = kNegotiateAuthEnabledDefault;
  if (command_line.HasSwitch(switches::kExperimentalEnableNegotiateAuth)) {
    std::string enable_negotiate_auth = command_line.GetSwitchValueASCII(
        switches::kExperimentalEnableNegotiateAuth);
    // Enabled if no value, or value is 'true'.  Disabled otherwise.
    negotiate_auth_enabled =
        enable_negotiate_auth.empty() ||
        (StringToLowerASCII(enable_negotiate_auth) == "true");
  }

  net::HttpAuthHandlerRegistryFactory* registry_factory =
      net::HttpAuthHandlerFactory::CreateDefault();

  globals_->url_security_manager.reset(
      net::URLSecurityManager::Create(auth_filter));

  // Add the security manager to the auth factories that need it.
  registry_factory->SetURLSecurityManager("ntlm",
                                          globals_->url_security_manager.get());
  registry_factory->SetURLSecurityManager("negotiate",
                                          globals_->url_security_manager.get());
  if (negotiate_auth_enabled) {
    // Configure the Negotiate settings for the Kerberos SPN.
    // TODO(cbentzel): Read the related IE registry settings on Windows builds.
    // TODO(cbentzel): Ugly use of static_cast here.
    net::HttpAuthHandlerNegotiate::Factory* negotiate_factory =
        static_cast<net::HttpAuthHandlerNegotiate::Factory*>(
            registry_factory->GetSchemeFactory("negotiate"));
    DCHECK(negotiate_factory);
    if (command_line.HasSwitch(switches::kDisableAuthNegotiateCnameLookup))
      negotiate_factory->set_disable_cname_lookup(true);
    if (command_line.HasSwitch(switches::kEnableAuthNegotiatePort))
      negotiate_factory->set_use_port(true);
  } else {
    // Disable the Negotiate authentication handler.
    registry_factory->RegisterSchemeFactory("negotiate", NULL);
  }
  return registry_factory;
}

void IOThread::InitNetworkPredictorOnIOThread(
    bool prefetching_enabled,
    base::TimeDelta max_dns_queue_delay,
    size_t max_concurrent,
    const chrome_common_net::UrlList& startup_urls,
    ListValue* referral_list,
    bool preconnect_enabled) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
  CHECK(!predictor_);

  chrome_browser_net::EnablePredictor(prefetching_enabled);

  predictor_ = new chrome_browser_net::Predictor(
      globals_->host_resolver,
      max_dns_queue_delay,
      max_concurrent,
      preconnect_enabled);
  predictor_->AddRef();

  // TODO(jar): Until connection notification and DNS observation handling are
  // properly combined into a learning model, we'll only use one observation
  // mechanism or the other.
  if (preconnect_enabled) {
    DCHECK(!speculative_interceptor_);
    speculative_interceptor_ = new chrome_browser_net::ConnectInterceptor;
  } else {
    DCHECK(!prefetch_observer_);
    prefetch_observer_ = chrome_browser_net::CreateResolverObserver();
    globals_->host_resolver->AddObserver(prefetch_observer_);
  }

  FinalizePredictorInitialization(
      predictor_, prefetch_observer_, startup_urls, referral_list);
}

void IOThread::ChangedToOnTheRecordOnIOThread() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));

  if (predictor_) {
    // Destroy all evidence of our OTR session.
    predictor_->Predictor::DiscardAllResults();
  }

  // Clear the host cache to avoid showing entries from the OTR session
  // in about:net-internals.
  if (globals_->host_resolver->GetAsHostResolverImpl()) {
    net::HostCache* host_cache =
        globals_->host_resolver.get()->GetAsHostResolverImpl()->cache();
    if (host_cache)
      host_cache->clear();
  }
  // Clear all of the passively logged data.
  // TODO(eroman): this is a bit heavy handed, really all we need to do is
  //               clear the data pertaining to off the record context.
  globals_->net_log->passive_collector()->Clear();
}
<commit_msg>Fix a crash when using negotiate HTTP auth.<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/io_thread.h"
#include "base/command_line.h"
#include "base/leak_tracker.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/gpu_process_host.h"
#include "chrome/browser/net/chrome_net_log.h"
#include "chrome/browser/net/predictor_api.h"
#include "chrome/browser/net/passive_log_collector.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fetcher.h"
#include "net/base/mapped_host_resolver.h"
#include "net/base/host_cache.h"
#include "net/base/host_resolver.h"
#include "net/base/host_resolver_impl.h"
#include "net/base/net_util.h"
#include "net/http/http_auth_filter.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_handler_negotiate.h"

namespace {

net::HostResolver* CreateGlobalHostResolver() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  net::HostResolver* global_host_resolver = net::CreateSystemHostResolver();

  // Determine if we should disable IPv6 support.
  if (!command_line.HasSwitch(switches::kEnableIPv6)) {
    if (command_line.HasSwitch(switches::kDisableIPv6)) {
      global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
    } else {
      net::HostResolverImpl* host_resolver_impl =
          global_host_resolver->GetAsHostResolverImpl();
      if (host_resolver_impl != NULL) {
        // (optionally) Use probe to decide if support is warranted.
        bool use_ipv6_probe = true;

#if defined(OS_WIN)
        // Measure impact of probing to allow IPv6.
        // Some users report confused OS handling of IPv6, leading to large
        // latency.  If we can show that IPv6 is not supported, then disabliing
        // it will work around such problems. This is the test of the probe.
        const FieldTrial::Probability kDivisor = 100;
        const FieldTrial::Probability kProbability = 50;  // 50% probability.
        FieldTrial* trial = new FieldTrial("IPv6_Probe", kDivisor);
        int skip_group = trial->AppendGroup("_IPv6_probe_skipped",
                                            kProbability);
        trial->AppendGroup("_IPv6_probe_done",
                           FieldTrial::kAllRemainingProbability);
        use_ipv6_probe = (trial->group() != skip_group);
#endif

        if (use_ipv6_probe)
          host_resolver_impl->ProbeIPv6Support();
      }
    }
  }

  // If hostname remappings were specified on the command-line, layer these
  // rules on top of the real host resolver. This allows forwarding all requests
  // through a designated test server.
  if (!command_line.HasSwitch(switches::kHostResolverRules))
    return global_host_resolver;

  net::MappedHostResolver* remapped_resolver =
      new net::MappedHostResolver(global_host_resolver);
  remapped_resolver->SetRulesFromString(
      command_line.GetSwitchValueASCII(switches::kHostResolverRules));
  return remapped_resolver;
}

class LoggingNetworkChangeObserver
    : public net::NetworkChangeNotifier::Observer {
 public:
  // |net_log| must remain valid throughout our lifetime.
  explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
      : net_log_(net_log) {
    net::NetworkChangeNotifier::AddObserver(this);
  }

  ~LoggingNetworkChangeObserver() {
    net::NetworkChangeNotifier::RemoveObserver(this);
  }

  virtual void OnIPAddressChanged() {
    LOG(INFO) << "Observed a change to the network IP addresses";

    net::NetLog::Source global_source;

    // TODO(eroman): We shouldn't need to assign an ID to this source, since
    //               conceptually it is the "global event stream". However
    //               currently the javascript does a grouping on source id, so
    //               the display will look weird if we don't give it one.
    global_source.id = net_log_->NextID();

    net_log_->AddEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSSES_CHANGED,
                       base::TimeTicks::Now(),
                       global_source,
                       net::NetLog::PHASE_NONE,
                       NULL);
  }

 private:
  net::NetLog* net_log_;
  DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
};

}  // namespace

// The IOThread object must outlive any tasks posted to the IO thread before the
// Quit task.
DISABLE_RUNNABLE_METHOD_REFCOUNT(IOThread);

IOThread::IOThread()
    : BrowserProcessSubThread(ChromeThread::IO),
      globals_(NULL),
      speculative_interceptor_(NULL),
      prefetch_observer_(NULL),
      predictor_(NULL) {}

IOThread::~IOThread() {
  // We cannot rely on our base class to stop the thread since we want our
  // CleanUp function to run.
  Stop();
  DCHECK(!globals_);
}

IOThread::Globals* IOThread::globals() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
  return globals_;
}

void IOThread::InitNetworkPredictor(
    bool prefetching_enabled,
    base::TimeDelta max_dns_queue_delay,
    size_t max_concurrent,
    const chrome_common_net::UrlList& startup_urls,
    ListValue* referral_list,
    bool preconnect_enabled) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(
          this,
          &IOThread::InitNetworkPredictorOnIOThread,
          prefetching_enabled, max_dns_queue_delay, max_concurrent,
          startup_urls, referral_list, preconnect_enabled));
}

void IOThread::ChangedToOnTheRecord() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
  message_loop()->PostTask(
      FROM_HERE,
      NewRunnableMethod(
          this,
          &IOThread::ChangedToOnTheRecordOnIOThread));
}

void IOThread::Init() {
  BrowserProcessSubThread::Init();

  DCHECK(!globals_);
  globals_ = new Globals;

  globals_->net_log.reset(new ChromeNetLog());

  // Add an observer that will emit network change events to the ChromeNetLog.
  // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
  // logging the network change before other IO thread consumers respond to it.
  network_change_observer_.reset(
      new LoggingNetworkChangeObserver(globals_->net_log.get()));

  globals_->host_resolver = CreateGlobalHostResolver();
  globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
      globals_->host_resolver));
}

void IOThread::CleanUp() {
  // This must be reset before the ChromeNetLog is destroyed.
  network_change_observer_.reset();

  // If any child processes are still running, terminate them and
  // and delete the BrowserChildProcessHost instances to release whatever
  // IO thread only resources they are referencing.
  BrowserChildProcessHost::TerminateAll();

  // Not initialized in Init().  May not be initialized.
  if (predictor_) {
    predictor_->Shutdown();

    // TODO(willchan): Stop reference counting Predictor.  It's owned by
    // IOThread now.
    predictor_->Release();
    predictor_ = NULL;
    chrome_browser_net::FreePredictorResources();
  }

  // Deletion will unregister this interceptor.
  delete speculative_interceptor_;
  speculative_interceptor_ = NULL;

  // Not initialized in Init().  May not be initialized.
  if (prefetch_observer_) {
    globals_->host_resolver->RemoveObserver(prefetch_observer_);
    delete prefetch_observer_;
    prefetch_observer_ = NULL;
  }

  // TODO(eroman): hack for http://crbug.com/15513
  if (globals_->host_resolver->GetAsHostResolverImpl()) {
    globals_->host_resolver.get()->GetAsHostResolverImpl()->Shutdown();
  }

  // We will delete the NetLog as part of CleanUpAfterMessageLoopDestruction()
  // in case any of the message loop destruction observers try to access it.
  deferred_net_log_to_delete_.reset(globals_->net_log.release());

  delete globals_;
  globals_ = NULL;

  // URLRequest instances must NOT outlive the IO thread.
  base::LeakTracker<URLRequest>::CheckForLeaks();

  BrowserProcessSubThread::CleanUp();
}

void IOThread::CleanUpAfterMessageLoopDestruction() {
  // TODO(eroman): get rid of this special case for 39723. If we could instead
  // have a method that runs after the message loop destruction obsevers have
  // run, but before the message loop itself is destroyed, we could safely
  // combine the two cleanups.
  deferred_net_log_to_delete_.reset();
  BrowserProcessSubThread::CleanUpAfterMessageLoopDestruction();
}

net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
    net::HostResolver* resolver) {
  net::HttpAuthFilterWhitelist* auth_filter = NULL;

  // Get the whitelist information from the command line, create an
  // HttpAuthFilterWhitelist, and attach it to the HttpAuthHandlerFactory.
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();

  if (command_line.HasSwitch(switches::kAuthServerWhitelist)) {
    std::string auth_server_whitelist =
        command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist);

    // Create a whitelist filter.
    auth_filter = new net::HttpAuthFilterWhitelist();
    auth_filter->SetWhitelist(auth_server_whitelist);
  }

  // Set the flag that enables or disables the Negotiate auth handler.
#if defined(OS_WIN)
  static const bool kNegotiateAuthEnabledDefault = true;
#else
  static const bool kNegotiateAuthEnabledDefault = false;
#endif
  bool negotiate_auth_enabled = kNegotiateAuthEnabledDefault;
  if (command_line.HasSwitch(switches::kExperimentalEnableNegotiateAuth)) {
    std::string enable_negotiate_auth = command_line.GetSwitchValueASCII(
        switches::kExperimentalEnableNegotiateAuth);
    // Enabled if no value, or value is 'true'.  Disabled otherwise.
    negotiate_auth_enabled =
        enable_negotiate_auth.empty() ||
        (StringToLowerASCII(enable_negotiate_auth) == "true");
  }

  net::HttpAuthHandlerRegistryFactory* registry_factory =
      net::HttpAuthHandlerFactory::CreateDefault();

  globals_->url_security_manager.reset(
      net::URLSecurityManager::Create(auth_filter));

  // Add the security manager to the auth factories that need it.
  registry_factory->SetURLSecurityManager("ntlm",
                                          globals_->url_security_manager.get());
  registry_factory->SetURLSecurityManager("negotiate",
                                          globals_->url_security_manager.get());
  if (negotiate_auth_enabled) {
    // Configure the Negotiate settings for the Kerberos SPN.
    // TODO(cbentzel): Read the related IE registry settings on Windows builds.
    // TODO(cbentzel): Ugly use of static_cast here.
    net::HttpAuthHandlerNegotiate::Factory* negotiate_factory =
        static_cast<net::HttpAuthHandlerNegotiate::Factory*>(
            registry_factory->GetSchemeFactory("negotiate"));
    DCHECK(negotiate_factory);
    negotiate_factory->set_host_resolver(resolver);
    if (command_line.HasSwitch(switches::kDisableAuthNegotiateCnameLookup))
      negotiate_factory->set_disable_cname_lookup(true);
    if (command_line.HasSwitch(switches::kEnableAuthNegotiatePort))
      negotiate_factory->set_use_port(true);
  } else {
    // Disable the Negotiate authentication handler.
    registry_factory->RegisterSchemeFactory("negotiate", NULL);
  }
  return registry_factory;
}

void IOThread::InitNetworkPredictorOnIOThread(
    bool prefetching_enabled,
    base::TimeDelta max_dns_queue_delay,
    size_t max_concurrent,
    const chrome_common_net::UrlList& startup_urls,
    ListValue* referral_list,
    bool preconnect_enabled) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
  CHECK(!predictor_);

  chrome_browser_net::EnablePredictor(prefetching_enabled);

  predictor_ = new chrome_browser_net::Predictor(
      globals_->host_resolver,
      max_dns_queue_delay,
      max_concurrent,
      preconnect_enabled);
  predictor_->AddRef();

  // TODO(jar): Until connection notification and DNS observation handling are
  // properly combined into a learning model, we'll only use one observation
  // mechanism or the other.
  if (preconnect_enabled) {
    DCHECK(!speculative_interceptor_);
    speculative_interceptor_ = new chrome_browser_net::ConnectInterceptor;
  } else {
    DCHECK(!prefetch_observer_);
    prefetch_observer_ = chrome_browser_net::CreateResolverObserver();
    globals_->host_resolver->AddObserver(prefetch_observer_);
  }

  FinalizePredictorInitialization(
      predictor_, prefetch_observer_, startup_urls, referral_list);
}

void IOThread::ChangedToOnTheRecordOnIOThread() {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));

  if (predictor_) {
    // Destroy all evidence of our OTR session.
    predictor_->Predictor::DiscardAllResults();
  }

  // Clear the host cache to avoid showing entries from the OTR session
  // in about:net-internals.
  if (globals_->host_resolver->GetAsHostResolverImpl()) {
    net::HostCache* host_cache =
        globals_->host_resolver.get()->GetAsHostResolverImpl()->cache();
    if (host_cache)
      host_cache->clear();
  }
  // Clear all of the passively logged data.
  // TODO(eroman): this is a bit heavy handed, really all we need to do is
  //               clear the data pertaining to off the record context.
  globals_->net_log->passive_collector()->Clear();
}
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "tree.hh"

namespace Dune {
namespace Stuff {
namespace Common {

ExtendedParameterTree::ExtendedParameterTree()
{}

ExtendedParameterTree::ExtendedParameterTree(const std::string filename)
  : BaseType(init(filename))
{}

ExtendedParameterTree::ExtendedParameterTree(int argc, char** argv, std::string filename)
  : ExtendedParameterTree::BaseType(init(argc, argv, filename))
{}

ExtendedParameterTree::ExtendedParameterTree(const Dune::ParameterTree& other)
  : ExtendedParameterTree::BaseType(other)
{}

ExtendedParameterTree& ExtendedParameterTree::operator=(const Dune::ParameterTree& other)
{
  if (this != &other) {
    BaseType::operator=(other);
  }
  return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)

/**
 *  \brief adds another Dune::ParameterTree
 */
void ExtendedParameterTree::add(const Dune::ParameterTree& _other, const std::string _subName /*= ""*/)
{
  if (_subName.empty()) {
    // copy each key/value pair and append subName
    const Dune::ParameterTree::KeyVector& keyVector = _other.getValueKeys();
    for (size_t ii = 0; ii < keyVector.size(); ++ii) {
      const std::string key = keyVector[ii];
      if (BaseType::hasKey(key))
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << DSC::colorStringRed("ERROR:")
                   << " key '" << key << "' already exists in the follingDune::ParameterTree:\n"
                   << reportString("  "));
      BaseType::operator[](key) = _other.get< std::string >(key);
    }
  } else {
    if (BaseType::hasKey(_subName))
      DUNE_THROW(Dune::InvalidStateException,
                 "\n" << DSC::colorStringRed("ERROR:")
                 << " key '" << _subName << "' already exists in the follingDune::ParameterTree:\n"
                 << reportString("  "));
    else if (BaseType::hasSub(_subName)) {
      ExtendedParameterTree _sub = BaseType::sub(_subName);
      _sub.add(_other);
      BaseType::sub(_subName) = _sub;
    } else
      BaseType::sub(_subName) = _other;
  }
} // ... add(...)

ExtendedParameterTree ExtendedParameterTree::sub(const std::string& _sub) const
{
  if (!hasSub(_sub))
      DUNE_THROW(Dune::RangeError,
                 "\n" << DSC::colorStringRed("ERROR:")
                 << " sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString("  "));
  return ExtendedParameterTree(BaseType::sub(_sub));
}

void ExtendedParameterTree::report(std::ostream& stream /*= std::cout*/, const std::string& prefix /*= ""*/) const
{
  reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const

void ExtendedParameterTree::reportNicely(std::ostream& stream /*= std::cout*/) const
{
  if (valueKeys.size() == 0 || subKeys.size() == 0) {
    const std::string commonPrefix = findCommonPrefix(*this);
    if (!commonPrefix.empty()) {
      stream << "[" << commonPrefix << "]" << std::endl;
      const ExtendedParameterTree& commonSub = sub(commonPrefix);
      reportFlatly(commonSub, "", stream);
    }
  } else
    reportAsSub(stream, "", "");
}

std::string ExtendedParameterTree::reportString(const std::string& prefix /*= ""*/) const
{
  std::stringstream stream;
  report(stream, prefix);
  return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const

bool ExtendedParameterTree::hasVector(const std::string& key) const
{
  if (hasKey(key)) {
    const std::string str = BaseType::get< std::string >(key, "meaningless_default_value");
    return (str.substr(0, 1) ==  "["
        && str.substr(str.size() - 1, 1) == "]");
  }
  return false;
} // bool hasVector(const std::string& vector) const

void ExtendedParameterTree::assertKey(const std::string& key) const
{
  if (!BaseType::hasKey(key))
    DUNE_THROW(Dune::RangeError,
               "\n" << DSC::colorStringRed("ERROR:")
               << " key '" << key << "' missing  in the following Dune::ParameterTree:\n" << reportString("  "));
}

void ExtendedParameterTree::assertSub(const std::string& _sub) const
{
  if (!BaseType::hasSub(_sub))
    DUNE_THROW(Dune::RangeError,
               "\n" << DSC::colorStringRed("ERROR:")
               << " sub '" << _sub << "' missing  in the following Dune::ParameterTree:\n" << reportString("  "));
}

/**
  \brief      Fills a Dune::ParameterTree given a parameter file or command line arguments.
  \param[in]  argc
              From \c main()
  \param[in]  argv
              From \c main()
  \return     The Dune::ParameterTree that is to be filled.
  **/
ParameterTree ExtendedParameterTree::init(int argc, char** argv, std::string filename)
{
  Dune::ParameterTree paramTree;
  if (argc == 1) {
    Dune::ParameterTreeParser::readINITree(filename, paramTree);
  } else if (argc == 2) {
    Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
  } else {
    Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
  }
  if (paramTree.hasKey("paramfile")) {
    Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
  }
  return paramTree;
} // static ExtendedParameterTree init(...)

ParameterTree ExtendedParameterTree::init(const std::string filename)
{
  Dune::ParameterTree paramTree;
  Dune::ParameterTreeParser::readINITree(filename, paramTree);
  return paramTree;
} // static ExtendedParameterTree init(...)

void ExtendedParameterTree::reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
  for (auto pair : values)
    stream << prefix << pair.first << " = " << pair.second << std::endl;
//      stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
  for (auto pair : subs) {
    ExtendedParameterTree subTree(pair.second);
    if (subTree.getValueKeys().size())
      stream << prefix << "[" << subPath << pair.first << "]" << std::endl;
    subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
  }
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const

std::string ExtendedParameterTree::findCommonPrefix(const BaseType& subtree, const std::string previousPrefix /*= ""*/) const
{
  const auto& valuekeys = subtree.getValueKeys();
  const auto& subkeys = subtree.getSubKeys();
  if (valuekeys.size() == 0 && subkeys.size() == 1) {
    // we append the subs name
    if (previousPrefix.empty())
      return findCommonPrefix(subtree.sub(subkeys[0]), subkeys[0]);
    else
      return findCommonPrefix(subtree.sub(subkeys[0]), previousPrefix + "." + subkeys[0]);
  } else {
    // end of the recursion, return the previous prefix
    return previousPrefix;
  }
}

void ExtendedParameterTree::reportFlatly(const BaseType& subtree, const std::string& prefix /*= ""*/,
                                         std::ostream& stream /*= std::cout*/) const
{
  // report all the keys
  for (auto key : subtree.getValueKeys())
    stream << prefix << key << " = " << subtree[key] << std::endl;
  // report all the subs
  for (auto subkey : subtree.getSubKeys()) {
    if (prefix.empty())
      reportFlatly(subtree.sub(subkey), subkey + ".", stream);
    else
      reportFlatly(subtree.sub(subkey), prefix + subkey+ "." , stream);
  }
}

} // namespace Common
} // namespace Stuff
} // namespace Dune
<commit_msg>[common.parameter.tree] added missing config.h include<commit_after>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include "tree.hh"

namespace Dune {
namespace Stuff {
namespace Common {

ExtendedParameterTree::ExtendedParameterTree()
{}

ExtendedParameterTree::ExtendedParameterTree(const std::string filename)
  : BaseType(init(filename))
{}

ExtendedParameterTree::ExtendedParameterTree(int argc, char** argv, std::string filename)
  : ExtendedParameterTree::BaseType(init(argc, argv, filename))
{}

ExtendedParameterTree::ExtendedParameterTree(const Dune::ParameterTree& other)
  : ExtendedParameterTree::BaseType(other)
{}

ExtendedParameterTree& ExtendedParameterTree::operator=(const Dune::ParameterTree& other)
{
  if (this != &other) {
    BaseType::operator=(other);
  }
  return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)

/**
 *  \brief adds another Dune::ParameterTree
 */
void ExtendedParameterTree::add(const Dune::ParameterTree& _other, const std::string _subName /*= ""*/)
{
  if (_subName.empty()) {
    // copy each key/value pair and append subName
    const Dune::ParameterTree::KeyVector& keyVector = _other.getValueKeys();
    for (size_t ii = 0; ii < keyVector.size(); ++ii) {
      const std::string key = keyVector[ii];
      if (BaseType::hasKey(key))
        DUNE_THROW(Dune::InvalidStateException,
                   "\n" << DSC::colorStringRed("ERROR:")
                   << " key '" << key << "' already exists in the follingDune::ParameterTree:\n"
                   << reportString("  "));
      BaseType::operator[](key) = _other.get< std::string >(key);
    }
  } else {
    if (BaseType::hasKey(_subName))
      DUNE_THROW(Dune::InvalidStateException,
                 "\n" << DSC::colorStringRed("ERROR:")
                 << " key '" << _subName << "' already exists in the follingDune::ParameterTree:\n"
                 << reportString("  "));
    else if (BaseType::hasSub(_subName)) {
      ExtendedParameterTree _sub = BaseType::sub(_subName);
      _sub.add(_other);
      BaseType::sub(_subName) = _sub;
    } else
      BaseType::sub(_subName) = _other;
  }
} // ... add(...)

ExtendedParameterTree ExtendedParameterTree::sub(const std::string& _sub) const
{
  if (!hasSub(_sub))
      DUNE_THROW(Dune::RangeError,
                 "\n" << DSC::colorStringRed("ERROR:")
                 << " sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString("  "));
  return ExtendedParameterTree(BaseType::sub(_sub));
}

void ExtendedParameterTree::report(std::ostream& stream /*= std::cout*/, const std::string& prefix /*= ""*/) const
{
  reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const

void ExtendedParameterTree::reportNicely(std::ostream& stream /*= std::cout*/) const
{
  if (valueKeys.size() == 0 || subKeys.size() == 0) {
    const std::string commonPrefix = findCommonPrefix(*this);
    if (!commonPrefix.empty()) {
      stream << "[" << commonPrefix << "]" << std::endl;
      const ExtendedParameterTree& commonSub = sub(commonPrefix);
      reportFlatly(commonSub, "", stream);
    }
  } else
    reportAsSub(stream, "", "");
}

std::string ExtendedParameterTree::reportString(const std::string& prefix /*= ""*/) const
{
  std::stringstream stream;
  report(stream, prefix);
  return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const

bool ExtendedParameterTree::hasVector(const std::string& key) const
{
  if (hasKey(key)) {
    const std::string str = BaseType::get< std::string >(key, "meaningless_default_value");
    return (str.substr(0, 1) ==  "["
        && str.substr(str.size() - 1, 1) == "]");
  }
  return false;
} // bool hasVector(const std::string& vector) const

void ExtendedParameterTree::assertKey(const std::string& key) const
{
  if (!BaseType::hasKey(key))
    DUNE_THROW(Dune::RangeError,
               "\n" << DSC::colorStringRed("ERROR:")
               << " key '" << key << "' missing  in the following Dune::ParameterTree:\n" << reportString("  "));
}

void ExtendedParameterTree::assertSub(const std::string& _sub) const
{
  if (!BaseType::hasSub(_sub))
    DUNE_THROW(Dune::RangeError,
               "\n" << DSC::colorStringRed("ERROR:")
               << " sub '" << _sub << "' missing  in the following Dune::ParameterTree:\n" << reportString("  "));
}

/**
  \brief      Fills a Dune::ParameterTree given a parameter file or command line arguments.
  \param[in]  argc
              From \c main()
  \param[in]  argv
              From \c main()
  \return     The Dune::ParameterTree that is to be filled.
  **/
ParameterTree ExtendedParameterTree::init(int argc, char** argv, std::string filename)
{
  Dune::ParameterTree paramTree;
  if (argc == 1) {
    Dune::ParameterTreeParser::readINITree(filename, paramTree);
  } else if (argc == 2) {
    Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
  } else {
    Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
  }
  if (paramTree.hasKey("paramfile")) {
    Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
  }
  return paramTree;
} // static ExtendedParameterTree init(...)

ParameterTree ExtendedParameterTree::init(const std::string filename)
{
  Dune::ParameterTree paramTree;
  Dune::ParameterTreeParser::readINITree(filename, paramTree);
  return paramTree;
} // static ExtendedParameterTree init(...)

void ExtendedParameterTree::reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
  for (auto pair : values)
    stream << prefix << pair.first << " = " << pair.second << std::endl;
//      stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
  for (auto pair : subs) {
    ExtendedParameterTree subTree(pair.second);
    if (subTree.getValueKeys().size())
      stream << prefix << "[" << subPath << pair.first << "]" << std::endl;
    subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
  }
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const

std::string ExtendedParameterTree::findCommonPrefix(const BaseType& subtree, const std::string previousPrefix /*= ""*/) const
{
  const auto& valuekeys = subtree.getValueKeys();
  const auto& subkeys = subtree.getSubKeys();
  if (valuekeys.size() == 0 && subkeys.size() == 1) {
    // we append the subs name
    if (previousPrefix.empty())
      return findCommonPrefix(subtree.sub(subkeys[0]), subkeys[0]);
    else
      return findCommonPrefix(subtree.sub(subkeys[0]), previousPrefix + "." + subkeys[0]);
  } else {
    // end of the recursion, return the previous prefix
    return previousPrefix;
  }
}

void ExtendedParameterTree::reportFlatly(const BaseType& subtree, const std::string& prefix /*= ""*/,
                                         std::ostream& stream /*= std::cout*/) const
{
  // report all the keys
  for (auto key : subtree.getValueKeys())
    stream << prefix << key << " = " << subtree[key] << std::endl;
  // report all the subs
  for (auto subkey : subtree.getSubKeys()) {
    if (prefix.empty())
      reportFlatly(subtree.sub(subkey), subkey + ".", stream);
    else
      reportFlatly(subtree.sub(subkey), prefix + subkey+ "." , stream);
  }
}

} // namespace Common
} // namespace Stuff
} // namespace Dune
<|endoftext|>


<commit_before>#include "test_common.hh"

#if HAVE_DUNE_GRID

#include <dune/stuff/grid/information.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/logstreams.hh>
#include <dune/common/shared_ptr.hh>

using namespace Dune::Stuff::Common;
using namespace Dune::Stuff::Grid;
using namespace std;

template < int i >
struct Int {
  static const int value = i;
};

typedef testing::Types< Int<1>, Int<2>, Int<3>, Int<4>, Int<5>, Int<6>, Int<7>, Int<8>, Int<9>, Int<10> > GridDims;

template < class T >
struct GridInfoTest : public ::testing::Test {
  static const int griddim  = T::value;
  static const int level = 1;
  typedef Dune::YaspGrid<griddim> GridType;
  Dune::shared_ptr<GridType> gridPtr;
  GridInfoTest()
    :gridPtr(Provider::Cube<GridType>(level).grid())
  {}

  void check() {
    const Dimensions<GridType> dim(*gridPtr);
    const auto gv = gridPtr->leafView();
    const int entities = gv.size(0);
    EXPECT_DOUBLE_EQ(1.0/double(entities),dim.entity_volume.min());
    EXPECT_DOUBLE_EQ(dim.entity_volume.min(),dim.entity_volume.max());
    EXPECT_DOUBLE_EQ(dim.entity_volume.min(),dim.entity_volume.average());
    EXPECT_DOUBLE_EQ(1.0,dim.volumeRelation());
    const auto& dl = dim.coord_limits;
    for( int i : valueRange(griddim) )
    {
      EXPECT_DOUBLE_EQ(dl[i].max(),1.0);
      EXPECT_DOUBLE_EQ(dl[i].min(),0.0);
      EXPECT_DOUBLE_EQ(dl[i].average(),0.5);
    }
    const Statistics st(gv);
    const int line = std::pow(2,level);
    EXPECT_EQ(std::pow(line,griddim-1)*2*griddim, st.numberOfBoundaryIntersections);
    EXPECT_EQ(entities*(2*griddim), st.numberOfIntersections);
    EXPECT_EQ(st.numberOfIntersections - st.numberOfBoundaryIntersections, st.numberOfInnerIntersections );
    EXPECT_EQ(griddim*2, maxNumberOfNeighbors(gv));
  }

  void print(std::ostream& out) {
    const auto& gv = gridPtr->leafView();
    printInfo(gv, out);
  }
};

TYPED_TEST_CASE(GridInfoTest, GridDims);
TYPED_TEST(GridInfoTest, Misc) {
  this->check();
  this->print(dev_null);
}

#endif // #if HAVE_DUNE_GRID

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  Dune::MPIHelper::instance(argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>[tests] narrow test dim range for grid info<commit_after>#include "test_common.hh"

#if HAVE_DUNE_GRID

#include <dune/stuff/grid/information.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/logstreams.hh>
#include <dune/common/shared_ptr.hh>

using namespace Dune::Stuff::Common;
using namespace Dune::Stuff::Grid;
using namespace std;

template < int i >
struct Int {
  static const int value = i;
};

typedef testing::Types< Int<1>, Int<2>, Int<3> > GridDims;

template < class T >
struct GridInfoTest : public ::testing::Test {
  static const int griddim  = T::value;
  static const int level = 1;
  typedef Dune::YaspGrid<griddim> GridType;
  Dune::shared_ptr<GridType> gridPtr;
  GridInfoTest()
    :gridPtr(Provider::Cube<GridType>(level).grid())
  {}

  void check() {
    const Dimensions<GridType> dim(*gridPtr);
    const auto gv = gridPtr->leafView();
    const int entities = gv.size(0);
    EXPECT_DOUBLE_EQ(1.0/double(entities),dim.entity_volume.min());
    EXPECT_DOUBLE_EQ(dim.entity_volume.min(),dim.entity_volume.max());
    EXPECT_DOUBLE_EQ(dim.entity_volume.min(),dim.entity_volume.average());
    EXPECT_DOUBLE_EQ(1.0,dim.volumeRelation());
    const auto& dl = dim.coord_limits;
    for( int i : valueRange(griddim) )
    {
      EXPECT_DOUBLE_EQ(dl[i].max(),1.0);
      EXPECT_DOUBLE_EQ(dl[i].min(),0.0);
      EXPECT_DOUBLE_EQ(dl[i].average(),0.5);
    }
    const Statistics st(gv);
    const int line = std::pow(2,level);
    EXPECT_EQ(std::pow(line,griddim-1)*2*griddim, st.numberOfBoundaryIntersections);
    EXPECT_EQ(entities*(2*griddim), st.numberOfIntersections);
    EXPECT_EQ(st.numberOfIntersections - st.numberOfBoundaryIntersections, st.numberOfInnerIntersections );
    EXPECT_EQ(griddim*2, maxNumberOfNeighbors(gv));
  }

  void print(std::ostream& out) {
    const auto& gv = gridPtr->leafView();
    printInfo(gv, out);
  }
};

TYPED_TEST_CASE(GridInfoTest, GridDims);
TYPED_TEST(GridInfoTest, Misc) {
  this->check();
  this->print(dev_null);
}

#endif // #if HAVE_DUNE_GRID

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  Dune::MPIHelper::instance(argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#ifdef ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37

#if ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 != 11
#error "Multiple anyode.hpp files included with version mismatch"
#endif

#else
#define ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 11

#include <string>
#include <unordered_map>
#include <vector>

namespace AnyODE {
    template<class T> void ignore( const T& ) { } // ignore unused parameter compiler warnings, or: `int /* arg */`

    enum class Status : int {success = 0, recoverable_error = 1, unrecoverable_error = -1};

    template <typename Real_t=double>
    struct OdeSysBase {
        int nfev=0, njev=0;
        void * integrator = nullptr;
        void * user_data = nullptr;
        std::unordered_map<std::string, int> last_integration_info;
        std::unordered_map<std::string, double> last_integration_info_dbl;
        std::unordered_map<std::string, std::vector<double> > last_integration_info_vecdbl;
        std::unordered_map<std::string, std::vector<int> > last_integration_info_vecint;
        Real_t default_dx0 = 0.0;  // *may* be used by `get_dx0`, 0 signifies solver default
        bool autonomous_exprs = false;
        bool use_get_dx_max = false;  // whether get_dx_max should be called
        bool record_rhs_xvals = false;
        bool record_jac_xvals = false;
        bool record_order = false;
        bool record_fpe = false;
        bool record_steps = false;
        virtual ~OdeSysBase() {}
        virtual int get_ny() const = 0;
        virtual int get_mlower() const { return -1; } // -1 denotes "not banded"
        virtual int get_mupper() const { return -1; } // -1 denotes "not banded"
        virtual int get_nroots() const { return 0; } // Do not look for roots by default;
        virtual Real_t get_dx0(Real_t /* t */,
                               const Real_t * const /* y */) {
            return default_dx0;
        }
        virtual Real_t get_dx_max(Real_t /* t */, const Real_t * const /* y */) {
            return 0.0;
        }
        virtual Status rhs(Real_t t, const Real_t * const y, Real_t * const f) = 0;
        virtual Status roots(Real_t xval, const Real_t * const y, Real_t * const out) {
            ignore(xval); ignore(y); ignore(out);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_cmaj(Real_t t,
                                      const Real_t * const __restrict__ y,
                                      const Real_t * const __restrict__ fy,
                                      Real_t * const __restrict__ jac,
                                      long int ldim,
                                      Real_t * const __restrict__ dfdt=nullptr){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_rmaj(Real_t t,
                                      const Real_t * const __restrict__ y,
                                      const Real_t * const __restrict__ fy,
                                      Real_t * const __restrict__ jac,
                                      long int ldim,
                                      Real_t * const __restrict__ dfdt=nullptr){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
            return Status::unrecoverable_error;
        }
        virtual Status banded_jac_cmaj(Real_t t,
                                       const Real_t * const __restrict__ y,
                                       const Real_t * const __restrict__ fy,
                                       Real_t * const __restrict__ jac,
                                       long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            throw std::runtime_error("banded_jac_cmaj not implemented.");
            return Status::unrecoverable_error;
        }
        virtual Status jac_times_vec(const Real_t * const __restrict__ vec,
                                     Real_t * const __restrict__ out,
                                     Real_t t,
                                     const Real_t * const __restrict__ y,
                                     const Real_t * const __restrict__ fy
                                     )
        {
            ignore(vec);
            ignore(out);
            ignore(t);
            ignore(y);
            ignore(fy);
            return Status::unrecoverable_error;
        }
        virtual Status prec_setup(Real_t t,
                                const Real_t * const __restrict__ y,
                                const Real_t * const __restrict__ fy,
                                bool jok,
                                bool& jac_recomputed,
                                Real_t gamma)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(jok);
            ignore(jac_recomputed);
            ignore(gamma);
            return Status::unrecoverable_error;
        }
        virtual Status prec_solve_left(const Real_t t,
                                       const Real_t * const __restrict__ y,
                                       const Real_t * const __restrict__ fy,
                                       const Real_t * const __restrict__ r,
                                       Real_t * const __restrict__ z,
                                       Real_t gamma,
                                       Real_t delta,
                                       const Real_t * const __restrict__ ewt)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(r);
            ignore(z);
            ignore(gamma);
            ignore(delta);
            ignore(ewt);
            return Status::unrecoverable_error;
        }
    };

}
#endif /* ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 */
<commit_msg>Add quads<commit_after>#ifdef ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37

#if ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 != 12
#error "Multiple anyode.hpp files included with version mismatch"
#endif

#else
#define ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 12

#include <string>
#include <unordered_map>
#include <vector>

namespace AnyODE {
    template<class T> void ignore( const T& ) { } // ignore unused parameter compiler warnings, or: `int /* arg */`

    enum class Status : int {success = 0, recoverable_error = 1, unrecoverable_error = -1};

    template <typename Real_t=double>
    struct OdeSysBase {
        int nfev=0, njev=0;
        void * integrator = nullptr;
        void * user_data = nullptr;
        std::unordered_map<std::string, int> last_integration_info;
        std::unordered_map<std::string, double> last_integration_info_dbl;
        std::unordered_map<std::string, std::vector<double> > last_integration_info_vecdbl;
        std::unordered_map<std::string, std::vector<int> > last_integration_info_vecint;
        Real_t default_dx0 = 0.0;  // *may* be used by `get_dx0`, 0 signifies solver default
        bool autonomous_exprs = false;
        bool use_get_dx_max = false;  // whether get_dx_max should be called
        bool record_rhs_xvals = false;
        bool record_jac_xvals = false;
        bool record_order = false;
        bool record_fpe = false;
        bool record_steps = false;
        virtual ~OdeSysBase() {}
        virtual int get_ny() const = 0;
        virtual int get_mlower() const { return -1; } // -1 denotes "not banded"
        virtual int get_mupper() const { return -1; } // -1 denotes "not banded"
        virtual int get_nroots() const { return 0; } // Do not look for roots by default;
        virtual int get_nquad() const { return 0; } // Do not track quadratures by default;
        virtual Real_t get_dx0(Real_t /* t */,
                               const Real_t * const /* y */) {
            return default_dx0;
        }
        virtual Real_t get_dx_max(Real_t /* t */, const Real_t * const /* y */) {
            return 0.0;
        }
        virtual Status rhs(Real_t t, const Real_t * const y, Real_t * const f) = 0;
        virtual Status roots(Real_t xval, const Real_t * const y, Real_t * const out) {
            ignore(xval); ignore(y); ignore(out);
            return Status::unrecoverable_error;
        }
        virtual Status quads(Real_t xval, const Real_t * const y, Real_t * const out) {
            ignore(xval); ignore(y); ignore(out);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_cmaj(Real_t t,
                                      const Real_t * const __restrict__ y,
                                      const Real_t * const __restrict__ fy,
                                      Real_t * const __restrict__ jac,
                                      long int ldim,
                                      Real_t * const __restrict__ dfdt=nullptr){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
            return Status::unrecoverable_error;
        }
        virtual Status dense_jac_rmaj(Real_t t,
                                      const Real_t * const __restrict__ y,
                                      const Real_t * const __restrict__ fy,
                                      Real_t * const __restrict__ jac,
                                      long int ldim,
                                      Real_t * const __restrict__ dfdt=nullptr){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
            return Status::unrecoverable_error;
        }
        virtual Status banded_jac_cmaj(Real_t t,
                                       const Real_t * const __restrict__ y,
                                       const Real_t * const __restrict__ fy,
                                       Real_t * const __restrict__ jac,
                                       long int ldim){
            ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
            throw std::runtime_error("banded_jac_cmaj not implemented.");
            return Status::unrecoverable_error;
        }
        virtual Status jac_times_vec(const Real_t * const __restrict__ vec,
                                     Real_t * const __restrict__ out,
                                     Real_t t,
                                     const Real_t * const __restrict__ y,
                                     const Real_t * const __restrict__ fy
                                     )
        {
            ignore(vec);
            ignore(out);
            ignore(t);
            ignore(y);
            ignore(fy);
            return Status::unrecoverable_error;
        }
        virtual Status prec_setup(Real_t t,
                                const Real_t * const __restrict__ y,
                                const Real_t * const __restrict__ fy,
                                bool jok,
                                bool& jac_recomputed,
                                Real_t gamma)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(jok);
            ignore(jac_recomputed);
            ignore(gamma);
            return Status::unrecoverable_error;
        }
        virtual Status prec_solve_left(const Real_t t,
                                       const Real_t * const __restrict__ y,
                                       const Real_t * const __restrict__ fy,
                                       const Real_t * const __restrict__ r,
                                       Real_t * const __restrict__ z,
                                       Real_t gamma,
                                       Real_t delta,
                                       const Real_t * const __restrict__ ewt)
        {
            ignore(t);
            ignore(y);
            ignore(fy);
            ignore(r);
            ignore(z);
            ignore(gamma);
            ignore(delta);
            ignore(ewt);
            return Status::unrecoverable_error;
        }
    };

}
#endif /* ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 */
<|endoftext|>


<commit_before>// App.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "App.h"
#include <debug.h>
#include <file.h>
#include <graphics.h>
#include <input.h>
#include <sound.h>
#include <array>

using namespace yappy;

class MyApp : public graphics::Application {
public:
	MyApp(const InitParam &param) :
		Application(param),
		m_input(param.hInstance, getHWnd()),
		m_sound()
	{}
protected:
	void init() override;
	void update() override;
	void render() override;
private:
	input::DInput m_input;
	sound::XAudio2 m_sound;
};

void MyApp::init()
{
	loadTexture("notpow2", L"../sampledata/test_400_300.png");
	loadTexture("testtex", L"../sampledata/circle.png");

	m_sound.loadSoundEffect("testwav", L"/C:/Windows/Media/chimes.wav");

	m_sound.playBgm(L"../sampledata/Epoq-Lepidoptera.ogg");
}

void MyApp::render()
{
	static int test = 0;
	test += 5;
	test %= 768;
	drawTexture("testtex", test, test);
}

void MyApp::update()
{
	m_input.processFrame();
	m_sound.processFrame();

	std::array<bool, 256> keys = m_input.getKeys();
	for (size_t i = 0U; i < keys.size(); i++) {
		if (keys[i]) {
			debug::writef(L"Key 0x%02x", i);
			m_sound.playSoundEffect("testwav");
		}
	}
	for (int i = 0; i < m_input.getPadCount(); i++) {
		DIJOYSTATE state;
		m_input.getPadState(&state, i);
		for (int b = 0; b < 32; b++) {
			if (state.rgbButtons[b] & 0x80) {
				debug::writef(L"pad[%d].button%d", i, b);
				m_sound.playSoundEffect("testwav");
			}
		}
		{
			// left stick
			if (std::abs(state.lX) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].x=%ld", i, state.lX);
			}
			if (std::abs(state.lY) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].y=%ld", i, state.lY);
			}
			// right stick
			if (std::abs(state.lZ) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].z=%ld", i, state.lZ);
			}
			if (std::abs(state.lRz) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].rz=%ld", i, state.lRz);
			}
		}
		for (int b = 0; b < 4; b++) {
			if (state.rgdwPOV[b] != -1) {
				debug::writef(L"pad[%d].POV%d=%u", i, b, state.rgdwPOV[b]);
			}
		}
	}
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	// debug test
	{
		debug::enableDebugOutput();
		debug::enableConsoleOutput();
		debug::enableFileOutput(L"log.txt");

		debug::writeLine(L"Start application");
		debug::writeLine(L"にほんご");
		debug::writef(L"%d 0x%08x %f %.8f", 123, 0x1234abcd, 3.14, 3.14);

		const wchar_t *digit = L"0123456789abcdef";
		wchar_t large[1024 + 32] = { 0 };
		for (int i = 0; i < 1024; i++) {
			large[i] = digit[i & 0xf];
		}
		debug::writef(large);

		wchar_t dir[MAX_PATH];
		::GetCurrentDirectory(MAX_PATH, dir);
		debug::writef(L"Current dir: %s", dir);
	}

	int result = 0;
	try {
		file::initWithFileSystem(L".");

		graphics::Application::InitParam param;
		param.hInstance = hInstance;
		param.w = 1024;
		param.h = 768;
		param.wndClsName = L"TestAppClass";
		param.title = L"Test App";
		param.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP));
		param.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
		param.nCmdShow = nCmdShow;

		MyApp app(param);
		result = app.run();
	}
	catch (const std::exception &ex) {
		debug::writef(L"Error: %s", ex.what());
	}

	debug::shutdownDebugOutput();
	return result;
}
<commit_msg>[#20] Animation by update(), not render()<commit_after>// App.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "App.h"
#include <debug.h>
#include <file.h>
#include <graphics.h>
#include <input.h>
#include <sound.h>
#include <array>

using namespace yappy;

class MyApp : public graphics::Application {
public:
	MyApp(const InitParam &param) :
		Application(param),
		m_input(param.hInstance, getHWnd()),
		m_sound()
	{}
protected:
	void init() override;
	void update() override;
	void render() override;
private:
	input::DInput m_input;
	sound::XAudio2 m_sound;
	uint64_t m_frameCount = 0;
};

void MyApp::init()
{
	loadTexture("notpow2", L"../sampledata/test_400_300.png");
	loadTexture("testtex", L"../sampledata/circle.png");

	m_sound.loadSoundEffect("testwav", L"/C:/Windows/Media/chimes.wav");

	m_sound.playBgm(L"../sampledata/Epoq-Lepidoptera.ogg");
}

void MyApp::render()
{
	int test = static_cast<int>(m_frameCount * 5 % 768);

	drawTexture("testtex", test, test);
}

void MyApp::update()
{
	m_input.processFrame();
	m_sound.processFrame();
	m_frameCount++;

	std::array<bool, 256> keys = m_input.getKeys();
	for (size_t i = 0U; i < keys.size(); i++) {
		if (keys[i]) {
			debug::writef(L"Key 0x%02x", i);
			m_sound.playSoundEffect("testwav");
		}
	}
	for (int i = 0; i < m_input.getPadCount(); i++) {
		DIJOYSTATE state;
		m_input.getPadState(&state, i);
		for (int b = 0; b < 32; b++) {
			if (state.rgbButtons[b] & 0x80) {
				debug::writef(L"pad[%d].button%d", i, b);
				m_sound.playSoundEffect("testwav");
			}
		}
		{
			// left stick
			if (std::abs(state.lX) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].x=%ld", i, state.lX);
			}
			if (std::abs(state.lY) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].y=%ld", i, state.lY);
			}
			// right stick
			if (std::abs(state.lZ) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].z=%ld", i, state.lZ);
			}
			if (std::abs(state.lRz) > input::DInput::AXIS_THRESHOLD) {
				debug::writef(L"pad[%d].rz=%ld", i, state.lRz);
			}
		}
		for (int b = 0; b < 4; b++) {
			if (state.rgdwPOV[b] != -1) {
				debug::writef(L"pad[%d].POV%d=%u", i, b, state.rgdwPOV[b]);
			}
		}
	}
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	// debug test
	{
		debug::enableDebugOutput();
		debug::enableConsoleOutput();
		debug::enableFileOutput(L"log.txt");

		debug::writeLine(L"Start application");
		debug::writeLine(L"にほんご");
		debug::writef(L"%d 0x%08x %f %.8f", 123, 0x1234abcd, 3.14, 3.14);

		const wchar_t *digit = L"0123456789abcdef";
		wchar_t large[1024 + 32] = { 0 };
		for (int i = 0; i < 1024; i++) {
			large[i] = digit[i & 0xf];
		}
		debug::writef(large);

		wchar_t dir[MAX_PATH];
		::GetCurrentDirectory(MAX_PATH, dir);
		debug::writef(L"Current dir: %s", dir);
	}

	int result = 0;
	try {
		file::initWithFileSystem(L".");

		graphics::Application::InitParam param;
		param.hInstance = hInstance;
		param.w = 1024;
		param.h = 768;
		param.wndClsName = L"TestAppClass";
		param.title = L"Test App";
		param.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP));
		param.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
		param.nCmdShow = nCmdShow;

		MyApp app(param);
		result = app.run();
	}
	catch (const std::exception &ex) {
		debug::writef(L"Error: %s", ex.what());
	}

	debug::shutdownDebugOutput();
	return result;
}
<|endoftext|>


<commit_before>#ifndef GLOBAL_HPP
#define GLOBAL_HPP

#include <iostream>
#include "athena/Types.hpp"
#include "athena/Utility.hpp"

#ifdef _MSC_VER
#pragma warning(disable : 4996)

#include <sys/stat.h>

#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif

#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif

#if !defined(S_ISLNK)
#define S_ISLNK(m) 0
#endif

#define PRISize "Iu"

#else

#define PRISize "zu"

#endif

#ifndef AT_PRETTY_FUNCTION
#   if defined(__PRETTY_FUNCTION__) || defined(__GNUC__)
#       define AT_PRETTY_FUNCTION __PRETTY_FUNCTION__
#   elif defined(__FUNCSIG__)
#       define AT_PRETTY_FUNCTION __FUNCSIG__
#   elif defined(__FUNCTION__)
#       define AT_PRETTY_FUNCTION __FUNCTION__
#   elif defined(__FUNC__)
#       define AT_PRETTY_FUNCTION __FUNC__
#   elif defined(__func__)
#       define AT_PRETTY_FUNCTION __func__
#   else
#       define AT_PRETTY_FUNCTION "<unknown>"
#   endif
#endif

#ifdef GEKKO
#include "gekko_support.h"
typedef struct stat atStat64_t;
#define atStat64 stat
#elif _WIN32
typedef struct _stat64 atStat64_t;
#define atStat64 _stat64
#elif __APPLE__ || __FreeBSD__
typedef struct stat atStat64_t;
#define atStat64 stat
#else
typedef struct stat64 atStat64_t;
#define atStat64 stat64
#endif

#ifndef BLOCKSZ
#define BLOCKSZ 512
#endif

#define ROUND_UP_256(val) (((val) + 255) & ~255)
#define ROUND_UP_64(val) (((val) + 63) & ~63)
#define ROUND_UP_32(val) (((val) + 31) & ~31)
#define ROUND_UP_16(val) (((val) + 15) & ~15)
#define ROUND_UP_4(val) (((val) + 3) & ~3)

#define _XSTR(s) _STR(s)
#define _STR(s) #s

#ifndef ENABLE_BITWISE_ENUM
#define ENABLE_BITWISE_ENUM(type)\
constexpr type operator|(type a, type b)\
{\
    using T = std::underlying_type_t<type>;\
    return type(static_cast<T>(a) | static_cast<T>(b));\
}\
constexpr type operator&(type a, type b)\
{\
    using T = std::underlying_type_t<type>;\
    return type(static_cast<T>(a) & static_cast<T>(b));\
}\
inline type& operator|=(type& a, const type& b)\
{\
    using T = std::underlying_type_t<type>;\
    a = type(static_cast<T>(a) | static_cast<T>(b));\
    return a;\
}\
inline type& operator&=(type& a, const type& b)\
{\
    using T = std::underlying_type_t<type>;\
    a = type(static_cast<T>(a) & static_cast<T>(b));\
    return a;\
}\
inline type operator~(const type& key)\
{\
    using T = std::underlying_type_t<type>;\
    return type(~static_cast<T>(key));\
}
#endif

namespace athena
{
namespace error
{
enum class Level
{
    Message,
    Warning,
    Error,
    Fatal
};
}
enum SeekOrigin
{
    Begin,
    Current,
    End
};

enum Endian
{
    LittleEndian,
    BigEndian
};
} // Athena

typedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* file, const char* function, int line, const char* fmt, ...);

atEXCEPTION_HANDLER atGetExceptionHandler();
/**
 * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,
 * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.
 */
void atSetExceptionHandler(atEXCEPTION_HANDLER func);

std::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);
std::ostream& operator<<(std::ostream& os, const athena::Endian& endian);

#ifdef _MSC_VER
#ifndef NDEBUG
#define atDebug(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)
#else
#define atDebug(fmt, ...)
#endif

#define atMessage(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)

#define atWarning(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)

#define atError(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)

#define atFatal(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)
#elif defined(__GNUC__)

#ifndef NDEBUG
#define atDebug(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)
#else // _MSC_VER
#define atDebug(fmt, ...)
#endif // NDEBUG

#define atMessage(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)

#define atWarning(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)

#define atError(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)

#define atFatal(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)
#endif // defined(__GNUC__)

#endif // GLOBAL_HPP
<commit_msg>Add ROUND_UP_8<commit_after>#ifndef GLOBAL_HPP
#define GLOBAL_HPP

#include <iostream>
#include "athena/Types.hpp"
#include "athena/Utility.hpp"

#ifdef _MSC_VER
#pragma warning(disable : 4996)

#include <sys/stat.h>

#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif

#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif

#if !defined(S_ISLNK)
#define S_ISLNK(m) 0
#endif

#define PRISize "Iu"

#else

#define PRISize "zu"

#endif

#ifndef AT_PRETTY_FUNCTION
#   if defined(__PRETTY_FUNCTION__) || defined(__GNUC__)
#       define AT_PRETTY_FUNCTION __PRETTY_FUNCTION__
#   elif defined(__FUNCSIG__)
#       define AT_PRETTY_FUNCTION __FUNCSIG__
#   elif defined(__FUNCTION__)
#       define AT_PRETTY_FUNCTION __FUNCTION__
#   elif defined(__FUNC__)
#       define AT_PRETTY_FUNCTION __FUNC__
#   elif defined(__func__)
#       define AT_PRETTY_FUNCTION __func__
#   else
#       define AT_PRETTY_FUNCTION "<unknown>"
#   endif
#endif

#ifdef GEKKO
#include "gekko_support.h"
typedef struct stat atStat64_t;
#define atStat64 stat
#elif _WIN32
typedef struct _stat64 atStat64_t;
#define atStat64 _stat64
#elif __APPLE__ || __FreeBSD__
typedef struct stat atStat64_t;
#define atStat64 stat
#else
typedef struct stat64 atStat64_t;
#define atStat64 stat64
#endif

#ifndef BLOCKSZ
#define BLOCKSZ 512
#endif

#define ROUND_UP_256(val) (((val) + 255) & ~255)
#define ROUND_UP_64(val) (((val) + 63) & ~63)
#define ROUND_UP_32(val) (((val) + 31) & ~31)
#define ROUND_UP_16(val) (((val) + 15) & ~15)
#define ROUND_UP_8(val) (((val) + 7) & ~7)
#define ROUND_UP_4(val) (((val) + 3) & ~3)

#define _XSTR(s) _STR(s)
#define _STR(s) #s

#ifndef ENABLE_BITWISE_ENUM
#define ENABLE_BITWISE_ENUM(type)\
constexpr type operator|(type a, type b)\
{\
    using T = std::underlying_type_t<type>;\
    return type(static_cast<T>(a) | static_cast<T>(b));\
}\
constexpr type operator&(type a, type b)\
{\
    using T = std::underlying_type_t<type>;\
    return type(static_cast<T>(a) & static_cast<T>(b));\
}\
inline type& operator|=(type& a, const type& b)\
{\
    using T = std::underlying_type_t<type>;\
    a = type(static_cast<T>(a) | static_cast<T>(b));\
    return a;\
}\
inline type& operator&=(type& a, const type& b)\
{\
    using T = std::underlying_type_t<type>;\
    a = type(static_cast<T>(a) & static_cast<T>(b));\
    return a;\
}\
inline type operator~(const type& key)\
{\
    using T = std::underlying_type_t<type>;\
    return type(~static_cast<T>(key));\
}
#endif

namespace athena
{
namespace error
{
enum class Level
{
    Message,
    Warning,
    Error,
    Fatal
};
}
enum SeekOrigin
{
    Begin,
    Current,
    End
};

enum Endian
{
    LittleEndian,
    BigEndian
};
} // Athena

typedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* file, const char* function, int line, const char* fmt, ...);

atEXCEPTION_HANDLER atGetExceptionHandler();
/**
 * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,
 * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.
 */
void atSetExceptionHandler(atEXCEPTION_HANDLER func);

std::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);
std::ostream& operator<<(std::ostream& os, const athena::Endian& endian);

#ifdef _MSC_VER
#ifndef NDEBUG
#define atDebug(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)
#else
#define atDebug(fmt, ...)
#endif

#define atMessage(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)

#define atWarning(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)

#define atError(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)

#define atFatal(fmt, ...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt, ##__VA_ARGS__); \
} while(0)
#elif defined(__GNUC__)

#ifndef NDEBUG
#define atDebug(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)
#else // _MSC_VER
#define atDebug(fmt, ...)
#endif // NDEBUG

#define atMessage(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)

#define atWarning(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)

#define atError(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)

#define atFatal(fmt...) \
    do { atEXCEPTION_HANDLER __handler = atGetExceptionHandler(); \
    if (__handler) \
        __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, fmt); \
} while(0)
#endif // defined(__GNUC__)

#endif // GLOBAL_HPP
<|endoftext|>


<commit_before>#ifndef LIBBITCOIN_TYPES_H
#define LIBBITCOIN_TYPES_H

#include <boost/detail/endian.hpp>
#include <boost/asio.hpp>
#include <array>
#include <memory>
#include <sstream>
#include <iomanip>
#include <vector>

#include <bitcoin/network/types.hpp>

namespace libbitcoin {

using std::shared_ptr;
using boost::asio::io_service;
using boost::asio::ip::tcp;
using boost::asio::deadline_timer;

class dialect;
class storage;
class kernel;
namespace net {
    class network;
} // net
class clock;

typedef shared_ptr<dialect> dialect_ptr;
typedef shared_ptr<storage> storage_ptr;
typedef shared_ptr<kernel> kernel_ptr;
typedef shared_ptr<network> network_ptr;
typedef shared_ptr<clock> clock_ptr;

typedef shared_ptr<io_service> service_ptr;
typedef shared_ptr<io_service::work> work_ptr;
typedef shared_ptr<io_service::strand> strand_ptr;
typedef shared_ptr<tcp::socket> socket_ptr;
typedef shared_ptr<deadline_timer> deadline_timer_ptr;

typedef std::array<uint8_t, 32> hash_digest;
typedef std::array<uint8_t, 20> short_hash;

typedef unsigned char byte;
typedef std::vector<byte> data_chunk;

void extend_data(data_chunk& chunk, const data_chunk& other);

template<typename T>
T cast_chunk(data_chunk chunk, bool reverse=false)
{
    #ifdef BOOST_LITTLE_ENDIAN
        reverse = !reverse;
    #elif BOOST_BIG_ENDIAN
        // do nothing
    #else
        #error "Endian isn't defined!"
    #endif

    if (reverse)
        std::reverse(chunk.begin(), chunk.end());

    T val = 0;
    for (size_t i = 0; i < sizeof(T); ++i)
        val += static_cast<T>(chunk[i]) << (i*8);
    return val;
}

template<typename T>
data_chunk uncast_type(T val)
{
    data_chunk chunk;
    for (size_t i = 0; i < sizeof(T); ++i)
        chunk.push_back(reinterpret_cast<byte*>(&val)[i]);
    return chunk;
}

template<typename T>
std::string hexlify(T data)
{
    std::stringstream ss;
    ss << std::hex;
    for (int val: data)
        ss << std::setw(2) << std::setfill('0') << val << ' ';
    // Remove end ' '
    std::string ret = ss.str();
    ret.resize(ret.size() - 1);
    return ret;
}

} // libbitcoin

#endif

<commit_msg>BUGFIX: hexlify segfault with zero-size argument<commit_after>#ifndef LIBBITCOIN_TYPES_H
#define LIBBITCOIN_TYPES_H

#include <boost/detail/endian.hpp>
#include <boost/asio.hpp>
#include <array>
#include <memory>
#include <sstream>
#include <iomanip>
#include <vector>

#include <bitcoin/network/types.hpp>

namespace libbitcoin {

using std::shared_ptr;
using boost::asio::io_service;
using boost::asio::ip::tcp;
using boost::asio::deadline_timer;

class dialect;
class storage;
class kernel;
namespace net {
    class network;
} // net
class clock;

typedef shared_ptr<dialect> dialect_ptr;
typedef shared_ptr<storage> storage_ptr;
typedef shared_ptr<kernel> kernel_ptr;
typedef shared_ptr<network> network_ptr;
typedef shared_ptr<clock> clock_ptr;

typedef shared_ptr<io_service> service_ptr;
typedef shared_ptr<io_service::work> work_ptr;
typedef shared_ptr<io_service::strand> strand_ptr;
typedef shared_ptr<tcp::socket> socket_ptr;
typedef shared_ptr<deadline_timer> deadline_timer_ptr;

typedef std::array<uint8_t, 32> hash_digest;
typedef std::array<uint8_t, 20> short_hash;

typedef unsigned char byte;
typedef std::vector<byte> data_chunk;

void extend_data(data_chunk& chunk, const data_chunk& other);

template<typename T>
T cast_chunk(data_chunk chunk, bool reverse=false)
{
    #ifdef BOOST_LITTLE_ENDIAN
        reverse = !reverse;
    #elif BOOST_BIG_ENDIAN
        // do nothing
    #else
        #error "Endian isn't defined!"
    #endif

    if (reverse)
        std::reverse(chunk.begin(), chunk.end());

    T val = 0;
    for (size_t i = 0; i < sizeof(T); ++i)
        val += static_cast<T>(chunk[i]) << (i*8);
    return val;
}

template<typename T>
data_chunk uncast_type(T val)
{
    data_chunk chunk;
    for (size_t i = 0; i < sizeof(T); ++i)
        chunk.push_back(reinterpret_cast<byte*>(&val)[i]);
    return chunk;
}

template<typename T>
std::string hexlify(T data)
{
    std::stringstream ss;
    ss << std::hex;
    for (int val: data)
        ss << std::setw(2) << std::setfill('0') << val << ' ';
    // Remove end ' '
    std::string ret = ss.str();
    if (ret.size() == 0)
        return "";
    ret.resize(ret.size() - 1);
    return ret;
}

} // libbitcoin

#endif

<|endoftext|>


<commit_before>// @(#)root/mathcore:$Id$
// Authors: David Gonzalez Maline    01/2008

/**********************************************************************
 *                                                                    *
 * Copyright (c) 2006 , LCG ROOT MathLib Team                         *
 *                                                                    *
 *                                                                    *
 **********************************************************************/

#include "Math/GaussLegendreIntegrator.h"
#include <cmath>

namespace ROOT {
namespace Math {

GaussLegendreIntegrator::GaussLegendreIntegrator(int num, double eps)
{
   // Basic contructor of GaussLegendreIntegrator.

   fEpsilon = eps;
   fNum = num;
   fX = 0;
   fW = 0;
   fLastResult = fLastError = 0;
   fUsedOnce = false;
   fFunctionCopied = false;
   fFunction = 0;

   CalcGaussLegendreSamplingPoints();
}

GaussLegendreIntegrator::~GaussLegendreIntegrator()
{
   if ( fFunction != 0 && fFunctionCopied )
      delete fFunction;

   delete [] fX;
   delete [] fW;
}

void GaussLegendreIntegrator::SetNumberPoints(int num)
{
   // Set the number of points used in the calculation of the
   // integral
   fNum = num;
   CalcGaussLegendreSamplingPoints();
}

void GaussLegendreIntegrator::GetWeightVectors(double *x, double *w)
{
   // Returns the arrays x and w containing the abscissa and weight of
   // the Gauss-Legendre n-point quadrature formula.
   //
   // Gauss-Legendre: W(x)=1 -1<x<1
   //                 (j+1)P_{j+1} = (2j+1)xP_j-jP_{j-1}

   memcpy(x, fX, fNum);
   memcpy(w, fW, fNum);
}

double GaussLegendreIntegrator::Integral(double a, double b)
{
   // Gauss-Legendre integral, see CalcGaussLegendreSamplingPoints

   if (fNum<=0 || fX == 0 || fW == 0)
      return 0;

   const double a0 = (b + a)/2;
   const double b0 = (b - a)/2;

   double xx[1];

   double result = 0.0;
   for (int i=0; i<fNum; i++)
   {
      xx[0] = a0 + b0*fX[i];
      result += fW[i] * (*fFunction)(xx);
   }

   fLastResult = result*b0;
   return fLastResult;
}

void GaussLegendreIntegrator::SetRelTolerance (double eps)
{
   // Set the desired relative Error

   fEpsilon = eps;
   CalcGaussLegendreSamplingPoints();
}

void GaussLegendreIntegrator::SetAbsTolerance (double)
{
   // Absolute Tolerance is not used in this class.

   MATH_ERROR_MSG("ROOT::Math::GausIntegratorOneDim", "There is no Absolute Tolerance!");
}

double GaussLegendreIntegrator::Result () const
{
   // Returns the result of the last Integral calculation

   if (!fUsedOnce)
      MATH_ERROR_MSG("ROOT::Math::GausIntegratorOneDim", "You must calculate the result at least once!");

   return fLastResult;
}

double GaussLegendreIntegrator::Error() const
{
   // This method is not implemented.

   return fLastError;
   // TODO
}

int GaussLegendreIntegrator::Status() const
{
   // This method is not implemented.

   return 0;
   // TODO
}

void GaussLegendreIntegrator::SetFunction (const IGenFunction & function, bool copy)
{
   // Set integration function (flag control if function must be
   // copied inside)

   if ( copy )
      fFunction = function.Clone();
   else
      fFunction = &function;

   fFunctionCopied = copy;
}

double GaussLegendreIntegrator::Integral ()
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::IntegralUp (double /*a*/)
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::IntegralLow (double /*b*/)
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::Integral (const std::vector< double > &/*pts*/)
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::IntegralCauchy (double /*a*/, double /*b*/, double /*c*/)
{
   // This method is not implemented.
   return 0.0;
}

void GaussLegendreIntegrator::CalcGaussLegendreSamplingPoints()
{
   // Type: unsafe but fast interface filling the arrays x and w (static method)
   //
   // Given the number of sampling points this routine fills the arrays x and w
   // of length num, containing the abscissa and weight of the Gauss-Legendre
   // n-point quadrature formula.
   //
   // Gauss-Legendre: W(x)=1  -1<x<1
   //                 (j+1)P_{j+1} = (2j+1)xP_j-jP_{j-1}
   //
   // num is the number of sampling points (>0)
   // x and w are arrays of size num
   // eps is the relative precision
   //
   // If num<=0 or eps<=0 no action is done.
   //
   // Reference: Numerical Recipes in C, Second Edition

   if (fNum<=0 || fEpsilon<=0)
      return;

   if ( fX == 0 )
      delete [] fX;

   if ( fW == 0 )
      delete [] fW;

   fX = new double[fNum];
   fW = new double[fNum];

   // The roots of symmetric is the interval, so we only have to find half of them
   const unsigned int m = (fNum+1)/2;

   double z, pp, p1,p2, p3;

   // Loop over the disired roots
   for (unsigned int i=0; i<m; i++) {
      z = std::cos(3.14159265358979323846*(i+0.75)/(fNum+0.5));

      // Starting with the above approximation to the i-th root, we enter
      // the main loop of refinement by Newton's method
      do {
         p1=1.0;
         p2=0.0;

         // Loop up the recurrence relation to get the Legendre
         // polynomial evaluated at z
         for (int j=0; j<fNum; j++)
         {
            p3 = p2;
            p2 = p1;
            p1 = ((2.0*j+1.0)*z*p2-j*p3)/(j+1.0);
         }
         // p1 is now the desired Legendre polynomial. We next compute pp, its
         // derivative, by a standard relation involving also p2, the polynomial
         // of one lower order
         pp = fNum*(z*p1-p2)/(z*z-1.0);
         // Newton's method
         z -= p1/pp;

      } while (std::fabs(p1/pp) > fEpsilon);

      // Put root and its symmetric counterpart
      fX[i]       = -z;
      fX[fNum-i-1] =  z;

      // Compute the weight and put its symmetric counterpart
      fW[i]       = 2.0/((1.0-z*z)*pp*pp);
      fW[fNum-i-1] = fW[i];
   }
}

}
}
<commit_msg>fix compilation error on gcc 4.3 (include missing).<commit_after>// @(#)root/mathcore:$Id$
// Authors: David Gonzalez Maline    01/2008

/**********************************************************************
 *                                                                    *
 * Copyright (c) 2006 , LCG ROOT MathLib Team                         *
 *                                                                    *
 *                                                                    *
 **********************************************************************/

#include "Math/GaussLegendreIntegrator.h"
#include <cmath>
#include <string.h>

namespace ROOT {
namespace Math {

GaussLegendreIntegrator::GaussLegendreIntegrator(int num, double eps)
{
   // Basic contructor of GaussLegendreIntegrator.

   fEpsilon = eps;
   fNum = num;
   fX = 0;
   fW = 0;
   fLastResult = fLastError = 0;
   fUsedOnce = false;
   fFunctionCopied = false;
   fFunction = 0;

   CalcGaussLegendreSamplingPoints();
}

GaussLegendreIntegrator::~GaussLegendreIntegrator()
{
   if ( fFunction != 0 && fFunctionCopied )
      delete fFunction;

   delete [] fX;
   delete [] fW;
}

void GaussLegendreIntegrator::SetNumberPoints(int num)
{
   // Set the number of points used in the calculation of the
   // integral
   fNum = num;
   CalcGaussLegendreSamplingPoints();
}

void GaussLegendreIntegrator::GetWeightVectors(double *x, double *w)
{
   // Returns the arrays x and w containing the abscissa and weight of
   // the Gauss-Legendre n-point quadrature formula.
   //
   // Gauss-Legendre: W(x)=1 -1<x<1
   //                 (j+1)P_{j+1} = (2j+1)xP_j-jP_{j-1}

   memcpy(x, fX, fNum);
   memcpy(w, fW, fNum);
}

double GaussLegendreIntegrator::Integral(double a, double b)
{
   // Gauss-Legendre integral, see CalcGaussLegendreSamplingPoints

   if (fNum<=0 || fX == 0 || fW == 0)
      return 0;

   const double a0 = (b + a)/2;
   const double b0 = (b - a)/2;

   double xx[1];

   double result = 0.0;
   for (int i=0; i<fNum; i++)
   {
      xx[0] = a0 + b0*fX[i];
      result += fW[i] * (*fFunction)(xx);
   }

   fLastResult = result*b0;
   return fLastResult;
}

void GaussLegendreIntegrator::SetRelTolerance (double eps)
{
   // Set the desired relative Error

   fEpsilon = eps;
   CalcGaussLegendreSamplingPoints();
}

void GaussLegendreIntegrator::SetAbsTolerance (double)
{
   // Absolute Tolerance is not used in this class.

   MATH_ERROR_MSG("ROOT::Math::GausIntegratorOneDim", "There is no Absolute Tolerance!");
}

double GaussLegendreIntegrator::Result () const
{
   // Returns the result of the last Integral calculation

   if (!fUsedOnce)
      MATH_ERROR_MSG("ROOT::Math::GausIntegratorOneDim", "You must calculate the result at least once!");

   return fLastResult;
}

double GaussLegendreIntegrator::Error() const
{
   // This method is not implemented.

   return fLastError;
   // TODO
}

int GaussLegendreIntegrator::Status() const
{
   // This method is not implemented.

   return 0;
   // TODO
}

void GaussLegendreIntegrator::SetFunction (const IGenFunction & function, bool copy)
{
   // Set integration function (flag control if function must be
   // copied inside)

   if ( copy )
      fFunction = function.Clone();
   else
      fFunction = &function;

   fFunctionCopied = copy;
}

double GaussLegendreIntegrator::Integral ()
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::IntegralUp (double /*a*/)
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::IntegralLow (double /*b*/)
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::Integral (const std::vector< double > &/*pts*/)
{
   // This method is not implemented.
   return 0.0;
}

double GaussLegendreIntegrator::IntegralCauchy (double /*a*/, double /*b*/, double /*c*/)
{
   // This method is not implemented.
   return 0.0;
}

void GaussLegendreIntegrator::CalcGaussLegendreSamplingPoints()
{
   // Type: unsafe but fast interface filling the arrays x and w (static method)
   //
   // Given the number of sampling points this routine fills the arrays x and w
   // of length num, containing the abscissa and weight of the Gauss-Legendre
   // n-point quadrature formula.
   //
   // Gauss-Legendre: W(x)=1  -1<x<1
   //                 (j+1)P_{j+1} = (2j+1)xP_j-jP_{j-1}
   //
   // num is the number of sampling points (>0)
   // x and w are arrays of size num
   // eps is the relative precision
   //
   // If num<=0 or eps<=0 no action is done.
   //
   // Reference: Numerical Recipes in C, Second Edition

   if (fNum<=0 || fEpsilon<=0)
      return;

   if ( fX == 0 )
      delete [] fX;

   if ( fW == 0 )
      delete [] fW;

   fX = new double[fNum];
   fW = new double[fNum];

   // The roots of symmetric is the interval, so we only have to find half of them
   const unsigned int m = (fNum+1)/2;

   double z, pp, p1,p2, p3;

   // Loop over the disired roots
   for (unsigned int i=0; i<m; i++) {
      z = std::cos(3.14159265358979323846*(i+0.75)/(fNum+0.5));

      // Starting with the above approximation to the i-th root, we enter
      // the main loop of refinement by Newton's method
      do {
         p1=1.0;
         p2=0.0;

         // Loop up the recurrence relation to get the Legendre
         // polynomial evaluated at z
         for (int j=0; j<fNum; j++)
         {
            p3 = p2;
            p2 = p1;
            p1 = ((2.0*j+1.0)*z*p2-j*p3)/(j+1.0);
         }
         // p1 is now the desired Legendre polynomial. We next compute pp, its
         // derivative, by a standard relation involving also p2, the polynomial
         // of one lower order
         pp = fNum*(z*p1-p2)/(z*z-1.0);
         // Newton's method
         z -= p1/pp;

      } while (std::fabs(p1/pp) > fEpsilon);

      // Put root and its symmetric counterpart
      fX[i]       = -z;
      fX[fNum-i-1] =  z;

      // Compute the weight and put its symmetric counterpart
      fW[i]       = 2.0/((1.0-z*z)*pp*pp);
      fW[fNum-i-1] = fW[i];
   }
}

}
}
<|endoftext|>


<commit_before>// Copyright Yangqing Jia 2013

#ifndef CAFFE_UTIL_IO_H_
#define CAFFE_UTIL_IO_H_

#include <google/protobuf/message.h>

#include <string>

#include "caffe/blob.hpp"
#include "caffe/proto/caffe.pb.h"

using std::string;
using ::google::protobuf::Message;

namespace caffe {

void ReadProtoFromTextFile(const char* filename,
    Message* proto);
inline void ReadProtoFromTextFile(const string& filename,
    Message* proto) {
  ReadProtoFromTextFile(filename.c_str(), proto);
}

void WriteProtoToTextFile(const Message& proto, const char* filename);
inline void WriteProtoToTextFile(const Message& proto, const string& filename) {
  WriteProtoToTextFile(proto, filename.c_str());
}

void ReadProtoFromBinaryFile(const char* filename,
    Message* proto);
inline void ReadProtoFromBinaryFile(const string& filename,
    Message* proto) {
  ReadProtoFromBinaryFile(filename.c_str(), proto);
}

void WriteProtoToBinaryFile(const Message& proto, const char* filename);
inline void WriteProtoToBinaryFile(
    const Message& proto, const string& filename) {
  WriteProtoToBinaryFile(proto, filename.c_str());
}

bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, Datum* datum);

inline bool ReadImageToDatum(const string& filename, const int label,
    Datum* datum) {
  ReadImageToDatum(filename, label, 0, 0, datum);
}

}  // namespace caffe

#endif   // CAFFE_UTIL_IO_H_
<commit_msg>io.hpp bugfix<commit_after>// Copyright Yangqing Jia 2013

#ifndef CAFFE_UTIL_IO_H_
#define CAFFE_UTIL_IO_H_

#include <google/protobuf/message.h>

#include <string>

#include "caffe/blob.hpp"
#include "caffe/proto/caffe.pb.h"

using std::string;
using ::google::protobuf::Message;

namespace caffe {

void ReadProtoFromTextFile(const char* filename,
    Message* proto);
inline void ReadProtoFromTextFile(const string& filename,
    Message* proto) {
  ReadProtoFromTextFile(filename.c_str(), proto);
}

void WriteProtoToTextFile(const Message& proto, const char* filename);
inline void WriteProtoToTextFile(const Message& proto, const string& filename) {
  WriteProtoToTextFile(proto, filename.c_str());
}

void ReadProtoFromBinaryFile(const char* filename,
    Message* proto);
inline void ReadProtoFromBinaryFile(const string& filename,
    Message* proto) {
  ReadProtoFromBinaryFile(filename.c_str(), proto);
}

void WriteProtoToBinaryFile(const Message& proto, const char* filename);
inline void WriteProtoToBinaryFile(
    const Message& proto, const string& filename) {
  WriteProtoToBinaryFile(proto, filename.c_str());
}

bool ReadImageToDatum(const string& filename, const int label,
    const int height, const int width, Datum* datum);

inline bool ReadImageToDatum(const string& filename, const int label,
    Datum* datum) {
  return ReadImageToDatum(filename, label, 0, 0, datum);
}

}  // namespace caffe

#endif   // CAFFE_UTIL_IO_H_
<|endoftext|>