text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_VIEW_IMPL_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_VIEW_IMPL_H_

#include <memory>

#include "base/gtest_prod_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/observer_list.h"
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/remote_set.h"
#include "third_party/blink/public/common/input/web_gesture_event.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
#include "third_party/blink/public/common/tokens/tokens.h"
#include "third_party/blink/public/mojom/frame/frame.mojom-blink.h"
#include "third_party/blink/public/mojom/input/focus_type.mojom-blink-forward.h"
#include "third_party/blink/public/mojom/page/page.mojom-blink.h"
#include "third_party/blink/public/mojom/page/page_visibility_state.mojom-blink.h"
#include "third_party/blink/public/mojom/renderer_preference_watcher.mojom-blink.h"
#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h"
#include "third_party/blink/public/platform/web_input_event_result.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_navigation_policy.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/public/web/web_view_observer.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/exported/web_page_popup_impl.h"
#include "third_party/blink/renderer/core/frame/resize_viewport_anchor.h"
#include "third_party/blink/renderer/core/loader/navigation_policy.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/context_menu_provider.h"
#include "third_party/blink/renderer/core/page/event_with_hit_test_results.h"
#include "third_party/blink/renderer/core/page/page_widget_delegate.h"
#include "third_party/blink/renderer/core/page/scoped_page_pauser.h"
#include "third_party/blink/renderer/platform/graphics/apply_viewport_changes.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d_f.h"

namespace cc {
class ScopedDeferMainFrameUpdate;
}

namespace blink {

namespace frame_test_helpers {
class WebViewHelper;
}

class BrowserControls;
class DevToolsEmulator;
class Frame;
class FullscreenController;
class PageScaleConstraintsSet;
class WebDevToolsAgentImpl;
class WebLocalFrame;
class WebLocalFrameImpl;
class WebSettingsImpl;
class WebViewClient;
class WebFrameWidgetImpl;

enum class FullscreenRequestType;

namespace mojom {
namespace blink {
class TextAutosizerPageInfo;
}
}  // namespace mojom

using PaintHoldingCommitTrigger = cc::PaintHoldingCommitTrigger;

class CORE_EXPORT WebViewImpl final : public WebView,
                                      public RefCounted<WebViewImpl>,
                                      public mojom::blink::PageBroadcast {
 public:
  static WebViewImpl* Create(
      WebViewClient*,
      mojom::blink::PageVisibilityState visibility,
      bool is_prerendering,
      bool is_inside_portal,
      bool is_fenced_frame,
      bool compositing_enabled,
      bool widgets_never_composited,
      WebViewImpl* opener,
      mojo::PendingAssociatedReceiver<mojom::blink::PageBroadcast> page_handle,
      scheduler::WebAgentGroupScheduler& agent_group_scheduler,
      const SessionStorageNamespaceId& session_storage_namespace_id,
      absl::optional<SkColor> page_base_background_color);

  // All calls to Create() should be balanced with a call to Close(). This
  // synchronously destroys the WebViewImpl.
  void Close() override;

  static HashSet<WebViewImpl*>& AllInstances();
  // Returns true if popup menus should be rendered by the browser, false if
  // they should be rendered by WebKit (which is the default).
  static bool UseExternalPopupMenus();

  // Returns whether frames under this WebView are backed by a compositor.
  bool does_composite() const { return does_composite_; }

  // WebView methods:
  void DidAttachLocalMainFrame() override;
  void DidDetachLocalMainFrame() override;
  void DidAttachRemoteMainFrame(
      CrossVariantMojoAssociatedRemote<
          mojom::blink::RemoteMainFrameHostInterfaceBase>,
      CrossVariantMojoAssociatedReceiver<
          mojom::blink::RemoteMainFrameInterfaceBase>) override;
  void DidDetachRemoteMainFrame() override;
  void SetNoStatePrefetchClient(WebNoStatePrefetchClient*) override;
  WebSettings* GetSettings() override;
  WebString PageEncoding() const override;
  void SetTabKeyCyclesThroughElements(bool value) override;
  bool IsActive() const override;
  void SetIsActive(bool value) override;
  void SetWindowFeatures(const WebWindowFeatures&) override;
  void SetOpenedByDOM() override;
  WebFrame* MainFrame() override;
  const WebFrame* MainFrame() const override;
  WebLocalFrame* FocusedFrame() override;
  void SetFocusedFrame(WebFrame*) override;
  void SmoothScroll(int target_x,
                    int target_y,
                    base::TimeDelta duration) override;
  void AdvanceFocus(bool reverse) override;
  double ZoomLevel() override;
  double SetZoomLevel(double) override;
  float PageScaleFactor() const override;
  float MinimumPageScaleFactor() const override;
  float MaximumPageScaleFactor() const override;
  void SetDefaultPageScaleLimits(float min_scale, float max_scale) override;
  void SetInitialPageScaleOverride(float) override;
  void SetPageScaleFactor(float) override;
  void SetVisualViewportOffset(const gfx::PointF&) override;
  gfx::PointF VisualViewportOffset() const override;
  gfx::SizeF VisualViewportSize() const override;
  void SetScreenOrientationOverrideForTesting(
      absl::optional<display::mojom::blink::ScreenOrientation> orientation)
      override;
  void UseSynchronousResizeModeForTesting(bool enable) override;
  void SetWindowRectSynchronouslyForTesting(
      const gfx::Rect& new_window_rect) override;
  void ResetScrollAndScaleState() override;
  gfx::Size ContentsPreferredMinimumSize() override;
  void UpdatePreferredSize() override;
  void EnablePreferredSizeChangedMode() override;
  void SetDeviceScaleFactor(float) override;
  void SetZoomFactorForDeviceScaleFactor(float) override;
  float ZoomFactorForDeviceScaleFactor() override {
    return zoom_factor_for_device_scale_factor_;
  }
  bool AutoResizeMode() override;
  void EnableAutoResizeForTesting(const gfx::Size& min_window_size,
                                  const gfx::Size& max_window_size) override;
  void DisableAutoResizeForTesting(const gfx::Size& new_window_size) override;
  WebHitTestResult HitTestResultForTap(const gfx::Point&,
                                       const gfx::Size&) override;
  void EnableDeviceEmulation(const DeviceEmulationParams&) override;
  void DisableDeviceEmulation() override;
  void PerformCustomContextMenuAction(unsigned action) override;
  void DidCloseContextMenu() override;
  void CancelPagePopup() override;
  WebPagePopupImpl* GetPagePopup() const override { return page_popup_.get(); }
  void SetPageFrozen(bool frozen) override;
  WebFrameWidget* MainFrameWidget() override;
  void SetDeviceColorSpaceForTesting(
      const gfx::ColorSpace& color_space) override;
  void PaintContent(cc::PaintCanvas*, const gfx::Rect&) override;
  void RegisterRendererPreferenceWatcher(
      CrossVariantMojoRemote<mojom::RendererPreferenceWatcherInterfaceBase>
          watcher) override;
  void SetRendererPreferences(const RendererPreferences& preferences) override;
  const RendererPreferences& GetRendererPreferences() const override;
  void SetWebPreferences(const web_pref::WebPreferences& preferences) override;
  const web_pref::WebPreferences& GetWebPreferences() override;
  void SetHistoryListFromNavigation(
      int32_t history_offset,
      absl::optional<int32_t> history_length) override;
  void IncreaseHistoryListFromNavigation() override;
  int32_t HistoryBackListCount() const override;
  int32_t HistoryForwardListCount() const override;
  int32_t HistoryListLength() const { return history_list_length_; }
  const SessionStorageNamespaceId& GetSessionStorageNamespaceId() override;
  bool IsFencedFrameRoot() const override;

  // Functions to add and remove observers for this object.
  void AddObserver(WebViewObserver* observer);
  void RemoveObserver(WebViewObserver* observer);

  // `BaseBackgroundColor()` affects how the document is rendered.
  // `BackgroundColor()` is what the document computes as its background color
  // (with `BaseBackgroundColor()` as an input), or `BaseBackgroundColor()` if
  // there is no local main frame; it's used as the background color of the
  // compositor.
  //
  // These methods override `BaseBackgroundColor()` or `BackgroundColor()` for
  // specific use cases. You can use this to set a transparent background,
  // which is useful if you want to have some custom background rendered behind
  // the widget.
  //
  // These settings only have an effect for composited WebViews
  // These overrides are listed in order of precedence.
  // - Overriding the background color for fullscreen ignores all other inputs,
  //   including `BaseBackgroundColor()`. Note, however, that
  //   `BaseBackgroundColor()` is passed directly into
  //   `LocalFrameView::SetBaseBackgroundColor`.
  // - Overriding base background color transparency takes precedences over
  //   any base background color that might be specified for inspector--the
  //   transparency specified in the inspector base background color is
  //   ignored.
  //
  // Add new methods with clear precedence for new use cases.
  void SetBackgroundColorOverrideForFullscreenController(
      absl::optional<SkColor>);
  void SetBaseBackgroundColorOverrideTransparent(bool override_to_transparent);
  void SetBaseBackgroundColorOverrideForInspector(absl::optional<SkColor>);

  // Resize the WebView. You likely should be using
  // MainFrameWidget()->Resize instead.
  void Resize(const gfx::Size&);

  // This method is used for testing.
  // Resize the view at the same time as changing the state of the top
  // controls. If |browser_controls_shrink_layout| is true, the embedder shrunk
  // the WebView size by the browser controls height.
  void ResizeWithBrowserControls(const gfx::Size& main_frame_widget_size,
                                 float top_controls_height,
                                 float bottom_controls_height,
                                 bool browser_controls_shrink_layout);
  // Same as ResizeWithBrowserControls(const gfx::Size&,float,float,bool), but
  // includes all browser controls params such as the min heights.
  void ResizeWithBrowserControls(const gfx::Size& main_frame_widget_size,
                                 const gfx::Size& visible_viewport_size,
                                 cc::BrowserControlsParams);

  // Requests a page-scale animation based on the specified point/rect.
  void AnimateDoubleTapZoom(const gfx::Point&, const gfx::Rect& block_bounds);

  // mojom::blink::PageBroadcast method:
  void SetPageLifecycleState(
      mojom::blink::PageLifecycleStatePtr state,
      mojom::blink::PageRestoreParamsPtr page_restore_params,
      SetPageLifecycleStateCallback callback) override;
  void AudioStateChanged(bool is_audio_playing) override;
  void ActivatePrerenderedPage(
      base::TimeTicks activation_start,
      ActivatePrerenderedPageCallback callback) override;
  void SetInsidePortal(bool is_inside_portal) override;
  void UpdateWebPreferences(
      const blink::web_pref::WebPreferences& preferences) override;
  void UpdateRendererPreferences(
      const RendererPreferences& preferences) override;
  void SetHistoryOffsetAndLength(int32_t history_offset,
                                 int32_t history_length) override;
  void SetPageBaseBackgroundColor(absl::optional<SkColor> color) override;

  void DispatchPageshow(base::TimeTicks navigation_start);
  void DispatchPagehide(mojom::blink::PagehideDispatch pagehide_dispatch);
  void HookBackForwardCacheEviction(bool hook);

  float DefaultMinimumPageScaleFactor() const;
  float DefaultMaximumPageScaleFactor() const;
  float ClampPageScaleFactorToLimits(float) const;
  void ResetScaleStateImmediately();
  absl::optional<display::mojom::blink::ScreenOrientation>
  ScreenOrientationOverride();

  // This is only for non-composited WebViewPlugin.
  void InvalidateContainer();

  void SetZoomFactorOverride(float);
  void SetCompositorDeviceScaleFactorOverride(float);
  TransformationMatrix GetDeviceEmulationTransform() const;
  void EnableAutoResizeMode(const gfx::Size& min_viewport_size,
                            const gfx::Size& max_viewport_size);
  void DisableAutoResizeMode();
  void ActivateDevToolsTransform(const DeviceEmulationParams&);
  void DeactivateDevToolsTransform();

  SkColor BackgroundColor() const;
  Color BaseBackgroundColor() const;

  Frame* FocusedCoreFrame() const;

  // Returns the currently focused Element or null if no element has focus.
  Element* FocusedElement() const;

  WebViewClient* Client() { return web_view_client_; }

  // Returns the page object associated with this view. This may be null when
  // the page is shutting down, but will be valid at all other times.
  Page* GetPage() const { return page_.Get(); }

  WebDevToolsAgentImpl* MainFrameDevToolsAgentImpl();

  DevToolsEmulator* GetDevToolsEmulator() const {
    return dev_tools_emulator_.Get();
  }

  // When true, a hint to all WebWidgets that they will never be
  // user-visible and thus never need to produce pixels for display. This is
  // separate from page visibility, as background pages can be marked visible in
  // blink even though they are not user-visible. Page visibility controls blink
  // behaviour for javascript, timers, and such to inform blink it is in the
  // foreground or background. Whereas this bit refers to user-visibility and
  // whether the tab needs to produce pixels to put on the screen at some point
  // or not.
  bool widgets_never_composited() const { return widgets_never_composited_; }

  // Returns the main frame associated with this view. This will be null when
  // the main frame is remote.
  // Internally during startup/shutdown this can be null when no main frame
  // (local or remote) is attached, but this should not generally matter to code
  // outside this class.
  WebLocalFrameImpl* MainFrameImpl() const;

  // TODO(https://crbug.com/1139104): Remove this.
  std::string GetNullFrameReasonForBug1139104() const;

  // Changes the zoom and scroll for zooming into an editable element
  // with bounds |element_bounds_in_document| and caret bounds
  // |caret_bounds_in_document|.
  void ZoomAndScrollToFocusedEditableElementRect(
      const gfx::Rect& element_bounds_in_document,
      const gfx::Rect& caret_bounds_in_document,
      bool zoom_into_legible_scale);

  bool StartPageScaleAnimation(const gfx::Point& target_position,
                               bool use_anchor,
                               float new_scale,
                               base::TimeDelta duration);

  // Handles context menu events orignated via the the keyboard. These
  // include the VK_APPS virtual key and the Shift+F10 combine. Code is
  // based on the Webkit function bool WebView::handleContextMenuEvent(WPARAM
  // wParam, LPARAM lParam) in webkit\webkit\win\WebView.cpp. The only
  // significant change in this function is the code to convert from a
  // Keyboard event to the Right Mouse button down event.
  WebInputEventResult SendContextMenuEvent();

  // Notifies the WebView that a load has been committed. isNewNavigation
  // will be true if a new session history item should be created for that
  // load. isNavigationWithinPage will be true if the navigation does
  // not take the user away from the current page.
  void DidCommitLoad(bool is_new_navigation, bool is_navigation_within_page);

  // Indicates two things:
  //   1) This view may have a new layout now.
  //   2) Layout is up-to-date.
  // After calling WebWidget::updateAllLifecyclePhases(), expect to get this
  // notification unless the view did not need a layout.
  void MainFrameLayoutUpdated();
  void ResizeAfterLayout();
  void DidCommitCompositorFrameForLocalMainFrame();
  void DidChangeContentsSize();
  void PageScaleFactorChanged();
  void MainFrameScrollOffsetChanged();
  void TextAutosizerPageInfoChanged(
      const mojom::blink::TextAutosizerPageInfo& page_info);

  bool ShouldAutoResize() const { return should_auto_resize_; }

  gfx::Size MinAutoSize() const { return min_auto_size_; }

  gfx::Size MaxAutoSize() const { return max_auto_size_; }

  void UpdateMainFrameLayoutSize();
  void UpdatePageDefinedViewportConstraints(const ViewportDescription&);

  WebPagePopupImpl* OpenPagePopup(PagePopupClient*);
  bool HasOpenedPopup() const { return page_popup_.get(); }
  void ClosePagePopup(PagePopup*);
  // Callback from PagePopup when it is closed, which it can be done directly
  // without coming through WebViewImpl.
  void CleanupPagePopup();
  // Ensure popup's size and position is correct based on its owner element's
  // dimensions.
  void UpdatePagePopup();
  LocalDOMWindow* PagePopupWindow() const;

  PageScheduler* Scheduler() const override;
  void SetVisibilityState(mojom::blink::PageVisibilityState visibility_state,
                          bool is_initial_state) override;
  mojom::blink::PageVisibilityState GetVisibilityState() override;

  void SetPageLifecycleStateFromNewPageCommit(
      mojom::blink::PageVisibilityState visibility,
      mojom::blink::PagehideDispatch pagehide_dispatch) override;

  // Called by a full frame plugin inside this view to inform it that its
  // zoom level has been updated.  The plugin should only call this function
  // if the zoom change was triggered by the browser, it's only needed in case
  // a plugin can update its own zoom, say because of its own UI.
  void FullFramePluginZoomLevelChanged(double zoom_level);

  // Requests a page-scale animation based on the specified rect.
  void ZoomToFindInPageRect(const gfx::Rect&);

  void ComputeScaleAndScrollForBlockRect(
      const gfx::Point& hit_point,
      const gfx::Rect& block_rect,
      float padding,
      float default_scale_when_already_legible,
      float& scale,
      gfx::Point& scroll);
  Node* BestTapNode(const GestureEventWithHitTestResults& targeted_tap_event);
  void EnableTapHighlightAtPoint(
      const GestureEventWithHitTestResults& targeted_tap_event);

  void EnableFakePageScaleAnimationForTesting(bool);
  bool FakeDoubleTapAnimationPendingForTesting() const {
    return double_tap_zoom_pending_;
  }
  gfx::Point FakePageScaleAnimationTargetPositionForTesting() const {
    return fake_page_scale_animation_target_position_;
  }
  float FakePageScaleAnimationPageScaleForTesting() const {
    return fake_page_scale_animation_page_scale_factor_;
  }
  bool FakePageScaleAnimationUseAnchorForTesting() const {
    return fake_page_scale_animation_use_anchor_;
  }

  void EnterFullscreen(LocalFrame&,
                       const FullscreenOptions*,
                       FullscreenRequestType);
  void ExitFullscreen(LocalFrame&);
  void FullscreenElementChanged(Element* old_element,
                                Element* new_element,
                                const FullscreenOptions* options,
                                FullscreenRequestType);

  // Sends a request to the main frame's view to resize, and updates the page
  // scale limits if needed.
  void SendResizeEventForMainFrame();

  // Exposed for testing purposes.
  bool HasHorizontalScrollbar();
  bool HasVerticalScrollbar();

  WebSettingsImpl* SettingsImpl();

  BrowserControls& GetBrowserControls();
  // Called anytime browser controls layout height or content offset have
  // changed.
  void DidUpdateBrowserControls();

  void AddAutoplayFlags(int32_t) override;
  void ClearAutoplayFlags() override;
  int32_t AutoplayFlagsForTest() override;
  gfx::Size GetPreferredSizeForTest() override;

  gfx::Size Size();
  gfx::Size MainFrameSize();

  PageScaleConstraintsSet& GetPageScaleConstraintsSet() const;

  gfx::Vector2dF ElasticOverscroll() const { return elastic_overscroll_; }

  class ChromeClient& GetChromeClient() const {
    return *chrome_client_.Get();
  }

  bool ShouldZoomToLegibleScale(const Element&);

  // Allows main frame updates to occur if they were previously blocked. They
  // are blocked during loading a navigation, to allow Blink to proceed without
  // being interrupted by useless work until enough progress is made that it
  // desires composited output to be generated.
  void StopDeferringMainFrameUpdate();

  // This function checks the element ids of ScrollableAreas only and returns
  // the equivalent DOM Node if such exists.
  Node* FindNodeFromScrollableCompositorElementId(
      cc::ElementId element_id) const;

  void DidEnterFullscreen();
  void DidExitFullscreen();

  // Called when some JS code has instructed the window associated to the main
  // frame to close, which will result in a request to the browser to close the
  // Widget associated to it.
  void CloseWindowSoon();

  // Controls whether pressing Tab key advances focus to links.
  bool TabsToLinks() const;
  void SetTabsToLinks(bool);

  // Prevent the web page from setting min/max scale via the viewport meta
  // tag. This is an accessibility feature that lets folks zoom in to web
  // pages even if the web page tries to block scaling.
  void SetIgnoreViewportTagScaleLimits(bool);

  // Sets the maximum page scale considered to be legible. Automatic zooms (e.g,
  // double-tap or find in page) will have the page scale limited to this value
  // times the font scale factor. Manual pinch zoom will not be affected by this
  // limit.
  void SetMaximumLegibleScale(float);

  void SetMainFrameViewWidget(WebFrameWidgetImpl* widget);
  WebFrameWidgetImpl* MainFrameViewWidget();

  // Called when hovering over an anchor with the given URL.
  void SetMouseOverURL(const KURL&);

  // Called when keyboard focus switches to an anchor with the given URL.
  void SetKeyboardFocusURL(const KURL&);

  // Asks the browser process to activate this web view.
  void Focus();

  // Asks the browser process to take focus away from the WebView by focusing an
  // adjacent UI element in the containing window.
  void TakeFocus(bool reverse);

  // Shows a previously created WebView (via window.open()).
  void Show(const LocalFrameToken& opener_frame_token,
            NavigationPolicy policy,
            const gfx::Rect& requested_rect,
            const gfx::Rect& adjusted_rect,
            bool opened_by_user_gesture);

  // Send the window rect to the browser and call `ack_callback` when the
  // browser has processed it.
  void SendWindowRectToMainFrameHost(const gfx::Rect& bounds,
                                     base::OnceClosure ack_callback);

  // Tells the browser that another page has accessed the DOM of the initial
  // empty document of a main frame.
  void DidAccessInitialMainDocument();

  // TODO(crbug.com/1149992): This is called from the associated widget and this
  // code should eventually move out of WebView into somewhere else.
  void ApplyViewportChanges(const ApplyViewportChangesArgs& args);

  // Indication that the root layer for the main frame widget has changed.
  void DidChangeRootLayer(bool root_layer_exists);

  // Sets the page focus.
  void SetPageFocus(bool enable);

  // This method is used for testing.
  // Resizes the unscaled (page scale = 1.0) visual viewport. Normally the
  // unscaled visual viewport is the same size as the main frame. The passed
  // size becomes the size of the viewport when page scale = 1. This
  // is used to shrink the visible viewport to allow things like the ChromeOS
  // virtual keyboard to overlay over content but allow scrolling it into view.
  void ResizeVisualViewport(const gfx::Size&);

  // Called once a paint happens after the first non empty layout. In other
  // words, after the frame has painted something.
  void DidFirstVisuallyNonEmptyPaint();

 private:
  FRIEND_TEST_ALL_PREFIXES(WebFrameTest, DivScrollIntoEditableTest);
  FRIEND_TEST_ALL_PREFIXES(WebFrameTest,
                           DivScrollIntoEditablePreservePageScaleTest);
  FRIEND_TEST_ALL_PREFIXES(WebFrameTest,
                           DivScrollIntoEditableTestZoomToLegibleScaleDisabled);
  FRIEND_TEST_ALL_PREFIXES(WebFrameTest,
                           DivScrollIntoEditableTestWithDeviceScaleFactor);
  FRIEND_TEST_ALL_PREFIXES(WebViewTest, SetBaseBackgroundColorBeforeMainFrame);
  FRIEND_TEST_ALL_PREFIXES(WebViewTest, LongPressImage);
  FRIEND_TEST_ALL_PREFIXES(WebViewTest, LongPressImageAndThenLongTapImage);
  FRIEND_TEST_ALL_PREFIXES(WebViewTest, UpdateTargetURLWithInvalidURL);
  FRIEND_TEST_ALL_PREFIXES(WebViewTest, TouchDragContextMenu);

  friend class frame_test_helpers::WebViewHelper;
  friend class SimCompositor;
  friend class WebView;  // So WebView::Create can call our constructor
  friend class WTF::RefCounted<WebViewImpl>;

  void AcceptLanguagesChanged();
  void ThemeChanged();

  // Update the target url locally and tell the browser that the target URL has
  // changed. If |url| is empty, show |fallback_url|.
  void UpdateTargetURL(const WebURL& url, const WebURL& fallback_url);

  // Helper functions to send the updated target URL to the right render frame
  // in the browser process, and to handle its associated reply message.
  void SendUpdatedTargetURLToBrowser(const KURL& target_url);
  void TargetURLUpdatedInBrowser();

  void SetPageScaleFactorAndLocation(float scale,
                                     bool is_pinch_gesture_active,
                                     const gfx::PointF&);
  void PropagateZoomFactorToLocalFrameRoots(Frame*, float);

  void SetPageLifecycleStateInternal(
      mojom::blink::PageLifecycleStatePtr new_state,
      mojom::blink::PageRestoreParamsPtr page_restore_params);

  float MaximumLegiblePageScale() const;
  void RefreshPageScaleFactor();
  gfx::Size ContentsSize() const;

  void UpdateBrowserControlsConstraint(cc::BrowserControlsState constraint);
  void UpdateICBAndResizeViewport(const gfx::Size& visible_viewport_size);
  void ResizeViewWhileAnchored(cc::BrowserControlsParams params,
                               const gfx::Size& visible_viewport_size);

  void UpdateBaseBackgroundColor();
  void UpdateFontRenderingFromRendererPrefs();

  // Request the window to close from the renderer by sending the request to the
  // browser.
  void DoDeferredCloseWindowSoon();

  WebViewImpl(
      WebViewClient*,
      mojom::blink::PageVisibilityState visibility,
      bool is_prerendering,
      bool is_inside_portal,
      bool is_fenced_frame,
      bool does_composite,
      bool widgets_never_composite,
      WebViewImpl* opener,
      mojo::PendingAssociatedReceiver<mojom::blink::PageBroadcast> page_handle,
      scheduler::WebAgentGroupScheduler& agent_group_scheduler,
      const SessionStorageNamespaceId& session_storage_namespace_id,
      absl::optional<SkColor> page_base_background_color);
  ~WebViewImpl() override;

  void ConfigureAutoResizeMode();

  void DoComposite();
  void ReallocateRenderer();

  void SetDeviceEmulationTransform(const TransformationMatrix&);
  void UpdateDeviceEmulationTransform();

  // Helper function: Widens the width of |source| by the specified margins
  // while keeping it smaller than page width.
  //
  // This method can only be called if the main frame is local.
  gfx::Rect WidenRectWithinPageBounds(const gfx::Rect& source,
                                      int target_margin,
                                      int minimum_margin);

  void EnablePopupMouseWheelEventListener(WebLocalFrameImpl* local_root);
  void DisablePopupMouseWheelEventListener();

  float DeviceScaleFactor() const;

  LocalFrame* FocusedLocalFrameInWidget() const;

  // Clear focus and text input state of the page. If there was a focused
  // element, this will trigger updates to observers and send focus, selection,
  // and text input-related events.
  void RemoveFocusAndTextInputState();

  // Finds the zoom and scroll parameters for zooming into an editable element
  // with bounds |element_bounds_in_document| and caret bounds
  // |caret_bounds_in_document|. If the original element belongs to the local
  // root of MainFrameImpl(), then the bounds are exactly those of the element
  // and caret. Otherwise (when the editable element is inside an OOPIF), the
  // bounds are projection of the original element's bounds in the main frame
  // which is inside the layout area of some remote frame in this frame tree.
  void ComputeScaleAndScrollForEditableElementRects(
      const gfx::Rect& element_bounds_in_document,
      const gfx::Rect& caret_bounds_in_document,
      bool zoom_into_legible_scale,
      float& scale,
      gfx::Point& scroll,
      bool& need_animation);

  // Sends any outstanding TrackedFeaturesUpdate messages to the browser.
  void ReportActiveSchedulerTrackedFeatures();

  // Callback when this widget window has been displayed by the browser.
  // Corresponds to a Show method call.
  void DidShowCreatedWindow();

  // A value provided by the browser to state that all Widgets in this
  // WebView's frame tree will never be user-visible and thus never need to
  // produce pixels for display. This is separate from Page visibility, as
  // non-user-visible pages can still be marked visible for blink. Page
  // visibility controls blink behaviour for javascript, timers, and such to
  // inform blink it is in the foreground or background. Whereas this bit refers
  // to user-visibility and whether the tab needs to produce pixels to put on
  // the screen at some point or not.
  const bool widgets_never_composited_;

  // Can be null (e.g. unittests, shared workers, etc).
  WebViewClient* web_view_client_;
  Persistent<ChromeClient> chrome_client_;
  Persistent<Page> page_;

  // This is the size of the page that the web contents will render into. This
  // is usually, but not necessarily the same as the VisualViewport size. The
  // VisualViewport is the 'inner' viewport, and can be smaller than the size of
  // the page. This allows the browser to shrink the size of the displayed
  // contents [e.g. to accomodate a keyboard] without forcing the web page to
  // relayout. For more details, see the header for the VisualViewport class.
  gfx::Size size_;
  // If true, automatically resize the layout view around its content.
  bool should_auto_resize_ = false;
  // The lower bound on the size when auto-resizing.
  gfx::Size min_auto_size_;
  // The upper bound on the size when auto-resizing.
  gfx::Size max_auto_size_;

  // An object that can be used to manipulate m_page->settings() without linking
  // against WebCore. This is lazily allocated the first time GetWebSettings()
  // is called.
  std::unique_ptr<WebSettingsImpl> web_settings_;

  // The state of our target_url transmissions. When we receive a request to
  // send a URL to the browser, we set this to TARGET_INFLIGHT until an ACK
  // comes back - if a new request comes in before the ACK, we store the new
  // URL in pending_target_url_ and set the status to TARGET_PENDING. If an
  // ACK comes back and we are in TARGET_PENDING, we send the stored URL and
  // revert to TARGET_INFLIGHT.
  //
  // We don't need a queue of URLs to send, as only the latest is useful.
  enum {
    TARGET_NONE,
    TARGET_INFLIGHT,  // We have a request in-flight, waiting for an ACK
    TARGET_PENDING    // INFLIGHT + we have a URL waiting to be sent
  } target_url_status_ = TARGET_NONE;

  // The URL we show the user in the status bar. We use this to determine if we
  // want to send a new one (we do not need to send duplicates). It will be
  // equal to either |mouse_over_url_| or |focus_url_|, depending on which was
  // updated last.
  KURL target_url_;

  // The next target URL we want to send to the browser.
  KURL pending_target_url_;

  // The URL the user's mouse is hovering over.
  KURL mouse_over_url_;

  // The URL that has keyboard focus.
  KURL focus_url_;

  // Keeps track of the current zoom level. 0 means no zoom, positive numbers
  // mean zoom in, negative numbers mean zoom out.
  double zoom_level_ = 0.;

  const double minimum_zoom_level_;
  const double maximum_zoom_level_;

  // Additional zoom factor used to scale the content by device scale factor.
  double zoom_factor_for_device_scale_factor_ = 0.;

  // This value, when multiplied by the font scale factor, gives the maximum
  // page scale that can result from automatic zooms.
  float maximum_legible_scale_ = 1.f;

  // The scale moved to by the latest double tap zoom, if any.
  float double_tap_zoom_page_scale_factor_ = 0.f;
  // Have we sent a double-tap zoom and not yet heard back the scale?
  bool double_tap_zoom_pending_ = false;

  // Used for testing purposes.
  bool enable_fake_page_scale_animation_for_testing_ = false;
  gfx::Point fake_page_scale_animation_target_position_;
  float fake_page_scale_animation_page_scale_factor_ = 0.f;
  bool fake_page_scale_animation_use_anchor_ = false;

  float compositor_device_scale_factor_override_ = 0.f;
  TransformationMatrix device_emulation_transform_;

  // The offset of the current item in the history list.
  // The initial value is -1 since the offset should be lower than
  // |history_list_length_| to count the back/forward history list.
  int32_t history_list_offset_ = -1;

  // The RenderView's current impression of the history length.  This includes
  // any items that have committed in this process, but because of cross-process
  // navigations, the history may have some entries that were committed in other
  // processes.  We won't know about them until the next navigation in this
  // process.
  int32_t history_list_length_ = 0;

  // The popup associated with an input/select element. The popup is owned via
  // closership (self-owned-but-deleted-via-close) by RenderWidget. We also hold
  // a reference here because we can extend the lifetime of the popup while
  // handling input events in order to compare its popup client after it was
  // closed.
  scoped_refptr<WebPagePopupImpl> page_popup_;

  Persistent<DevToolsEmulator> dev_tools_emulator_;

  // Whether the user can press tab to focus links.
  bool tabs_to_links_ = false;

  // WebViews, and WebWidgets, are used to host a Page. The WidgetClient()
  // provides compositing support for the WebView.
  // In some cases, a WidgetClient() is not provided, or it informs us that
  // it won't be presenting content via a compositor.
  //
  // TODO(dcheng): All WebViewImpls should have an associated LayerTreeView,
  // but for various reasons, that's not the case... WebView plugin, printing,
  // workers, and tests don't use a compositor in their WebViews. Sometimes
  // they avoid the compositor by using a null client, and sometimes by having
  // the client return a null compositor. We should make things more consistent
  // and clear.
  const bool does_composite_;

  bool matches_heuristics_for_gpu_rasterization_ = false;

  std::unique_ptr<FullscreenController> fullscreen_controller_;

  absl::optional<SkColor> background_color_override_for_fullscreen_controller_;
  bool override_base_background_color_to_transparent_ = false;
  absl::optional<SkColor> base_background_color_override_for_inspector_;
  SkColor page_base_background_color_;  // Only applies to main frame.

  float zoom_factor_override_ = 0.f;

  gfx::Vector2dF elastic_overscroll_;

  // If true, we send IPC messages when |preferred_size_| changes.
  bool send_preferred_size_changes_ = false;

  // Whether the preferred size may have changed and |UpdatePreferredSize| needs
  // to be called.
  bool needs_preferred_size_update_ = true;

  // Cache the preferred size of the page in order to prevent sending the IPC
  // when layout() recomputes but doesn't actually change sizes.
  gfx::Size preferred_size_in_dips_;

  Persistent<EventListener> popup_mouse_wheel_event_listener_;

  web_pref::WebPreferences web_preferences_;

  blink::RendererPreferences renderer_preferences_;

  // The local root whose document has |popup_mouse_wheel_event_listener_|
  // registered.
  WeakPersistent<WebLocalFrameImpl> local_root_with_empty_mouse_wheel_listener_;

  // The WebWidget for the main frame. This is expected to be unset when the
  // WebWidget destroys itself. This will be null if the main frame is remote.
  WeakPersistent<WebFrameWidgetImpl> web_widget_;

  // We defer commits when transitioning to a new page. ChromeClientImpl calls
  // StopDeferringCommits() to release this when a new page is loaded.
  std::unique_ptr<cc::ScopedDeferMainFrameUpdate>
      scoped_defer_main_frame_update_;

  Persistent<ResizeViewportAnchor> resize_viewport_anchor_;

  // Handle to the local main frame host. Only valid when the MainFrame is
  // local. It is ok to use WTF::Unretained(this) for callbacks made on this
  // interface because the callbacks will be associated with the lifecycle
  // of this AssociatedRemote and the lifetiime of the main LocalFrame.
  mojo::AssociatedRemote<mojom::blink::LocalMainFrameHost>
      local_main_frame_host_remote_;

  // Handle to the remote main frame host. Only valid when the MainFrame is
  // remote.  It is ok to use WTF::Unretained(this) for callbacks made on this
  // interface because the callbacks will be associated with the lifecycle
  // of this AssociatedRemote and the lifetime of the main RemoteFrame.
  mojo::AssociatedRemote<mojom::blink::RemoteMainFrameHost>
      remote_main_frame_host_remote_;

  absl::optional<display::mojom::blink::ScreenOrientation>
      screen_orientation_override_;

  mojo::AssociatedReceiver<mojom::blink::PageBroadcast> receiver_;

  // These are observing changes in |renderer_preferences_|. This is used for
  // keeping WorkerFetchContext in sync.
  mojo::RemoteSet<mojom::blink::RendererPreferenceWatcher>
      renderer_preference_watchers_;

  // The SessionStorage namespace that we're assigned to has an ID, and that ID
  // is passed to us upon creation.  WebKit asks for this ID upon first use and
  // uses it whenever asking the browser process to allocate new storage areas.
  SessionStorageNamespaceId session_storage_namespace_id_;

  // All the registered observers.
  base::ObserverList<WebViewObserver> observers_;

  base::WeakPtrFactory<WebViewImpl> weak_ptr_factory_{this};
};

// WebView is always implemented by WebViewImpl, so explicitly allow the
// downcast.
template <>
struct DowncastTraits<WebViewImpl> {
  static bool AllowFrom(const WebView& web_view) { return true; }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_VIEW_IMPL_H_


text:
package org.springframework.roo.addon.requestfactory.visualize;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.addon.requestfactory.RequestFactoryCommands;
import org.springframework.roo.addon.requestfactory.annotations.visualize.RooMapMarker;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.shell.CliAvailabilityIndicator;
import org.springframework.roo.shell.CliCommand;
import org.springframework.roo.shell.CliOption;
import org.springframework.roo.shell.CommandMarker;

@Component
@Service
public class VisualizeCommands implements CommandMarker {

    private static final String MAP_MARKER_COMMAND = RequestFactoryCommands.WEB_REQUEST_FACTORY_PREFIX + " map marker";
    private static final String SETUP_MAP_COMMAND = RequestFactoryCommands.WEB_REQUEST_FACTORY_PREFIX + " gwt maps setup";

    public static final String[] TAILORED_COMMANDS = new String[] {
        MAP_MARKER_COMMAND, SETUP_MAP_COMMAND
    };

    @Reference private VisualizeOperations operations;

    @CliAvailabilityIndicator({ MAP_MARKER_COMMAND })
    public boolean isScaffoldAvailable() {
        return operations.isAnnotateCommandAvailable();
    }

    @CliAvailabilityIndicator({ SETUP_MAP_COMMAND })
    public boolean isGwtSetupAvailable() {
        return operations.isSetupCommandAvailable();
    }

    @CliCommand(value = SETUP_MAP_COMMAND, help = "Setup project for displaying maps")
    public void setupMapsGwt() {
        operations.setupMapsGwt();
    }

    @CliCommand(value = MAP_MARKER_COMMAND, help = "Creates map scaffold for the specified type")
    public void scaffoldType(@CliOption(key = "type", mandatory = false, unspecifiedDefaultValue = "*", optionContext = "update,project", help = "The type to base the created map marker scaffold on") final JavaType type,
            @CliOption(key = RooMapMarker.LAT_FIELD_ATTRIBUTE, mandatory = false, help = "Field name for marker latitude") final String lat,
            @CliOption(key = RooMapMarker.LON_FIELD_ATTRIBUTE, mandatory = false, help = "Field name for marker longitude") final String lon) {
        operations.annotateNodeType(type, lat, lon);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <title>Pages - Mr Pebcac</title>
  <meta property="og:title" content="Pages" />
  <meta name="twitter:title" content="Pages" />
  <meta name="author" content="Preston Davis"/>
  <link href='https://pebcac.github.io/img/favicon.ico' rel='icon' type='image/x-icon'/>
  <meta property="og:image" content="https://pebcac.github.io/img/avatar-icon.png" />
  <meta name="twitter:image" content="https://pebcac.github.io/img/avatar-icon.png" />
  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="@username" />
  <meta name="twitter:creator" content="@username" />
  <meta property="og:url" content="https://pebcac.github.io/page/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="Mr Pebcac" />

  <meta name="generator" content="Hugo 0.37.1" />
  <link rel="canonical" href="https://pebcac.github.io/page/" />
  <link rel="alternate" href="https://pebcac.github.io/page/index.xml" type="application/rss+xml" title="Mr Pebcac">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://pebcac.github.io/css/main.css" /><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="https://pebcac.github.io/css/highlight.min.css" /><link rel="stylesheet" href="https://pebcac.github.io/css/codeblock.css" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.css" integrity="sha384-h/L2W9KefUClHWaty3SLE5F/qvc4djlyR4qY3NUV5HGQBBW7stbcfff1+I/vmsHh" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/default-skin/default-skin.min.css" integrity="sha384-iD0dNku6PYSIQLyfTOpB06F2KCZJAKLOThS5HRe8b3ibhdEQ6eKsFf/EeFxdOt5R" crossorigin="anonymous">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        Toggle navigation

      </button>
      Mr Pebcac

              Blog

              Tags

              About

      <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      <button class="pswp__button pswp__button--share" title="Share"></button>
      <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
      <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

    <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    </button>
    <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    </button>

Pages

About me

                    Why you'd want to go on a date with me

   Posted on January 1, 0001

     (Last modified on October 27, 2018)

   |
   1 minutes (53 words)

My name is Inigo Montoya. I have the following qualities:

I rock a great mustache

I’m extremely loyal to my family

What else do you need?

my history

To be honest, I’m having some trouble remembering right now, so why don’t you just watch my movie and it will answer all your questions.

              Preston Davis

           •
          2018

             •
            Mr Pebcac

          Hugo v0.37.1 powered  •  Theme by Beautiful Jekyll adapted to Beautiful Hugo


text:
package com.haulmont.chile.core.datatypes.impl;

import com.haulmont.chile.core.annotations.Ddl;
import com.haulmont.chile.core.annotations.JavaClass;
import com.haulmont.chile.core.datatypes.FormatStrings;
import org.dom4j.Element;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalQuery;
import java.util.Locale;

@JavaClass(LocalDate.class)
@Ddl("date")
@Ddl(dbms = "mssql", value = "datetime")
@Ddl(dbms = "mssql-2012", value = "datetime2")
public class LocalDateDatatype extends AbstractTemporalDatatype<LocalDate> {

    public LocalDateDatatype(Element element) {
        super(element);
    }

    @Override
    protected DateTimeFormatter getDateTimeFormatter() {
        return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
    }

    @Override
    protected DateTimeFormatter getDateTimeFormatter(FormatStrings formatStrings, Locale locale) {
        return DateTimeFormatter.ofPattern(formatStrings.getDateFormat(), locale);
    }

    @Override
    protected TemporalQuery<LocalDate> newInstance() {
        return LocalDate::from;
    }
}


text:
<?xml version="1.0"?>

<!-- ===================================================================
     This file is imported by buildwar.xml and adds a target
        doPortal
     which will be invoked by the buildwar targets.
     =================================================================== -->

<project name="bedework.portalWar" default="doPortal" >
  <target name="doPortal" >
    <!-- Add common portlet files -->

    <copy todir="${app.dest.lib}"
          file="${org.bedework.appjar.portals-bridges-common}"/>
    <copy todir="${app.dest.lib}"
          file="${org.bedework.appjar.portals-bridges-struts-1.2.7}"/>

    <!-- Use generic bedework portlet tld -->
    <copy todir="${app.dest.webinf}/tlds"
          overwrite="yes"
          failonerror="no" >
      <fileset dir="${app.root.dir}/resources/portlet" >
        <include name="*.tld"/>
      </fileset>
    </copy>

    <copy todir="${app.dest.webinf}"
          file="${org.bedework.deploy.type.dir}/portlet/struts-portlet-config.xml"
          overwrite="yes"
          failonerror="no" />

    <copy todir="${app.dest.webinf}"
          file="${org.bedework.deploy.type.dir}/portlet/portlet.xml"
          overwrite="yes"
          failonerror="no" >
      <filterset refid="property.filters" />
    </copy>

    <!-- Add the portal bridge controller def -->
    <replace file="${app.dest.webinf}/struts-config.xml">
      <replacetoken><![CDATA[<!-- portlet controller def here -->]]></replacetoken>
      <replacevalue><![CDATA[<controller pagePattern="$M$P" inputForward="true"
              processorClass="org.apache.portals.bridges.struts.PortletRequestProcessor"/>]]>
      </replacevalue>
    </replace>

   <!-- Add liferay config files -->

    <copy tofile="${app.dest.webinf}/liferay-display.xml"
          file="${org.bedework.deploy.type.dir}/portlet/liferay4-display.xml"
          overwrite="yes"
          failonerror="no" >
      <filterset refid="property.filters" />
    </copy>

    <copy tofile="${app.dest.webinf}/liferay-portlet.xml"
          file="${org.bedework.deploy.type.dir}/portlet/liferay4-portlet.xml"
          overwrite="yes"
          failonerror="no" >
      <filterset refid="property.filters" />
    </copy>

    <copy todir="${app.dest.lib}" file="${org.bedework.appjar.liferay}"/>
    <copy todir="${app.dest.lib}" file="${org.bedework.appjar.liferay.util-bridges}"/>
    <copy todir="${app.dest.lib}" file="${org.bedework.appjar.liferay.util-java}"/>

    <!-- Add the context params -->
    <replace file="${app.temp.web.xml}">
      <replacetoken><![CDATA[<!-- add context params here -->]]></replacetoken>
      <replacevalue><![CDATA[<!-- add context params here -->

  <context-param>
    <param-name>company_id</param-name>
    <param-value>@LIFERAY-COMPANY-ID@</param-value>
  </context-param>]]>
      </replacevalue>
    </replace>

    <!-- Add the portal listener -->
    <replace file="${app.temp.web.xml}">
      <replacetoken><![CDATA[<!-- add listeners here -->]]></replacetoken>
      <replacevalue><![CDATA[<!-- add listeners here -->

  <listener>
    <listener-class>
      @PORTAL-SERVLET-CONTEXT-LISTENER@
    </listener-class>
  </listener>]]>
      </replacevalue>
    </replace>

    <!-- Add the portlet servlet definition -->
    <replace file="${app.temp.web.xml}">
      <replacetoken><![CDATA[<!-- add servlet definitions here -->]]></replacetoken>
      <replacevalue><![CDATA[<!-- add servlet definitions here -->

  <!-- Servlet definition for portlet use. -->
  <servlet>
    <servlet-name>@PORTLET-NAME@</servlet-name>
    <display-name>@PORTLET-NAME@ Wrapper</display-name>
    <servlet-class>@PORTLET-SERVLET-CLASS@</servlet-class>
    <init-param>
      <param-name>portlet-class</param-name>
      <param-value>@PORTLET-CLASS@</param-value>
    </init-param>
    <init-param>
      <param-name>portlet-guid</param-name>
      <param-value>@CONTEXT-ROOT@.@PORTLET-NAME@</param-value>
    </init-param>
  </servlet>]]>
      </replacevalue>
    </replace>

    <!-- Add the portlet servlet mapping -->
    <replace file="${app.temp.web.xml}">
      <replacetoken><![CDATA[<!-- add servlet mappings here -->]]></replacetoken>
      <replacevalue><![CDATA[<!-- add servlet mappings here -->

  <servlet-mapping>
    <servlet-name>@PORTLET-NAME@</servlet-name>
    <url-pattern>/@PORTLET-NAME@/*</url-pattern>
  </servlet-mapping>]]>
      </replacevalue>
    </replace>
  </target>
</project>


text:
ruby_block "update hadoop.fs_name" do
	block do

		layer_name = node[:ttx_hbase][:opsworks][:hadoop_namenode_layer]
		layer = defined?(node[:opsworks][:layers][layer_name]) == nil ? nil : node[:opsworks][:layers][layer_name]

		if defined?(node[:opsworks][:layers]) != nil
			puts node[:opsworks][:layers].inspect
		else
			puts "no node[:opsworks][:layers]"
		end

		node.override[:ttx_hbase][:opsworks][:hadoop_fs_name_changed] = false
		instance = nil

		if layer != nil
			if layer[:instances].length != 1
			    #check if current instance belong to the layer
				if node[:opsworks][:instance][:layers].include?(layer_name)
					instance = node[:opsworks][:instance]
				end
			else
				layer[:instances].each do |key, value|
				    instance = value
					break
				end
			end

			if (instance != nil)
				new_name = "hdfs://#{instance[:private_ip]}:9000"
				if(new_name != node[:ttx_hbase][:hadoop][:_fs_name])
					node.override[:ttx_hbase][:hadoop][:_fs_name] = new_name
					Chef::Log.info("found updated namenode instance: #{instance.inspect}")
					node.override[:ttx_hbase][:opsworks][:hadoop_fs_name_changed] = true
				end
			end
		end

		if(instance == nil)
			Chef::Log.debug("will use default namenode")
		end

		Chef::Log.info( "fs_name_changed? #{node[:ttx_hbase][:opsworks][:hadoop_fs_name_changed]}, fs_name = #{node[:ttx_hbase][:hadoop][:_fs_name]}")

	end
end

ruby_block "update hbase.rootdir" do
	block do
		new_name = "#{node[:ttx_hbase][:hadoop][:_fs_name]}/hbase"
		if(new_name != node[:ttx_hbase][:hbase][:_root_dir])
			node.override[:ttx_hbase][:hbase][:_root_dir] = new_name
			node.override[:ttx_hbase][:opsworks][:hbase_rootdir_changed] = true

			Chef::Log.info("hbase rootdir changed: #{new_name}")
		else
		end

		Chef::Log.info("rootdir_changed? #{node[:ttx_hbase][:opsworks][:hbase_rootdir_changed]}, rootdir = #{node[:ttx_hbase][:hbase][:_root_dir]}")
	end
end

ruby_block "update zookeeper.quorum" do
	block do
		layer_name = node[:ttx_hbase][:opsworks][:zookeeper_layer]
		layer = defined?(node[:opsworks][:layers][layer_name]) == nil ? nil : node[:opsworks][:layers][layer_name]

		node.override[:ttx_hbase][:opsworks][:zookeeper_quorum_changed] = false

		quorum = Set.new;

		if layer != nil

			if node[:opsworks][:instance][:layers].include?(layer_name)
				quorum << node[:opsworks][:instance][:private_dns_name]
			end

			layer[:instances].each do |key, value|
				quorum << value[:private_dns_name]
			end
		end

		sorted_quorum =  quorum.to_a.sort
		if(sorted_quorum.length > 0 && sorted_quorum !=  node[:ttx_hbase][:zookeeper][:quorum].sort)
				node.override[:ttx_hbase][:zookeeper][:quorum] = sorted_quorum
				Chef::Log.info( "quorum changed: #{sorted_quorum}" )
				node.override[:ttx_hbase][:opsworks][:zookeeper_quorum_changed] = true
		end

		Chef::Log.info("zookeeper_quorum_changed? #{node[:ttx_hbase][:opsworks][:zookeeper_quorum_changed]}, quorum= #{node[:ttx_hbase][:zookeeper][:quorum]}")

	end
end


text:
package com.netflix.hollow.api.producer;

import com.netflix.hollow.core.write.HollowWriteStateEngine;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;

final class CloseableWriteState implements HollowProducer.WriteState, AutoCloseable {
    private final long version;
    private final HollowObjectMapper objectMapper;
    private final HollowProducer.ReadState priorReadState;
    private volatile boolean closed;

    CloseableWriteState(long version, HollowObjectMapper objectMapper, HollowProducer.ReadState priorReadState) {
        this.version = version;
        this.objectMapper = objectMapper;
        this.priorReadState = priorReadState;
    }

    @Override
    public int add(Object o) throws IllegalStateException {
        ensureNotClosed();

        return objectMapper.add(o);
    }

    @Override
    public HollowObjectMapper getObjectMapper() throws IllegalStateException {
        ensureNotClosed();

        return objectMapper;
    }

    @Override
    public HollowWriteStateEngine getStateEngine() throws IllegalStateException {
        ensureNotClosed();

        return objectMapper.getStateEngine();
    }

    @Override
    public long getVersion() throws IllegalStateException {
        ensureNotClosed();

        return version;
    }

    @Override
    public HollowProducer.ReadState getPriorState() throws IllegalStateException {
        ensureNotClosed();
        return priorReadState;
    }

    private void ensureNotClosed() {
        if (closed) {
            throw new IllegalStateException(
                    String.format("Write state operated on after the population stage of a cycle; version=%d",
                            version));
        }
    }

    @Override
    public void close() {
        closed = true;
    }
}


text:
package com.google.gwt.dom.client;

public class Html5DOMImplIE8 extends DOMImplIE8 {

    @Override public native Element createElement(Document doc, String tag) /*-{
        if("nav" === tag ||
           "section" === tag ||
           "article" === tag ||
           "aside" === tag ||
           "main" === tag) {
          tag = "div";
        }
        return doc.createElement(tag);
    }-*/;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Bubák, Annls mycol. 10(1): 51 (1912)

#### Original name
Stagonospora pulchra Bubák & Krieg.

### Remarks
null


text:
class wire
{
    public:
        wire(void);
        position_ptr mp_a;
        position_ptr mp_b;
        int m_segments;
        float m_diameter;
};
typedef boost::shared_ptr<wire> wire_ptr;
#endif


text:
package com.pinterest.secor.common;

import com.google.common.base.Preconditions;
import com.google.common.collect.ObjectArrays;
import java.util.Arrays;

/**
 * Components are used to construct the actual paths used by LogFilePath implementations.
 *
 * @author Mathias Söderberg (mathias@burtcorp.com)
 */
public class Components {
    private String[] mPath;
    private String[] mFilename;

    // convenience constructor
    public Components(String[] path, String topic, int generation) {
        this(ObjectArrays.concat(topic, path), new String[] { Integer.toString(generation) });
    }

    public Components(String[] path, String[] filename) {
        Preconditions.checkArgument(path != null && path.length > 0, "Path components cannot be null or empty");
        Preconditions.checkArgument(filename != null && filename.length > 0, "Filename components cannot be null or empty");
        this.mPath = path;
        this.mFilename = filename;
    }

    public String[] getPath() {
        return mPath;
    }

    public String[] getFilename() {
        return mFilename;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Components that = (Components) o;
        return Arrays.equals(mPath, that.getPath()) && Arrays.equals(mFilename, that.getFilename());
    }

    @Override
    public int hashCode() {
        int result = 0;
        result = 31 * result + Arrays.hashCode(mPath);
        result = 31 * result + Arrays.hashCode(mFilename);
        return result;
    }

    @Override
    public String toString() {
        return "Components{" + Arrays.toString(mPath) + ", " +
          Arrays.toString(mFilename) + "}";
    }
}


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

#include "components/services/storage/dom_storage/session_storage_namespace_impl.h"

#include <algorithm>
#include <memory>
#include <utility>

#include "base/bind.h"

namespace storage {

namespace {

void SessionStorageResponse(base::OnceClosure callback, bool success) {
  std::move(callback).Run();
}

}  // namespace

SessionStorageNamespaceImpl::SessionStorageNamespaceImpl(
    std::string namespace_id,
    SessionStorageDataMap::Listener* data_map_listener,
    SessionStorageAreaImpl::RegisterNewAreaMap register_new_map_callback,
    Delegate* delegate)
    : namespace_id_(std::move(namespace_id)),
      data_map_listener_(data_map_listener),
      register_new_map_callback_(std::move(register_new_map_callback)),
      delegate_(delegate) {}

SessionStorageNamespaceImpl::~SessionStorageNamespaceImpl() {
  DCHECK(child_namespaces_waiting_for_clone_call_.empty());
}

void SessionStorageNamespaceImpl::SetPendingPopulationFromParentNamespace(
    const std::string& from_namespace) {
  pending_population_from_parent_namespace_ = from_namespace;
  state_ = State::kNotPopulatedAndPendingClone;
}

void SessionStorageNamespaceImpl::AddChildNamespaceWaitingForClone(
    const std::string& namespace_id) {
  child_namespaces_waiting_for_clone_call_.insert(namespace_id);
}
bool SessionStorageNamespaceImpl::HasChildNamespacesWaitingForClone() const {
  return !child_namespaces_waiting_for_clone_call_.empty();
}
void SessionStorageNamespaceImpl::ClearChildNamespacesWaitingForClone() {
  child_namespaces_waiting_for_clone_call_.clear();
}

bool SessionStorageNamespaceImpl::HasAreaForStorageKey(
    const blink::StorageKey& storage_key) const {
  return storage_key_areas_.find(storage_key) != storage_key_areas_.end();
}

void SessionStorageNamespaceImpl::PopulateFromMetadata(
    AsyncDomStorageDatabase* database,
    SessionStorageMetadata::NamespaceEntry namespace_metadata) {
  DCHECK(!IsPopulated());
  database_ = database;
  state_ = State::kPopulated;
  pending_population_from_parent_namespace_.clear();
  namespace_entry_ = namespace_metadata;
  for (const auto& pair : namespace_entry_->second) {
    scoped_refptr<SessionStorageDataMap> data_map =
        delegate_->MaybeGetExistingDataMapForId(
            pair.second->MapNumberAsBytes());
    if (!data_map) {
      data_map = SessionStorageDataMap::CreateFromDisk(data_map_listener_,
                                                       pair.second, database_);
    }
    storage_key_areas_[pair.first] = std::make_unique<SessionStorageAreaImpl>(
        namespace_entry_, pair.first, std::move(data_map),
        register_new_map_callback_);
  }
  if (!run_after_population_.empty()) {
    for (base::OnceClosure& callback : run_after_population_)
      std::move(callback).Run();
    run_after_population_.clear();
  }
}

void SessionStorageNamespaceImpl::PopulateAsClone(
    AsyncDomStorageDatabase* database,
    SessionStorageMetadata::NamespaceEntry namespace_metadata,
    const StorageKeyAreas& areas_to_clone) {
  DCHECK(!IsPopulated());
  database_ = database;
  state_ = State::kPopulated;
  pending_population_from_parent_namespace_.clear();
  namespace_entry_ = namespace_metadata;
  std::transform(areas_to_clone.begin(), areas_to_clone.end(),
                 std::inserter(storage_key_areas_, storage_key_areas_.begin()),
                 [namespace_metadata](const auto& source) {
                   return std::make_pair(
                       source.first, source.second->Clone(namespace_metadata));
                 });
  if (!run_after_population_.empty()) {
    for (base::OnceClosure& callback : run_after_population_)
      std::move(callback).Run();
    run_after_population_.clear();
  }
}

void SessionStorageNamespaceImpl::Reset() {
  namespace_entry_ = SessionStorageMetadata::NamespaceEntry();
  database_ = nullptr;
  pending_population_from_parent_namespace_.clear();
  bind_waiting_on_population_ = false;
  run_after_population_.clear();
  state_ = State::kNotPopulated;
  child_namespaces_waiting_for_clone_call_.clear();
  storage_key_areas_.clear();
  receivers_.Clear();
}

void SessionStorageNamespaceImpl::Bind(
    mojo::PendingReceiver<blink::mojom::SessionStorageNamespace> receiver) {
  if (!IsPopulated()) {
    bind_waiting_on_population_ = true;
    run_after_population_.push_back(
        base::BindOnce(&SessionStorageNamespaceImpl::Bind,
                       base::Unretained(this), std::move(receiver)));
    return;
  }
  DCHECK(IsPopulated());
  receivers_.Add(this, std::move(receiver));
  bind_waiting_on_population_ = false;
}

void SessionStorageNamespaceImpl::PurgeUnboundAreas() {
  auto it = storage_key_areas_.begin();
  while (it != storage_key_areas_.end()) {
    if (!it->second->IsBound())
      it = storage_key_areas_.erase(it);
    else
      ++it;
  }
}

void SessionStorageNamespaceImpl::RemoveStorageKeyData(
    const blink::StorageKey& storage_key,
    base::OnceClosure callback) {
  DCHECK_NE(state_, State::kNotPopulated);
  if (!IsPopulated()) {
    run_after_population_.push_back(base::BindOnce(
        &SessionStorageNamespaceImpl::RemoveStorageKeyData,
        base::Unretained(this), storage_key, std::move(callback)));
    return;
  }
  DCHECK(IsPopulated());
  auto it = storage_key_areas_.find(storage_key);
  if (it == storage_key_areas_.end()) {
    std::move(callback).Run();
    return;
  }
  // Renderer process expects |source| to always be two newline separated
  // strings.
  it->second->DeleteAll(
      "\n", /*new_observer=*/mojo::NullRemote(),
      base::BindOnce(&SessionStorageResponse, std::move(callback)));
  it->second->NotifyObserversAllDeleted();
  it->second->data_map()->storage_area()->ScheduleImmediateCommit();
}

void SessionStorageNamespaceImpl::OpenArea(
    const blink::StorageKey& storage_key,
    mojo::PendingReceiver<blink::mojom::StorageArea> receiver) {
  if (!IsPopulated()) {
    run_after_population_.push_back(base::BindOnce(
        &SessionStorageNamespaceImpl::OpenArea, base::Unretained(this),
        storage_key, std::move(receiver)));
    return;
  }

  auto it = storage_key_areas_.find(storage_key);
  if (it == storage_key_areas_.end()) {
    // The area may have been purged due to lack of bindings, so check the
    // metadata for the map.
    scoped_refptr<SessionStorageDataMap> data_map;
    auto map_data_it = namespace_entry_->second.find(storage_key);
    if (map_data_it != namespace_entry_->second.end()) {
      // The map exists already, either on disk or being used by another
      // namespace.
      scoped_refptr<SessionStorageMetadata::MapData> map_data =
          map_data_it->second;
      data_map =
          delegate_->MaybeGetExistingDataMapForId(map_data->MapNumberAsBytes());
      if (!data_map) {
        data_map = SessionStorageDataMap::CreateFromDisk(data_map_listener_,
                                                         map_data, database_);
      }
    } else {
      // The map doesn't exist yet.
      data_map = SessionStorageDataMap::CreateEmpty(
          data_map_listener_,
          register_new_map_callback_.Run(namespace_entry_, storage_key),
          database_);
    }
    it = storage_key_areas_
             .emplace(std::make_pair(
                 storage_key,
                 std::make_unique<SessionStorageAreaImpl>(
                     namespace_entry_, storage_key, std::move(data_map),
                     register_new_map_callback_)))
             .first;
  }
  it->second->Bind(std::move(receiver));
}

void SessionStorageNamespaceImpl::Clone(const std::string& clone_to_namespace) {
  DCHECK(IsPopulated());
  child_namespaces_waiting_for_clone_call_.erase(clone_to_namespace);
  delegate_->RegisterShallowClonedNamespace(
      namespace_entry_, clone_to_namespace, storage_key_areas_);
}

void SessionStorageNamespaceImpl::CloneAllNamespacesWaitingForClone(
    AsyncDomStorageDatabase* database,
    SessionStorageMetadata* metadata,
    const std::map<std::string, std::unique_ptr<SessionStorageNamespaceImpl>>&
        namespaces_map) {
  SessionStorageNamespaceImpl* parent = this;
  // If the current state is kNotPopulatedAndPendingClone, then the children can
  // all be cloned from our parent instead of us.
  if (state() == State::kNotPopulatedAndPendingClone) {
    auto parent_it =
        namespaces_map.find(pending_population_from_parent_namespace_);
    // The parent must be in the map, because the only way to remove something
    // from the map is to call DeleteNamespace, which would have called this
    // method on the parent if there were children, and resolved our clone
    // dependency.
    DCHECK(parent_it != namespaces_map.end());
    parent = parent_it->second.get();
  }

  if (parent->state() == State::kNotPopulated) {
    // Populate the namespace to prepare for copy.
    parent->PopulateFromMetadata(
        database, metadata->GetOrCreateNamespaceEntry(parent->namespace_id_));
  }

  auto* delegate = parent->delegate_.get();
  for (const std::string& destination_namespace :
       child_namespaces_waiting_for_clone_call_) {
    if (parent->IsPopulated()) {
      delegate->RegisterShallowClonedNamespace(parent->namespace_entry(),
                                               destination_namespace,
                                               parent->storage_key_areas_);
    } else {
      parent->AddChildNamespaceWaitingForClone(destination_namespace);
      parent->run_after_population_.push_back(
          base::BindOnce(&SessionStorageNamespaceImpl::Clone,
                         base::Unretained(parent), destination_namespace));
      auto child_it = namespaces_map.find(destination_namespace);
      // The child must be in the map, as the only way to add it to
      // |child_namespaces_waiting_for_clone_call_| is to call
      // CloneNamespace, which always adds it to the map.
      DCHECK(child_it != namespaces_map.end());
      child_it->second->SetPendingPopulationFromParentNamespace(
          parent->namespace_id_);
    }
  }
  child_namespaces_waiting_for_clone_call_.clear();
}

void SessionStorageNamespaceImpl::FlushAreasForTesting() {
  for (auto& area : storage_key_areas_)
    area.second->FlushForTesting();
}

void SessionStorageNamespaceImpl::FlushStorageKeyForTesting(
    const blink::StorageKey& storage_key) {
  if (!IsPopulated())
    return;
  auto it = storage_key_areas_.find(storage_key);
  if (it == storage_key_areas_.end())
    return;
  it->second->data_map()->storage_area()->ScheduleImmediateCommit();
}

}  // namespace storage


text:
class ALIndexVirtualMatrix:public ALFloatMatrix
{
public:
    ALIndexVirtualMatrix(ALFLOAT** indexes, size_t w, size_t h, bool copy=false);
    virtual ~ALIndexVirtualMatrix();

    virtual ALFLOAT* vGetAddr(size_t y) const;
private:
    ALFLOAT** mIndexes;
    bool mOwn;
};
#endif


text:
package fr.jweb.app.mbeans;

import java.io.Serializable;
import java.sql.SQLException;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.apache.log4j.Logger;

import fr.jweb.app.entities.Product;
import fr.jweb.app.entities.Review;

/**
 * ReviewPoster ManagedBean
 * Handle the posting of a new review for a selected product
 */
@ManagedBean(name = "reviewPoster")
@ViewScoped
public class ReviewPosterMB implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(ReviewPosterMB.class);

    @ManagedProperty(value = "#{dbManager}")
    private DatabaseManagerMB dbManager;

    @ManagedProperty(value = "#{currentUser}")
    private CurrentUserMB currentUser;

    private String reviewTitle;
    private String reviewContent;
    private Boolean alreadyPosted = false;

    public Boolean getAlreadyPosted() {
		return alreadyPosted;
	}

	public void setAlreadyPosted(Boolean alreadyPosted) {
		this.alreadyPosted = alreadyPosted;
	}

	private int rating;

    public DatabaseManagerMB getDbManager() {
        return dbManager;
    }

    public void setDbManager(DatabaseManagerMB dbManager) {
        this.dbManager = dbManager;
    }

    public int getRating() {
        return rating;
    }

    public CurrentUserMB getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(CurrentUserMB currentUser) {
        this.currentUser = currentUser;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public ReviewPosterMB() {

    }

    @PostConstruct
    public void init() {
    	try {
			if (dbManager.getReviewDao().queryBuilder().where().eq("user_id", currentUser.getActualUser().getId()).query().size() > 0)
				alreadyPosted = true;
			dbManager.getConn().close();
		} catch (SQLException e) {
			logger.error("SQLException: " + e.getMessage());
			e.printStackTrace();
		}
    }

    public String getReviewTitle() {
        return reviewTitle;
    }

    public void setReviewTitle(String reviewTitle) {
        this.reviewTitle = reviewTitle;
    }

    public String getReviewContent() {
        return reviewContent;
    }

    public void setReviewContent(String reviewContent) {
        this.reviewContent = reviewContent;
    }

    /**
     * Handle the posting of a new review with the given informations
     *
     * @return redirection to the product with the new review
     */
    public String newReview(Product item) {
        try {
            Review tmp = new Review();
            tmp.setProduct(item);
            tmp.setRating(this.rating);
            tmp.setReviewContent(this.reviewContent);
            tmp.setUser(currentUser.getActualUser());
            dbManager.getReviewDao().create(tmp);
        } catch (SQLException e) {
            System.out.println("SQLException: exception caught while creating review: " + e.getMessage());
            logger.error("SQLException: exception caught while creating review: " + e.getMessage());
            e.printStackTrace();
        }
        return ("single_product?faces-redirect=true&id=" + item.getId());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<uses-sdk android:minSdkVersion="15" />
	<application android:label="SQLDemo.Android"></application>
</manifest>


text:
@implementation RDTextInputCell

@synthesize textField, delegate;

//- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
//    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
//        // Initialization code
//    }
//    return self;
//}
//
//
//- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
//
//    [super setSelected:selected animated:animated];
//
//    // Configure the view for the selected state
//}

- (BOOL) textFieldShouldReturn:(UITextField *)field
{
  if (delegate && [delegate respondsToSelector:@selector(nextFieldFromInputCell:)]) {
    [delegate performSelector:@selector(nextFieldFromInputCell:) withObject:self];
  }
  return YES;
}

- (void) textFieldDidEndEditing:(UITextField *)field
{
}

@end


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _checkTypes = require('check-types');

var _checkTypes2 = _interopRequireDefault(_checkTypes);

var _keys2 = require('fast.js/object/keys');

var _keys3 = _interopRequireDefault(_keys2);

var _try2 = require('fast.js/function/try');

var _try3 = _interopRequireDefault(_try2);

var _bind2 = require('fast.js/function/bind');

var _bind3 = _interopRequireDefault(_bind2);

var _marsdb = require('marsdb');

var _PromiseQueue = require('marsdb/dist/PromiseQueue');

var _PromiseQueue2 = _interopRequireDefault(_PromiseQueue);

var _AsyncEventEmitter2 = require('marsdb/dist/AsyncEventEmitter');

var _AsyncEventEmitter3 = _interopRequireDefault(_AsyncEventEmitter2);

var _HeartbeatManager = require('./HeartbeatManager');

var _HeartbeatManager2 = _interopRequireDefault(_HeartbeatManager);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// Internals
var HEARTBEAT_INTERVAL = 15000;
var HEARTBEAT_TIMEOUT = 15000;

/**
 * WebSocket connection wrapper, that handles incoming messages
 * and emits an appropriate events.
 * While one message is asynchronously processed, another
 * message can't be processed.
 */

var DDPConnection = function (_AsyncEventEmitter) {
  _inherits(DDPConnection, _AsyncEventEmitter);

  function DDPConnection(rawConn) {
    _classCallCheck(this, DDPConnection);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(DDPConnection).call(this));

    _this.data = {};
    _this._rawConn = rawConn;
    _this._queue = new _PromiseQueue2.default(1);
    _this._connected = false;
    _this._sessionId = null;
    _this._heartbeat = new _HeartbeatManager2.default(HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT);

    _this._heartbeat.on('timeout', (0, _bind3.default)(_this._handleHearbeatTimeout, _this));
    _this._heartbeat.on('sendPing', (0, _bind3.default)(_this.sendPing, _this));
    _this._heartbeat.on('sendPong', (0, _bind3.default)(_this.sendPong, _this));
    _this._rawConn.on('message', (0, _bind3.default)(_this._handleRawMessage, _this));
    _this._rawConn.on('close', (0, _bind3.default)(_this._handleClose, _this));
    return _this;
  }

  _createClass(DDPConnection, [{
    key: 'sendPing',
    value: function sendPing() {
      this._sendMessage({
        msg: 'ping',
        id: _marsdb.Random.default().hexString(20)
      });
    }
  }, {
    key: 'sendPong',
    value: function sendPong(id) {
      this._sendMessage({
        msg: 'pong',
        id: id
      });
    }
  }, {
    key: 'sendReady',
    value: function sendReady(idOrArr) {
      var ids = _checkTypes2.default.array(idOrArr) ? idOrArr : [idOrArr];
      this._sendMessage({
        msg: 'ready',
        subs: ids
      });
    }
  }, {
    key: 'sendNoSub',
    value: function sendNoSub(subId, error) {
      var msg = { msg: 'nosub', id: subId };
      if (error && error instanceof Error) {
        msg.error = this._getErrorMessageByObject(error);
      }
      this._sendMessage(msg);
    }
  }, {
    key: 'sendResult',
    value: function sendResult(id, result) {
      var msg = { msg: 'result', id: id };
      if (result instanceof Error) {
        msg.error = this._getErrorMessageByObject(result);
      } else {
        msg.result = result;
      }
      this._sendMessage(msg);
    }
  }, {
    key: 'sendUpdated',
    value: function sendUpdated(idOrArr) {
      var ids = _checkTypes2.default.array(idOrArr) ? idOrArr : [idOrArr];
      this._sendMessage({
        msg: 'updated',
        methods: ids
      });
    }
  }, {
    key: 'sendAdded',
    value: function sendAdded(collName, objId, fields) {
      var msg = { msg: 'added', collection: collName, id: objId };
      if (_checkTypes2.default.object(fields)) {
        msg.fields = fields;
        this._sendMessage(msg);
      }
    }
  }, {
    key: 'sendChanged',
    value: function sendChanged(collName, objId, fields, cleared) {
      var msg = { msg: 'changed', collection: collName, id: objId };
      if (_checkTypes2.default.object(fields) && (0, _keys3.default)(fields).length > 0) {
        msg.fields = fields;
      }
      if (_checkTypes2.default.assigned(cleared) && cleared.length > 0) {
        msg.cleared = _checkTypes2.default.array(cleared) ? cleared : [cleared];
      }
      if (msg.fields || msg.cleared) {
        this._sendMessage(msg);
      }
    }
  }, {
    key: 'sendRemoved',
    value: function sendRemoved(collName, objId) {
      this._sendMessage({
        msg: 'removed',
        collection: collName,
        id: objId
      });
    }
  }, {
    key: '_sendMessage',
    value: function _sendMessage(msgObj) {
      var _this2 = this;

      if (!this._closed) {
        (0, _try3.default)(function () {
          return _this2._rawConn.send(_marsdb.EJSON.stringify(msgObj));
        });
      }
    }
  }, {
    key: '_getErrorMessageByObject',
    value: function _getErrorMessageByObject(err) {
      return { error: err && err.message || 'unknown error' };
    }
  }, {
    key: '_handleClose',
    value: function _handleClose() {
      this._closed = true;
      this._heartbeat._clearTimers();
      this.emit('close');
    }
  }, {
    key: '_handleRawMessage',
    value: function _handleRawMessage(rawMsg) {
      var _this3 = this;

      return this._queue.add(function () {
        var msgObj = _marsdb.EJSON.parse(rawMsg);
        return _this3._processMessage(msgObj);
      }).then(null, function (err) {
        return _this3._handleProcessingError(err);
      });
    }
  }, {
    key: '_handleProcessingError',
    value: function _handleProcessingError(err) {
      this.emit('error', err);
      this._sendMessage({
        msg: 'error',
        reason: err && err.message || 'unknown error'
      });
    }
  }, {
    key: '_processMessage',
    value: function _processMessage(msg) {
      switch (msg.msg) {
        case 'connect':
          return this._handleConnectMessage(msg);
        case 'ping':
          return this._heartbeat.handlePing(msg);
        case 'pong':
          return this._heartbeat.handlePong(msg);
        case 'method':
        case 'sub':
        case 'unsub':
          if (!this._connected) {
            throw new Error('You are not connected yet');
          }
          return this.emitAsync('message:' + msg.msg, msg);
        default:
          throw new Error('Unknown message type ' + msg.msg);
      }
    }
  }, {
    key: '_handleHearbeatTimeout',
    value: function _handleHearbeatTimeout() {
      this._rawConn.close();
    }
  }, {
    key: '_handleConnectMessage',
    value: function _handleConnectMessage() {
      if (!this._connected) {
        this._connected = true;
        this._sessionId = _marsdb.Random.default().id();
        this._heartbeat.waitPing();
        this._sendMessage({
          msg: 'connected',
          session: this._sessionId
        });
        this.emit('connected');
      }
    }
  }]);

  return DDPConnection;
}(_AsyncEventEmitter3.default);

exports.default = DDPConnection;


text:
module.exports = plugin;

const utils = require('./utils');
const fs = require('fs');

let initial_variables = JSON.parse(fs.readFileSync(utils.files.initial_variables));
let derived_variables = JSON.parse(fs.readFileSync(utils.files.derived_variables));

function plugin() {
  return (files, metalsmith, done) => {
    setImmediate(done);

    Object.keys(files).forEach(file_path => {
      // if (file_path.startsWith('utilities')) {
      //   return;
      // }

      const {file_name, lines} = utils.getLines(files, file_path);
      let variables = {
        by_name: {},
        list: [],
        file_path,
      };

      lines.forEach(line => {
        const variable = utils.parseLine(line);

        if (variable != false) {
          const computed_data = utils.getComputedData(variable.name, variable.value, variable.type, initial_variables, derived_variables);

          if (Object.keys(computed_data).length > 0) {
            variable.computed_type = computed_data.computed_type;
            variable.computed_value = computed_data.computed_value;
          }

          variables.by_name[variable.name] = variable;
          variables.list.push(variable.name);
        }
      });

      if (variables.list.length > 0) {
        utils.writeFile(file_path, variables);
      }
    });
  };
}


text:
import Promise from 'promise-polyfill'

window.Promise = window.Promise || Promise


text:
'use strict';

const assert = require('assert');
const processNested = require('../lib/processNested');

describe('Test Convert Flatten object to Nested object', function() {
  it('With no nested data', () => {
    const data = {
        'firstname': 'John',
        'lastname': 'Doe',
        'age': 22
      },
      excerpt = { firstname: 'John', lastname: 'Doe', age: 22 },
      processed = processNested(data);

    assert.deepEqual(processed, excerpt);
  });

  it('With nested data', () => {
    const data = {
        'firstname': 'John',
        'lastname': 'Doe',
        'age': 22,
        'hobbies[0]': 'Cinema',
        'hobbies[1]': 'Bike',
        'address[line]': '78  Lynch Street',
        'address[city]': 'Milwaukee',
        'friends[0][name]': 'Jane',
        'friends[0][lastname]': 'Doe',
        'friends[1][name]': 'Joe',
        'friends[1][lastname]': 'Doe'
      },
      excerpt = {
        firstname: 'John',
        lastname: 'Doe',
        age: 22,
        hobbies: [ 'Cinema', 'Bike' ],
        address: { line: '78  Lynch Street', city: 'Milwaukee' },
        friends: [
          { name: 'Jane', lastname: 'Doe' },
          { name: 'Joe', lastname: 'Doe' }
        ]
      },
      processed = processNested(data);

    assert.deepEqual(processed, excerpt);
  });

  it('Do not allow prototype pollution', () => {
    const pollutionOb1 = JSON.parse(`{"__proto__.POLLUTED1": "FOOBAR"}`);
    const pollutionOb2 = JSON.parse(`{"constructor.prototype.POLLUTED2": "FOOBAR"}`);

    processNested(pollutionOb1);
    processNested(pollutionOb2);

    assert.equal(global.POLLUTED1, undefined);
    assert.equal(global.POLLUTED2, undefined);
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>apimgt-feature</artifactId>
        <groupId>org.wso2.carbon.apimgt</groupId>
        <version>9.4.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.apimgt.eventing.hub.feature</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Carbon - Api Management Eventing Hub Feature</name>
    <url>http://wso2.org</url>
    <description>This feature contains the bundles required for event publishing to event hub</description>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.apimgt</groupId>
            <artifactId>org.wso2.carbon.apimgt.eventing.hub</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.wso2.maven</groupId>
                <artifactId>carbon-p2-plugin</artifactId>
                <executions>
                    <execution>
                        <id>4-p2-feature-generation</id>
                        <phase>package</phase>
                        <goals>
                            <goal>p2-feature-gen</goal>
                        </goals>
                        <configuration>
                            <id>org.wso2.carbon.apimgt.eventing.hub</id>
                            <propertiesFile>../../etc/feature.properties</propertiesFile>
                            <adviceFile>
                                <properties>
                                    <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
                                    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
                                </properties>
                            </adviceFile>
                            <bundles>
                                <bundleDef>
                                    org.wso2.carbon.apimgt:org.wso2.carbon.apimgt.eventing.hub:${carbon.apimgt.version}
                                </bundleDef>
                            </bundles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
require_relative './errors_service/model'

class ErrorsService
  class << self
    def do(errorable_exception)
      errors = errorable_exception.errors.reduce([]) do |acc, message|
        acc << Model.new(status: errorable_exception.status, detail: message).to_h
      end
      { errors: errors }
    end
  end
end


text:
namespace Google.Cloud.GSuiteAddOns.V1.Snippets
{
    // [START gsuiteaddons_v1_generated_GSuiteAddOns_ListDeployments_async]
    using Google.Api.Gax;
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.GSuiteAddOns.V1;
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public sealed partial class GeneratedGSuiteAddOnsClientSnippets
    {
        /// <summary>Snippet for ListDeploymentsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task ListDeploymentsRequestObjectAsync()
        {
            // Create client
            GSuiteAddOnsClient gSuiteAddOnsClient = await GSuiteAddOnsClient.CreateAsync();
            // Initialize request argument(s)
            ListDeploymentsRequest request = new ListDeploymentsRequest
            {
                ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
            };
            // Make the request
            PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = gSuiteAddOnsClient.ListDeploymentsAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Deployment item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Deployment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Deployment> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Deployment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END gsuiteaddons_v1_generated_GSuiteAddOns_ListDeployments_async]
}


text:
[instagram-private-api](../../README.md) / [responses](../../modules/responses.md) / TagsFeedResponseSectionsItem

# Interface: TagsFeedResponseSectionsItem

[responses](../../modules/responses.md).TagsFeedResponseSectionsItem

## Table of contents

### Properties

- [explore\_item\_info](TagsFeedResponseSectionsItem.md#explore_item_info)
- [feed\_type](TagsFeedResponseSectionsItem.md#feed_type)
- [layout\_content](TagsFeedResponseSectionsItem.md#layout_content)
- [layout\_type](TagsFeedResponseSectionsItem.md#layout_type)

## Properties

### explore\_item\_info

• **explore\_item\_info**: [`TagsFeedResponseExplore_item_info`](TagsFeedResponseExplore_item_info.md)

#### Defined in

[src/responses/tags.feed.response.ts:13](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/tags.feed.response.ts#L13)

___

### feed\_type

• **feed\_type**: `string`

#### Defined in

[src/responses/tags.feed.response.ts:12](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/tags.feed.response.ts#L12)

___

### layout\_content

• **layout\_content**: [`TagsFeedResponseLayout_content`](TagsFeedResponseLayout_content.md)

#### Defined in

[src/responses/tags.feed.response.ts:11](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/tags.feed.response.ts#L11)

___

### layout\_type

• **layout\_type**: `string`

#### Defined in

[src/responses/tags.feed.response.ts:10](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/tags.feed.response.ts#L10)


text:
title: Universal Image
category: feature
authors: mburns
wiki_category: Feature
wiki_title: Features/Universal Image
wiki_revision_count: 5
wiki_last_updated: 2013-05-22
---

The actual name of your feature page should look something like: "Your feature name". Use natural language to [name the pages](How to make pages#Page_naming).

# Universal oVirt Node Image

### Summary

This feature converts the oVirt Node image into a generic image that can be customized for many different projects using [Node Plugins](Node_plugins).

### Owner

*   Name: [ Mike Burns](User:mburns)

<!-- -->

*   Email: mburns AT redhat DOT com
*   IRC: mburns

### Current status

*   Feature is complete and merged into oVirt Node 3.0.0 (pending release at End of May)
*   Last Updated: 2013-05-22

### Detailed Description

A number of requests to use oVirt Node in projects other than oVirt have been received. This feature is the conversion of oVirt Node into a generic image that can be customized for use in other projects using specialized Plugins. A separate feature for moving the logic for working with oVirt Engine into a plugin is also filed [here](Features/Node_vdsm_plugin)

### Benefit to oVirt

Making oVirt Node more generic and available to other projects widens the user base for the model that oVirt Node uses. This model will then get additional testing and use outside of the oVirt Project and thus be more stable in the long term.

### Dependencies / Related Features

*   [Node VDSM Plugin](Features/Node_vdsm_plugin)
*   Affected Packages
    -   ovirt-node
    -   ovirt-node-image
    -   New Package for the plugin

### Documentation / External references

*   Coming Soon

### Comments and Discussion

This below adds a link to the "discussion" tab associated with your page. This provides the ability to have ongoing comments or conversation without bogging down the main feature page

*   Refer to [Talk:Universal Image](Talk:Universal Image)

<Category:Feature> <Category:Template> <Category:Node>


text:
<?php

namespace LiveTest\TestRun;

use LiveTest\Connection\Session\Session;

use Base\Http\Request\Request;

use LiveTest\TestRun\Test;

/**
 * A test set contains a number of tests that will be run on a spefific uri.
 *
 * @todo this class should implement the iterator interface. (create Base\Collection\Set)
 *
 * @author Nils Langner
 */
class TestSet
{
  /**
   * The request for this test set
   * @var Request
   */
  private $request;

  /**
   * The tests
   * @var Test[]
   */
  private $tests = array ();

  public function __construct(Request $request)
  {
    $this->request = $request;
  }

  /**
   * Returns the request of this test set.
   *
   * @return Request
   */
  public function getRequest()
  {
    return $this->request;
  }

  /**
   * Add a test to this set
   *
   * @param Test $test
   */
  public function addTest(Test $test)
  {
    $this->tests[] = $test;
  }

  /**
   * Returns the number of tests
   *
   * @return int
   */
  public function getTestCount()
  {
    return count($this->tests);
  }

  /**
   * Returns a set of tests
   *
   * @return Test[]
   */
  public function getTests()
  {
    return $this->tests;
  }
}


text:
<?php
require_once './vendor/autoload.php';
use Twilio\TwiML\VoiceResponse;

$response = new VoiceResponse();
$pay = $response->pay(['paymentMethod' => 'ach-debit', 'chargeAmount' => '13.22']);
$prompt = $pay->prompt(['for' => 'bank-account-number']);
$prompt->say('Thanks for using our service. Please enter your bank account number.');
$prompt2 = $pay->prompt(['for' => 'bank-account-number', 'requireMatchingInputs' => 'true']);
$prompt2->say('Thank you. Please enter your bank account number again.');

echo $response;