<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/browser_shutdown.h"

#include <string>

#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/histogram.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/time.h"
#include "base/waitable_event.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/jankometer.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/plugin_process_host.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "net/predictor_api.h"

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

using base::Time;
using base::TimeDelta;

namespace browser_shutdown {

// Whether the browser is trying to quit (e.g., Quit chosen from menu).
bool g_trying_to_quit = false;

Time shutdown_started_;
ShutdownType shutdown_type_ = NOT_VALID;
int shutdown_num_processes_;
int shutdown_num_processes_slow_;

bool delete_resources_on_shutdown = true;

const char kShutdownMsFile[] = "chrome_shutdown_ms.txt";

void RegisterPrefs(PrefService* local_state) {
  local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);
  local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);
  local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);
}

ShutdownType GetShutdownType() {
  return shutdown_type_;
}

void OnShutdownStarting(ShutdownType type) {
  if (shutdown_type_ != NOT_VALID)
    return;

  shutdown_type_ = type;
  // For now, we're only counting the number of renderer processes
  // since we can't safely count the number of plugin processes from this
  // thread, and we'd really like to avoid anything which might add further
  // delays to shutdown time.
  shutdown_started_ = Time::Now();

  // Call FastShutdown on all of the RenderProcessHosts.  This will be
  // a no-op in some cases, so we still need to go through the normal
  // shutdown path for the ones that didn't exit here.
  shutdown_num_processes_ = 0;
  shutdown_num_processes_slow_ = 0;
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance()) {
    ++shutdown_num_processes_;
    if (!i.GetCurrentValue()->FastShutdownIfPossible())
      ++shutdown_num_processes_slow_;
  }
}

FilePath GetShutdownMsPath() {
  FilePath shutdown_ms_file;
  PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);
  return shutdown_ms_file.AppendASCII(kShutdownMsFile);
}

void Shutdown() {
  // Unload plugins. This needs to happen on the IO thread.
  ChromeThread::PostTask(
        ChromeThread::IO, FROM_HERE,
        NewRunnableFunction(&ChromePluginLib::UnloadAllPlugins));

  // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
  // time to get here. If you have something that *must* happen on end session,
  // consider putting it in BrowserProcessImpl::EndSession.
  DCHECK(g_browser_process);

  // Notifies we are going away.
  g_browser_process->shutdown_event()->Signal();

  PrefService* prefs = g_browser_process->local_state();

  chrome_browser_net::SavePredictorStateForNextStartupAndTrim(prefs);

  MetricsService* metrics = g_browser_process->metrics_service();
  if (metrics) {
    metrics->RecordCleanShutdown();
    metrics->RecordCompletedSessionEnd();
  }

  if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
    // Record the shutdown info so that we can put it into a histogram at next
    // startup.
    prefs->SetInteger(prefs::kShutdownType, shutdown_type_);
    prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);
    prefs->SetInteger(prefs::kShutdownNumProcessesSlow,
                      shutdown_num_processes_slow_);
  }

  // Check local state for the restart flag so we can restart the session below.
  bool restart_last_session = false;
  if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {
    restart_last_session =
        prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);
    prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);
  }

  prefs->SavePersistentPrefs();

#if defined(OS_WIN)
  // Cleanup any statics created by RLZ. Must be done before NotificationService
  // is destroyed.
  RLZTracker::CleanupRlz();
#endif

  // The jank'o'meter requires that the browser process has been destroyed
  // before calling UninstallJankometer().
  delete g_browser_process;
  g_browser_process = NULL;

  // Uninstall Jank-O-Meter here after the IO thread is no longer running.
  UninstallJankometer();

  if (delete_resources_on_shutdown)
    ResourceBundle::CleanupSharedInstance();

#if defined(OS_WIN)
  if (!Upgrade::IsBrowserAlreadyRunning() &&
      shutdown_type_ != browser_shutdown::END_SESSION) {
    Upgrade::SwapNewChromeExeIfPresent();
  }
#endif

  if (restart_last_session) {
#if !defined(OS_CHROMEOS)
    // Make sure to relaunch the browser with the same command line and add
    // Restore Last Session flag if session restore is not set.
    CommandLine command_line(*CommandLine::ForCurrentProcess());
    if (!command_line.HasSwitch(switches::kRestoreLastSession))
      command_line.AppendSwitch(switches::kRestoreLastSession);
#if defined(OS_WIN) || defined(OS_LINUX)
    Upgrade::RelaunchChromeBrowser(command_line);
#endif  // defined(OS_WIN) || defined(OS_LINUX)

#if defined(OS_MACOSX)
    command_line.AppendSwitch(switches::kActivateOnLaunch);
    base::LaunchApp(command_line, false, false, NULL);
#endif  // defined(OS_MACOSX)

#else
    NOTIMPLEMENTED();
#endif  // !defined(OS_CHROMEOS)
  }

  if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
    // Measure total shutdown time as late in the process as possible
    // and then write it to a file to be read at startup.
    // We can't use prefs since all services are shutdown at this point.
    TimeDelta shutdown_delta = Time::Now() - shutdown_started_;
    std::string shutdown_ms = Int64ToString(shutdown_delta.InMilliseconds());
    int len = static_cast<int>(shutdown_ms.length()) + 1;
    FilePath shutdown_ms_file = GetShutdownMsPath();
    file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);
  }

  UnregisterURLRequestChromeJob();
}

void ReadLastShutdownFile(
    ShutdownType type,
    int num_procs,
    int num_procs_slow) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));

  FilePath shutdown_ms_file = GetShutdownMsPath();
  std::string shutdown_ms_str;
  int64 shutdown_ms = 0;
  if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))
    shutdown_ms = StringToInt64(shutdown_ms_str);
  file_util::Delete(shutdown_ms_file, false);

  if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)
    return;

  const char *time_fmt = "Shutdown.%s.time";
  const char *time_per_fmt = "Shutdown.%s.time_per_process";
  std::string time;
  std::string time_per;
  if (type == WINDOW_CLOSE) {
    time = StringPrintf(time_fmt, "window_close");
    time_per = StringPrintf(time_per_fmt, "window_close");
  } else if (type == BROWSER_EXIT) {
    time = StringPrintf(time_fmt, "browser_exit");
    time_per = StringPrintf(time_per_fmt, "browser_exit");
  } else if (type == END_SESSION) {
    time = StringPrintf(time_fmt, "end_session");
    time_per = StringPrintf(time_per_fmt, "end_session");
  } else {
    NOTREACHED();
  }

  if (time.empty())
    return;

  // TODO(erikkay): change these to UMA histograms after a bit more testing.
  UMA_HISTOGRAM_TIMES(time.c_str(),
                      TimeDelta::FromMilliseconds(shutdown_ms));
  UMA_HISTOGRAM_TIMES(time_per.c_str(),
                      TimeDelta::FromMilliseconds(shutdown_ms / num_procs));
  UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs);
  UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow);
}

void ReadLastShutdownInfo() {
  PrefService* prefs = g_browser_process->local_state();
  ShutdownType type =
      static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));
  int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);
  int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);
  // clear the prefs immediately so we don't pick them up on a future run
  prefs->SetInteger(prefs::kShutdownType, NOT_VALID);
  prefs->SetInteger(prefs::kShutdownNumProcesses, 0);
  prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);

  // Read and delete the file on the file thread.
  ChromeThread::PostTask(
      ChromeThread::FILE, FROM_HERE,
      NewRunnableFunction(
          &ReadLastShutdownFile, type, num_procs, num_procs_slow));
}

void SetTryingToQuit(bool quitting) {
  g_trying_to_quit = quitting;
}

bool IsTryingToQuit() {
  return g_trying_to_quit;
}

}  // namespace browser_shutdown
<commit_msg>Make sure restart due to Upgrade Notification works, even if the browser was started through ShellExecute (with a switch argument terminator).<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/browser_shutdown.h"

#include <string>

#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/histogram.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/time.h"
#include "base/waitable_event.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/jankometer.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/plugin_process_host.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "net/predictor_api.h"

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

using base::Time;
using base::TimeDelta;

namespace browser_shutdown {

// Whether the browser is trying to quit (e.g., Quit chosen from menu).
bool g_trying_to_quit = false;

Time shutdown_started_;
ShutdownType shutdown_type_ = NOT_VALID;
int shutdown_num_processes_;
int shutdown_num_processes_slow_;

bool delete_resources_on_shutdown = true;

const char kShutdownMsFile[] = "chrome_shutdown_ms.txt";

void RegisterPrefs(PrefService* local_state) {
  local_state->RegisterIntegerPref(prefs::kShutdownType, NOT_VALID);
  local_state->RegisterIntegerPref(prefs::kShutdownNumProcesses, 0);
  local_state->RegisterIntegerPref(prefs::kShutdownNumProcessesSlow, 0);
}

ShutdownType GetShutdownType() {
  return shutdown_type_;
}

void OnShutdownStarting(ShutdownType type) {
  if (shutdown_type_ != NOT_VALID)
    return;

  shutdown_type_ = type;
  // For now, we're only counting the number of renderer processes
  // since we can't safely count the number of plugin processes from this
  // thread, and we'd really like to avoid anything which might add further
  // delays to shutdown time.
  shutdown_started_ = Time::Now();

  // Call FastShutdown on all of the RenderProcessHosts.  This will be
  // a no-op in some cases, so we still need to go through the normal
  // shutdown path for the ones that didn't exit here.
  shutdown_num_processes_ = 0;
  shutdown_num_processes_slow_ = 0;
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance()) {
    ++shutdown_num_processes_;
    if (!i.GetCurrentValue()->FastShutdownIfPossible())
      ++shutdown_num_processes_slow_;
  }
}

FilePath GetShutdownMsPath() {
  FilePath shutdown_ms_file;
  PathService::Get(chrome::DIR_USER_DATA, &shutdown_ms_file);
  return shutdown_ms_file.AppendASCII(kShutdownMsFile);
}

void Shutdown() {
  // Unload plugins. This needs to happen on the IO thread.
  ChromeThread::PostTask(
        ChromeThread::IO, FROM_HERE,
        NewRunnableFunction(&ChromePluginLib::UnloadAllPlugins));

  // WARNING: During logoff/shutdown (WM_ENDSESSION) we may not have enough
  // time to get here. If you have something that *must* happen on end session,
  // consider putting it in BrowserProcessImpl::EndSession.
  DCHECK(g_browser_process);

  // Notifies we are going away.
  g_browser_process->shutdown_event()->Signal();

  PrefService* prefs = g_browser_process->local_state();

  chrome_browser_net::SavePredictorStateForNextStartupAndTrim(prefs);

  MetricsService* metrics = g_browser_process->metrics_service();
  if (metrics) {
    metrics->RecordCleanShutdown();
    metrics->RecordCompletedSessionEnd();
  }

  if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
    // Record the shutdown info so that we can put it into a histogram at next
    // startup.
    prefs->SetInteger(prefs::kShutdownType, shutdown_type_);
    prefs->SetInteger(prefs::kShutdownNumProcesses, shutdown_num_processes_);
    prefs->SetInteger(prefs::kShutdownNumProcessesSlow,
                      shutdown_num_processes_slow_);
  }

  // Check local state for the restart flag so we can restart the session below.
  bool restart_last_session = false;
  if (prefs->HasPrefPath(prefs::kRestartLastSessionOnShutdown)) {
    restart_last_session =
        prefs->GetBoolean(prefs::kRestartLastSessionOnShutdown);
    prefs->ClearPref(prefs::kRestartLastSessionOnShutdown);
  }

  prefs->SavePersistentPrefs();

#if defined(OS_WIN)
  // Cleanup any statics created by RLZ. Must be done before NotificationService
  // is destroyed.
  RLZTracker::CleanupRlz();
#endif

  // The jank'o'meter requires that the browser process has been destroyed
  // before calling UninstallJankometer().
  delete g_browser_process;
  g_browser_process = NULL;

  // Uninstall Jank-O-Meter here after the IO thread is no longer running.
  UninstallJankometer();

  if (delete_resources_on_shutdown)
    ResourceBundle::CleanupSharedInstance();

#if defined(OS_WIN)
  if (!Upgrade::IsBrowserAlreadyRunning() &&
      shutdown_type_ != browser_shutdown::END_SESSION) {
    Upgrade::SwapNewChromeExeIfPresent();
  }
#endif

  if (restart_last_session) {
#if !defined(OS_CHROMEOS)
    // Make sure to relaunch the browser with the original command line plus
    // the Restore Last Session flag. Note that Chrome can be launched (ie.
    // through ShellExecute on Windows) with a switch argument terminator at
    // the end (double dash, as described in b/1366444) plus a URL,
    // which prevents us from appending to the command line directly (issue
    // 46182). We therefore use GetSwitches to copy the command line (it stops
    // at the switch argument terminator).
    CommandLine old_cl(*CommandLine::ForCurrentProcess());
    scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl.GetProgram()));
    std::map<std::string, CommandLine::StringType> switches =
        old_cl.GetSwitches();
    // Append the old switches to the new command line.
    for (std::map<std::string, CommandLine::StringType>::const_iterator i =
        switches.begin(); i != switches.end(); ++i) {
      CommandLine::StringType switch_value = i->second;
      if (!switch_value.empty())
        new_cl->AppendSwitchWithValue(i->first, i->second);
      else
        new_cl->AppendSwitch(i->first);
    }
    // Ensure restore last session is set.
    if (!new_cl->HasSwitch(switches::kRestoreLastSession))
      new_cl->AppendSwitch(switches::kRestoreLastSession);

#if defined(OS_WIN) || defined(OS_LINUX)
    Upgrade::RelaunchChromeBrowser(*new_cl.get());
#endif  // defined(OS_WIN) || defined(OS_LINUX)

#if defined(OS_MACOSX)
    new_cl->AppendSwitch(switches::kActivateOnLaunch);
    base::LaunchApp(*new_cl.get(), false, false, NULL);
#endif  // defined(OS_MACOSX)

#else
    NOTIMPLEMENTED();
#endif  // !defined(OS_CHROMEOS)
  }

  if (shutdown_type_ > NOT_VALID && shutdown_num_processes_ > 0) {
    // Measure total shutdown time as late in the process as possible
    // and then write it to a file to be read at startup.
    // We can't use prefs since all services are shutdown at this point.
    TimeDelta shutdown_delta = Time::Now() - shutdown_started_;
    std::string shutdown_ms = Int64ToString(shutdown_delta.InMilliseconds());
    int len = static_cast<int>(shutdown_ms.length()) + 1;
    FilePath shutdown_ms_file = GetShutdownMsPath();
    file_util::WriteFile(shutdown_ms_file, shutdown_ms.c_str(), len);
  }

  UnregisterURLRequestChromeJob();
}

void ReadLastShutdownFile(
    ShutdownType type,
    int num_procs,
    int num_procs_slow) {
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));

  FilePath shutdown_ms_file = GetShutdownMsPath();
  std::string shutdown_ms_str;
  int64 shutdown_ms = 0;
  if (file_util::ReadFileToString(shutdown_ms_file, &shutdown_ms_str))
    shutdown_ms = StringToInt64(shutdown_ms_str);
  file_util::Delete(shutdown_ms_file, false);

  if (type == NOT_VALID || shutdown_ms == 0 || num_procs == 0)
    return;

  const char *time_fmt = "Shutdown.%s.time";
  const char *time_per_fmt = "Shutdown.%s.time_per_process";
  std::string time;
  std::string time_per;
  if (type == WINDOW_CLOSE) {
    time = StringPrintf(time_fmt, "window_close");
    time_per = StringPrintf(time_per_fmt, "window_close");
  } else if (type == BROWSER_EXIT) {
    time = StringPrintf(time_fmt, "browser_exit");
    time_per = StringPrintf(time_per_fmt, "browser_exit");
  } else if (type == END_SESSION) {
    time = StringPrintf(time_fmt, "end_session");
    time_per = StringPrintf(time_per_fmt, "end_session");
  } else {
    NOTREACHED();
  }

  if (time.empty())
    return;

  // TODO(erikkay): change these to UMA histograms after a bit more testing.
  UMA_HISTOGRAM_TIMES(time.c_str(),
                      TimeDelta::FromMilliseconds(shutdown_ms));
  UMA_HISTOGRAM_TIMES(time_per.c_str(),
                      TimeDelta::FromMilliseconds(shutdown_ms / num_procs));
  UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.total", num_procs);
  UMA_HISTOGRAM_COUNTS_100("Shutdown.renderers.slow", num_procs_slow);
}

void ReadLastShutdownInfo() {
  PrefService* prefs = g_browser_process->local_state();
  ShutdownType type =
      static_cast<ShutdownType>(prefs->GetInteger(prefs::kShutdownType));
  int num_procs = prefs->GetInteger(prefs::kShutdownNumProcesses);
  int num_procs_slow = prefs->GetInteger(prefs::kShutdownNumProcessesSlow);
  // clear the prefs immediately so we don't pick them up on a future run
  prefs->SetInteger(prefs::kShutdownType, NOT_VALID);
  prefs->SetInteger(prefs::kShutdownNumProcesses, 0);
  prefs->SetInteger(prefs::kShutdownNumProcessesSlow, 0);

  // Read and delete the file on the file thread.
  ChromeThread::PostTask(
      ChromeThread::FILE, FROM_HERE,
      NewRunnableFunction(
          &ReadLastShutdownFile, type, num_procs, num_procs_slow));
}

void SetTryingToQuit(bool quitting) {
  g_trying_to_quit = quitting;
}

bool IsTryingToQuit() {
  return g_trying_to_quit;
}

}  // namespace browser_shutdown
<|endoftext|>


<commit_before>
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <omp.h>
using namespace std;

#pragma omp
#include "config.h"
#include "stats/utils.h"
#include "datastr/graph/graph.h"
#include "datastr/graph/SearchGraph.h"
#include "processing/DijkstraCH.h"

#include "manyToMany.h"

typedef datastr::graph::SearchGraph TransitGraph;
typedef datastr::graph::SearchGraph MyGraph;
typedef DijkstraCHManyToManyFW DijkstraManyToManyFW;
typedef DijkstraCHManyToManyBW DijkstraManyToManyBW;

/*
 * Performing the bucket scans is a crucial part of the many-to-many
 * computation.
 * It can be switched off to allow time measurements of the forward search
 * without accounting for the bucket scans.
 */
const bool performBucketScans = true;
const std::string PROFILEDIR = "/var/lib/spp/ch/";

const EdgeWeight Weight::MAX_VALUE;

Counter counter;

inline NodeID mapNodeID(const MyGraph* const g, const NodeID u) {
  // map the actual node ID to the node ID that is used internally by
  // highway-node routing
  return g->mapExtToIntNodeID(u);
}

MyGraph* loadGraph(const std::string& country, const int speed_profile,
                   const std::string& dataDir) {
  std::ostringstream filename;
  filename << dataDir << country << "-" << speed_profile << ".sgr";

  std::string path = filename.str();

  ifstream inGraph(path.c_str(), ios::binary);

  if (!inGraph) {
    std::cerr << "Input file '" << path << "' could not be read." << endl;
    exit(-1);
  }

  MyGraph* graph = new MyGraph(inGraph);
  inGraph.close();
  return graph;
}

const std::string calc_dm(const std::string& json_data,
                          const std::string& country, const int speed_profile,
                          const std::string& dataDir) {
  rapidjson::Document d;
  LevelID earlyStopLevel = 10;

  MyGraph* graph = loadGraph(country, speed_profile, dataDir);

  d.Parse<0>(json_data.c_str());

  const rapidjson::Value& sources = d["sources"];
  assert(sources.IsArray());
  vector<NodeID> v_sources;

  for (rapidjson::SizeType i = 0; i < sources.Size(); i++) {
    v_sources.push_back(mapNodeID(graph, (NodeID)sources[i].GetUint()));
  }

  ManyToMany<MyGraph, DijkstraManyToManyFW, DijkstraManyToManyBW,
             performBucketScans> mtm(graph, earlyStopLevel);
  Matrix<EdgeWeight> matrix((NodeID)sources.Size(), (NodeID)sources.Size());
  mtm.computeMatrix(v_sources, v_sources, matrix);

  int noOfRows = matrix.noOfRows();
  int noOfCols = matrix.noOfCols();

  rapidjson::Document out_doc;
  out_doc.SetObject();
  vector<string> names;

  for (int j = 0; j < noOfRows; j++) {
    rapidjson::Value result;
    result.SetArray();
    rapidjson::Document::AllocatorType& allocator = out_doc.GetAllocator();

    for (int k = 0; k < noOfCols; k++) {
      result.PushBack(matrix.value(j, k), allocator);
    }

    stringstream ss;
    ss << j;
    string str = ss.str();
    names.push_back(str);
    out_doc.AddMember(names[j].c_str(), result, out_doc.GetAllocator());
  }

  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  out_doc.Accept(writer);

  delete graph;

  return strbuf.GetString();
}

/*
const std::string calc_dm_par(const std::string& json_data,
                              const std::string& country,
                              const int speed_profile,
                              const std::string& dataDir) {
  std::cout << "parallel is enabled" << std::endl;
  rapidjson::Document d;
  LevelID earlyStopLevel = 10;

  std::stringstream filename;

  MyGraph* graph = loadGraph(country, speed_profile, dataDir);

  d.Parse<0>(json_data.c_str());

  const rapidjson::Value& sources = d["sources"];
  assert(sources.IsArray());
  vector<NodeID> v_sources;

  for (rapidjson::SizeType i = 0; i < sources.Size(); i++) {
    v_sources.push_back(mapNodeID(graph, (NodeID)sources[i].GetUint()));
  }
  rapidjson::Document out_doc;
  out_doc.SetObject();
  int max_thr = omp_get_max_threads();
  int thr_size = v_sources.size() / max_thr;
  int size_rest = v_sources.size() % max_thr;
  vector<int> matr_cols;
  for (int j = 0; j < max_thr; j++) {
    matr_cols.push_back(thr_size);
  }
  matr_cols[matr_cols.size() - 1] += size_rest;

#pragma omp parallel for ordered schedule(dynamic)
  for (int matr_id = 0; matr_id < max_thr; matr_id++) {
    MyGraph* const graph_thr = new MyGraph(*graph);
    int num_threads = omp_get_num_threads();
    ManyToMany<MyGraph, DijkstraManyToManyFW, DijkstraManyToManyBW,
               performBucketScans> mtm(graph_thr, earlyStopLevel);
    Matrix<EdgeWeight> matrix((NodeID)matr_cols[matr_id],
                              (NodeID)sources.Size());
    int offset = matr_id * thr_size;
    vector<NodeID>::const_iterator first = v_sources.begin() + offset;
    vector<NodeID>::const_iterator last =
        v_sources.begin() + offset + matr_cols[matr_id];
    vector<NodeID> newVec(first, last);

    mtm.computeMatrix(newVec, v_sources, matrix);

    int noOfRows = matrix.noOfRows();
    int noOfCols = matrix.noOfCols();

#pragma omp ordered
    {
      vector<string> names;
      for (int j = 0; j < noOfRows; j++) {
        rapidjson::Value result;
        result.SetArray();
        rapidjson::Document::AllocatorType& allocator = out_doc.GetAllocator();

        for (int k = 0; k < noOfCols; k++) {
          result.PushBack(matrix.value(j, k), allocator);
        }

        stringstream ss;
        ss << j + matr_id* thr_size;

        string str = ss.str();

        names.push_back(str);

        rapidjson::Value key;
        key.SetString(names[j].c_str(), names[j].length(),
                      out_doc.GetAllocator());
        out_doc.AddMember(key, result, allocator);
      }
    }
  }

  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  out_doc.Accept(writer);

  delete graph;

  return strbuf.GetString();
}
*/

const std::string calc_paths(const std::string& json_data,
                             const std::string& country,
                             const int speed_profile,
                             const std::string& dataDir) {
  rapidjson::Document d;
  LevelID earlyStopLevel = 10;

  const clock_t begin_time = clock();

  MyGraph* graph = loadGraph(country, speed_profile, dataDir);

  d.Parse<0>(json_data.c_str());
  // cout <<"Load and parse: "<<float( clock () - begin_time ) /  CLOCKS_PER_SEC
  // <<endl;
  rapidjson::Document out_doc;
  out_doc.SetObject();

  rapidjson::Value result;
  result.SetArray();
  rapidjson::Document::AllocatorType& allocator = out_doc.GetAllocator();
  DijkstraManyToManyFW _dFW(graph);
  for (rapidjson::SizeType i = 0; i < d.Size(); i++) {
    // cout <<"loop begins: "<<float( clock () - begin_time ) /  CLOCKS_PER_SEC
    // <<endl;

    const rapidjson::Value& c = d[i];
    NodeID source_id = mapNodeID(graph, (NodeID)c["source"].GetUint());
    NodeID target_id = mapNodeID(graph, (NodeID)c["target"].GetUint());

    _dFW.clear();
    EdgeWeight w = _dFW.bidirSearch(source_id, target_id);
    Path a;
    _dFW.pathTo(a, target_id, -1, true, true);
    EdgeID num_edges = a.noOfEdges();

    rapidjson::Value result_internal;
    result_internal.SetArray();
    rapidjson::Value out_doc_internal;
    out_doc_internal.SetObject();

    if (num_edges > 0) {
      for (EdgeID e = 0; e <= num_edges; e++) {
        result_internal.PushBack(a.node(e), out_doc.GetAllocator());
      }
    }

    rapidjson::Value plen(w);
    out_doc_internal.AddMember("length", plen, out_doc.GetAllocator());
    out_doc_internal.AddMember("nodes", result_internal,
                               out_doc.GetAllocator());
    result.PushBack(out_doc_internal, out_doc.GetAllocator());
    // cout <<"loop end: "<<float( clock () - begin_time ) /  CLOCKS_PER_SEC
    // <<"Number: "<<num_edges<<endl;
  }

  out_doc.AddMember("edges", result, allocator);
  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  out_doc.Accept(writer);

  delete graph;

  return strbuf.GetString();
}
<commit_msg>Better error handling when no country file is found.<commit_after>
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <omp.h>
using namespace std;

#pragma omp
#include "config.h"
#include "stats/utils.h"
#include "datastr/graph/graph.h"
#include "datastr/graph/SearchGraph.h"
#include "processing/DijkstraCH.h"

#include "manyToMany.h"

typedef datastr::graph::SearchGraph TransitGraph;
typedef datastr::graph::SearchGraph MyGraph;
typedef DijkstraCHManyToManyFW DijkstraManyToManyFW;
typedef DijkstraCHManyToManyBW DijkstraManyToManyBW;

/*
 * Performing the bucket scans is a crucial part of the many-to-many
 * computation.
 * It can be switched off to allow time measurements of the forward search
 * without accounting for the bucket scans.
 */
const bool performBucketScans = true;
const std::string PROFILEDIR = "/var/lib/spp/ch/";

const EdgeWeight Weight::MAX_VALUE;

Counter counter;

inline NodeID mapNodeID(const MyGraph* const g, const NodeID u) {
  // map the actual node ID to the node ID that is used internally by
  // highway-node routing
  return g->mapExtToIntNodeID(u);
}

MyGraph* loadGraph(const std::string& country, const int speed_profile,
                   const std::string& dataDir) {
  std::ostringstream filename;
  filename << dataDir << country << "-" << speed_profile << ".sgr";

  std::string path = filename.str();

  ifstream inGraph(path.c_str(), ios::binary);

  if (!inGraph) {
    throw std::invalid_argument("Input file " + filename.str() + " could not be read.");
  }

  MyGraph* graph = new MyGraph(inGraph);
  inGraph.close();
  return graph;
}

const std::string calc_dm(const std::string& json_data,
                          const std::string& country, const int speed_profile,
                          const std::string& dataDir) {
  rapidjson::Document d;
  LevelID earlyStopLevel = 10;
  MyGraph* graph;

  try {
    graph = loadGraph(country, speed_profile, dataDir);
  }
  catch (std::invalid_argument& e) {
    return "{}";
  }

  d.Parse<0>(json_data.c_str());

  const rapidjson::Value& sources = d["sources"];
  assert(sources.IsArray());
  vector<NodeID> v_sources;

  for (rapidjson::SizeType i = 0; i < sources.Size(); i++) {
    v_sources.push_back(mapNodeID(graph, (NodeID)sources[i].GetUint()));
  }

  ManyToMany<MyGraph, DijkstraManyToManyFW, DijkstraManyToManyBW,
             performBucketScans> mtm(graph, earlyStopLevel);
  Matrix<EdgeWeight> matrix((NodeID)sources.Size(), (NodeID)sources.Size());
  mtm.computeMatrix(v_sources, v_sources, matrix);

  int noOfRows = matrix.noOfRows();
  int noOfCols = matrix.noOfCols();

  rapidjson::Document out_doc;
  out_doc.SetObject();
  vector<string> names;

  for (int j = 0; j < noOfRows; j++) {
    rapidjson::Value result;
    result.SetArray();
    rapidjson::Document::AllocatorType& allocator = out_doc.GetAllocator();

    for (int k = 0; k < noOfCols; k++) {
      result.PushBack(matrix.value(j, k), allocator);
    }

    stringstream ss;
    ss << j;
    string str = ss.str();
    names.push_back(str);
    out_doc.AddMember(names[j].c_str(), result, out_doc.GetAllocator());
  }

  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  out_doc.Accept(writer);

  delete graph;

  return strbuf.GetString();
}

/*
const std::string calc_dm_par(const std::string& json_data,
                              const std::string& country,
                              const int speed_profile,
                              const std::string& dataDir) {
  std::cout << "parallel is enabled" << std::endl;
  rapidjson::Document d;
  LevelID earlyStopLevel = 10;

  std::stringstream filename;

  MyGraph* graph = loadGraph(country, speed_profile, dataDir);

  d.Parse<0>(json_data.c_str());

  const rapidjson::Value& sources = d["sources"];
  assert(sources.IsArray());
  vector<NodeID> v_sources;

  for (rapidjson::SizeType i = 0; i < sources.Size(); i++) {
    v_sources.push_back(mapNodeID(graph, (NodeID)sources[i].GetUint()));
  }
  rapidjson::Document out_doc;
  out_doc.SetObject();
  int max_thr = omp_get_max_threads();
  int thr_size = v_sources.size() / max_thr;
  int size_rest = v_sources.size() % max_thr;
  vector<int> matr_cols;
  for (int j = 0; j < max_thr; j++) {
    matr_cols.push_back(thr_size);
  }
  matr_cols[matr_cols.size() - 1] += size_rest;

#pragma omp parallel for ordered schedule(dynamic)
  for (int matr_id = 0; matr_id < max_thr; matr_id++) {
    MyGraph* const graph_thr = new MyGraph(*graph);
    int num_threads = omp_get_num_threads();
    ManyToMany<MyGraph, DijkstraManyToManyFW, DijkstraManyToManyBW,
               performBucketScans> mtm(graph_thr, earlyStopLevel);
    Matrix<EdgeWeight> matrix((NodeID)matr_cols[matr_id],
                              (NodeID)sources.Size());
    int offset = matr_id * thr_size;
    vector<NodeID>::const_iterator first = v_sources.begin() + offset;
    vector<NodeID>::const_iterator last =
        v_sources.begin() + offset + matr_cols[matr_id];
    vector<NodeID> newVec(first, last);

    mtm.computeMatrix(newVec, v_sources, matrix);

    int noOfRows = matrix.noOfRows();
    int noOfCols = matrix.noOfCols();

#pragma omp ordered
    {
      vector<string> names;
      for (int j = 0; j < noOfRows; j++) {
        rapidjson::Value result;
        result.SetArray();
        rapidjson::Document::AllocatorType& allocator = out_doc.GetAllocator();

        for (int k = 0; k < noOfCols; k++) {
          result.PushBack(matrix.value(j, k), allocator);
        }

        stringstream ss;
        ss << j + matr_id* thr_size;

        string str = ss.str();

        names.push_back(str);

        rapidjson::Value key;
        key.SetString(names[j].c_str(), names[j].length(),
                      out_doc.GetAllocator());
        out_doc.AddMember(key, result, allocator);
      }
    }
  }

  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  out_doc.Accept(writer);

  delete graph;

  return strbuf.GetString();
}
*/

const std::string calc_paths(const std::string& json_data,
                             const std::string& country,
                             const int speed_profile,
                             const std::string& dataDir) {
  rapidjson::Document d;
  LevelID earlyStopLevel = 10;

  const clock_t begin_time = clock();

  MyGraph* graph;

  try {
    graph = loadGraph(country, speed_profile, dataDir);
  }
  catch (std::invalid_argument& e) {
    return "{}";
  }

  d.Parse<0>(json_data.c_str());
  // cout <<"Load and parse: "<<float( clock () - begin_time ) /  CLOCKS_PER_SEC
  // <<endl;
  rapidjson::Document out_doc;
  out_doc.SetObject();

  rapidjson::Value result;
  result.SetArray();
  rapidjson::Document::AllocatorType& allocator = out_doc.GetAllocator();
  DijkstraManyToManyFW _dFW(graph);
  for (rapidjson::SizeType i = 0; i < d.Size(); i++) {
    // cout <<"loop begins: "<<float( clock () - begin_time ) /  CLOCKS_PER_SEC
    // <<endl;

    const rapidjson::Value& c = d[i];
    NodeID source_id = mapNodeID(graph, (NodeID)c["source"].GetUint());
    NodeID target_id = mapNodeID(graph, (NodeID)c["target"].GetUint());

    _dFW.clear();
    EdgeWeight w = _dFW.bidirSearch(source_id, target_id);
    Path a;
    _dFW.pathTo(a, target_id, -1, true, true);
    EdgeID num_edges = a.noOfEdges();

    rapidjson::Value result_internal;
    result_internal.SetArray();
    rapidjson::Value out_doc_internal;
    out_doc_internal.SetObject();

    if (num_edges > 0) {
      for (EdgeID e = 0; e <= num_edges; e++) {
        result_internal.PushBack(a.node(e), out_doc.GetAllocator());
      }
    }

    rapidjson::Value plen(w);
    out_doc_internal.AddMember("length", plen, out_doc.GetAllocator());
    out_doc_internal.AddMember("nodes", result_internal,
                               out_doc.GetAllocator());
    result.PushBack(out_doc_internal, out_doc.GetAllocator());
    // cout <<"loop end: "<<float( clock () - begin_time ) /  CLOCKS_PER_SEC
    // <<"Number: "<<num_edges<<endl;
  }

  out_doc.AddMember("edges", result, allocator);
  rapidjson::StringBuffer strbuf;
  rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
  out_doc.Accept(writer);

  delete graph;

  return strbuf.GetString();
}
<|endoftext|>


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

#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/test/test_server.h"

class ErrorPageTest : public UITest {
 protected:
  bool WaitForTitleMatching(const std::wstring& title) {
    for (int i = 0; i < 10; ++i) {
      if (GetActiveTabTitle() == title)
        return true;
      base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
    }
    EXPECT_EQ(title, GetActiveTabTitle());
    return false;
  }
};

TEST_F(ErrorPageTest, DNSError_Basic) {
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack1) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2AndForward FLAKY_DNSError_GoBack2AndForward
#else
#define MAYBE_DNSError_GoBack2AndForward DNSError_GoBack2AndForward
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("page404.html"))));

  EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
<commit_msg>Change bug reference for flaky test<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/test/test_server.h"

class ErrorPageTest : public UITest {
 protected:
  bool WaitForTitleMatching(const std::wstring& title) {
    for (int i = 0; i < 10; ++i) {
      if (GetActiveTabTitle() == title)
        return true;
      base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
    }
    EXPECT_EQ(title, GetActiveTabTitle());
    return false;
  }
};

TEST_F(ErrorPageTest, DNSError_Basic) {
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

TEST_F(ErrorPageTest, DNSError_GoBack1) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux, see http://crbug.com/79412
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.
  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

// Flaky on Linux, see http://crbug.com/79412
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2AndForward FLAKY_DNSError_GoBack2AndForward
#else
#define MAYBE_DNSError_GoBack2AndForward DNSError_GoBack2AndForward
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));

  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}

// Flaky on Linux, see http://crbug.com/79412
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
  // Test that a DNS error occuring in the main frame does not result in an
  // additional session history entry.

  GURL test_url(URLRequestFailedDnsJob::kTestUrl);

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title3.html"))));
  // The first navigation should fail, and the second one should be the error
  // page.
  NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));

  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoBack());
  // The first navigation should fail, and the second one should be the error
  // page.
  EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
  EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());

  EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}

TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
  // Test that a DNS error occuring in an iframe does not result in an
  // additional session history entry.

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("title2.html"))));
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));

  EXPECT_TRUE(GetActiveTab()->GoBack());
  EXPECT_TRUE(GetActiveTab()->GoForward());

  EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}

// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
                    FilePath(FILE_PATH_LITERAL("page404.html"))));

  EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <gmpxx.h>
#include <vector>
#include <string>
#include <rsa-attack-lib/rsa-attack-lib.hh>
using namespace std;

TEST(factorize, smallSemiPrime) {
  mpz_class small_n = 48443;
  vector<pair<mpz_class, mpz_class>> expected_outputs = {
      pair<mpz_class, mpz_class>(193, 251)};
  EXPECT_EQ(expected_outputs, rsatk::find_prime_factors(small_n));
}

TEST(factorize, bigSemiPrime) {
  mpz_class big_n = 8884963;
  vector<pair<mpz_class, mpz_class>> expected_outputs = {
      pair<mpz_class, mpz_class>(2677, 3319)};

  // output won't be the same
  EXPECT_EQ(expected_outputs, rsatk::find_prime_factors(big_n));
}

TEST(factorize, smallNormalNumber) {
  mpz_class norm_num = 108;
  //factors are (2, 54) , (4, 27) , (9, 12) , (3, 36) , (6, 18)
  //since none of these are prime, result should be empty
  EXPECT_TRUE(rsatk::find_prime_factors(norm_num).empty());
}

TEST(factorize, largerN) {
  mpz_class big_n = 239774199806447;

  vector<pair<mpz_class, mpz_class>> expected_outputs = {
      pair<mpz_class, mpz_class>(15484627, 15484661)};

  // output won't be the same
  EXPECT_EQ(expected_outputs, rsatk::find_prime_factors(big_n));
}

//test based from example in http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
TEST(ExtendedEuclidean, wikipediaExample){
  mpz_class a = 240;
  mpz_class b = 46;

  mpz_class expected_x = -9;
  mpz_class expected_y = 47;
  mpz_class expected_gcd = 2;

  vector<mpz_class> actual = rsatk::extended_euclidean(a,b);
  EXPECT_EQ(expected_x, actual[0]);
  EXPECT_EQ(expected_y, actual[1]);
  EXPECT_EQ(expected_gcd, actual[2]);
}

//test pulled from here: http://doctrina.org/How-RSA-Works-With-Examples.html
class EasyCrackingRSATest : public ::testing::Test {
protected:
  virtual void SetUp() {
    n = p * q;
  }

  mpz_class p = 11; //we get this from factorization
  mpz_class q = 13;
  mpz_class e = 7; //given(supposedly) in public key
  string m = "9";
  mpz_class n;
};

  TEST_F(EasyCrackingRSATest, calculateTotient){
    mpz_class expected_totient = 120;
    mpz_class actual_totient = rsatk::calculate_totient(p, q);
    EXPECT_EQ(expected_totient, actual_totient);
  }

  TEST_F(EasyCrackingRSATest, calculateD){
    mpz_class expected_d = 103;
    mpz_class totient = rsatk::calculate_totient(p, q);
    ASSERT_EQ(120, totient);
    mpz_class actual_d = rsatk::calculate_d(totient, e);
    EXPECT_EQ(expected_d, actual_d);
  }

  TEST_F(EasyCrackingRSATest, applyPrivateKey){
    string encrypted_message = "48";

    mpz_class totient = rsatk::calculate_totient(p, q);
    ASSERT_EQ(120, totient);
    mpz_class d = rsatk::calculate_d(totient, e);
    ASSERT_EQ(103, d);

    string decrypted_message = rsatk::decrypt_message(encrypted_message, n, d);

    EXPECT_EQ(m, decrypted_message);
  }

/*
  TEST(PublicKeyReading, findE){
  EXPECT_EQ(0,1); //dummy
}

 TEST(Primes, Generate){
 generate_n_primes(1000000);
 }
*/
<commit_msg>added and passed harder tests<commit_after>#include <gtest/gtest.h>
#include <gmpxx.h>
#include <vector>
#include <string>
#include <rsa-attack-lib/rsa-attack-lib.hh>
using namespace std;

TEST(factorize, smallSemiPrime) {
  mpz_class small_n = 48443;
  vector<pair<mpz_class, mpz_class>> expected_outputs = {
      pair<mpz_class, mpz_class>(193, 251)};
  EXPECT_EQ(expected_outputs, rsatk::find_prime_factors(small_n));
}

TEST(factorize, bigSemiPrime) {
  mpz_class big_n = 8884963;
  vector<pair<mpz_class, mpz_class>> expected_outputs = {
      pair<mpz_class, mpz_class>(2677, 3319)};

  // output won't be the same
  EXPECT_EQ(expected_outputs, rsatk::find_prime_factors(big_n));
}

TEST(factorize, smallNormalNumber) {
  mpz_class norm_num = 108;
  //factors are (2, 54) , (4, 27) , (9, 12) , (3, 36) , (6, 18)
  //since none of these are prime, result should be empty
  EXPECT_TRUE(rsatk::find_prime_factors(norm_num).empty());
}

TEST(factorize, largerN) {
  mpz_class big_n = 239774199806447;

  vector<pair<mpz_class, mpz_class>> expected_outputs = {
      pair<mpz_class, mpz_class>(15484627, 15484661)};

  // output won't be the same
  EXPECT_EQ(expected_outputs, rsatk::find_prime_factors(big_n));
}

//test based from example in http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
TEST(ExtendedEuclidean, wikipediaExample){
  mpz_class a = 240;
  mpz_class b = 46;

  mpz_class expected_x = -9;
  mpz_class expected_y = 47;
  mpz_class expected_gcd = 2;

  vector<mpz_class> actual = rsatk::extended_euclidean(a,b);
  EXPECT_EQ(expected_x, actual[0]);
  EXPECT_EQ(expected_y, actual[1]);
  EXPECT_EQ(expected_gcd, actual[2]);
}

//both of the ...CrackingRSATest fixtures pulled from here: http://doctrina.org/How-RSA-Works-With-Examples.html
class EasyCrackingRSATest : public ::testing::Test {
protected:
  virtual void SetUp() {
    n = p * q;
  }

  mpz_class p = 11; //we get this from factorization
  mpz_class q = 13;
  mpz_class e = 7; //given(supposedly) in public key
  string m = "9";
  mpz_class n;
};

TEST_F(EasyCrackingRSATest, calculateTotient){
  mpz_class expected_totient = 120;
  mpz_class actual_totient = rsatk::calculate_totient(p, q);
  EXPECT_EQ(expected_totient, actual_totient);
}

TEST_F(EasyCrackingRSATest, calculateD){
  mpz_class expected_d = 103;
  mpz_class totient = rsatk::calculate_totient(p, q);
  ASSERT_EQ(120, totient);
  mpz_class actual_d = rsatk::calculate_d(totient, e);
  EXPECT_EQ(expected_d, actual_d);
}

TEST_F(EasyCrackingRSATest, applyPrivateKey){
  string encrypted_message = "48";

  mpz_class totient = rsatk::calculate_totient(p, q);
  ASSERT_EQ(120, totient);
  mpz_class d = rsatk::calculate_d(totient, e);
  ASSERT_EQ(103, d);

  string decrypted_message = rsatk::decrypt_message(encrypted_message, n, d);

  EXPECT_EQ(m, decrypted_message);
}

class HarderCrackingRSATest : public ::testing::Test {
protected:
  virtual void SetUp() {
    //the reason for this nonstandard initialization is discussed http://stackoverflow.com/a/9844465
    p = "12131072439211271897323671531612440428472427633701410925634549312301964373042085619324197365322416866541017057361365214171711713797974299334871062829803541";
    q = "12027524255478748885956220793734512128733387803682075433653899983955179850988797899869146900809131611153346817050832096022160146366346391812470987105415233";
    n = p * q;
  }
  mpz_class p;
  mpz_class q;
  mpz_class e = 65537;
  string m = "attack at dawn";
  mpz_class n;
};

TEST_F(HarderCrackingRSATest, calculateTotient){
  mpz_class expected_totient;
  expected_totient = "145906768007583323230186939349070635292401872375357164399581871019873438799005358938369571402670149802121818086292467422828157022922076746906543401224889648313811232279966317301397777852365301547848273478871297222058587457152891606459269718119268971163555070802643999529549644116811947516513938184296683521280";
  mpz_class actual_totient = rsatk::calculate_totient(p, q);
  EXPECT_EQ(expected_totient, actual_totient);
}

TEST_F(HarderCrackingRSATest, calculateD){
  mpz_class expected_d;
  expected_d = "89489425009274444368228545921773093919669586065884257445497854456487674839629818390934941973262879616797970608917283679875499331574161113854088813275488110588247193077582527278437906504015680623423550067240042466665654232383502922215493623289472138866445818789127946123407807725702626644091036502372545139713";
  mpz_class totient = rsatk::calculate_totient(p, q);
  mpz_class actual_d = rsatk::calculate_d(totient, e);
  EXPECT_EQ(expected_d, actual_d);
}

TEST_F(HarderCrackingRSATest, applyPrivateKey){
  string encrypted_message = "attack at dawn";

  mpz_class totient = rsatk::calculate_totient(p, q);
  mpz_class d = rsatk::calculate_d(totient, e);

  string decrypted_message = rsatk::decrypt_message(encrypted_message, n, d);

  EXPECT_EQ(m, decrypted_message);
}
/*
  TEST(PublicKeyReading, findE){
  EXPECT_EQ(0,1); //dummy
  }

  TEST(Primes, Generate){
  generate_n_primes(1000000);
  }
*/
<|endoftext|>


<commit_before>#include "al_quat.hpp"

/*
	C-binding implementation:

	al::Quat<double> should be the same as struct al_quat in terms of memory layout.
*/
typedef al::Quat<double> Quatd;

#define TO_QUAT(q) ((Quatd)(q))
#define TO_QUAT_PTR(q) ((Quatd *)(q))

#define FROM_QUAT(q) ((al_quat)(q))
#define FROM_QUAT_PTR(q) ((al_quat *)(q))

al_quat * al_quat_create(double w, double x, double y, double z) {
	Quatd * qd = new Quatd(w, x, y, z);
	return FROM_QUAT_PTR(qd);
}

void al_quat_free(al_quat ** q) {
	if (q && *q) {
		delete (TO_QUAT_PTR(*q));
		*q = 0;
	}
}

void al_quat_normalize(al_quat * q) {
	(TO_QUAT_PTR(q))->normalize();
}

void al_quat_reset(al_quat * q) {
	(TO_QUAT_PTR(q))->reset();
}

void al_quat_conjugate(al_quat * q, al_quat * result) {
	*(TO_QUAT_PTR(result)) = (TO_QUAT_PTR(q))->conjugate();
}

void al_quat_from_quat(al_quat * dst, double w, double x, double y, double z) {
	(TO_QUAT_PTR(dst))->fromQuat(w, x, y, z);
}

void al_quat_from_axisangle(al_quat * dst, double theta, double x, double y, double z) {
	(TO_QUAT_PTR(dst))->fromAxisAngle(theta, x, y, z);
}

void al_quat_from_euler(al_quat * dst, double az, double el, double ba) {
	(TO_QUAT_PTR(dst))->fromEuler(az, el, ba);
}

void al_quat_to_vector_x(al_quat * q, double * x, double * y, double * z) {
	(TO_QUAT_PTR(q))->toVectorX(x, y, z);
}

void al_quat_to_vector_y(al_quat * q, double * x, double * y, double * z) {
	(TO_QUAT_PTR(q))->toVectorY(x, y, z);
}

void al_quat_to_vector_z(al_quat * q, double * x, double * y, double * z) {
	(TO_QUAT_PTR(q))->toVectorZ(x, y, z);
}

void al_quat_to_matrix(al_quat * q, double * mat) {
	(TO_QUAT_PTR(q))->toMatrix(mat);
}

void al_quat_rotate_vector(al_quat * q, double * src, double * dst) {
	(TO_QUAT_PTR(q))->rotateVector(src, dst);
}

void al_quat_rotate_vector_transposed(al_quat * q, double * src, double * dst) {
	(TO_QUAT_PTR(q))->rotateVectorTransposed(src, dst);
}
<commit_msg>Changes to reflect changes in al_Quat.hpp<commit_after>#include "al_quat.hpp"

/*
	C-binding implementation:

	al::Quat<double> should be the same as struct al_quat in terms of memory layout.
*/
typedef al::Quat<double> Quatd;

#define TO_QUAT(q) ((Quatd)(q))
#define TO_QUAT_PTR(q) ((Quatd *)(q))

#define FROM_QUAT(q) ((al_quat)(q))
#define FROM_QUAT_PTR(q) ((al_quat *)(q))

al_quat * al_quat_create(double w, double x, double y, double z) {
	Quatd * qd = new Quatd(w, x, y, z);
	return FROM_QUAT_PTR(qd);
}

void al_quat_free(al_quat ** q) {
	if (q && *q) {
		delete (TO_QUAT_PTR(*q));
		*q = 0;
	}
}

void al_quat_normalize(al_quat * q) {
	(TO_QUAT_PTR(q))->normalize();
}

void al_quat_reset(al_quat * q) {
	(TO_QUAT_PTR(q))->identity();
}

void al_quat_conjugate(al_quat * q, al_quat * result) {
	*(TO_QUAT_PTR(result)) = (TO_QUAT_PTR(q))->conjugate();
}

void al_quat_from_quat(al_quat * dst, double w, double x, double y, double z) {
	(TO_QUAT_PTR(dst))->set(w, x, y, z);
}

void al_quat_from_axisangle(al_quat * dst, double theta, double x, double y, double z) {
	(TO_QUAT_PTR(dst))->fromAxisAngle(theta, x, y, z);
}

void al_quat_from_euler(al_quat * dst, double az, double el, double ba) {
	(TO_QUAT_PTR(dst))->fromEuler(az, el, ba);
}

void al_quat_to_vector_x(al_quat * q, double * x, double * y, double * z) {
	(TO_QUAT_PTR(q))->toVectorX(x, y, z);
}

void al_quat_to_vector_y(al_quat * q, double * x, double * y, double * z) {
	(TO_QUAT_PTR(q))->toVectorY(x, y, z);
}

void al_quat_to_vector_z(al_quat * q, double * x, double * y, double * z) {
	(TO_QUAT_PTR(q))->toVectorZ(x, y, z);
}

void al_quat_to_matrix(al_quat * q, double * mat) {
	(TO_QUAT_PTR(q))->toMatrix(mat);
}

void al_quat_rotate_vector(al_quat * q, double * src, double * dst) {
	(TO_QUAT_PTR(q))->rotateVector(src, dst);
}

void al_quat_rotate_vector_transposed(al_quat * q, double * src, double * dst) {
	(TO_QUAT_PTR(q))->rotateVectorTransposed(src, dst);
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CommonDialogsDemo.cpp
    created:    Sun Oct 23 2011
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "SampleBase.h"
#include "CEGUI/CEGUI.h"

#include "CEGUI/CommonDialogs/ColourPicker/ColourPicker.h"

//----------------------------------------------------------------------------//
class CommonDialogsDemo : public Sample
{
public:
    virtual bool initialise(CEGUI::GUIContext* guiContext);
    void deinitialise(void) {}
};

//----------------------------------------------------------------------------//
bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext)
{
    using namespace CEGUI;

    d_usedFiles = CEGUI::String(__FILE__);

    // load font and setup default if not loaded via scheme
    Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font");
    // Set default font for the gui context
    guiContext->setDefaultFont(&defaultFont);

    // load resources and set up system defaults
    SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme");
    SchemeManager::getSingleton().createFromFile("VanillaCommonDialogs.scheme");
    guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow");

    // set up the root window / gui sheet
    WindowManager& winMgr = WindowManager::getSingleton();
    Window* root = winMgr.createWindow("DefaultWindow", "Root");
    guiContext->setRootWindow(root);

    // create container window for the demo
    FrameWindow* wnd = static_cast<FrameWindow*>(
        winMgr.createWindow("Vanilla/FrameWindow"));
    root->addChild(wnd);

    wnd->setAlwaysOnTop(true);

    wnd->setPosition(UVector2(cegui_reldim(0.05f), cegui_reldim( 0.25f)));
    wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f)));
    wnd->setText("Common Dialogs Demo - Main Window");
    wnd->setCloseButtonEnabled(false);

    // Add a colour picker & label
    Window* colourPickerLabel = winMgr.createWindow("Vanilla/Label");
    wnd->addChild(colourPickerLabel);
    colourPickerLabel->setSize(USize(UDim(0, 270), UDim(0, 30)));
    colourPickerLabel->setText("Open the colour picker by clicking on the respective box:");

    CEGUI::ColourPicker* colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 40)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(1.f, 0.f, 0.f, 0.5f));

    colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 80)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(0.f, 1.f, 1.f, 0.f));

    colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 120)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(0.4f, 0.4f, 0.f, 1.f));

    colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 160)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(1.f, 0.2f, 0.5f, 0.8f));

    return true;
}

//----------------------------------------------------------------------------//

/*************************************************************************
    Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
    static CommonDialogsDemo sample;
    return sample;
}
<commit_msg>MOD: 0.f and 1.f to 0.0f and 1.0f<commit_after>/***********************************************************************
    filename:   CommonDialogsDemo.cpp
    created:    Sun Oct 23 2011
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "SampleBase.h"
#include "CEGUI/CEGUI.h"

#include "CEGUI/CommonDialogs/ColourPicker/ColourPicker.h"

//----------------------------------------------------------------------------//
class CommonDialogsDemo : public Sample
{
public:
    virtual bool initialise(CEGUI::GUIContext* guiContext);
    void deinitialise(void) {}
};

//----------------------------------------------------------------------------//
bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext)
{
    using namespace CEGUI;

    d_usedFiles = CEGUI::String(__FILE__);

    // load font and setup default if not loaded via scheme
    Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font");
    // Set default font for the gui context
    guiContext->setDefaultFont(&defaultFont);

    // load resources and set up system defaults
    SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme");
    SchemeManager::getSingleton().createFromFile("VanillaCommonDialogs.scheme");
    guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow");

    // set up the root window / gui sheet
    WindowManager& winMgr = WindowManager::getSingleton();
    Window* root = winMgr.createWindow("DefaultWindow", "Root");
    guiContext->setRootWindow(root);

    // create container window for the demo
    FrameWindow* wnd = static_cast<FrameWindow*>(
        winMgr.createWindow("Vanilla/FrameWindow"));
    root->addChild(wnd);

    wnd->setAlwaysOnTop(true);

    wnd->setPosition(UVector2(cegui_reldim(0.05f), cegui_reldim( 0.25f)));
    wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f)));
    wnd->setText("Common Dialogs Demo - Main Window");
    wnd->setCloseButtonEnabled(false);

    // Add a colour picker & label
    Window* colourPickerLabel = winMgr.createWindow("Vanilla/Label");
    wnd->addChild(colourPickerLabel);
    colourPickerLabel->setSize(USize(UDim(0, 270), UDim(0, 30)));
    colourPickerLabel->setText("Open the colour picker by clicking on the respective box:");

    CEGUI::ColourPicker* colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 40)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(1.0f, 0.0f, 0.0f, 0.5f));

    colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 80)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(0.0f, 1.0f, 1.0f, 0.0f));

    colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 120)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(0.4f, 0.4f, 0.0f, 1.0f));

    colourPicker = static_cast<CEGUI::ColourPicker*>(winMgr.createWindow("Vanilla/ColourPicker"));
    wnd->addChild(colourPicker);
    colourPicker->setPosition(UVector2(UDim(0, 20), UDim(0, 160)));
    colourPicker->setSize(USize(UDim(0, 100), UDim(0, 30)));
    colourPicker->setColour(CEGUI::Colour(1.0f, 0.2f, 0.5f, 0.8f));

    return true;
}

//----------------------------------------------------------------------------//

/*************************************************************************
    Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
    static CommonDialogsDemo sample;
    return sample;
}
<|endoftext|>


<commit_before><commit_msg>Revert "It looks like the unit tests instantiate the TaskManagerView..."<commit_after><|endoftext|>


<commit_before>#include "unit_test.h"
#include <cachelot/memalloc.h>

namespace {

using namespace cachelot;

static constexpr size_t MEMSIZE = 1024 * 1024 * 4; // 4Mb
static constexpr size_t NUM_ALLOC = 100000;
static constexpr size_t NUM_REPEAT = 50;
static constexpr size_t MIN_ALLOC_SIZE = 4;
static constexpr size_t MAX_ALLOC_SIZE = 1024 * 1024;

BOOST_AUTO_TEST_SUITE(test_memalloc)

BOOST_AUTO_TEST_CASE(test_block_list) {
    const size_t blocks_mem_size = (memalloc::block::min_size + memalloc::block::meta_size) * 5;
    std::unique_ptr<uint8[]> blocks_layout(new uint8[blocks_mem_size]);
    uint8 * layout_ptr = blocks_layout.get();
    memalloc::block * left_border = new (layout_ptr) memalloc::block();
    layout_ptr += left_border->size_with_meta();

    memalloc::block * b1 = new (layout_ptr) memalloc::block(memalloc::block::min_size, left_border);
    layout_ptr += b1->size_with_meta();
    memalloc::block * b2 = new (layout_ptr) memalloc::block(memalloc::block::min_size, b1);
    layout_ptr += b2->size_with_meta();
    memalloc::block * b3 = new (layout_ptr) memalloc::block(memalloc::block::min_size, b2);
    layout_ptr += b3->size_with_meta();

    memalloc::block * right_border = new (layout_ptr) memalloc::block(0, b3);
    memalloc::block::checkout(left_border);
    memalloc::block::checkout(right_border);

    memalloc::block_list the_list;
    BOOST_CHECK(the_list.empty());
    // single item basic operations
    the_list.push_front(b1);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b1);
    BOOST_CHECK_EQUAL(the_list.back(), b1);
    BOOST_CHECK(the_list.is_head(b1));
    BOOST_CHECK(the_list.is_tail(b1));
    BOOST_CHECK_EQUAL(the_list.pop_back(), b1);
    BOOST_CHECK(the_list.empty());
    the_list.push_back(b1);
    BOOST_CHECK_EQUAL(the_list.back(), b1);
    BOOST_CHECK_EQUAL(the_list.front(), b1);
    BOOST_CHECK(the_list.is_head(b1));
    BOOST_CHECK(the_list.is_tail(b1));
    BOOST_CHECK_EQUAL(the_list.pop_front(), b1);
    BOOST_CHECK(the_list.empty());

    // multiple item operations
    the_list.push_front(b1);
    the_list.push_front(b2);
    the_list.push_back(b3);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b2);
    BOOST_CHECK_EQUAL(the_list.back(), b3);
    BOOST_CHECK(the_list.is_head(b2));
    BOOST_CHECK(the_list.is_tail(b3));
    // remove one item
    memalloc::block_list::unlink(b1);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b2);
    BOOST_CHECK_EQUAL(the_list.back(), b3);
    BOOST_CHECK(the_list.is_head(b2));
    BOOST_CHECK(the_list.is_tail(b3));
    // remove second element
    BOOST_CHECK_EQUAL(the_list.pop_front(), b2);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b3);
    BOOST_CHECK_EQUAL(the_list.back(), b3);
    BOOST_CHECK(the_list.is_head(b3));
    BOOST_CHECK(the_list.is_tail(b3));
    // remove last element
    memalloc::block_list::unlink(b3);
    BOOST_CHECK(the_list.empty());
}

// return `true` with probability of given `persents`
inline bool probably(unsigned persents) noexcept {
    debug_assert(persents <= 100);
    random_int<unsigned> chance(1, 100);
    return chance() > (100u - persents);
}

template <class Container>
typename Container::iterator random_choise(Container & c) noexcept {
    random_int<> random_offset(0, c.size() - 1);
    return c.begin() + random_offset();
}

// allocate and free blocks of a random size
// in case of the internal inconsistency, memalloc will trigger internal failure calling debug_assert
//
BOOST_AUTO_TEST_CASE(memalloc_stress_test) {
    // setup
    std::unique_ptr<char[]> _g_memory(new char[MEMSIZE] );
    memalloc allocator(_g_memory.get(), MEMSIZE);
    random_int<size_t> random_size(MIN_ALLOC_SIZE, MAX_ALLOC_SIZE);
    std::vector<void * > allocations;
    allocations.reserve(NUM_ALLOC);

    // run test NUM_REPEAT times
    for (size_t repeat_no = 0; repeat_no < NUM_REPEAT; ++repeat_no) {

        // random allocations / deallocations
        for (size_t allocation_no = 0; allocation_no < NUM_ALLOC; ++allocation_no) {
            // try to allocate new element
            // if we need to evict existing elements to free space, remove it from the allocations list
            void * ptr = allocator.alloc_or_evict(random_size(), true,
                [&allocations](void * mem) {
                    for (size_t i = 0; i < allocations.size(); ++i) {
                        if (allocations[i] == mem) {
                            allocations[i] = allocations.back();
                            allocations.pop_back();
                            return;
                        }
                    }
                    debug_assert(false && "unknown pointer");
                });
            if (ptr != nullptr) {
                allocations.push_back(ptr);
            }

            // free one of previously allocated blocks with 40% probability
            if (not allocations.empty() && probably(40)) {
                auto prev_alloc = random_choise(allocations);
                BOOST_CHECK(*prev_alloc != nullptr);
                allocator.free(*prev_alloc);
                // remove pointer from the vector
                *prev_alloc = allocations.back();
                allocations.pop_back();
            }

            // reallocate one of previously allocated blocks with 60% probability
            if (not allocations.empty() && probably(60)) {
                auto prev_alloc = random_choise(allocations);
                allocator.realloc_inplace(*prev_alloc, random_size());
            }
        }
        // free all previously allocated memory
        while (not allocations.empty()) {
            void * ptr = allocations.back();
            allocator.free(ptr);
            allocations.pop_back();
        }
        // start over again
    }
}

BOOST_AUTO_TEST_SUITE_END()

} // anonymouse namespace

<commit_msg>memalloc unit tests removed from the ASAN build<commit_after>#include "unit_test.h"
#include <cachelot/memalloc.h>

namespace {

using namespace cachelot;

static constexpr size_t MEMSIZE = 1024 * 1024 * 4; // 4Mb
static constexpr size_t NUM_ALLOC = 100000;
static constexpr size_t NUM_REPEAT = 50;
static constexpr size_t MIN_ALLOC_SIZE = 4;
static constexpr size_t MAX_ALLOC_SIZE = 1024 * 1024;

// there is no memalloc in the AddressSanitizer build
#ifndef ADDRESS_SANITIZER

BOOST_AUTO_TEST_SUITE(test_memalloc)

BOOST_AUTO_TEST_CASE(test_block_list) {
    const size_t blocks_mem_size = (memalloc::block::min_size + memalloc::block::meta_size) * 5;
    std::unique_ptr<uint8[]> blocks_layout(new uint8[blocks_mem_size]);
    uint8 * layout_ptr = blocks_layout.get();
    memalloc::block * left_border = new (layout_ptr) memalloc::block();
    layout_ptr += left_border->size_with_meta();

    memalloc::block * b1 = new (layout_ptr) memalloc::block(memalloc::block::min_size, left_border);
    layout_ptr += b1->size_with_meta();
    memalloc::block * b2 = new (layout_ptr) memalloc::block(memalloc::block::min_size, b1);
    layout_ptr += b2->size_with_meta();
    memalloc::block * b3 = new (layout_ptr) memalloc::block(memalloc::block::min_size, b2);
    layout_ptr += b3->size_with_meta();

    memalloc::block * right_border = new (layout_ptr) memalloc::block(0, b3);
    memalloc::block::checkout(left_border);
    memalloc::block::checkout(right_border);

    memalloc::block_list the_list;
    BOOST_CHECK(the_list.empty());
    // single item basic operations
    the_list.push_front(b1);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b1);
    BOOST_CHECK_EQUAL(the_list.back(), b1);
    BOOST_CHECK(the_list.is_head(b1));
    BOOST_CHECK(the_list.is_tail(b1));
    BOOST_CHECK_EQUAL(the_list.pop_back(), b1);
    BOOST_CHECK(the_list.empty());
    the_list.push_back(b1);
    BOOST_CHECK_EQUAL(the_list.back(), b1);
    BOOST_CHECK_EQUAL(the_list.front(), b1);
    BOOST_CHECK(the_list.is_head(b1));
    BOOST_CHECK(the_list.is_tail(b1));
    BOOST_CHECK_EQUAL(the_list.pop_front(), b1);
    BOOST_CHECK(the_list.empty());

    // multiple item operations
    the_list.push_front(b1);
    the_list.push_front(b2);
    the_list.push_back(b3);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b2);
    BOOST_CHECK_EQUAL(the_list.back(), b3);
    BOOST_CHECK(the_list.is_head(b2));
    BOOST_CHECK(the_list.is_tail(b3));
    // remove one item
    memalloc::block_list::unlink(b1);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b2);
    BOOST_CHECK_EQUAL(the_list.back(), b3);
    BOOST_CHECK(the_list.is_head(b2));
    BOOST_CHECK(the_list.is_tail(b3));
    // remove second element
    BOOST_CHECK_EQUAL(the_list.pop_front(), b2);
    BOOST_CHECK(not the_list.empty());
    BOOST_CHECK_EQUAL(the_list.front(), b3);
    BOOST_CHECK_EQUAL(the_list.back(), b3);
    BOOST_CHECK(the_list.is_head(b3));
    BOOST_CHECK(the_list.is_tail(b3));
    // remove last element
    memalloc::block_list::unlink(b3);
    BOOST_CHECK(the_list.empty());
}

// return `true` with probability of given `persents`
inline bool probably(unsigned persents) noexcept {
    debug_assert(persents <= 100);
    random_int<unsigned> chance(1, 100);
    return chance() > (100u - persents);
}

template <class Container>
typename Container::iterator random_choise(Container & c) noexcept {
    random_int<> random_offset(0, c.size() - 1);
    return c.begin() + random_offset();
}

// allocate and free blocks of a random size
// in case of the internal inconsistency, memalloc will trigger internal failure calling debug_assert
//
BOOST_AUTO_TEST_CASE(memalloc_stress_test) {
    // setup
    std::unique_ptr<char[]> _g_memory(new char[MEMSIZE] );
    memalloc allocator(_g_memory.get(), MEMSIZE);
    random_int<size_t> random_size(MIN_ALLOC_SIZE, MAX_ALLOC_SIZE);
    std::vector<void * > allocations;
    allocations.reserve(NUM_ALLOC);

    // run test NUM_REPEAT times
    for (size_t repeat_no = 0; repeat_no < NUM_REPEAT; ++repeat_no) {

        // random allocations / deallocations
        for (size_t allocation_no = 0; allocation_no < NUM_ALLOC; ++allocation_no) {
            // try to allocate new element
            // if we need to evict existing elements to free space, remove it from the allocations list
            void * ptr = allocator.alloc_or_evict(random_size(), true,
                [&allocations](void * mem) {
                    for (size_t i = 0; i < allocations.size(); ++i) {
                        if (allocations[i] == mem) {
                            allocations[i] = allocations.back();
                            allocations.pop_back();
                            return;
                        }
                    }
                    debug_assert(false && "unknown pointer");
                });
            if (ptr != nullptr) {
                allocations.push_back(ptr);
            }

            // free one of previously allocated blocks with 40% probability
            if (not allocations.empty() && probably(40)) {
                auto prev_alloc = random_choise(allocations);
                BOOST_CHECK(*prev_alloc != nullptr);
                allocator.free(*prev_alloc);
                // remove pointer from the vector
                *prev_alloc = allocations.back();
                allocations.pop_back();
            }

            // reallocate one of previously allocated blocks with 60% probability
            if (not allocations.empty() && probably(60)) {
                auto prev_alloc = random_choise(allocations);
                allocator.realloc_inplace(*prev_alloc, random_size());
            }
        }
        // free all previously allocated memory
        while (not allocations.empty()) {
            void * ptr = allocations.back();
            allocator.free(ptr);
            allocations.pop_back();
        }
        // start over again
    }
}

BOOST_AUTO_TEST_SUITE_END()

#endif // ifndef ADDRESS_SANITIZER

} // anonymouse namespace

<|endoftext|>


<commit_before>#include <cmath>
#include namespace "miniwin.h"
using namespace miniwin;
using namespace std;

//Curve Level 0 -
//Curve Level 1 -^-

struct Punto
{
	float x,  y;
};

//
Punto rotar(const Punto& p, const Punto& cen, float da) {
	float dx = p.x - cen.x, dy = p.y - cen.y;
	float r = sqrt(dx*dx + dy*dy);
	float a = atan2(dy, dx);
	a += da;
	Punto q = { cen.x + r * cos(a + da), cen.y + r * sin(a) };
	return q;
}

void intermedio(const Punto& a, const Punto& b, float t) {
	Punto p = { a.x * (1-t) + b.x * t, a.y * (1-t) + b.y };
}

void Vonkoch(const Punto& p0, const Punto& p4, int nivel) {
	Punto p[5] = { p0, p0, p0, p0, p4};
	p[1] = intermedio(p[0], p[4], 1.0/3.0);
	p[3] = intermedio(p[0], p[4], 2.0/3.0);
	p[2] = rotar(p[3], p[1]. M_PI / 3.0);
}

<commit_msg>the method main is added<commit_after>#include <cmath>
#include namespace "miniwin.h"
using namespace miniwin;
using namespace std;

//Curve Level 0 -
//Curve Level 1 -^-

struct Punto
{
	float x,  y;
};

//
Punto rotar(const Punto& p, const Punto& cen, float da) {
	float dx = p.x - cen.x, dy = p.y - cen.y;
	float r = sqrt(dx*dx + dy*dy);
	float a = atan2(dy, dx);
	a -= da;
	Punto q = { cen.x + r * cos(a + da), cen.y + r * sin(a) };
	return q;
}

Punto intermedio(const Punto& a, const Punto& b, float t) {
	Punto p = { a.x * (1-t) + b.x * t, a.y * (1-t) + b.y * t};
}

void Vonkoch(const Punto& p0, const Punto& p4, int nivel) {
	Punto p[5] = { p0, p0, p0, p0, p4};
	p[1] = intermedio(p[0], p[4], 1.0/3.0);
	p[3] = intermedio(p[0], p[4], 2.0/3.0);
	p[2] = rotar(p[3], p[1]. M_PI / 3.0);
	for (int i = 0; i < 4; ++i)
	{
		linea(p[i].x, p[i].y, p[i+1].x, p[i+1].y);
	}
}

int main()
{
	vredimensiona(1260,440);
	Punto p0 = { 1240, 420}, p4 = { 1220. 420 };
	Vonkoch(p0, p4, 1);
	refresca();
	return 0;
}<|endoftext|>


<commit_before>#include "internal.hh"

using namespace std;

DWARFPP_BEGIN_NAMESPACE

//////////////////////////////////////////////////////////////////
// class dwarf
//

struct dwarf::impl
{
        impl(const std::shared_ptr<loader> &l)
                : l(l) { }

        std::shared_ptr<loader> l;

        std::shared_ptr
 sec_info;
        std::shared_ptr
 sec_abbrev;

        std::vector<compilation_unit> compilation_units;

        std::shared_ptr
 get_section(section_type type)
        {
                if (type == section_type::info)
                        return sec_info;
                if (type == section_type::abbrev)
                        return sec_abbrev;

                auto it = sections.find(type);
                if (it != sections.end())
                        return it->second;

                size_t size;
                const void *data = l->load(type, &size);
                if (!data)
                        throw format_error(std::string(elf::section_type_to_name(type)) + " section missing");
                sections[type] = std::make_shared
(section_type::str, data, size);
                return sections[type];
        }

private:
        std::map<section_type, std::shared_ptr
 > sections;
};

dwarf::dwarf(const std::shared_ptr<loader> &l)
        : m(make_shared<impl>(l))
{
        const void *data;
        size_t size;

        // Get required sections
        data = l->load(section_type::info, &size);
        if (!data)
                throw format_error("required .debug_info section missing");
        m->sec_info = make_shared
(section_type::info, data, size);

        data = l->load(section_type::abbrev, &size);
        if (!data)
                throw format_error("required .debug_abbrev section missing");
        m->sec_abbrev = make_shared
(section_type::abbrev, data, size);

        // Get compilation units.  Everything derives from these, so
        // there's no point in doing it lazily.
        cursor infocur(m->sec_info);
        while (!infocur.end()) {
                // XXX Circular reference
                m->compilation_units.emplace_back(
                        *this, infocur.get_section_offset());
                infocur.subsection();
        }
}

dwarf::~dwarf()
{
}

const std::vector<compilation_unit> &
dwarf::compilation_units() const
{
        static std::vector<compilation_unit> empty;
        if (!m)
                return empty;
        return m->compilation_units;
}

std::shared_ptr

dwarf::get_section(section_type type) const
{
        // XXX Fold this in once there are no more direct calls to the
        // impl
        return m->get_section(type);
}

//////////////////////////////////////////////////////////////////
// class compilation_unit
//

compilation_unit::compilation_unit(shared_ptr<impl> m)
        : m(m)
{
}

compilation_unit::compilation_unit(const dwarf &file, section_offset offset)
{
        uhalf version;
        // .debug_abbrev-relative offset of this unit's abbrevs
        section_offset debug_abbrev_offset;
        ubyte address_size;

        // Read the CU header (DWARF4 section 7.5.1.1)
        cursor cur(file.get_section(section_type::info), offset);
        std::shared_ptr
 subsec = cur.subsection();
        cursor sub(subsec);
        sub.skip_initial_length();
        version = sub.fixed<uhalf>();
        if (version < 2 || version > 4)
                throw format_error("unknown info unit version " + std::to_string(version));
        debug_abbrev_offset = sub.offset();
        address_size = sub.fixed<ubyte>();
        subsec->addr_size = address_size;

        m = make_shared<impl>(file, offset, subsec, debug_abbrev_offset,
                              sub.get_section_offset());
}

section_offset
compilation_unit::get_section_offset() const
{
        return m->offset;
}

const die&
compilation_unit::root() const
{
        if (!m->root.valid()) {
                m->force_abbrevs();
                m->root = die(m);
                m->root.read(m->root_offset);
        }
        return m->root;
}

void
compilation_unit::impl::force_abbrevs()
{
        // XXX Compilation units can share abbrevs.  Parse each table
        // at most once.
        if (have_abbrevs)
                return;

        // Section 7.5.3
        cursor c(file.get_section(section_type::abbrev),
                 debug_abbrev_offset);
        abbrev_entry entry;
        abbrev_code highest = 0;
        while (entry.read(&c)) {
                abbrevs_map[entry.code] = entry;
                if (entry.code > highest)
                        highest = entry.code;
        }

        // Typically, abbrev codes are assigned linearly, so it's more
        // space efficient and time efficient to store the table in a
        // vector.  Convert to a vector if it's dense enough, by some
        // rough estimate of "enough".
        if (highest * 10 < abbrevs_map.size() * 15) {
                // Move the map into the vector
                abbrevs_vec.resize(highest + 1);
                for (auto &entry : abbrevs_map)
                        abbrevs_vec[entry.first] = move(entry.second);
                abbrevs_map.clear();
        }

        have_abbrevs = true;
}

const abbrev_entry &
compilation_unit::impl::get_abbrev(abbrev_code acode)
{
        if (!abbrevs_vec.empty()) {
                if (acode >= abbrevs_vec.size())
                        goto unknown;
                const abbrev_entry &entry = abbrevs_vec[acode];
                if (entry.code == 0)
                        goto unknown;
                return entry;
        } else {
                auto it = abbrevs_map.find(acode);
                if (it == abbrevs_map.end())
                        goto unknown;
                return it->second;
        }

unknown:
        throw format_error("unknown abbrev code 0x" + to_hex(acode));
}

DWARFPP_END_NAMESPACE
<commit_msg>Move get_section implementation from dwarf::impl to dwarf<commit_after>#include "internal.hh"

using namespace std;

DWARFPP_BEGIN_NAMESPACE

//////////////////////////////////////////////////////////////////
// class dwarf
//

struct dwarf::impl
{
        impl(const std::shared_ptr<loader> &l)
                : l(l) { }

        std::shared_ptr<loader> l;

        std::shared_ptr
 sec_info;
        std::shared_ptr
 sec_abbrev;

        std::vector<compilation_unit> compilation_units;

        std::map<section_type, std::shared_ptr
 > sections;
};

dwarf::dwarf(const std::shared_ptr<loader> &l)
        : m(make_shared<impl>(l))
{
        const void *data;
        size_t size;

        // Get required sections
        data = l->load(section_type::info, &size);
        if (!data)
                throw format_error("required .debug_info section missing");
        m->sec_info = make_shared
(section_type::info, data, size);

        data = l->load(section_type::abbrev, &size);
        if (!data)
                throw format_error("required .debug_abbrev section missing");
        m->sec_abbrev = make_shared
(section_type::abbrev, data, size);

        // Get compilation units.  Everything derives from these, so
        // there's no point in doing it lazily.
        cursor infocur(m->sec_info);
        while (!infocur.end()) {
                // XXX Circular reference
                m->compilation_units.emplace_back(
                        *this, infocur.get_section_offset());
                infocur.subsection();
        }
}

dwarf::~dwarf()
{
}

const std::vector<compilation_unit> &
dwarf::compilation_units() const
{
        static std::vector<compilation_unit> empty;
        if (!m)
                return empty;
        return m->compilation_units;
}

std::shared_ptr

dwarf::get_section(section_type type) const
{
        if (type == section_type::info)
                return m->sec_info;
        if (type == section_type::abbrev)
                return m->sec_abbrev;

        auto it = m->sections.find(type);
        if (it != m->sections.end())
                return it->second;

        size_t size;
        const void *data = m->l->load(type, &size);
        if (!data)
                throw format_error(std::string(elf::section_type_to_name(type))
                                   + " section missing");
        m->sections[type] = std::make_shared
(section_type::str, data, size);
        return m->sections[type];
}

//////////////////////////////////////////////////////////////////
// class compilation_unit
//

compilation_unit::compilation_unit(shared_ptr<impl> m)
        : m(m)
{
}

compilation_unit::compilation_unit(const dwarf &file, section_offset offset)
{
        uhalf version;
        // .debug_abbrev-relative offset of this unit's abbrevs
        section_offset debug_abbrev_offset;
        ubyte address_size;

        // Read the CU header (DWARF4 section 7.5.1.1)
        cursor cur(file.get_section(section_type::info), offset);
        std::shared_ptr
 subsec = cur.subsection();
        cursor sub(subsec);
        sub.skip_initial_length();
        version = sub.fixed<uhalf>();
        if (version < 2 || version > 4)
                throw format_error("unknown info unit version " + std::to_string(version));
        debug_abbrev_offset = sub.offset();
        address_size = sub.fixed<ubyte>();
        subsec->addr_size = address_size;

        m = make_shared<impl>(file, offset, subsec, debug_abbrev_offset,
                              sub.get_section_offset());
}

section_offset
compilation_unit::get_section_offset() const
{
        return m->offset;
}

const die&
compilation_unit::root() const
{
        if (!m->root.valid()) {
                m->force_abbrevs();
                m->root = die(m);
                m->root.read(m->root_offset);
        }
        return m->root;
}

void
compilation_unit::impl::force_abbrevs()
{
        // XXX Compilation units can share abbrevs.  Parse each table
        // at most once.
        if (have_abbrevs)
                return;

        // Section 7.5.3
        cursor c(file.get_section(section_type::abbrev),
                 debug_abbrev_offset);
        abbrev_entry entry;
        abbrev_code highest = 0;
        while (entry.read(&c)) {
                abbrevs_map[entry.code] = entry;
                if (entry.code > highest)
                        highest = entry.code;
        }

        // Typically, abbrev codes are assigned linearly, so it's more
        // space efficient and time efficient to store the table in a
        // vector.  Convert to a vector if it's dense enough, by some
        // rough estimate of "enough".
        if (highest * 10 < abbrevs_map.size() * 15) {
                // Move the map into the vector
                abbrevs_vec.resize(highest + 1);
                for (auto &entry : abbrevs_map)
                        abbrevs_vec[entry.first] = move(entry.second);
                abbrevs_map.clear();
        }

        have_abbrevs = true;
}

const abbrev_entry &
compilation_unit::impl::get_abbrev(abbrev_code acode)
{
        if (!abbrevs_vec.empty()) {
                if (acode >= abbrevs_vec.size())
                        goto unknown;
                const abbrev_entry &entry = abbrevs_vec[acode];
                if (entry.code == 0)
                        goto unknown;
                return entry;
        } else {
                auto it = abbrevs_map.find(acode);
                if (it == abbrevs_map.end())
                        goto unknown;
                return it->second;
        }

unknown:
        throw format_error("unknown abbrev code 0x" + to_hex(acode));
}

DWARFPP_END_NAMESPACE
<|endoftext|>


<commit_before><commit_msg>fix win build<commit_after><|endoftext|>