<commit_before>// Copyright (c) 2009 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 <string>

#include "base/logging.h"
#include "chrome/browser/sync/notifier/listener/mediator_thread_mock.h"
#include "chrome/browser/sync/notifier/listener/talk_mediator_impl.h"
#include "chrome/browser/sync/util/event_sys-inl.h"
#include "talk/xmpp/xmppengine.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace browser_sync {

class TalkMediatorImplTest : public testing::Test {
 public:
  void HandleTalkMediatorEvent(
      const browser_sync::TalkMediatorEvent& event) {
    last_message_ = event.what_happened;
  }

 protected:
  TalkMediatorImplTest() {}
  ~TalkMediatorImplTest() {}

  virtual void SetUp() {
    last_message_ = -1;
  }

  virtual void TearDown() {
  }

  int last_message_;
};

TEST_F(TalkMediatorImplTest, ConstructionOfTheClass) {
  // Constructing a single talk mediator enables SSL through the singleton.
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(
      browser_sync::kDefaultNotificationMethod, false));
  talk1.reset(NULL);
}

TEST_F(TalkMediatorImplTest, SetAuthTokenWithBadInput) {
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_FALSE(talk1->SetAuthToken("@missinguser.com", ""));
  ASSERT_TRUE(talk1->state_.initialized == 0);

  scoped_ptr<TalkMediatorImpl> talk2(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_FALSE(talk2->SetAuthToken("", "1234567890"));
  ASSERT_TRUE(talk2->state_.initialized == 0);

  scoped_ptr<TalkMediatorImpl> talk3(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_FALSE(talk3->SetAuthToken("missingdomain", "abcde"));
  ASSERT_TRUE(talk3->state_.initialized == 0);
}

TEST_F(TalkMediatorImplTest, SetAuthTokenWithGoodInput) {
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token"));
  ASSERT_TRUE(talk1->state_.initialized == 1);

  scoped_ptr<TalkMediatorImpl> talk2(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_TRUE(talk2->SetAuthToken("chromium@mail.google.com", "token"));
  ASSERT_TRUE(talk2->state_.initialized == 1);

  scoped_ptr<TalkMediatorImpl> talk3(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_TRUE(talk3->SetAuthToken("chromium@chromium.org", "token"));
  ASSERT_TRUE(talk3->state_.initialized == 1);
}

TEST_F(TalkMediatorImplTest, LoginWiring) {
  // The TalkMediatorImpl owns the mock.
  MockMediatorThread* mock = new MockMediatorThread();
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(mock));

  // Login checks states for initialization.
  ASSERT_TRUE(talk1->Login() == false);
  ASSERT_TRUE(mock->login_calls == 0);

  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token") == true);
  ASSERT_TRUE(talk1->Login() == true);
  ASSERT_TRUE(mock->login_calls == 1);

  // Successive calls to login will fail.  One needs to create a new talk
  // mediator object.
  ASSERT_TRUE(talk1->Login() == false);
  ASSERT_TRUE(mock->login_calls == 1);

  ASSERT_TRUE(talk1->Logout() == true);
  ASSERT_TRUE(mock->logout_calls == 1);

  // Successive logout calls do nothing.
  ASSERT_TRUE(talk1->Logout() == false);
  ASSERT_TRUE(mock->logout_calls == 1);
}

TEST_F(TalkMediatorImplTest, SendNotification) {
  // The TalkMediatorImpl owns the mock.
  MockMediatorThread* mock = new MockMediatorThread();
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(mock));

  // Failure due to not being logged in.
  ASSERT_TRUE(talk1->SendNotification() == false);
  ASSERT_TRUE(mock->send_calls == 0);

  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token") == true);
  ASSERT_TRUE(talk1->Login() == true);
  talk1->OnLogin();
  ASSERT_TRUE(mock->login_calls == 1);

  // Failure due to not being subscribed.
  ASSERT_TRUE(talk1->SendNotification() == false);
  ASSERT_TRUE(mock->send_calls == 0);

  // Fake subscription
  talk1->OnSubscriptionSuccess();
  ASSERT_TRUE(talk1->state_.subscribed == 1);
  ASSERT_TRUE(talk1->SendNotification() == true);
  ASSERT_TRUE(mock->send_calls == 1);
  ASSERT_TRUE(talk1->SendNotification() == true);
  ASSERT_TRUE(mock->send_calls == 2);

  ASSERT_TRUE(talk1->Logout() == true);
  ASSERT_TRUE(mock->logout_calls == 1);

  // Failure due to being logged out.
  ASSERT_TRUE(talk1->SendNotification() == false);
  ASSERT_TRUE(mock->send_calls == 2);
}

TEST_F(TalkMediatorImplTest, MediatorThreadCallbacks) {
  // The TalkMediatorImpl owns the mock.
  MockMediatorThread* mock = new MockMediatorThread();
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(mock));

  scoped_ptr<EventListenerHookup> callback(NewEventListenerHookup(
      talk1->channel(), this, &TalkMediatorImplTest::HandleTalkMediatorEvent));

  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token") == true);
  ASSERT_TRUE(talk1->Login() == true);
  ASSERT_TRUE(mock->login_calls == 1);

  mock->ChangeState(MediatorThread::MSG_LOGGED_IN);
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::LOGIN_SUCCEEDED);

  // The message triggers calls to listen and subscribe.
  ASSERT_TRUE(mock->listen_calls == 1);
  ASSERT_TRUE(mock->subscribe_calls == 1);
  ASSERT_TRUE(talk1->state_.subscribed == 0);

  mock->ChangeState(MediatorThread::MSG_SUBSCRIPTION_SUCCESS);
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::SUBSCRIPTIONS_ON);
  ASSERT_TRUE(talk1->state_.subscribed == 1);

  // After subscription success is receieved, the talk mediator will allow
  // sending of notifications.
  ASSERT_TRUE(talk1->SendNotification() == true);
  ASSERT_TRUE(mock->send_calls == 1);

  // |MSG_NOTIFICATION_RECEIVED| from the MediatorThread triggers a callback
  // of type |NOTIFICATION_RECEIVED|.
  mock->ChangeState(MediatorThread::MSG_NOTIFICATION_RECEIVED);
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::NOTIFICATION_RECEIVED);

  // A |TALKMEDIATOR_DESTROYED| message is received during tear down.
  talk1.reset();
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::TALKMEDIATOR_DESTROYED);
}

}  // namespace browser_sync
<commit_msg>TBR: chron@chromium.org<commit_after>// Copyright (c) 2009 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 <string>

#include "base/logging.h"
#include "chrome/browser/sync/notifier/listener/mediator_thread_mock.h"
#include "chrome/browser/sync/notifier/listener/talk_mediator_impl.h"
#include "chrome/browser/sync/util/event_sys-inl.h"
#include "talk/xmpp/xmppengine.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace browser_sync {

class TalkMediatorImplTest : public testing::Test {
 public:
  void HandleTalkMediatorEvent(
      const browser_sync::TalkMediatorEvent& event) {
    last_message_ = event.what_happened;
  }

 protected:
  TalkMediatorImplTest() {}
  ~TalkMediatorImplTest() {}

  virtual void SetUp() {
    last_message_ = -1;
  }

  virtual void TearDown() {
  }

  int last_message_;
};

TEST_F(TalkMediatorImplTest, ConstructionOfTheClass) {
  // Constructing a single talk mediator enables SSL through the singleton.
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(
      browser_sync::kDefaultNotificationMethod, false));
  talk1.reset(NULL);
}

TEST_F(TalkMediatorImplTest, SetAuthTokenWithBadInput) {
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_FALSE(talk1->SetAuthToken("@missinguser.com", ""));
  ASSERT_TRUE(talk1->state_.initialized == 0);

  scoped_ptr<TalkMediatorImpl> talk2(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_FALSE(talk2->SetAuthToken("", "1234567890"));
  ASSERT_TRUE(talk2->state_.initialized == 0);

  scoped_ptr<TalkMediatorImpl> talk3(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_FALSE(talk3->SetAuthToken("missingdomain", "abcde"));
  ASSERT_TRUE(talk3->state_.initialized == 0);
}

TEST_F(TalkMediatorImplTest, SetAuthTokenWithGoodInput) {
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token"));
  ASSERT_TRUE(talk1->state_.initialized == 1);

  scoped_ptr<TalkMediatorImpl> talk2(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_TRUE(talk2->SetAuthToken("chromium@mail.google.com", "token"));
  ASSERT_TRUE(talk2->state_.initialized == 1);

  scoped_ptr<TalkMediatorImpl> talk3(new TalkMediatorImpl(
      new MockMediatorThread()));
  ASSERT_TRUE(talk3->SetAuthToken("chromium@chromium.org", "token"));
  ASSERT_TRUE(talk3->state_.initialized == 1);
}

TEST_F(TalkMediatorImplTest, LoginWiring) {
  // The TalkMediatorImpl owns the mock.
  MockMediatorThread* mock = new MockMediatorThread();
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(mock));

  // Login checks states for initialization.
  ASSERT_TRUE(talk1->Login() == false);
  ASSERT_TRUE(mock->login_calls == 0);

  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token") == true);
  ASSERT_TRUE(talk1->Login() == true);
  ASSERT_TRUE(mock->login_calls == 1);

  // Successive calls to login will fail.  One needs to create a new talk
  // mediator object.
  ASSERT_TRUE(talk1->Login() == false);
  ASSERT_TRUE(mock->login_calls == 1);

  ASSERT_TRUE(talk1->Logout() == true);
  ASSERT_TRUE(mock->logout_calls == 1);

  // Successive logout calls do nothing.
  ASSERT_TRUE(talk1->Logout() == false);
  ASSERT_TRUE(mock->logout_calls == 1);
}

TEST_F(TalkMediatorImplTest, SendNotification) {
  // The TalkMediatorImpl owns the mock.
  MockMediatorThread* mock = new MockMediatorThread();
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(mock));

  // Failure due to not being logged in.
  ASSERT_TRUE(talk1->SendNotification() == false);
  ASSERT_TRUE(mock->send_calls == 0);

  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token") == true);
  ASSERT_TRUE(talk1->Login() == true);
  talk1->OnLogin();
  ASSERT_TRUE(mock->login_calls == 1);

  // Failure due to not being subscribed.
  ASSERT_TRUE(talk1->SendNotification() == false);
  ASSERT_TRUE(mock->send_calls == 0);

  // Fake subscription
  talk1->OnSubscriptionSuccess();
  ASSERT_TRUE(talk1->state_.subscribed == 1);
  ASSERT_TRUE(talk1->SendNotification() == true);
  ASSERT_TRUE(mock->send_calls == 2);
  ASSERT_TRUE(talk1->SendNotification() == true);
  ASSERT_TRUE(mock->send_calls == 3);

  ASSERT_TRUE(talk1->Logout() == true);
  ASSERT_TRUE(mock->logout_calls == 1);

  // Failure due to being logged out.
  ASSERT_TRUE(talk1->SendNotification() == false);
  ASSERT_TRUE(mock->send_calls == 3);
}

TEST_F(TalkMediatorImplTest, MediatorThreadCallbacks) {
  // The TalkMediatorImpl owns the mock.
  MockMediatorThread* mock = new MockMediatorThread();
  scoped_ptr<TalkMediatorImpl> talk1(new TalkMediatorImpl(mock));

  scoped_ptr<EventListenerHookup> callback(NewEventListenerHookup(
      talk1->channel(), this, &TalkMediatorImplTest::HandleTalkMediatorEvent));

  ASSERT_TRUE(talk1->SetAuthToken("chromium@gmail.com", "token") == true);
  ASSERT_TRUE(talk1->Login() == true);
  ASSERT_TRUE(mock->login_calls == 1);

  mock->ChangeState(MediatorThread::MSG_LOGGED_IN);
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::LOGIN_SUCCEEDED);

  // The message triggers calls to listen and subscribe.
  ASSERT_TRUE(mock->listen_calls == 1);
  ASSERT_TRUE(mock->subscribe_calls == 1);
  ASSERT_TRUE(talk1->state_.subscribed == 0);

  mock->ChangeState(MediatorThread::MSG_SUBSCRIPTION_SUCCESS);
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::SUBSCRIPTIONS_ON);
  ASSERT_TRUE(talk1->state_.subscribed == 1);

  // After subscription success is receieved, the talk mediator will allow
  // sending of notifications.
  ASSERT_TRUE(talk1->SendNotification() == true);
  ASSERT_TRUE(mock->send_calls == 2);

  // |MSG_NOTIFICATION_RECEIVED| from the MediatorThread triggers a callback
  // of type |NOTIFICATION_RECEIVED|.
  mock->ChangeState(MediatorThread::MSG_NOTIFICATION_RECEIVED);
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::NOTIFICATION_RECEIVED);

  // A |TALKMEDIATOR_DESTROYED| message is received during tear down.
  talk1.reset();
  ASSERT_TRUE(last_message_ == TalkMediatorEvent::TALKMEDIATOR_DESTROYED);
}

}  // namespace browser_sync
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestHyperOctreeContourFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/

// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT

#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeContourFilter.h"

#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeSampleFunction.h"
#include "vtkSphere.h"
#include "vtkCamera.h"

int TestHyperOctreeContourFilter(int argc, char* argv[])
{
  // Standard rendering classes
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  vtkTimerLog *timer=vtkTimerLog::New();

  // 3D
  vtkHyperOctreeSampleFunction *source3d=vtkHyperOctreeSampleFunction::New();
  vtkSphere *f3d=vtkSphere::New();
  f3d->SetRadius(1);
  f3d->SetCenter(1,1,0);
  source3d->SetImplicitFunction(f3d);
  source3d->SetThreshold(0.2);
  f3d->Delete();

  source3d->SetDimension(3);
  source3d->SetWidth(2);
  source3d->SetHeight(3);
  source3d->SetDepth(4);
  source3d->SetLevels(6); // 10
  source3d->SetMinLevels(0);

  cout<<"update source3d..."<<endl;
  timer->StartTimer();
  source3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated3d"<<endl;
  cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeContourFilter *contour3d=vtkHyperOctreeContourFilter::New();
  contour3d->SetNumberOfContours(3);
  contour3d->SetValue(0,0.5);
  contour3d->SetValue(1,4.0);
  contour3d->SetValue(2,8.0);

  contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
  source3d->Delete();
  cout<<"update contour3d..."<<endl;
  timer->StartTimer();
  contour3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour3d updated"<<endl;
  cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut3d = vtkLookupTable::New();
  lut3d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
  mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
  contour3d->Delete();

  mapper3d->SetLookupTable(lut3d);

  if(contour3d->GetOutput()->GetCellData()!=0)
    {
    if(contour3d->GetOutput()->GetCellData()->GetScalars()!=0)
      {
      mapper3d->SetScalarRange( contour3d->GetOutput()->GetCellData()->
                                GetScalars()->GetRange());
      }
    }

  vtkActor *actor3d = vtkActor::New();
  actor3d->SetMapper(mapper3d);
  renderer->AddActor(actor3d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
  writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
  writer3d->SetFileName("contour3d.vtp");
  writer3d->SetDataModeToAscii();
  writer3d->Write();
  writer3d->Delete();
#endif // #ifdef WRITE_RESULT

  // 2D
  vtkHyperOctreeSampleFunction *source2d=vtkHyperOctreeSampleFunction::New();
  vtkSphere *f2d=vtkSphere::New();
  f2d->SetRadius(1);
  f2d->SetCenter(1,1,0);
  source2d->SetImplicitFunction(f2d);
  source2d->SetThreshold(0.2);
  f2d->Delete();

  source2d->SetDimension(2);
  source2d->SetWidth(2);
  source2d->SetHeight(3);
  source2d->SetDepth(4);
  source2d->SetLevels(10); // 7
  source2d->SetMinLevels(0);

  cout<<"update source2d..."<<endl;
  timer->StartTimer();
  source2d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated2d"<<endl;
  cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeContourFilter *contour2d=vtkHyperOctreeContourFilter::New();
  contour2d->SetNumberOfContours(3);
  contour2d->SetValue(0,0.5);
  contour2d->SetValue(1,4.0);
  contour2d->SetValue(2,8.0);

  contour2d->SetInputConnection(0,source2d->GetOutputPort(0));
  source2d->Delete();
  cout<<"update contour2d..."<<endl;
  timer->StartTimer();
  contour2d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour2d updated"<<endl;
  cout<<"contour2d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut2d = vtkLookupTable::New();
  lut2d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper2d = vtkPolyDataMapper::New();
  mapper2d->SetInputConnection(0,contour2d->GetOutputPort(0));
  mapper2d->SetLookupTable(lut2d);
  mapper2d->SetScalarModeToUseCellData();

  if(contour2d->GetOutput()->GetCellData()!=0)
    {
    if(contour2d->GetOutput()->GetCellData()->GetScalars()!=0)
      {
      mapper2d->SetScalarRange( contour2d->GetOutput()->GetCellData()->
                              GetScalars()->GetRange());
      }
    }

  vtkActor *actor2d = vtkActor::New();
  actor2d->SetPosition(5,0,0);
  actor2d->SetMapper(mapper2d);
  renderer->AddActor(actor2d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
  writer2d->SetInputConnection(0,contour2d->GetOutputPort(0));
  writer2d->SetFileName("contour2d.vtp");
  writer2d->SetDataModeToAscii();
  writer2d->Write();
  writer2d->Delete();
#endif // #ifdef WRITE_RESULT

  // 1D
  vtkHyperOctreeSampleFunction *source1d=vtkHyperOctreeSampleFunction::New();
  vtkSphere *f1d=vtkSphere::New();
  f1d->SetRadius(1);
  f1d->SetCenter(1,1,0);
  source1d->SetImplicitFunction(f1d);
  source1d->SetThreshold(0.2);
  f1d->Delete();

  source1d->SetDimension(1);
  source1d->SetWidth(2);
  source1d->SetHeight(3);
  source1d->SetDepth(4);
  source1d->SetLevels(10); // 7
  source1d->SetMinLevels(0);

  cout<<"update source1d..."<<endl;
  timer->StartTimer();
  source1d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated1d"<<endl;
  cout<<"source1d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeContourFilter *contour1d=vtkHyperOctreeContourFilter::New();
  contour1d->SetNumberOfContours(3);
  contour1d->SetValue(0,0.5);
  contour1d->SetValue(1,4.0);
  contour1d->SetValue(2,8.0);

  contour1d->SetInputConnection(0,source1d->GetOutputPort(0));
  source1d->Delete();
  cout<<"update contour1d..."<<endl;
  timer->StartTimer();
  contour1d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour1d updated"<<endl;
  cout<<"contour1d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut1d = vtkLookupTable::New();
  lut1d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper1d = vtkPolyDataMapper::New();
  mapper1d->SetInputConnection(0,contour1d->GetOutputPort(0));
  mapper1d->SetLookupTable(lut1d);

  if(contour1d->GetOutput()->GetCellData()!=0)
    {
    if(contour1d->GetOutput()->GetCellData()->GetScalars()!=0)
      {
      mapper1d->SetScalarRange( contour1d->GetOutput()->GetCellData()->
                              GetScalars()->GetRange());
      }
    }

  vtkActor *actor1d = vtkActor::New();
  actor1d->SetPosition(10,0,0);
  actor1d->SetMapper(mapper1d);
  renderer->AddActor(actor1d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer1d=vtkXMLPolyDataWriter::New();
  writer1d->SetInputConnection(0,contour1d->GetOutputPort(0));
  writer1d->SetFileName("contour1d.vtp");
  writer1d->SetDataModeToAscii();
  writer1d->Write();
  writer1d->Delete();
#endif // #ifdef WRITE_RESULT

  // Standard testing code.
  renderer->SetBackground(0.5,0.5,0.5);
  renWin->SetSize(300,300);
  vtkCamera *cam=renderer->GetActiveCamera();
  renderer->ResetCamera();
  cam->Azimuth(180);
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  renderer->Delete();
  renWin->Delete();
  iren->Delete();

  mapper3d->Delete();
  actor3d->Delete();
  lut3d->Delete();

  mapper2d->Delete();
  actor2d->Delete();
  lut2d->Delete();
  contour2d->Delete();

  mapper1d->Delete();
  actor1d->Delete();
  lut1d->Delete();
  contour1d->Delete();

  timer->Delete();

  return !retVal;
}
<commit_msg>BUG: Conditional jump or move depends on uninitialised value<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestHyperOctreeContourFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This example demonstrates how to use a vtkHyperOctreeSampleFunction and
// apply a vtkHyperOctreeCutter filter on it.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/

// If WRITE_RESULT is defined, the result of the surface filter is saved.
//#define WRITE_RESULT

#include "vtkActor.h"
#include "vtkCellData.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <assert.h>
#include "vtkLookupTable.h"
#include "vtkPolyData.h"
#include "vtkXMLPolyDataWriter.h"
#include "vtkHyperOctreeContourFilter.h"

#include "vtkPolyDataMapper.h"
#include "vtkTimerLog.h"
#include "vtkHyperOctreeSampleFunction.h"
#include "vtkSphere.h"
#include "vtkCamera.h"

int TestHyperOctreeContourFilter(int argc, char* argv[])
{
  // Standard rendering classes
  vtkRenderer *renderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(renderer);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  vtkTimerLog *timer=vtkTimerLog::New();

  // 3D
  vtkHyperOctreeSampleFunction *source3d=vtkHyperOctreeSampleFunction::New();
  vtkSphere *f3d=vtkSphere::New();
  f3d->SetRadius(1);
  f3d->SetCenter(1,1,0);
  source3d->SetImplicitFunction(f3d);
  source3d->SetThreshold(0.2);
  f3d->Delete();

  source3d->SetDimension(3);
  source3d->SetWidth(2);
  source3d->SetHeight(3);
  source3d->SetDepth(4);
  source3d->SetLevels(6); // 10
  source3d->SetMinLevels(0);

  cout<<"update source3d..."<<endl;
  timer->StartTimer();
  source3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated3d"<<endl;
  cout<<"source3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeContourFilter *contour3d=vtkHyperOctreeContourFilter::New();
  contour3d->SetNumberOfContours(3);
  contour3d->SetValue(0,0.5);
  contour3d->SetValue(1,4.0);
  contour3d->SetValue(2,8.0);

  contour3d->SetInputConnection(0,source3d->GetOutputPort(0));
  source3d->Delete();
  cout<<"update contour3d..."<<endl;
  timer->StartTimer();
  contour3d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour3d updated"<<endl;
  cout<<"contour3d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut3d = vtkLookupTable::New();
  lut3d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper3d = vtkPolyDataMapper::New();
  mapper3d->SetInputConnection(0, contour3d->GetOutputPort(0) );
  contour3d->Delete();

  mapper3d->SetLookupTable(lut3d);

  if(contour3d->GetOutput()->GetCellData()!=0)
    {
    if(contour3d->GetOutput()->GetCellData()->GetScalars()!=0)
      {
      mapper3d->SetScalarRange( contour3d->GetOutput()->GetCellData()->
                                GetScalars()->GetRange());
      }
    }

  vtkActor *actor3d = vtkActor::New();
  actor3d->SetMapper(mapper3d);
  renderer->AddActor(actor3d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer3d=vtkXMLPolyDataWriter::New();
  writer3d->SetInputConnection(0,contour3d->GetOutputPort(0));
  writer3d->SetFileName("contour3d.vtp");
  writer3d->SetDataModeToAscii();
  writer3d->Write();
  writer3d->Delete();
#endif // #ifdef WRITE_RESULT

  // 2D
  vtkHyperOctreeSampleFunction *source2d=vtkHyperOctreeSampleFunction::New();
  vtkSphere *f2d=vtkSphere::New();
  f2d->SetRadius(1);
  f2d->SetCenter(1,1,0);
  source2d->SetImplicitFunction(f2d);
  source2d->SetThreshold(0.2);
  f2d->Delete();

  source2d->SetDimension(2);
  source2d->SetWidth(2);
  source2d->SetHeight(3);
  source2d->SetDepth(4);
  source2d->SetLevels(10); // 7
  source2d->SetMinLevels(0);

  cout<<"update source2d..."<<endl;
  timer->StartTimer();
  source2d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated2d"<<endl;
  cout<<"source2d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeContourFilter *contour2d=vtkHyperOctreeContourFilter::New();
  contour2d->SetNumberOfContours(3);
  contour2d->SetValue(0,0.5);
  contour2d->SetValue(1,4.0);
  contour2d->SetValue(2,8.0);

  contour2d->SetInputConnection(0,source2d->GetOutputPort(0));
  source2d->Delete();
  cout<<"update contour2d..."<<endl;
  timer->StartTimer();
  contour2d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour2d updated"<<endl;
  cout<<"contour2d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut2d = vtkLookupTable::New();
  lut2d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper2d = vtkPolyDataMapper::New();
  mapper2d->SetInputConnection(0,contour2d->GetOutputPort(0));
  mapper2d->SetLookupTable(lut2d);
  mapper2d->SetScalarModeToUseCellData();

  if(contour2d->GetOutput()->GetCellData()!=0)
    {
    if(contour2d->GetOutput()->GetCellData()->GetScalars()!=0)
      {
      mapper2d->SetScalarRange( contour2d->GetOutput()->GetCellData()->
                              GetScalars()->GetRange());
      }
    }

  vtkActor *actor2d = vtkActor::New();
  actor2d->SetPosition(5,0,0);
  actor2d->SetMapper(mapper2d);
  renderer->AddActor(actor2d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer2d=vtkXMLPolyDataWriter::New();
  writer2d->SetInputConnection(0,contour2d->GetOutputPort(0));
  writer2d->SetFileName("contour2d.vtp");
  writer2d->SetDataModeToAscii();
  writer2d->Write();
  writer2d->Delete();
#endif // #ifdef WRITE_RESULT

  // 1D
  vtkHyperOctreeSampleFunction *source1d=vtkHyperOctreeSampleFunction::New();
  vtkSphere *f1d=vtkSphere::New();
  f1d->SetRadius(1);
  f1d->SetCenter(1,1,0);
  source1d->SetImplicitFunction(f1d);
  source1d->SetThreshold(0.2);
  f1d->Delete();

  source1d->SetDimension(1);
  source1d->SetWidth(2);
  source1d->SetHeight(3);
  source1d->SetDepth(4);
  source1d->SetLevels(10); // 7
  source1d->SetMinLevels(0);

  cout<<"update source1d..."<<endl;
  timer->StartTimer();
  source1d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"source updated1d"<<endl;
  cout<<"source1d time="<<timer->GetElapsedTime()<<" s"<<endl;

  vtkHyperOctreeContourFilter *contour1d=vtkHyperOctreeContourFilter::New();
  contour1d->SetNumberOfContours(3);
  contour1d->SetValue(0,0.5);
  contour1d->SetValue(1,4.0);
  contour1d->SetValue(2,8.0);

  contour1d->SetInputConnection(0,source1d->GetOutputPort(0));
  source1d->Delete();
  cout<<"update contour1d..."<<endl;
  timer->StartTimer();
  contour1d->Update(); // Update now, make things easier with a debugger
  timer->StopTimer();
  cout<<"contour1d updated"<<endl;
  cout<<"contour1d time="<<timer->GetElapsedTime()<<" s"<<endl;

  // This creates a blue to red lut.
  vtkLookupTable *lut1d = vtkLookupTable::New();
  lut1d->SetHueRange (0.667, 0.0);

  vtkPolyDataMapper *mapper1d = vtkPolyDataMapper::New();
  mapper1d->SetInputConnection(0,contour1d->GetOutputPort(0));
  mapper1d->SetLookupTable(lut1d);
  mapper1d->SetScalarModeToUseCellData();

  if(contour1d->GetOutput()->GetCellData()!=0)
    {
    if(contour1d->GetOutput()->GetCellData()->GetScalars()!=0)
      {
      mapper1d->SetScalarRange( contour1d->GetOutput()->GetCellData()->
                              GetScalars()->GetRange());
      }
    }

  vtkActor *actor1d = vtkActor::New();
  actor1d->SetPosition(10,0,0);
  actor1d->SetMapper(mapper1d);
  renderer->AddActor(actor1d);

#ifdef WRITE_RESULT
  // Save the result of the filter in a file
  vtkXMLPolyDataWriter *writer1d=vtkXMLPolyDataWriter::New();
  writer1d->SetInputConnection(0,contour1d->GetOutputPort(0));
  writer1d->SetFileName("contour1d.vtp");
  writer1d->SetDataModeToAscii();
  writer1d->Write();
  writer1d->Delete();
#endif // #ifdef WRITE_RESULT

  // Standard testing code.
  renderer->SetBackground(0.5,0.5,0.5);
  renWin->SetSize(300,300);
  vtkCamera *cam=renderer->GetActiveCamera();
  renderer->ResetCamera();
  cam->Azimuth(180);
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  renderer->Delete();
  renWin->Delete();
  iren->Delete();

  mapper3d->Delete();
  actor3d->Delete();
  lut3d->Delete();

  mapper2d->Delete();
  actor2d->Delete();
  lut2d->Delete();
  contour2d->Delete();

  mapper1d->Delete();
  actor1d->Delete();
  lut1d->Delete();
  contour1d->Delete();

  timer->Delete();

  return !retVal;
}
<|endoftext|>


<commit_before>#pragma once
#ifndef TETRA_META_VARIANT_HPP
#define TETRA_META_VARIANT_HPP

#include <tetra/meta/MetaData.hpp>

#include <stdexcept>

namespace tetra
{
namespace meta
{

/**
 * Thrown by the Variant when there is a type mismatch of some sort.
 **/
class TypeCastException : public std::runtime_error
{
public:
  inline TypeCastException()
    : std::runtime_error{"Error while attempting to cast types!"}
  { }
};

/**
 * Uses MetaData to safely hold a freestore allocated instance
 * of the class that the MetaData describes.
 **/
class Variant
{
  const MetaData* metaData{nullptr};
  void* pObj{nullptr};

public:
  /**
   * Creates a new Variant which holds an instance of the class
   * that the provided MetaData describes.
   **/
  Variant( const MetaData& metaData ) noexcept;

  /**
   * Creates a payload object using the inferred type's MetaData,
   * then stores the given object into the payload. Only works
   * if the type has a copy or move operator.
   * @param toStore The object to store.
   **/
  template <typename T>
  static Variant create( T&& toStore ) noexcept
  {
    using Type = typename std::remove_reference<T>::type;
    Variant v{MetaData::create<Type>()};
    v.getObject<Type>() = toStore;

    return v;
  }

  /**
   * Safely deletes the object using its MetaData.
   **/
  ~Variant();

  /**
   * Variants are not copyable, if you must copy
   * a variant then use the Variant::create method along
   * with the getObject method. (e.g. create(v.getObject()))
   **/
  Variant( const Variant& ) = delete;
  Variant& operator=( const Variant& ) = delete;

  /**
   * Variants are moveable, the object that is left behind
   * holds no data and will always throw when getObject is called.
   **/
  Variant( Variant&& variant ) noexcept;
  Variant& operator=( Variant&& variant ) noexcept;

  /**
   * Returns the MetaData which describes this Variant's payload.
   **/
  const MetaData& getMetaData() const noexcept;

  /**
   * Safely casts the Variant's payload to the type requested
   * and returns a reference to it.
   * @throws TypeCastException if the type requested is incompatable
   *         with the type of the Variant's payload.
   * @templateParam T The type to cast the payload to.
   * @return Reference to the Variant's payload, cast to the templated
   *         type
   **/
  template <typename T>
  T& getObject() const throw( TypeCastException )
  {
    if ( metaData != &MetaData::create<T>() )
    {
      throw TypeCastException{};
    }

    return *reinterpret_cast<T*>( pObj );
  }
};

} /* namespace meta */
} /* namespace tetra */

#endif
<commit_msg>updated Variant to have a default constructor<commit_after>#pragma once
#ifndef TETRA_META_VARIANT_HPP
#define TETRA_META_VARIANT_HPP

#include <tetra/meta/MetaData.hpp>

#include <stdexcept>

namespace tetra
{
namespace meta
{

/**
 * Thrown by the Variant when there is a type mismatch of some sort.
 **/
class TypeCastException : public std::runtime_error
{
public:
  inline TypeCastException()
    : std::runtime_error{"Error while attempting to cast types!"}
  { }
};

/**
 * Uses MetaData to safely hold a freestore allocated instance
 * of the class that the MetaData describes.
 **/
class Variant
{
  const MetaData* metaData{nullptr};
  void* pObj{nullptr};

public:
  /**
   * Creates an empty variant that always throws a TypeCastException
   * when getObject is called.
   **/
  Variant() = default;

  /**
   * Creates a new Variant which holds an instance of the class
   * that the provided MetaData describes.
   **/
  Variant( const MetaData& metaData ) noexcept;

  /**
   * Creates a payload object using the inferred type's MetaData,
   * then stores the given object into the payload. Only works
   * if the type has a copy or move operator.
   * @param toStore The object to store.
   **/
  template <typename T>
  static Variant create( T&& toStore ) noexcept
  {
    using Type = typename std::remove_reference<T>::type;
    Variant v{MetaData::create<Type>()};
    v.getObject<Type>() = toStore;

    return v;
  }

  /**
   * Safely deletes the object using its MetaData.
   **/
  ~Variant();

  /**
   * Variants are not copyable, if you must copy
   * a variant then use the Variant::create method along
   * with the getObject method. (e.g. create(v.getObject()))
   **/
  Variant( const Variant& ) = delete;
  Variant& operator=( const Variant& ) = delete;

  /**
   * Variants are moveable, the object that is left behind
   * holds no data and will always throw when getObject is called.
   **/
  Variant( Variant&& variant ) noexcept;
  Variant& operator=( Variant&& variant ) noexcept;

  /**
   * Returns the MetaData which describes this Variant's payload.
   **/
  const MetaData& getMetaData() const noexcept;

  /**
   * Safely casts the Variant's payload to the type requested
   * and returns a reference to it.
   * @throws TypeCastException if the type requested is incompatable
   *         with the type of the Variant's payload.
   * @templateParam T The type to cast the payload to.
   * @return Reference to the Variant's payload, cast to the templated
   *         type
   **/
  template <typename T>
  T& getObject() const throw( TypeCastException )
  {
    if ( metaData != &MetaData::create<T>() )
    {
      throw TypeCastException{};
    }

    return *reinterpret_cast<T*>( pObj );
  }
};

} /* namespace meta */
} /* namespace tetra */

#endif
<|endoftext|>


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

#include <oleacc.h>

#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  IAccessible* acc_obj = NULL;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  // TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
  // "about:blank - Chromium"
  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
                        ROLE_SYSTEM_WINDOW);

  acc_obj->Release();
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<commit_msg>Mark TestAboutViewChromeAccObj as FAILS.<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 <oleacc.h>

#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  IAccessible* acc_obj = NULL;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  // TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
  // "about:blank - Chromium"
  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
                        ROLE_SYSTEM_WINDOW);

  acc_obj->Release();
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<|endoftext|>


<commit_before>/*
 * RunGrid.cpp
 *
 * Grid-level initialization, run, and output (if any)
 *    Note: the output modules are put here, so can be flexible for outputs
 *
*/

#include "RunGrid.h"
#include "../TEMUtilityFunctions.h"

RunGrid::RunGrid() {
  // grided data record ids in .nc files
  gridrecno  = MISSING_I;
  drainrecno = MISSING_I;
  soilrecno  = MISSING_I;
  gfirerecno = MISSING_I;
};

RunGrid::~RunGrid() {
};

void RunGrid::setModelData(ModelData * mdp) {
  md= mdp;
};

/** Setups up the grid ids from various input files.
*
*  Note: recno - the order (from ZERO) in the .nc file, ids - the real
*        ids in the *.nc files
*/
void RunGrid::setup_gridids_from_files(int recno) {

  this->grdids.push_back(MISSING_I);
  this->grddrgids.push_back(MISSING_I);
  this->grdsoilids.push_back(MISSING_I);
  this->grdfireids.push_back(MISSING_I);

  NcFile grid_file = temutil::open_ncfile(md->grdinputdir+"grid.nc");

  NcVar* grididV = temutil::get_ncvar(grid_file, "GRIDID");
  grididV->set_cur(recno);
  grididV->get(&this->grdids.back(), 1);

  NcVar* drgidV = temutil::get_ncvar(grid_file, "DRAINAGEID");
  drgidV->set_cur(recno);
  drgidV->get(&this->grddrgids.back(), 1);

  NcVar* soilidV = temutil::get_ncvar(grid_file, "SOILID");
  soilidV->set_cur(recno);
  soilidV->get(&this->grdsoilids.back(), 1);

  NcVar* gfireidV = temutil::get_ncvar(grid_file, "GFIREID");
  gfireidV->set_cur(recno);
  gfireidV->get(&this->grdfireids.back(), 1);

}

/** Reading all grid-level data ids.
*/
int RunGrid::allgridids() {
  int error = 0;

  /* NOTE: Should probbaly add some kind of error checking. Right now, the
   * error stack-variable is doing nothing.
   */

  for (int rec_num = 0; rec_num < md->act_gridno; ++rec_num) {
    this->setup_gridids_from_files(rec_num);
  }

  for (int i = 0; i < md->act_drainno; ++i) {

    this->drainids.push_back(MISSING_I);

    NcFile f = temutil::open_ncfile(md->grdinputdir+"drainage.nc");

    NcVar* v = temutil::get_ncvar(f, "DRAINAGEID");
    v->set_cur(i);
    v->get(&this->drainids.back(), 1);

  }

  for (int i = 0; i < md->act_soilno; ++i) {

    this->soilids.push_back(MISSING_I);

    NcFile f = temutil::open_ncfile(md->grdinputdir+"soiltexture.nc");

    NcVar* v = temutil::get_ncvar(f, "SOILID");
    v->set_cur(i);
    v->get(&this->soilids.back(), 1);

  }

  for (int i = 0; i < md->act_gfireno; ++i) {

    this->gfireids.push_back(MISSING_I);

    NcFile f = temutil::open_ncfile(md->grdinputdir+"firestatistics.nc");

    NcVar* v = temutil::get_ncvar(f, "GFIREID");
    v->set_cur(i);
    v->get(&this->gfireids.back(), 1);
  }

  return error;
};

//reading data for ONE grid, using its record no (the order) in .nc files,
// which must be known before calling
int RunGrid::readData() {
  //reading the grided 'lat/lon' data
  if (gridrecno<0) {
    return -1;
  }

  this->grid.gd.read_location_from_file(md->grdinputdir + "grid.nc", gridrecno);

  //reading the grided 'drainage type' data
  if (drainrecno<0) {
    return -2;
  }

  grid.gd.drainage_type_from_file(md->grdinputdir + "drainage.nc", drainrecno);

  //reading the grided 'soil texture' data
  if (soilrecno<0) {
    return -3;
  }

  grid.gd.soil_texture_from_file(md->grdinputdir + "soiltexture.nc", soilrecno);

  //reading the grided 'fire' data
  if (gfirerecno<0) {
    return -4;
  }

  grid.gd.g_fire_from_file(md->grdinputdir + "fire.nc", gfirerecno);

  //
  grid.reinit();          //checking grid data
  return 0;
};
<commit_msg>Fix typo in file name - wrong fire file.<commit_after>/*
 * RunGrid.cpp
 *
 * Grid-level initialization, run, and output (if any)
 *    Note: the output modules are put here, so can be flexible for outputs
 *
*/

#include "RunGrid.h"
#include "../TEMUtilityFunctions.h"

RunGrid::RunGrid() {
  // grided data record ids in .nc files
  gridrecno  = MISSING_I;
  drainrecno = MISSING_I;
  soilrecno  = MISSING_I;
  gfirerecno = MISSING_I;
};

RunGrid::~RunGrid() {
};

void RunGrid::setModelData(ModelData * mdp) {
  md= mdp;
};

/** Setups up the grid ids from various input files.
*
*  Note: recno - the order (from ZERO) in the .nc file, ids - the real
*        ids in the *.nc files
*/
void RunGrid::setup_gridids_from_files(int recno) {

  this->grdids.push_back(MISSING_I);
  this->grddrgids.push_back(MISSING_I);
  this->grdsoilids.push_back(MISSING_I);
  this->grdfireids.push_back(MISSING_I);

  NcFile grid_file = temutil::open_ncfile(md->grdinputdir+"grid.nc");

  NcVar* grididV = temutil::get_ncvar(grid_file, "GRIDID");
  grididV->set_cur(recno);
  grididV->get(&this->grdids.back(), 1);

  NcVar* drgidV = temutil::get_ncvar(grid_file, "DRAINAGEID");
  drgidV->set_cur(recno);
  drgidV->get(&this->grddrgids.back(), 1);

  NcVar* soilidV = temutil::get_ncvar(grid_file, "SOILID");
  soilidV->set_cur(recno);
  soilidV->get(&this->grdsoilids.back(), 1);

  NcVar* gfireidV = temutil::get_ncvar(grid_file, "GFIREID");
  gfireidV->set_cur(recno);
  gfireidV->get(&this->grdfireids.back(), 1);

}

/** Reading all grid-level data ids.
*/
int RunGrid::allgridids() {
  int error = 0;

  /* NOTE: Should probbaly add some kind of error checking. Right now, the
   * error stack-variable is doing nothing.
   */

  for (int rec_num = 0; rec_num < md->act_gridno; ++rec_num) {
    this->setup_gridids_from_files(rec_num);
  }

  for (int i = 0; i < md->act_drainno; ++i) {

    this->drainids.push_back(MISSING_I);

    NcFile f = temutil::open_ncfile(md->grdinputdir+"drainage.nc");

    NcVar* v = temutil::get_ncvar(f, "DRAINAGEID");
    v->set_cur(i);
    v->get(&this->drainids.back(), 1);

  }

  for (int i = 0; i < md->act_soilno; ++i) {

    this->soilids.push_back(MISSING_I);

    NcFile f = temutil::open_ncfile(md->grdinputdir+"soiltexture.nc");

    NcVar* v = temutil::get_ncvar(f, "SOILID");
    v->set_cur(i);
    v->get(&this->soilids.back(), 1);

  }

  for (int i = 0; i < md->act_gfireno; ++i) {

    this->gfireids.push_back(MISSING_I);

    NcFile f = temutil::open_ncfile(md->grdinputdir+"firestatistics.nc");

    NcVar* v = temutil::get_ncvar(f, "GFIREID");
    v->set_cur(i);
    v->get(&this->gfireids.back(), 1);
  }

  return error;
};

//reading data for ONE grid, using its record no (the order) in .nc files,
// which must be known before calling
int RunGrid::readData() {
  //reading the grided 'lat/lon' data
  if (gridrecno<0) {
    return -1;
  }

  this->grid.gd.read_location_from_file(md->grdinputdir + "grid.nc", gridrecno);

  //reading the grided 'drainage type' data
  if (drainrecno<0) {
    return -2;
  }

  grid.gd.drainage_type_from_file(md->grdinputdir + "drainage.nc", drainrecno);

  //reading the grided 'soil texture' data
  if (soilrecno<0) {
    return -3;
  }

  grid.gd.soil_texture_from_file(md->grdinputdir + "soiltexture.nc", soilrecno);

  //reading the grided 'fire' data
  if (gfirerecno<0) {
    return -4;
  }

  grid.gd.g_fire_from_file(md->grdinputdir + "firestatistics.nc", gfirerecno);

  //
  grid.reinit();          //checking grid data
  return 0;
};
<|endoftext|>


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

#include <set>
#include <vector>

#include "base/command_line.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/browser/webdata/web_data_service_test_util.h"
#include "chrome/common/notification_observer_mock.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
#include "chrome/test/thread_observer_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/glue/form_field.h"

using base::WaitableEvent;
using testing::_;

namespace {

// Define these << operators so we can use EXPECT_EQ with the
// AutofillKeys type.
template<class T1, class T2, class T3>
std::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {
  typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;
  for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {
    os << *i << ", ";
  }
  return os;
}

std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
  return os << UTF16ToUTF8(key.name()) << ", " << UTF16ToUTF8(key.value());
}

class GetAllAutofillEntries
    : public base::RefCountedThreadSafe<GetAllAutofillEntries> {
 public:
  explicit GetAllAutofillEntries(WebDataService* web_data_service)
      : web_data_service_(web_data_service),
        done_event_(false, false) {}

  void Init() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
    ChromeThread::PostTask(
        ChromeThread::DB,
        FROM_HERE,
        NewRunnableMethod(this, &GetAllAutofillEntries::Run));
    done_event_.Wait();
  }

  const std::vector<AutofillEntry>& entries() const {
    return entries_;
  }

 private:
  friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;

  void Run() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
    web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);
    done_event_.Signal();
  }

  WebDataService* web_data_service_;
  base::WaitableEvent done_event_;
  std::vector<AutofillEntry> entries_;
};

ACTION_P(SignalEvent, event) {
  event->Signal();
}

class AutofillDBThreadObserverHelper : public DBThreadObserverHelper {
 protected:
  virtual void RegisterObservers() {
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_ENTRIES_CHANGED,
                   NotificationService::AllSources());
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_PROFILE_CHANGED,
                   NotificationService::AllSources());
  }
};

}  // namespace;

class TwoClientLiveAutofillSyncTest : public LiveSyncTest {
 public:
  typedef std::set<AutofillKey> AutofillKeys;
  TwoClientLiveAutofillSyncTest()
      : name1_(ASCIIToUTF16("name1")),
        name2_(ASCIIToUTF16("name2")),
        value1_(ASCIIToUTF16("value1")),
        value2_(ASCIIToUTF16("value2")),
        done_event1_(false, false),
        done_event2_(false, false) {
    // This makes sure browser is visible and active while running test.
    InProcessBrowserTest::set_show_window(true);
    // Set the initial timeout value to 5 min.
    InProcessBrowserTest::SetInitialTimeoutInMS(300000);
  }
  ~TwoClientLiveAutofillSyncTest() {}

 protected:
  void SetupHarness() {
    client1_.reset(new ProfileSyncServiceTestHarness(
        browser()->profile(), username_, password_));
    profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
    client2_.reset(new ProfileSyncServiceTestHarness(
        profile2_.get(), username_, password_));
    wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
    wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);
  }

  void SetupSync() {
    EXPECT_TRUE(client1_->SetupSync());
    EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
    EXPECT_TRUE(client2_->SetupSync());
    EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
  }

  void Cleanup() {
    client2_.reset();
    profile2_.reset();
  }

  void AddToWds(WebDataService* wds, const AutofillKeys& keys) {
    std::vector<webkit_glue::FormField> form_fields;
    for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {
      form_fields.push_back(
          webkit_glue::FormField(string16(),
                                 (*i).name(),
                                 (*i).value(),
                                 string16()));
    }

    WaitableEvent done_event(false, false);
    scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(
        new AutofillDBThreadObserverHelper());
    observer_helper->Init();

    EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).
        WillOnce(SignalEvent(&done_event));
    wds->AddFormFields(form_fields);
    done_event.Wait();
  }

  void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {
    scoped_refptr<GetAllAutofillEntries> get_all_entries =
        new GetAllAutofillEntries(wds);
    get_all_entries->Init();
    const std::vector<AutofillEntry>& entries = get_all_entries->entries();

    for (size_t i = 0; i < entries.size(); ++i) {
      keys->insert(entries[i].key());
    }
  }

  ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
  ProfileSyncServiceTestHarness* client2() { return client2_.get(); }

  PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
  PrefService* prefs2() { return profile2_->GetPrefs(); }

  string16 name1_;
  string16 name2_;
  string16 value1_;
  string16 value2_;
  base::WaitableEvent done_event1_;
  base::WaitableEvent done_event2_;

  scoped_ptr<ProfileSyncServiceTestHarness> client1_;
  scoped_ptr<ProfileSyncServiceTestHarness> client2_;
  scoped_ptr<Profile> profile2_;
  WebDataService* wds1_;
  WebDataService* wds2_;

  DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);
};

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {
  SetupHarness();

  AutofillKeys keys;
  keys.insert(AutofillKey("name1", "value1"));
  keys.insert(AutofillKey("name1", "value2"));
  keys.insert(AutofillKey("name2", "value3"));
  keys.insert(AutofillKey("Sigur R\u00F3s", "\u00C1g\u00E6tis byrjun"));
  AddToWds(wds1_, keys);

  SetupSync();

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {
  SetupHarness();

  AutofillKeys keys1;
  keys1.insert(AutofillKey("name1", "value1"));
  keys1.insert(AutofillKey("name1", "value2"));
  keys1.insert(AutofillKey("name2", "value3"));
  AddToWds(wds1_, keys1);

  AutofillKeys keys2;
  keys2.insert(AutofillKey("name1", "value2"));
  keys2.insert(AutofillKey("name2", "value3"));
  keys2.insert(AutofillKey("name3", "value4"));
  keys2.insert(AutofillKey("name4", "value4"));
  AddToWds(wds2_, keys2);

  SetupSync();
  // Wait for client1 to get the new keys from client2.
  EXPECT_TRUE(client1()->AwaitSyncCycleCompletion("sync cycle"));

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));
  expected_keys.insert(AutofillKey("name1", "value2"));
  expected_keys.insert(AutofillKey("name2", "value3"));
  expected_keys.insert(AutofillKey("name3", "value4"));
  expected_keys.insert(AutofillKey("name4", "value4"));

  AutofillKeys wd1_keys;
  GetAllAutofillKeys(wds1_, &wd1_keys);
  EXPECT_EQ(expected_keys, wd1_keys);

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(expected_keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {
  SetupHarness();
  SetupSync();

  AutofillKeys add_one_key;
  add_one_key.insert(AutofillKey("name1", "value1"));
  AddToWds(wds1_, add_one_key);

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));

  EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));

  AutofillKeys keys;
  GetAllAutofillKeys(wds1_, &keys);
  EXPECT_EQ(expected_keys, keys);
  keys.clear();
  GetAllAutofillKeys(wds2_, &keys);
  EXPECT_EQ(expected_keys, keys);

  Cleanup();
}
<commit_msg>Embed unicode literals the correct way<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 <set>
#include <vector>

#include "base/command_line.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/waitable_event.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/browser/webdata/web_data_service_test_util.h"
#include "chrome/common/notification_observer_mock.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
#include "chrome/test/thread_observer_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/glue/form_field.h"

using base::WaitableEvent;
using testing::_;

namespace {

// Define these << operators so we can use EXPECT_EQ with the
// AutofillKeys type.
template<class T1, class T2, class T3>
std::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {
  typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;
  for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {
    os << *i << ", ";
  }
  return os;
}

std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
  return os << UTF16ToUTF8(key.name()) << ", " << UTF16ToUTF8(key.value());
}

class GetAllAutofillEntries
    : public base::RefCountedThreadSafe<GetAllAutofillEntries> {
 public:
  explicit GetAllAutofillEntries(WebDataService* web_data_service)
      : web_data_service_(web_data_service),
        done_event_(false, false) {}

  void Init() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
    ChromeThread::PostTask(
        ChromeThread::DB,
        FROM_HERE,
        NewRunnableMethod(this, &GetAllAutofillEntries::Run));
    done_event_.Wait();
  }

  const std::vector<AutofillEntry>& entries() const {
    return entries_;
  }

 private:
  friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;

  void Run() {
    DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
    web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);
    done_event_.Signal();
  }

  WebDataService* web_data_service_;
  base::WaitableEvent done_event_;
  std::vector<AutofillEntry> entries_;
};

ACTION_P(SignalEvent, event) {
  event->Signal();
}

class AutofillDBThreadObserverHelper : public DBThreadObserverHelper {
 protected:
  virtual void RegisterObservers() {
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_ENTRIES_CHANGED,
                   NotificationService::AllSources());
    registrar_.Add(&observer_,
                   NotificationType::AUTOFILL_PROFILE_CHANGED,
                   NotificationService::AllSources());
  }
};

}  // namespace;

class TwoClientLiveAutofillSyncTest : public LiveSyncTest {
 public:
  typedef std::set<AutofillKey> AutofillKeys;
  TwoClientLiveAutofillSyncTest()
      : name1_(ASCIIToUTF16("name1")),
        name2_(ASCIIToUTF16("name2")),
        value1_(ASCIIToUTF16("value1")),
        value2_(ASCIIToUTF16("value2")),
        done_event1_(false, false),
        done_event2_(false, false) {
    // This makes sure browser is visible and active while running test.
    InProcessBrowserTest::set_show_window(true);
    // Set the initial timeout value to 5 min.
    InProcessBrowserTest::SetInitialTimeoutInMS(300000);
  }
  ~TwoClientLiveAutofillSyncTest() {}

 protected:
  void SetupHarness() {
    client1_.reset(new ProfileSyncServiceTestHarness(
        browser()->profile(), username_, password_));
    profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
    client2_.reset(new ProfileSyncServiceTestHarness(
        profile2_.get(), username_, password_));
    wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
    wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);
  }

  void SetupSync() {
    EXPECT_TRUE(client1_->SetupSync());
    EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
    EXPECT_TRUE(client2_->SetupSync());
    EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
  }

  void Cleanup() {
    client2_.reset();
    profile2_.reset();
  }

  void AddToWds(WebDataService* wds, const AutofillKeys& keys) {
    std::vector<webkit_glue::FormField> form_fields;
    for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {
      form_fields.push_back(
          webkit_glue::FormField(string16(),
                                 (*i).name(),
                                 (*i).value(),
                                 string16()));
    }

    WaitableEvent done_event(false, false);
    scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(
        new AutofillDBThreadObserverHelper());
    observer_helper->Init();

    EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).
        WillOnce(SignalEvent(&done_event));
    wds->AddFormFields(form_fields);
    done_event.Wait();
  }

  void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {
    scoped_refptr<GetAllAutofillEntries> get_all_entries =
        new GetAllAutofillEntries(wds);
    get_all_entries->Init();
    const std::vector<AutofillEntry>& entries = get_all_entries->entries();

    for (size_t i = 0; i < entries.size(); ++i) {
      keys->insert(entries[i].key());
    }
  }

  ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
  ProfileSyncServiceTestHarness* client2() { return client2_.get(); }

  PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
  PrefService* prefs2() { return profile2_->GetPrefs(); }

  string16 name1_;
  string16 name2_;
  string16 value1_;
  string16 value2_;
  base::WaitableEvent done_event1_;
  base::WaitableEvent done_event2_;

  scoped_ptr<ProfileSyncServiceTestHarness> client1_;
  scoped_ptr<ProfileSyncServiceTestHarness> client2_;
  scoped_ptr<Profile> profile2_;
  WebDataService* wds1_;
  WebDataService* wds2_;

  DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);
};

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {
  SetupHarness();

  AutofillKeys keys;
  keys.insert(AutofillKey("name1", "value1"));
  keys.insert(AutofillKey("name1", "value2"));
  keys.insert(AutofillKey("name2", "value3"));
  keys.insert(AutofillKey(WideToUTF16(L"Sigur R\u00F3s"),
                          WideToUTF16(L"\u00C1g\u00E6tis byrjun")));
  AddToWds(wds1_, keys);

  SetupSync();

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {
  SetupHarness();

  AutofillKeys keys1;
  keys1.insert(AutofillKey("name1", "value1"));
  keys1.insert(AutofillKey("name1", "value2"));
  keys1.insert(AutofillKey("name2", "value3"));
  AddToWds(wds1_, keys1);

  AutofillKeys keys2;
  keys2.insert(AutofillKey("name1", "value2"));
  keys2.insert(AutofillKey("name2", "value3"));
  keys2.insert(AutofillKey("name3", "value4"));
  keys2.insert(AutofillKey("name4", "value4"));
  AddToWds(wds2_, keys2);

  SetupSync();
  // Wait for client1 to get the new keys from client2.
  EXPECT_TRUE(client1()->AwaitSyncCycleCompletion("sync cycle"));

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));
  expected_keys.insert(AutofillKey("name1", "value2"));
  expected_keys.insert(AutofillKey("name2", "value3"));
  expected_keys.insert(AutofillKey("name3", "value4"));
  expected_keys.insert(AutofillKey("name4", "value4"));

  AutofillKeys wd1_keys;
  GetAllAutofillKeys(wds1_, &wd1_keys);
  EXPECT_EQ(expected_keys, wd1_keys);

  AutofillKeys wd2_keys;
  GetAllAutofillKeys(wds2_, &wd2_keys);
  EXPECT_EQ(expected_keys, wd2_keys);

  Cleanup();
}

IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {
  SetupHarness();
  SetupSync();

  AutofillKeys add_one_key;
  add_one_key.insert(AutofillKey("name1", "value1"));
  AddToWds(wds1_, add_one_key);

  AutofillKeys expected_keys;
  expected_keys.insert(AutofillKey("name1", "value1"));

  EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));

  AutofillKeys keys;
  GetAllAutofillKeys(wds1_, &keys);
  EXPECT_EQ(expected_keys, keys);
  keys.clear();
  GetAllAutofillKeys(wds2_, &keys);
  EXPECT_EQ(expected_keys, keys);

  Cleanup();
}
<|endoftext|>


<commit_before>///
/// @file  S2LoadBalancer.hpp
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef S2LOADBALANCER_HPP
#define S2LOADBALANCER_HPP

#include <aligned_vector.hpp>
#include <int128.hpp>

#include <stdint.h>

namespace primecount {

class S2LoadBalancer
{
public:
  S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads);
  S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd);
  void init(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd);
  int64_t get_min_segment_size() const;
  double get_rsd() const;
  void update(int64_t low,
              int64_t threads,
              int64_t* segment_size,
              int64_t* segments_per_thread,
              aligned_vector<double>& timings);
private:
  void set_min_size(int64_t z);
  void update_avg_seconds(double seconds);
  void update_min_size(double divisor);
  double get_decrease_threshold(double seconds) const;
  bool increase_size(double seconds, double decrease) const;
  bool decrease_size(double seconds, double decrease) const;
  double x_;
  double y_;
  double z_;
  double rsd_;
  double avg_seconds_;
  double min_seconds_;
  double decrease_dividend_;
  int64_t min_size_;
  int64_t sqrtz_;
  int64_t count_;
  int64_t smallest_hard_leaf_;
};

} // namespace

#endif
<commit_msg>Refactoring<commit_after>///
/// @file  S2LoadBalancer.hpp
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef S2LOADBALANCER_HPP
#define S2LOADBALANCER_HPP

#include <aligned_vector.hpp>
#include <int128.hpp>

#include <stdint.h>

namespace primecount {

class S2LoadBalancer
{
public:
  S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads);
  S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd);
  void init(int64_t threads);
  int64_t get_min_segment_size() const;
  double get_rsd() const;
  void update(int64_t low,
              int64_t threads,
              int64_t* segment_size,
              int64_t* segments_per_thread,
              aligned_vector<double>& timings);
private:
  void set_min_size(int64_t z);
  void update_avg_seconds(double seconds);
  void update_min_size(double divisor);
  double get_decrease_threshold(double seconds) const;
  bool increase_size(double seconds, double decrease) const;
  bool decrease_size(double seconds, double decrease) const;
  double x_;
  double y_;
  double z_;
  double rsd_;
  double avg_seconds_;
  double min_seconds_;
  double decrease_dividend_;
  int64_t min_size_;
  int64_t count_;
  int64_t sqrtz_;
  int64_t smallest_hard_leaf_;
};

} // namespace

#endif
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010-2015 Raffaello D. Di Napoli

This file is part of Abaclade.

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

Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

/*! @file
Stack tracing infrastructure. */

#ifndef _ABACLADE_HXX_INTERNAL
   #error "Please #include <abaclade.hxx> instead of this file"
#endif

/*! @page stack-tracing Stack tracing
Automatic generation of stack traces whenever an exception occurs.

Any function that is not of negligible size and is not an hotspot should invoke, as its first line,
ABC_TRACE_FUNC(arg1, arg2, …) in order to have its name show up in a post-exception stack trace.

ABC_TRACE_FUNC() initializes a local variable of type abc::detail::scope_trace which will store
references to every provided argument.

abc::detail::scope_trace::~scope_trace() detects if the object is being destroyed due to an
exceptional stack unwinding, in which case it will dump its contents into a thread-local stack trace
buffer. The outermost catch block (main-level) will output the generated stack trace, if available,
using abc::exception::write_with_scope_trace().

When an abc::exception is thrown (it becomes “in-flight”), it will request that the stack trace
buffer be cleared and it will count itself a a reference to the new trace; when copied, the number
of references will increase if the source was in-flight, in which case the copy will also consider
itself in-flight; when an exception is destroyed, it will release a reference to the stack trace
buffer if it was holding one. Reference counting is necessary due to platform-specific code that
will copy a thrown exception to non-local storage and throwing that one instead of using the
original one.

This covers the following code flows:

•  No exception thrown: no stack trace is generated.

•  Exception is thrown and escapes past abc::app::main(): each abc::detail::scope_trace adds itself
   to the stack trace, which is then output; the exception is then destroyed, cleaning the trace
   buffer.

•  Exception is thrown, then caught and blocked: one or more abc::detail::scope_trace might add
   themselves to the stack trace, but the exception is blocked before it escapes abc::app::main(),
   so no output occurs.

•  Exception is thrown, then caught and rethrown: one or more abc::detail::scope_trace might add
   themselves to the stack trace, up to the point the exception is caught. Since the exception is
   not destroyed, the stack trace buffer will keep the original point at which the exception was
   thrown, resulting in an accurate stack trace in case the exception reaches main().

•  Exception is thrown, then caught and a new one is thrown: similar to the previous case, except
   the original exception is destroyed, so the stack trace buffer will not reveal where the original
   exception was thrown. This is acceptable, since it cannot be determined whether the two
   exceptions were related.

See related diagram doc/Stack_trace_generation.svg for all code flows covered by this design.
See also ABC_THROW() and abc::exception for the remainder of the implementation.

Currently unsupported:

•  TODO: storing a thrown exception, handling a different exception, and throwing back the first
   one. In the current implementation, there’s nothing telling an exception that it’s no longer
   in-flight (and there can’t be!); additionally, throwing the second exception and re-throwing the
   first one (using throw x; instead of throw; because it’s no longer in-flight) will both reset the
   stack trace buffer.

•  TODO: properly handling exceptions occurring while generating a stack trace. The current behavior
   swallows any nested exceptions, gracefully failing to generate a complete stack trace. */

////////////////////////////////////////////////////////////////////////////////////////////////////

/*! Provides stack frame logging for the function in which it’s used.

@param ...
   Arguments or variables to trace.
*/
#define ABC_TRACE_FUNC(...) \
   _ABC_TRACE_SCOPE_IMPL( \
      ABC_CPP_APPEND_UID(_scope_trace_), ABC_CPP_APPEND_UID(_scope_trace_tuple_), \
      ABC_CPP_APPEND_UID(_scope_trace_source_location_), __VA_ARGS__ \
   )

/*! @cond
Implementation of ABC_TRACE_FUNC() and similar macros. */
#define _ABC_TRACE_SCOPE_IMPL(st, tuple, srcloc, ...) \
   static ::abc::detail::scope_trace_source_location const srcloc = { \
      ABC_THIS_FUNC, ABC_SL(__FILE__), __LINE__ \
   }; \
   auto tuple(::abc::detail::scope_trace_tuple::make(__VA_ARGS__)); \
   ::abc::detail::scope_trace st(&srcloc, &tuple)
//! @endcond
<commit_msg>Use a single UID for each _ABC_TRACE_SCOPE_IMPL()<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010-2015 Raffaello D. Di Napoli

This file is part of Abaclade.

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

Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

/*! @file
Stack tracing infrastructure. */

#ifndef _ABACLADE_HXX_INTERNAL
   #error "Please #include <abaclade.hxx> instead of this file"
#endif

/*! @page stack-tracing Stack tracing
Automatic generation of stack traces whenever an exception occurs.

Any function that is not of negligible size and is not an hotspot should invoke, as its first line,
ABC_TRACE_FUNC(arg1, arg2, …) in order to have its name show up in a post-exception stack trace.

ABC_TRACE_FUNC() initializes a local variable of type abc::detail::scope_trace which will store
references to every provided argument.

abc::detail::scope_trace::~scope_trace() detects if the object is being destroyed due to an
exceptional stack unwinding, in which case it will dump its contents into a thread-local stack trace
buffer. The outermost catch block (main-level) will output the generated stack trace, if available,
using abc::exception::write_with_scope_trace().

When an abc::exception is thrown (it becomes “in-flight”), it will request that the stack trace
buffer be cleared and it will count itself a a reference to the new trace; when copied, the number
of references will increase if the source was in-flight, in which case the copy will also consider
itself in-flight; when an exception is destroyed, it will release a reference to the stack trace
buffer if it was holding one. Reference counting is necessary due to platform-specific code that
will copy a thrown exception to non-local storage and throwing that one instead of using the
original one.

This covers the following code flows:

•  No exception thrown: no stack trace is generated.

•  Exception is thrown and escapes past abc::app::main(): each abc::detail::scope_trace adds itself
   to the stack trace, which is then output; the exception is then destroyed, cleaning the trace
   buffer.

•  Exception is thrown, then caught and blocked: one or more abc::detail::scope_trace might add
   themselves to the stack trace, but the exception is blocked before it escapes abc::app::main(),
   so no output occurs.

•  Exception is thrown, then caught and rethrown: one or more abc::detail::scope_trace might add
   themselves to the stack trace, up to the point the exception is caught. Since the exception is
   not destroyed, the stack trace buffer will keep the original point at which the exception was
   thrown, resulting in an accurate stack trace in case the exception reaches main().

•  Exception is thrown, then caught and a new one is thrown: similar to the previous case, except
   the original exception is destroyed, so the stack trace buffer will not reveal where the original
   exception was thrown. This is acceptable, since it cannot be determined whether the two
   exceptions were related.

See related diagram doc/Stack_trace_generation.svg for all code flows covered by this design.
See also ABC_THROW() and abc::exception for the remainder of the implementation.

Currently unsupported:

•  TODO: storing a thrown exception, handling a different exception, and throwing back the first
   one. In the current implementation, there’s nothing telling an exception that it’s no longer
   in-flight (and there can’t be!); additionally, throwing the second exception and re-throwing the
   first one (using throw x; instead of throw; because it’s no longer in-flight) will both reset the
   stack trace buffer.

•  TODO: properly handling exceptions occurring while generating a stack trace. The current behavior
   swallows any nested exceptions, gracefully failing to generate a complete stack trace. */

////////////////////////////////////////////////////////////////////////////////////////////////////

/*! Provides stack frame logging for the function in which it’s used.

@param ...
   Arguments or variables to trace.
*/
#define ABC_TRACE_FUNC(...) \
   _ABC_TRACE_SCOPE_IMPL(ABC_CPP_APPEND_UID(__scope_trace_), __VA_ARGS__)

/*! Implementation of ABC_TRACE_FUNC() and similar macros.

@param uid
   Unique ID for this scope trace.
@param ...
   Arguments or variables to trace.
*/
#define _ABC_TRACE_SCOPE_IMPL(uid, ...) \
   static ::abc::detail::scope_trace_source_location const ABC_CPP_CAT(uid, _srcloc) = { \
      ABC_THIS_FUNC, ABC_SL(__FILE__), __LINE__ \
   }; \
   auto ABC_CPP_CAT(uid, _tuple)(::abc::detail::scope_trace_tuple::make(__VA_ARGS__)); \
   ::abc::detail::scope_trace uid(&ABC_CPP_CAT(uid, _srcloc), &ABC_CPP_CAT(uid, _tuple))
<|endoftext|>