text:
namespace cc {

LayerAnimationController::LayerAnimationController(int id)
    : registrar_(0),
      id_(id),
      is_active_(false),
      value_provider_(nullptr),
      layer_animation_delegate_(nullptr),
      needs_to_start_animations_(false),
      scroll_offset_animation_was_interrupted_(false),
      potentially_animating_transform_for_active_observers_(false),
      potentially_animating_transform_for_pending_observers_(false) {}

LayerAnimationController::~LayerAnimationController() {
  if (registrar_)
    registrar_->UnregisterAnimationController(this);
}

scoped_refptr<LayerAnimationController> LayerAnimationController::Create(
    int id) {
  return make_scoped_refptr(new LayerAnimationController(id));
}

void LayerAnimationController::PauseAnimation(int animation_id,
                                              base::TimeDelta time_offset) {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->id() == animation_id) {
      animations_[i]->SetRunState(Animation::PAUSED,
                                  time_offset + animations_[i]->start_time() +
                                      animations_[i]->time_offset());
    }
  }
}

void LayerAnimationController::UpdatePotentiallyAnimatingTransform() {
  bool was_potentially_animating_transform_for_active_observers =
      potentially_animating_transform_for_active_observers_;
  bool was_potentially_animating_transform_for_pending_observers =
      potentially_animating_transform_for_pending_observers_;

  potentially_animating_transform_for_active_observers_ = false;
  potentially_animating_transform_for_pending_observers_ = false;

  for (const auto& animation : animations_) {
    if (!animation->is_finished() &&
        animation->target_property() == TargetProperty::TRANSFORM) {
      potentially_animating_transform_for_active_observers_ |=
          animation->affects_active_observers();
      potentially_animating_transform_for_pending_observers_ |=
          animation->affects_pending_observers();
    }
  }

  bool changed_for_active_observers =
      was_potentially_animating_transform_for_active_observers !=
      potentially_animating_transform_for_active_observers_;
  bool changed_for_pending_observers =
      was_potentially_animating_transform_for_pending_observers !=
      potentially_animating_transform_for_pending_observers_;

  if (!changed_for_active_observers && !changed_for_pending_observers)
    return;

  NotifyObserversTransformIsPotentiallyAnimatingChanged(
      changed_for_active_observers, changed_for_pending_observers);
}

void LayerAnimationController::RemoveAnimation(int animation_id) {
  bool removed_transform_animation = false;
  // Since we want to use the animations that we're going to remove, we need to
  // use a stable_parition here instead of remove_if. Remove_if leaves the
  // removed items in an unspecified state.
  auto animations_to_remove = std::stable_partition(
      animations_.begin(), animations_.end(),
      [animation_id](const scoped_ptr<Animation>& animation) {
        return animation->id() != animation_id;
      });
  for (auto it = animations_to_remove; it != animations_.end(); ++it) {
    if ((*it)->target_property() == TargetProperty::SCROLL_OFFSET) {
      scroll_offset_animation_was_interrupted_ = true;
    } else if ((*it)->target_property() == TargetProperty::TRANSFORM &&
               !(*it)->is_finished()) {
      removed_transform_animation = true;
    }
  }

  animations_.erase(animations_to_remove, animations_.end());
  UpdateActivation(NORMAL_ACTIVATION);
  if (removed_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::AbortAnimation(int animation_id) {
  bool aborted_transform_animation = false;
  if (Animation* animation = GetAnimationById(animation_id)) {
    if (!animation->is_finished()) {
      animation->SetRunState(Animation::ABORTED, last_tick_time_);
      if (animation->target_property() == TargetProperty::TRANSFORM)
        aborted_transform_animation = true;
    }
  }
  if (aborted_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::AbortAnimations(
    TargetProperty::Type target_property,
    bool needs_completion) {
  if (needs_completion)
    DCHECK(target_property == TargetProperty::SCROLL_OFFSET);

  bool aborted_transform_animation = false;
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->target_property() == target_property &&
        !animations_[i]->is_finished()) {
      // Currently only impl-only scroll offset animations can be completed on
      // the main thread.
      if (needs_completion && animations_[i]->is_impl_only()) {
        animations_[i]->SetRunState(Animation::ABORTED_BUT_NEEDS_COMPLETION,
                                    last_tick_time_);
      } else {
        animations_[i]->SetRunState(Animation::ABORTED, last_tick_time_);
      }
      if (target_property == TargetProperty::TRANSFORM)
        aborted_transform_animation = true;
    }
  }
  if (aborted_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

// Ensures that the list of active animations on the main thread and the impl
// thread are kept in sync.
void LayerAnimationController::PushAnimationUpdatesTo(
    LayerAnimationController* controller_impl) {
  DCHECK(this != controller_impl);
  if (!has_any_animation() && !controller_impl->has_any_animation())
    return;
  MarkAbortedAnimationsForDeletion(controller_impl);
  PurgeAnimationsMarkedForDeletion();
  PushNewAnimationsToImplThread(controller_impl);

  // Remove finished impl side animations only after pushing,
  // and only after the animations are deleted on the main thread
  // this insures we will never push an animation twice.
  RemoveAnimationsCompletedOnMainThread(controller_impl);

  PushPropertiesToImplThread(controller_impl);
  controller_impl->UpdateActivation(NORMAL_ACTIVATION);
  UpdateActivation(NORMAL_ACTIVATION);
}

void LayerAnimationController::Animate(base::TimeTicks monotonic_time) {
  DCHECK(!monotonic_time.is_null());
  if (!HasValueObserver())
    return;

  if (needs_to_start_animations_)
    StartAnimations(monotonic_time);
  TickAnimations(monotonic_time);
  last_tick_time_ = monotonic_time;
}

void LayerAnimationController::AccumulatePropertyUpdates(
    base::TimeTicks monotonic_time,
    AnimationEvents* events) {
  if (!events)
    return;

  for (size_t i = 0; i < animations_.size(); ++i) {
    Animation* animation = animations_[i].get();
    if (!animation->is_impl_only())
      continue;

    if (!animation->InEffect(monotonic_time))
      continue;

    base::TimeDelta trimmed =
        animation->TrimTimeToCurrentIteration(monotonic_time);
    switch (animation->target_property()) {
      case TargetProperty::OPACITY: {
        AnimationEvent event(AnimationEvent::PROPERTY_UPDATE, id_,
                             animation->group(), TargetProperty::OPACITY,
                             monotonic_time);
        const FloatAnimationCurve* float_animation_curve =
            animation->curve()->ToFloatAnimationCurve();
        event.opacity = float_animation_curve->GetValue(trimmed);
        event.is_impl_only = true;
        events->events_.push_back(event);
        break;
      }

      case TargetProperty::TRANSFORM: {
        AnimationEvent event(AnimationEvent::PROPERTY_UPDATE, id_,
                             animation->group(), TargetProperty::TRANSFORM,
                             monotonic_time);
        const TransformAnimationCurve* transform_animation_curve =
            animation->curve()->ToTransformAnimationCurve();
        event.transform = transform_animation_curve->GetValue(trimmed);
        event.is_impl_only = true;
        events->events_.push_back(event);
        break;
      }

      case TargetProperty::FILTER: {
        AnimationEvent event(AnimationEvent::PROPERTY_UPDATE, id_,
                             animation->group(), TargetProperty::FILTER,
                             monotonic_time);
        const FilterAnimationCurve* filter_animation_curve =
            animation->curve()->ToFilterAnimationCurve();
        event.filters = filter_animation_curve->GetValue(trimmed);
        event.is_impl_only = true;
        events->events_.push_back(event);
        break;
      }

      case TargetProperty::BACKGROUND_COLOR: {
        break;
      }

      case TargetProperty::SCROLL_OFFSET: {
        // Impl-side changes to scroll offset are already sent back to the
        // main thread (e.g. for user-driven scrolling), so a PROPERTY_UPDATE
        // isn't needed.
        break;
      }
    }
  }
}

void LayerAnimationController::UpdateState(bool start_ready_animations,
                                           AnimationEvents* events) {
  if (!HasActiveValueObserver())
    return;

  // Animate hasn't been called, this happens if an observer has been added
  // between the Commit and Draw phases.
  if (last_tick_time_ == base::TimeTicks())
    return;

  if (start_ready_animations)
    PromoteStartedAnimations(last_tick_time_, events);

  MarkFinishedAnimations(last_tick_time_);
  MarkAnimationsForDeletion(last_tick_time_, events);

  if (needs_to_start_animations_ && start_ready_animations) {
    StartAnimations(last_tick_time_);
    PromoteStartedAnimations(last_tick_time_, events);
  }

  AccumulatePropertyUpdates(last_tick_time_, events);

  UpdateActivation(NORMAL_ACTIVATION);
}

void LayerAnimationController::ActivateAnimations() {
  bool changed_transform_animation = false;
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->affects_active_observers() !=
            animations_[i]->affects_pending_observers() &&
        animations_[i]->target_property() == TargetProperty::TRANSFORM)
      changed_transform_animation = true;
    animations_[i]->set_affects_active_observers(
        animations_[i]->affects_pending_observers());
  }
  auto affects_no_observers = [](const scoped_ptr<Animation>& animation) {
    return !animation->affects_active_observers() &&
           !animation->affects_pending_observers();
  };
  animations_.erase(std::remove_if(animations_.begin(), animations_.end(),
                                   affects_no_observers),
                    animations_.end());
  scroll_offset_animation_was_interrupted_ = false;
  UpdateActivation(NORMAL_ACTIVATION);
  if (changed_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::AddAnimation(scoped_ptr<Animation> animation) {
  bool added_transform_animation =
      animation->target_property() == TargetProperty::TRANSFORM;
  animations_.push_back(std::move(animation));
  needs_to_start_animations_ = true;
  UpdateActivation(NORMAL_ACTIVATION);
  if (added_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

Animation* LayerAnimationController::GetAnimation(
    TargetProperty::Type target_property) const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    size_t index = animations_.size() - i - 1;
    if (animations_[index]->target_property() == target_property)
      return animations_[index].get();
  }
  return nullptr;
}

Animation* LayerAnimationController::GetAnimationById(int animation_id) const {
  for (size_t i = 0; i < animations_.size(); ++i)
    if (animations_[i]->id() == animation_id)
      return animations_[i].get();
  return nullptr;
}

bool LayerAnimationController::HasActiveAnimation() const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (!animations_[i]->is_finished())
      return true;
  }
  return false;
}

bool LayerAnimationController::IsPotentiallyAnimatingProperty(
    TargetProperty::Type target_property,
    ObserverType observer_type) const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (!animations_[i]->is_finished() &&
        animations_[i]->target_property() == target_property) {
      if ((observer_type == ObserverType::ACTIVE &&
           animations_[i]->affects_active_observers()) ||
          (observer_type == ObserverType::PENDING &&
           animations_[i]->affects_pending_observers()))
        return true;
    }
  }
  return false;
}

bool LayerAnimationController::IsCurrentlyAnimatingProperty(
    TargetProperty::Type target_property,
    ObserverType observer_type) const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (!animations_[i]->is_finished() &&
        animations_[i]->InEffect(last_tick_time_) &&
        animations_[i]->target_property() == target_property) {
      if ((observer_type == ObserverType::ACTIVE &&
           animations_[i]->affects_active_observers()) ||
          (observer_type == ObserverType::PENDING &&
           animations_[i]->affects_pending_observers()))
        return true;
    }
  }
  return false;
}

void LayerAnimationController::SetAnimationRegistrar(
    AnimationRegistrar* registrar) {
  if (registrar_ == registrar)
    return;

  if (registrar_)
    registrar_->UnregisterAnimationController(this);

  registrar_ = registrar;
  if (registrar_)
    registrar_->RegisterAnimationController(this);

  UpdateActivation(FORCE_ACTIVATION);
}

void LayerAnimationController::NotifyAnimationStarted(
    const AnimationEvent& event) {
  if (event.is_impl_only) {
    FOR_EACH_OBSERVER(LayerAnimationEventObserver, event_observers_,
                      OnAnimationStarted(event));
    if (layer_animation_delegate_)
      layer_animation_delegate_->NotifyAnimationStarted(
          event.monotonic_time, event.target_property, event.group_id);
    return;
  }

  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->group() == event.group_id &&
        animations_[i]->target_property() == event.target_property &&
        animations_[i]->needs_synchronized_start_time()) {
      animations_[i]->set_needs_synchronized_start_time(false);
      if (!animations_[i]->has_set_start_time())
        animations_[i]->set_start_time(event.monotonic_time);

      FOR_EACH_OBSERVER(LayerAnimationEventObserver, event_observers_,
                        OnAnimationStarted(event));
      if (layer_animation_delegate_)
        layer_animation_delegate_->NotifyAnimationStarted(
            event.monotonic_time, event.target_property, event.group_id);

      return;
    }
  }
}

void LayerAnimationController::NotifyAnimationFinished(
    const AnimationEvent& event) {
  if (event.is_impl_only) {
    if (layer_animation_delegate_)
      layer_animation_delegate_->NotifyAnimationFinished(
          event.monotonic_time, event.target_property, event.group_id);
    return;
  }

  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->group() == event.group_id &&
        animations_[i]->target_property() == event.target_property) {
      animations_[i]->set_received_finished_event(true);
      if (layer_animation_delegate_)
        layer_animation_delegate_->NotifyAnimationFinished(
            event.monotonic_time, event.target_property, event.group_id);

      return;
    }
  }
}

void LayerAnimationController::NotifyAnimationTakeover(
    const AnimationEvent& event) {
  DCHECK(event.target_property == TargetProperty::SCROLL_OFFSET);
  if (layer_animation_delegate_) {
    scoped_ptr<AnimationCurve> animation_curve = event.curve->Clone();
    layer_animation_delegate_->NotifyAnimationTakeover(
        event.monotonic_time, event.target_property, event.animation_start_time,
        std::move(animation_curve));
  }
}

void LayerAnimationController::NotifyAnimationAborted(
    const AnimationEvent& event) {
  bool aborted_transform_animation = false;
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->group() == event.group_id &&
        animations_[i]->target_property() == event.target_property) {
      animations_[i]->SetRunState(Animation::ABORTED, event.monotonic_time);
      animations_[i]->set_received_finished_event(true);
      if (layer_animation_delegate_)
        layer_animation_delegate_->NotifyAnimationAborted(
            event.monotonic_time, event.target_property, event.group_id);
      if (event.target_property == TargetProperty::TRANSFORM)
        aborted_transform_animation = true;
    }
  }
  if (aborted_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::NotifyAnimationPropertyUpdate(
    const AnimationEvent& event) {
  bool notify_active_observers = true;
  bool notify_pending_observers = true;
  switch (event.target_property) {
    case TargetProperty::OPACITY:
      NotifyObserversOpacityAnimated(
          event.opacity, notify_active_observers, notify_pending_observers);
      break;
    case TargetProperty::TRANSFORM:
      NotifyObserversTransformAnimated(
          event.transform, notify_active_observers, notify_pending_observers);
      break;
    default:
      NOTREACHED();
  }
}

void LayerAnimationController::AddValueObserver(
    LayerAnimationValueObserver* observer) {
  if (!value_observers_.HasObserver(observer))
    value_observers_.AddObserver(observer);
}

void LayerAnimationController::RemoveValueObserver(
    LayerAnimationValueObserver* observer) {
  value_observers_.RemoveObserver(observer);
}

void LayerAnimationController::AddEventObserver(
    LayerAnimationEventObserver* observer) {
  if (!event_observers_.HasObserver(observer))
    event_observers_.AddObserver(observer);
}

void LayerAnimationController::RemoveEventObserver(
    LayerAnimationEventObserver* observer) {
  event_observers_.RemoveObserver(observer);
}

bool LayerAnimationController::HasFilterAnimationThatInflatesBounds() const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (!animations_[i]->is_finished() &&
        animations_[i]->target_property() == TargetProperty::FILTER &&
        animations_[i]
            ->curve()
            ->ToFilterAnimationCurve()
            ->HasFilterThatMovesPixels())
      return true;
  }

  return false;
}

bool LayerAnimationController::HasTransformAnimationThatInflatesBounds() const {
  return IsCurrentlyAnimatingProperty(TargetProperty::TRANSFORM,
                                      ObserverType::ACTIVE) ||
         IsCurrentlyAnimatingProperty(TargetProperty::TRANSFORM,
                                      ObserverType::PENDING);
}

bool LayerAnimationController::FilterAnimationBoundsForBox(
    const gfx::BoxF& box, gfx::BoxF* bounds) const {
  // TODO(avallee): Implement.
  return false;
}

bool LayerAnimationController::TransformAnimationBoundsForBox(
    const gfx::BoxF& box,
    gfx::BoxF* bounds) const {
  DCHECK(HasTransformAnimationThatInflatesBounds())
      << "TransformAnimationBoundsForBox will give incorrect results if there "
      << "are no transform animations affecting bounds, non-animated transform "
      << "is not known";

  // Compute bounds based on animations for which is_finished() is false.
  // Do nothing if there are no such animations; in this case, it is assumed
  // that callers will take care of computing bounds based on the owning layer's
  // actual transform.
  *bounds = gfx::BoxF();
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->is_finished() ||
        animations_[i]->target_property() != TargetProperty::TRANSFORM)
      continue;

    const TransformAnimationCurve* transform_animation_curve =
        animations_[i]->curve()->ToTransformAnimationCurve();
    gfx::BoxF animation_bounds;
    bool success =
        transform_animation_curve->AnimatedBoundsForBox(box, &animation_bounds);
    if (!success)
      return false;
    bounds->Union(animation_bounds);
  }

  return true;
}

bool LayerAnimationController::HasAnimationThatAffectsScale() const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->is_finished() ||
        animations_[i]->target_property() != TargetProperty::TRANSFORM)
      continue;

    const TransformAnimationCurve* transform_animation_curve =
        animations_[i]->curve()->ToTransformAnimationCurve();
    if (transform_animation_curve->AffectsScale())
      return true;
  }

  return false;
}

bool LayerAnimationController::HasOnlyTranslationTransforms(
    ObserverType observer_type) const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->is_finished() ||
        animations_[i]->target_property() != TargetProperty::TRANSFORM)
      continue;

    if ((observer_type == ObserverType::ACTIVE &&
         !animations_[i]->affects_active_observers()) ||
        (observer_type == ObserverType::PENDING &&
         !animations_[i]->affects_pending_observers()))
      continue;

    const TransformAnimationCurve* transform_animation_curve =
        animations_[i]->curve()->ToTransformAnimationCurve();
    if (!transform_animation_curve->IsTranslation())
      return false;
  }

  return true;
}

bool LayerAnimationController::AnimationsPreserveAxisAlignment() const {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->is_finished() ||
        animations_[i]->target_property() != TargetProperty::TRANSFORM)
      continue;

    const TransformAnimationCurve* transform_animation_curve =
        animations_[i]->curve()->ToTransformAnimationCurve();
    if (!transform_animation_curve->PreservesAxisAlignment())
      return false;
  }

  return true;
}

bool LayerAnimationController::AnimationStartScale(ObserverType observer_type,
                                                   float* start_scale) const {
  *start_scale = 0.f;
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->is_finished() ||
        animations_[i]->target_property() != TargetProperty::TRANSFORM)
      continue;

    if ((observer_type == ObserverType::ACTIVE &&
         !animations_[i]->affects_active_observers()) ||
        (observer_type == ObserverType::PENDING &&
         !animations_[i]->affects_pending_observers()))
      continue;

    bool forward_direction = true;
    switch (animations_[i]->direction()) {
      case Animation::DIRECTION_NORMAL:
      case Animation::DIRECTION_ALTERNATE:
        forward_direction = animations_[i]->playback_rate() >= 0.0;
        break;
      case Animation::DIRECTION_REVERSE:
      case Animation::DIRECTION_ALTERNATE_REVERSE:
        forward_direction = animations_[i]->playback_rate() < 0.0;
        break;
    }

    const TransformAnimationCurve* transform_animation_curve =
        animations_[i]->curve()->ToTransformAnimationCurve();
    float animation_start_scale = 0.f;
    if (!transform_animation_curve->AnimationStartScale(forward_direction,
                                                        &animation_start_scale))
      return false;
    *start_scale = std::max(*start_scale, animation_start_scale);
  }
  return true;
}

bool LayerAnimationController::MaximumTargetScale(ObserverType observer_type,
                                                  float* max_scale) const {
  *max_scale = 0.f;
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->is_finished() ||
        animations_[i]->target_property() != TargetProperty::TRANSFORM)
      continue;

    if ((observer_type == ObserverType::ACTIVE &&
         !animations_[i]->affects_active_observers()) ||
        (observer_type == ObserverType::PENDING &&
         !animations_[i]->affects_pending_observers()))
      continue;

    bool forward_direction = true;
    switch (animations_[i]->direction()) {
      case Animation::DIRECTION_NORMAL:
      case Animation::DIRECTION_ALTERNATE:
        forward_direction = animations_[i]->playback_rate() >= 0.0;
        break;
      case Animation::DIRECTION_REVERSE:
      case Animation::DIRECTION_ALTERNATE_REVERSE:
        forward_direction = animations_[i]->playback_rate() < 0.0;
        break;
    }

    const TransformAnimationCurve* transform_animation_curve =
        animations_[i]->curve()->ToTransformAnimationCurve();
    float animation_scale = 0.f;
    if (!transform_animation_curve->MaximumTargetScale(forward_direction,
                                                       &animation_scale))
      return false;
    *max_scale = std::max(*max_scale, animation_scale);
  }

  return true;
}

void LayerAnimationController::PushNewAnimationsToImplThread(
    LayerAnimationController* controller_impl) const {
  // Any new animations owned by the main thread's controller are cloned and
  // add to the impl thread's controller.
  for (size_t i = 0; i < animations_.size(); ++i) {
    // If the animation is already running on the impl thread, there is no
    // need to copy it over.
    if (controller_impl->GetAnimationById(animations_[i]->id()))
      continue;

    if (animations_[i]->target_property() == TargetProperty::SCROLL_OFFSET &&
        !animations_[i]
             ->curve()
             ->ToScrollOffsetAnimationCurve()
             ->HasSetInitialValue()) {
      gfx::ScrollOffset current_scroll_offset;
      if (controller_impl->value_provider_) {
        current_scroll_offset =
            controller_impl->value_provider_->ScrollOffsetForAnimation();
      } else {
        // The owning layer isn't yet in the active tree, so the main thread
        // scroll offset will be up-to-date.
        current_scroll_offset = value_provider_->ScrollOffsetForAnimation();
      }
      animations_[i]->curve()->ToScrollOffsetAnimationCurve()->SetInitialValue(
          current_scroll_offset);
    }

    // The new animation should be set to run as soon as possible.
    Animation::RunState initial_run_state =
        Animation::WAITING_FOR_TARGET_AVAILABILITY;
    scoped_ptr<Animation> to_add(
        animations_[i]->CloneAndInitialize(initial_run_state));
    DCHECK(!to_add->needs_synchronized_start_time());
    to_add->set_affects_active_observers(false);
    controller_impl->AddAnimation(std::move(to_add));
  }
}

static bool IsCompleted(
    Animation* animation,
    const LayerAnimationController* main_thread_controller) {
  if (animation->is_impl_only()) {
    return (animation->run_state() == Animation::WAITING_FOR_DELETION);
  } else {
    return !main_thread_controller->GetAnimationById(animation->id());
  }
}

void LayerAnimationController::RemoveAnimationsCompletedOnMainThread(
    LayerAnimationController* controller_impl) const {
  bool removed_transform_animation = false;
  // Animations removed on the main thread should no longer affect pending
  // observers, and should stop affecting active observers after the next call
  // to ActivateAnimations. If already WAITING_FOR_DELETION, they can be removed
  // immediately.
  auto& animations = controller_impl->animations_;
  for (const auto& animation : animations) {
    if (IsCompleted(animation.get(), this)) {
      animation->set_affects_pending_observers(false);
      if (animation->target_property() == TargetProperty::TRANSFORM)
        removed_transform_animation = true;
    }
  }
  auto affects_active_only_and_is_waiting_for_deletion = [](
      const scoped_ptr<Animation>& animation) {
    return animation->run_state() == Animation::WAITING_FOR_DELETION &&
           !animation->affects_pending_observers();
  };
  animations.erase(
      std::remove_if(animations.begin(), animations.end(),
                     affects_active_only_and_is_waiting_for_deletion),
      animations.end());

  if (removed_transform_animation)
    controller_impl->UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::PushPropertiesToImplThread(
    LayerAnimationController* controller_impl) {
  for (size_t i = 0; i < animations_.size(); ++i) {
    Animation* current_impl =
        controller_impl->GetAnimationById(animations_[i]->id());
    if (current_impl)
      animations_[i]->PushPropertiesTo(current_impl);
  }
  controller_impl->scroll_offset_animation_was_interrupted_ =
      scroll_offset_animation_was_interrupted_;
  scroll_offset_animation_was_interrupted_ = false;
}

void LayerAnimationController::StartAnimations(base::TimeTicks monotonic_time) {
  DCHECK(needs_to_start_animations_);
  needs_to_start_animations_ = false;
  // First collect running properties affecting each type of observer.
  TargetProperties blocked_properties_for_active_observers;
  TargetProperties blocked_properties_for_pending_observers;
  std::vector<size_t> animations_waiting_for_target;

  animations_waiting_for_target.reserve(animations_.size());
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->run_state() == Animation::STARTING ||
        animations_[i]->run_state() == Animation::RUNNING) {
      if (animations_[i]->affects_active_observers()) {
        blocked_properties_for_active_observers.insert(
            animations_[i]->target_property());
      }
      if (animations_[i]->affects_pending_observers()) {
        blocked_properties_for_pending_observers.insert(
            animations_[i]->target_property());
      }
    } else if (animations_[i]->run_state() ==
               Animation::WAITING_FOR_TARGET_AVAILABILITY) {
      animations_waiting_for_target.push_back(i);
    }
  }

  for (size_t i = 0; i < animations_waiting_for_target.size(); ++i) {
      // Collect all properties for animations with the same group id (they
      // should all also be in the list of animations).
    size_t animation_index = animations_waiting_for_target[i];
    Animation* animation_waiting_for_target =
        animations_[animation_index].get();
    // Check for the run state again even though the animation was waiting
    // for target because it might have changed the run state while handling
    // previous animation in this loop (if they belong to same group).
    if (animation_waiting_for_target->run_state() ==
        Animation::WAITING_FOR_TARGET_AVAILABILITY) {
      TargetProperties enqueued_properties;
      bool affects_active_observers =
          animation_waiting_for_target->affects_active_observers();
      bool affects_pending_observers =
          animation_waiting_for_target->affects_pending_observers();
      enqueued_properties.insert(
          animation_waiting_for_target->target_property());
      for (size_t j = animation_index + 1; j < animations_.size(); ++j) {
        if (animation_waiting_for_target->group() == animations_[j]->group()) {
          enqueued_properties.insert(animations_[j]->target_property());
          affects_active_observers |=
              animations_[j]->affects_active_observers();
          affects_pending_observers |=
              animations_[j]->affects_pending_observers();
        }
      }

      // Check to see if intersection of the list of properties affected by
      // the group and the list of currently blocked properties is null, taking
      // into account the type(s) of observers affected by the group. In any
      // case, the group's target properties need to be added to the lists of
      // blocked properties.
      bool null_intersection = true;
      for (TargetProperties::iterator p_iter = enqueued_properties.begin();
           p_iter != enqueued_properties.end();
           ++p_iter) {
        if (affects_active_observers &&
            !blocked_properties_for_active_observers.insert(*p_iter).second)
          null_intersection = false;
        if (affects_pending_observers &&
            !blocked_properties_for_pending_observers.insert(*p_iter).second)
          null_intersection = false;
      }

      // If the intersection is null, then we are free to start the animations
      // in the group.
      if (null_intersection) {
        animation_waiting_for_target->SetRunState(Animation::STARTING,
                                                  monotonic_time);
        for (size_t j = animation_index + 1; j < animations_.size(); ++j) {
          if (animation_waiting_for_target->group() ==
              animations_[j]->group()) {
            animations_[j]->SetRunState(Animation::STARTING, monotonic_time);
          }
        }
      } else {
        needs_to_start_animations_ = true;
      }
    }
  }
}

void LayerAnimationController::PromoteStartedAnimations(
    base::TimeTicks monotonic_time,
    AnimationEvents* events) {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->run_state() == Animation::STARTING &&
        animations_[i]->affects_active_observers()) {
      animations_[i]->SetRunState(Animation::RUNNING, monotonic_time);
      if (!animations_[i]->has_set_start_time() &&
          !animations_[i]->needs_synchronized_start_time())
        animations_[i]->set_start_time(monotonic_time);
      if (events) {
        base::TimeTicks start_time;
        if (animations_[i]->has_set_start_time())
          start_time = animations_[i]->start_time();
        else
          start_time = monotonic_time;
        AnimationEvent started_event(
            AnimationEvent::STARTED, id_, animations_[i]->group(),
            animations_[i]->target_property(), start_time);
        started_event.is_impl_only = animations_[i]->is_impl_only();
        if (started_event.is_impl_only)
          NotifyAnimationStarted(started_event);
        else
          events->events_.push_back(started_event);
      }
    }
  }
}

void LayerAnimationController::MarkFinishedAnimations(
    base::TimeTicks monotonic_time) {
  bool finished_transform_animation = false;
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (!animations_[i]->is_finished() &&
        animations_[i]->IsFinishedAt(monotonic_time)) {
      animations_[i]->SetRunState(Animation::FINISHED, monotonic_time);
      if (animations_[i]->target_property() == TargetProperty::TRANSFORM) {
        finished_transform_animation = true;
      }
    }
  }
  if (finished_transform_animation)
    UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::MarkAnimationsForDeletion(
    base::TimeTicks monotonic_time,
    AnimationEvents* events) {
  bool marked_animations_for_deletions = false;
  std::vector<size_t> animations_with_same_group_id;

  animations_with_same_group_id.reserve(animations_.size());
  // Non-aborted animations are marked for deletion after a corresponding
  // AnimationEvent::FINISHED event is sent or received. This means that if
  // we don't have an events vector, we must ensure that non-aborted animations
  // have received a finished event before marking them for deletion.
  for (size_t i = 0; i < animations_.size(); i++) {
    int group_id = animations_[i]->group();
    if (animations_[i]->run_state() == Animation::ABORTED) {
      if (events && !animations_[i]->is_impl_only()) {
        AnimationEvent aborted_event(AnimationEvent::ABORTED, id_, group_id,
                                     animations_[i]->target_property(),
                                     monotonic_time);
        events->events_.push_back(aborted_event);
      }
      // If on the compositor or on the main thread and received finish event,
      // animation can be marked for deletion.
      if (events || animations_[i]->received_finished_event()) {
        animations_[i]->SetRunState(Animation::WAITING_FOR_DELETION,
                                    monotonic_time);
        marked_animations_for_deletions = true;
      }
      continue;
    }

    // If running on the compositor and need to complete an aborted animation
    // on the main thread.
    if (events &&
        animations_[i]->run_state() ==
            Animation::ABORTED_BUT_NEEDS_COMPLETION) {
      AnimationEvent aborted_event(AnimationEvent::TAKEOVER, id_, group_id,
                                   animations_[i]->target_property(),
                                   monotonic_time);
      aborted_event.animation_start_time =
          (animations_[i]->start_time() - base::TimeTicks()).InSecondsF();
      const ScrollOffsetAnimationCurve* scroll_offset_animation_curve =
          animations_[i]->curve()->ToScrollOffsetAnimationCurve();
      aborted_event.curve = scroll_offset_animation_curve->Clone();
      // Notify the compositor that the animation is finished.
      if (layer_animation_delegate_) {
        layer_animation_delegate_->NotifyAnimationFinished(
            aborted_event.monotonic_time, aborted_event.target_property,
            aborted_event.group_id);
      }
      // Notify main thread.
      events->events_.push_back(aborted_event);

      // Remove the animation from the compositor.
      animations_[i]->SetRunState(Animation::WAITING_FOR_DELETION,
                                  monotonic_time);
      marked_animations_for_deletions = true;
      continue;
    }

    bool all_anims_with_same_id_are_finished = false;

    // Since deleting an animation on the main thread leads to its deletion
    // on the impl thread, we only mark a FINISHED main thread animation for
    // deletion once it has received a FINISHED event from the impl thread.
    bool animation_i_will_send_or_has_received_finish_event =
        animations_[i]->is_controlling_instance() ||
        animations_[i]->is_impl_only() ||
        animations_[i]->received_finished_event();
    // If an animation is finished, and not already marked for deletion,
    // find out if all other animations in the same group are also finished.
    if (animations_[i]->run_state() == Animation::FINISHED &&
        animation_i_will_send_or_has_received_finish_event) {
      // Clear the animations_with_same_group_id if it was added for
      // the previous animation's iteration.
      if (animations_with_same_group_id.size() > 0)
        animations_with_same_group_id.clear();
      all_anims_with_same_id_are_finished = true;
      for (size_t j = 0; j < animations_.size(); ++j) {
        bool animation_j_will_send_or_has_received_finish_event =
            animations_[j]->is_controlling_instance() ||
            animations_[j]->is_impl_only() ||
            animations_[j]->received_finished_event();
        if (group_id == animations_[j]->group()) {
          if (!animations_[j]->is_finished() ||
              (animations_[j]->run_state() == Animation::FINISHED &&
               !animation_j_will_send_or_has_received_finish_event)) {
            all_anims_with_same_id_are_finished = false;
            break;
          } else if (j >= i &&
                     animations_[j]->run_state() != Animation::ABORTED) {
            // Mark down the animations which belong to the same group
            // and is not yet aborted. If this current iteration finds that all
            // animations with same ID are finished, then the marked
            // animations below will be set to WAITING_FOR_DELETION in next
            // iteration.
            animations_with_same_group_id.push_back(j);
          }
        }
      }
    }
    if (all_anims_with_same_id_are_finished) {
      // We now need to remove all animations with the same group id as
      // group_id (and send along animation finished notifications, if
      // necessary).
      for (size_t j = 0; j < animations_with_same_group_id.size(); j++) {
        size_t animation_index = animations_with_same_group_id[j];
          if (events) {
            AnimationEvent finished_event(
                AnimationEvent::FINISHED, id_,
                animations_[animation_index]->group(),
                animations_[animation_index]->target_property(),
                monotonic_time);
            finished_event.is_impl_only =
                animations_[animation_index]->is_impl_only();
            if (finished_event.is_impl_only)
              NotifyAnimationFinished(finished_event);
            else
              events->events_.push_back(finished_event);
          }
          animations_[animation_index]->SetRunState(
              Animation::WAITING_FOR_DELETION, monotonic_time);
      }
      marked_animations_for_deletions = true;
    }
  }
  if (marked_animations_for_deletions)
    NotifyObserversAnimationWaitingForDeletion();
}

void LayerAnimationController::MarkAbortedAnimationsForDeletion(
    LayerAnimationController* controller_impl) const {
  bool aborted_transform_animation = false;
  auto& animations_impl = controller_impl->animations_;
  for (const auto& animation_impl : animations_impl) {
    // If the animation has been aborted on the main thread, mark it for
    // deletion.
    if (Animation* animation = GetAnimationById(animation_impl->id())) {
      if (animation->run_state() == Animation::ABORTED) {
        animation_impl->SetRunState(Animation::WAITING_FOR_DELETION,
                                    controller_impl->last_tick_time_);
        animation->SetRunState(Animation::WAITING_FOR_DELETION,
                               last_tick_time_);
        if (animation_impl->target_property() == TargetProperty::TRANSFORM) {
          aborted_transform_animation = true;
        }
      }
    }
  }

  if (aborted_transform_animation)
    controller_impl->UpdatePotentiallyAnimatingTransform();
}

void LayerAnimationController::PurgeAnimationsMarkedForDeletion() {
  animations_.erase(std::remove_if(animations_.begin(), animations_.end(),
                                   [](const scoped_ptr<Animation>& animation) {
                                     return animation->run_state() ==
                                            Animation::WAITING_FOR_DELETION;
                                   }),
                    animations_.end());
}

void LayerAnimationController::TickAnimations(base::TimeTicks monotonic_time) {
  for (size_t i = 0; i < animations_.size(); ++i) {
    if (animations_[i]->run_state() == Animation::STARTING ||
        animations_[i]->run_state() == Animation::RUNNING ||
        animations_[i]->run_state() == Animation::PAUSED) {
      if (!animations_[i]->InEffect(monotonic_time))
        continue;

      base::TimeDelta trimmed =
          animations_[i]->TrimTimeToCurrentIteration(monotonic_time);

      switch (animations_[i]->target_property()) {
        case TargetProperty::TRANSFORM: {
          const TransformAnimationCurve* transform_animation_curve =
              animations_[i]->curve()->ToTransformAnimationCurve();
          const gfx::Transform transform =
              transform_animation_curve->GetValue(trimmed);
          NotifyObserversTransformAnimated(
              transform,
              animations_[i]->affects_active_observers(),
              animations_[i]->affects_pending_observers());
          break;
        }

        case TargetProperty::OPACITY: {
          const FloatAnimationCurve* float_animation_curve =
              animations_[i]->curve()->ToFloatAnimationCurve();
          const float opacity = std::max(
              std::min(float_animation_curve->GetValue(trimmed), 1.0f), 0.f);
          NotifyObserversOpacityAnimated(
              opacity,
              animations_[i]->affects_active_observers(),
              animations_[i]->affects_pending_observers());
          break;
        }

        case TargetProperty::FILTER: {
          const FilterAnimationCurve* filter_animation_curve =
              animations_[i]->curve()->ToFilterAnimationCurve();
          const FilterOperations filter =
              filter_animation_curve->GetValue(trimmed);
          NotifyObserversFilterAnimated(
              filter,
              animations_[i]->affects_active_observers(),
              animations_[i]->affects_pending_observers());
          break;
        }

        case TargetProperty::BACKGROUND_COLOR: {
          // Not yet implemented.
          break;
        }

        case TargetProperty::SCROLL_OFFSET: {
          const ScrollOffsetAnimationCurve* scroll_offset_animation_curve =
              animations_[i]->curve()->ToScrollOffsetAnimationCurve();
          const gfx::ScrollOffset scroll_offset =
              scroll_offset_animation_curve->GetValue(trimmed);
          NotifyObserversScrollOffsetAnimated(
              scroll_offset,
              animations_[i]->affects_active_observers(),
              animations_[i]->affects_pending_observers());
          break;
        }
      }
    }
  }
}

void LayerAnimationController::UpdateActivation(UpdateActivationType type) {
  bool force = type == FORCE_ACTIVATION;
  if (registrar_) {
    bool was_active = is_active_;
    is_active_ = false;
    for (size_t i = 0; i < animations_.size(); ++i) {
      if (animations_[i]->run_state() != Animation::WAITING_FOR_DELETION) {
        is_active_ = true;
        break;
      }
    }

    if (is_active_ && (!was_active || force))
      registrar_->DidActivateAnimationController(this);
    else if (!is_active_ && (was_active || force))
      registrar_->DidDeactivateAnimationController(this);
  }
}

void LayerAnimationController::NotifyObserversOpacityAnimated(
    float opacity,
    bool notify_active_observers,
    bool notify_pending_observers) {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    LayerAnimationValueObserver* obs;
    while ((obs = it.GetNext()) != nullptr) {
      if ((notify_active_observers && notify_pending_observers) ||
          (notify_active_observers && obs->IsActive()) ||
          (notify_pending_observers && !obs->IsActive()))
        obs->OnOpacityAnimated(opacity);
    }
  }
}

void LayerAnimationController::NotifyObserversTransformAnimated(
    const gfx::Transform& transform,
    bool notify_active_observers,
    bool notify_pending_observers) {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    LayerAnimationValueObserver* obs;
    while ((obs = it.GetNext()) != nullptr) {
      if ((notify_active_observers && notify_pending_observers) ||
          (notify_active_observers && obs->IsActive()) ||
          (notify_pending_observers && !obs->IsActive()))
        obs->OnTransformAnimated(transform);
    }
  }
}

void LayerAnimationController::NotifyObserversFilterAnimated(
    const FilterOperations& filters,
    bool notify_active_observers,
    bool notify_pending_observers) {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    LayerAnimationValueObserver* obs;
    while ((obs = it.GetNext()) != nullptr) {
      if ((notify_active_observers && notify_pending_observers) ||
          (notify_active_observers && obs->IsActive()) ||
          (notify_pending_observers && !obs->IsActive()))
        obs->OnFilterAnimated(filters);
    }
  }
}

void LayerAnimationController::NotifyObserversScrollOffsetAnimated(
    const gfx::ScrollOffset& scroll_offset,
    bool notify_active_observers,
    bool notify_pending_observers) {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    LayerAnimationValueObserver* obs;
    while ((obs = it.GetNext()) != nullptr) {
      if ((notify_active_observers && notify_pending_observers) ||
          (notify_active_observers && obs->IsActive()) ||
          (notify_pending_observers && !obs->IsActive()))
        obs->OnScrollOffsetAnimated(scroll_offset);
    }
  }
}

void LayerAnimationController::NotifyObserversAnimationWaitingForDeletion() {
  FOR_EACH_OBSERVER(LayerAnimationValueObserver,
                    value_observers_,
                    OnAnimationWaitingForDeletion());
}

void LayerAnimationController::
    NotifyObserversTransformIsPotentiallyAnimatingChanged(
        bool notify_active_observers,
        bool notify_pending_observers) {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    LayerAnimationValueObserver* obs;
    while ((obs = it.GetNext()) != nullptr) {
      if (notify_active_observers && obs->IsActive())
        obs->OnTransformIsPotentiallyAnimatingChanged(
            potentially_animating_transform_for_active_observers_);
      else if (notify_pending_observers && !obs->IsActive())
        obs->OnTransformIsPotentiallyAnimatingChanged(
            potentially_animating_transform_for_pending_observers_);
    }
  }
}

bool LayerAnimationController::HasValueObserver() {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    return it.GetNext() != nullptr;
  }
  return false;
}

bool LayerAnimationController::HasActiveValueObserver() {
  if (value_observers_.might_have_observers()) {
    base::ObserverListBase<LayerAnimationValueObserver>::Iterator it(
        &value_observers_);
    LayerAnimationValueObserver* obs;
    while ((obs = it.GetNext()) != nullptr)
      if (obs->IsActive())
        return true;
  }
  return false;
}

}  // namespace cc


text:
package org.sagebionetworks.web.client.widget.entity.renderer;

import static org.sagebionetworks.web.client.ServiceEntryPointUtils.fixServiceEntryPoint;

import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.web.client.ChallengeClientAsync;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.SynapseJavascriptClient;
import org.sagebionetworks.web.client.place.LoginPlace;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.utils.CallbackP;
import org.sagebionetworks.web.client.widget.WidgetRendererPresenter;
import org.sagebionetworks.web.client.widget.evaluation.EvaluationSubmitter;
import org.sagebionetworks.web.shared.FormParams;
import org.sagebionetworks.web.shared.WidgetConstants;
import org.sagebionetworks.web.shared.WikiPageKey;
import org.sagebionetworks.web.shared.exceptions.ForbiddenException;

public class SubmitToEvaluationWidget
  implements SubmitToEvaluationWidgetView.Presenter, WidgetRendererPresenter {

  private SubmitToEvaluationWidgetView view;
  private Map<String, String> descriptor;
  private AuthenticationController authenticationController;
  private ChallengeClientAsync challengeClient;
  private GlobalApplicationState globalApplicationState;
  private Set<String> evaluationIds;
  private String formContainerId;
  private String formSchemaId;
  private String formUiSchemaId;
  PortalGinInjector ginInjector;
  private String evaluationUnavailableMessage;
  private SynapseJavascriptClient jsClient;

  @Inject
  public SubmitToEvaluationWidget(
    SubmitToEvaluationWidgetView view,
    SynapseJavascriptClient jsClient,
    ChallengeClientAsync challengeClient,
    AuthenticationController authenticationController,
    GlobalApplicationState globalApplicationState,
    PortalGinInjector ginInjector
  ) {
    this.view = view;
    view.setPresenter(this);
    this.challengeClient = challengeClient;
    fixServiceEntryPoint(challengeClient);
    this.authenticationController = authenticationController;
    this.globalApplicationState = globalApplicationState;
    this.jsClient = jsClient;
    this.ginInjector = ginInjector;
  }

  @Override
  public void configure(
    final WikiPageKey wikiKey,
    final Map<String, String> widgetDescriptor,
    Callback widgetRefreshRequired,
    Long wikiVersionInView
  ) {
    this.descriptor = widgetDescriptor;
    formContainerId = descriptor.get(WidgetConstants.FORM_CONTAINER_ID_KEY);
    formSchemaId = descriptor.get(WidgetConstants.JSON_SCHEMA_ID_KEY);
    formUiSchemaId = descriptor.get(WidgetConstants.UI_SCHEMA_ID_KEY);
    evaluationUnavailableMessage =
      descriptor.get(WidgetConstants.UNAVAILABLE_MESSAGE);

    String evaluationId = descriptor.get(WidgetConstants.EVALUATION_ID_KEY);
    if (evaluationId != null) {
      evaluationIds = new HashSet<String>();
      evaluationIds.add(evaluationId);
    }
    getEvaluationIds(
      descriptor,
      new CallbackP<Set<String>>() {
        @Override
        public void invoke(Set<String> evalIds) {
          evaluationIds = evalIds;
          final String buttonText = descriptor.get(
            WidgetConstants.BUTTON_TEXT_KEY
          );
          // figure out if we should show anything
          jsClient.getAvailableEvaluations(
            evaluationIds,
            true,
            Integer.MAX_VALUE,
            0,
            new AsyncCallback<List<Evaluation>>() {
              @Override
              public void onSuccess(List<Evaluation> results) {
                if (results.size() == 0) {
                  view.showUnavailable(evaluationUnavailableMessage);
                } else {
                  view.configure(buttonText);
                }
              }

              @Override
              public void onFailure(Throwable caught) {
                // if the user can't read the evaluation, then don't show the join button. if there was some other
                // error, then report it...
                if (!(caught instanceof ForbiddenException)) {
                  view.showUnavailable(
                    DisplayConstants.EVALUATION_SUBMISSION_ERROR +
                    caught.getMessage()
                  );
                }
              }
            }
          );
        }
      }
    );
  }

  /**
   * Get the evaluation queue ids
   *
   * @param callback
   */
  public void getEvaluationIds(
    Map<String, String> descriptor,
    final CallbackP<Set<String>> callback
  ) {
    String subchallengeIdList = null;
    if (
      descriptor.containsKey(
        WidgetConstants.JOIN_WIDGET_SUBCHALLENGE_ID_LIST_KEY
      )
    ) subchallengeIdList =
      descriptor.get(WidgetConstants.JOIN_WIDGET_SUBCHALLENGE_ID_LIST_KEY);
    if (subchallengeIdList != null) {
      String[] evaluationIdsArray = subchallengeIdList.split(
        WidgetConstants.JOIN_WIDGET_SUBCHALLENGE_ID_LIST_DELIMETER
      );
      Set<String> evaluationIds = new HashSet<String>();
      for (String evaluationId : evaluationIdsArray) {
        evaluationIds.add(evaluationId);
      }
      if (!evaluationIds.isEmpty()) callback.invoke(evaluationIds); else {
        view.showUnavailable(evaluationUnavailableMessage);
      }
      return;
    } else {
      AsyncCallback<Set<String>> asyncCallback = new AsyncCallback<Set<String>>() {
        @Override
        public void onSuccess(Set<String> evaluationIds) {
          // if no evaluations are accessible, do not continue (show nothing)
          if (!evaluationIds.isEmpty()) callback.invoke(
            evaluationIds
          ); else view.showUnavailable(evaluationUnavailableMessage);
        }

        @Override
        public void onFailure(Throwable caught) {
          view.showErrorMessage(
            DisplayConstants.CHALLENGE_EVALUATIONS_ERROR + caught.getMessage()
          );
        }
      };

      if (descriptor.containsKey(WidgetConstants.CHALLENGE_ID_KEY)) {
        // else, look for the challenge id
        String challengeId = descriptor.get(WidgetConstants.CHALLENGE_ID_KEY);
        challengeClient.getChallengeEvaluationIds(challengeId, asyncCallback);
      } else if (descriptor.containsKey(WidgetConstants.PROJECT_ID_KEY)) {
        // else, look for the project id
        String projectId = descriptor.get(WidgetConstants.PROJECT_ID_KEY);
        challengeClient.getProjectEvaluationIds(projectId, asyncCallback);
      } else if (!evaluationIds.isEmpty()) {
        callback.invoke(evaluationIds);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public void clearState() {}

  @Override
  public Widget asWidget() {
    return view.asWidget();
  }

  @Override
  public void gotoLoginPage() {
    goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN));
  }

  public void goTo(Place place) {
    globalApplicationState.getPlaceChanger().goTo(place);
  }

  @Override
  public void submitToChallengeClicked() {
    if (!authenticationController.isLoggedIn()) {
      // go to login page
      view.showAnonymousRegistrationMessage();
      // directs to the login page
    } else showSubmissionDialog();
  }

  public void showSubmissionDialog() {
    FormParams formParams = null;
    if (formContainerId != null) {
      formParams =
        new FormParams(formContainerId, formSchemaId, formUiSchemaId);
    }
    EvaluationSubmitter submitter = ginInjector.getEvaluationSubmitter();
    view.setEvaluationSubmitterWidget(submitter.asWidget());
    submitter.configure(null, evaluationIds, formParams);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.hl7.fhir.instance.model.valuesets;

// Generated on Tue, Sep 1, 2015 19:08-0400 for FHIR v1.0.0

public enum ListExampleCodes {

        /**
         * A list of alerts for the patient
         */
        ALERTS,
        /**
         * A list of part adverse reactions
         */
        ADVERSERXNS,
        /**
         * A list of Allergies for the patient
         */
        ALLERGIES,
        /**
         * A list of medication statements for the patient
         */
        MEDICATIONS,
        /**
         * A list of problems that the patient is known of have (or have had in the past)
         */
        PROBLEMS,
        /**
         * A list of items that constitute a set of work to be performed (typically this code would be specialised for more specific uses, such as a ward round list)
         */
        WORKLIST,
        /**
         * A list of items waiting for an event (perhaps a surgical patient waiting list)
         */
        WAITING,
        /**
         * A set of protocols to be followed
         */
        PROTOCOLS,
        /**
         * A set of care plans that apply in a particular context of care
         */
        PLANS,
        /**
         * added to help the parsers
         */
        NULL;
        public static ListExampleCodes fromCode(String codeString) throws Exception {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("alerts".equals(codeString))
          return ALERTS;
        if ("adverserxns".equals(codeString))
          return ADVERSERXNS;
        if ("allergies".equals(codeString))
          return ALLERGIES;
        if ("medications".equals(codeString))
          return MEDICATIONS;
        if ("problems".equals(codeString))
          return PROBLEMS;
        if ("worklist".equals(codeString))
          return WORKLIST;
        if ("waiting".equals(codeString))
          return WAITING;
        if ("protocols".equals(codeString))
          return PROTOCOLS;
        if ("plans".equals(codeString))
          return PLANS;
        throw new Exception("Unknown ListExampleCodes code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case ALERTS: return "alerts";
            case ADVERSERXNS: return "adverserxns";
            case ALLERGIES: return "allergies";
            case MEDICATIONS: return "medications";
            case PROBLEMS: return "problems";
            case WORKLIST: return "worklist";
            case WAITING: return "waiting";
            case PROTOCOLS: return "protocols";
            case PLANS: return "plans";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/list-example-use-codes";
        }
        public String getDefinition() {
          switch (this) {
            case ALERTS: return "A list of alerts for the patient";
            case ADVERSERXNS: return "A list of part adverse reactions";
            case ALLERGIES: return "A list of Allergies for the patient";
            case MEDICATIONS: return "A list of medication statements for the patient";
            case PROBLEMS: return "A list of problems that the patient is known of have (or have had in the past)";
            case WORKLIST: return "A list of items that constitute a set of work to be performed (typically this code would be specialised for more specific uses, such as a ward round list)";
            case WAITING: return "A list of items waiting for an event (perhaps a surgical patient waiting list)";
            case PROTOCOLS: return "A set of protocols to be followed";
            case PLANS: return "A set of care plans that apply in a particular context of care";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case ALERTS: return "Alerts";
            case ADVERSERXNS: return "Adverse Reactions";
            case ALLERGIES: return "Allergies";
            case MEDICATIONS: return "Medication List";
            case PROBLEMS: return "Problem List";
            case WORKLIST: return "Worklist";
            case WAITING: return "Waiting List";
            case PROTOCOLS: return "Protocols";
            case PLANS: return "Care Plans";
            default: return "?";
          }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright (C) 2015 Actor LLC. <https://actor.im>
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/searchField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="24dp"
        android:hint="@string/add_contact_phone_hint" />

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <include
        layout="@layout/bar_search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


text:
package de.mpg.mpdl.labcam;

import android.app.Application;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;

import com.facebook.react.ReactApplication;
import com.reactlibrary.RNLabCamLibraryPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.rnfs.RNFSPackage;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import org.reactnative.camera.RNCameraPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private NetworkChangeReceiver networkReceiver = new NetworkChangeReceiver();

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new RNLabCamLibraryPackage(),
            new VectorIconsPackage(),
            new RNFSPackage(),
            new RNFetchBlobPackage(),
            new RNCameraPackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);

    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    registerReceiver(
            networkReceiver,
            filter
    );
  }

  @Override
  public void onTerminate() {
    super.onTerminate();
    unregisterReceiver(networkReceiver);
  }

}


text:
/*
 * cg.h
 *
 *  Created on: July 23, 2016
 *      Author: weitan
 */

#ifndef CG_H_
#define CG_H_

int updateXWithCG(const int batchSize, const int batchOffset, float * ythetaT, float * tt, float * XT,
		cublasHandle_t handle, const int m, const int n, const int f, const int nnz);

void updateXWithCGHost(float * A, float * x, float * b, const int batchSize, const int f, const float cgIter);

void updateXWithCGHost_tt_fp16(float * A, float * x, float * b, const int batchSize, const int f, const float cgIter);

void alsUpdateFeature100Host(const int batch_offset,
		const int* csrRowIndex, const int* csrColIndex, const float lambda, const int m, const int F,
		const float* thetaT, float* XT, float* ythetaT, int cgIter);
#endif /* CG_H_ */


text:
function [e E] = xyzankurError(X1,X2,type)

% XYZANKURERROR Computes the error between two poses in xyz format
%
%	Description:
%
%	E = XYZANKURERROR(X1, X2) Computes the error between two poses in
%	xyz format data.
%	 Returns:
%	  E - mean error for the sequence
%	 Arguments:
%	  X1 - first set of poses
%	  X2 - second set of poses
%
%
%
%	See also
%	XYZANKURDRAW, XYZANKURMODIFY

%	Copyright (c) Andreas Damianou  and Neil Lawrence, 2011 Carl Henrik Ek

if(nargin<2)
    error('Too few arguments');
end
if(size(X1)~=size(X2))
    error('Dimensions mismatch');
end

E = zeros(size(X1,1),1);
for(i = 1:1:size(X1,1))
    E(i) = mean(sqrt(sum((xyzankur2joint(X1(i,:)) - xyzankur2joint(X2(i,:))).^2,2)));
end
e = mean(E);

return


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/assets/js/";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	__webpack_require__(10);
	module.exports = __webpack_require__(15);

/***/ },
/* 1 */,
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	(function webpackUniversalModuleDefinition(root, factory) {
		if(true)
			module.exports = factory();
		else if(typeof define === 'function' && define.amd)
			define([], factory);
		else {
			var a = factory();
			for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
		}
	})(this, function() {
	return /******/ (function(modules) { // webpackBootstrap
	/******/ 	// The module cache
	/******/ 	var installedModules = {};

	/******/ 	// The require function
	/******/ 	function __webpack_require__(moduleId) {

	/******/ 		// Check if module is in cache
	/******/ 		if(installedModules[moduleId])
	/******/ 			return installedModules[moduleId].exports;

	/******/ 		// Create a new module (and put it into the cache)
	/******/ 		var module = installedModules[moduleId] = {
	/******/ 			exports: {},
	/******/ 			id: moduleId,
	/******/ 			loaded: false
	/******/ 		};

	/******/ 		// Execute the module function
	/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

	/******/ 		// Flag the module as loaded
	/******/ 		module.loaded = true;

	/******/ 		// Return the exports of the module
	/******/ 		return module.exports;
	/******/ 	}

	/******/ 	// expose the modules object (__webpack_modules__)
	/******/ 	__webpack_require__.m = modules;

	/******/ 	// expose the module cache
	/******/ 	__webpack_require__.c = installedModules;

	/******/ 	// __webpack_public_path__
	/******/ 	__webpack_require__.p = "";

	/******/ 	// Load entry module and return exports
	/******/ 	return __webpack_require__(0);
	/******/ })
	/************************************************************************/
	/******/ ([
	/* 0 */
	/***/ function(module, exports, __webpack_require__) {

		/*
		  Version: 0.0.1
		  Author: Cheft
		*/
		var Component = __webpack_require__(1);
		var observable = __webpack_require__(3);

		var coala = {
		  observable: observable,

		  mount: function(opts, el) {
		    return new Component(opts).mount(el);
		  }
		};

		observable(coala);

		module.exports = coala;

	/***/ },
	/* 1 */
	/***/ function(module, exports, __webpack_require__) {

		var util = __webpack_require__(2);
		var observable = __webpack_require__(3);

		function Component(opts) {
		  this.opts = opts;
		  this.tpl = opts.tpl || {};
		  this.el = opts.el ? $(opts.el) : undefined;
		  this.data = opts.data || {};
		  this.listen = opts.listen || {};
		  this.events = opts.events || {};
		  this.handle = opts.handle || {};
		  this.refs = {};
		  this.id = util.uniqueId('component');
		  observable(this);
		  this._listenTo();
		  this.trigger('init');
		}

		Component.prototype.mount = function(el) {
		  this.el = el ? $(el) : this.el;
		  this.update();
		  this.trigger('mount');
		  return this;
		};

		Component.prototype.update = function(data) {
		  this.trigger('update');
		  this.data = data || this.data;
		  if (this.rid) {
		    var parentEl = this.el;
		    var html = this._html();
		    var $html = $(html).attr('rid', this.rid);
		    parentEl.append($html[0].outerHTML);
		    this.el = parentEl.find('[rid=' + this.rid + ']');
		    delete this.rid;
		  }else {
		    this.el.empty().html(this._html());
		  }

		  this._mountRefs(this);
		  this._bindEvents();
		  this.trigger('updated');
		};

		Component.prototype.unmount = function() {
		  this.el.empty();
		  this.trigger('unmount');
		};

		Component.prototype._html = function() {
		  return this.tpl(this.data);
		};

		Component.prototype._mountRefs = function(parent) {
		  if (!this.opts.refs) {
		    return;
		  }

		  for (var p in this.opts.refs) {
		    var component;
		    var value = this.opts.refs[p];
		    if (value.component) {
		      var component = new Component(value.component);
		      if (value.data) {
		        component.data = value.data;
		      }

		      if (value.rid) {
		        component.rid = value.rid;
		      }

		      component.el = $(value.el);
		    }else {
		      component = new Component(value);
		      component.el = $(p);
		    }

		    component.parent = parent;
		    component.mount();
		    this.refs[p] = component;
		  }
		};

		Component.prototype._bindEvents = function() {
		  for (var e in this.events) {
		    var handleName = this.events[e];
		    var $el = this.el.find(e.split(' ')[1]);
		    $el.on(e.split(' ')[0], $.proxy(this.handle[handleName], this));
		  }
		};

		Component.prototype._listenTo = function() {
		  for (var l in this.listen) {
		    var fn = this.listen[l];
		    this.on(l, fn);
		  }
		};

		module.exports = Component;

	/***/ },
	/* 2 */
	/***/ function(module, exports) {

		module.exports = {
		  counter: 0,
		  uniqueId: function(prefix) {
		    return (prefix || '') + (++this.counter);
		  },

		  isUndefined: function(obj) {
		    return typeof obj == 'undefined';
		  },

		  isFunction: function(obj) {
		    return typeof obj == 'function';
		  }
		};

	/***/ },
	/* 3 */
	/***/ function(module, exports, __webpack_require__) {

		var util = __webpack_require__(2);

		module.exports = function(el) {
		  el = el || {};
		  var callbacks = {};
		  var _id = 0;

		  el.on = function(events, fn) {
		    if (util.isFunction(fn)) {
		      if (util.isUndefined(fn.id)) {
		        fn._id = _id++;
		      }

		      events.replace(/\S+/g, function(name, pos) {
		        (callbacks[name] = callbacks[name] || []).push(fn);
		        fn.typed = pos > 0;
		      });
		    }

		    return el;
		  };

		  el.off = function(events, fn) {
		    if (events == '*') {
		      callbacks = {};
		    }else {
		      events.replace(/\S+/g, function(name) {
		        if (fn) {
		          var arr = callbacks[name];
		          for (var i = 0, cb; (cb = arr && arr[i]); ++i) {
		            if (cb._id == fn._id) {
		              arr.splice(i--, 1);
		            }
		          }
		        } else {
		          callbacks[name] = [];
		        }
		      });
		    }

		    return el;
		  };

		  // only single event supported
		  el.one = function(name, fn) {
		    function on() {
		      el.off(name, on);
		      fn.apply(el, arguments);
		    }

		    return el.on(name, on);
		  };

		  el.trigger = function(name) {
		    var args = [].slice.call(arguments, 1);
		    var fns = callbacks[name] || [];

		    for (var i = 0, fn; (fn = fns[i]); ++i) {
		      if (!fn.busy) {
		        fn.busy = 1;
		        fn.apply(el, fn.typed ? [name].concat(args) : args);
		        if (fns[i] !== fn) {
		          i--;
		        }

		        fn.busy = 0;
		      }
		    }

		    if (callbacks.all && name != 'all') {
		      el.trigger.apply(el, ['all', name].concat(args));
		    }

		    return el;
		  };

		  return el;
		};

	/***/ }
	/******/ ])
	});
	;

/***/ },
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */
/***/ function(module, exports, __webpack_require__) {

	/*
		MIT License http://www.opensource.org/licenses/mit-license.php
		Author Tobias Koppers @sokra
	*/
	/*globals window __webpack_hash__ */
	if(false) {
		var lastData;
		var upToDate = function upToDate() {
			return lastData.indexOf(__webpack_hash__) >= 0;
		};
		var check = function check() {
			module.hot.check(true, function(err, updatedModules) {
				if(err) {
					if(module.hot.status() in {
							abort: 1,
							fail: 1
						}) {
						console.warn("[HMR] Cannot apply update. Need to do a full reload!");
						console.warn("[HMR] " + err.stack || err.message);
						window.location.reload();
					} else {
						console.warn("[HMR] Update failed: " + err.stack || err.message);
					}
					return;
				}

				if(!updatedModules) {
					console.warn("[HMR] Cannot find update. Need to do a full reload!");
					console.warn("[HMR] (Probably because of restarting the webpack-dev-server)");
					window.location.reload();
					return;
				}

				if(!upToDate()) {
					check();
				}

				require("./log-apply-result")(updatedModules, updatedModules);

				if(upToDate()) {
					console.log("[HMR] App is up to date.");
				}

			});
		};
		var addEventListener = window.addEventListener ? function(eventName, listener) {
			window.addEventListener(eventName, listener, false);
		} : function(eventName, listener) {
			window.attachEvent("on" + eventName, listener);
		};
		addEventListener("message", function(event) {
			if(typeof event.data === "string" && event.data.indexOf("webpackHotUpdate") === 0) {
				lastData = event.data;
				if(!upToDate() && module.hot.status() === "idle") {
					console.log("[HMR] Checking for updates on the server...");
					check();
				}
			}
		});
		console.log("[HMR] Waiting for update signal from WDS...");
	} else {
		throw new Error("[HMR] Hot Module Replacement is disabled.");
	}

/***/ },
/* 11 */,
/* 12 */,
/* 13 */,
/* 14 */,
/* 15 */
/***/ function(module, exports, __webpack_require__) {

	var coala = __webpack_require__(2);
	var github = __webpack_require__(16);
	var githubDynamic = __webpack_require__(18);
	var tpl = __webpack_require__(22);

	var mytodo = {
	  tpl: tpl,
	  refs: {
	    '#todo1': github,
	    '#todo2': githubDynamic
	  }
	};

	window.todo = coala.mount(mytodo, '#app');

/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {

	var tpl = __webpack_require__(17);

	module.exports = {
	  tpl: tpl,
	  listen: {
	    mount: function() {
	      console.log(111);
	      this.trigger('fetch', 'react');
	    },

	    updated: function() {
	      this.el.find('#search').focus();
	    },

	    fetch: function(keyword) {
	      var _this = this;
	      $.ajax({
	        // url: 'https://api.github.com/search/repositories?q=' + keyword + '&sort=start',
	        url: 'http://localhost:3000/github',
	        type: 'get'
	      }).done(function(data) {
	        _this.data = data;
	        _this.update();
	      });
	    }
	  },

	  events: {
	    'keypress #search': 'search'
	  },

	  handle: {
	    search: function(e) {
	      if (e.keyCode === 13) {
	        this.trigger('fetch', e.target.value);
	      }
	    }
	  }
	};

/***/ },
/* 17 */
/***/ function(module, exports) {

	module.exports = function anonymous(it
	/**/) {
	var out='

这里所有的项是一个 view
 <input id="search" placeholder="enter search"/>
';var arr1=it.items;if(arr1){var gh,index=-1,l1=arr1.length-1;while(index<l1){gh=arr1[index+=1];out+='

'+( gh.name)+'

'+( gh.owner.login)+'

';} } return out;
	}

/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {

	var item = __webpack_require__(19);
	var tpl = __webpack_require__(21);

	module.exports = {
	  tpl: tpl,
	  listen: {
	    mount: function() {
	      this.trigger('fetch', 'react');
	    },

	    updated: function() {
	      this.el.find('#search').focus();
	    },

	    fetch: function(keyword) {
	      var _this = this;
	      _this.opts.refs = {};
	      $.ajax({
	        // url: 'https://api.github.com/search/repositories?q=' + keyword + '&sort=start',
	        url: 'http://localhost:3000/github',
	        type: 'get'
	      }).done(function(data) {
	        for (var i = 0; i < data.items.length; i++) {
	          var com = {
	            component: item,
	            data: data.items[i],
	            el: '#repositories',
	            rid: 'item_' + data.items[i].id
	          };
	          _this.opts.refs[com.rid] = com;
	        }

	        _this.update();
	      });
	    }
	  },

	  events: {
	    'keypress #search': 'search'
	  },

	  handle: {
	    search: function(e) {
	      if (e.keyCode === 13) {
	        this.trigger('fetch', e.target.value);
	      }
	    }
	  }
	};

/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {

	var tpl = __webpack_require__(20);

	module.exports = {
	  tpl: tpl,
	  listen: {
	    updated: function() {
	      // console.log(this.el.attr('id') + ' item updated');
	    }
	  },

	  events: {
	    'click [id^=img-]': 'test'
	  },

	  handle: {
	    test: function() {
	      this.data.name = 'Chefttttttttttttttt!';
	      this.data.owner.avatar_url = 'https://avatars0.githubusercontent.com/u/1567209?v=3&s=460';
	      this.update();
	    }
	  }
	};

/***/ },
/* 20 */
/***/ function(module, exports) {

	module.exports = function anonymous(it
	/**/) {
	var out='

'+(it.name)+'

'+( it.owner.login)+'

';return out;
	}

/***/ },
/* 21 */
/***/ function(module, exports) {

	module.exports = function anonymous(it
	/**/) {
	var out='

这里每一项都是一个 view
 <input id="search" placeholder="enter search"/>

';return out;
	}

/***/ },
/* 22 */
/***/ function(module, exports) {

	module.exports = function anonymous(it
	/**/) {
	var out='

';return out;
	}

/***/ }
/******/ ]);


text:
import {Pos} from "../model"
import {NamespaceError} from "../util/error"

import {nullMap} from "./map"

// ;; A step object wraps an atomic operation. It generally applies
// only to the document it was created for, since the positions
// associated with it will only make sense for that document.
export class Step {
  // :: (string, ?Pos, ?Pos, ?Pos, ?any)
  // Build a step. The type should name a [defined](Step.define) step
  // type, and the shape of the positions and parameter should be
  // appropriate for that type.
  constructor(type, from, to, pos, param = null) {
    if (!(type in steps)) throw new NamespaceError("Unknown step type: " + type)
    // :: string
    // The type of the step.
    this.type = type
    // :: ?Pos
    // The start of the step's range, if any. Which of the three
    // optional positions associated with a step a given step type
    // uses differs. The way each of these positions is mapped when
    // the step is mapped over a [position mapping](#PosMap) depends
    // on its role.
    this.from = from
    // :: ?Pos
    // The end of the step's range.
    this.to = to
    // :: ?Pos
    // The base position for this step.
    this.pos = pos
    // :: ?any
    // Extra step-type-specific information associated with the step.
    this.param = param
  }

  // :: (Node) → ?StepResult
  // Applies this step to the given document, returning a result
  // containing the transformed document (the input document is not
  // changed) and a `PosMap`. If the step could not meaningfully be
  // applied to the given document, this returns `null`.
  apply(doc) {
    return steps[this.type].apply(doc, this)
  }

  // :: (Node, PosMap) → Step
  // Create an inverted version of this step. Needs the document as it
  // was before the step, as well as `PosMap` created by applying the
  // step to that document, as input.
  invert(oldDoc, map) {
    return steps[this.type].invert(this, oldDoc, map)
  }

  // :: (Mappable) → ?Step
  // Map this step through a mappable thing, returning either a
  // version of that step with its positions adjusted, or `null` if
  // the step was entirely deleted by the mapping.
  map(remapping) {
    let allDeleted = true
    let from = null, to = null, pos = null

    if (this.from) {
      let result = remapping.map(this.from, 1)
      from = result.pos
      if (!result.deleted) allDeleted = false
    }
    if (this.to) {
      if (this.to.cmp(this.from) == 0) {
        to = from
      } else {
        let result = remapping.map(this.to, -1)
        to = result.pos.max(from)
        if (!result.deleted) allDeleted = false
      }
    }
    if (this.pos) {
      if (from && this.pos.cmp(this.from) == 0) {
        pos = from
      } else if (to && this.pos.cmp(this.to) == 0) {
        pos = to
      } else {
        let result = remapping.map(this.pos, 1)
        pos = result.pos
        if (!result.deleted) allDeleted = false
      }
    }
    return allDeleted ? null : new Step(this.type, from, to, pos, this.param)
  }

  // :: () → Object
  // Create a JSON-serializeable representation of this step.
  toJSON() {
    let impl = steps[this.type]
    return {
      type: this.type,
      from: this.from,
      to: this.to,
      pos: this.pos,
      param: impl.paramToJSON ? impl.paramToJSON(this.param) : this.param
    }
  }

  // :: (Schema, Object) → Step
  // Deserialize a step from its JSON representation.
  static fromJSON(schema, json) {
    let impl = steps[json.type]
    return new Step(
      json.type,
      json.from && Pos.fromJSON(json.from),
      json.to && Pos.fromJSON(json.to),
      json.pos && Pos.fromJSON(json.pos),
      impl.paramFromJSON ? impl.paramFromJSON(schema, json.param) : json.param)
  }

  // :: (string, Object)
  // Define a new type of step. Implementation should have the
  // following properties:
  //
  // **`apply`**`(doc: Node, step: Step) → ?StepResult
  //   : Applies the step to a document.
  // **`invert`**`(step: Step, oldDoc: Node, map: PosMap) → Step
  //   : Create an inverted version of the step.
  // **`paramToJSON`**`(param: ?any) → ?Object
  //   : Serialize this step type's parameter to JSON.
  // **`paramFromJSON`**`(schema: Schema, json: ?Object) → ?any
  //   : Deserialize this step type's parameter from JSON.
  static define(type, implementation) {
    steps[type] = implementation
  }
}

// ;; Objects of this type are returned as the result of
// applying a transform step to a document.
export class StepResult {
  constructor(doc, map = nullMap) {
    // :: Node The transformed document.
    this.doc = doc
    // :: PosMap
    // The position map that describes the correspondence between the
    // old and the new document.
    this.map = map
  }
}

const steps = Object.create(null)


text:
/*************************************************************************************************/
/*!
 *  \file   hci_tr.h
 *
 *  \brief  HCI transport interface.
 *
 *          $Date: 2016-12-28 16:12:14 -0600 (Wed, 28 Dec 2016) $
 *          $Revision: 10805 $
 *
 *  Copyright (c) 2009-2017 ARM Ltd., all rights reserved.
 *  SPDX-License-Identifier: LicenseRef-PBL
 *
 *  This file and the related binary are licensed under the
 *  Permissive Binary License, Version 1.0 (the "License");
 *  you may not use these files except in compliance with the License.
 *
 *  You may obtain a copy of the License here:
 *  LICENSE-permissive-binary-license-1.0.txt and at
 *  https://www.mbed.com/licenses/PBL-1.0
 *
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/*************************************************************************************************/
#ifndef HCI_TR_H
#define HCI_TR_H

#ifdef __cplusplus
extern "C" {
#endif

/**************************************************************************************************
  Function Declarations
**************************************************************************************************/

void hciTrSendAclData(void *pContext, uint8_t *pAclData);
void hciTrSendCmd(uint8_t *pCmdData);
bool_t hciTrInit(uint8_t port, uint32_t baudRate, bool_t flowControl);
void hciTrShutdown(void);

#ifdef __cplusplus
};
#endif

#endif /* HCI_TR_H */


text:
"""
Created on Fri Jan 27 17:58:35 2017

@author: Suhas Somnath
"""

from __future__ import division, print_function, absolute_import, unicode_literals

from os import path, remove
import h5py
import numpy as np  # For array operations
from scipy.io import loadmat

from .translator import Translator
from .utils import build_ind_val_dsets
from ..microdata import MicroDataset  # building blocks for defining hierarchical storage in the H5 file

class ForcIVTranslator(Translator):
    """
    Translates FORC IV datasets from .mat files to .h5
    """

    def _parse_file_path(self, input_path):
        pass

    def translate(self, raw_data_path):
        """
        The main function that translates the provided file into a .h5 file

        Parameters
        ------------
        raw_data_path : string / unicode
            Absolute file path of the data .mat file.

        Returns
        ----------
        h5_path : string / unicode
            Absolute path of the translated h5 file
        """
        folder_path, file_name = path.split(raw_data_path)

        h5_path = path.join(folder_path, file_name[:-4] + '.h5')
        if path.exists(h5_path):
            remove(h5_path)

        self.h5_read = True
        try:
            h5_f = h5py.File(raw_data_path, 'r')
        except ImportError:
            self.h5_read = False
            h5_f = loadmat(raw_data_path)

        excite_cell = h5_f['dc_amp_cell3']
        test = excite_cell[0][0]
        if self.h5_read:
            excitation_vec = h5_f[test]
        else:
            excitation_vec = np.float32(np.squeeze(test))

        current_cell = h5_f['current_cell3']

        num_rows = current_cell.shape[0]
        num_cols = current_cell.shape[1]
        num_iv_pts = excitation_vec.size

        current_data = np.zeros(shape=(num_rows * num_cols, num_iv_pts), dtype=np.float32)
        for row_ind in range(num_rows):
            for col_ind in range(num_cols):
                pix_ind = row_ind * num_cols + col_ind
                if self.h5_read:
                    curr_val = np.squeeze(h5_f[current_cell[row_ind][col_ind]].value)
                else:
                    curr_val = np.float32(np.squeeze(current_cell[row_ind][col_ind]))
                current_data[pix_ind, :] = 1E+9 * curr_val

        parm_dict = self._read_parms(h5_f)

        ds_main = MicroDataset('Raw_Data', data=current_data, dtype=np.float32, compression='gzip',
                               chunking=(min(num_cols * num_rows, 100), num_iv_pts))
        ds_main.attrs = {'quantity': 'Current', 'units': '1E-9 A'}

        ds_pos_ind, ds_pos_val = build_ind_val_dsets([num_rows, num_cols], is_spectral=False,
                                                     labels=['Y', 'X'], units=['m', 'm'], verbose=False)
        ds_spec_inds, ds_spec_vals = build_ind_val_dsets([num_iv_pts], is_spectral=True,
                                                         labels=['DC Bias'], units=['V'], verbose=False)
        ds_spec_vals.data = np.atleast_2d(excitation_vec)

        return super(ForcIVTranslator, self).simple_write(h5_path, 'FORC_IV', ds_main,
                                                          [ds_pos_ind, ds_pos_val, ds_spec_inds, ds_spec_vals],
                                                          parm_dict)

    def _read_parms(self, raw_data_file_handle):
        """
        Copies experimental parameters from the .mat file to a dictionary

        Parameters
        ----------
        raw_data_file_handle : h5py.Group object or dictionary
            Handle to the file containing the raw data

        Returns
        -------
        parm_dict : dictionary
            Dictionary containing all relevant parameters
        """
        parm_dict = dict()
        exceptions = ['Z_cell3', 'current_cell3', 'dc_amp_cell3', 'loop_area_rel', '__version__', '__header__',
                      '__globals__']
        for att_name in raw_data_file_handle:
            if att_name not in exceptions:
                if not self.h5_read:
                    parm_dict[att_name] = raw_data_file_handle[att_name][0][0]
        return parm_dict


text:
Installation
============

From PyPI
---------

Donfig can be installed from PyPI using pip:

.. code-block:: bash

    pip install donfig

From Conda
----------

Donfig is available on the conda-forge conda channel:

.. code-block:: bash

    conda install -c conda-forge donfig

From Github
-----------

The current version on github can be installed directly with pip:

.. code-block:: bash

    pip install git+https://github.com/pytroll/donfig.git

From Source
-----------

After downloading the source code for donfig from github or other source,
the package can be installed in a "development mode" by running:

.. code-block:: bash

    pip install -e .

This will install the package so that any changes to the source code are
immediately reflected in your environment.


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * Organizations profiles module.
 */
class BxOrgsModule extends BxBaseModGroupsModule
{
    function __construct(&$aModule)
    {
        parent::__construct($aModule);

        $CNF = &$this->_oConfig->CNF;

        $this->_aSearchableNamesExcept[] = $CNF['FIELD_AUTHOR'];
        $this->_aSearchableNamesExcept[] = $CNF['FIELD_JOIN_CONFIRMATION'];
    }

	/**
     * Check if this module entry can be used as profile
     */
    public function serviceActAsProfile ()
    {
        return true;
    }

    public function serviceGetSearchResultUnit ($iContentId, $sUnitTemplate = '')
    {
        if(empty($sUnitTemplate))
            $sUnitTemplate = 'unit_with_cover.html';

        return parent::serviceGetSearchResultUnit($iContentId, $sUnitTemplate);
    }

    /**
     * @see BxBaseModProfileModule::serviceGetSpaceTitle
     */
    public function serviceGetSpaceTitle()
    {
        return BxBaseModProfileModule::serviceGetSpaceTitle();
    }

    /**
     * @see iBxDolProfileService::serviceGetParticipatingProfiles
     */
    public function serviceGetParticipatingProfiles($iProfileId, $aConnectionObjects = false)
    {
        if (false === $aConnectionObjects)
            $aConnectionObjects = array('sys_profiles_friends');
        return BxBaseModProfileModule::serviceGetParticipatingProfiles($iProfileId, $aConnectionObjects);
    }

    public function servicePrepareFields ($aFieldsProfile)
    {
        return parent::_servicePrepareFields($aFieldsProfile, array('org_cat' => 35), array(
            'org_name' => 'name',
            'org_desc' => 'description',
        ));
    }

    public function serviceGetTimelineData()
    {
    	return BxBaseModProfileModule::serviceGetTimelineData();
    }

    public function onFanRemovedFromAdmins($iGroupProfileId, $iProfileId)
    {
        if (!($oProfile = BxDolProfile::getInstance($iProfileId)))
            return false;
        $oAccount = $oProfile->getAccountObject();
        $oAccount->updateProfileContextAuto();
    }

    public function checkAllowedCompose (&$aDataEntry, $isPerformAction = false)
    {
        return BxBaseModProfileModule::checkAllowedCompose ($aDataEntry, $isPerformAction);
    }
}

/** @} */


text:
package io.github.zhihulittlepaper.util;

import io.github.zhihulittlepaper.entity.News;
import io.github.zhihulittlepaper.entity.NewsDetail;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONUtils {

	public static List<News> parseNewsList(String data) {
		List<News> newsList = new ArrayList<News>();
		try {
			JSONObject obj = new JSONObject(data);
			String date = obj.getString("date");

			Log.i("tedu", "»ñµÃеÄÐÂÎÅÁбíµÄÈÕÆÚ=" + date);

			JSONArray arr = obj.getJSONArray("stories");
			int length = arr.length();
			for(int i = 0; i< length; i++) {
				JSONObject objNews = arr.getJSONObject(i);
				News news = new News();
				news.setId(objNews.getString("id"));
				news.setTitle(objNews.getString("title"));
				news.setImage(fixUrl(objNews.getString("images")));
				news.setDate(date);
				newsList.add(news);
			}
			return newsList;
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String fixUrl(String string) {
		string = string.substring(2, string.length() - 2);
		String sub;
		String url;
		sub = string.substring(0, 5);
		url = sub + "//";
		sub = string.substring(9, 23);
		url = url + sub + "/";
		sub = string.substring(25);
		url = url + sub;
		return url;
	}

	public static NewsDetail parseNewsDetail(String data) {
		NewsDetail detail = new NewsDetail();
		try {
			JSONObject obj = new JSONObject(data);
			detail.setBody(obj.getString("body"));
			detail.setImageSource(obj.getString("image_source"));
			detail.setImage(obj.getString("image"));
			return detail;
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

}


text:
<organisation>
	<id eid="orgUnitId"></id>
	<name eid="orgUnitName"></name>
	<address>
		<line1 eid="addr1"></line1>
		<line2 eid="addr2"></line2>
		<city eid="city"></city>
		<country eid="countryCode"></country>
		<postcode eid="postcode"></postcode>
	</address>
</organisation>


text:
{{ title }}

  <form name="editForm" ng-submit="addFormItem()">
    <fieldset ng-show="groups.length">
      <legend>Current group(s)</legend>

            Group ID
            Action

            {{ group.groupId }}

    </fieldset>

    <fieldset>
      <legend>Add a group</legend>

        <input type="text"
               ng-model="newItem"
               name="newItem"
               required />
        <button ng-click="addItem()"
                type="submit"
                class="btn btn-primary"
                ng-disabled="invalid()">

        </button>

    </fieldset>
  </form>

  <button ng-repeat="btn in buttons"
          ng-click="close(btn.result)"
          class="btn" ng-class="btn.cssClass">
    {{ btn.label }}
  </button>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Symb. bot. upsal. 16(no. 1): 104 (1958)

#### Original name
Odontia quercina Pers., 1800

### Remarks
null


text:
package org.rtevo.gui;

import org.jbox2d.common.Vec2;
import org.rtevo.common.Vector;

/**
 * Deals with transformations for world->screen coordinates.
 *
 * Always at the center of the window.
 */
public class Camera {
    private final Renderer renderer;
    private Vector<Integer> position = new Vector<Integer>(0, 0);
    private Vector<Integer> lastDrag = new Vector<Integer>(0, 0);
    private static final double pixelsPerMeter = 250;
    private final double scrollScale = 0.2;
    private double zoom = 0.15;

    public Camera(Renderer renderer) {
        this.renderer = renderer;
    }

    public Vector<Integer> translate(Vector<Float> toTranslate) {
        Vector<Integer> point = new Vector<Integer>();

        point.x = (int) ((toTranslate.x * pixelsPerMeter - position.x) * zoom);
        point.y = (int) ((toTranslate.y * pixelsPerMeter - position.y) * zoom);

        point.x += renderer.getWidth() / 2;
        point.y += renderer.getHeight() / 2;

        return point;
    }

    public Vector<Integer> translate(Vec2 worldPosition) {
        Vector<Float> position = new Vector<Float>();
        position.x = worldPosition.x;
        position.y = worldPosition.y;
        return translate(position);
    }

    public Vector<Integer> translateRelative(Vec2 worldPosition) {
        Vector<Integer> point = new Vector<Integer>();

        point.x = (int) (worldPosition.x * pixelsPerMeter * zoom);
        point.y = (int) (worldPosition.y * pixelsPerMeter * zoom);

        return point;
    }

    public float translateRelative(float a) {
        return (float) (a * zoom);
    }

    public int translateRelative(int a) {
        return (int) (a * zoom);
    }

    public void startDragging(int x, int y) {
        lastDrag = new Vector<Integer>(x, y);
    }

    public void updateDragging(int x, int y) {
        position.x -= (int) ((x - lastDrag.x) / zoom);
        position.y -= (int) ((y - lastDrag.y) / zoom);

        lastDrag.x = x;
        lastDrag.y = y;
    }

    public void scrolled(int amount) {
        float newZoom = (float) (zoom - amount * scrollScale * zoom);
        if (newZoom > 0.02 && newZoom < 1) {
            zoom = newZoom;
        }
    }

}