text:
// Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cc/trees/single_thread_proxy.h"

#include <memory>
#include <utility>
#include <vector>

#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/trace_event/trace_event.h"
#include "build/chromeos_buildflags.h"
#include "cc/base/completion_event.h"
#include "cc/base/devtools_instrumentation.h"
#include "cc/benchmarks/benchmark_instrumentation.h"
#include "cc/input/browser_controls_offset_manager.h"
#include "cc/metrics/compositor_timing_history.h"
#include "cc/paint/paint_worklet_layer_painter.h"
#include "cc/resources/ui_resource_manager.h"
#include "cc/scheduler/commit_earlyout_reason.h"
#include "cc/scheduler/scheduler.h"
#include "cc/trees/compositor_commit_data.h"
#include "cc/trees/latency_info_swap_promise.h"
#include "cc/trees/layer_tree_frame_sink.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_host_single_thread_client.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/mutator_host.h"
#include "cc/trees/paint_holding_reason.h"
#include "cc/trees/render_frame_metadata_observer.h"
#include "cc/trees/scoped_abort_remaining_swap_promises.h"
#include "components/power_scheduler/power_mode_arbiter.h"
#include "components/viz/common/frame_sinks/delay_based_time_source.h"
#include "components/viz/common/frame_timing_details.h"
#include "components/viz/common/gpu/context_provider.h"

namespace cc {

std::unique_ptr<Proxy> SingleThreadProxy::Create(
    LayerTreeHost* layer_tree_host,
    LayerTreeHostSingleThreadClient* client,
    TaskRunnerProvider* task_runner_provider) {
  return base::WrapUnique(
      new SingleThreadProxy(layer_tree_host, client, task_runner_provider));
}

SingleThreadProxy::SingleThreadProxy(LayerTreeHost* layer_tree_host,
                                     LayerTreeHostSingleThreadClient* client,
                                     TaskRunnerProvider* task_runner_provider)
    : layer_tree_host_(layer_tree_host),
      single_thread_client_(client),
      task_runner_provider_(task_runner_provider),
      next_frame_is_newly_committed_frame_(false),
#if DCHECK_IS_ON()
      inside_impl_frame_(false),
#endif
      inside_draw_(false),
      defer_main_frame_update_(false),
      animate_requested_(false),
      update_layers_requested_(false),
      commit_requested_(false),
      inside_synchronous_composite_(false),
      needs_impl_frame_(false),
      layer_tree_frame_sink_creation_requested_(false),
      layer_tree_frame_sink_lost_(true) {
  TRACE_EVENT0("cc", "SingleThreadProxy::SingleThreadProxy");
  DCHECK(task_runner_provider_);
  DCHECK(task_runner_provider_->IsMainThread());
  DCHECK(layer_tree_host);
}

void SingleThreadProxy::Start() {
  DebugScopedSetImplThread impl(task_runner_provider_);

  const LayerTreeSettings& settings = layer_tree_host_->GetSettings();
  DCHECK(settings.single_thread_proxy_scheduler ||
         !settings.enable_checker_imaging)
      << "Checker-imaging is not supported in synchronous single threaded mode";
  {
    DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
    host_impl_ = layer_tree_host_->CreateLayerTreeHostImpl(this);
  }
  if (settings.single_thread_proxy_scheduler && !scheduler_on_impl_thread_) {
    SchedulerSettings scheduler_settings(settings.ToSchedulerSettings());
    scheduler_settings.commit_to_active_tree = true;

    std::unique_ptr<CompositorTimingHistory> compositor_timing_history(
        new CompositorTimingHistory(
            scheduler_settings.using_synchronous_renderer_compositor,
            CompositorTimingHistory::BROWSER_UMA,
            layer_tree_host_->rendering_stats_instrumentation()));
    scheduler_on_impl_thread_ = std::make_unique<Scheduler>(
        this, scheduler_settings, layer_tree_host_->GetId(),
        task_runner_provider_->MainThreadTaskRunner(),
        std::move(compositor_timing_history),
        host_impl_->compositor_frame_reporting_controller(),
        power_scheduler::PowerModeArbiter::GetInstance());
  }
}

SingleThreadProxy::~SingleThreadProxy() {
  TRACE_EVENT0("cc", "SingleThreadProxy::~SingleThreadProxy");
  DCHECK(task_runner_provider_->IsMainThread());
  // Make sure Stop() got called or never Started.
  DCHECK(!host_impl_);
}

bool SingleThreadProxy::IsStarted() const {
  DCHECK(task_runner_provider_->IsMainThread());
  return !!host_impl_;
}

void SingleThreadProxy::SetVisible(bool visible) {
  TRACE_EVENT1("cc", "SingleThreadProxy::SetVisible", "visible", visible);
  DebugScopedSetImplThread impl(task_runner_provider_);

  host_impl_->SetVisible(visible);

  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetVisible(host_impl_->visible());
}

void SingleThreadProxy::RequestNewLayerTreeFrameSink() {
  DCHECK(task_runner_provider_->IsMainThread());
  layer_tree_frame_sink_creation_callback_.Cancel();
  if (layer_tree_frame_sink_creation_requested_)
    return;
  layer_tree_frame_sink_creation_requested_ = true;
  layer_tree_host_->RequestNewLayerTreeFrameSink();
}

void SingleThreadProxy::ReleaseLayerTreeFrameSink() {
  layer_tree_frame_sink_lost_ = true;
  frame_sink_bound_weak_factory_.InvalidateWeakPtrs();
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->DidLoseLayerTreeFrameSink();
  return host_impl_->ReleaseLayerTreeFrameSink();
}

void SingleThreadProxy::SetLayerTreeFrameSink(
    LayerTreeFrameSink* layer_tree_frame_sink) {
  DCHECK(task_runner_provider_->IsMainThread());
  DCHECK(layer_tree_frame_sink_creation_requested_);

  bool success;
  {
    DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
    DebugScopedSetImplThread impl(task_runner_provider_);
    success = host_impl_->InitializeFrameSink(layer_tree_frame_sink);
  }

  if (success) {
    frame_sink_bound_weak_ptr_ = frame_sink_bound_weak_factory_.GetWeakPtr();
    layer_tree_host_->DidInitializeLayerTreeFrameSink();
    if (scheduler_on_impl_thread_)
      scheduler_on_impl_thread_->DidCreateAndInitializeLayerTreeFrameSink();
    else if (!inside_synchronous_composite_)
      SetNeedsCommit();
    layer_tree_frame_sink_creation_requested_ = false;
    layer_tree_frame_sink_lost_ = false;
  } else {
    // DidFailToInitializeLayerTreeFrameSink is treated as a
    // RequestNewLayerTreeFrameSink, and so
    // layer_tree_frame_sink_creation_requested remains true.
    layer_tree_host_->DidFailToInitializeLayerTreeFrameSink();
  }
}

void SingleThreadProxy::SetNeedsAnimate() {
  TRACE_EVENT0("cc", "SingleThreadProxy::SetNeedsAnimate");
  DCHECK(task_runner_provider_->IsMainThread());
  if (animate_requested_)
    return;
  animate_requested_ = true;
  DebugScopedSetImplThread impl(task_runner_provider_);
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetNeedsBeginMainFrame();
}

void SingleThreadProxy::SetNeedsUpdateLayers() {
  TRACE_EVENT0("cc", "SingleThreadProxy::SetNeedsUpdateLayers");
  DCHECK(task_runner_provider_->IsMainThread());
  if (!RequestedAnimatePending()) {
    DebugScopedSetImplThread impl(task_runner_provider_);
    if (scheduler_on_impl_thread_)
      scheduler_on_impl_thread_->SetNeedsBeginMainFrame();
  }
  update_layers_requested_ = true;
}

void SingleThreadProxy::DoCommit(const viz::BeginFrameArgs& commit_args) {
  TRACE_EVENT0("cc", "SingleThreadProxy::DoCommit");
  DCHECK(task_runner_provider_->IsMainThread());

  if (host_impl_->EvictedUIResourcesExist())
    layer_tree_host_->GetUIResourceManager()->RecreateUIResources();

  // Strictly speaking, it's not necessary to pass a CompletionEvent to
  // WillCommit, since we can't have thread contention issues. The benefit to
  // creating one here is that it simplifies LayerTreeHost::in_commit(), which
  // useful in DCHECKs sprinkled throughout the code.
  auto completion_event_ptr = std::make_unique<CompletionEvent>(
      base::WaitableEvent::ResetPolicy::MANUAL);
  auto* completion_event = completion_event_ptr.get();
  auto& unsafe_state = layer_tree_host_->GetUnsafeStateForCommit();
  std::unique_ptr<CommitState> commit_state =
      layer_tree_host_->WillCommit(std::move(completion_event_ptr),
                                   /*has_updates=*/true);
  devtools_instrumentation::ScopedCommitTrace commit_task(
      layer_tree_host_->GetId(), commit_args.frame_id.sequence_number);

  // Commit immediately.
  {
    DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
    DebugScopedSetImplThread impl(task_runner_provider_);

    host_impl_->BeginCommit(commit_state->source_frame_number);

    host_impl_->FinishCommit(*commit_state, unsafe_state);
    completion_event->Signal();

    if (scheduler_on_impl_thread_) {
      scheduler_on_impl_thread_->DidCommit();
    }

    IssueImageDecodeFinishedCallbacks();
    host_impl_->CommitComplete();

    layer_tree_host_->NotifyTransitionRequestsFinished(
        host_impl_->TakeFinishedTransitionRequestSequenceIds());

    // Commit goes directly to the active tree, but we need to synchronously
    // "activate" the tree still during commit to satisfy any potential
    // SetNextCommitWaitsForActivation calls.  Unfortunately, the tree
    // might not be ready to draw, so DidActivateSyncTree must set
    // the flag to force the tree to not draw until textures are ready.
    NotifyReadyToActivate();
  }
}

void SingleThreadProxy::IssueImageDecodeFinishedCallbacks() {
  DCHECK(task_runner_provider_->IsImplThread());

  layer_tree_host_->ImageDecodesFinished(
      host_impl_->TakeCompletedImageDecodeRequests());
}

void SingleThreadProxy::CommitComplete() {
  // Commit complete happens on the main side after activate to satisfy any
  // SetNextCommitWaitsForActivation calls.
  DCHECK(!host_impl_->pending_tree())
      << "Activation is expected to have synchronously occurred by now.";

  DebugScopedSetMainThread main(task_runner_provider_);
  layer_tree_host_->DidBeginMainFrame();
  layer_tree_host_->CommitComplete({base::TimeTicks(), base::TimeTicks::Now()});

  next_frame_is_newly_committed_frame_ = true;
}

void SingleThreadProxy::SetNeedsCommit() {
  DCHECK(task_runner_provider_->IsMainThread());
  if (commit_requested_)
    return;
  commit_requested_ = true;
  DebugScopedSetImplThread impl(task_runner_provider_);
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetNeedsBeginMainFrame();
}

void SingleThreadProxy::SetNeedsRedraw(const gfx::Rect& damage_rect) {
  TRACE_EVENT0("cc", "SingleThreadProxy::SetNeedsRedraw");
  DCHECK(task_runner_provider_->IsMainThread());
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->SetViewportDamage(damage_rect);
  SetNeedsRedrawOnImplThread();
}

void SingleThreadProxy::SetTargetLocalSurfaceId(
    const viz::LocalSurfaceId& target_local_surface_id) {
  if (!scheduler_on_impl_thread_)
    return;
  host_impl_->SetTargetLocalSurfaceId(target_local_surface_id);
}

bool SingleThreadProxy::RequestedAnimatePending() {
  return animate_requested_ || update_layers_requested_ || commit_requested_ ||
         needs_impl_frame_;
}

void SingleThreadProxy::SetDeferMainFrameUpdate(bool defer_main_frame_update) {
  DCHECK(task_runner_provider_->IsMainThread());
  // Deferring main frame updates only makes sense if there's a scheduler.
  if (!scheduler_on_impl_thread_)
    return;
  if (defer_main_frame_update_ == defer_main_frame_update)
    return;

  if (defer_main_frame_update) {
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
        "cc", "SingleThreadProxy::SetDeferMainFrameUpdate",
        TRACE_ID_LOCAL(this));
  } else {
    TRACE_EVENT_NESTABLE_ASYNC_END0(
        "cc", "SingleThreadProxy::SetDeferMainFrameUpdate",
        TRACE_ID_LOCAL(this));
  }

  defer_main_frame_update_ = defer_main_frame_update;

  // Notify dependent systems that the deferral status has changed.
  layer_tree_host_->OnDeferMainFrameUpdatesChanged(defer_main_frame_update_);

  // The scheduler needs to know that it should not issue BeginMainFrame.
  scheduler_on_impl_thread_->SetDeferBeginMainFrame(defer_main_frame_update_);
}

bool SingleThreadProxy::StartDeferringCommits(base::TimeDelta timeout,
                                              PaintHoldingReason reason) {
  DCHECK(task_runner_provider_->IsMainThread());

  // Do nothing if already deferring. The timeout remains as it was from when
  // we most recently began deferring.
  if (IsDeferringCommits())
    return false;

  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("cc", "SingleThreadProxy::SetDeferCommits",
                                    TRACE_ID_LOCAL(this));

  paint_holding_reason_ = reason;
  commits_restart_time_ = base::TimeTicks::Now() + timeout;

  // Notify dependent systems that the deferral status has changed.
  layer_tree_host_->OnDeferCommitsChanged(true, reason);
  return true;
}

void SingleThreadProxy::StopDeferringCommits(
    PaintHoldingCommitTrigger trigger) {
  if (!IsDeferringCommits())
    return;
  auto reason = *paint_holding_reason_;
  paint_holding_reason_.reset();
  commits_restart_time_ = base::TimeTicks();
  UMA_HISTOGRAM_ENUMERATION("PaintHolding.CommitTrigger2", trigger);
  TRACE_EVENT_NESTABLE_ASYNC_END0("cc", "SingleThreadProxy::SetDeferCommits",
                                  TRACE_ID_LOCAL(this));

  // Notify dependent systems that the deferral status has changed.
  layer_tree_host_->OnDeferCommitsChanged(false, reason);
}

bool SingleThreadProxy::IsDeferringCommits() const {
  DCHECK(task_runner_provider_->IsMainThread());
  return paint_holding_reason_.has_value();
}

bool SingleThreadProxy::CommitRequested() const {
  DCHECK(task_runner_provider_->IsMainThread());
  return commit_requested_;
}

void SingleThreadProxy::Stop() {
  TRACE_EVENT0("cc", "SingleThreadProxy::stop");
  DCHECK(task_runner_provider_->IsMainThread());
  {
    DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
    DebugScopedSetImplThread impl(task_runner_provider_);

    // Prevent the scheduler from performing actions while we're in an
    // inconsistent state.
    if (scheduler_on_impl_thread_)
      scheduler_on_impl_thread_->Stop();
    // Take away the LayerTreeFrameSink before destroying things so it doesn't
    // try to call into its client mid-shutdown.
    host_impl_->ReleaseLayerTreeFrameSink();

    // It is important to destroy LTHI before the Scheduler since it can make
    // callbacks that access it during destruction cleanup.
    host_impl_ = nullptr;
    scheduler_on_impl_thread_ = nullptr;
  }
  layer_tree_host_ = nullptr;
}

void SingleThreadProxy::SetMutator(std::unique_ptr<LayerTreeMutator> mutator) {
  DCHECK(task_runner_provider_->IsMainThread());
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->SetLayerTreeMutator(std::move(mutator));
}

void SingleThreadProxy::SetPaintWorkletLayerPainter(
    std::unique_ptr<PaintWorkletLayerPainter> painter) {
  NOTREACHED();
}

void SingleThreadProxy::OnCanDrawStateChanged(bool can_draw) {
  TRACE_EVENT1("cc", "SingleThreadProxy::OnCanDrawStateChanged", "can_draw",
               can_draw);
  DCHECK(task_runner_provider_->IsImplThread());
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetCanDraw(can_draw);
}

void SingleThreadProxy::NotifyReadyToActivate() {
  TRACE_EVENT0("cc", "SingleThreadProxy::NotifyReadyToActivate");
  DebugScopedSetImplThread impl(task_runner_provider_);
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->NotifyReadyToActivate();
}

void SingleThreadProxy::NotifyReadyToDraw() {
  TRACE_EVENT0("cc", "SingleThreadProxy::NotifyReadyToDraw");
  DebugScopedSetImplThread impl(task_runner_provider_);
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->NotifyReadyToDraw();
}

void SingleThreadProxy::SetNeedsRedrawOnImplThread() {
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetNeedsRedraw();
}

void SingleThreadProxy::SetNeedsOneBeginImplFrameOnImplThread() {
  TRACE_EVENT0("cc",
               "SingleThreadProxy::SetNeedsOneBeginImplFrameOnImplThread");
  single_thread_client_->ScheduleAnimationForWebTests();
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetNeedsOneBeginImplFrame();
  needs_impl_frame_ = true;
}

void SingleThreadProxy::SetNeedsPrepareTilesOnImplThread() {
  TRACE_EVENT0("cc", "SingleThreadProxy::SetNeedsPrepareTilesOnImplThread");
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetNeedsPrepareTiles();
}

void SingleThreadProxy::SetNeedsCommitOnImplThread() {
  single_thread_client_->ScheduleAnimationForWebTests();
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetNeedsBeginMainFrame();
  commit_requested_ = true;
}

void SingleThreadProxy::SetVideoNeedsBeginFrames(bool needs_begin_frames) {
  TRACE_EVENT1("cc", "SingleThreadProxy::SetVideoNeedsBeginFrames",
               "needs_begin_frames", needs_begin_frames);
  // In tests the layer tree is destroyed after the scheduler is.
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetVideoNeedsBeginFrames(needs_begin_frames);
}

bool SingleThreadProxy::HasInvalidationAnimation() const {
  return false;
}

bool SingleThreadProxy::IsInsideDraw() {
  return inside_draw_;
}

bool SingleThreadProxy::IsBeginMainFrameExpected() {
  return true;
}

void SingleThreadProxy::DidActivateSyncTree() {
  CommitComplete();
}

void SingleThreadProxy::WillPrepareTiles() {
  DCHECK(task_runner_provider_->IsImplThread());
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->WillPrepareTiles();
}

void SingleThreadProxy::DidPrepareTiles() {
  DCHECK(task_runner_provider_->IsImplThread());
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->DidPrepareTiles();
}

void SingleThreadProxy::DidCompletePageScaleAnimationOnImplThread() {
  layer_tree_host_->DidCompletePageScaleAnimation();
}

void SingleThreadProxy::DidLoseLayerTreeFrameSinkOnImplThread() {
  TRACE_EVENT0("cc",
               "SingleThreadProxy::DidLoseLayerTreeFrameSinkOnImplThread");
  {
    DebugScopedSetMainThread main(task_runner_provider_);
    // This must happen before we notify the scheduler as it may try to recreate
    // the output surface if already in BEGIN_IMPL_FRAME_STATE_IDLE.
    layer_tree_host_->DidLoseLayerTreeFrameSink();
  }
  single_thread_client_->DidLoseLayerTreeFrameSink();
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->DidLoseLayerTreeFrameSink();
  layer_tree_frame_sink_lost_ = true;
}

void SingleThreadProxy::SetBeginFrameSource(viz::BeginFrameSource* source) {
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->SetBeginFrameSource(source);
}

void SingleThreadProxy::DidReceiveCompositorFrameAckOnImplThread() {
  TRACE_EVENT0("cc,benchmark",
               "SingleThreadProxy::DidReceiveCompositorFrameAckOnImplThread");
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->DidReceiveCompositorFrameAck();
  if (layer_tree_host_->GetSettings().send_compositor_frame_ack) {
    // We do a PostTask here because freeing resources in some cases (such as in
    // TextureLayer) is PostTasked and we want to make sure ack is received
    // after resources are returned.
    task_runner_provider_->MainThreadTaskRunner()->PostTask(
        FROM_HERE,
        base::BindOnce(&SingleThreadProxy::DidReceiveCompositorFrameAck,
                       frame_sink_bound_weak_ptr_));
  }
}

void SingleThreadProxy::OnDrawForLayerTreeFrameSink(
    bool resourceless_software_draw,
    bool skip_draw) {
  NOTREACHED() << "Implemented by ThreadProxy for synchronous compositor.";
}

void SingleThreadProxy::NeedsImplSideInvalidation(
    bool needs_first_draw_on_activation) {
  if (scheduler_on_impl_thread_) {
    scheduler_on_impl_thread_->SetNeedsImplSideInvalidation(
        needs_first_draw_on_activation);
  }
}

void SingleThreadProxy::NotifyImageDecodeRequestFinished() {
  // If we don't have a scheduler, then just issue the callbacks here.
  // Otherwise, schedule a commit.
  if (!scheduler_on_impl_thread_) {
    DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
    DebugScopedSetImplThread impl(task_runner_provider_);

    IssueImageDecodeFinishedCallbacks();

    layer_tree_host_->NotifyTransitionRequestsFinished(
        host_impl_->TakeFinishedTransitionRequestSequenceIds());
    return;
  }
  SetNeedsCommitOnImplThread();
}

void SingleThreadProxy::DidPresentCompositorFrameOnImplThread(
    uint32_t frame_token,
    PresentationTimeCallbackBuffer::PendingCallbacks callbacks,
    const viz::FrameTimingDetails& details) {
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->NotifyDidPresentCompositorFrameOnImplThread(
      frame_token, std::move(callbacks.compositor_thread_callbacks), details);
  {
    DebugScopedSetMainThread main(task_runner_provider_);
    layer_tree_host_->DidPresentCompositorFrame(
        frame_token, std::move(callbacks.main_thread_callbacks),
        details.presentation_feedback);
  }
  if (scheduler_on_impl_thread_) {
    scheduler_on_impl_thread_->DidPresentCompositorFrame(frame_token, details);
  }
}

void SingleThreadProxy::NotifyAnimationWorkletStateChange(
    AnimationWorkletMutationState state,
    ElementListType element_list_type) {
  layer_tree_host_->NotifyAnimationWorkletStateChange(state, element_list_type);
}

void SingleThreadProxy::NotifyPaintWorkletStateChange(
    Scheduler::PaintWorkletState state) {
  // Off-Thread PaintWorklet is only supported on the threaded compositor.
  NOTREACHED();
}

void SingleThreadProxy::NotifyThroughputTrackerResults(
    CustomTrackerResults results) {
  // This method is called from ImplThread side to report after being requested,
  // or from the MainThread when releasing FrameSequenceTrackers during
  // destruction. Regardless, `layer_tree_host_` should be accessed from
  // MainThread side.
  DebugScopedSetMainThread main(task_runner_provider_);
  layer_tree_host_->NotifyThroughputTrackerResults(std::move(results));
}

bool SingleThreadProxy::IsInSynchronousComposite() const {
  return inside_synchronous_composite_;
}

void SingleThreadProxy::FrameSinksToThrottleUpdated(
    const base::flat_set<viz::FrameSinkId>& ids) {
  DebugScopedSetMainThread main(task_runner_provider_);
  single_thread_client_->FrameSinksToThrottleUpdated(ids);
}

void SingleThreadProxy::RequestBeginMainFrameNotExpected(bool new_state) {
  if (scheduler_on_impl_thread_) {
    scheduler_on_impl_thread_->SetMainThreadWantsBeginMainFrameNotExpected(
        new_state);
  }
}

void SingleThreadProxy::CompositeImmediatelyForTest(
    base::TimeTicks frame_begin_time,
    bool raster) {
  TRACE_EVENT0("cc,benchmark",
               "SingleThreadProxy::CompositeImmediatelyForTest");
  DCHECK(task_runner_provider_->IsMainThread());
#if DCHECK_IS_ON()
  DCHECK(!inside_impl_frame_);
#endif
  base::AutoReset<bool> inside_composite(&inside_synchronous_composite_, true);

  if (layer_tree_frame_sink_lost_) {
    RequestNewLayerTreeFrameSink();
    // RequestNewLayerTreeFrameSink could have synchronously created an output
    // surface, so check again before returning.
    if (layer_tree_frame_sink_lost_)
      return;
  }

  viz::BeginFrameArgs begin_frame_args(viz::BeginFrameArgs::Create(
      BEGINFRAME_FROM_HERE, viz::BeginFrameArgs::kManualSourceId,
      begin_frame_sequence_number_++, frame_begin_time, base::TimeTicks(),
      viz::BeginFrameArgs::DefaultInterval(), viz::BeginFrameArgs::NORMAL));

  // Start the impl frame.
  {
    DebugScopedSetImplThread impl(task_runner_provider_);
    WillBeginImplFrame(begin_frame_args);
  }

  // Run the "main thread" and get it to commit.
  {
#if DCHECK_IS_ON()
    DCHECK(inside_impl_frame_);
#endif
    animate_requested_ = false;
    needs_impl_frame_ = false;
    // Prevent new commits from being requested inside DoBeginMainFrame.
    // Note: We do not want to prevent SetNeedsAnimate from requesting
    // a commit here.
    commit_requested_ = true;
    StopDeferringCommits(PaintHoldingCommitTrigger::kFeatureDisabled);
    DoBeginMainFrame(begin_frame_args);
    commit_requested_ = false;
    DoPainting(begin_frame_args);
    DoCommit(begin_frame_args);

    DCHECK_EQ(
        0u,
        layer_tree_host_->GetSwapPromiseManager()->num_queued_swap_promises())
        << "Commit should always succeed and transfer promises.";
  }

  // Finish the impl frame.
  {
    DebugScopedSetImplThread impl(task_runner_provider_);
    host_impl_->ActivateSyncTree();
    if (raster) {
      host_impl_->PrepareTiles();
      host_impl_->SynchronouslyInitializeAllTiles();
    }

    // TODO(danakj): Don't do this last... we prepared the wrong things. D:
    host_impl_->Animate();

    if (raster) {
      LayerTreeHostImpl::FrameData frame;
      frame.begin_frame_ack = viz::BeginFrameAck(begin_frame_args, true);
      frame.origin_begin_main_frame_args = begin_frame_args;
      DoComposite(&frame);
    }

    // DoComposite could abort, but because this is a synchronous composite
    // another draw will never be scheduled, so break remaining promises.
    host_impl_->active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);

    DidFinishImplFrame(begin_frame_args);
  }
}

bool SingleThreadProxy::ShouldComposite() const {
  DCHECK(task_runner_provider_->IsImplThread());
  return host_impl_->visible() && host_impl_->CanDraw();
}

void SingleThreadProxy::ScheduleRequestNewLayerTreeFrameSink() {
  if (layer_tree_frame_sink_creation_callback_.IsCancelled() &&
      !layer_tree_frame_sink_creation_requested_) {
    layer_tree_frame_sink_creation_callback_.Reset(
        base::BindOnce(&SingleThreadProxy::RequestNewLayerTreeFrameSink,
                       weak_factory_.GetWeakPtr()));
    task_runner_provider_->MainThreadTaskRunner()->PostTask(
        FROM_HERE, layer_tree_frame_sink_creation_callback_.callback());
  }
}

DrawResult SingleThreadProxy::DoComposite(LayerTreeHostImpl::FrameData* frame) {
  TRACE_EVENT0("cc", "SingleThreadProxy::DoComposite");

  DrawResult draw_result;
  bool draw_frame;
  {
    DebugScopedSetImplThread impl(task_runner_provider_);
    base::AutoReset<bool> mark_inside(&inside_draw_, true);

    // We guard PrepareToDraw() with CanDraw() because it always returns a valid
    // frame, so can only be used when such a frame is possible. Since
    // DrawLayers() depends on the result of PrepareToDraw(), it is guarded on
    // CanDraw() as well.
    if (!ShouldComposite()) {
      return DRAW_ABORTED_CANT_DRAW;
    }

    // This CapturePostTasks should be destroyed before
    // DidCommitAndDrawFrame() is called since that goes out to the
    // embedder, and we want the embedder to receive its callbacks before that.
    // NOTE: This maintains consistent ordering with the ThreadProxy since
    // the DidCommitAndDrawFrame() must be post-tasked from the impl thread
    // there as the main thread is not blocked, so any posted tasks inside
    // the swap buffers will execute first.
    DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);

    draw_result = host_impl_->PrepareToDraw(frame);
    draw_frame = draw_result == DRAW_SUCCESS;
    if (draw_frame) {
      if (host_impl_->DrawLayers(frame)) {
        if (scheduler_on_impl_thread_) {
          // Drawing implies we submitted a frame to the LayerTreeFrameSink.
          scheduler_on_impl_thread_->DidSubmitCompositorFrame(
              frame->frame_token, host_impl_->TakeEventsMetrics(),
              frame->has_missing_content);
        }
        single_thread_client_->DidSubmitCompositorFrame();
      }
    }
    host_impl_->DidDrawAllLayers(*frame);

    bool start_ready_animations = draw_frame;
    host_impl_->UpdateAnimationState(start_ready_animations);
  }
  DidCommitAndDrawFrame();

  return draw_result;
}

void SingleThreadProxy::DidCommitAndDrawFrame() {
  if (next_frame_is_newly_committed_frame_) {
    DebugScopedSetMainThread main(task_runner_provider_);
    next_frame_is_newly_committed_frame_ = false;
    layer_tree_host_->DidCommitAndDrawFrame();
  }
}

bool SingleThreadProxy::MainFrameWillHappenForTesting() {
  if (!scheduler_on_impl_thread_)
    return false;
  return scheduler_on_impl_thread_->MainFrameForTestingWillHappen();
}

void SingleThreadProxy::ClearHistory() {
  DCHECK(task_runner_provider_->IsImplThread());
  if (scheduler_on_impl_thread_)
    scheduler_on_impl_thread_->ClearHistory();
}

size_t SingleThreadProxy::CommitDurationSampleCountForTesting() const {
  DCHECK(scheduler_on_impl_thread_);
  return scheduler_on_impl_thread_
      ->CommitDurationSampleCountForTesting();  // IN-TEST
}

void SingleThreadProxy::SetRenderFrameObserver(
    std::unique_ptr<RenderFrameMetadataObserver> observer) {
  host_impl_->SetRenderFrameObserver(std::move(observer));
}

uint32_t SingleThreadProxy::GetAverageThroughput() const {
  DebugScopedSetImplThread impl(task_runner_provider_);
  return host_impl_->dropped_frame_counter()->GetAverageThroughput();
}

void SingleThreadProxy::UpdateBrowserControlsState(
    BrowserControlsState constraints,
    BrowserControlsState current,
    bool animate) {
  host_impl_->browser_controls_manager()->UpdateBrowserControlsState(
      constraints, current, animate);
}

bool SingleThreadProxy::WillBeginImplFrame(const viz::BeginFrameArgs& args) {
  DebugScopedSetImplThread impl(task_runner_provider_);
#if DCHECK_IS_ON()
  DCHECK(!inside_impl_frame_)
      << "WillBeginImplFrame called while already inside an impl frame!";
  inside_impl_frame_ = true;
#endif
  return host_impl_->WillBeginImplFrame(args);
}

void SingleThreadProxy::ScheduledActionSendBeginMainFrame(
    const viz::BeginFrameArgs& begin_frame_args) {
  TRACE_EVENT0("cc", "SingleThreadProxy::ScheduledActionSendBeginMainFrame");
#if DCHECK_IS_ON()
  // Although this proxy is single-threaded, it's problematic to synchronously
  // have BeginMainFrame happen after ScheduledActionSendBeginMainFrame.  This
  // could cause a commit to occur in between a series of SetNeedsCommit calls
  // (i.e. property modifications) causing some to fall on one frame and some to
  // fall on the next.  Doing it asynchronously instead matches the semantics of
  // ThreadProxy::SetNeedsCommit where SetNeedsCommit will not cause a
  // synchronous commit.
  DCHECK(inside_impl_frame_)
      << "BeginMainFrame should only be sent inside a BeginImplFrame";
#endif

  host_impl_->WillSendBeginMainFrame();
  task_runner_provider_->MainThreadTaskRunner()->PostTask(
      FROM_HERE, base::BindOnce(&SingleThreadProxy::BeginMainFrame,
                                weak_factory_.GetWeakPtr(), begin_frame_args));
  host_impl_->DidSendBeginMainFrame(begin_frame_args);
}

void SingleThreadProxy::FrameIntervalUpdated(base::TimeDelta interval) {
  DebugScopedSetMainThread main(task_runner_provider_);
  single_thread_client_->FrameIntervalUpdated(interval);
}

void SingleThreadProxy::SendBeginMainFrameNotExpectedSoon() {
  layer_tree_host_->BeginMainFrameNotExpectedSoon();
}

void SingleThreadProxy::ScheduledActionBeginMainFrameNotExpectedUntil(
    base::TimeTicks time) {
  layer_tree_host_->BeginMainFrameNotExpectedUntil(time);
}

void SingleThreadProxy::BeginMainFrame(
    const viz::BeginFrameArgs& begin_frame_args) {
  // This checker assumes NotifyReadyToCommit in this stack causes a synchronous
  // commit.
  ScopedAbortRemainingSwapPromises swap_promise_checker(
      layer_tree_host_->GetSwapPromiseManager());

  if (scheduler_on_impl_thread_) {
    scheduler_on_impl_thread_->NotifyBeginMainFrameStarted(
        base::TimeTicks::Now());
  }

  commit_requested_ = false;
  needs_impl_frame_ = false;
  animate_requested_ = false;
  update_layers_requested_ = false;

  if (defer_main_frame_update_) {
    TRACE_EVENT_INSTANT0("cc", "EarlyOut_DeferBeginMainFrame",
                         TRACE_EVENT_SCOPE_THREAD);
    BeginMainFrameAbortedOnImplThread(
        CommitEarlyOutReason::ABORTED_DEFERRED_MAIN_FRAME_UPDATE);
    return;
  }

  if (!layer_tree_host_->IsVisible()) {
    TRACE_EVENT_INSTANT0("cc", "EarlyOut_NotVisible", TRACE_EVENT_SCOPE_THREAD);
    BeginMainFrameAbortedOnImplThread(
        CommitEarlyOutReason::ABORTED_NOT_VISIBLE);
    return;
  }

  // Prevent new commits from being requested inside DoBeginMainFrame.
  // Note: We do not want to prevent SetNeedsAnimate from requesting
  // a commit here.
  commit_requested_ = true;

  // Check now if we should stop deferring commits. Do this before
  // DoBeginMainFrame because the latter updates scroll offsets, which
  // we should avoid if deferring commits.
  if (IsDeferringCommits() && base::TimeTicks::Now() > commits_restart_time_)
    StopDeferringCommits(ReasonToTimeoutTrigger(*paint_holding_reason_));

  DoBeginMainFrame(begin_frame_args);

  // New commits requested inside UpdateLayers should be respected.
  commit_requested_ = false;

  // At this point the main frame may have deferred commits to avoid committing
  // right now.
  if (defer_main_frame_update_ || IsDeferringCommits() ||
      begin_frame_args.animate_only) {
    TRACE_EVENT_INSTANT0("cc", "EarlyOut_DeferCommit_InsideBeginMainFrame",
                         TRACE_EVENT_SCOPE_THREAD);
    BeginMainFrameAbortedOnImplThread(
        CommitEarlyOutReason::ABORTED_DEFERRED_COMMIT);
    layer_tree_host_->DidBeginMainFrame();
    return;
  }

  DoPainting(begin_frame_args);
}

void SingleThreadProxy::DoBeginMainFrame(
    const viz::BeginFrameArgs& begin_frame_args) {
  // Only update scroll deltas if we are going to commit the frame, otherwise
  // scroll offsets get confused.
  if (!IsDeferringCommits()) {
    // The impl-side scroll deltas may be manipulated directly via the
    // InputHandler on the UI thread and the scale deltas may change when they
    // are clamped on the impl thread.
    std::unique_ptr<CompositorCommitData> commit_data =
        host_impl_->ProcessCompositorDeltas();
    layer_tree_host_->ApplyCompositorChanges(commit_data.get());
    did_apply_compositor_deltas_ = true;
  }
  layer_tree_host_->ApplyMutatorEvents(host_impl_->TakeMutatorEvents());
  layer_tree_host_->WillBeginMainFrame();
  layer_tree_host_->BeginMainFrame(begin_frame_args);
  layer_tree_host_->AnimateLayers(begin_frame_args.frame_time);

#if BUILDFLAG(IS_CHROMEOS_ASH)
  const bool record_metrics =
      layer_tree_host_->GetSettings().is_layer_tree_for_ui;
#else
  constexpr bool record_metrics = false;
#endif
  layer_tree_host_->RequestMainFrameUpdate(record_metrics);

  // Reset the flag for the next time around. It has been used for this frame.
  did_apply_compositor_deltas_ = false;
}

void SingleThreadProxy::DoPainting(const viz::BeginFrameArgs& commit_args) {
  layer_tree_host_->UpdateLayers();
  update_layers_requested_ = false;

  std::unique_ptr<BeginMainFrameMetrics> begin_main_frame_metrics =
      layer_tree_host_->TakeBeginMainFrameMetrics();
  host_impl_->ReadyToCommit(commit_args, begin_main_frame_metrics.get());

  // TODO(enne): SingleThreadProxy does not support cancelling commits yet,
  // search for CommitEarlyOutReason::FINISHED_NO_UPDATES inside
  // thread_proxy.cc
  if (scheduler_on_impl_thread_) {
    scheduler_on_impl_thread_->NotifyReadyToCommit(
        std::move(begin_main_frame_metrics));
  }
}

void SingleThreadProxy::BeginMainFrameAbortedOnImplThread(
    CommitEarlyOutReason reason) {
  DebugScopedSetImplThread impl(task_runner_provider_);
  DCHECK(scheduler_on_impl_thread_->CommitPending());
  DCHECK(!host_impl_->pending_tree());

  std::vector<std::unique_ptr<SwapPromise>> empty_swap_promises;
  host_impl_->BeginMainFrameAborted(
      reason, std::move(empty_swap_promises),
      scheduler_on_impl_thread_->last_dispatched_begin_main_frame_args(),
      did_apply_compositor_deltas_);
  scheduler_on_impl_thread_->BeginMainFrameAborted(reason);
}

DrawResult SingleThreadProxy::ScheduledActionDrawIfPossible() {
  DebugScopedSetImplThread impl(task_runner_provider_);
  LayerTreeHostImpl::FrameData frame;
  frame.begin_frame_ack =
      scheduler_on_impl_thread_->CurrentBeginFrameAckForActiveTree();
  frame.origin_begin_main_frame_args =
      scheduler_on_impl_thread_->last_activate_origin_frame_args();
  return DoComposite(&frame);
}

DrawResult SingleThreadProxy::ScheduledActionDrawForced() {
  NOTREACHED();
  return INVALID_RESULT;
}

void SingleThreadProxy::ScheduledActionCommit() {
  DebugScopedSetMainThread main(task_runner_provider_);
  DoCommit(scheduler_on_impl_thread_->last_dispatched_begin_main_frame_args());
}

void SingleThreadProxy::ScheduledActionActivateSyncTree() {
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->ActivateSyncTree();
}

void SingleThreadProxy::ScheduledActionBeginLayerTreeFrameSinkCreation() {
  DebugScopedSetMainThread main(task_runner_provider_);
  DCHECK(scheduler_on_impl_thread_);
  // If possible, create the output surface in a post task.  Synchronously
  // creating the output surface makes tests more awkward since this differs
  // from the ThreadProxy behavior.  However, sometimes there is no
  // task runner.
  if (task_runner_provider_->MainThreadTaskRunner()) {
    ScheduleRequestNewLayerTreeFrameSink();
  } else {
    RequestNewLayerTreeFrameSink();
  }
}

void SingleThreadProxy::ScheduledActionPrepareTiles() {
  TRACE_EVENT0("cc", "SingleThreadProxy::ScheduledActionPrepareTiles");
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->PrepareTiles();
}

void SingleThreadProxy::ScheduledActionInvalidateLayerTreeFrameSink(
    bool needs_redraw) {
  // This is an Android WebView codepath, which only uses multi-thread
  // compositor. So this should not occur in single-thread mode.
  NOTREACHED() << "Android Webview use-case, so multi-thread only";
}

void SingleThreadProxy::ScheduledActionPerformImplSideInvalidation() {
  DCHECK(scheduler_on_impl_thread_);

  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->InvalidateContentOnImplSide();

  // Invalidations go directly to the active tree, so we synchronously call
  // NotifyReadyToActivate to update the scheduler and LTHI state correctly.
  // Since in single-threaded mode the scheduler will wait for a ready to draw
  // signal from LTHI, the draw will remain blocked till the invalidated tiles
  // are ready.
  NotifyReadyToActivate();
}

void SingleThreadProxy::DidFinishImplFrame(
    const viz::BeginFrameArgs& last_activated_args) {
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->DidFinishImplFrame(last_activated_args);
#if DCHECK_IS_ON()
  DCHECK(inside_impl_frame_)
      << "DidFinishImplFrame called while not inside an impl frame!";
  inside_impl_frame_ = false;
#endif
}

void SingleThreadProxy::DidNotProduceFrame(const viz::BeginFrameAck& ack,
                                           FrameSkippedReason reason) {
  DebugScopedSetImplThread impl(task_runner_provider_);
  host_impl_->DidNotProduceFrame(ack, reason);
}

void SingleThreadProxy::WillNotReceiveBeginFrame() {
  host_impl_->DidNotNeedBeginFrame();
}

void SingleThreadProxy::DidReceiveCompositorFrameAck() {
  layer_tree_host_->DidReceiveCompositorFrameAck();
}

}  // namespace cc


text:
goog.module('goog.events.ListenableTest');
goog.setTestOnly();

const Listenable = goog.require('goog.events.Listenable');
const testSuite = goog.require('goog.testing.testSuite');

testSuite({
  testIsImplementedBy() {
    const ListenableClass = class {};
    Listenable.addImplementation(ListenableClass);

    const NonListenableClass = class {};

    assertTrue(Listenable.isImplementedBy(new ListenableClass()));
    assertFalse(Listenable.isImplementedBy(new NonListenableClass()));
  },
});

redpajama_set_name: RedPajamaGithub


text:
package org.w3c.domts.level2.core;

import org.junit.jupiter.api.Test;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.w3c.domts.DOMTest.load;

/**
 * The "createAttributeNS(namespaceURI,qualifiedName)" method for a
 * Document should raise NAMESPACE_ERR DOMException
 * if qualifiedName is malformed.
 *

 * Invoke method createAttributeNS(namespaceURI,qualifiedName) on
 * the XMLNS Document with namespaceURI being "http://www.ecommerce.org/",
 * qualifiedName as "prefix::local".  Method should raise
 * NAMESPACE_ERR DOMException.
 *
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='NAMESPACE_ERR'])
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-DocCrAttrNS
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-DocCrAttrNS')/raises/exception[@name='DOMException']/descr/p[substring-before(.,':')='NAMESPACE_ERR'])
 */
public class createAttributeNS01 {
    @Test
    void testRun() throws Throwable {
        String namespaceURI = "http://www.ecommerce.org/";
        String malformedName = "prefix::local";
        Document doc = load("staffNS", false);
        DOMException ex = assertThrows(DOMException.class, () -> doc.createAttributeNS(namespaceURI, malformedName));
        assertEquals(DOMException.NAMESPACE_ERR, ex.code);
    }

    /**
     * Gets URI that identifies the test
     *
     * @return uri identifier of test
     */
    public String getTargetURI() {
        return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/createAttributeNS01";
    }

}


text:
package com.company.crm.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.company.crm.exceptions.ClientAlreadyExistsException;
import com.company.crm.exceptions.ClientPropertyValidationException;

public class ClientFactory {
    private Connection dbConnection = null;

    public ClientFactory(Connection databaseConnection) {
        this.dbConnection = databaseConnection;
    }

    public Client createClient(String name, String location, String notes, String contractDate, String logoName)
            throws ClientAlreadyExistsException, ClientPropertyValidationException {
        Client client = null;

        try {
            String sqlQuery = "SELECT * FROM clients WHERE Name=?";
            PreparedStatement stmt = this.dbConnection.prepareStatement(sqlQuery);
            stmt.setString(1, name);
            ResultSet clientsWithSameName = stmt.executeQuery();

            if (!clientsWithSameName.next()) {
                client = new Client(name, location, notes, contractDate, logoName, false);

                // create new record
                String sqlInsert = "INSERT INTO clients (Name, Location, Notes, ContractDate, LogoImageName) VALUES (?, ?, ?, ?, ?)";
                PreparedStatement stm = this.dbConnection.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
                stm.setString(1, name);
                stm.setString(2, location);
                stm.setString(3, notes);
                stm.setString(4, contractDate);
                stm.setString(5, logoName);
                stm.executeUpdate();

                ResultSet generatedKeys = stm.getGeneratedKeys();
                if (generatedKeys.next()) {
                    client.setId(generatedKeys.getInt(1));
                } else {
                    throw new SQLException("Creating user failed, no generated key obtained.");
                }
            } else {
                throw new ClientAlreadyExistsException("A client with the same name already exists.");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return client;
    }
}


text:
using namespace foundation;

namespace renderer
{

namespace
{
    //
    // Bidirectional Path Tracing lighting engine.
    //

    class BDPTLightingEngine
      : public ILightingEngine
    {
      public:
        struct Parameters
        {
            explicit Parameters(const ParamArray& params)
            {
            }
        };

        BDPTLightingEngine(
            const Project&              project,
            const ForwardLightSampler&  light_sampler,
            const ParamArray&           params)
          : m_light_sampler(light_sampler)
          ,  m_params(params)
        {
            const Camera* camera = project.get_uncached_active_camera();
            m_shutter_open_begin_time = camera->get_shutter_open_begin_time();
            m_shutter_close_end_time = camera->get_shutter_close_end_time();
        }

        void release() override
        {
            delete this;
        }

        void print_settings() const override
        {
        }

        void compute_lighting(
            SamplingContext&        sampling_context,
            const PixelContext&     pixel_context,
            const ShadingContext&   shading_context,
            const ShadingPoint&     shading_point,
            ShadingComponents&      radiance) override      // output radiance, in W.sr^-1.m^-2
        {
            PathVisitor light_path_visitor;
            VolumeVisitor volume_visitor;

            PathTracer<PathVisitor, VolumeVisitor, true> light_path_tracer(     // true = adjoint
                light_path_visitor,
                volume_visitor,
                ~0,
                1,
                ~0,
                ~0,
                ~0,
                ~0,
                shading_context.get_max_iterations());
        }

        void trace_light(
            SamplingContext&        sampling_context,
            const ShadingContext&   shading_context)
        {
            // Sample the light sources.
            sampling_context.split_in_place(4, 1);
            const Vector4f s = sampling_context.next2<Vector4f>();
            LightSample light_sample;
            m_light_sampler.sample(
                ShadingRay::Time::create_with_normalized_time(
                    s[0],
                    m_shutter_open_begin_time,
                    m_shutter_close_end_time),
                Vector3f(s[1], s[2], s[3]),
                light_sample);

            light_sample.m_triangle
                ? trace_emitting_triangle(
                    sampling_context,
                    shading_context,
                    light_sample)
                : trace_non_physical_light(
                    sampling_context,
                    shading_context,
                    light_sample);
        }

        void trace_emitting_triangle(
            SamplingContext&        sampling_context,
            const ShadingContext&   shading_context,
            LightSample&            light_sample)
        {
            // Make sure the geometric normal of the light sample is in the same hemisphere as the shading normal.
            light_sample.m_geometric_normal =
                flip_to_same_hemisphere(
                    light_sample.m_geometric_normal,
                    light_sample.m_shading_normal);

            const Material* material = light_sample.m_triangle->m_material;
            const Material::RenderData& material_data = material->get_render_data();

            // Build a shading point on the light source.
            ShadingPoint light_shading_point;
            light_sample.make_shading_point(
                light_shading_point,
                light_sample.m_shading_normal,
                shading_context.get_intersector());

            if (material_data.m_shader_group)
            {
                shading_context.execute_osl_emission(
                    *material_data.m_shader_group,
                    light_shading_point);
            }

            // Sample the EDF.
            sampling_context.split_in_place(2, 1);
            Vector3f emission_direction;
            Spectrum edf_value(Spectrum::Illuminance);
            float edf_prob;
            material_data.m_edf->sample(
                sampling_context,
                material_data.m_edf->evaluate_inputs(shading_context, light_shading_point),
                Vector3f(light_sample.m_geometric_normal),
                Basis3f(Vector3f(light_sample.m_shading_normal)),
                sampling_context.next2<Vector2f>(),
                emission_direction,
                edf_value,
                edf_prob);

            // Compute the initial particle weight.
            Spectrum initial_flux = edf_value;
            initial_flux *=
                dot(emission_direction, Vector3f(light_sample.m_shading_normal)) /
                (light_sample.m_probability * edf_prob);

            // Make a shading point that will be used to avoid self-intersections with the light sample.
            ShadingPoint parent_shading_point;
            light_sample.make_shading_point(
                parent_shading_point,
                Vector3d(emission_direction),
                shading_context.get_intersector());

            // Build the light ray.
            sampling_context.split_in_place(1, 1);
            const ShadingRay::Time time =
                ShadingRay::Time::create_with_normalized_time(
                    sampling_context.next2<float>(),
                    m_shutter_open_begin_time,
                    m_shutter_close_end_time);
            const ShadingRay light_ray(
                light_sample.m_point,
                Vector3d(emission_direction),
                time,
                VisibilityFlags::LightRay,
                0);

            // Build the path tracer.
            PathVisitor path_visitor;
            VolumeVisitor volume_visitor;
            PathTracer<PathVisitor, VolumeVisitor, true> path_tracer(
                path_visitor,
                volume_visitor,
                ~0,
                1,
                ~0,
                ~0,
                ~0,
                ~0,
                shading_context.get_max_iterations());   // don't illuminate points closer than the light near start value

            const size_t light_path_length =
                path_tracer.trace(
                    sampling_context,
                    shading_context,
                    light_ray,
                    &parent_shading_point);

            m_light_path_length.insert(light_path_length);
        }

        void trace_non_physical_light(
            SamplingContext&        sampling_context,
            const ShadingContext&   shading_context,
            LightSample&            light_sample)
        {
        }

        StatisticsVector get_statistics() const override
        {
            Statistics stats;

            return StatisticsVector::make("bdpt statistics", stats);
        }

      private:
        const Parameters            m_params;

        const ForwardLightSampler&  m_light_sampler;
        //Intersector                 m_intersector;

        float                       m_shutter_open_begin_time;
        float                       m_shutter_close_end_time;

        Population<uint64>          m_light_path_length;

        struct PathVisitor
        {
            PathVisitor()
            {
            }

            bool accept_scattering(
                const ScatteringMode::Mode  prev_mode,
                const ScatteringMode::Mode  next_mode) const
            {
                return false;
            }

            void on_miss(const PathVertex& vertex)
            {

            }

            void on_hit(const PathVertex& vertex)
            {
            }

            void on_scatter(const PathVertex& vertex)
            {
            }
        };

        struct VolumeVisitor
        {
            VolumeVisitor()
            {
            }

            bool accept_scattering(
                const ScatteringMode::Mode  prev_mode)
            {
                return true;
            }

            void on_scatter(PathVertex& vertex) {}

            void visit_ray(PathVertex& vertex, const ShadingRay& volume_ray) {}
        };
    };
}

BDPTLightingEngineFactory::BDPTLightingEngineFactory(
    const Project&              project,
    const ForwardLightSampler&  light_sampler,
    const ParamArray&           params)
  : m_project(project)
  , m_light_sampler(light_sampler)
  , m_params(params)
{
}

void BDPTLightingEngineFactory::release()
{
    delete this;
}

ILightingEngine* BDPTLightingEngineFactory::create()
{
    return new BDPTLightingEngine(
        m_project,
        m_light_sampler,
        m_params);
}

Dictionary BDPTLightingEngineFactory::get_params_metadata()
{
    Dictionary metadata;
    add_common_params_metadata(metadata, true);

    return metadata;
}

}   // namespace renderer


text:
package com.commonsware.android.downmgr;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;

public class DownloadDemo extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                                .detectAll()
                                .penaltyDeath()
                                .build());

      if (getFragmentManager().findFragmentById(android.R.id.content)==null) {
        getFragmentManager().beginTransaction()
                                   .add(android.R.id.content,
                                        new DownloadFragment()).commit();
      }
  }

  public void viewLog() {
    startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
  }
}


text:
import { Form } from '../Form';
export declare class TableForm extends Form {
    fillAttributes(response: any): void;
}


text:
using System;
using NuGet;

namespace NuGetPackageExplorer.Types
{
    public enum PackageType
    {
        LocalPackage,
        DataServicePackage
    }

    public sealed class MruItem : IEquatable<MruItem>
    {
        public string Id { get; set; }
        public SemanticVersion Version { get; set; }
        public string Path { get; set; }
        public PackageType PackageType { get; set; }

        #region IEquatable<MruItem> Members

        public bool Equals(MruItem other)
        {
            if (other == null)
            {
                return false;
            }
            return Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase);
        }

        #endregion

        public override bool Equals(object obj)
        {
            return Equals(obj as MruItem);
        }

        public override int GetHashCode()
        {
            return Path.GetHashCode();
        }
    }
}


text:
Chef::Log.info("[CLOUD] :: #{recipe_name}")

# node.default['owncloud']['admin']['pass'] = ''
# node.default['owncloud']['config']['dbpassword'] = ''
# node.default['owncloud']['database']['rootpassword'] = ''

node.default['owncloud']['server_name'] = node['paramount']['domain']
node.default['owncloud']['config']['dbtype'] = 'pgsql'
# node.default['owncloud']['ssl'] = true

# ssl cert
# node.default['owncloud']['ssl_key']
# node.default['owncloud']['ssl_cert']

# node.default['owncloud']['config']

# include_recipe 'owncloud'


text:
<!DOCTYPE html>

    <title>Example</title>

    <link rel="stylesheet" type="text/css" href="styles.css"/>

Jacqui's Flower Shop

    <form id="orderForm" method="post" action="http://node.jacquisflowershop.com/order">

<button type="submit">Place Order</button>

    </form>
    <form id="summaryForm" method="post" action="">

Order Summary

Product	Quantity

Number of Items:

Total Price:

<button type="submit">Complete Order</button>

    </form>


text:
package org.jetbrains.idea.svn;

import org.tigris.subversion.javahl.*;

import java.io.OutputStream;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Irina.Chernushina
 * Date: 2/5/13
 * Time: 3:08 PM
 */
public class SvnBindClient implements SVNClientInterface {
  private final String myExecutablePath;
  private CommitEventHandler myHandler;
  private AuthenticationCallback myAuthenticationCallback;

  public SvnBindClient(String path) {
    myExecutablePath = path;
  }

  @Override
  public void dispose() {
  }

  @Override
  public Version getVersion() {
    // todo real version
    throw new UnsupportedOperationException();
  }

  @Override
  public String getAdminDirectoryName() {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean isAdminDirectory(String name) {
    throw new UnsupportedOperationException();
  }

  @Override
  public String getLastPath() {
    throw new UnsupportedOperationException();
  }

  @Override
  public Status singleStatus(String path, boolean onServer) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Status[] status(String path, boolean descend, boolean onServer, boolean getAll) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Status[] status(String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Status[] status(String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void status(String path,
                     int depth,
                     boolean onServer,
                     boolean getAll,
                     boolean noIgnore,
                     boolean ignoreExternals,
                     String[] changelists,
                     StatusCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public DirEntry[] list(String url, Revision revision, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public DirEntry[] list(String url, Revision revision, Revision pegRevision, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void list(String url,
                   Revision revision,
                   Revision pegRevision,
                   int depth,
                   int direntFields,
                   boolean fetchLocks,
                   ListCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void username(String username) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void password(String password) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void setPrompt(PromptUserPassword prompt) {
    throw new UnsupportedOperationException();
  }

  @Override
  public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public LogMessage[] logMessages(String path,
                                  Revision revisionStart,
                                  Revision revisionEnd,
                                  boolean stopOnCopy,
                                  boolean discoverPath,
                                  long limit) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void logMessages(String path,
                          Revision pegRevision,
                          Revision revisionStart,
                          Revision revisionEnd,
                          boolean stopOnCopy,
                          boolean discoverPath,
                          boolean includeMergedRevisions,
                          String[] revProps,
                          long limit,
                          LogMessageCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void logMessages(String path,
                          Revision pegRevision,
                          RevisionRange[] ranges,
                          boolean stopOnCopy,
                          boolean discoverPath,
                          boolean includeMergedRevisions,
                          String[] revProps,
                          long limit,
                          LogMessageCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long checkout(String moduleName, String destPath, Revision revision, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long checkout(String moduleName,
                       String destPath,
                       Revision revision,
                       Revision pegRevision,
                       boolean recurse,
                       boolean ignoreExternals) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long checkout(String moduleName,
                       String destPath,
                       Revision revision,
                       Revision pegRevision,
                       int depth,
                       boolean ignoreExternals,
                       boolean allowUnverObstructions) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void notification(Notify notify) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void notification2(Notify2 notify) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void setConflictResolver(ConflictResolverCallback listener) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void setProgressListener(ProgressListener listener) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void commitMessageHandler(CommitMessage messageHandler) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void remove(String[] path, String message, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void remove(String[] path, String message, boolean force, boolean keepLocal, Map revpropTable) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void revert(String path, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void revert(String path, int depth, String[] changelists) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void add(String path, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void add(String path, boolean recurse, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void add(String path, int depth, boolean force, boolean noIgnores, boolean addParents) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long update(String path, Revision revision, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long[] update(String[] path, Revision revision, boolean recurse, boolean ignoreExternals) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long update(String path,
                     Revision revision,
                     int depth,
                     boolean depthIsSticky,
                     boolean ignoreExternals,
                     boolean allowUnverObstructions) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long[] update(String[] path,
                       Revision revision,
                       int depth,
                       boolean depthIsSticky,
                       boolean ignoreExternals,
                       boolean allowUnverObstructions) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long commit(String[] path, String message, boolean recurse) throws ClientException {
    return commit(path, message, recurse? 3 : 0, false, false, null, null);
  }

  @Override
  public long commit(String[] path, String message, boolean recurse, boolean noUnlock) throws ClientException {
    return commit(path, message, recurse? 3 : 0, noUnlock, false, null, null);
  }

  @Override
  public long commit(String[] path,
                     String message,
                     int depth,
                     boolean noUnlock,
                     boolean keepChangelist,
                     String[] changelists,
                     Map revpropTable) throws ClientException {
    final long commit = new SvnCommitRunner(myExecutablePath, myHandler, myAuthenticationCallback).
        commit(path, message, depth, noUnlock, keepChangelist, changelists, revpropTable);
    if (commit < 0) {
      throw new BindClientException("Wrong committed revision number: " + commit, null, -1);
    }
    return commit;
  }

  @Override
  public void copy(CopySource[] sources,
                   String destPath,
                   String message,
                   boolean copyAsChild,
                   boolean makeParents,
                   boolean ignoreExternals,
                   Map revpropTable) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void copy(CopySource[] sources, String destPath, String message, boolean copyAsChild, boolean makeParents, Map revpropTable)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void copy(String srcPath, String destPath, String message, Revision revision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void move(String[] srcPaths,
                   String destPath,
                   String message,
                   boolean force,
                   boolean moveAsChild,
                   boolean makeParents,
                   Map revpropTable) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void move(String srcPath, String destPath, String message, Revision ignored, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void move(String srcPath, String destPath, String message, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void mkdir(String[] path, String message, boolean makeParents, Map revpropTable) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void mkdir(String[] path, String message) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void cleanup(String path) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void resolve(String path, int depth, int conflictResult) throws SubversionException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void resolved(String path, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long doExport(String srcPath, String destPath, Revision revision, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long doExport(String srcPath,
                       String destPath,
                       Revision revision,
                       Revision pegRevision,
                       boolean force,
                       boolean ignoreExternals,
                       boolean recurse,
                       String nativeEOL) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long doExport(String srcPath,
                       String destPath,
                       Revision revision,
                       Revision pegRevision,
                       boolean force,
                       boolean ignoreExternals,
                       int depth,
                       String nativeEOL) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long doSwitch(String path, String url, Revision revision, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public long doSwitch(String path,
                       String url,
                       Revision revision,
                       Revision pegRevision,
                       int depth,
                       boolean depthIsSticky,
                       boolean ignoreExternals,
                       boolean allowUnverObstructions) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void doImport(String path, String url, String message, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void doImport(String path,
                       String url,
                       String message,
                       int depth,
                       boolean noIgnore,
                       boolean ignoreUnknownNodeTypes,
                       Map revpropTable) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public String[] suggestMergeSources(String path, Revision pegRevision) throws SubversionException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void merge(String path1,
                    Revision revision1,
                    String path2,
                    Revision revision2,
                    String localPath,
                    boolean force,
                    boolean recurse,
                    boolean ignoreAncestry,
                    boolean dryRun) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void merge(String path1,
                    Revision revision1,
                    String path2,
                    Revision revision2,
                    String localPath,
                    boolean force,
                    int depth,
                    boolean ignoreAncestry,
                    boolean dryRun,
                    boolean recordOnly) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void merge(String path,
                    Revision pegRevision,
                    Revision revision1,
                    Revision revision2,
                    String localPath,
                    boolean force,
                    boolean recurse,
                    boolean ignoreAncestry,
                    boolean dryRun) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void merge(String path,
                    Revision pegRevision,
                    RevisionRange[] revisions,
                    String localPath,
                    boolean force,
                    int depth,
                    boolean ignoreAncestry,
                    boolean dryRun,
                    boolean recordOnly) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void mergeReintegrate(String path, Revision pegRevision, String localPath, boolean dryRun) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Mergeinfo getMergeinfo(String path, Revision pegRevision) throws SubversionException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void getMergeinfoLog(int kind,
                              String pathOrUrl,
                              Revision pegRevision,
                              String mergeSourceUrl,
                              Revision srcPegRevision,
                              boolean discoverChangedPaths,
                              int depth,
                              String[] revProps,
                              LogMessageCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void getMergeinfoLog(int kind,
                              String pathOrUrl,
                              Revision pegRevision,
                              String mergeSourceUrl,
                              Revision srcPegRevision,
                              boolean discoverChangedPaths,
                              String[] revProps,
                              LogMessageCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target1,
                   Revision revision1,
                   String target2,
                   Revision revision2,
                   String outFileName,
                   boolean recurse,
                   boolean ignoreAncestry,
                   boolean noDiffDeleted,
                   boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target1,
                   Revision revision1,
                   String target2,
                   Revision revision2,
                   String relativeToDir,
                   String outFileName,
                   int depth,
                   String[] changelists,
                   boolean ignoreAncestry,
                   boolean noDiffDeleted,
                   boolean force,
                   boolean copiesAsAdds) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target1,
                   Revision revision1,
                   String target2,
                   Revision revision2,
                   String relativeToDir,
                   String outFileName,
                   int depth,
                   String[] changelists,
                   boolean ignoreAncestry,
                   boolean noDiffDeleted,
                   boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target,
                   Revision pegRevision,
                   Revision startRevision,
                   Revision endRevision,
                   String outFileName,
                   boolean recurse,
                   boolean ignoreAncestry,
                   boolean noDiffDeleted,
                   boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target,
                   Revision pegRevision,
                   Revision startRevision,
                   Revision endRevision,
                   String relativeToDir,
                   String outFileName,
                   int depth,
                   String[] changelists,
                   boolean ignoreAncestry,
                   boolean noDiffDeleted,
                   boolean force,
                   boolean copiesAsAdds) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diff(String target,
                   Revision pegRevision,
                   Revision startRevision,
                   Revision endRevision,
                   String relativeToDir,
                   String outFileName,
                   int depth,
                   String[] changelists,
                   boolean ignoreAncestry,
                   boolean noDiffDeleted,
                   boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diffSummarize(String target1,
                            Revision revision1,
                            String target2,
                            Revision revision2,
                            int depth,
                            String[] changelists,
                            boolean ignoreAncestry,
                            DiffSummaryReceiver receiver) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void diffSummarize(String target,
                            Revision pegRevision,
                            Revision startRevision,
                            Revision endRevision,
                            int depth,
                            String[] changelists,
                            boolean ignoreAncestry,
                            DiffSummaryReceiver receiver) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData[] properties(String path) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData[] properties(String path, Revision revision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData[] properties(String path, Revision revision, Revision pegRevision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void properties(String path, Revision revision, Revision pegRevision, int depth, String[] changelists, ProplistCallback callback)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertySet(String path, String name, String value, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertySet(String path, String name, String value, boolean recurse, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertySet(String path, String name, byte[] value, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertySet(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertySet(String path, String name, String value, int depth, String[] changelists, boolean force, Map revpropTable)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyRemove(String path, String name, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyRemove(String path, String name, int depth, String[] changelists) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyCreate(String path, String name, String value, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyCreate(String path, String name, String value, boolean recurse, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyCreate(String path, String name, byte[] value, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyCreate(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void propertyCreate(String path, String name, String value, int depth, String[] changelists, boolean force)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData revProperty(String path, String name, Revision rev) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData[] revProperties(String path, Revision rev) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void setRevProperty(String path, String name, Revision rev, String value, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void setRevProperty(String path, String name, Revision rev, String value, String originalValue, boolean force)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData propertyGet(String path, String name) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData propertyGet(String path, String name, Revision revision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public PropertyData propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public byte[] fileContent(String path, Revision revision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void streamFileContent(String path, Revision revision, Revision pegRevision, int bufferSize, OutputStream stream)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void relocate(String from, String to, String path, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public byte[] blame(String path, Revision revisionStart, Revision revisionEnd) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void blame(String path, Revision revisionStart, Revision revisionEnd, BlameCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, BlameCallback callback)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void blame(String path,
                    Revision pegRevision,
                    Revision revisionStart,
                    Revision revisionEnd,
                    boolean ignoreMimeType,
                    boolean includeMergedRevisions,
                    BlameCallback2 callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void blame(String path,
                    Revision pegRevision,
                    Revision revisionStart,
                    Revision revisionEnd,
                    boolean ignoreMimeType,
                    boolean includeMergedRevisions,
                    BlameCallback3 callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void setConfigDirectory(String configDir) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public String getConfigDirectory() throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void cancelOperation() throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Info info(String path) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void addToChangelist(String[] paths, String changelist, int depth, String[] changelists) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void removeFromChangelists(String[] paths, int depth, String[] changelists) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void getChangelists(String rootPath, String[] changelists, int depth, ChangelistCallback callback) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void lock(String[] path, String comment, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void unlock(String[] path, boolean force) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Info2[] info2(String pathOrUrl, Revision revision, Revision pegRevision, boolean recurse) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void info2(String pathOrUrl, Revision revision, Revision pegRevision, int depth, String[] changelists, InfoCallback callback)
    throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException {
    throw new UnsupportedOperationException();
  }

  @Override
  public void upgrade(String path) throws ClientException {
    throw new UnsupportedOperationException();
  }

  public void setHandler(CommitEventHandler handler) {
    myHandler = handler;
  }

  public void setAuthenticationCallback(AuthenticationCallback authenticationCallback) {
    myAuthenticationCallback = authenticationCallback;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info organisation="atg.tools"
          module="atg-ant-plugin"
          revision="2.0.0-SNAPSHOT">
        <license name="MIT" url="http://opensource.org/licenses/MIT"/>
        <description homepage="http://atg-tools.com/">
            Ant library to aid in creating build scripts for Oracle Commerce ATG modules.
        </description>
    </info>
    <configurations>
        <conf name="compile"/>
        <conf name="test" extends="compile"/>
    </configurations>
    <dependencies>
        <dependency name="hamcrest-all" rev="1.3" org="org.hamcrest" conf="test->default"/>
        <dependency name="junit" rev="4.11" org="junit" conf="test->default"/>
    </dependencies>
</ivy-module>


text:
/* eslint-disable camelcase */
import {
  ADD_FILTER,
  REMOVE_FILTER,
  CHANGE_FILTER,
  UPDATE_DIRECT_PATH_TO_FILTER,
  UPDATE_LAYOUT_COMPONENTS,
  UPDATE_DASHBOARD_FILTERS_SCOPE,
} from '../actions/dashboardFilters';
import { HYDRATE_DASHBOARD } from '../actions/hydrate';
import { TIME_RANGE } from '../../visualizations/FilterBox/FilterBox';
import { DASHBOARD_ROOT_ID } from '../util/constants';
import getFilterConfigsFromFormdata from '../util/getFilterConfigsFromFormdata';
import { buildActiveFilters } from '../util/activeDashboardFilters';
import { getChartIdAndColumnFromFilterKey } from '../util/getDashboardFilterKey';

export const DASHBOARD_FILTER_SCOPE_GLOBAL = {
  scope: [DASHBOARD_ROOT_ID],
  immune: [],
};

export const dashboardFilter = {
  chartId: null,
  componentId: null,
  filterName: null,
  datasourceId: null,
  directPathToFilter: [],
  isDateFilter: false,
  isInstantFilter: true,
  columns: {},
  labels: {},
  scopes: {},
};

const CHANGE_FILTER_VALUE_ACTIONS = [ADD_FILTER, REMOVE_FILTER, CHANGE_FILTER];

export default function dashboardFiltersReducer(dashboardFilters = {}, action) {
  const actionHandlers = {
    [ADD_FILTER]() {
      const { chartId, component, form_data } = action;
      const { columns, labels } = getFilterConfigsFromFormdata(form_data);
      const scopes = Object.keys(columns).reduce(
        (map, column) => ({
          ...map,
          [column]: DASHBOARD_FILTER_SCOPE_GLOBAL,
        }),
        {},
      );
      const directPathToFilter = component
        ? (component.parents || []).slice().concat(component.id)
        : [];

      const newFilter = {
        ...dashboardFilter,
        chartId,
        componentId: component.id,
        datasourceId: form_data.datasource,
        filterName: component.meta.sliceName,
        directPathToFilter,
        columns,
        labels,
        scopes,
        isInstantFilter: !!form_data.instant_filtering,
        isDateFilter: Object.keys(columns).includes(TIME_RANGE),
      };

      return newFilter;
    },

    [CHANGE_FILTER](state) {
      const { newSelectedValues, merge } = action;
      const updatedColumns = Object.keys(newSelectedValues).reduce(
        (columns, name) => {
          // override existed column value, or add new column name
          if (!merge || !(name in columns)) {
            return {
              ...columns,
              [name]: newSelectedValues[name],
            };
          }

          return {
            ...columns,
            [name]: [...columns[name], ...newSelectedValues[name]],
          };
        },
        { ...state.columns },
      );

      return {
        ...state,
        columns: updatedColumns,
      };
    },

    [UPDATE_DIRECT_PATH_TO_FILTER](state) {
      const { path } = action;
      return {
        ...state,
        directPathToFilter: path,
      };
    },
  };

  if (action.type === UPDATE_LAYOUT_COMPONENTS) {
    buildActiveFilters({
      dashboardFilters,
      components: action.components,
    });
    return dashboardFilters;
  }
  if (action.type === UPDATE_DASHBOARD_FILTERS_SCOPE) {
    const allDashboardFiltersScope = action.scopes;
    // update filter scope for each filter field
    const updatedFilters = Object.entries(allDashboardFiltersScope).reduce(
      (map, entry) => {
        const [filterKey, { scope, immune }] = entry;
        const { chartId, column } = getChartIdAndColumnFromFilterKey(filterKey);
        const scopes = {
          ...map[chartId].scopes,
          [column]: {
            scope,
            immune,
          },
        };
        return {
          ...map,
          [chartId]: {
            ...map[chartId],
            scopes,
          },
        };
      },
      dashboardFilters,
    );

    buildActiveFilters({ dashboardFilters: updatedFilters });
    return updatedFilters;
  }
  if (action.type === REMOVE_FILTER) {
    const { chartId } = action;
    const { [chartId]: deletedFilter, ...updatedFilters } = dashboardFilters;
    buildActiveFilters({ dashboardFilters: updatedFilters });

    return updatedFilters;
  }
  if (action.type === HYDRATE_DASHBOARD) {
    return action.data.dashboardFilters;
  }

  if (action.type in actionHandlers) {
    const updatedFilters = {
      ...dashboardFilters,
      [action.chartId]: actionHandlers[action.type](
        dashboardFilters[action.chartId],
      ),
    };
    if (CHANGE_FILTER_VALUE_ACTIONS.includes(action.type)) {
      buildActiveFilters({ dashboardFilters: updatedFilters });
    }

    return updatedFilters;
  }

  return dashboardFilters;
}


text:
package org.renyan.leveldb.table;

import org.renyan.leveldb.util.Slice;

import java.util.Comparator;

// todo this interface needs more thought
public interface UserComparator extends Comparator<Slice>
{
    String name();

    Slice findShortestSeparator(Slice start, Slice limit);

    Slice findShortSuccessor(Slice key);
}


text:
<?php $this->layout('layout', ['title' => 'Monocle']) ?>

Error

There was a problem trying to load the channels from your Microsub endpoint.

Microsub endpoint: <?= e($_SESSION['microsub']) ?>

Your website: <?= e($_SESSION['token']['me']) ?>

The endpoint returned the following response.

<?= e(json_encode($response, JSON_PRETTY_PRINT+JSON_UNESCAPED_SLASHES)) ?>

Start Over


text:
Parameters::Parameters(json_t *root) {

  // strategy and global parameters
  spreadEntry = json_real_value(json_object_get(root, "SpreadEntry"));
  spreadExit = json_real_value(json_object_get(root, "SpreadExit"));
  maxLength = json_integer_value(json_object_get(root, "MaxLength"));
  verbose = json_boolean_value(json_object_get(root, "Verbose"));

  // exchanges credentials
  bitfinexApi = json_string_value(json_object_get(root, "BitfinexApiHead"));
  bitfinexSecret = json_string_value(json_object_get(root, "BitfinexKey"));
  okCoinApi = json_string_value(json_object_get(root, "OkCoinApiKey"));
  okCoinSecret = json_string_value(json_object_get(root, "OkCoinSecretKey"));
  bitstampClientId = json_string_value(json_object_get(root, "BitstampClientId"));
  bitstampApi = json_string_value(json_object_get(root, "BitstampApiKey"));
  bitstampSecret = json_string_value(json_object_get(root, "BitstampSecretKey"));

  // email
  sendEmail = json_boolean_value(json_object_get(root, "SendEmail"));
  senderAddress = json_string_value(json_object_get(root, "SenderAddress"));
  senderUsername = json_string_value(json_object_get(root, "SenderUsername"));
  senderPassword = json_string_value(json_object_get(root, "SenderPassword"));
  smtpServerAddress = json_string_value(json_object_get(root, "SmtpServerAddress"));
  receiverAddress = json_string_value(json_object_get(root, "ReceiverAddress"));
}

// add an exchange
void Parameters::addExchange(std::string n, double f, bool h) {
  exchName.push_back(n);
  fees.push_back(f);
  hasShort.push_back(h);
}

// returns number of exchanges
unsigned Parameters::nbExch() const {
  return exchName.size();
}


text:
package types

// ClusterOperatingSystemArchitecture type.
//
// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/cluster/stats/types.ts#L223-L226
type ClusterOperatingSystemArchitecture struct {
	Arch  string `json:"arch"`
	Count int    `json:"count"`
}

// NewClusterOperatingSystemArchitecture returns a ClusterOperatingSystemArchitecture.
func NewClusterOperatingSystemArchitecture() *ClusterOperatingSystemArchitecture {
	r := &ClusterOperatingSystemArchitecture{}

	return r
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace BHS_questionnaire_demo
{
    class RankBox
    {
        private Label label;
        private ComboBox select;
        private Question question;
        private int spacer = 5;
        private QuestionManager qm;
        private Option previouslySelectedOption;
        private string processedData;

        public RankBox(string labelText, Question question, int xPos, int yPos, int width, int selectLength, QuestionManager qm)
        {

            this.question = question;
            label = new Label();
            label.Text = labelText;
            label.ForeColor = GlobalColours.mainTextColour;
            label.Location = new Point(xPos, yPos);
            label.Size = new Size(width, 30);

            select = new ComboBox();

            select.Click += new EventHandler(question.button_click);

            //stop user being able to type in the combobox
            select.DropDownStyle = ComboBoxStyle.DropDownList;
            select.BackColor = GlobalColours.controlBackColour;

            select.Location = new Point(xPos, yPos + 30 + spacer);
            select.Size = new Size(selectLength, 20);
            select.IntegralHeight = false; //won't work unless this is set to false
            select.MaxDropDownItems = 5;

            question.setFontSize(label, select);

            this.qm = qm;

            qm.getPanel().Controls.Add(label);
            qm.getPanel().Controls.Add(select);

            //MessageBox.Show("Adding label at Y:" + yPos + ". Adding select at Y:" + (yPos + 30 + spacer));

        }

        public void AddOption(Option op)
        {
            select.Items.Add(op);

        }

        public void removeControls()
        {

            qm.getPanel().Controls.Remove(label);
            qm.getPanel().Controls.Remove(select);
            label.Dispose();
            select.Dispose();

        }

        public void setProcessedData(string pd)
        {
            processedData = pd;

        }

        public string getProcessedData()
        {
            return processedData;

        }

        /*
        public void setProcessedData(Option op)
        {

            if (processedData == op.getValue())
            {
                previouslySelectedOption = op;

            }

        }
         */

        public void setSelectedOption(Option op)
        {

            select.SelectedItem = op;

        }

        public Option getSelectedOption()
        {

            return (Option)(select.SelectedItem);

        }

    }
}