text:
"use strict";

/**
 * @param {Application} application - application
 */
module.exports.controller = function (application) {

    /**
     * Create a new project - page
     */
    application.getExpress().get('/admin/projects/create/', (request, response) => {
        request.project = request.projectManager.create();

        response.render('admin/project/project.create.html.twig', {
            action: 'admin.projects'
        });
    });

    /**
     * Renders template for all projects
     *
     * @param {Object} request - expressjs request
     * @param {Object} response - expressjs response
     * @param {(string|null)} error - error message, if present     *
     * @param {(string|null)} success - success message, if present
     */
    function routeToAllProjects(request, response, error = null, success = null) {
        request.projectManager.getAllExceptLocal((_, projects) => {
            response.locals.allProjects = projects;

            request.projectManager.getAllExceptLocal((getAllError, projects) => {
                response.render('admin/project/projects.html.twig', {
                    action: 'admin.projects',
                    projects: projects,
                    projectsCount: Object.keys(projects).length,
                    success: success,
                    error: error
                });
            });
        });
    };

    /**
     * Create a new project - handler
     */
    application.getExpress().post('/admin/projects/create/', (request, response) => {
        request.project = request.projectManager.create();

         request.projectUtils.validateProjectActionCreateNewOrUpdateProject(false, (error) => {
             if (error !== null) {
                 return response.render('admin/project/project.create.html.twig', {
                     action: 'admin.projects',
                     error: error
                 });
             }

             request.projectManager.add(request.project, function (error) {
                 if (error !== null) {
                     request.logger.error(error);

                     response.render('admin/project/project.create.html.twig', {
                         action: 'admin.projects',
                         error: 'Got error. Contact your system administrator.'
                     });
                 } else {
                     request.logger.info('new project [' + request.project.getName() + '] was created');

                     return routeToAllProjects(
                         request, response, null, 'Project [' + request.project.getName() + '] was created.'
                     );
                 }
             });
         });
    });

    /**
     * Middleware to preload project if there is a projectId in the url
     */
    application.getExpress().all('/admin/projects/:projectId/*', (request, response, next) => {
        var projectId = parseInt(request.params.projectId);

        if (Number.isNaN(projectId)) {
            request.logger.info('project was requested by non-NAN id [' + projectId + ']');

            return routeToAllProjects(request, response, 'Wrong project id');
        }

        request.projectManager.getById(projectId, (error, project) => {
            if (project === null) {
                request.logger.info('non-existed project [' + projectId + '] was requested');

                return routeToAllProjects(request, response, 'Project with given id doesn\'t exist');
            }

            if (project.getUserId() != -1) {
                request.logger.info('local docker as project [' + projectId + '] was requested in admin');

                return routeToAllProjects(request, response, 'Project with given id doesn\'t exist');
            }

            request.project = project;
            return next();
        });
    });

    /**
     * View all projects
     */
    application.getExpress().get('/admin/projects/', (request, response) => {
        return routeToAllProjects(request, response);
    });

    /**
     * View/Edit project
     */
    application.getExpress().get('/admin/projects/:projectId/', (request, response) => {
        response.render('admin/project/project.html.twig', {
            action: 'admin.projects'
        });
    });

    /**
     * Handle action "update project files"
     *
     * @param {Object} request - expressjs request
     * @param {Object} response - expressjs response
     */
    function handleActionFiles(request, response) {
        request.projectUtils.validateProjectActionUpdateCerts((error) => {
            if (error === null) {
                request.projectManager.update(request.project, (error) => {
                    if (error === null) {
                        return routeToAllProjects(
                            request, response, null, 'Project [' + request.project.getName() + '] files were updated.'
                        );
                    } else {
                        return response.render('admin/project/project.html.twig', {
                            action: 'admin.projects',
                            error: 'Got error. Contact your system administrator'
                        });
                    }
                });
            } else {
                return response.render('admin/project/project.html.twig', {
                    action: 'admin.projects',
                    error: error
                });
            }
        });
    }

    /**
     * Handle action "update project info"
     *
     * @param {Object} request - expressjs request
     * @param {Object} response - expressjs response
     */
    function handleActionInfo(request, response) {
        request.projectUtils.validateProjectActionCreateNewOrUpdateProject(true, (error) => {
            if (error !== null) {
                return response.render('admin/project/project.html.twig', {
                    action: 'admin.projects',
                    error: error
                });
            }

            request.projectManager.update(request.project, function (error) {
                if (error === null) {
                    request.logger.info('project [' + request.project.getName() + '] was updated.');

                    return routeToAllProjects(
                        request, response, null, 'Project [' + request.project.getName() + '] info was updated.'
                    );
                } else {
                    request.logger.error(error);

                    return response.render('admin/project/project.html.twig', {
                        action: 'admin.projects',
                        error: 'Got error. Contact your system administrator.'
                    });
                }
            });

        });
    }

    /**
     * Update project info
     */
    application.getExpress().post('/admin/projects/:projectId/', (request, response) => {
        const   ACTION_INFO     = 'info'; // action == update project info (name, etc)
        const   ACTION_FILES    = 'files'; // action == update project files

        var action = request.body.action;

        if (typeof action === 'undefined') {
            request.logger.error('No action in the request');
            return response.render('admin/project/project.html.twig', {
                action: 'admin.projects',
                error: 'Wrong request'
            });
        }

        switch (action) {
            case ACTION_FILES:
                return handleActionFiles(request, response);
                break;

            case ACTION_INFO:
                return handleActionInfo(request, response);
                break;

            default:
                request.logger.error('Wrong action [' + action + ']');

                return response.render('admin/project/project.html.twig', {
                    action: 'admin.projects',
                    error: 'Wrong request'
                });
        }
    });

    /**
     * Delete project - page
     */
    application.getExpress().get('/admin/projects/:projectId/delete/', (request, response) => {
        response.render('admin/project/delete.html.twig', {
            action: 'admin.projects'
        });
    });

    /**
     * Delete project - handler
     */
    application.getExpress().post('/admin/projects/:projectId/delete/', (request, response) => {
        request.projectLogManager.deleteByProjectId(request.project.getId(), (error) => {
            if (error === null) {
                request.logger.info('project_log for [' + request.project.getName() + '] was deleted.');

                request.projectManager.deleteProject(request.project.getId(), (error) => {
                    if (error === null) {
                        request.logger.info('project [' + request.project.getName() + '] was deleted.');

                        return routeToAllProjects(
                            request, response, null, 'Project [' + request.project.getName() + '] was deleted.'
                        );
                    } else {
                        request.logger.error(error);

                        return routeToAllProjects(request, response, 'Got error. Contact your system administrator.');
                    }
                });
            } else {
                request.logger.error(error);

                return routeToAllProjects(request, response, 'Got error. Contact your system administrator.');
            }
        });
    });

};


text:
<?php

/**
 * Clase para recorrer los resultados de la consulta
 *
 * @category   Kumbia
 * @package    ActRecord
 */

//NAMESPACE

class ActRow implements Iterator, ArrayAccess, SeekableIterator, Countable
{

  __set()
  {

  }

  __get()
  {

  }

}

redpajama_set_name: RedPajamaGithub


text:
Please make sure all tests pass before sending your PR.

How to install dependencies
```shell
$ npm install
```

How to run the tests
```shell
$ npm test
```

Additional tests can be added to `tests/fquarterSpec.coffee`


text:
package com.wang.baseadapter.delegate;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.RequestBuilder;
import com.wang.baseadapter.ViewHolder;
import com.wang.baseadapter.model.ItemArray;
import com.wang.baseadapter.model.TypeData;

import java.util.List;

public abstract class AdapterDelegate<ViewHolder extends RecyclerView.ViewHolder> {

    /**
     * Creates the  {@link RecyclerView.ViewHolder} for the given data source item
     *
     * @param parent The ViewGroup parent of the given datasource
     * @param viewType the datasource type
     * @return The new instantiated {@link RecyclerView.ViewHolder}
     */
    public abstract ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType);

    /**
     * Called to bind the {@link RecyclerView.ViewHolder} to the item of the datas source set
     *
     * @param itemArray    The data source
     * @param position The position in the datasource
     * @param vh   The {@link RecyclerView.ViewHolder} to bind
     * @param payloads A non-null list of merged payloads. Can be empty list if requires full update.
     */
    public void onBindViewHolder(@NonNull ItemArray itemArray, @NonNull ViewHolder vh, int position, @NonNull List<Object> payloads){
        onBindViewHolder(itemArray, vh, position);
    }

    /**
     * Called to bind the {@link RecyclerView.ViewHolder} to the item of the datas source set
     *
     * @param itemArray    The data source
     * @param position The position in the datasource
     * @param vh   The {@link RecyclerView.ViewHolder} to bind
     */
    public abstract void onBindViewHolder(@NonNull ItemArray itemArray, @NonNull ViewHolder vh, int position);

    @Nullable
    public RequestBuilder<?> getPreloadRequestBuilder(@NonNull TypeData data) {
        throw new IllegalStateException("must be override");
    }

    /**
     * Called when a view created by this adapter has been recycled.
     *

     *
A view is recycled when a {@link RecyclerView.LayoutManager} decides that it no longer
     * needs to be attached to its parent {@link RecyclerView}. This can be because it has
     * fallen out of visibility or a set of cached views represented by views still
     * attached to the parent RecyclerView. If an item view has large or expensive data
     * bound to it such as large bitmaps, this may be a good place to release those
     * resources.

     *

     * RecyclerView calls this method right before clearing ViewHolder's internal data and
     * sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
     * before being recycled, you can call {@link RecyclerView.ViewHolder#getAdapterPosition()} to
     * get
     * its adapter position.
     *
     * @param vh The ViewHolder for the view being recycled
     */
    protected void onViewRecycled(@NonNull ViewHolder vh) {

    }

    /**
     * Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled
     * due to its transient state. Upon receiving this callback, Adapter can clear the
     * animation(s) that effect the View's transient state and return true so that
     * the View can be recycled. Keep in mind that the View in question is already removed from
     * the RecyclerView.
     *

     * In some cases, it is acceptable to recycle a View although it has transient state. Most
     * of the time, this is a case where the transient state will be cleared in
     * {@link RecyclerView.Adapter#onBindViewHolder(RecyclerView.ViewHolder, int)} call when View is
     * rebound to a new position.
     * For this reason, RecyclerView leaves the decision to the Adapter and uses the return
     * value of this method to decide whether the View should be recycled or not.
     *

     * Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you
     * should never receive this callback because RecyclerView keeps those Views as children
     * until their animations are complete. This callback is useful when children of the item
     * views create animations which may not be easy to implement using an {@link
     * RecyclerView.ItemAnimator}.
     *

     * You should never fix this issue by calling
     * holder.itemView.setHasTransientState(false); unless you've previously called
     * holder.itemView.setHasTransientState(true);. Each
     * View.setHasTransientState(true) call must be matched by a
     * View.setHasTransientState(false) call, otherwise, the state of the View
     * may become inconsistent. You should always prefer to end or cancel animations that are
     * triggering the transient state instead of handling it manually.
     *
     * @param vh The ViewHolder containing the View that could not be recycled due to its
     *               transient state.
     * @return True if the View should be recycled, false otherwise. Note that if this method
     * returns true, RecyclerView will ignore the transient state of
     * the View and recycle it regardless. If this method returns false,
     * RecyclerView will check the View's transient state again before giving a final decision.
     * Default implementation returns false.
     */
    protected boolean onFailedToRecycleView(@NonNull ViewHolder vh) {
        return false;
    }

    /**
     * Called when a view created by this adapter has been attached to a window.
     *

     *
This can be used as a reasonable signal that the view is about to be seen
     * by the user. If the adapter previously freed any resources in
     * {@link RecyclerView.Adapter#onViewDetachedFromWindow(RecyclerView.ViewHolder)
     * onViewDetachedFromWindow}
     * those resources should be restored here.

     *
     * @param vh Holder of the view being attached
     */
    protected void onViewAttachedToWindow(@NonNull ViewHolder vh) {
    }

    /**
     * Called when a view created by this adapter has been detached from its window.
     *

     *
Becoming detached from the window is not necessarily a permanent condition;
     * the consumer of an Adapter's views may choose to cache views offscreen while they
     * are not visible, attaching an detaching them as appropriate.

     *
     * @param vh Holder of the view being detached
     */
    protected void onViewDetachedFromWindow(@NonNull ViewHolder vh) {
    }
}


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;

// 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(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_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));
  }

  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.
  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.
  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) {
  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);

  // 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 a message loop to allow message passing into this thread.
  MessageLoop msg_loop(MessageLoop::TYPE_UI);

  // 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 = MessageLoop::TYPE_IO;
  io_thread.StartWithOptions(options);

  std::string ipc_channel_name("viewer");

  // TODO(robertshield): Figure out how to receive and append the channel ID
  // from the delegate_execute instance that launched the browser process.
  // See http://crbug.com/162474
  // ipc_channel_name.append(IPC::Channel::GenerateUniqueRandomChannelID());

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

  // In Aura mode we create an IPC channel to the browser, then ask it to
  // connect to us.
  ChromeChannelListener ui_channel_listener(&msg_loop, this);
  IPC::ChannelProxy ui_channel(ipc_channel_name,
                               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_;

  // And post the task that'll do the inner Metro message pumping to it.
  msg_loop.PostTask(FROM_HERE, base::Bind(&RunMessageLoop, dispatcher.Get()));
  msg_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.value(),
                                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::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;

  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;

  // The AURA event handling code does not handle the system key down event for
  // the Alt key if we pass in the flag EF_ALT_DOWN.
  uint32 keyboard_flags = GetKeyboardEventFlags() & ~ui::EF_ALT_DOWN;

  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;
}

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

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:
package org.teamninjaneer.simulator.locationsimulator.converter;

import java.time.Instant;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Unit tests for Function Converter.
 *
 * @author Travis.Rennemann
 */
public class FunctionConverterTest {

    private static final String DT_FORMAT = "yyyy/MM/dd,HH:mm:s.SSSz";
    private static final Long EPOCH_TIME = 231757811001L;

    public FunctionConverterTest() {
    }

    /**
     * Test of convertDt method, of class FunctionConverter.
     */
    @Test
    public void testConvertDt() {
        Instant dateTime = Instant.ofEpochMilli(EPOCH_TIME);

        String expected = "1977/05/06,09:10:11.001UTC";
        String result = FunctionConverter.convertDt(DT_FORMAT, dateTime);

        assertEquals(expected, result);
    }

    /**
     * Test of convertRand method, of class FunctionConverter.
     */
    @Test
    public void testConvertRand() {

        String result = FunctionConverter.convertRand();
        assertNotNull(result);
        System.out.println(result);

        Integer intResult = Integer.valueOf(result);
        assertTrue(intResult > 0);
    }

    /**
     * Test of convertRand method, of class FunctionConverter.
     */
    @Test
    public void testConvertRand_seedAndUpperBound() {

        String result = FunctionConverter.convertRand(10, 100);
        assertNotNull(result);
        System.out.println(result);

        Integer intResult = Integer.valueOf(result);
        assertTrue(intResult > 0 && intResult < 100);
    }

    /**
     * Test of convertRand method, of class FunctionConverter.
     */
    @Test
    public void testConvertRand_upperBound() {

        String result = FunctionConverter.convertRand(null, 100);
        assertNotNull(result);
        System.out.println(result);

        Integer intResult = Integer.valueOf(result);
        assertTrue(intResult > 0 && intResult < 100);
    }

    /**
     * Test of convertRand method, of class FunctionConverter.
     */
    @Test
    public void testConvertRand_stringParam() {

        String result = FunctionConverter.convertRand("10, 15");
        assertNotNull(result);
        System.out.println(result);

        Integer intResult = Integer.valueOf(result);
        assertTrue(intResult > 0 && intResult < 15);
    }

}