text:
datasciencecoursera
===================

Coursework repository for Coursera "Data Science Specialization" Track

redpajama_set_name: RedPajamaGithub


text:
class Ability
  include CanCan::Ability

  def initialize(user)
    can :manage, Task, user_id: user.id
  end
end


text:
package com.intellij.execution.testframework.autotest;

import com.intellij.execution.DelayedDocumentWatcher;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessListener;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionUtil;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.content.Content;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * @author yole
 */
public class AutoTestManager {
  private static final String AUTO_TEST_MANAGER_DELAY = "auto.test.manager.delay";
  private static final int AUTO_TEST_MANAGER_DELAY_DEFAULT = 3000;

  private static final Key<ProcessListener> ON_TERMINATION_RESTARTER_KEY = Key.create("auto.test.manager.on.termination.restarter");
  private static final Key<ExecutionEnvironment> EXECUTION_ENVIRONMENT_KEY = Key.create("auto.test.manager.execution.environment");

  private final Project myProject;
  private int myDelayMillis;
  private DelayedDocumentWatcher myDocumentWatcher;

  @NotNull
  public static AutoTestManager getInstance(Project project) {
    return ServiceManager.getService(project, AutoTestManager.class);
  }

  public AutoTestManager(@NotNull Project project) {
    myProject = project;
    myDelayMillis = StringUtilRt.parseInt(PropertiesComponent.getInstance(project).getValue(AUTO_TEST_MANAGER_DELAY), AUTO_TEST_MANAGER_DELAY_DEFAULT);
    myDocumentWatcher = createWatcher();
  }

  @NotNull
  private DelayedDocumentWatcher createWatcher() {
    return new DelayedDocumentWatcher(myProject, myDelayMillis, new Consumer<Integer>() {
      @Override
      public void consume(Integer modificationStamp) {
        restartAllAutoTests(modificationStamp);
      }
    }, new Condition<VirtualFile>() {
      @Override
      public boolean value(VirtualFile file) {
        // Vladimir.Krivosheev - I don't know, why AutoTestManager checks it, but old behavior is preserved
        return FileEditorManager.getInstance(myProject).isFileOpen(file);
      }
    });
  }

  public void setAutoTestEnabled(@NotNull RunContentDescriptor descriptor, @NotNull ExecutionEnvironment environment, boolean enabled) {
    Content content = descriptor.getAttachedContent();
    if (content != null) {
      if (enabled) {
        EXECUTION_ENVIRONMENT_KEY.set(content, environment);
        myDocumentWatcher.activate();
      }
      else {
        EXECUTION_ENVIRONMENT_KEY.set(content, null);
        if (!hasEnabledAutoTests()) {
          myDocumentWatcher.deactivate();
        }
        ProcessHandler processHandler = descriptor.getProcessHandler();
        if (processHandler != null) {
          clearRestarterListener(processHandler);
        }
      }
    }
  }

  private boolean hasEnabledAutoTests() {
    RunContentManager contentManager = ExecutionManager.getInstance(myProject).getContentManager();
    for (RunContentDescriptor descriptor : contentManager.getAllDescriptors()) {
      if (isAutoTestEnabledForDescriptor(descriptor)) {
        return true;
      }
    }
    return false;
  }

  public boolean isAutoTestEnabled(@NotNull RunContentDescriptor descriptor) {
    return isAutoTestEnabledForDescriptor(descriptor);
  }

  private static boolean isAutoTestEnabledForDescriptor(@NotNull RunContentDescriptor descriptor) {
    Content content = descriptor.getAttachedContent();
    if (content != null) {
      ExecutionEnvironment watched = EXECUTION_ENVIRONMENT_KEY.get(content);
      if (watched != null) {
        ExecutionEnvironment current = getCurrentEnvironment(content);
        boolean result = current != null && equals(current, watched);
        if (!result) {
          // let GC do its work
          EXECUTION_ENVIRONMENT_KEY.set(content, null);
        }
        return result;
      }
    }
    return false;
  }

  @Nullable
  private static ExecutionEnvironment getCurrentEnvironment(@NotNull Content content) {
    JComponent component = content.getComponent();
    if (component == null) {
      return null;
    }
    return LangDataKeys.EXECUTION_ENVIRONMENT.getData(DataManager.getInstance().getDataContext(component));
  }

  private static boolean equals(@NotNull ExecutionEnvironment env1, @NotNull ExecutionEnvironment env2) {
    return env1.getRunProfile() == env2.getRunProfile() &&
           env1.getRunner() == env2.getRunner() &&
           env1.getExecutor() == env2.getExecutor() &&
           env1.getExecutionTarget() == env2.getExecutionTarget();
  }

  private static void clearRestarterListener(@NotNull ProcessHandler processHandler) {
    ProcessListener restarterListener = ON_TERMINATION_RESTARTER_KEY.get(processHandler, null);
    if (restarterListener != null) {
      processHandler.removeProcessListener(restarterListener);
      ON_TERMINATION_RESTARTER_KEY.set(processHandler, null);
    }
  }

  private void restartAllAutoTests(int modificationStamp) {
    RunContentManager contentManager = ExecutionManager.getInstance(myProject).getContentManager();
    boolean active = false;
    for (RunContentDescriptor descriptor : contentManager.getAllDescriptors()) {
      if (isAutoTestEnabledForDescriptor(descriptor)) {
        restartAutoTest(descriptor, modificationStamp, myDocumentWatcher);
        active = true;
      }
    }
    if (!active) {
      myDocumentWatcher.deactivate();
    }
  }

  private static void restartAutoTest(@NotNull RunContentDescriptor descriptor,
                                      int modificationStamp,
                                      @NotNull DelayedDocumentWatcher documentWatcher) {
    ProcessHandler processHandler = descriptor.getProcessHandler();
    if (processHandler != null && !processHandler.isProcessTerminated()) {
      scheduleRestartOnTermination(descriptor, processHandler, modificationStamp, documentWatcher);
    }
    else {
      restart(descriptor);
    }
  }

  private static void scheduleRestartOnTermination(@NotNull final RunContentDescriptor descriptor,
                                                   @NotNull final ProcessHandler processHandler,
                                                   final int modificationStamp,
                                                   @NotNull final DelayedDocumentWatcher documentWatcher) {
    ProcessListener restarterListener = ON_TERMINATION_RESTARTER_KEY.get(processHandler);
    if (restarterListener != null) {
      clearRestarterListener(processHandler);
    }
    restarterListener = new ProcessAdapter() {
      @Override
      public void processTerminated(ProcessEvent event) {
        clearRestarterListener(processHandler);
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            if (isAutoTestEnabledForDescriptor(descriptor) && documentWatcher.isUpToDate(modificationStamp)) {
              restart(descriptor);
            }
          }
        }, ModalityState.any());
      }
    };
    ON_TERMINATION_RESTARTER_KEY.set(processHandler, restarterListener);
    processHandler.addProcessListener(restarterListener);
  }

  private static void restart(@NotNull RunContentDescriptor descriptor) {
    descriptor.setActivateToolWindowWhenAdded(false);
    descriptor.setReuseToolWindowActivation(true);
    ExecutionUtil.restart(descriptor);
  }

  int getDelay() {
    return myDelayMillis;
  }

  void setDelay(int delay) {
    myDelayMillis = delay;
    myDocumentWatcher.deactivate();
    myDocumentWatcher = createWatcher();
    if (hasEnabledAutoTests()) {
      myDocumentWatcher.activate();
    }
    PropertiesComponent.getInstance(myProject).setValue(AUTO_TEST_MANAGER_DELAY, myDelayMillis, AUTO_TEST_MANAGER_DELAY_DEFAULT);
  }
}


text:
/**
 *
 */
package info.rmapproject.core.exception;

/**
 * Exception occurs when a User attempts to update a DiSCO version that is no longer active.
 *
 * @author khanson
 */
public class RMapInactiveVersionException extends RuntimeException {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -2993203728345433963L;

	/**
	 * Instantiates a new RMap inactive version exception.
	 */
	public RMapInactiveVersionException() {
		super();
	}

	/**
	 * Instantiates a new RMap inactive version exception.
	 *
	 * @param message the message
	 */
	public RMapInactiveVersionException(String message) {
		super(message);
	}

	/**
	 * Instantiates a new RMap inactive version exception.
	 *
	 * @param cause the cause
	 */
	public RMapInactiveVersionException(Throwable cause) {
		super(cause);
	}

	/**
	 * Instantiates a new RMap inactive version exception.
	 *
	 * @param message the message
	 * @param cause the cause
	 */
	public RMapInactiveVersionException(String message, Throwable cause) {
		super(message, cause);
	}

	/**
	 * Instantiates a new RMap inactive version exception.
	 *
	 * @param message the message
	 * @param cause the cause
	 * @param enableSuppression
	 * @param writableStackTrace
	 */
	public RMapInactiveVersionException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

}


text:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package net.maehtricks.libspykeej.util;

public class DebugUtil {
    // The number of characters decoded per line in the hex dump
    private static final int CHARS_PER_LINE = 32;

    // After this many characters in the hex dump, an extra space is inserted
    // (this must be a power of two).
    private static final int EXTRA_SPACE_FREQ = 8;
    private static final int EXTRA_SPACE_MASK = EXTRA_SPACE_FREQ - 1;

    public static void showBuffer(String tag, byte[] bytes, int len) {
        if (len > 256) {
            len = 256;
        }
        int charsPerLine = CHARS_PER_LINE;
        if (len < charsPerLine) {
            charsPerLine = len;
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; i += charsPerLine) {
            builder.append(tag + " ");
            for (int j = 0; j < charsPerLine; j++) {
                if (i + j >= len) {
                    break;
                }
                byte val = bytes[i + j];
                builder.append(String.format("%02x ", val));
                if ((j & EXTRA_SPACE_MASK) == EXTRA_SPACE_MASK) {
                    builder.append(' ');
                }
            }
            if (len - i < charsPerLine) {
                for (int j = len - i; j < charsPerLine; j++) {
                    builder.append("   ");
                    if ((j & EXTRA_SPACE_MASK) == EXTRA_SPACE_MASK) {
                        builder.append(' ');
                    }
                }
            }

            // Put an extra space before the ascii character dump
            builder.append(' ');
            for (int j = 0; j < charsPerLine; j++) {
                if (i + j >= len) {
                    break;
                }
                byte val = bytes[i + j];
                if (val < 0x20 || val > 0x7e) {
                    val = '.';
                }
                builder.append(String.format("%c", val));
                if ((j & EXTRA_SPACE_MASK) == EXTRA_SPACE_MASK) {
                    builder.append(' ');
                }
            }
            System.out.println(builder.toString());
            builder.setLength(0);
        }
    }
}


text:
#ifndef NODERB_DEFER_H
#define	NODERB_DEFER_H

#ifdef	__cplusplus
extern "C" {
#endif

VALUE nodeRb_defer(VALUE self, VALUE worker, VALUE callback);

#ifdef	__cplusplus
}
#endif

#endif	/* NODERB_DEFER_H */


text:
<TITLE>Review for L.A. Story (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

L.A. Story (1991)

reviewed by
Steve Rhodes

L.A. STORY
                     A film review by Steve Rhodes
                      Copyright 1997 Steve Rhodes

RATING (0 TO ****):  *** 1/2

     L.A. STORY (1991), a beautiful parody and homage written by and
starring Steve Martin, opens to a carefully choreographed water ballet
of lawn sprinklers.

     As L.A. wakes for another morning of glorious California sun, the
image is subtitled "Los Angeles, California, Temperature 72 degrees."
We see Los Angelenos going about their morning routines, switching from
one sleepy guy in shorts busily dragging his Christmas tree to the curb
to a suit who chats away on his cell phone as the stretched limo he is
riding in is being towed.

     "I live in Los Angeles, and I've had 7 heart attacks -- all
imagined," explains meteorologist Harris K. Telemacher (Steve Martin).
"That is to say, I was deeply unhappy, but I didn't know it because I
was happy all the time."

     "When the weather dropped to 58 degrees this weekend, how did you
cope?" asks Harris in a man-on-the-street interview.  As a wacky
television weatherman, he fits right in with the area's "culture."
Even so, he is almost fired by the show's producer, played devilishly
by a candy sucking and Hawaiian shirt wearing Woody Harrelson, when the
producer claims Harris was doing some intellectual thing during another
of his slapstickish weather reports.

     In a film so rich that it would take at least three viewings to
sift through all of the humor and subtleties, the show's subtext is
highly romantic and poignant.  The humor is presented with such
delicious seriousness that it becomes almost an anthropological
exploration of West Coast tribes.  ("Hi, my name is Bob," chirps Dennis
Dragon as a saccharinely polite thief.  "I'll be your robber.")  The
resulting film by director Mick Jackson is so funny that I could not
control myself at times -- one belly laugh would not subside before
another began.

     In a completely plastic city, where Harris drives a hundred yards
to his next door neighbor's house, he meets his would-be wife, Sara
McDowel (Victoria Tennant), who has just arrived from her home in
London.  She shocks the locals by saying exactly what is on her mind.

     When not attempting to date someone his own age, Harris goes out
with Sandy, who, after all, is just "4 years shy of 27."  Although the
credits list her as "Sandy," she carefully writes her name for Harris
as "SanDeE" with a star at the end and a heart encasing the name.
Sarah Jessica Parker, who has been too often miscast as she was in THE
SUBSTANCE OF FIRE, plays free spirit SanDeE with perfection.  The woman
is incapable of standing still and constantly dances and twirls, while
throwing her long, curly hair about.  Having not a care in the world
and not burdened with excessive brain power, she lives an experiential
lifestyle.

     An electronic highway sign plays perhaps the sweetest, and
certainly the most unusual character in the story.  The sign gives
Harris prescient advice and even speaks in riddles -- unscramble "How
Daddy is Doing," commands the sign.

     The show is full of well chosen cameos by known actors playing
against type.  Rick Moranis, in a Hamlet take-off, appears as a
gravedigger with a thick English accent.  Best is Patrick Stewart as
the maitre d' of a restaurant so exclusive that Harris has to accompany
him to the maitre d's bank (Fourth Reich of Hamburg) to review Harris's
financial statement before he can get a reservation.  And since his is
deemed deficient in several areas, he can order only a limited number
of items on the menu, and certainly not the duck.

     Thanks to the sparkling and romantic cinematography by Andrew
Dunn, the picture has a magical sense of wonderment about life.  Amidst
all the humor is a sensitive story about a man in search of meaning for
his life.  And in a quest for love.  ("Forget for this moment the smog
and the cars and the restaurant and the skating and remember only this.
A kiss may not be the truth, but it is what we wish were true.")

     "Wow, that was something!" says Harris as the show draws to its
delightful conclusion.  "That was really something!"  As my newfound
friends faded away, I thought, "My sentiments exactly!"

     L.A. STORY runs a fast 1:35.  It is rated PG-13 for very brief
nudity and a little profanity.  The show has so much mature humor that
I think kids would need to be nine or ten to appreciate it.  I strongly
recommend this gem to you and give it *** 1/2.

**** = A must see film.
***  = Excellent show.  Look for it.
**   = Average movie.  Kind of enjoyable.
*    = Poor show.  Don't waste your money.
0    = Totally and painfully unbearable picture.

REVIEW WRITTEN ON: July 5, 1997

Opinions expressed are mine and not meant to reflect my employer's.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
(function(scope) {

// Old versions of iOS do not have bind.

if (!Function.prototype.bind) {
  Function.prototype.bind = function(scope) {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);
    return function() {
      var args2 = args.slice();
      args2.push.apply(args2, arguments);
      return self.apply(scope, args2);
    };
  };
}

})(window.WebComponents);


text:
package stack

import (
	"github.com/stretchr/testify/assert"
	"sync"
	"testing"
)

func TestNewStack(t *testing.T) {
	s := NewStack()
	assert.Equal(t, 0, s.Len(), "Expect the length of Queue is 0")
}

func TestPush(t *testing.T) {
	s := NewStack()
	s.Push(99)

	assert.Equal(t, 1, s.Len(), "Expect the length of Queue is 1")
}

func TestPop(t *testing.T) {
	s := NewStack()
	assert.Equal(t, nil, s.Pop(), "Expect the value of stack is nil")
	assert.Equal(t, 0, s.Len(), "Expect the length of Queue is 0")

	s.Push(99)
	assert.Equal(t, 1, s.Len(), "Expect the length of Queue is 1")
	data := s.Pop()
	assert.Equal(t, 99, data, "Expect the value of stack is 99")
	assert.Equal(t, 0, s.Len(), "Expect the length of Queue is 0")

}

func TestPeek(t *testing.T) {
	s := NewStack()
	assert.Equal(t, nil, s.Peek(), "Expect the value of stack is nil")
	assert.Equal(t, 0, s.Len(), "Expect the length of Queue is 0")

	s.Push(99)
	assert.Equal(t, 1, s.Len(), "Expect the length of Queue is 1")
	data := s.Peek()
	assert.Equal(t, 99, data, "Expect the value of stack is 99")
	assert.Equal(t, 1, s.Len(), "Expect the length of Queue is 1")
}

//--Concurrent tests

func TestConcurrent(t *testing.T) {
	s := NewStack()
	numberGoRoutines := 50
	numberOfPushes := 10000
	var wg sync.WaitGroup
	for i := 0; i < numberGoRoutines; i++ {
		wg.Add(1)
		go func() {
			for j := 0; j < numberOfPushes; j++ {
				s.Push(j)
			}
			wg.Done()
		}()
	}
	wg.Wait()
	assert.Equal(t, numberGoRoutines*numberOfPushes, s.Len(), "Expected length of queue is product of numberGoRoutines and numberOfPushes ")
}


text:
package tastytest

object TestDependentExtension {
  import DependentExtension._

  def test = {
    val box = new Box {
      type Repr = Int
      val value: Int = 23
    }
    val res = implicitly[DependentExtension].extract(box)(_ + 1)
    assert(res == 24)
  }

}


text:
// Tests for the ScrollAnimator class.

#include "third_party/blink/renderer/core/scroll/scroll_animator.h"

#include "base/single_thread_task_runner.h"
#include "base/test/test_mock_time_task_runner.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"

namespace blink {

using testing::AtLeast;
using testing::Return;
using testing::_;

namespace {

double NowTicksInSeconds(const base::TestMockTimeTaskRunner* task_runner) {
  return task_runner->NowTicks().since_origin().InSecondsF();
}

}  // namespace

class MockScrollableAreaForAnimatorTest
    : public GarbageCollected<MockScrollableAreaForAnimatorTest>,
      public ScrollableArea {
  USING_GARBAGE_COLLECTED_MIXIN(MockScrollableAreaForAnimatorTest);

 public:
  explicit MockScrollableAreaForAnimatorTest(bool scroll_animator_enabled,
                                             const ScrollOffset& min_offset,
                                             const ScrollOffset& max_offset)
      : scroll_animator_enabled_(scroll_animator_enabled),
        min_offset_(min_offset),
        max_offset_(max_offset) {}

  MOCK_CONST_METHOD0(VisualRectForScrollbarParts, LayoutRect());
  MOCK_CONST_METHOD0(IsActive, bool());
  MOCK_CONST_METHOD0(IsThrottled, bool());
  MOCK_CONST_METHOD1(ScrollSize, int(ScrollbarOrientation));
  MOCK_CONST_METHOD0(IsScrollCornerVisible, bool());
  MOCK_CONST_METHOD0(ScrollCornerRect, IntRect());
  MOCK_METHOD2(UpdateScrollOffset,
               void(const ScrollOffset&, mojom::blink::ScrollType));
  MOCK_METHOD0(ScrollControlWasSetNeedsPaintInvalidation, void());
  MOCK_CONST_METHOD0(EnclosingScrollableArea, ScrollableArea*());
  MOCK_CONST_METHOD1(VisibleContentRect, IntRect(IncludeScrollbarsInRect));
  MOCK_CONST_METHOD0(ContentsSize, IntSize());
  MOCK_CONST_METHOD0(ScrollbarsCanBeActive, bool());
  MOCK_METHOD0(RegisterForAnimation, void());
  MOCK_METHOD0(ScheduleAnimation, bool());
  MOCK_CONST_METHOD0(UsedColorScheme, WebColorScheme());

  bool UserInputScrollable(ScrollbarOrientation) const override { return true; }
  bool ShouldPlaceVerticalScrollbarOnLeft() const override { return false; }
  IntSize ScrollOffsetInt() const override { return IntSize(); }
  int VisibleHeight() const override { return 768; }
  int VisibleWidth() const override { return 1024; }
  CompositorElementId GetScrollElementId() const override {
    return CompositorElementId();
  }
  bool ScrollAnimatorEnabled() const override {
    return scroll_animator_enabled_;
  }
  int PageStep(ScrollbarOrientation) const override { return 0; }
  IntSize MinimumScrollOffsetInt() const override {
    return FlooredIntSize(min_offset_);
  }
  IntSize MaximumScrollOffsetInt() const override {
    return FlooredIntSize(max_offset_);
  }

  void SetScrollAnimator(ScrollAnimator* scroll_animator) {
    animator = scroll_animator;
  }

  ScrollOffset GetScrollOffset() const override {
    if (animator)
      return animator->CurrentOffset();
    return ScrollableArea::GetScrollOffset();
  }

  void SetScrollOffset(const ScrollOffset& offset,
                       mojom::blink::ScrollType type,
                       mojom::blink::ScrollBehavior behavior =
                           mojom::blink::ScrollBehavior::kInstant,
                       ScrollCallback on_finish = ScrollCallback()) override {
    if (animator)
      animator->SetCurrentOffset(offset);
    ScrollableArea::SetScrollOffset(offset, type, behavior,
                                    std::move(on_finish));
  }

  scoped_refptr<base::SingleThreadTaskRunner> GetTimerTaskRunner() const final {
    if (!timer_task_runner_) {
      timer_task_runner_ =
          blink::scheduler::GetSingleThreadTaskRunnerForTesting();
    }
    return timer_task_runner_;
  }

  ScrollbarTheme& GetPageScrollbarTheme() const override {
    return ScrollbarTheme::GetTheme();
  }

  void Trace(Visitor* visitor) override {
    visitor->Trace(animator);
    ScrollableArea::Trace(visitor);
  }

  void DisposeImpl() override { timer_task_runner_.reset(); }

 private:
  bool scroll_animator_enabled_;
  ScrollOffset min_offset_;
  ScrollOffset max_offset_;
  Member<ScrollAnimator> animator;
  mutable scoped_refptr<base::SingleThreadTaskRunner> timer_task_runner_;
};

class TestScrollAnimator : public ScrollAnimator {
 public:
  TestScrollAnimator(ScrollableArea* scrollable_area,
                     const base::TickClock* tick_clock)
      : ScrollAnimator(scrollable_area, tick_clock) {}
  ~TestScrollAnimator() override = default;

  void SetShouldSendToCompositor(bool send) {
    should_send_to_compositor_ = send;
  }

  bool SendAnimationToCompositor() override {
    if (should_send_to_compositor_) {
      run_state_ =
          ScrollAnimatorCompositorCoordinator::RunState::kRunningOnCompositor;
      compositor_animation_id_ = 1;
      return true;
    }
    return false;
  }

 protected:
  void AbortAnimation() override {}

 private:
  bool should_send_to_compositor_ = false;
};

static void Reset(ScrollAnimator& scroll_animator) {
  scroll_animator.ScrollToOffsetWithoutAnimation(ScrollOffset());
}

// TODO(skobes): Add unit tests for composited scrolling paths.

TEST(ScrollAnimatorTest, MainThreadStates) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(2);
  // Once from userScroll, once from updateCompositorAnimations.
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(2);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  // Idle
  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::kIdle);

  // WaitingToSendToCompositor
  scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                              FloatSize(10, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToSendToCompositor);

  // RunningOnMainThread
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);

  // PostAnimationCleanup
  scroll_animator->CancelAnimation();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);

  // Idle
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::kIdle);

  Reset(*scroll_animator);

  // Forced GC in order to finalize objects depending on the mock object.
  ThreadState::Current()->CollectAllGarbageForTesting();
}

TEST(ScrollAnimatorTest, MainThreadEnabled) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(9);
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(6);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());

  ScrollResult result = scroll_animator->UserScroll(
      ScrollGranularity::kScrollByLine, FloatSize(-100, 0),
      ScrollableArea::ScrollCallback());
  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_FALSE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(-100.0f, result.unused_scroll_delta_x);

  result = scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                                       FloatSize(100, 0),
                                       ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);

  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));

  EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
  EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByPage,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());

  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));

  EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
  EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByPixel,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());

  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));

  EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
  EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());

  task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1.0));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));

  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());

  Reset(*scroll_animator);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByPrecisePixel,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());

  EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
  EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);
}

// Test that a smooth scroll offset animation is aborted when followed by a
// non-smooth scroll offset animation.
TEST(ScrollAnimatorTest, AnimatedScrollAborted) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(3);
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(2);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());

  // Smooth scroll.
  ScrollResult result = scroll_animator->UserScroll(
      ScrollGranularity::kScrollByLine, FloatSize(100, 0),
      ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
  EXPECT_TRUE(scroll_animator->HasRunningAnimation());

  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));

  EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
  EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());

  float x = scroll_animator->CurrentOffset().Width();

  // Instant scroll.
  result = scroll_animator->UserScroll(ScrollGranularity::kScrollByPrecisePixel,
                                       FloatSize(100, 0),
                                       ScrollableArea::ScrollCallback());
  EXPECT_TRUE(result.did_scroll_x);
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_FALSE(scroll_animator->HasRunningAnimation());
  EXPECT_EQ(x + 100, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());

  Reset(*scroll_animator);
}

// Test that a smooth scroll offset animation running on the compositor is
// completed on the main thread.
TEST(ScrollAnimatorTest, AnimatedScrollTakeover) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  TestScrollAnimator* scroll_animator =
      MakeGarbageCollected<TestScrollAnimator>(scrollable_area,
                                               task_runner->GetMockTickClock());

  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(2);
  // Called from userScroll, updateCompositorAnimations, then
  // takeOverCompositorAnimation (to re-register after RunningOnCompositor).
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(3);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());

  // Smooth scroll.
  ScrollResult result = scroll_animator->UserScroll(
      ScrollGranularity::kScrollByLine, FloatSize(100, 0),
      ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
  EXPECT_TRUE(scroll_animator->HasRunningAnimation());

  // Update compositor animation.
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->SetShouldSendToCompositor(true);
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnCompositor);

  // Takeover.
  scroll_animator->TakeOverCompositorAnimation();
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kRunningOnCompositorButNeedsTakeover);

  // Animation should now be running on the main thread.
  scroll_animator->SetShouldSendToCompositor(false);
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
  EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);
}

TEST(ScrollAnimatorTest, Disabled) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          false, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(8);
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(0);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByPage,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByDocument,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);

  scroll_animator->UserScroll(ScrollGranularity::kScrollByPixel,
                              FloatSize(100, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);
}

// Test that cancelling an animation resets the animation state.
// See crbug.com/598548.
TEST(ScrollAnimatorTest, CancellingAnimationResetsState) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  // Called from first userScroll, setCurrentOffset, and second userScroll.
  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(3);
  // Called from userScroll, updateCompositorAnimations.
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(4);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_EQ(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());

  // WaitingToSendToCompositor
  scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                              FloatSize(10, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToSendToCompositor);

  // RunningOnMainThread
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);

  // Amount scrolled so far.
  float offset_x = scroll_animator->CurrentOffset().Width();

  // Interrupt user scroll.
  scroll_animator->CancelAnimation();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);

  // Another userScroll after modified scroll offset.
  scroll_animator->SetCurrentOffset(ScrollOffset(offset_x + 15, 0));
  scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                              FloatSize(10, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToSendToCompositor);

  // Finish scroll animation.
  task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);

  EXPECT_EQ(offset_x + 15 + 10, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);
}

// Test that the callback passed to UserScroll function will be run when the
// animation is canceled or finished when the scroll is sent to main thread.
TEST(ScrollAnimatorTest, UserScrollCallBackAtAnimationFinishOnMainThread) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  // Called from first userScroll, setCurrentOffset, and second userScroll.
  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(3);
  // Called from userScroll, updateCompositorAnimations.
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(4);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_EQ(0, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());

  // WaitingToSendToCompositor
  bool finished = false;
  scroll_animator->UserScroll(
      ScrollGranularity::kScrollByLine, FloatSize(10, 0),
      ScrollableArea::ScrollCallback(
          base::BindOnce([](bool* finished) { *finished = true; }, &finished)));
  EXPECT_FALSE(finished);
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToSendToCompositor);

  // RunningOnMainThread
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_FALSE(finished);
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));

  // Amount scrolled so far.
  float offset_x = scroll_animator->CurrentOffset().Width();

  // Interrupt user scroll.
  scroll_animator->CancelAnimation();
  EXPECT_TRUE(finished);
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);

  // Another userScroll after modified scroll offset.
  scroll_animator->SetCurrentOffset(ScrollOffset(offset_x + 15, 0));
  scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                              FloatSize(10, 0),
                              ScrollableArea::ScrollCallback());
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToSendToCompositor);

  // Finish scroll animation.
  task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1.0));
  scroll_animator->UpdateCompositorAnimations();
  scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_TRUE(finished);
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
  EXPECT_EQ(offset_x + 15 + 10, scroll_animator->CurrentOffset().Width());
  EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
  Reset(*scroll_animator);

  // Forced GC in order to finalize objects depending on the mock object.
  ThreadState::Current()->CollectAllGarbageForTesting();
}

// Test that the callback passed to UserScroll function will be run when the
// animation is canceled or finished when the scroll is sent to compositor.
TEST(ScrollAnimatorTest, UserScrollCallBackAtAnimationFinishOnCompositor) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  TestScrollAnimator* scroll_animator =
      MakeGarbageCollected<TestScrollAnimator>(scrollable_area,
                                               task_runner->GetMockTickClock());

  // Called from userScroll, and first update.
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  // First user scroll.
  bool finished = false;
  scroll_animator->UserScroll(
      ScrollGranularity::kScrollByLine, FloatSize(100, 0),
      ScrollableArea::ScrollCallback(
          base::BindOnce([](bool* finished) { *finished = true; }, &finished)));
  EXPECT_FALSE(finished);
  EXPECT_TRUE(scroll_animator->HasRunningAnimation());
  EXPECT_EQ(100, scroll_animator->DesiredTargetOffset().Width());
  EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToSendToCompositor);

  // Update compositor animation.
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->SetShouldSendToCompositor(true);
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_FALSE(finished);
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnCompositor);

  // Cancel
  scroll_animator->CancelAnimation();
  EXPECT_TRUE(finished);
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToCancelOnCompositor);

  // Forced GC in order to finalize objects depending on the mock object.
  ThreadState::Current()->CollectAllGarbageForTesting();
}

// Test the behavior when in WaitingToCancelOnCompositor and a new user scroll
// happens.
TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  TestScrollAnimator* scroll_animator =
      MakeGarbageCollected<TestScrollAnimator>(scrollable_area,
                                               task_runner->GetMockTickClock());

  // Called when reset, not setting anywhere else.
  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(1);
  // Called from userScroll, and first update.
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(4);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());

  // First user scroll.
  ScrollResult result = scroll_animator->UserScroll(
      ScrollGranularity::kScrollByLine, FloatSize(100, 0),
      ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
  EXPECT_TRUE(scroll_animator->HasRunningAnimation());
  EXPECT_EQ(100, scroll_animator->DesiredTargetOffset().Width());
  EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());

  // Update compositor animation.
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->SetShouldSendToCompositor(true);
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnCompositor);

  // Cancel
  scroll_animator->CancelAnimation();
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToCancelOnCompositor);

  // Unrelated scroll offset update.
  scroll_animator->SetCurrentOffset(ScrollOffset(50, 0));

  // Desired target offset should be that of the second scroll.
  result = scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                                       FloatSize(100, 0),
                                       ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kWaitingToCancelOnCompositorButNewScroll);
  EXPECT_EQ(150, scroll_animator->DesiredTargetOffset().Width());
  EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());

  // Update compositor animation.
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  scroll_animator->UpdateCompositorAnimations();
  EXPECT_EQ(
      scroll_animator->run_state_,
      ScrollAnimatorCompositorCoordinator::RunState::kRunningOnCompositor);

  // Third user scroll after compositor update updates the target.
  result = scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
                                       FloatSize(100, 0),
                                       ScrollableArea::ScrollCallback());
  EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(result.did_scroll_x);
  EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
  EXPECT_EQ(scroll_animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::
                kRunningOnCompositorButNeedsUpdate);
  EXPECT_EQ(250, scroll_animator->DesiredTargetOffset().Width());
  EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());
  Reset(*scroll_animator);

  // Forced GC in order to finalize objects depending on the mock object.
  ThreadState::Current()->CollectAllGarbageForTesting();
}

// This test verifies that impl only animation updates get cleared once they
// are pushed to compositor animation host.
TEST(ScrollAnimatorTest, ImplOnlyAnimationUpdatesCleared) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  TestScrollAnimator* animator = MakeGarbageCollected<TestScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());

  // From calls to adjust/takeoverImplOnlyScrollOffsetAnimation.
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(3);

  // Verify that the adjustment update is cleared.
  EXPECT_EQ(animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::kIdle);
  EXPECT_FALSE(animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(animator->ImplOnlyAnimationAdjustmentForTesting().IsZero());

  animator->AdjustImplOnlyScrollOffsetAnimation(IntSize(100, 100));
  animator->AdjustImplOnlyScrollOffsetAnimation(IntSize(10, -10));

  EXPECT_TRUE(animator->HasAnimationThatRequiresService());
  EXPECT_EQ(IntSize(110, 90),
            animator->ImplOnlyAnimationAdjustmentForTesting());

  animator->UpdateCompositorAnimations();

  EXPECT_EQ(animator->run_state_,
            ScrollAnimatorCompositorCoordinator::RunState::kIdle);
  EXPECT_FALSE(animator->HasAnimationThatRequiresService());
  EXPECT_TRUE(animator->ImplOnlyAnimationAdjustmentForTesting().IsZero());

  // Verify that the takeover update is cleared.
  animator->TakeOverImplOnlyScrollOffsetAnimation();
  EXPECT_FALSE(animator->HasAnimationThatRequiresService());

  // Forced GC in order to finalize objects depending on the mock object.
  ThreadState::Current()->CollectAllGarbageForTesting();
}

TEST(ScrollAnimatorTest, MainThreadAnimationTargetAdjustment) {
  auto* scrollable_area =
      MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
          true, ScrollOffset(-100, -100), ScrollOffset(1000, 1000));
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  ScrollAnimator* animator = MakeGarbageCollected<ScrollAnimator>(
      scrollable_area, task_runner->GetMockTickClock());
  scrollable_area->SetScrollAnimator(animator);

  // Twice from tickAnimation, once from reset, and twice from
  // adjustAnimationAndSetScrollOffset.
  EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(5);
  // One from call to userScroll and one from updateCompositorAnimations.
  EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(2);
  EXPECT_CALL(*scrollable_area, ScheduleAnimation())
      .Times(AtLeast(1))
      .WillRepeatedly(Return(true));

  // Idle
  EXPECT_FALSE(animator->HasAnimationThatRequiresService());
  EXPECT_EQ(ScrollOffset(), animator->CurrentOffset());

  // WaitingToSendToCompositor
  animator->UserScroll(ScrollGranularity::kScrollByLine, ScrollOffset(100, 100),
                       ScrollableArea::ScrollCallback());

  // RunningOnMainThread
  task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
  animator->UpdateCompositorAnimations();
  animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  ScrollOffset offset = animator->CurrentOffset();
  EXPECT_EQ(ScrollOffset(100, 100), animator->DesiredTargetOffset());
  EXPECT_GT(offset.Width(), 0);
  EXPECT_GT(offset.Height(), 0);

  // Adjustment
  ScrollOffset new_offset = offset + ScrollOffset(10, -10);
  animator->AdjustAnimationAndSetScrollOffset(
      new_offset, mojom::blink::ScrollType::kAnchoring);
  EXPECT_EQ(ScrollOffset(110, 90), animator->DesiredTargetOffset());

  // Adjusting after finished animation should do nothing.
  task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
  animator->UpdateCompositorAnimations();
  animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
  EXPECT_EQ(
      animator->RunStateForTesting(),
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
  new_offset = animator->CurrentOffset() + ScrollOffset(10, -10);
  animator->AdjustAnimationAndSetScrollOffset(
      new_offset, mojom::blink::ScrollType::kAnchoring);
  EXPECT_EQ(
      animator->RunStateForTesting(),
      ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
  EXPECT_EQ(ScrollOffset(110, 90), animator->DesiredTargetOffset());

  Reset(*animator);

  // Forced GC in order to finalize objects depending on the mock object.
  ThreadState::Current()->CollectAllGarbageForTesting();
}

}  // namespace blink


text:
div.main-panel {
    position: absolute;
    top: 70px;
    left: 0;
    bottom: 0;
    right: 0;
    overflow-y: auto;
    padding: 10px;
    height: 100%;
    transition: 500ms right;
}

div.main-panel-offset {
    right: 350px;
    transition: 500ms right;
}

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
    background-color: lightsteelblue;
    font-weight: bold;
    -webkit-transition: 500ms all;
    transition: 500ms all;
}
tr.active td {
    background-color: lightsteelblue !important;
    font-weight: bold;
    -webkit-transition: 500ms all;
    transition: 500ms all;
}


text:
All about Openstack with VMware solutions :-)
VMware provide drivers and plugin in order to integrate vSphere,vSAN and NSX with Openstack. The usefull links:
- [VMware vSphere Driver : Nova + vSphere](http://docs.openstack.org/trunk/config-reference/content/vmware.html)
- [VMware VMDK Driver : Cinder + vSphere](http://docs.openstack.org/trunk/config-reference/content/vmware-vmdk-driver.html)
- [VMware NSX Plugin : Neutron + NSX](https://wiki.openstack.org/wiki/Neutron/VMware_NSX_plugins)

## vRealize Automation
![VRA](docs/vra.jpg)
- [vra-openstack](vra-openstack/README.md) : all that your need to know to integrate openstack with vRealize Automation

## VIO
![VIO](docs/vmw%2Bopenstack.jpg)
![NSX](docs/nsx.png)
- [VIO](vio/README.md) : scripts, conf files and tips for VMware Integrated Openstack, vCenter and NSX-V

## Fuel
![FUEL](docs/fuel.png)
- [vnw-fueled](vmw-fueled/README.md) : scripts, conf files and tips for Mirantis Fuel with VMware vCenter & VDS plugins
- [vnw-nsx-fueled](vmw-nsx-fueled/README.md) : scripts, conf files and tips for Mirantis Fuel with VMware vCenter & NSX-V plugins

## Autopilot/Landscape
![UBUNTU](docs/ubuntu.png)
- [vnw-autopiloted](vmw-autopiloted/README.md) : scripts, conf files and tips for Canonical Landscape + Autopilot with VMware vCenter & NSX-V plugins

## Red Hat Openstack
[Redhat Openstack VMware integration](https://access.redhat.com/webassets/avalon/d/Red_Hat_Enterprise_Linux_OpenStack_Platform-7-VMware_Integration_Guide-en-US/Red_Hat_Enterprise_Linux_OpenStack_Platform-7-VMware_Integration_Guide-en-US.pdf)


text:
package org.consumersunion.stories.server.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.consumersunion.stories.common.shared.model.User;
import org.consumersunion.stories.server.business_logic.AuthorizationService;
import org.consumersunion.stories.server.business_logic.UserService;
import org.consumersunion.stories.server.index.Indexer;
import org.consumersunion.stories.server.index.collection.CollectionDocument;
import org.consumersunion.stories.server.index.collection.FullCollectionIndexer;
import org.consumersunion.stories.server.index.elasticsearch.query.QueryBuilder;
import org.consumersunion.stories.server.index.elasticsearch.search.Search;
import org.consumersunion.stories.server.index.elasticsearch.search.SearchBuilder;
import org.consumersunion.stories.server.index.profile.FullPersonIndexer;
import org.consumersunion.stories.server.index.profile.ProfileDocument;
import org.consumersunion.stories.server.index.story.FullStoryIndexer;
import org.consumersunion.stories.server.index.story.StoryDocument;
import org.consumersunion.stories.server.persistence.AnswerSetPersister;
import org.consumersunion.stories.server.persistence.CollectionPersister;
import org.consumersunion.stories.server.persistence.DocumentPersister;
import org.consumersunion.stories.server.persistence.SupportDataUtilsFactory;
import org.consumersunion.stories.server.util.ApplicationContextProvider;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;

import static org.consumersunion.stories.common.shared.AuthConstants.OPERATION_INDEX;

public class IndexServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final static Logger logger = Logger.getLogger(IndexServlet.class.getName());

    @Inject
    private AuthorizationService authService;
    @Inject
    private UserService userService;
    @Inject
    @Named("storyIndexer")
    private Indexer<StoryDocument> storyIndexer;
    @Inject
    @Named("profileIndexer")
    private Indexer<ProfileDocument> profileIndexer;
    @Inject
    @Named("collectionIndexer")
    private Indexer<CollectionDocument> collectionIndexer;
    @Inject
    private DocumentPersister documentPersister;
    @Inject
    private CollectionPersister collectionPersister;
    @Inject
    private SupportDataUtilsFactory supportDataUtilsFactory;
    @Inject
    private AnswerSetPersister answerSetPersister;

    @Override
    public void init(ServletConfig cfg) throws ServletException {
        super.init(cfg);

        ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
        AutowireCapableBeanFactory beanFactory = ctx.getAutowireCapableBeanFactory();
        beanFactory.autowireBean(this);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, final HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("No-Compress", "true");
        response.setContentType("text/plain");
        response.setHeader("Content-Encoding", "none");

        User user = userService.getLoggedInUser();
        if (user == null) {
            response.getWriter().println("Not logged in.");
            return;
        }

        if (!authService.isEntityAuthorized(user.getId(), OPERATION_INDEX, null)) {
            response.getWriter().println("Unauthorized.");
            return;
        }

        final Object lock = new Object();
        Thread bgThread = new Thread(new Runnable() {
            public void run() {
                try {
                    logger.log(Level.INFO, "Reindexing collections.");
                    Search searchAll = SearchBuilder.ofQuery(QueryBuilder.newMatchAll());
                    collectionIndexer.deleteByQuery(searchAll);
                    new FullCollectionIndexer(response, supportDataUtilsFactory, collectionPersister,
                            collectionIndexer).index();
                    logger.log(Level.INFO, "Reindexing stories.");
                    storyIndexer.deleteByQuery(searchAll);
                    new FullStoryIndexer(response, storyIndexer, documentPersister, answerSetPersister,
                            supportDataUtilsFactory).index();
                    logger.log(Level.INFO, "Reindexing people.");
                    profileIndexer.deleteByQuery(searchAll);
                    new FullPersonIndexer(profileIndexer, supportDataUtilsFactory, response).index();
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Error running re-index.", e);
                } finally {
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
        });

        bgThread.start();
        response.getWriter().println("Index started in separate thread. If you have access to the Elasticsearch " +
                "server, you can watch the progress there. The index order will be 'collections', then 'stories', " +
                "then 'people'. Each core will be cleared immediately before re-indexing. We will attempt to send " +
                "incremental updates to the browser window, but the HTTP server's compression filters may interefere." +
                " All the '-' below are to force the buffer to flush this message.\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n" +
                "-------------------------------------------------------------------------------------------------\n");
        response.flushBuffer();

        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
            }
        }
    }
}


text:
using Examine;

namespace Umbraco.Cms.Infrastructure.Examine
{
    public static class UmbracoExamineFieldNames
    {
        /// <summary>
        /// Used to store the path of a content object
        /// </summary>
        public const string IndexPathFieldName = ExamineFieldNames.SpecialFieldPrefix + "Path";
        public const string NodeKeyFieldName = ExamineFieldNames.SpecialFieldPrefix + "Key";
        public const string UmbracoFileFieldName = "umbracoFileSrc";
        public const string IconFieldName = ExamineFieldNames.SpecialFieldPrefix + "Icon";
        public const string PublishedFieldName = ExamineFieldNames.SpecialFieldPrefix + "Published";

        /// <summary>
        /// The prefix added to a field when it is duplicated in order to store the original raw value.
        /// </summary>
        public const string RawFieldPrefix = ExamineFieldNames.SpecialFieldPrefix + "Raw_";

        public const string VariesByCultureFieldName = ExamineFieldNames.SpecialFieldPrefix + "VariesByCulture";

        public const string NodeNameFieldName = "nodeName";
        public const string ItemIdFieldName ="__NodeId";
        public const string CategoryFieldName = "__IndexType";
        public const string ItemTypeFieldName = "__NodeTypeAlias";
    }
}