text:
package com.vinitello.packet;

public class Packet {

	private final int id, length;
	private final byte[] data;
	private final boolean headless;

	public Packet(byte[] data) {
		this(-1, data.length, data, true);
	}

	public Packet(int id, byte[] data) {
		this(id, data.length, data);
	}

	public Packet(int id, int length, byte[] data) {
		this(id, length, data, false);
	}

	private Packet(int id, int length, byte[] data, boolean headless) {
		this.id = id;
		this.length = length;
		this.data = data;
		this.headless = headless;
	}

	public int getId() {
		return id;
	}

	public int getLength() {
		return length;
	}

	public byte[] getData() {
		return data;
	}

	public boolean isHeadless() {
		return headless;
	}

	@Override
	public String toString() {
		return "(id=" + id + ", length=" + length + ")";
	}

}


text:
module.exports = {
  ...require('.prisma/client/index'),
}

redpajama_set_name: RedPajamaGithub


text:
namespace views {
namespace test {

namespace {

// A View that closes the Widget and exits the current message-loop when it
// receives a mouse-release event.
class ExitLoopOnRelease : public View {
 public:
  ExitLoopOnRelease() {}
  virtual ~ExitLoopOnRelease() {}

 private:
  // Overridden from View:
  virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE {
    GetWidget()->Close();
    base::MessageLoop::current()->QuitNow();
  }

  DISALLOW_COPY_AND_ASSIGN(ExitLoopOnRelease);
};

// A view that does a capture on ui::ET_GESTURE_TAP_DOWN events.
class GestureCaptureView : public View {
 public:
  GestureCaptureView() {}
  virtual ~GestureCaptureView() {}

 private:
  // Overridden from View:
  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
    if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
      GetWidget()->SetCapture(this);
      event->StopPropagation();
    }
  }

  DISALLOW_COPY_AND_ASSIGN(GestureCaptureView);
};

// A view that always processes all mouse events.
class MouseView : public View {
 public:
  MouseView()
      : View(),
        entered_(0),
        exited_(0),
        pressed_(0) {
  }
  virtual ~MouseView() {}

  virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE {
    pressed_++;
    return true;
  }

  virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE {
    entered_++;
  }

  virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE {
    exited_++;
  }

  // Return the number of OnMouseEntered calls and reset the counter.
  int EnteredCalls() {
    int i = entered_;
    entered_ = 0;
    return i;
  }

  // Return the number of OnMouseExited calls and reset the counter.
  int ExitedCalls() {
    int i = exited_;
    exited_ = 0;
    return i;
  }

  int pressed() const { return pressed_; }

 private:
  int entered_;
  int exited_;

  int pressed_;

  DISALLOW_COPY_AND_ASSIGN(MouseView);
};

// A View that shows a different widget, sets capture on that widget, and
// initiates a nested message-loop when it receives a mouse-press event.
class NestedLoopCaptureView : public View {
 public:
  explicit NestedLoopCaptureView(Widget* widget) : widget_(widget) {}
  virtual ~NestedLoopCaptureView() {}

 private:
  // Overridden from View:
  virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE {
    // Start a nested loop.
    widget_->Show();
    widget_->SetCapture(widget_->GetContentsView());
    EXPECT_TRUE(widget_->HasCapture());

    base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
    base::MessageLoop::ScopedNestableTaskAllower allow(loop);

    base::RunLoop run_loop;
    run_loop.Run();
    return true;
  }

  Widget* widget_;

  DISALLOW_COPY_AND_ASSIGN(NestedLoopCaptureView);
};

}  // namespace

class WidgetTestInteractive : public WidgetTest {
 public:
  WidgetTestInteractive() {}
  virtual ~WidgetTestInteractive() {}

  virtual void SetUp() OVERRIDE {
    gfx::GLSurface::InitializeOneOffForTests();
    ui::RegisterPathProvider();
    base::FilePath ui_test_pak_path;
    ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
    ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
    WidgetTest::SetUp();
  }

 protected:
  static void ShowQuickMenuImmediately(
      TouchSelectionControllerImpl* controller) {
    DCHECK(controller);
    if (controller->context_menu_timer_.IsRunning()) {
      controller->context_menu_timer_.Stop();
// TODO(tapted): Enable this when porting ui/views/touchui to Mac.
#if !defined(OS_MACOSX)
      controller->ContextMenuTimerFired();
#endif
    }
  }

  static bool IsQuickMenuVisible(TouchSelectionControllerImpl* controller) {
    DCHECK(controller);
    return controller->context_menu_ && controller->context_menu_->visible();
  }
};

#if defined(OS_WIN)
// Tests whether activation and focus change works correctly in Windows.
// We test the following:-
// 1. If the active aura window is correctly set when a top level widget is
//    created.
// 2. If the active aura window in widget 1 created above, is set to NULL when
//    another top level widget is created and focused.
// 3. On focusing the native platform window for widget 1, the active aura
//    window for widget 1 should be set and that for widget 2 should reset.
// TODO(ananta): Discuss with erg on how to write this test for linux x11 aura.
TEST_F(WidgetTestInteractive, DesktopNativeWidgetAuraActivationAndFocusTest) {
  // Create widget 1 and expect the active window to be its window.
  View* contents_view1 = new View;
  contents_view1->SetFocusable(true);
  Widget widget1;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  init_params.bounds = gfx::Rect(0, 0, 200, 200);
  init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  init_params.native_widget = new DesktopNativeWidgetAura(&widget1);
  widget1.Init(init_params);
  widget1.SetContentsView(contents_view1);
  widget1.Show();
  aura::Window* root_window1= widget1.GetNativeView()->GetRootWindow();
  contents_view1->RequestFocus();

  EXPECT_TRUE(root_window1 != NULL);
  aura::client::ActivationClient* activation_client1 =
      aura::client::GetActivationClient(root_window1);
  EXPECT_TRUE(activation_client1 != NULL);
  EXPECT_EQ(activation_client1->GetActiveWindow(), widget1.GetNativeView());

  // Create widget 2 and expect the active window to be its window.
  View* contents_view2 = new View;
  Widget widget2;
  Widget::InitParams init_params2 =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  init_params2.bounds = gfx::Rect(0, 0, 200, 200);
  init_params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  init_params2.native_widget = new DesktopNativeWidgetAura(&widget2);
  widget2.Init(init_params2);
  widget2.SetContentsView(contents_view2);
  widget2.Show();
  aura::Window* root_window2 = widget2.GetNativeView()->GetRootWindow();
  contents_view2->RequestFocus();
  ::SetActiveWindow(
      root_window2->GetHost()->GetAcceleratedWidget());

  aura::client::ActivationClient* activation_client2 =
      aura::client::GetActivationClient(root_window2);
  EXPECT_TRUE(activation_client2 != NULL);
  EXPECT_EQ(activation_client2->GetActiveWindow(), widget2.GetNativeView());
  EXPECT_EQ(activation_client1->GetActiveWindow(),
            reinterpret_cast<aura::Window*>(NULL));

  // Now set focus back to widget 1 and expect the active window to be its
  // window.
  contents_view1->RequestFocus();
  ::SetActiveWindow(
      root_window1->GetHost()->GetAcceleratedWidget());
  EXPECT_EQ(activation_client2->GetActiveWindow(),
            reinterpret_cast<aura::Window*>(NULL));
  EXPECT_EQ(activation_client1->GetActiveWindow(), widget1.GetNativeView());
}
#endif  // defined(OS_WIN)

TEST_F(WidgetTestInteractive, CaptureAutoReset) {
  Widget* toplevel = CreateTopLevelFramelessPlatformWidget();
  View* container = new View;
  toplevel->SetContentsView(container);

  EXPECT_FALSE(toplevel->HasCapture());
  toplevel->SetCapture(NULL);
  EXPECT_TRUE(toplevel->HasCapture());

  // By default, mouse release removes capture.
  gfx::Point click_location(45, 15);
  ui::MouseEvent release(ui::ET_MOUSE_RELEASED, click_location, click_location,
                         ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  toplevel->OnMouseEvent(&release);
  EXPECT_FALSE(toplevel->HasCapture());

  // Now a mouse release shouldn't remove capture.
  toplevel->set_auto_release_capture(false);
  toplevel->SetCapture(NULL);
  EXPECT_TRUE(toplevel->HasCapture());
  toplevel->OnMouseEvent(&release);
  EXPECT_TRUE(toplevel->HasCapture());
  toplevel->ReleaseCapture();
  EXPECT_FALSE(toplevel->HasCapture());

  toplevel->Close();
  RunPendingMessages();
}

TEST_F(WidgetTestInteractive, ResetCaptureOnGestureEnd) {
  Widget* toplevel = CreateTopLevelFramelessPlatformWidget();
  View* container = new View;
  toplevel->SetContentsView(container);

  View* gesture = new GestureCaptureView;
  gesture->SetBounds(0, 0, 30, 30);
  container->AddChildView(gesture);

  MouseView* mouse = new MouseView;
  mouse->SetBounds(30, 0, 30, 30);
  container->AddChildView(mouse);

  toplevel->SetSize(gfx::Size(100, 100));
  toplevel->Show();

  // Start a gesture on |gesture|.
  ui::GestureEvent tap_down(15,
                            15,
                            0,
                            base::TimeDelta(),
                            ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN,
                                                    0,
                                                    0));
  ui::GestureEvent end(15,
                       15,
                       0,
                       base::TimeDelta(),
                       ui::GestureEventDetails(ui::ET_GESTURE_END, 0, 0));
  toplevel->OnGestureEvent(&tap_down);

  // Now try to click on |mouse|. Since |gesture| will have capture, |mouse|
  // will not receive the event.
  gfx::Point click_location(45, 15);

  ui::MouseEvent press(ui::ET_MOUSE_PRESSED, click_location, click_location,
                       ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  ui::MouseEvent release(ui::ET_MOUSE_RELEASED, click_location, click_location,
                         ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);

  EXPECT_TRUE(toplevel->HasCapture());

  toplevel->OnMouseEvent(&press);
  toplevel->OnMouseEvent(&release);
  EXPECT_EQ(0, mouse->pressed());

  EXPECT_FALSE(toplevel->HasCapture());

  // The end of the gesture should release the capture, and pressing on |mouse|
  // should now reach |mouse|.
  toplevel->OnGestureEvent(&end);
  toplevel->OnMouseEvent(&press);
  toplevel->OnMouseEvent(&release);
  EXPECT_EQ(1, mouse->pressed());

  toplevel->Close();
  RunPendingMessages();
}

// Checks that if a mouse-press triggers a capture on a different widget (which
// consumes the mouse-release event), then the target of the press does not have
// capture.
TEST_F(WidgetTestInteractive, DisableCaptureWidgetFromMousePress) {
  // The test creates two widgets: |first| and |second|.
  // The View in |first| makes |second| visible, sets capture on it, and starts
  // a nested loop (like a menu does). The View in |second| terminates the
  // nested loop and closes the widget.
  // The test sends a mouse-press event to |first|, and posts a task to send a
  // release event to |second|, to make sure that the release event is
  // dispatched after the nested loop starts.

  Widget* first = CreateTopLevelFramelessPlatformWidget();
  Widget* second = CreateTopLevelFramelessPlatformWidget();

  View* container = new NestedLoopCaptureView(second);
  first->SetContentsView(container);

  second->SetContentsView(new ExitLoopOnRelease());

  first->SetSize(gfx::Size(100, 100));
  first->Show();

  gfx::Point location(20, 20);
  base::MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&Widget::OnMouseEvent,
                 base::Unretained(second),
                 base::Owned(new ui::MouseEvent(ui::ET_MOUSE_RELEASED,
                                                location,
                                                location,
                                                ui::EF_LEFT_MOUSE_BUTTON,
                                                ui::EF_LEFT_MOUSE_BUTTON))));
  ui::MouseEvent press(ui::ET_MOUSE_PRESSED, location, location,
                       ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  first->OnMouseEvent(&press);
  EXPECT_FALSE(first->HasCapture());
  first->Close();
  RunPendingMessages();
}

// Tests some grab/ungrab events.
// TODO(estade): can this be enabled now that this is an interactive ui test?
TEST_F(WidgetTestInteractive, DISABLED_GrabUngrab) {
  Widget* toplevel = CreateTopLevelPlatformWidget();
  Widget* child1 = CreateChildNativeWidgetWithParent(toplevel);
  Widget* child2 = CreateChildNativeWidgetWithParent(toplevel);

  toplevel->SetBounds(gfx::Rect(0, 0, 500, 500));

  child1->SetBounds(gfx::Rect(10, 10, 300, 300));
  View* view = new MouseView();
  view->SetBounds(0, 0, 300, 300);
  child1->GetRootView()->AddChildView(view);

  child2->SetBounds(gfx::Rect(200, 10, 200, 200));
  view = new MouseView();
  view->SetBounds(0, 0, 200, 200);
  child2->GetRootView()->AddChildView(view);

  toplevel->Show();
  RunPendingMessages();

  // Click on child1
  gfx::Point p1(45, 45);
  ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1,
                         ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  toplevel->OnMouseEvent(&pressed);

  EXPECT_TRUE(toplevel->HasCapture());
  EXPECT_TRUE(child1->HasCapture());
  EXPECT_FALSE(child2->HasCapture());

  ui::MouseEvent released(ui::ET_MOUSE_RELEASED, p1, p1,
                          ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  toplevel->OnMouseEvent(&released);

  EXPECT_FALSE(toplevel->HasCapture());
  EXPECT_FALSE(child1->HasCapture());
  EXPECT_FALSE(child2->HasCapture());

  RunPendingMessages();

  // Click on child2
  gfx::Point p2(315, 45);
  ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED, p2, p2,
                          ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  toplevel->OnMouseEvent(&pressed2);
  EXPECT_TRUE(pressed2.handled());
  EXPECT_TRUE(toplevel->HasCapture());
  EXPECT_TRUE(child2->HasCapture());
  EXPECT_FALSE(child1->HasCapture());

  ui::MouseEvent released2(ui::ET_MOUSE_RELEASED, p2, p2,
                           ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  toplevel->OnMouseEvent(&released2);
  EXPECT_FALSE(toplevel->HasCapture());
  EXPECT_FALSE(child1->HasCapture());
  EXPECT_FALSE(child2->HasCapture());

  toplevel->CloseNow();
}

// Tests mouse move outside of the window into the "resize controller" and back
// will still generate an OnMouseEntered and OnMouseExited event..
TEST_F(WidgetTestInteractive, CheckResizeControllerEvents) {
  Widget* toplevel = CreateTopLevelPlatformWidget();

  toplevel->SetBounds(gfx::Rect(0, 0, 100, 100));

  MouseView* view = new MouseView();
  view->SetBounds(90, 90, 10, 10);
  toplevel->GetRootView()->AddChildView(view);

  toplevel->Show();
  RunPendingMessages();

  // Move to an outside position.
  gfx::Point p1(200, 200);
  ui::MouseEvent moved_out(ui::ET_MOUSE_MOVED, p1, p1, ui::EF_NONE,
                           ui::EF_NONE);
  toplevel->OnMouseEvent(&moved_out);
  EXPECT_EQ(0, view->EnteredCalls());
  EXPECT_EQ(0, view->ExitedCalls());

  // Move onto the active view.
  gfx::Point p2(95, 95);
  ui::MouseEvent moved_over(ui::ET_MOUSE_MOVED, p2, p2, ui::EF_NONE,
                            ui::EF_NONE);
  toplevel->OnMouseEvent(&moved_over);
  EXPECT_EQ(1, view->EnteredCalls());
  EXPECT_EQ(0, view->ExitedCalls());

  // Move onto the outer resizing border.
  gfx::Point p3(102, 95);
  ui::MouseEvent moved_resizer(ui::ET_MOUSE_MOVED, p3, p3, ui::EF_NONE,
                               ui::EF_NONE);
  toplevel->OnMouseEvent(&moved_resizer);
  EXPECT_EQ(0, view->EnteredCalls());
  EXPECT_EQ(1, view->ExitedCalls());

  // Move onto the view again.
  toplevel->OnMouseEvent(&moved_over);
  EXPECT_EQ(1, view->EnteredCalls());
  EXPECT_EQ(0, view->ExitedCalls());

  RunPendingMessages();

  toplevel->CloseNow();
}

// Test view focus restoration when a widget is deactivated and re-activated.
TEST_F(WidgetTestInteractive, ViewFocusOnWidgetActivationChanges) {
  Widget* widget1 = CreateTopLevelPlatformWidget();
  View* view1 = new View;
  view1->SetFocusable(true);
  widget1->GetContentsView()->AddChildView(view1);

  Widget* widget2 = CreateTopLevelPlatformWidget();
  View* view2a = new View;
  View* view2b = new View;
  view2a->SetFocusable(true);
  view2b->SetFocusable(true);
  widget2->GetContentsView()->AddChildView(view2a);
  widget2->GetContentsView()->AddChildView(view2b);

  widget1->Show();
  EXPECT_TRUE(widget1->IsActive());
  view1->RequestFocus();
  EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView());

  widget2->Show();
  EXPECT_TRUE(widget2->IsActive());
  EXPECT_FALSE(widget1->IsActive());
  EXPECT_EQ(NULL, widget1->GetFocusManager()->GetFocusedView());
  view2a->RequestFocus();
  EXPECT_EQ(view2a, widget2->GetFocusManager()->GetFocusedView());
  view2b->RequestFocus();
  EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView());

  widget1->Activate();
  EXPECT_TRUE(widget1->IsActive());
  EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView());
  EXPECT_FALSE(widget2->IsActive());
  EXPECT_EQ(NULL, widget2->GetFocusManager()->GetFocusedView());

  widget2->Activate();
  EXPECT_TRUE(widget2->IsActive());
  EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView());
  EXPECT_FALSE(widget1->IsActive());
  EXPECT_EQ(NULL, widget1->GetFocusManager()->GetFocusedView());

  widget1->CloseNow();
  widget2->CloseNow();
}

#if defined(OS_WIN)

// Test view focus retention when a widget's HWND is disabled and re-enabled.
TEST_F(WidgetTestInteractive, ViewFocusOnHWNDEnabledChanges) {
  Widget* widget = CreateTopLevelFramelessPlatformWidget();
  widget->SetContentsView(new View);
  for (size_t i = 0; i < 2; ++i) {
    widget->GetContentsView()->AddChildView(new View);
    widget->GetContentsView()->child_at(i)->SetFocusable(true);
  }

  widget->Show();
  const HWND hwnd = HWNDForWidget(widget);
  EXPECT_TRUE(::IsWindow(hwnd));
  EXPECT_TRUE(::IsWindowEnabled(hwnd));
  EXPECT_EQ(hwnd, ::GetActiveWindow());

  for (int i = 0; i < widget->GetContentsView()->child_count(); ++i) {
    SCOPED_TRACE(base::StringPrintf("Child view %d", i));
    View* view = widget->GetContentsView()->child_at(i);

    view->RequestFocus();
    EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView());
    EXPECT_FALSE(::EnableWindow(hwnd, FALSE));
    EXPECT_FALSE(::IsWindowEnabled(hwnd));

    // Oddly, disabling the HWND leaves it active with the focus unchanged.
    EXPECT_EQ(hwnd, ::GetActiveWindow());
    EXPECT_TRUE(widget->IsActive());
    EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView());

    EXPECT_TRUE(::EnableWindow(hwnd, TRUE));
    EXPECT_TRUE(::IsWindowEnabled(hwnd));
    EXPECT_EQ(hwnd, ::GetActiveWindow());
    EXPECT_TRUE(widget->IsActive());
    EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView());
  }

  widget->CloseNow();
}

// This class subclasses the Widget class to listen for activation change
// notifications and provides accessors to return information as to whether
// the widget is active. We need this to ensure that users of the widget
// class activate the widget only when the underlying window becomes really
// active. Previously we would activate the widget in the WM_NCACTIVATE
// message which is incorrect because APIs like FlashWindowEx flash the
// window caption by sending fake WM_NCACTIVATE messages.
class WidgetActivationTest : public Widget {
 public:
  WidgetActivationTest()
      : active_(false) {}

  virtual ~WidgetActivationTest() {}

  virtual void OnNativeWidgetActivationChanged(bool active) OVERRIDE {
    active_ = active;
  }

  bool active() const { return active_; }

 private:
  bool active_;

  DISALLOW_COPY_AND_ASSIGN(WidgetActivationTest);
};

// Tests whether the widget only becomes active when the underlying window
// is really active.
TEST_F(WidgetTestInteractive, WidgetNotActivatedOnFakeActivationMessages) {
  WidgetActivationTest widget1;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  init_params.native_widget = new DesktopNativeWidgetAura(&widget1);
  init_params.bounds = gfx::Rect(0, 0, 200, 200);
  widget1.Init(init_params);
  widget1.Show();
  EXPECT_EQ(true, widget1.active());

  WidgetActivationTest widget2;
  init_params.native_widget = new DesktopNativeWidgetAura(&widget2);
  widget2.Init(init_params);
  widget2.Show();
  EXPECT_EQ(true, widget2.active());
  EXPECT_EQ(false, widget1.active());

  HWND win32_native_window1 = HWNDForWidget(&widget1);
  EXPECT_TRUE(::IsWindow(win32_native_window1));

  ::SendMessage(win32_native_window1, WM_NCACTIVATE, 1, 0);
  EXPECT_EQ(false, widget1.active());
  EXPECT_EQ(true, widget2.active());

  ::SetActiveWindow(win32_native_window1);
  EXPECT_EQ(true, widget1.active());
  EXPECT_EQ(false, widget2.active());
}
#endif  // defined(OS_WIN)

#if !defined(OS_CHROMEOS)
// Provides functionality to create a window modal dialog.
class ModalDialogDelegate : public DialogDelegateView {
 public:
  explicit ModalDialogDelegate(ui::ModalType type) : type_(type) {}
  virtual ~ModalDialogDelegate() {}

  // WidgetDelegate overrides.
  virtual ui::ModalType GetModalType() const OVERRIDE {
    return type_;
  }

 private:
  ui::ModalType type_;

  DISALLOW_COPY_AND_ASSIGN(ModalDialogDelegate);
};

// Tests whether the focused window is set correctly when a modal window is
// created and destroyed. When it is destroyed it should focus the owner window.
TEST_F(WidgetTestInteractive, WindowModalWindowDestroyedActivationTest) {
  TestWidgetFocusChangeListener focus_listener;
  WidgetFocusManager::GetInstance()->AddFocusChangeListener(&focus_listener);
  const std::vector<NativeViewPair>& focus_changes =
      focus_listener.focus_changes();

  // Create a top level widget.
  Widget top_level_widget;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW);
  init_params.show_state = ui::SHOW_STATE_NORMAL;
  gfx::Rect initial_bounds(0, 0, 500, 500);
  init_params.bounds = initial_bounds;
  init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  init_params.native_widget =
      new PlatformDesktopNativeWidget(&top_level_widget);
  top_level_widget.Init(init_params);
  top_level_widget.Show();

  gfx::NativeView top_level_native_view = top_level_widget.GetNativeView();
  EXPECT_EQ(1u, focus_changes.size());
  EXPECT_EQ(NativeViewPair(NULL, top_level_native_view), focus_changes[0]);

  // Create a modal dialog.
  // This instance will be destroyed when the dialog is destroyed.
  ModalDialogDelegate* dialog_delegate =
      new ModalDialogDelegate(ui::MODAL_TYPE_WINDOW);

  Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
      dialog_delegate, NULL, top_level_widget.GetNativeView());
  modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200));
  modal_dialog_widget->Show();

  gfx::NativeView modal_native_view = modal_dialog_widget->GetNativeView();
  EXPECT_EQ(3u, focus_changes.size());
  EXPECT_EQ(NativeViewPair(top_level_native_view, modal_native_view),
            focus_changes[1]);
  EXPECT_EQ(NativeViewPair(top_level_native_view, modal_native_view),
            focus_changes[2]);

  modal_dialog_widget->CloseNow();

  EXPECT_EQ(5u, focus_changes.size());
  EXPECT_EQ(NativeViewPair(modal_native_view, top_level_native_view),
            focus_changes[3]);
  EXPECT_EQ(NativeViewPair(modal_native_view, top_level_native_view),
            focus_changes[4]);

  top_level_widget.CloseNow();
  WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(&focus_listener);
}

// Test that when opening a system-modal window, capture is released.
TEST_F(WidgetTestInteractive, SystemModalWindowReleasesCapture) {
  TestWidgetFocusChangeListener focus_listener;
  WidgetFocusManager::GetInstance()->AddFocusChangeListener(&focus_listener);

  // Create a top level widget.
  Widget top_level_widget;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW);
  init_params.show_state = ui::SHOW_STATE_NORMAL;
  gfx::Rect initial_bounds(0, 0, 500, 500);
  init_params.bounds = initial_bounds;
  init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  init_params.native_widget =
      new PlatformDesktopNativeWidget(&top_level_widget);
  top_level_widget.Init(init_params);
  top_level_widget.Show();

  EXPECT_EQ(top_level_widget.GetNativeView(),
            focus_listener.focus_changes().back().second);;

  EXPECT_FALSE(top_level_widget.HasCapture());
  top_level_widget.SetCapture(NULL);
  EXPECT_TRUE(top_level_widget.HasCapture());

  // Create a modal dialog.
  ModalDialogDelegate* dialog_delegate =
      new ModalDialogDelegate(ui::MODAL_TYPE_SYSTEM);

  Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
      dialog_delegate, NULL, top_level_widget.GetNativeView());
  modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200));
  modal_dialog_widget->Show();

  EXPECT_FALSE(top_level_widget.HasCapture());

  modal_dialog_widget->CloseNow();
  top_level_widget.CloseNow();
  WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(&focus_listener);
}

#endif  // !defined(OS_CHROMEOS)

TEST_F(WidgetTestInteractive, CanActivateFlagIsHonored) {
  Widget widget;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW);
  init_params.bounds = gfx::Rect(0, 0, 200, 200);
  init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  init_params.activatable = Widget::InitParams::ACTIVATABLE_NO;
#if !defined(OS_CHROMEOS)
  init_params.native_widget = new PlatformDesktopNativeWidget(&widget);
#endif  // !defined(OS_CHROMEOS)
  widget.Init(init_params);

  widget.Show();
  EXPECT_FALSE(widget.IsActive());
}

// Test that touch selection quick menu is not activated when opened.
TEST_F(WidgetTestInteractive, TouchSelectionQuickMenuIsNotActivated) {
  CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnableTouchEditing);
#if defined(OS_WIN)
  views_delegate().set_use_desktop_native_widgets(true);
#endif  // !defined(OS_WIN)

  Widget widget;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  init_params.bounds = gfx::Rect(0, 0, 200, 200);
  init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  widget.Init(init_params);

  Textfield* textfield = new Textfield;
  textfield->SetBounds(0, 0, 200, 20);
  textfield->SetText(base::ASCIIToUTF16("some text"));
  widget.GetRootView()->AddChildView(textfield);

  widget.Show();
  textfield->RequestFocus();
  textfield->SelectAll(true);
  TextfieldTestApi textfield_test_api(textfield);

  RunPendingMessages();

  ui::test::EventGenerator generator(widget.GetNativeWindow());
  generator.GestureTapAt(gfx::Point(10, 10));
  ShowQuickMenuImmediately(static_cast<TouchSelectionControllerImpl*>(
      textfield_test_api.touch_selection_controller()));

  EXPECT_TRUE(textfield->HasFocus());
  EXPECT_TRUE(widget.IsActive());
  EXPECT_TRUE(IsQuickMenuVisible(static_cast<TouchSelectionControllerImpl*>(
      textfield_test_api.touch_selection_controller())));
}

TEST_F(WidgetTestInteractive, DisableViewDoesNotActivateWidget) {
#if defined(OS_WIN)
  views_delegate().set_use_desktop_native_widgets(true);
#endif  // !defined(OS_WIN)

  // Create first widget and view, activate the widget, and focus the view.
  Widget widget1;
  Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_POPUP);
  params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params1.activatable = Widget::InitParams::ACTIVATABLE_YES;
  widget1.Init(params1);

  View* view1 = new View();
  view1->SetFocusable(true);
  widget1.GetRootView()->AddChildView(view1);

  widget1.Activate();
  EXPECT_TRUE(widget1.IsActive());

  FocusManager* focus_manager1 = widget1.GetFocusManager();
  ASSERT_TRUE(focus_manager1);
  focus_manager1->SetFocusedView(view1);
  EXPECT_EQ(view1, focus_manager1->GetFocusedView());

  // Create second widget and view, activate the widget, and focus the view.
  Widget widget2;
  Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_POPUP);
  params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params2.activatable = Widget::InitParams::ACTIVATABLE_YES;
  widget2.Init(params2);

  View* view2 = new View();
  view2->SetFocusable(true);
  widget2.GetRootView()->AddChildView(view2);

  widget2.Activate();
  EXPECT_TRUE(widget2.IsActive());
  EXPECT_FALSE(widget1.IsActive());

  FocusManager* focus_manager2 = widget2.GetFocusManager();
  ASSERT_TRUE(focus_manager2);
  focus_manager2->SetFocusedView(view2);
  EXPECT_EQ(view2, focus_manager2->GetFocusedView());

  // Disable the first view and make sure it loses focus, but its widget is not
  // activated.
  view1->SetEnabled(false);
  EXPECT_NE(view1, focus_manager1->GetFocusedView());
  EXPECT_FALSE(widget1.IsActive());
  EXPECT_TRUE(widget2.IsActive());
}

namespace {

// Used to veirfy OnMouseCaptureLost() has been invoked.
class CaptureLostTrackingWidget : public Widget {
 public:
  CaptureLostTrackingWidget() : got_capture_lost_(false) {}
  virtual ~CaptureLostTrackingWidget() {}

  bool GetAndClearGotCaptureLost() {
    bool value = got_capture_lost_;
    got_capture_lost_ = false;
    return value;
  }

  // Widget:
  virtual void OnMouseCaptureLost() OVERRIDE {
    got_capture_lost_ = true;
    Widget::OnMouseCaptureLost();
  }

 private:
  bool got_capture_lost_;

  DISALLOW_COPY_AND_ASSIGN(CaptureLostTrackingWidget);
};

}  // namespace

class WidgetCaptureTest : public ViewsTestBase {
 public:
  WidgetCaptureTest() {
  }

  virtual ~WidgetCaptureTest() {
  }

  virtual void SetUp() OVERRIDE {
    gfx::GLSurface::InitializeOneOffForTests();
    ui::RegisterPathProvider();
    base::FilePath ui_test_pak_path;
    ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
    ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
    ViewsTestBase::SetUp();
  }

  // Verifies Widget::SetCapture() results in updating native capture along with
  // invoking the right Widget function.
  void TestCapture(bool use_desktop_native_widget) {
    CaptureLostTrackingWidget widget1;
    Widget::InitParams params1 =
        CreateParams(views::Widget::InitParams::TYPE_WINDOW);
    params1.native_widget = CreateNativeWidget(use_desktop_native_widget,
                                               &widget1);
    params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    widget1.Init(params1);
    widget1.Show();

    CaptureLostTrackingWidget widget2;
    Widget::InitParams params2 =
        CreateParams(views::Widget::InitParams::TYPE_WINDOW);
    params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params2.native_widget = CreateNativeWidget(use_desktop_native_widget,
                                               &widget2);
    widget2.Init(params2);
    widget2.Show();

    // Set capture to widget2 and verity it gets it.
    widget2.SetCapture(widget2.GetRootView());
    EXPECT_FALSE(widget1.HasCapture());
    EXPECT_TRUE(widget2.HasCapture());
    EXPECT_FALSE(widget1.GetAndClearGotCaptureLost());
    EXPECT_FALSE(widget2.GetAndClearGotCaptureLost());

    // Set capture to widget1 and verify it gets it.
    widget1.SetCapture(widget1.GetRootView());
    EXPECT_TRUE(widget1.HasCapture());
    EXPECT_FALSE(widget2.HasCapture());
    EXPECT_FALSE(widget1.GetAndClearGotCaptureLost());
    EXPECT_TRUE(widget2.GetAndClearGotCaptureLost());

    // Release and verify no one has it.
    widget1.ReleaseCapture();
    EXPECT_FALSE(widget1.HasCapture());
    EXPECT_FALSE(widget2.HasCapture());
    EXPECT_TRUE(widget1.GetAndClearGotCaptureLost());
    EXPECT_FALSE(widget2.GetAndClearGotCaptureLost());
  }

  NativeWidget* CreateNativeWidget(bool create_desktop_native_widget,
                                   Widget* widget) {
#if !defined(OS_CHROMEOS)
    if (create_desktop_native_widget)
      return new PlatformDesktopNativeWidget(widget);
#endif
    return NULL;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(WidgetCaptureTest);
};

// See description in TestCapture().
TEST_F(WidgetCaptureTest, Capture) {
  TestCapture(false);
}

#if !defined(OS_CHROMEOS)
// See description in TestCapture(). Creates DesktopNativeWidget.
TEST_F(WidgetCaptureTest, CaptureDesktopNativeWidget) {
  TestCapture(true);
}
#endif

// Test that no state is set if capture fails.
TEST_F(WidgetCaptureTest, FailedCaptureRequestIsNoop) {
  Widget widget;
  Widget::InitParams params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.bounds = gfx::Rect(400, 400);
  widget.Init(params);

  MouseView* mouse_view1 = new MouseView;
  MouseView* mouse_view2 = new MouseView;
  View* contents_view = new View;
  contents_view->AddChildView(mouse_view1);
  contents_view->AddChildView(mouse_view2);
  widget.SetContentsView(contents_view);

  mouse_view1->SetBounds(0, 0, 200, 400);
  mouse_view2->SetBounds(200, 0, 200, 400);

  // Setting capture should fail because |widget| is not visible.
  widget.SetCapture(mouse_view1);
  EXPECT_FALSE(widget.HasCapture());

  widget.Show();
  ui::test::EventGenerator generator(GetContext(), widget.GetNativeWindow());
  generator.set_current_location(gfx::Point(300, 10));
  generator.PressLeftButton();

  EXPECT_FALSE(mouse_view1->pressed());
  EXPECT_TRUE(mouse_view2->pressed());
}

#if !defined(OS_CHROMEOS) && !defined(OS_WIN)
// Test that a synthetic mouse exit is sent to the widget which was handling
// mouse events when a different widget grabs capture.
// TODO(pkotwicz): Make test pass on CrOS and Windows.
TEST_F(WidgetCaptureTest, MouseExitOnCaptureGrab) {
  Widget widget1;
  Widget::InitParams params1 =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params1.native_widget = CreateNativeWidget(true, &widget1);
  params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  widget1.Init(params1);
  MouseView* mouse_view1 = new MouseView;
  widget1.SetContentsView(mouse_view1);
  widget1.Show();
  widget1.SetBounds(gfx::Rect(300, 300));

  Widget widget2;
  Widget::InitParams params2 =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params2.native_widget = CreateNativeWidget(true, &widget2);
  params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  widget2.Init(params2);
  widget2.Show();
  widget2.SetBounds(gfx::Rect(400, 0, 300, 300));

  ui::test::EventGenerator generator(widget1.GetNativeWindow());
  generator.set_current_location(gfx::Point(100, 100));
  generator.MoveMouseBy(0, 0);

  EXPECT_EQ(1, mouse_view1->EnteredCalls());
  EXPECT_EQ(0, mouse_view1->ExitedCalls());

  widget2.SetCapture(NULL);
  EXPECT_EQ(0, mouse_view1->EnteredCalls());
  // Grabbing native capture on Windows generates a ui::ET_MOUSE_EXITED event
  // in addition to the one generated by Chrome.
  EXPECT_LT(0, mouse_view1->ExitedCalls());
}
#endif  // !defined(OS_CHROMEOS)

namespace {

// Widget observer which grabs capture when the widget is activated.
class CaptureOnActivationObserver : public WidgetObserver {
 public:
  CaptureOnActivationObserver() {
  }
  virtual ~CaptureOnActivationObserver() {
  }

  // WidgetObserver:
  virtual void OnWidgetActivationChanged(Widget* widget, bool active) OVERRIDE {
    if (active)
      widget->SetCapture(NULL);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(CaptureOnActivationObserver);
};

}  // namespace

// Test that setting capture on widget activation of a non-toplevel widget
// (e.g. a bubble on Linux) succeeds.
TEST_F(WidgetCaptureTest, SetCaptureToNonToplevel) {
  Widget toplevel;
  Widget::InitParams toplevel_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  toplevel_params.native_widget = CreateNativeWidget(true, &toplevel);
  toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  toplevel.Init(toplevel_params);
  toplevel.Show();

  Widget* child = new Widget;
  Widget::InitParams child_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  child_params.parent = toplevel.GetNativeView();
  child_params.context = toplevel.GetNativeWindow();
  child->Init(child_params);

  CaptureOnActivationObserver observer;
  child->AddObserver(&observer);
  child->Show();

  EXPECT_TRUE(child->HasCapture());
}

#if defined(OS_WIN)
namespace {

// Used to verify OnMouseEvent() has been invoked.
class MouseEventTrackingWidget : public Widget {
 public:
  MouseEventTrackingWidget() : got_mouse_event_(false) {}
  virtual ~MouseEventTrackingWidget() {}

  bool GetAndClearGotMouseEvent() {
    bool value = got_mouse_event_;
    got_mouse_event_ = false;
    return value;
  }

  // Widget:
  virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
    got_mouse_event_ = true;
    Widget::OnMouseEvent(event);
  }

 private:
  bool got_mouse_event_;

  DISALLOW_COPY_AND_ASSIGN(MouseEventTrackingWidget);
};

}  // namespace

// Verifies if a mouse event is received on a widget that doesn't have capture
// on Windows that it is correctly processed by the widget that doesn't have
// capture. This behavior is not desired on OSes other than Windows.
TEST_F(WidgetCaptureTest, MouseEventDispatchedToRightWindow) {
  MouseEventTrackingWidget widget1;
  Widget::InitParams params1 =
      CreateParams(views::Widget::InitParams::TYPE_WINDOW);
  params1.native_widget = new DesktopNativeWidgetAura(&widget1);
  params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  widget1.Init(params1);
  widget1.Show();

  MouseEventTrackingWidget widget2;
  Widget::InitParams params2 =
      CreateParams(views::Widget::InitParams::TYPE_WINDOW);
  params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params2.native_widget = new DesktopNativeWidgetAura(&widget2);
  widget2.Init(params2);
  widget2.Show();

  // Set capture to widget2 and verity it gets it.
  widget2.SetCapture(widget2.GetRootView());
  EXPECT_FALSE(widget1.HasCapture());
  EXPECT_TRUE(widget2.HasCapture());

  widget1.GetAndClearGotMouseEvent();
  widget2.GetAndClearGotMouseEvent();
  // Send a mouse event to the RootWindow associated with |widget1|. Even though
  // |widget2| has capture, |widget1| should still get the event.
  ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(),
                             ui::EF_NONE, ui::EF_NONE);
  ui::EventDispatchDetails details = widget1.GetNativeWindow()->
      GetHost()->event_processor()->OnEventFromSource(&mouse_event);
  ASSERT_FALSE(details.dispatcher_destroyed);
  EXPECT_TRUE(widget1.GetAndClearGotMouseEvent());
  EXPECT_FALSE(widget2.GetAndClearGotMouseEvent());
}
#endif  // defined(OS_WIN)

}  // namespace test
}  // namespace views


text:
module Azure end
module Azure::Security end
module Azure::Security::Mgmt end
module Azure::Security::Mgmt::V2020_01_01_preview end


text:
/**
 * client index.js
 * pack-cli uses this to build the app,
 * so we export the app component and import anything
 * we need that's not explicitly imported elsewhere.
 */

import '../css/style.scss';

export { default } from './components/app.jsx';


text:
import * as React from 'react'
import * as Reflux from 'reflux'
import * as _ from 'lodash'
import * as moment from 'moment'
import userStore from '../stores/userStore'
import List from '../components/list'

let Meals = React.createClass({
	mixins: [Reflux.listenTo(userStore, 'onUserChanged', 'onUserChanged')],
	getInitialState() {
		return {
			user: undefined,
			upcomingMeals: [],
			pendingMatches: [],
		}
	},
	onUserChanged(user) {
		this.setState({user})
		this.findMeals()
	},
	findMeals() {
		if (this.state.user) {
			Parse.Cloud.run('getMealsToday', {objectID: this.state.user.id})
				.then((results) => {
					results = JSON.parse(results)
					this.setState({upcomingMeals: results})
					window.meals = results
				})
		}
	},
	render() {
		let upcomingMealElements = React.createElement(List, {
			title: 'Upcoming Meals',
			list: this.state.upcomingMeals,
			errorMessage: 'No items.',
		})

		let pendingMatchElements = React.createElement(List, {
			title: 'Pending Matches',
			list: this.state.pendingMatches,
			errorMessage: 'No items.',
		})

		return React.createElement('div', {id: 'meals'},
			upcomingMealElements,
			pendingMatchElements)
	},
})

export default Meals


text:
package eu.stratuslab.storage.disk.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;

public final class MiscUtils {

	private MiscUtils() {

	}

	public static void checkForNullEntity(Representation entity) {
		if (entity == null) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
					"post with null entity");
		}
	}

	public static String getTimestamp() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();

		return dateFormat.format(date);
	}

	public static String join(List<String> list, String conjunction) {
		StringBuilder sb = new StringBuilder();
		boolean first = true;
		for (String item : list) {
			if (first)
				first = false;
			else
				sb.append(conjunction);
			sb.append(item);
		}
		return sb.toString();
	}

	public static String sub(String pattern, String replace, String string) {
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(string);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(sb, replace);
		}
		m.appendTail(sb);
		return sb.toString();
	}

    public static void sleep(int ms) {
		try {
			Thread.currentThread();
			Thread.sleep(ms);
		} catch (InterruptedException ie) {
			// Do nothing
		}
	}
}


text:
require 'spec_helper'

describe "DataBag API operations", type: "acceptance" do
  let(:server_url) { "https://api.opscode.com/organizations/ridley" }
  let(:client_name) { "reset" }
  let(:client_key) { "/Users/reset/.chef/reset.pem" }

  let(:connection) do
    Ridley.new(
      server_url: server_url,
      client_name: client_name,
      client_key: client_key
    )
  end

  before(:all) { WebMock.allow_net_connect! }
  after(:all) { WebMock.disable_net_connect! }

  before(:each) do
    connection.data_bag.delete_all
  end

  describe "listing data bags" do
    context "when no data bags exist" do
      it "returns an empty array" do
        connection.data_bag.all.should have(0).items
      end
    end

    context "when the server has data bags" do
      before(:each) do
        connection.data_bag.create(name: "ridley-one")
        connection.data_bag.create(name: "ridley-two")
      end

      it "returns an array of data bags" do
        connection.data_bag.all.should each be_a(Ridley::DataBagResource)
      end

      it "returns all of the data bags on the server" do
        connection.data_bag.all.should have(2).items
      end
    end
  end

  describe "creating a data bag" do
    pending
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>game.logic</title>
<meta name="date" content="2015-10-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

game.logic

Classes

Level

Player

Room

SpawnPoint

StealthGame


text:
package org.kie.workbench.common.dmn.api.property.dmn;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class DescriptionTest {

    private static final String DESCRIPTION_VALUE = "DESCRIPTION_VALUE";

    @Test
    public void testCopy() {
        final Description source = new Description(DESCRIPTION_VALUE);

        final Description target = source.copy();

        assertNotNull(target);
        assertEquals(DESCRIPTION_VALUE, target.getValue());
    }
}


text:
package biospectra;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;

/**
 *
 * @author iychoi
 */
public class CommandArgumentsParser<T extends CommandArgumentsBase> {
    public boolean parse(String[] args, T cmdargs) {
        CmdLineParser parser = new CmdLineParser(cmdargs);
        CmdLineException parseException = null;
        try {
            parser.parseArgument(args);
        } catch (CmdLineException e) {
            // handling of wrong arguments
            parseException = e;
        }

        if(cmdargs.isHelp()) {
            parser.printUsage(System.err);
            return false;
        }

        if(parseException != null) {
            System.err.println(parseException.getMessage());
            parser.printUsage(System.err);
            return false;
        }

        if(!cmdargs.checkValidity()) {
            String errorMsg = cmdargs.getValidityErrorMessage();
            if(errorMsg != null) {
                System.err.println(errorMsg);
            }

            System.err.println("\n");

            parser.printUsage(System.err);
            return false;
        }

        return true;
    }
}


text:
@interface RBUtil : NSObject

+ (UIColor *)colorWithHexString:(NSString *)color;
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;

@end


text:
<?php
namespace User\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class User
{
	/**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /** @ORM\Column(type="string") */
    protected $fullName;

    /** @ORM\Column(type="string") */
    protected $username;

    /** @ORM\Column(type="string", unique=true) */
    protected $password;

    /**
     * @ORM\ManyToOne(targetEntity="Role\Entity\Role", inversedBy="users")
     * @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     */
    private $role;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set fullName
     *
     * @param string $fullName
     *
     * @return User
     */
    public function setFullName($fullName)
    {
        $this->fullName = $fullName;

        return $this;
    }

    /**
     * Get fullName
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->fullName;
    }

    /**
     * Set username
     *
     * @param string $username
     *
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Set role
     *
     * @param \Role\Entity\Role $role
     *
     * @return User
     */
    public function setRole(\Role\Entity\Role $role = null)
    {
        $this->role = $role;

        return $this;
    }

    /**
     * Get role
     *
     * @return \Role\Entity\Role
     */
    public function getRole()
    {
        return $this->role;
    }
}


text:
import { IResourceHandlerResponse, IResourceRequest } from './Declarations';

export abstract class ResourceHandler {
  abstract handle(req: IResourceRequest): IResourceHandlerResponse;
}


text:
package com.hmsoft.locationlogger.data.commands;

import com.hmsoft.locationlogger.common.Utils;

class InfoCommand extends Command {

    static final String COMMAND_NAME = "Info";

    @Override
    public String getSummary() {
        return "General application info.";
    }

    @Override
    public String getName() {
        return COMMAND_NAME;
    }

    @Override
    public void execute(String[] params, CommandContext context) {
        String info = Utils.getGeneralInfo(context.androidContext);
        sendReply(context, info);
    }
}


text:
<?php

namespace Sign;

 use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
 use Zend\ModuleManager\Feature\ConfigProviderInterface;

use Sign\Model\Sign;
use Sign\Model\SignTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

 class Module implements AutoloaderProviderInterface, ConfigProviderInterface
 {
     public function getAutoloaderConfig()
     {
         return array(
             'Zend\Loader\ClassMapAutoloader' => array(
                 __DIR__ . '/autoload_classmap.php',
             ),
             'Zend\Loader\StandardAutoloader' => array(
                 'namespaces' => array(
                     __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                 ),
             ),
         );
     }

     public function getConfig()
     {
         return include __DIR__ . '/config/module.config.php';
     }

     public function getServiceConfig()
     {
         return array(
             'factories' => array(
                 'Sign\Model\SignTable' =>  function($sm) {
                     $tableGateway = $sm->get('SignTableGateway');
                     $table = new SignTable($tableGateway);
                     return $table;
                 },
                 'SignTableGateway' => function ($sm) {
                     $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                     $resultSetPrototype = new ResultSet();
                     $resultSetPrototype->setArrayObjectPrototype(new Sign());
                     return new TableGateway('fg_users', $dbAdapter, null, $resultSetPrototype);
                 },
             ),
         );
     }

 }

 ?>


text:
Tessel application for demonstrating accel, ambient, camera, climate, servo and leds.

## Getting Started

```shell
git clone https://github.com/ghaiklor/tessel-vesnasoft-2015.git
cd tessel-vesnasoft-2015
npm install
npm start # for dev flow
npm build # for prod flow
```

## License
The MIT License (MIT)

Copyright (c) 2015 Eugene Obrezkov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
export function createSession(
  opts:  CreateSessionOpts,
  cb:    (err: Error, session: Session) => void
) {}

//------------------------------------------------------------------------------
interface CreateSessionOpts {
  url: string
  key: string
}

//------------------------------------------------------------------------------
interface Session extends events.EventEmitter {
  close()

  createAgent(
    agentInfo: AgentInfo,
    cb:        (err: Error, agent: Agent) => void
  )

  getRemoteAgents(
    cb: (err: Error, ragents: RAgent[]) => void
  )
}

// events
interface Session_event_close              { () }
interface Session_event_error              { () }
interface Session_event_ragentCreated      { (ragent: RAgent) }
interface Session_event_ragentDestroyed    { (ragent: RAgent) }

//------------------------------------------------------------------------------
interface AgentInfo {
  id:    string
  name:  string
  title: string
}

//------------------------------------------------------------------------------
interface Agent {
  info: AgentInfo

  destroy()

  emit(
    name:    string,
    message: any
  )

  receive(
    name: string,
    cb:   (message: any, reply: Reply) => void
  )
}

//------------------------------------------------------------------------------
interface Reply {
  reply(
    err:     Error,
    message: any
  )
}

//------------------------------------------------------------------------------
interface RAgent extends events.EventEmitter {
  info: AgentInfo

  send(
    name:    string,
    message: any,
    cb:      (err: Error, response: any) => void
  )

}

//------------------------------------------------------------------------------
// traditional events.Eventemitter
//------------------------------------------------------------------------------
module events { export interface EventEmitter { } }

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


text:
__author__ = 'mikemax'
import math

"""
By replacing the 1st digit of the 2-digit number *3, it turns out that six of the
nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.

By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit
number is the first example having seven primes among the ten generated numbers,
yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993.
Consequently 56003, being the first member of this family, is the smallest
prime with this property.

Find the smallest prime which, by replacing part of the number (not necessarily
adjacent digits) with the same digit, is part of an eight prime value family.

"""

def is_prime(number):
    sqrt = math.sqrt(number)
    if sqrt % 1.0 == 0.0:
        return False
    i = 2
    while i < sqrt:
        if number % i == 0:
            return False
        i += 1
    return True

def gen_replace_strs(n):
    if len(n) == 1:
        return [n[0]]
    a = ['X' + x for x in gen_replace_strs(n[1:])]
    a.extend(n[0] + x for x in gen_replace_strs(n[1:]))
    return a

def test_primes(replace_str):
    prime_count = 0
    for i in xrange(1, 10):
        prime_count += 1 if is_prime(int(replace_str.replace('X', str(i)))) else 0
    return prime_count

found = False
tested = {}
for i in xrange(10, 1000000):
    n_str = str(i)
    replace_strs = gen_replace_strs(n_str)
    for replace_str in replace_strs:
        replace_str = ''.join(replace_str)
        if replace_str not in tested:
            prime_count = test_primes(replace_str)
            if prime_count == 8:
                print replace_str.replace('X', 1)
                exit(0)
            tested[replace_str] = False


text:
import { ParametricDescription } from "./parametric_description";
/**
 * From org/apache/lucene/util/automaton/Lev1TParametricDescription.java
 * @hidden
 */
export declare class Lev1TParametricDescription extends ParametricDescription {
    constructor(w: number);
    transition(absState: number, position: number, vector: number): number;
}


text:
import os
from unittest import TestSuite
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError
from django.utils import unittest
from django.test import TestCase
from django.test.client import Client
from django.conf import settings

class Command(BaseCommand):
    help = """
    Tests the api by feeding it canned requests, and comparing the
    response from the server to a stored response.
    """
    option_list = BaseCommand.option_list + (make_option("--write-expect",
                                                         action='store_true',
                                                         dest='write_expect',
                                                         default=False,
                                                         help="Instead of testing the responses, write the responses out to the expect files."),
                                             make_option("--case",
                                                         action='store',
                                                         dest='case',
                                                         default=None,
                                                         help="Name of a case file to use."),)
    def handle(self, **options):
        unittest.TextTestRunner().run(XMLTestSuite(write_expect = options['write_expect'],
                                                   case = options['case']))

TESTDIR = os.path.join(settings.PROJECT_ROOT, 'functional-tests', 'api')
CASEDIR = os.path.join(TESTDIR, 'case')
EXPECTDIR = os.path.join(TESTDIR, 'expect')

class XMLTestCase(TestCase):
    case = None
    expect = None
    client = Client()
    maxDiff = 10000
    def __init__(self, filename, write_expect=False, *args, **kwargs):
        TestCase.__init__(self, *args, **kwargs)
        self.writing = write_expect
        self.filename = filename
        self.case = os.path.join(CASEDIR, filename)
        self.expect = os.path.join(EXPECTDIR, filename)
        self._testMethodDoc = self.case
    def runTest(self, result=None):
        with open(self.case) as casefile:
            response = self.client.post("/api/read/engineering_verification",
                                        data=casefile.read(),
                                        content_type="text/xml")
        self.assertEqual(200, response.status_code)
        if self.writing:
            with open(self.expect, 'w+') as expectfile:
                expectfile.write(response.content)
        try:
            with open(self.expect) as expectfile:
                self.assertMultiLineEqual(expectfile.read(), response.content)
        except IOError as e:
            self.assertMultiLineEqual("", response.content)

class XMLTestSuite(TestSuite):
    _files = None
    writing = False
    def __init__(self, write_expect=False, case=None, *args, **kwargs):
        unittest.TestSuite.__init__(self, *args, **kwargs)
        self.writing = write_expect
        if case is None:
            self._files = filter(lambda f: f.endswith('.xml'), os.listdir(CASEDIR))
        else:
            self._files = filter(lambda f: f == case, os.listdir(CASEDIR))
    def __iter__(self):
        return (XMLTestCase(f, write_expect=self.writing) for f in self._files)


text:
require 'pathname'
require 'tempfile'

require 'brewed'

module Brewed
  module Path

    ##
    # Expand each path to an absolute path and return only those which are
    # directories.
    #
    # @param dirs [Array<Pathname, String>]
    # @return [Array<Pathname>]
    ##
    def self.expand_dirs(*dirs)
      dirs.flatten.
          map { |dir| (dir.is_a? Pathname) ? dir : Pathname.new(dir) }.
            map { |dir| dir.expand_path }.
              select { |dir| dir.directory? }
    end

    ##
    # Search a list of paths for a specific filename.
    #
    # Returns the absolute path for the first filename found.
    #
    # @param fname [Pathname, String]
    # @param paths [Array<Pathname, String>]
    # @return [Pathname, nil]
    ##
    def self.first_in_path(fname, *paths)
      fname = (fname.is_a? Pathname) ? fname : Pathname.new(fname)
      paths.each do |p|
        fullpath = ((p.is_a? Pathname) ? p : Pathname.new(p)) + fname
        return fullpath if fullpath.file?
      end
      nil
    end

    ##
    #
    ##
    def self.next_fname_version(fname, firstver = 'AAA')
      fname    = Pathname(fname)
      fndir    = fname.dirname
      fnbase   = (fname.basename fname.extname).to_s
      fnext    = fname.extname.to_s

      ver      = nil
      filename = fname
      while filename.exists?
        ver = (ver ? ver.succ : firstver)
        filename = (fndir + (fnbase + ver)).subext fnext
      end

      filename
    end

    ##
    # Construct a "safe" filename from the provided filename.
    #
    # +fname+ can be just a filename, a full pathname or a
    # relative path.  Before generating the safe filename,
    # +safe_fname+ reduces +fname+ to just its basename without
    # a file extension.  Once this basename has been converted to
    # a "safe" version, the original directory and file extension
    # are restored.
    #
    # @param fname [String, Pathname]
    #     the full path, relative path or filename to make "safe"
    #
    # @return [Pathname]
    #     the safe result
    #
    # @example Make a "safe" filename of a class name
    #     PathUtils.safe_fname Pathname
    #     => pathname
    #
    # @example Make a "safe" filename from a path
    #     PathUtils.safe_fname '../../this is a test.bar'
    #     => '../../this_is_a_test.bar'
    ##
    def self.safe_fname(fname)
      return '_' if fname == '.'
      return '__' if fname == '..'

      newfn = Pathname.new fname.to_s
      dir = newfn.dirname
      fext = newfn.extname

      # reduce to base filename with no extension
      newfn = newfn.basename fext

      newfn = newfn.to_s.downcase
      newfn.gsub! /\s+/, '_'
      newfn.gsub! /[^-a-zA-Z0-9_.;+~]/, ''
      newfn.gsub! /_+/, '_'

      dir + (newfn + fext)
    end

    ##
    # Generate a tempory filename.
    #
    # The :for option specifies the existing filename which the temporary file is intended
    # to replace.
    #
    # @param options [Hash]
    # @option options :cleanup  [true, false]
    #    delete the file automatically upon close (default: false)
    #
    # @option options :for      [String, Pathname]
    #    the absolute filename containing the content to be replaced
    #
    # @option options :dir      [String, Pathname]  (Optional; use :for! instead)
    # @option options :basename [String, Pathname]  (Optional; use :for! instead)
    # @option options :fext     [String]            (Optional; use :for! instead)
    #
    # @option options :fname_prepend      [String]
    # @option options :fname_append       [String]
    #
    # @return [nil, Pathname]
    ##
    def self.temp_filename(options = {})
      if options[:for].is_pathname?
        dir      = Pathname.new(options[:for]).expand_path
        fext     = dir.extname
        basename = dir.basename dir.extname
        dir      = dir.dirname
      else
        dir      = options[:dir]      || Dir.tmp
        basename = options[:basename] || 'temp_filename'
        fext     = options[:fext]     || 'tmp'
      end

      missing =
        {:dir => dir, :basename => basename, :fext => fext}.each_pair.select { |opt, val| val.nil? }
      raise "missing required options: #{missing.map { |pair| pair[0].to_s }.join(', ')}" if
          missing.length > 0

      basename = basename.to_s
      basename = "#{options[:fname_prepend]}#{basename}" if options[:fname_prepend].is_str?
      basename = "#{basename}#{options[:fname_append]}"  if options[:fname_append].is_str?

      meth = (options[:cleanup] == true) ? :new : :create
      file = ::Tempfile.send meth, [basename, fext.to_s], dir.to_s

      newpath = (file.respond_to? :path) ? Pathname.new(file.path.to_s) : nil

      if options[:cleanup] == true and file.respond_to?(:close!)
        file.close!
      elsif file.respond_to? :close
        file.close
      end

      newpath
    end

    ##
    # Determine whether a given object can be used as a filesystem path.
    #
    # @note DEPRECATED!  `DataUtils` adds `is_pathname?` to `Object`.
    #
    # @param obj [String, Pathname]
    # @return [true, false]
    ##
    def self.is_pathname?(obj)
      (obj.is_str? or obj.is_a?(Pathname)) ? true : false
    end

    ##
    # Given a fully-qualified path, a relative path or just a filename,
    # return just the basename without a file extension.
    #
    # @param fname  [String, Pathname]
    # @return       [String]
    #
    # @example Basename of relative path
    #    PathUtils.just_basename '../../foo_cockles.bar'
    #    => 'foo_cockles'
    ##
    def self.just_basename(fname)
      p = Pathname(fname)
      (p.basename p.extname).to_s
    end
  end

end


text:
FROM ubuntu:14.04

MAINTAINER KiwenLau <kiwenlau@gmail.com>

WORKDIR /root

# install openssh-server, openjdk and wget
RUN apt-get update && apt-get install -y openssh-server openjdk-7-jdk wget

# install hadoop 2.7.2
RUN wget https://github.com/kiwenlau/compile-hadoop/releases/download/2.7.2/hadoop-2.7.2.tar.gz && \
    tar -xzvf hadoop-2.7.2.tar.gz && \
    mv hadoop-2.7.2 /usr/local/hadoop && \
    rm hadoop-2.7.2.tar.gz

# set environment variable
ENV JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
ENV HADOOP_HOME=/usr/local/hadoop
ENV PATH=$PATH:/usr/local/hadoop/bin:/usr/local/hadoop/sbin

# ssh without key
RUN ssh-keygen -t rsa -f ~/.ssh/id_rsa -P '' && \
    cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

RUN mkdir -p ~/hdfs/namenode && \
    mkdir -p ~/hdfs/datanode && \
    mkdir $HADOOP_HOME/logs

COPY config/* /tmp/

RUN mv /tmp/ssh_config ~/.ssh/config && \
    mv /tmp/hadoop-env.sh /usr/local/hadoop/etc/hadoop/hadoop-env.sh && \
    mv /tmp/hdfs-site.xml $HADOOP_HOME/etc/hadoop/hdfs-site.xml && \
    mv /tmp/core-site.xml $HADOOP_HOME/etc/hadoop/core-site.xml && \
    mv /tmp/mapred-site.xml $HADOOP_HOME/etc/hadoop/mapred-site.xml && \
    mv /tmp/yarn-site.xml $HADOOP_HOME/etc/hadoop/yarn-site.xml && \
    mv /tmp/slaves $HADOOP_HOME/etc/hadoop/slaves && \
    mv /tmp/start-hadoop.sh ~/start-hadoop.sh && \
    mv /tmp/run-wordcount.sh ~/run-wordcount.sh

RUN chmod +x ~/start-hadoop.sh && \
    chmod +x ~/run-wordcount.sh && \
    chmod +x $HADOOP_HOME/sbin/start-dfs.sh && \
    chmod +x $HADOOP_HOME/sbin/start-yarn.sh

# format namenode
RUN /usr/local/hadoop/bin/hdfs namenode -format

CMD [ "sh", "-c", "service ssh start; bash"]


text:
namespace content {

bool ContentUtilityClient::OnMessageReceived(const IPC::Message& message) {
  return false;
}

}  // namespace content


text:
import { Component, Renderer2 } from '@angular/core';
import { Router } from '@angular/router';
import {
  SkyTheme,
  SkyThemeMode,
  SkyThemeService,
  SkyThemeSettings,
} from '@skyux/theme';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'integration';

  constructor(
    private router: Router,
    renderer: Renderer2,
    themeService: SkyThemeService
  ) {
    themeService.init(
      document.body,
      renderer,
      new SkyThemeSettings(
        SkyTheme.presets['default'],
        SkyThemeMode.presets.light
      )
    );
  }

  public isHome(): boolean {
    return this.router.url === '/';
  }
}


text:
#ifndef CPU_H_
#define CPU_H_

/* Includes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include "common.h"

/* Public defines ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Public types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Public constants ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Public variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Public macro ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Public functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void CPU_PreInit(void);

void CPU_EnterLowPowerState(void);
void CPU_InitUserHeap(void);

void *CPU_GetUserHeapStart(void);
size_t CPU_GetUserHeapSize(void);

/* Public static inline functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

#endif /* CPU_H_ */


text:
/* -*- Mode: Java; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 * acp-java : Arcus Java Client Performance benchmark program
 * Copyright 2013-2014 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.Random;

public class simple_async_decr implements client_profile {

  public boolean do_test(client cli) {
    try {
      if (!do_simple_test(cli))
        return false;
    } catch (Exception e) {
      System.out.printf("client_profile exception. id=%d exception=%s\n",
                        cli.id, e.toString());
      if (cli.conf.print_stack_trace)
        e.printStackTrace();
    }
    return true;
  }

  public boolean do_simple_test(client cli) throws Exception {
    int by = 1;

    if (!cli.before_request())
      return false;

    String key = cli.ks.get_key();
    String val = "10000";

    // SET
    Future<Boolean> fb =
      cli.next_ac.set(key, cli.conf.client_exptime, val);
    boolean ok = fb.get(cli.conf.client_timeout, TimeUnit.MILLISECONDS);
    if (!cli.after_request(ok))
      return false;
    if (!ok)
      return true;

    // Decr 100 times.
    for (int i = 0; i < 100; i++) {
      if (!cli.before_request())
        return false;

      Future<Long> f = cli.next_ac.asyncDecr(key, by);
      Long result = f.get(cli.conf.client_timeout, TimeUnit.MILLISECONDS);
      if (result == null) {
        System.out.printf("key-value Decr failed. id=%d\n", cli.id);
      }
      if (!cli.after_request(true))
        return false;
      if (result == null)
        return true;
    }

    return true;
  }
}


text:
chrome.webRequest.onBeforeRequest.addListener(function(details) {
    chrome.test.sendMessage(details.type);
}, {
    urls: ['*://*/*webrequest_hosted_app*']
});


text:
@interface NSView (Color)

@property (nonatomic,copy) NSString *mm_backgroundColor;

@property (nonatomic,strong) NSColor  *mm_BackgroundColor;

@end


text:
package pop

import (
	"fmt"
)

// BelongsTo adds a "where" clause based on the "ID" of the
// "model" passed into it.
func (c *Connection) BelongsTo(model interface{}) *Query {
	return Q(c).BelongsTo(model)
}

// BelongsToAs adds a "where" clause based on the "ID" of the
// "model" passed into it using an alias.
func (c *Connection) BelongsToAs(model interface{}, as string) *Query {
	return Q(c).BelongsToAs(model, as)
}

// BelongsTo adds a "where" clause based on the "ID" of the
// "model" passed into it.
func (q *Query) BelongsTo(model interface{}) *Query {
	m := &Model{Value: model}
	q.Where(fmt.Sprintf("%s = ?", m.associationName()), m.ID())
	return q
}

// BelongsToAs adds a "where" clause based on the "ID" of the
// "model" passed into it, using an alias.
func (q *Query) BelongsToAs(model interface{}, as string) *Query {
	m := &Model{Value: model}
	q.Where(fmt.Sprintf("%s = ?", as), m.ID())
	return q
}

// BelongsToThrough adds a "where" clause that connects the "bt" model
// through the associated "thru" model.
func (c *Connection) BelongsToThrough(bt, thru interface{}) *Query {
	return Q(c).BelongsToThrough(bt, thru)
}

// BelongsToThrough adds a "where" clause that connects the "bt" model
// through the associated "thru" model.
func (q *Query) BelongsToThrough(bt, thru interface{}) *Query {
	q.belongsToThroughClauses = append(q.belongsToThroughClauses, belongsToThroughClause{
		BelongsTo: &Model{Value: bt},
		Through:   &Model{Value: thru},
	})
	return q
}


text:
<?php declare(strict_types=1);

namespace PHPUnit\Event;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 */
final class RuntimeException extends \RuntimeException implements Exception
{
}


text:
class GetterLazy {
  static class ValueType {
    ValueType() {
      super();
    }
  }
  private final @lombok.Getter(lazy = true) java.util.concurrent.atomic.AtomicReference<java.lang.Object> fieldName = new java.util.concurrent.atomic.AtomicReference<java.lang.Object>();
  GetterLazy() {
    super();
  }
  public @java.lang.SuppressWarnings("all") ValueType getFieldName() {
    java.lang.Object value = this.fieldName.get();
    if ((value == null))
        {
          synchronized (this.fieldName)
            {
              value = this.fieldName.get();
              if ((value == null))
                  {
                    final ValueType actualValue = new ValueType();
                    value = ((actualValue == null) ? this.fieldName : actualValue);
                    this.fieldName.set(value);
                  }
            }
        }
    return (ValueType) ((value == this.fieldName) ? null : value);
  }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
  <!--
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF 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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.sakaiproject.nakamura</groupId>
    <artifactId>base</artifactId>
    <version>1.3-SNAPSHOT</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>
  <artifactId>org.sakaiproject.nakamura.testutils</artifactId>
  <packaging>jar</packaging>
  <name>Sakai Nakamura :: Test Utilities</name>
  <description>Testing Support Utilities.</description>
  <repositories>
	   <repository>
	      <id>powermock-repo</id>
	      <url>http://powermock.googlecode.com/svn/repo/</url>
	   </repository>
  </repositories>
  <properties>
    <powermock.version>1.3.5</powermock.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.osgi.core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.osgi.compendium</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
    </dependency>
      <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
      </dependency>
    <dependency>
      <groupId>javax.jcr</groupId>
      <artifactId>jcr</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.sakaiproject.nakamura</groupId>
      <artifactId>org.sakaiproject.nakamura.utils</artifactId>
      <version>1.3-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jetty</artifactId>
      </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.commons.testing</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock.modules</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>compile</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock.api</groupId>
      <artifactId>powermock-api-easymock</artifactId>
      <version>${powermock.version}</version>
      <scope>compile</scope>
   </dependency>
   <dependency>
   	<groupId>org.apache.jackrabbit</groupId>
   	<artifactId>jackrabbit-api</artifactId>
   </dependency>
   <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <scope>compile</scope>
   </dependency>
  </dependencies>
</project>


text:
@echo off
java -Dfile.encoding=UTF-8 -jar easyjasub.jar %*


text:
package org.trustedanalytics.metricsprovider.cloudadapter;

import static java.util.Collections.singletonList;

import org.trustedanalytics.cloud.auth.HeaderAddingHttpInterceptor;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.support.InterceptingHttpAccessor;
import org.springframework.web.client.RestOperations;

import java.util.Map;

public class RestOperationsHelpers {

    private RestOperationsHelpers() {
    }

    public static <T> ResponseEntity<T> getForEntityWithToken(RestOperations restTemplate,
        String token, String url, Class<T> type, Map<String, Object> pathVars) {
        addAuthHeaderToTemplate(restTemplate, token);
        return restTemplate.getForEntity(url, type, pathVars);
    }

    public static ResponseEntity<String> getForEntityWithToken(RestOperations restTemplate,
        String token, String url) {
        addAuthHeaderToTemplate(restTemplate, token);
        return restTemplate.getForEntity(url, String.class);
    }

    public static <T> ResponseEntity<T> postForEntityWithToken(RestOperations restTemplate,
        String token, String url, Object request, Class<T> type) {
        addAuthHeaderToTemplate(restTemplate, token);
        return restTemplate.postForEntity(url, request, type);
    }

    public static <T> ResponseEntity<T> postForEntityWithToken(RestOperations restTemplate,
        String token, String url, Object request, Class<T> type, Map<String, ?> pathVars) {
        addAuthHeaderToTemplate(restTemplate, token);
        return restTemplate.postForEntity(url, request, type, pathVars);
    }

    public static void deleteWithToken(RestOperations restTemplate, String token,
        String url, Map<String, ?> pathVars) {
        addAuthHeaderToTemplate(restTemplate, token);
        restTemplate.delete(url, pathVars);
    }

    private static void addAuthHeaderToTemplate(RestOperations restTemplate, String token) {
        ClientHttpRequestInterceptor interceptor =
            new HeaderAddingHttpInterceptor("Authorization", "bearer " + token);
        ((InterceptingHttpAccessor) restTemplate).setInterceptors(singletonList(interceptor));
    }
}


text:
/***
* Inferno Engine v4 2015-2017
* Written by Tomasz "Rex Dex" Jonarski
*
* [#filter: io\system\impl #]
* [#platform: winapi #]
***/

#pragma once

#include "absolutePath.h"
#include "base/containers/include/stringBuf.h"

#include "ioFileHandle.h"

#include <Windows.h>

namespace base
{
    namespace io
    {
        namespace prv
        {
            class WinAsyncReadDispatcher;

            // WinAPI based file handle
            class WinFileHandle : public IFileHandle
            {
            public:
                WinFileHandle(HANDLE hSyncFile, HANDLE hAsyncFile, const StringBuf& origin, const Bool reader, const Bool writer, WinAsyncReadDispatcher* dispatcher);
                virtual ~WinFileHandle();

                HANDLE getSyncFileHandle() const;
                HANDLE getAsyncFileHandle() const;

                // IFileHandle implementation
                virtual const StringBuf& getOriginInfo() const override final;
                virtual const Uint64 getSize() const override final;
                virtual const Uint64 getPos() const override final;
                virtual const Bool setPos(const Uint64 newPosition) override final;

                virtual const Bool isReadingAllowed() const override final;
                virtual const Bool isWritingAllowed() const override final;

                virtual const Uint64 writeSync(const void* data, const Uint64 size) override final;
                virtual const Uint64 readSync(void* data, const Uint64 size) override final;

                virtual CAN_YIELD const Uint64 readAsync(const Uint64 offset, const Uint64 size, void* readBuffer) override final;

            protected:
                HANDLE m_hSyncFile; // always there

                mutable HANDLE m_hAsyncFile; // not created until requested
                mutable CRITICAL_SECTION m_asyncHandleLock; // prevents race on the m_hAsyncFile

                StringBuf m_origin;

                Bool m_isReader : 1;
                Bool m_isWriter : 1;

                WinAsyncReadDispatcher* m_dispatcher;
            };

        } // prv
    } // io
} // base


text:
import * as path from 'canonical-path';
import * as yargs from 'yargs';

import {checkMarkerFile, writeMarkerFile} from './packages/build_marker';
import {DependencyHost} from './packages/dependency_host';
import {DependencyResolver} from './packages/dependency_resolver';
import {EntryPointFormat} from './packages/entry_point';
import {makeEntryPointBundle} from './packages/entry_point_bundle';
import {EntryPointFinder} from './packages/entry_point_finder';
import {Transformer} from './packages/transformer';

export function mainNgcc(args: string[]): number {
  const options =
      yargs
          .option('s', {
            alias: 'source',
            describe: 'A path to the root folder to compile.',
            default: './node_modules'
          })
          .option('f', {
            alias: 'formats',
            array: true,
            describe: 'An array of formats to compile.',
            default: ['fesm2015', 'esm2015', 'fesm5', 'esm5']
          })
          .option('t', {
            alias: 'target',
            describe: 'A path to a root folder where the compiled files will be written.',
            defaultDescription: 'The `source` folder.'
          })
          .help()
          .parse(args);

  const sourcePath: string = path.resolve(options['s']);
  const formats: EntryPointFormat[] = options['f'];
  const targetPath: string = options['t'] || sourcePath;

  const transformer = new Transformer(sourcePath, targetPath);
  const host = new DependencyHost();
  const resolver = new DependencyResolver(host);
  const finder = new EntryPointFinder(resolver);

  try {
    const {entryPoints} = finder.findEntryPoints(sourcePath);
    entryPoints.forEach(entryPoint => {

      // Are we compiling the Angular core?
      const isCore = entryPoint.name === '@angular/core';

      // We transform the d.ts typings files while transforming one of the formats.
      // This variable decides with which of the available formats to do this transform.
      // It is marginally faster to process via the flat file if available.
      const dtsTransformFormat: EntryPointFormat = entryPoint.fesm2015 ? 'fesm2015' : 'esm2015';

      formats.forEach(format => {
        if (checkMarkerFile(entryPoint, format)) {
          console.warn(`Skipping ${entryPoint.name} : ${format} (already built).`);
          return;
        }

        const bundle =
            makeEntryPointBundle(entryPoint, isCore, format, format === dtsTransformFormat);
        if (bundle === null) {
          console.warn(
              `Skipping ${entryPoint.name} : ${format} (no entry point file for this format).`);
        } else {
          transformer.transform(entryPoint, isCore, bundle);
        }

        // Write the built-with-ngcc marker
        writeMarkerFile(entryPoint, format);
      });
    });
  } catch (e) {
    console.error(e.stack || e.message);
    return 1;
  }

  return 0;
}