text:
typedef winfoundtn::ITypedEventHandler<
    winapp::Core::CoreApplicationView*,
    winapp::Activation::IActivatedEventArgs*> ActivatedHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreWindow*,
    winui::Core::PointerEventArgs*> PointerEventHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreWindow*,
    winui::Core::KeyEventArgs*> KeyEventHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreDispatcher*,
    winui::Core::AcceleratorKeyEventArgs*> AcceleratorKeyEventHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreWindow*,
    winui::Core::CharacterReceivedEventArgs*> CharEventHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreWindow*,
    winui::Core::VisibilityChangedEventArgs*> VisibilityChangedHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreWindow*,
    winui::Core::WindowActivatedEventArgs*> WindowActivatedHandler;

typedef winfoundtn::ITypedEventHandler<
    winui::Core::CoreWindow*,
    winui::Core::WindowSizeChangedEventArgs*> SizeChangedHandler;

// This function is exported by chrome.exe.
typedef int (__cdecl *BreakpadExceptionHandler)(EXCEPTION_POINTERS* info);

// Global information used across the metro driver.
struct Globals {
  winapp::Activation::ApplicationExecutionState previous_state;
  winapp::Core::ICoreApplicationExit* app_exit;
  BreakpadExceptionHandler breakpad_exception_handler;
} globals;

namespace {

// TODO(robertshield): Share this with chrome_app_view.cc
void MetroExit() {
  globals.app_exit->Exit();
}

class ChromeChannelListener : public IPC::Listener {
 public:
  ChromeChannelListener(base::MessageLoop* ui_loop, ChromeAppViewAsh* app_view)
      : ui_proxy_(ui_loop->message_loop_proxy()), app_view_(app_view) {}

  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
    IPC_BEGIN_MESSAGE_MAP(ChromeChannelListener, message)
      IPC_MESSAGE_HANDLER(MetroViewerHostMsg_SetCursor, OnSetCursor)
      IPC_MESSAGE_HANDLER(MetroViewerHostMsg_DisplayFileOpen,
                          OnDisplayFileOpenDialog)
      IPC_MESSAGE_HANDLER(MetroViewerHostMsg_DisplayFileSaveAs,
                          OnDisplayFileSaveAsDialog)
      IPC_MESSAGE_HANDLER(MetroViewerHostMsg_DisplaySelectFolder,
                          OnDisplayFolderPicker)
      IPC_MESSAGE_HANDLER(MetroViewerHostMsg_SetCursorPos, OnSetCursorPos)
      IPC_MESSAGE_UNHANDLED(__debugbreak())
    IPC_END_MESSAGE_MAP()
    return true;
  }

  virtual void OnChannelError() OVERRIDE {
    DVLOG(1) << "Channel error";
    MetroExit();
  }

 private:
  void OnSetCursor(int64 cursor) {
    ui_proxy_->PostTask(FROM_HERE,
                        base::Bind(&ChromeAppViewAsh::OnSetCursor,
                                   base::Unretained(app_view_),
                                   reinterpret_cast<HCURSOR>(cursor)));
  }

  void OnDisplayFileOpenDialog(const string16& title,
                               const string16& filter,
                               const base::FilePath& default_path,
                               bool allow_multiple_files) {
    ui_proxy_->PostTask(FROM_HERE,
                        base::Bind(&ChromeAppViewAsh::OnDisplayFileOpenDialog,
                                   base::Unretained(app_view_),
                                   title,
                                   filter,
                                   default_path,
                                   allow_multiple_files));
  }

  void OnDisplayFileSaveAsDialog(
    const MetroViewerHostMsg_SaveAsDialogParams& params) {
    ui_proxy_->PostTask(
        FROM_HERE,
        base::Bind(&ChromeAppViewAsh::OnDisplayFileSaveAsDialog,
                   base::Unretained(app_view_),
                   params));
  }

  void OnDisplayFolderPicker(const string16& title) {
    ui_proxy_->PostTask(
        FROM_HERE,
        base::Bind(&ChromeAppViewAsh::OnDisplayFolderPicker,
                   base::Unretained(app_view_),
                   title));
  }

  void OnSetCursorPos(int x, int y) {
    VLOG(1) << "In IPC OnSetCursorPos: " << x << ", " << y;
    ui_proxy_->PostTask(
        FROM_HERE,
        base::Bind(&ChromeAppViewAsh::OnSetCursorPos,
                   base::Unretained(app_view_),
                   x, y));
  }

  scoped_refptr<base::MessageLoopProxy> ui_proxy_;
  ChromeAppViewAsh* app_view_;
};

bool WaitForChromeIPCConnection(const std::string& channel_name) {
  int ms_elapsed = 0;
  while (!IPC::Channel::IsNamedServerInitialized(channel_name) &&
         ms_elapsed < 10000) {
    ms_elapsed += 500;
    Sleep(500);
  }
  return IPC::Channel::IsNamedServerInitialized(channel_name);
}

// This class helps decoding the pointer properties of an event.
class PointerInfoHandler {
 public:
  PointerInfoHandler() :
      x_(0),
      y_(0),
      wheel_delta_(0),
      update_kind_(winui::Input::PointerUpdateKind_Other),
      timestamp_(0),
      pointer_id_(0) {}

  HRESULT Init(winui::Core::IPointerEventArgs* args) {
    HRESULT hr = args->get_CurrentPoint(&pointer_point_);
    if (FAILED(hr))
      return hr;

    winfoundtn::Point point;
    hr = pointer_point_->get_Position(&point);
    if (FAILED(hr))
      return hr;

    mswr::ComPtr<winui::Input::IPointerPointProperties> properties;
    hr = pointer_point_->get_Properties(&properties);
    if (FAILED(hr))
      return hr;

    hr = properties->get_PointerUpdateKind(&update_kind_);
    if (FAILED(hr))
      return hr;

    hr = properties->get_MouseWheelDelta(&wheel_delta_);
    if (FAILED(hr))
      return hr;
    x_ = point.X;
    y_ = point.Y;
    pointer_point_->get_Timestamp(&timestamp_);
    pointer_point_->get_PointerId(&pointer_id_);
    // Map the OS touch event id to a range allowed by the gesture recognizer.
    if (IsTouch())
      pointer_id_ %= ui::GestureSequence::kMaxGesturePoints;
    return S_OK;
  }

  bool IsType(windevs::Input::PointerDeviceType type) const {
    mswr::ComPtr<windevs::Input::IPointerDevice> pointer_device;
    CheckHR(pointer_point_->get_PointerDevice(&pointer_device));
    windevs::Input::PointerDeviceType device_type;
    CheckHR(pointer_device->get_PointerDeviceType(&device_type));
    return  (device_type == type);
  }

  bool IsMouse() const {
    return IsType(windevs::Input::PointerDeviceType_Mouse);
  }

  bool IsTouch() const {
    return IsType(windevs::Input::PointerDeviceType_Touch);
  }

  int32 wheel_delta() const {
    return wheel_delta_;
  }

  ui::EventFlags flags() {
    switch (update_kind_) {
      case winui::Input::PointerUpdateKind_LeftButtonPressed:
        return ui::EF_LEFT_MOUSE_BUTTON;
      case winui::Input::PointerUpdateKind_LeftButtonReleased:
        return ui::EF_LEFT_MOUSE_BUTTON;
      case winui::Input::PointerUpdateKind_RightButtonPressed:
        return ui::EF_RIGHT_MOUSE_BUTTON;
      case winui::Input::PointerUpdateKind_RightButtonReleased:
        return ui::EF_RIGHT_MOUSE_BUTTON;
      case winui::Input::PointerUpdateKind_MiddleButtonPressed:
        return ui::EF_MIDDLE_MOUSE_BUTTON;
      case winui::Input::PointerUpdateKind_MiddleButtonReleased:
        return ui::EF_MIDDLE_MOUSE_BUTTON;
      default:
        return ui::EF_NONE;
    };
  }

  int x() const { return x_; }
  int y() const { return y_; }

  uint32 pointer_id() const {
    return pointer_id_;
  }

  uint64 timestamp() const { return timestamp_; }

 private:
  int x_;
  int y_;
  int wheel_delta_;
  uint32 pointer_id_;
  winui::Input::PointerUpdateKind update_kind_;
  mswr::ComPtr<winui::Input::IPointerPoint> pointer_point_;
  uint64 timestamp_;
};

void RunMessageLoop(winui::Core::ICoreDispatcher* dispatcher) {
  // We're entering a nested message loop, let's allow dispatching
  // tasks while we're in there.
  base::MessageLoop::current()->SetNestableTasksAllowed(true);

  // Enter main core message loop. There are several ways to exit it
  // Nicely:
  // 1 - User action like ALT-F4.
  // 2 - Calling ICoreApplicationExit::Exit().
  // 3-  Posting WM_CLOSE to the core window.
  HRESULT hr = dispatcher->ProcessEvents(
      winui::Core::CoreProcessEventsOption
          ::CoreProcessEventsOption_ProcessUntilQuit);

  // Wind down the thread's chrome message loop.
  base::MessageLoop::current()->Quit();
}

// Helper to return the state of the shift/control/alt keys.
uint32 GetKeyboardEventFlags() {
  uint32 flags = 0;
  if (base::win::IsShiftPressed())
    flags |= ui::EF_SHIFT_DOWN;
  if (base::win::IsCtrlPressed())
    flags |= ui::EF_CONTROL_DOWN;
  if (base::win::IsAltPressed())
    flags |= ui::EF_ALT_DOWN;
  return flags;
}

}  // namespace

ChromeAppViewAsh::ChromeAppViewAsh()
    : mouse_down_flags_(ui::EF_NONE),
      ui_channel_(nullptr),
      core_window_hwnd_(NULL),
      ui_loop_(base::MessageLoop::TYPE_UI) {
  DVLOG(1) << __FUNCTION__;
  globals.previous_state =
      winapp::Activation::ApplicationExecutionState_NotRunning;
}

ChromeAppViewAsh::~ChromeAppViewAsh() {
  DVLOG(1) << __FUNCTION__;
}

IFACEMETHODIMP
ChromeAppViewAsh::Initialize(winapp::Core::ICoreApplicationView* view) {
  view_ = view;
  DVLOG(1) << __FUNCTION__;
  HRESULT hr = view_->add_Activated(mswr::Callback<ActivatedHandler>(
      this, &ChromeAppViewAsh::OnActivate).Get(),
      &activated_token_);
  CheckHR(hr);
  return hr;
}

IFACEMETHODIMP
ChromeAppViewAsh::SetWindow(winui::Core::ICoreWindow* window) {
  window_ = window;
  DVLOG(1) << __FUNCTION__;

  // Retrieve the native window handle via the interop layer.
  mswr::ComPtr<ICoreWindowInterop> interop;
  HRESULT hr = window->QueryInterface(interop.GetAddressOf());
  CheckHR(hr);
  hr = interop->get_WindowHandle(&core_window_hwnd_);
  CheckHR(hr);

  hr = window_->add_SizeChanged(mswr::Callback<SizeChangedHandler>(
      this, &ChromeAppViewAsh::OnSizeChanged).Get(),
      &sizechange_token_);
  CheckHR(hr);

  // Register for pointer and keyboard notifications. We forward
  // them to the browser process via IPC.
  hr = window_->add_PointerMoved(mswr::Callback<PointerEventHandler>(
      this, &ChromeAppViewAsh::OnPointerMoved).Get(),
      &pointermoved_token_);
  CheckHR(hr);

  hr = window_->add_PointerPressed(mswr::Callback<PointerEventHandler>(
      this, &ChromeAppViewAsh::OnPointerPressed).Get(),
      &pointerpressed_token_);
  CheckHR(hr);

  hr = window_->add_PointerReleased(mswr::Callback<PointerEventHandler>(
      this, &ChromeAppViewAsh::OnPointerReleased).Get(),
      &pointerreleased_token_);
  CheckHR(hr);

  hr = window_->add_KeyDown(mswr::Callback<KeyEventHandler>(
      this, &ChromeAppViewAsh::OnKeyDown).Get(),
      &keydown_token_);
  CheckHR(hr);

  hr = window_->add_KeyUp(mswr::Callback<KeyEventHandler>(
      this, &ChromeAppViewAsh::OnKeyUp).Get(),
      &keyup_token_);
  CheckHR(hr);

  mswr::ComPtr<winui::Core::ICoreDispatcher> dispatcher;
  hr = window_->get_Dispatcher(&dispatcher);
  CheckHR(hr, "Get Dispatcher failed.");

  mswr::ComPtr<winui::Core::ICoreAcceleratorKeys> accelerator_keys;
  hr = dispatcher.CopyTo(__uuidof(winui::Core::ICoreAcceleratorKeys),
                         reinterpret_cast<void**>(
                            accelerator_keys.GetAddressOf()));
  CheckHR(hr, "QI for ICoreAcceleratorKeys failed.");
  hr = accelerator_keys->add_AcceleratorKeyActivated(
      mswr::Callback<AcceleratorKeyEventHandler>(
          this, &ChromeAppViewAsh::OnAcceleratorKeyDown).Get(),
      &accel_keydown_token_);
  CheckHR(hr);

  hr = window_->add_PointerWheelChanged(mswr::Callback<PointerEventHandler>(
      this, &ChromeAppViewAsh::OnWheel).Get(),
      &wheel_token_);
  CheckHR(hr);

  hr = window_->add_CharacterReceived(mswr::Callback<CharEventHandler>(
      this, &ChromeAppViewAsh::OnCharacterReceived).Get(),
      &character_received_token_);
  CheckHR(hr);

  hr = window_->add_VisibilityChanged(mswr::Callback<VisibilityChangedHandler>(
      this, &ChromeAppViewAsh::OnVisibilityChanged).Get(),
      &visibility_changed_token_);
  CheckHR(hr);

  hr = window_->add_Activated(mswr::Callback<WindowActivatedHandler>(
      this, &ChromeAppViewAsh::OnWindowActivated).Get(),
      &window_activated_token_);
  CheckHR(hr);

  // By initializing the direct 3D swap chain with the corewindow
  // we can now directly blit to it from the browser process.
  direct3d_helper_.Initialize(window);
  DVLOG(1) << "Initialized Direct3D.";
  return S_OK;
}

IFACEMETHODIMP
ChromeAppViewAsh::Load(HSTRING entryPoint) {
  DVLOG(1) << __FUNCTION__;
  return S_OK;
}

IFACEMETHODIMP
ChromeAppViewAsh::Run() {
  DVLOG(1) << __FUNCTION__;
  mswr::ComPtr<winui::Core::ICoreDispatcher> dispatcher;
  HRESULT hr = window_->get_Dispatcher(&dispatcher);
  CheckHR(hr, "Dispatcher failed.");

  hr = window_->Activate();
  if (FAILED(hr)) {
    DLOG(WARNING) << "activation failed hr=" << hr;
    return hr;
  }

  // Create the IPC channel IO thread. It needs to out-live the ChannelProxy.
  base::Thread io_thread("metro_IO_thread");
  base::Thread::Options options;
  options.message_loop_type = base::MessageLoop::TYPE_IO;
  io_thread.StartWithOptions(options);

  // Start up Chrome and wait for the desired IPC server connection to exist.
  WaitForChromeIPCConnection(win8::kMetroViewerIPCChannelName);

  // In Aura mode we create an IPC channel to the browser, then ask it to
  // connect to us.
  ChromeChannelListener ui_channel_listener(&ui_loop_, this);
  IPC::ChannelProxy ui_channel(win8::kMetroViewerIPCChannelName,
                               IPC::Channel::MODE_NAMED_CLIENT,
                               &ui_channel_listener,
                               io_thread.message_loop_proxy());
  ui_channel_ = &ui_channel;

  // Upon receipt of the MetroViewerHostMsg_SetTargetSurface message the
  // browser will use D3D from the browser process to present to our Window.
  ui_channel_->Send(new MetroViewerHostMsg_SetTargetSurface(
                    gfx::NativeViewId(core_window_hwnd_)));
  DVLOG(1) << "ICoreWindow sent " << core_window_hwnd_;

  // Send an initial size message so that the Ash root window host gets sized
  // correctly.
  RECT rect = {0};
  ::GetWindowRect(core_window_hwnd_, &rect);
  ui_channel_->Send(
      new MetroViewerHostMsg_WindowSizeChanged(rect.right - rect.left,
                                               rect.bottom - rect.top));

  // And post the task that'll do the inner Metro message pumping to it.
  ui_loop_.PostTask(FROM_HERE, base::Bind(&RunMessageLoop, dispatcher.Get()));
  ui_loop_.Run();

  DVLOG(0) << "ProcessEvents done, hr=" << hr;
  return hr;
}

IFACEMETHODIMP
ChromeAppViewAsh::Uninitialize() {
  DVLOG(1) << __FUNCTION__;
  window_ = nullptr;
  view_ = nullptr;
  core_window_hwnd_ = NULL;
  return S_OK;
}

// static
HRESULT ChromeAppViewAsh::Unsnap() {
  mswr::ComPtr<winui::ViewManagement::IApplicationViewStatics> view_statics;
  HRESULT hr = winrt_utils::CreateActivationFactory(
      RuntimeClass_Windows_UI_ViewManagement_ApplicationView,
      view_statics.GetAddressOf());
  CheckHR(hr);

  winui::ViewManagement::ApplicationViewState state =
      winui::ViewManagement::ApplicationViewState_FullScreenLandscape;
  hr = view_statics->get_Value(&state);
  CheckHR(hr);

  if (state == winui::ViewManagement::ApplicationViewState_Snapped) {
    boolean success = FALSE;
    hr = view_statics->TryUnsnap(&success);

    if (FAILED(hr) || !success) {
      LOG(ERROR) << "Failed to unsnap. Error 0x" << hr;
      if (SUCCEEDED(hr))
        hr = E_UNEXPECTED;
    }
  }
  return hr;
}

void ChromeAppViewAsh::OnSetCursor(HCURSOR cursor) {
  ::SetCursor(HCURSOR(cursor));
}

void ChromeAppViewAsh::OnDisplayFileOpenDialog(
    const string16& title,
    const string16& filter,
    const base::FilePath& default_path,
    bool allow_multiple_files) {
  DVLOG(1) << __FUNCTION__;

  // The OpenFilePickerSession instance is deleted when we receive a
  // callback from the OpenFilePickerSession class about the completion of the
  // operation.
  FilePickerSessionBase* file_picker_ =
      new OpenFilePickerSession(this,
                                title,
                                filter,
                                default_path,
                                allow_multiple_files);
  file_picker_->Run();
}

void ChromeAppViewAsh::OnDisplayFileSaveAsDialog(
    const MetroViewerHostMsg_SaveAsDialogParams& params) {
  DVLOG(1) << __FUNCTION__;

  // The SaveFilePickerSession instance is deleted when we receive a
  // callback from the SaveFilePickerSession class about the completion of the
  // operation.
  FilePickerSessionBase* file_picker_ =
      new SaveFilePickerSession(this, params);
  file_picker_->Run();
}

void ChromeAppViewAsh::OnDisplayFolderPicker(const string16& title) {
  DVLOG(1) << __FUNCTION__;
  // The FolderPickerSession instance is deleted when we receive a
  // callback from the FolderPickerSession class about the completion of the
  // operation.
  FilePickerSessionBase* file_picker_ = new FolderPickerSession(this, title);
  file_picker_->Run();
}

void ChromeAppViewAsh::OnSetCursorPos(int x, int y) {
  if (ui_channel_) {
    ::SetCursorPos(x, y);
    DVLOG(1) << "In UI OnSetCursorPos: " << x << ", " << y;
    ui_channel_->Send(new MetroViewerHostMsg_SetCursorPosAck());
    // Generate a fake mouse move which matches the SetCursor coordinates as
    // the browser expects to receive a mouse move for these coordinates.
    // It is not clear why we don't receive a real mouse move in response to
    // the SetCursorPos calll above.
    ui_channel_->Send(new MetroViewerHostMsg_MouseMoved(x, y, 0));
  }
}

void ChromeAppViewAsh::OnOpenFileCompleted(
    OpenFilePickerSession* open_file_picker,
    bool success) {
  DVLOG(1) << __FUNCTION__;
  DVLOG(1) << "Success: " << success;
  if (ui_channel_) {
    if (open_file_picker->allow_multi_select()) {
      ui_channel_->Send(new MetroViewerHostMsg_MultiFileOpenDone(
          success, open_file_picker->filenames()));
    } else {
      ui_channel_->Send(new MetroViewerHostMsg_FileOpenDone(
          success, base::FilePath(open_file_picker->result())));
    }
  }
  delete open_file_picker;
}

void ChromeAppViewAsh::OnSaveFileCompleted(
    SaveFilePickerSession* save_file_picker,
    bool success) {
  DVLOG(1) << __FUNCTION__;
  DVLOG(1) << "Success: " << success;
  if (ui_channel_) {
    ui_channel_->Send(new MetroViewerHostMsg_FileSaveAsDone(
        success,
        base::FilePath(save_file_picker->result()),
        save_file_picker->filter_index()));
  }
  delete save_file_picker;
}

void ChromeAppViewAsh::OnFolderPickerCompleted(
    FolderPickerSession* folder_picker,
    bool success) {
  DVLOG(1) << __FUNCTION__;
  DVLOG(1) << "Success: " << success;
  if (ui_channel_) {
    ui_channel_->Send(new MetroViewerHostMsg_SelectFolderDone(
        success,
        base::FilePath(folder_picker->result())));
  }
  delete folder_picker;
}

HRESULT ChromeAppViewAsh::OnActivate(
    winapp::Core::ICoreApplicationView*,
    winapp::Activation::IActivatedEventArgs* args) {
  DVLOG(1) << __FUNCTION__;
  // Note: If doing more work in this function, you migth need to call
  // get_PreviousExecutionState() and skip the work if  the result is
  // ApplicationExecutionState_Running and globals.previous_state is too.
  args->get_PreviousExecutionState(&globals.previous_state);
  DVLOG(1) << "Previous Execution State: " << globals.previous_state;

  winapp::Activation::ActivationKind activation_kind;
  CheckHR(args->get_Kind(&activation_kind));
  if (activation_kind == winapp::Activation::ActivationKind_Search)
    HandleSearchRequest(args);
  else if (activation_kind == winapp::Activation::ActivationKind_Protocol)
    HandleProtocolRequest(args);
  // We call ICoreWindow::Activate after the handling for the search/protocol
  // requests because Chrome can be launched to handle a search request which
  // in turn launches the chrome browser process in desktop mode via
  // ShellExecute. If we call ICoreWindow::Activate before this, then
  // Windows kills the metro chrome process when it calls ShellExecute. Seems
  // to be a bug.
  window_->Activate();
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnPointerMoved(winui::Core::ICoreWindow* sender,
                                         winui::Core::IPointerEventArgs* args) {
  PointerInfoHandler pointer;
  HRESULT hr = pointer.Init(args);
  if (FAILED(hr))
    return hr;

  if (pointer.IsMouse()) {
    ui_channel_->Send(new MetroViewerHostMsg_MouseMoved(pointer.x(),
                                                        pointer.y(),
                                                        mouse_down_flags_));
  } else {
    DCHECK(pointer.IsTouch());
    ui_channel_->Send(new MetroViewerHostMsg_TouchMoved(pointer.x(),
                                                        pointer.y(),
                                                        pointer.timestamp(),
                                                        pointer.pointer_id()));
  }
  return S_OK;
}

// NOTE: From experimentation, it seems like Metro only sends a PointerPressed
// event for the first button pressed and the last button released in a sequence
// of mouse events.
// For example, a sequence of LEFT_DOWN, RIGHT_DOWN, LEFT_UP, RIGHT_UP results
// only in PointerPressed(LEFT)/PointerReleased(RIGHT) events.
HRESULT ChromeAppViewAsh::OnPointerPressed(
    winui::Core::ICoreWindow* sender,
    winui::Core::IPointerEventArgs* args) {
  PointerInfoHandler pointer;
  HRESULT hr = pointer.Init(args);
  if (FAILED(hr))
    return hr;

  if (pointer.IsMouse()) {
    mouse_down_flags_ = pointer.flags();
    ui_channel_->Send(new MetroViewerHostMsg_MouseButton(pointer.x(),
                                                         pointer.y(),
                                                         0,
                                                         ui::ET_MOUSE_PRESSED,
                                                         mouse_down_flags_));
  } else {
    DCHECK(pointer.IsTouch());
    ui_channel_->Send(new MetroViewerHostMsg_TouchDown(pointer.x(),
                                                       pointer.y(),
                                                       pointer.timestamp(),
                                                       pointer.pointer_id()));
  }
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnPointerReleased(
    winui::Core::ICoreWindow* sender,
    winui::Core::IPointerEventArgs* args) {
  PointerInfoHandler pointer;
  HRESULT hr = pointer.Init(args);
  if (FAILED(hr))
    return hr;

  if (pointer.IsMouse()) {
    mouse_down_flags_ = ui::EF_NONE;
    ui_channel_->Send(new MetroViewerHostMsg_MouseButton(pointer.x(),
                                                         pointer.y(),
                                                         0,
                                                         ui::ET_MOUSE_RELEASED,
                                                         pointer.flags()));
  } else {
    DCHECK(pointer.IsTouch());
    ui_channel_->Send(new MetroViewerHostMsg_TouchUp(pointer.x(),
                                                     pointer.y(),
                                                     pointer.timestamp(),
                                                     pointer.pointer_id()));
  }
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnWheel(
    winui::Core::ICoreWindow* sender,
    winui::Core::IPointerEventArgs* args) {
  PointerInfoHandler pointer;
  HRESULT hr = pointer.Init(args);
  if (FAILED(hr))
    return hr;
  DCHECK(pointer.IsMouse());
  ui_channel_->Send(new MetroViewerHostMsg_MouseButton(pointer.x(), pointer.y(),
                                                       pointer.wheel_delta(),
                                                       ui::ET_MOUSEWHEEL,
                                                       ui::EF_NONE));
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnKeyDown(
    winui::Core::ICoreWindow* sender,
    winui::Core::IKeyEventArgs* args) {
  winsys::VirtualKey virtual_key;
  HRESULT hr = args->get_VirtualKey(&virtual_key);
  if (FAILED(hr))
    return hr;
  winui::Core::CorePhysicalKeyStatus status;
  hr = args->get_KeyStatus(&status);
  if (FAILED(hr))
    return hr;

  ui_channel_->Send(new MetroViewerHostMsg_KeyDown(virtual_key,
                                                   status.RepeatCount,
                                                   status.ScanCode,
                                                   GetKeyboardEventFlags()));
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnKeyUp(
    winui::Core::ICoreWindow* sender,
    winui::Core::IKeyEventArgs* args) {
  winsys::VirtualKey virtual_key;
  HRESULT hr = args->get_VirtualKey(&virtual_key);
  if (FAILED(hr))
    return hr;
  winui::Core::CorePhysicalKeyStatus status;
  hr = args->get_KeyStatus(&status);
  if (FAILED(hr))
    return hr;

  ui_channel_->Send(new MetroViewerHostMsg_KeyUp(virtual_key,
                                                 status.RepeatCount,
                                                 status.ScanCode,
                                                 GetKeyboardEventFlags()));
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnAcceleratorKeyDown(
    winui::Core::ICoreDispatcher* sender,
    winui::Core::IAcceleratorKeyEventArgs* args) {
  winsys::VirtualKey virtual_key;
  HRESULT hr = args->get_VirtualKey(&virtual_key);
  if (FAILED(hr))
    return hr;
  winui::Core::CorePhysicalKeyStatus status;
  hr = args->get_KeyStatus(&status);
  if (FAILED(hr))
    return hr;

  winui::Core::CoreAcceleratorKeyEventType event_type;
  hr = args->get_EventType(&event_type);
  if (FAILED(hr))
    return hr;

  uint32 keyboard_flags = GetKeyboardEventFlags();

  switch (event_type) {
    case winui::Core::CoreAcceleratorKeyEventType_SystemCharacter:
      ui_channel_->Send(new MetroViewerHostMsg_Character(virtual_key,
                                                         status.RepeatCount,
                                                         status.ScanCode,
                                                         keyboard_flags));
      break;

    case winui::Core::CoreAcceleratorKeyEventType_SystemKeyDown:
      ui_channel_->Send(new MetroViewerHostMsg_KeyDown(virtual_key,
                                                       status.RepeatCount,
                                                       status.ScanCode,
                                                       keyboard_flags));
      break;

    case winui::Core::CoreAcceleratorKeyEventType_SystemKeyUp:
      ui_channel_->Send(new MetroViewerHostMsg_KeyUp(virtual_key,
                                                     status.RepeatCount,
                                                     status.ScanCode,
                                                     keyboard_flags));
      break;

    default:
      break;
  }
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnCharacterReceived(
  winui::Core::ICoreWindow* sender,
  winui::Core::ICharacterReceivedEventArgs* args) {
  unsigned int char_code = 0;
  HRESULT hr = args->get_KeyCode(&char_code);
  if (FAILED(hr))
    return hr;

  winui::Core::CorePhysicalKeyStatus status;
  hr = args->get_KeyStatus(&status);
  if (FAILED(hr))
    return hr;

  ui_channel_->Send(new MetroViewerHostMsg_Character(char_code,
                                                     status.RepeatCount,
                                                     status.ScanCode,
                                                     GetKeyboardEventFlags()));
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnVisibilityChanged(
    winui::Core::ICoreWindow* sender,
    winui::Core::IVisibilityChangedEventArgs* args) {
  boolean visible = false;
  HRESULT hr = args->get_Visible(&visible);
  if (FAILED(hr))
    return hr;

  ui_channel_->Send(new MetroViewerHostMsg_VisibilityChanged(!!visible));
  return S_OK;
}

HRESULT ChromeAppViewAsh::OnWindowActivated(
    winui::Core::ICoreWindow* sender,
    winui::Core::IWindowActivatedEventArgs* args) {
  winui::Core::CoreWindowActivationState state;
  HRESULT hr = args->get_WindowActivationState(&state);
  if (FAILED(hr))
    return hr;
  DVLOG(1) << "Window activation state: "  << state;
  ui_channel_->Send(new MetroViewerHostMsg_WindowActivated(
      state != winui::Core::CoreWindowActivationState_Deactivated));
  return S_OK;
}

HRESULT ChromeAppViewAsh::HandleSearchRequest(
    winapp::Activation::IActivatedEventArgs* args) {
  mswr::ComPtr<winapp::Activation::ISearchActivatedEventArgs> search_args;
  CheckHR(args->QueryInterface(
          winapp::Activation::IID_ISearchActivatedEventArgs, &search_args));

  if (!ui_channel_) {
    DVLOG(1) << "Launched to handle search request";
    base::FilePath chrome_exe_path;

    if (!PathService::Get(base::FILE_EXE, &chrome_exe_path))
      return E_FAIL;

    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.nShow = SW_SHOWNORMAL;
    sei.lpFile = chrome_exe_path.value().c_str();
    sei.lpDirectory = L"";
    sei.lpParameters =
        L"--silent-launch --viewer-connection=viewer --windows8-search";
    ::ShellExecuteEx(&sei);
  }

  mswrw::HString search_string;
  CheckHR(search_args->get_QueryText(search_string.GetAddressOf()));
  string16 search_text(MakeStdWString(search_string.Get()));

  ui_loop_.PostTask(FROM_HERE,
                    base::Bind(&ChromeAppViewAsh::OnSearchRequest,
                    base::Unretained(this),
                    search_text));
  return S_OK;
}

HRESULT ChromeAppViewAsh::HandleProtocolRequest(
    winapp::Activation::IActivatedEventArgs* args) {
  DVLOG(1) << __FUNCTION__;
  if (!ui_channel_)
    DVLOG(1) << "Launched to handle url request";

  mswr::ComPtr<winapp::Activation::IProtocolActivatedEventArgs>
      protocol_args;
  CheckHR(args->QueryInterface(
          winapp::Activation::IID_IProtocolActivatedEventArgs,
          &protocol_args));

  mswr::ComPtr<winfoundtn::IUriRuntimeClass> uri;
  protocol_args->get_Uri(&uri);
  mswrw::HString url;
  uri->get_AbsoluteUri(url.GetAddressOf());
  string16 actual_url(MakeStdWString(url.Get()));
  DVLOG(1) << "Received url request: " << actual_url;

  ui_loop_.PostTask(FROM_HERE,
                    base::Bind(&ChromeAppViewAsh::OnNavigateToUrl,
                               base::Unretained(this),
                               actual_url));
  return S_OK;
}

void ChromeAppViewAsh::OnSearchRequest(const string16& search_string) {
  DCHECK(ui_channel_);
  ui_channel_->Send(new MetroViewerHostMsg_SearchRequest(search_string));
}

void ChromeAppViewAsh::OnNavigateToUrl(const string16& url) {
  DCHECK(ui_channel_);
 ui_channel_->Send(new MetroViewerHostMsg_OpenURL(url));
}

HRESULT ChromeAppViewAsh::OnSizeChanged(winui::Core::ICoreWindow* sender,
    winui::Core::IWindowSizeChangedEventArgs* args) {
  if (!window_) {
    return S_OK;
  }

  winfoundtn::Size size;
  HRESULT hr = args->get_Size(&size);
  if (FAILED(hr))
    return hr;

  uint32 cx = static_cast<uint32>(size.Width);
  uint32 cy = static_cast<uint32>(size.Height);

  DVLOG(1) << "Window size changed: width=" << cx << ", height=" << cy;
  ui_channel_->Send(new MetroViewerHostMsg_WindowSizeChanged(cx, cy));
  return S_OK;
}

///////////////////////////////////////////////////////////////////////////////

ChromeAppViewFactory::ChromeAppViewFactory(
    winapp::Core::ICoreApplication* icore_app,
    LPTHREAD_START_ROUTINE host_main,
    void* host_context) {
  mswr::ComPtr<winapp::Core::ICoreApplication> core_app(icore_app);
  mswr::ComPtr<winapp::Core::ICoreApplicationExit> app_exit;
  CheckHR(core_app.As(&app_exit));
  globals.app_exit = app_exit.Detach();
}

IFACEMETHODIMP
ChromeAppViewFactory::CreateView(winapp::Core::IFrameworkView** view) {
  *view = mswr::Make<ChromeAppViewAsh>().Detach();
  return (*view) ? S_OK :  E_OUTOFMEMORY;
}


text:
/* global module, require */

var config = require('../../app/config');
var co = require('co');
var r = require('rethinkdbdash')(config.rethinkdb);

module.exports = {
    load: function (table, data) {
        return co(function *() {
            yield r.db(config.rethinkdb.db)
                .table(table)
                .delete();

            yield r.db(config.rethinkdb.db)
                .table(table)
                .insert(data)
                .run()
        });
    }
};

redpajama_set_name: RedPajamaGithub


text:
(function() {
    'use strict';
    appDep.Controllers.controller('movieListCtrl', [
        '$scope', 'movieModelServices', 'commonConstants', 'validationServices',
        function($scope, movieModelServices, commonConstants, validationServices) {
            self = this;

            self.scope = $scope;
            $scope.movieList = [];
            $scope.searchPhrase = '';
            $scope.errorMessage = '';

            $scope.pagination = {};
            $scope.list = commonConstants.numberMoviesPageLoad;
            $scope.currentPage = 1;
            $scope.finalPage = 1;

            $scope.totalfilteredMovies = $scope.list;
            $scope.totalMoviesCount = $scope.list;

            //send this for custom pagination
            $scope.nextcallback = function() {
                if (self.scope.finalPage > self.scope.currentPage) {
                    self.scope.currentPage++;
                }
            }.bind(self);

            $scope.previouscallback = function() {
                if (1 < self.scope.currentPage) {
                    self.scope.currentPage--;
                }
            }.bind(self);

            //self invoked to load 20 movies on page load
            // - On page load, you should display first 20 movies,
            // ordered alphabetically by title.
            var loadMoviesOnInit = function() {
                movieModelServices.getAllMovies(commonConstants.numberMoviesPageLoad)
                    .then(function(data) {
                        $scope.movieList = data.movies || 1;
                        $scope.list = commonConstants.numberMoviesPageLoad;
                        $scope.totalfilteredMovies = data.totalMoviesCount;
                        $scope.totalMoviesCount = data.totalMoviesCount;
                        $scope.finalPage = Math.ceil(data.totalMoviesCount / $scope.list) || 1;
                    });
            };

            loadMoviesOnInit();

            //exposing the callback functions for testing
            var getAllMoviesSuccess = function(data) {

                //on each call we clear the errors
                //if we have more errors they will be loaded on the result
                if (!data.errorMessage) {
                    $scope.errorMessage = '';
                }
                else{
                    $scope.errorMessage = data.errorMessage;
                }

                $scope.movieList = data.movies;
                $scope.totalMoviesCount = data.totalMoviesCount;

                if ($scope.searchPhrase) {
                    $scope.totalfilteredMovies = data.totalfilteredMovies;
                    $scope.finalPage = Math.ceil(data.totalfilteredMovies / $scope.list) || 1;
                } else {
                    $scope.totalfilteredMovies = data.totalMoviesCount;
                    $scope.finalPage = Math.ceil(data.totalMoviesCount / $scope.list) || 1;
                }

                if ($scope.totalfilteredMovies < $scope.list) {

                    $scope.list = $scope.totalfilteredMovies || 1;
                }
            };

            //exposing the callback functions for testing
            var getAllMoviesError = function(data) {

                //when error received we handle it
                if (data.errorMessage) {
                    $scope.errorMessage = data.errorMessage;
                    $scope.movieList = [];
                }
            };

            var proccessMovies = function(list, currentPage, searchPhrase, forceList) {
                if (searchPhrase.length < 3) {
                    searchPhrase = '';
                }

                if (searchPhrase.length > 2 || searchPhrase === '') {

                    movieModelServices.getAllMovies(list, currentPage, searchPhrase)
                        .then(getAllMoviesSuccess, getAllMoviesError);
                }
            };

            $scope.$watch('searchPhrase', function(newVal, oldVal) {

                //if search phrase not valid do not call the backend
                if (newVal.length < 3) {
                    $scope.list = commonConstants.numberMoviesPageLoad;
                    $scope.errorMessage = '';
                }

                //if the search phrase have changed do request
                if (oldVal !== newVal) {
                    proccessMovies($scope.list, $scope.currentPage, newVal, false, 'search');
                    return;
                }
            });

            $scope.$watch('list', function(newVal, oldVal) {
                //handling any bad input data
                if (!validationServices.isNumeric(newVal)) {
                    $scope.list = commonConstants.numberMoviesPageLoad;
                }

                if (newVal < 1) {
                    $scope.list = 1;
                }

                if (newVal > $scope.totalMoviesCount) {
                    $scope.list = $scope.totalMoviesCount || 1;
                }

                //if search phrase valid then update $scope.list
                if ($scope.searchPhrase && $scope.searchPhrase.length && $scope.searchPhrase.length > 2) {
                    if ($scope.list > $scope.totalfilteredMovies && $scope.totalfilteredMovies > 0) {

                        $scope.list = $scope.totalfilteredMovies;
                    }
                }

                //do not request final page many times
                //optimisation for uneeded calls
                if (oldVal !== newVal) {

                    if (newVal && oldVal &&
                        (newVal > $scope.totalfilteredMovies && oldVal === $scope.totalfilteredMovies ||
                            newVal >= $scope.totalfilteredMovies && oldVal >= $scope.totalfilteredMovies)) {
                        return;
                    }

                    proccessMovies($scope.list, $scope.currentPage, $scope.searchPhrase, false, 'list');
                }
            });

            $scope.$watch('currentPage', function(newVal, oldVal) {

                if (!validationServices.isNumeric(newVal)) {

                    $scope.currentPage = 1;
                    return;
                }

                if (newVal < 1) {
                    $scope.currentPage = 1;
                    return;
                }

                if ($scope.finalPage < $scope.currentPage) {
                    $scope.currentPage = $scope.finalPage;
                    return;
                }

                if (oldVal !== newVal && newVal <= $scope.finalPage && oldVal !== $scope.finalPage + 1) {
                    proccessMovies($scope.list, newVal, $scope.searchPhrase, false, 'currentPage');
                }
            });

            //for dynamic updating the front end
            $scope.$watch('finalPage', function(newVal, oldVal) {
                if ($scope.finalPage < $scope.currentPage) {
                    $scope.currentPage = $scope.finalPage ;
                }
            });
        }
    ]);
})();


text:
@implementation HMMessageTypeModel

+ (NSString *)tableName {

    return @"messageType";
}

+ (NSArray*)columns
{
    return @[
             column_constrains("typeId","text","UNIQUE ON CONFLICT REPLACE"),
             column("familyId","text"),
             column("type","integer"), // 列表项分组序号
             column("delFlag","integer"),
             column("updateTime","text"),
             column("createTime","text")
             ];
}

-(void)setInsertWithDb:(FMDatabase *)db
{
    [self insertModel:db];
}

+ (NSMutableArray *)messageTypesArrOfFamilyId:(NSString *)familyId
{
    NSString *sql = [NSString stringWithFormat:@"select distinct type from messageType where familyId = '%@' and delFlag= 0 and type != -1 order by type asc",familyId];
    NSMutableArray *tmpArray = [NSMutableArray array];
    queryDatabase(sql, ^(FMResultSet *rs) {
        int type = [rs intForColumn:@"type"];
        [tmpArray addObject:@(type)];
    });
    return tmpArray;
}

@end


text:
'use strict';

var fs         = require('fs-extra');
var existsSync = require('exists-sync');
var path       = require('path');
var Plugin     = require('broccoli-plugin');

function CustomReplace (inputNode, configNode, options) {
  options = options || {};
  Plugin.call(this, [inputNode, configNode], { annotation: options.annotation }); // this._super();

  this.options = options;
}
CustomReplace.prototype = Object.create(Plugin.prototype);
CustomReplace.prototype.constructor = CustomReplace;

CustomReplace.prototype.build = function () {
  var inputPath = this.inputPaths[0];
  var configPath = this.inputPaths[1];
  var files = this.options.files;
  var config = this.getConfig(configPath);

  for (var i = 0, l = files.length; i < l; i++) {
    var file = files[i];
    var filePath = path.join(inputPath, file);
    var destPath = path.join(this.outputPath, file);

    this.processFile(config, filePath, destPath);
  }
};

CustomReplace.prototype.processFile = function(config, filePath, destPath) {
  var contents = fs.readFileSync(filePath, { encoding: 'utf8' });

  for (var i = 0, l = this.options.patterns.length; i < l; i++) {
    // jshint loopfunc:true
    var pattern = this.options.patterns[i];
    var replacement = pattern.replacement;

    if (typeof pattern.replacement === 'function') {
      replacement = function() {
        var args = Array.prototype.slice.call(arguments);

        return pattern.replacement.apply(null, [config].concat(args));
      };
    }

    contents = contents.replace(pattern.match, replacement);
  }

  if (!existsSync(path.dirname(destPath))) {
    fs.mkdirsSync(path.dirname(destPath));
  }
  fs.writeFileSync(destPath, contents, { encoding: 'utf8' });
};

CustomReplace.prototype.getConfig = function (srcDir) {
  var configPath = path.join(srcDir, this.options.configPath);

  return JSON.parse(fs.readFileSync(configPath, { encoding: 'utf8' }));
};

module.exports = CustomReplace;


text:
namespace autoboost {
namespace asio {
namespace detail {

DWORD WINAPI winapi_thread_function(LPVOID arg);

class winapi_thread
  : private noncopyable
{
public:
  // Constructor.
  template <typename Function>
  winapi_thread(Function f, unsigned int = 0)
  {
    std::auto_ptr<func_base> arg(new func<Function>(f));
    DWORD thread_id = 0;
    thread_ = ::CreateThread(0, 0, winapi_thread_function,
        arg.get(), 0, &thread_id);
    if (!thread_)
    {
      DWORD last_error = ::GetLastError();
      autoboost::system::error_code ec(last_error,
          autoboost::asio::error::get_system_category());
      autoboost::asio::detail::throw_error(ec, "thread");
    }
    arg.release();
  }

  // Destructor.
  ~winapi_thread()
  {
    ::CloseHandle(thread_);
  }

  // Wait for the thread to exit.
  void join()
  {
#if defined(AUTOBOOST_ASIO_WINDOWS_APP)
    ::WaitForSingleObjectEx(thread_, INFINITE, false);
#else // defined(AUTOBOOST_ASIO_WINDOWS_APP)
    ::WaitForSingleObject(thread_, INFINITE);
#endif // defined(AUTOBOOST_ASIO_WINDOWS_APP)
  }

private:
  friend DWORD WINAPI winapi_thread_function(LPVOID arg);

  class func_base
  {
  public:
    virtual ~func_base() {}
    virtual void run() = 0;
  };

  template <typename Function>
  class func
    : public func_base
  {
  public:
    func(Function f)
      : f_(f)
    {
    }

    virtual void run()
    {
      f_();
    }

  private:
    Function f_;
  };

  ::HANDLE thread_;
};

inline DWORD WINAPI winapi_thread_function(LPVOID arg)
{
  std::auto_ptr<winapi_thread::func_base> func(
      static_cast<winapi_thread::func_base*>(arg));
  func->run();
  return 0;
}

} // namespace detail
} // namespace asio
} // namespace autoboost

#include <autoboost/asio/detail/pop_options.hpp>

#endif // defined(AUTOBOOST_ASIO_WINDOWS_APP) || defined(UNDER_CE)
#endif // defined(AUTOBOOST_ASIO_WINDOWS)

#endif // AUTOBOOST_ASIO_DETAIL_WINAPI_THREAD_HPP


text:
package org.adbcj.support;

import org.adbcj.Field;
import org.adbcj.ResultHandler;
import org.adbcj.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author roman.stoffel@gamlor.info
* @since 10.05.12
*/
public class DefaultResultEventsHandler implements ResultHandler<DefaultResultSet> {
    private static final Logger logger = LoggerFactory.getLogger(DefaultResultEventsHandler.class);

    private Value[] currentRow;
    private int rowIndex;

    public void startFields(DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: startFields");
    }

    public void field(Field field, DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: field");
        accumulator.addField(field);
    }

    public void endFields(DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: endFields");
    }

    public void startResults(DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: startResults");
    }

    public void startRow(DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: startRow");

        int columnCount = accumulator.getFields().size();
        currentRow = new Value[columnCount];
    }

    public void value(Value value, DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: value");

        currentRow[rowIndex%currentRow.length] = value;
        rowIndex++;
    }

    public void endRow(DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: endRow");
        DefaultRow row = new DefaultRow(accumulator, currentRow);
        accumulator.addResult(row);
        currentRow = null;
    }

    public void endResults(DefaultResultSet accumulator) {
        logger.trace("ResultSetEventHandler: endResults");
    }

    public void exception(Throwable t, DefaultResultSet accumulator) {
    }
}


text:
package de.interseroh.report.controller;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

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

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;

import de.interseroh.report.auth.Role;
import de.interseroh.report.auth.RoleEntity;
import de.interseroh.report.auth.UserRole;
import de.interseroh.report.auth.UserRoleEntity;
import de.interseroh.report.auth.UserService;
import de.interseroh.report.services.SecurityHelper;
import de.interseroh.report.services.SecurityService;

/**
 * Created by hhopf on 26.09.15.
 */
@RunWith(MockitoJUnitRunner.class)
public class SecurityControlTest {

	@Mock
	UserService userService;

	@InjectMocks
	private SecurityService securityControl = new SecurityService();

	@Mock
	private SecurityHelper securityHelper;

	@Before
	public void setup() {
		ReflectionTestUtils.setField(securityControl, "securityEnabled", "true");
	}

	@Test
	public void testForLoop1() {
		UserRole userRole = getUserRole();
		Collection<UserRole> roles = new ArrayList<>();
		roles.add(userRole);

		when(securityHelper.getPrincipalName()).thenReturn("userName");

		when(userService.findUserRolesByUserEmail(eq("userName")))
				.thenReturn(roles);

		List<String> rolesResult = securityControl.getRoles();

		assertEquals("1 role is in Array", 1, rolesResult.size());
	}

	@Test
	public void testForLoop2() {
		Collection<UserRole> roles = getUserRoles();

		when(securityHelper.getPrincipalName()).thenReturn("userName");

		when(userService.findUserRolesByUserEmail(eq("userName")))
				.thenReturn(roles);

		List<String> rolesResult = securityControl.getRoles();

		assertEquals("2 role is in Array", 2, rolesResult.size());
	}

	@Test
	public void testHasUserRoleValid() {
		Collection<UserRole> roles = getUserRoles();
		roles.add(getUserRoleForCascade());

		when(securityHelper.getPrincipalName()).thenReturn("userName");

		when(userService.findUserRolesByUserEmail(eq("userName")))
				.thenReturn(roles);
		boolean visible = securityControl
				.hasUserValidRole("cascade_parameters");

		assertTrue(visible);

	}

	@Test
	public void testHasUserRoleValidWITHPräfixFalse() {
		Collection<UserRole> roles = getUserRolesWithEqualsPräfix();
		roles.add(getUserRoleForCascade());

		when(securityHelper.getPrincipalName()).thenReturn("userName");

		when(userService.findUserRolesByUserEmail(eq("userName")))
				.thenReturn(roles);
		boolean visible = securityControl
				.hasUserValidRole("CHART");

		assertFalse(visible);

	}

	private UserRole getUserRole() {
		return createUserRole("ROLE_SALESINVOICE");
	}

	private UserRole getUserRoleForCascade() {
		return createUserRole("ROLE_CASCADE_PARAMETERS");
	}

	private Collection<UserRole> getUserRoles() {
		Collection<UserRole> userRoles = new ArrayList<>();
		userRoles.add(createUserRole("ROLE_SALESINVOICE"));
		userRoles.add(createUserRole("ROLE_PRODUCTCATALOG"));
		return userRoles;
	}

	private Collection<UserRole> getUserRolesWithEqualsPräfix() {
		Collection<UserRole> userRoles = new ArrayList<>();
		userRoles.add(createUserRole("ROLE_CHARTI"));
		userRoles.add(createUserRole("ROLE_CHARTDATE"));
		return userRoles;
	}

	private UserRole createUserRole(String roleName) {
		Role role = new RoleEntity();
		role.setName(roleName);
		UserRole userRole = new UserRoleEntity();
		userRole.setRole(role);
		return userRole;
	}

}


text:
package gov.va.research.red.ex.hadoop;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;

import in.ashwanthkumar.hadoop2.mapreduce.lib.input.CSVLineRecordReader;
import in.ashwanthkumar.hadoop2.mapreduce.lib.input.CSVNLineInputFormat;

/**
 * @author Doug Redd <doug_redd@gwu.edu> Executes Hadoop Map-Reduce jobs
 *         to apply a REDEx model to clinical notes. Input files must have a key
 *         on the first line and the text of the clinical note following, one
 *         clinical note per file. The key is a pipe delimited set of patient
 *         ID, document ID, and document date/time in ISO 8601 format, i.e.
 *         <patient ID>|<document ID>|<date/time>
 */
public class REDExHadoop extends Configured implements Tool {

	private static final Logger LOG = Logger.getLogger(REDExHadoop.class);

	public static void main(String[] args) throws Exception {
		int result = ToolRunner.run(new Configuration(), new REDExHadoop(), args);
		System.exit(result);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.hadoop.util.Tool#run(java.lang.String[])
	 */
	@Override
	public int run(String[] args) throws Exception {
		LOG.info("> args = " + Arrays.asList(args));
		if (args.length != 4) {
			LOG.info("Usage: REDExHadoop <redex-model-file> <annotation type>"
					+ " <input file directory, csv files, tab-separated, not compressed>"
					+ " <output file directory> [hadoop options]");
			System.exit(2);
		}
		Path inputPath = new Path(args[2]);
		String outputPath = args[3];

		// Set up configuration
		Configuration conf = getConf();
		conf.set("redex.model.file", args[0]);
		conf.set("annotation.type", args[1]);
		conf.set(CSVLineRecordReader.FORMAT_SEPARATOR, "\t");
		conf.set(CSVLineRecordReader.IS_ZIPFILE, "false");
		conf.set(CSVLineRecordReader.FORMAT_DELIMITER, "\"");

		Path filteredFilesDir = filterNonASCIIDir(getConf(), inputPath);

		// Set up job
		Job job = Job.getInstance(conf, "redex " + args[1]);
		job.setJarByClass(REDExHadoop.class);
		job.setInputFormatClass(CSVNLineInputFormat.class);

		job.setMapperClass(OMOPNoteREDExMapper.class);
		job.setMapOutputKeyClass(LongWritable.class);
		job.setMapOutputValueClass(OMOPNoteMatchedElementsWritable.class);

		job.setReducerClass(BioCReducer.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(NullWritable.class);

		// Add input/output paths
		FileInputFormat.addInputPath(job, filteredFilesDir);
		FileOutputFormat.setOutputPath(job, new Path(outputPath));

		// Run job
		int succeeded = job.waitForCompletion(true) ? 0 : 1;
		filteredFilesDir.getFileSystem(getConf()).delete(filteredFilesDir, true);
		return succeeded;
	}

	static void filterNonASCII(Configuration conf, Path inPath, Path outPath) throws IOException {
		FileSystem fs = inPath.getFileSystem(conf);

		Map<Integer, Character> illegalChars = new HashMap<>();

		try (	FSDataInputStream dis = fs.open(inPath);
				InputStreamReader isr = new InputStreamReader(dis);
				FSDataOutputStream dos = fs.create(outPath);
				OutputStreamWriter osw = new OutputStreamWriter(dos)) {
			int readInt = -1;
			while ((readInt = isr.read()) != -1) {
				if (readInt > 127) {
					illegalChars.put(Integer.valueOf(readInt), Character.valueOf((char) readInt));
					osw.write(' ');
				} else {
					osw.write(readInt);
				}
			}
		}
		if (illegalChars.size() > 0) {
			LOG.warn("Illegal characters found in input file '" + inPath.toString()
					+ ". Replaced with space characters in temp file '" + outPath.toString() + "'.\n"
					+ illegalChars.toString());
		}
	}

	static Path filterNonASCIIDir(Configuration conf, Path inDir) throws IOException {
		FileSystem fs = inDir.getFileSystem(conf);
		long timestamp = System.currentTimeMillis();
		Path tempDir = new Path(inDir, "tmp-" + timestamp);
		fs.mkdirs(tempDir);
		for (FileStatus fstat : fs.listStatus(inDir, new PathFilter() {
			@Override
			public boolean accept(Path path) {
				try {
					return fs.isFile(path);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		})) {
			filterNonASCII(conf, fstat.getPath(), new Path(tempDir, fstat.getPath().getName()));
		}
		return tempDir;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>1. research_ovws</title>

  <link href="../../_static/styles/theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link href="../../_static/styles/pydata-sphinx-theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">

  <link rel="stylesheet"
    href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" href="../../_static/styles/sphinx-book-theme.css?digest=62ba249389abaaa9ffc34bf36a076bdc1d65ee18" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/togglebutton.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/copybutton.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/mystnb.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/sphinx-thebe.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/design-style.b7bb847fb20b106c3d81b95245e65545.min.css" />

  <link rel="preload" as="script" href="../../_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf">

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="1.1. comp neuro" href="ovw_comp_neuro.html" />
    <link rel="prev" title="overview 👋" href="../../intro.html" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="None">

<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation" aria-label="Toggle navigation sidebar">

Toggle navigation sidebar

<input type="checkbox" class="sidebar-toggle" name="__page-toc" id="__page-toc" aria-label="Toggle in-page Table of Contents">

Toggle in-page Table of Contents

<form class="bd-search d-flex align-items-center" action="../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>

                    overview 👋

   1. research_ovws

  <input checked="" class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" type="checkbox"/>

     1.1. comp neuro

     1.2. transfer learning

     1.3. disentanglement

     1.4. omics

     1.5. complexity

     1.6. interesting science

     1.7. dl theory

     1.8. scattering transform

     1.9. ml in medicine

     1.10. transformers

     1.11. causal inference

     1.12. dl for neuro

     1.13. uncertainty

     1.14. interpretability

     1.15. generalization

   2. cs

  <input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" type="checkbox"/>

     2.1. info retrieval

     2.2. data structures

     2.3. languages

     2.4. software engineering

     2.5. quantum

     2.6. algorithms

     2.7. graphs

     2.8. os

     2.9. architecture

     2.10. reproducibility

     2.11. cs theory

   3. math

  <input class="toctree-checkbox" id="toctree-checkbox-3" name="toctree-checkbox-3" type="checkbox"/>

     3.1. differential equations

     3.2. proofs

     3.3. real analysis

     3.4. linear algebra

     3.5. signals

     3.6. optimization

     3.7. calculus

     3.8. chaos

     3.9. math basics

   4. stat

  <input class="toctree-checkbox" id="toctree-checkbox-4" name="toctree-checkbox-4" type="checkbox"/>

     4.1. graphical models

     4.2. data analysis

     4.3. testing

     4.4. causal inference

     4.5. info theory

     4.6. linear models

     4.7. time series

     4.8. game theory

   5. ml

  <input class="toctree-checkbox" id="toctree-checkbox-5" name="toctree-checkbox-5" type="checkbox"/>

     5.1. kernels

     5.2. nlp

     5.3. computer vision

     5.4. structure learning

     5.5. classification

     5.6. unsupervised

     5.7. deep learning

     5.8. feature selection

     5.9. learning theory

     5.10. evaluation

   6. ai

  <input class="toctree-checkbox" id="toctree-checkbox-6" name="toctree-checkbox-6" type="checkbox"/>

     6.1. search

     6.2. decisions, rl

     6.3. fairness, sts

     6.4. cogsci

     6.5. ai futures

     6.6. logic

     6.7. philosophy

     6.8. psychology

     6.9. representations

   7. neuro

  <input class="toctree-checkbox" id="toctree-checkbox-7" name="toctree-checkbox-7" type="checkbox"/>

     7.1. disease

     7.2. brain basics

     7.3. vision

     7.4. comp neuro

     7.5. sensory input

     7.6. memory

     7.7. motor system

     7.8. development

            Powered by Jupyter Book

<button onclick="toggleFullScreen()"
  class="headerbtn"
  data-toggle="tooltip"
data-placement="bottom"
title="Fullscreen mode"
>

</button>

  <button class="headerbtn menu-dropdown__trigger"
      aria-label="Download this page">

  </button>

.md

<button onclick="printPdf(this)"
  class="headerbtn"
  data-toggle="tooltip"
data-placement="left"
title="Print to PDF"
>

.pdf
</button>

research_ovws

1. research_ovws#

previous

overview 👋

next

1.1. comp neuro

    By Chandan Singh

      © Copyright None.

Many of these images are taken from resources on the web.


text:
package session

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/valyala/fasthttp"

	"github.com/authelia/authelia/v4/internal/authentication"
	"github.com/authelia/authelia/v4/internal/authorization"
	"github.com/authelia/authelia/v4/internal/configuration/schema"
	"github.com/authelia/authelia/v4/internal/oidc"
)

func TestShouldInitializerSession(t *testing.T) {
	ctx := &fasthttp.RequestCtx{}
	configuration := schema.SessionConfiguration{}
	configuration.Domain = testDomain
	configuration.Name = testName
	configuration.Expiration = testExpiration

	provider := NewProvider(configuration, nil)
	session, err := provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t, NewDefaultUserSession(), session)
}

func TestShouldUpdateSession(t *testing.T) {
	ctx := &fasthttp.RequestCtx{}

	configuration := schema.SessionConfiguration{}
	configuration.Domain = testDomain
	configuration.Name = testName
	configuration.Expiration = testExpiration

	provider := NewProvider(configuration, nil)
	session, _ := provider.GetSession(ctx)

	session.Username = testUsername
	session.AuthenticationLevel = authentication.TwoFactor

	err := provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t, UserSession{
		Username:            testUsername,
		AuthenticationLevel: authentication.TwoFactor,
	}, session)
}

func TestShouldSetSessionAuthenticationLevels(t *testing.T) {
	ctx := &fasthttp.RequestCtx{}
	configuration := schema.SessionConfiguration{}

	timeOneFactor := time.Unix(1625048140, 0)
	timeTwoFactor := time.Unix(1625048150, 0)
	timeZeroFactor := time.Unix(0, 0)

	configuration.Domain = testDomain
	configuration.Name = testName
	configuration.Expiration = testExpiration

	provider := NewProvider(configuration, nil)
	session, _ := provider.GetSession(ctx)

	session.SetOneFactor(timeOneFactor, &authentication.UserDetails{Username: testUsername}, false)

	err := provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	authAt, err := session.AuthenticatedTime(authorization.OneFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeOneFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.TwoFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeZeroFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.Denied)
	assert.EqualError(t, err, "invalid authorization level")
	assert.Equal(t, timeZeroFactor, authAt)

	assert.Equal(t, UserSession{
		Username:                  testUsername,
		AuthenticationLevel:       authentication.OneFactor,
		LastActivity:              timeOneFactor.Unix(),
		FirstFactorAuthnTimestamp: timeOneFactor.Unix(),
		AuthenticationMethodRefs:  oidc.AuthenticationMethodsReferences{UsernameAndPassword: true},
	}, session)

	session.SetTwoFactorDuo(timeTwoFactor)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t, UserSession{
		Username:                   testUsername,
		AuthenticationLevel:        authentication.TwoFactor,
		LastActivity:               timeTwoFactor.Unix(),
		FirstFactorAuthnTimestamp:  timeOneFactor.Unix(),
		SecondFactorAuthnTimestamp: timeTwoFactor.Unix(),
		AuthenticationMethodRefs:   oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Duo: true},
	}, session)

	authAt, err = session.AuthenticatedTime(authorization.OneFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeOneFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.TwoFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeTwoFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.Denied)
	assert.EqualError(t, err, "invalid authorization level")
	assert.Equal(t, timeZeroFactor, authAt)
}

func TestShouldSetSessionAuthenticationLevelsAMR(t *testing.T) {
	ctx := &fasthttp.RequestCtx{}
	configuration := schema.SessionConfiguration{}

	timeOneFactor := time.Unix(1625048140, 0)
	timeTwoFactor := time.Unix(1625048150, 0)
	timeZeroFactor := time.Unix(0, 0)

	configuration.Domain = testDomain
	configuration.Name = testName
	configuration.Expiration = testExpiration

	provider := NewProvider(configuration, nil)
	session, _ := provider.GetSession(ctx)

	session.SetOneFactor(timeOneFactor, &authentication.UserDetails{Username: testUsername}, false)

	err := provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	authAt, err := session.AuthenticatedTime(authorization.OneFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeOneFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.TwoFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeZeroFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.Denied)
	assert.EqualError(t, err, "invalid authorization level")
	assert.Equal(t, timeZeroFactor, authAt)

	assert.Equal(t, UserSession{
		Username:                  testUsername,
		AuthenticationLevel:       authentication.OneFactor,
		LastActivity:              timeOneFactor.Unix(),
		FirstFactorAuthnTimestamp: timeOneFactor.Unix(),
		AuthenticationMethodRefs:  oidc.AuthenticationMethodsReferences{UsernameAndPassword: true},
	}, session)

	session.SetTwoFactorWebauthn(timeTwoFactor, false, false)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t, oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true}, session.AuthenticationMethodRefs)
	assert.True(t, session.AuthenticationMethodRefs.MultiFactorAuthentication())

	authAt, err = session.AuthenticatedTime(authorization.OneFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeOneFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.TwoFactor)
	assert.NoError(t, err)
	assert.Equal(t, timeTwoFactor, authAt)

	authAt, err = session.AuthenticatedTime(authorization.Denied)
	assert.EqualError(t, err, "invalid authorization level")
	assert.Equal(t, timeZeroFactor, authAt)

	session.SetTwoFactorWebauthn(timeTwoFactor, false, false)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorWebauthn(timeTwoFactor, false, false)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorWebauthn(timeTwoFactor, true, false)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true, WebauthnUserPresence: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorWebauthn(timeTwoFactor, true, false)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true, WebauthnUserPresence: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorWebauthn(timeTwoFactor, false, true)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true, WebauthnUserVerified: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorWebauthn(timeTwoFactor, false, true)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, Webauthn: true, WebauthnUserVerified: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorTOTP(timeTwoFactor)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, TOTP: true, Webauthn: true, WebauthnUserVerified: true},
		session.AuthenticationMethodRefs)

	session.SetTwoFactorTOTP(timeTwoFactor)

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	session, err = provider.GetSession(ctx)
	require.NoError(t, err)

	assert.Equal(t,
		oidc.AuthenticationMethodsReferences{UsernameAndPassword: true, TOTP: true, Webauthn: true, WebauthnUserVerified: true},
		session.AuthenticationMethodRefs)
}

func TestShouldDestroySessionAndWipeSessionData(t *testing.T) {
	ctx := &fasthttp.RequestCtx{}
	configuration := schema.SessionConfiguration{}
	configuration.Domain = testDomain
	configuration.Name = testName
	configuration.Expiration = testExpiration

	provider := NewProvider(configuration, nil)
	session, err := provider.GetSession(ctx)
	require.NoError(t, err)

	session.Username = testUsername
	session.AuthenticationLevel = authentication.TwoFactor

	err = provider.SaveSession(ctx, session)
	require.NoError(t, err)

	newUserSession, err := provider.GetSession(ctx)
	require.NoError(t, err)
	assert.Equal(t, testUsername, newUserSession.Username)
	assert.Equal(t, authentication.TwoFactor, newUserSession.AuthenticationLevel)

	err = provider.DestroySession(ctx)
	require.NoError(t, err)

	newUserSession, err = provider.GetSession(ctx)
	require.NoError(t, err)
	assert.Equal(t, "", newUserSession.Username)
	assert.Equal(t, authentication.NotAuthenticated, newUserSession.AuthenticationLevel)
}


text:
<#

.SYNOPSIS
	Script To Query EdData API and Create Freshdesk Clients
.DESCRIPTION
	Loop through all staff in api and check for existing accounts in Freshdesk.  If they don't exist in FD, create them.
.NOTES
	File Name	:	create-freshdesk-clients.ps1
	Author		:	Kris Hagel - hagelk@psd401.net
	Date		:	August 6, 2015
    Requires    :   Environment Variables for API Tokens
.LINK
	https://github.com/psd401
.EXAMPLE
	.\create-freshdesk-clients.ps1
	Launches script and will perform all api calls to EdData api and then all calls to Freshdesk

#>

# Get environment variables for all needed info
$EDApiToken = [Environment]::GetEnvironmentVariable("PSDApiToken","Machine")
$FDApiKey = [Environment]::GetEnvironmentVariable("FDApiKey","Machine")

# Setup api calls
$EDAuthHeader = "Bearer " + $EDApiToken
$EDHeaders = @{"Authorization" = $EDAuthHeader}
$EDBaseEndpoint = "https://api2.psd401.net/api/v1/"

$pair = "$($FDApiKey):$($FDApiKey)"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$FDHeaders = @{ Authorization = $basicAuthValue }
$FDBaseEndpoint = "http://techcentral.psd401.net/"

$FDLocationTable = @{
    "ADMINISTRATION" = "6000156909";
    "PURDY" = "6000156897";
    "HUMAN RESOURCES" = "6000156909";
    "HARBOR RIDGE" = "6000156900";
    "TRANSPORTATION" = "6000156912";
    "DISCOVERY" = "6000156893";
    "MAIL" = "6000156913";
    "EVERGREEN" = "6000079630";
    "GIG HARBOR HS" = "6000156897";
    "MINTER" = "6000156896";
    "ARTONDALE" = "6000156892";
    "TECH SUPPORT" = "6000156910";
    "HARBOR HEIGHTS" = "6000156895";
    "MAINTENANCE" = "6000156911";
    "PENINSULA HS" = "6000156907";
    "KEY PENINSULA" = "6000156901";
    "GOODMAN" = "6000156897";
    "STUDENT SVCS" = "6000246902";
    "HENDERSON BAY HS" = "6000156903";
    "KOPACHUCK" = "6000156902";
    "BUSINESS SERV" = "6000156909";
    "UDDENBERG FAC" = "6000156908";
    "VAUGHN" = "6000079630";
    "VOYAGER" = "6000156897";
    "CUSTODIAN" = "6000156911";
    "PHS POOL" = "6000156907";
}

# Make initial connection to endpoint to determine total records and limits
$EDInitialEndpoint = $EDBaseEndpoint+"employees"
$initial = Invoke-RestMethod -Uri $EDInitialEndpoint -ContentType application/json -Method GET -Headers $EDHeaders
$records = $initial.meta.total
$limit = $initial.meta.limit

<#
$FDLookupEndpoint = $FDBaseEndpoint+"contacts.json"
$FDAllContactData = Invoke-WebRequest -uri $FDLookupEndpoint -Headers $FDHeaders -Method GET -ContentType application/json | ConvertFrom-Json
$found = $FDAllContactData | Foreach-object { Get-Item("hagelk@psd401.net") }
write-host "---"
write-host $found
write-host "---"
#>

$counter = 0

#loop through all records returned to us by initial api call to make sure we have all staff
for($i=0; $i -le $records; $i = $i+$limit)
{
    #generate dynamic url for querying the api, then make the api call
    $EDEmployeeEndpoint = $EDBaseEndpoint + "employees?offset=" + $i
    $employeeData = Invoke-RestMethod -Uri $EDEmployeeEndpoint -ContentType application/json -Method GET -Headers $EDHeaders

    #loop through the returned records
    foreach ($staff in $employeeData.employee) {
        #if the staff member has an username, compare them to the freshdesk
        if ($staff.username) {
            $FDBldgId = $FDLocationTable.Get_Item($staff.buildingName)
            $fullName = $staff.lastName+", "+$staff.firstName
            $email = $staff.username+"@psd401.net"

            $FDLookupEndpoint = $FDBaseEndpoint+"contacts.json?query=email is "+$staff.username+"@psd401.net"
            $FDContactData = Invoke-WebRequest -uri $FDLookupEndpoint -Headers $FDHeaders -Method GET -ContentType application/json | ConvertFrom-Json
            $counter++
            write-host $counter
            if($FDContactData.user.email) {
                #Do a comparison of data
                if ($fullName -eq $FDContactData.user.name -and $staff.title -eq $FDContactData.user.job_title -and $FDBldgId -eq $FDContactData.user.company_id) {
                    #Do Nothing
                } else {
                    #Update contact record
                    $FDUserId = $FDContactData.user.id
                    write-host $fullName "-" $FDUserId "Needs to be updated"
                    $json = "{
                        `"user`": {
                            `"name`": `"$($fullName)`",
                            `"email`": `"$($email)`",
                            `"time_zone`": `"Pacific Time (US & Canada)`",
                            `"customer_id`": `"$($FDBldgId)`",
                            `"job_title`": `"$($staff.title)`"
                        }
                    }"
                    $FDUpdateEndpoint = $FDBaseEndpoint+"contacts/"+$FDUserId+".json"
                    Invoke-WebRequest -Uri $FDUpdateEndpoint -Body $json -ContentType application/json -Method PUT -Headers $FDHeaders
                    $counter++
                    write-host $counter

                }
            } else {
                #create contact record
                write-host $fullName "Must be created"
                $json = "{
                    `"user`": {
                        `"name`": `"$($fullName)`",
                        `"email`": `"$($email)`",
                        `"time_zone`": `"Pacific Time (US & Canada)`",
                        `"customer_id`": `"$($FDBldgId)`",
                        `"job_title`": `"$($staff.title)`"
                    }
                }"
                $FDCreateEndpoint = $FDBaseEndpoint+"contacts.json"
                Invoke-WebRequest -Uri $FDCreateEndpoint -Body $json -ContentType application/json -Method POST -Headers $FDHeaders
                $counter++
                write-host $counter

            }
        }
    }
}


text:
package org.assertj.core.error;

import org.assertj.core.internal.TestDescription;
import org.assertj.core.presentation.StandardRepresentation;
import org.junit.jupiter.api.Test;

import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;

import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.ShouldBeEqualIgnoringMinutes.shouldBeEqualIgnoringMinutes;

/**
 * Tests for <code>{@link org.assertj.core.error.ShouldBeEqualIgnoringMinutes#create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation)}</code>.
 *
 * @author Alexander Bischof
 */
public class ShouldBeEqualIgnoringMinutes_create_Test {

  private ErrorMessageFactory factory;

  @Test
  public void should_create_error_message_for_LocalTime() {

      factory = shouldBeEqualIgnoringMinutes(LocalTime.of(12, 0), LocalTime.of(12, 1));

      String message = factory.create(new TestDescription("Test"), new StandardRepresentation());
      assertThat(message).isEqualTo(format("[Test] %n" +
                                           "Expecting:%n" +
                                           "  <12:00>%n" +
                                           "to have same hour as:%n" +
                                           "  <12:01>%n" +
                                           "but had not."));
  }

  @Test
  public void should_create_error_message_for_OffsetTime() {

    factory = shouldBeEqualIgnoringMinutes(OffsetTime.of(12,0,0,0, ZoneOffset.UTC),OffsetTime.of(12,1,0,0, ZoneOffset.UTC));

    String message = factory.create(new TestDescription("Test"), new StandardRepresentation());
    assertThat(message).isEqualTo(format("[Test] %n" +
                                         "Expecting:%n" +
                                         "  <12:00Z>%n" +
                                         "to have same hour as:%n" +
                                         "  <12:01Z>%n" +
                                         "but had not."));
  }
}