text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.Practices.ServiceLocation;

using Yarm.Extensions;
using Yarm.Functions.Extensions;
using Yarm.Functions.Formatters;
using Yarm.Models.Functions.Responses;

namespace Yarm.Functions.FunctionFactories
{
    /// <summary>
    /// This represents the base function entity.
    /// </summary>
    public abstract class FunctionBase : IFunction
    {
        private static List<string> validContentTypes = new[] { "application/json", "application/yaml" }.ToList();
        private static List<string> yamlMediaTypes = new[] { "application/x-yaml", "application/yaml", "text/yaml" }.ToList();

        private bool _disposed;

        /// <summary>
        /// Gets or sets the <see cref="ILogger"/> instance.
        /// </summary>
        public ILogger Log { get; set; }

        /// <summary>
        /// Gets or sets the service locator for the function.
        /// </summary>
        public IServiceLocator ServiceLocator { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="FunctionParameterOptions"/> instance.
        /// </summary>
        public FunctionParameterOptions ParameterOptions { protected get; set; }

        /// <summary>
        /// Invokes the function.
        /// </summary>
        /// <param name="req"><see cref="HttpRequestMessage"/> instance.</param>
        /// <returns>Returns the <see cref="HttpResponseMessage"/> instance.</returns>
        public virtual Task<HttpResponseMessage> InvokeAsync(HttpRequestMessage req)
        {
            return null;
        }

        /// <summary>
        /// Invokes the function.
        /// </summary>
        /// <param name="info"><see cref="TimerInfo"/> instance.</param>
        /// <returns>Returns the <see cref="Task"/>.</returns>
        public virtual Task InvokeAsync(TimerInfo info)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <param name="disposing">Value indicating whether to dispose managed resources or not.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (this._disposed)
            {
                return;
            }

            if (disposing)
            {
                this.ReleaseManagedResources();
            }

            this.ReleaseUnmanagedResources();

            this._disposed = true;
        }

        /// <summary>
        /// Releases managed resources during the disposing event.
        /// </summary>
        protected virtual void ReleaseManagedResources()
        {
            // Release managed resources here.
        }

        /// <summary>
        /// Releases unmanaged resources during the disposing event.
        /// </summary>
        protected virtual void ReleaseUnmanagedResources()
        {
            // Release unmanaged resources here.
        }

        /// <summary>
        /// Ensures whether the <see cref="FunctionParameterOptions"/> instance has been loaded or not.
        /// </summary>
        /// <returns>Returns <c>True</c>, if <see cref="FunctionParameterOptions"/> instance has been loaded; otherwise returns <c>False</c>.</returns>
        protected bool EnsureParameterOptionsLoaded()
        {
            return !this.ParameterOptions.IsNullOrDefault();
        }

        /// <summary>
        /// Checks whether the request contains payload or not.
        /// </summary>
        /// <param name="req">The request.</param>
        /// <returns>Returns <c>True</c>, if the request contains payload; otherwise returns <c>False</c>.</returns>
        protected async Task<bool> ContainsPayloadAsync(HttpRequestMessage req)
        {
            var content = await req.Content.ReadAsStringAsync().ConfigureAwait(false);

            return !content.IsNullOrWhiteSpace();
        }

        /// <summary>
        /// Checks whether the content type has valid content type or not.
        /// </summary>
        /// <param name="req">The request.</param>
        /// <returns>Returns <c>True</c>, if the content type has valid content type; otherwise returns <c>False</c>.</returns>
        protected bool HasValidContentType(HttpRequestMessage req)
        {
            var contentType = req.Content.Headers.ContentType.MediaType;

            return validContentTypes.ContainsEquivalent(contentType);
        }

        /// <summary>
        /// Writes an informational log message.
        /// </summary>
        /// <param name="message">Message to log.</param>
        protected void LogInformation(string message)
        {
            this.Log.Info(message);
        }

        /// <summary>
        /// Writes a warning log message.
        /// </summary>
        /// <param name="message">Message to log.</param>
        protected void LogWarning(string message)
        {
            this.Log.Warning(message);
        }

        /// <summary>
        /// Writes an error log message.
        /// </summary>
        /// <param name="message">Message to log.</param>
        protected void LogError(string message)
        {
            this.Log.Error(message);
        }

        /// <summary>
        /// Creates a 200 OK response for a request.
        /// </summary>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <param name="req">The request.</param>
        /// <param name="value">The response content.</param>
        /// <param name="mediaType">Media type.</param>
        /// <returns>The 200 OK response.</returns>
        protected HttpResponseMessage CreateOkResponse<T>(HttpRequestMessage req, T value, string mediaType = null)
        {
            return this.CreateResponse(req, HttpStatusCode.OK, value, mediaType);
        }

        /// <summary>
        /// Creates a 400 Bad Request response for a request.
        /// </summary>
        /// <param name="req">The request.</param>
        /// <param name="message">The response content.</param>
        /// <returns>The 400 Bad Request response.</returns>
        protected HttpResponseMessage CreateBadRequestResponse(HttpRequestMessage req, string message)
        {
            var errorResponse = new ErrorResponseModel
                                    {
                                        StatusCode = (int)HttpStatusCode.BadRequest,
                                        Message = message
                                    };

            return this.CreateBadRequestResponse(req, errorResponse);
        }

        /// <summary>
        /// Creates a 400 Bad Request response for a request.
        /// </summary>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <param name="req">The request.</param>
        /// <param name="value">The response content.</param>
        /// <returns>The 400 Bad Request response.</returns>
        protected HttpResponseMessage CreateBadRequestResponse<T>(HttpRequestMessage req, T value)
        {
            return this.CreateResponse(req, HttpStatusCode.BadRequest, value);
        }

        /// <summary>
        /// Creates a 404 Not Found response for a request.
        /// </summary>
        /// <param name="req">The request.</param>
        /// <param name="message">The response content.</param>
        /// <returns>The 404 Not Found response.</returns>
        protected HttpResponseMessage CreateNotFoundResponse(HttpRequestMessage req, string message)
        {
            var errorResponse = new ErrorResponseModel
                                    {
                                        StatusCode = (int)HttpStatusCode.NotFound,
                                        Message = message
                                    };

            return this.CreateNotFoundResponse(req, errorResponse);
        }

        /// <summary>
        /// Creates a 404 Not Found response for a request.
        /// </summary>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <param name="req">The request.</param>
        /// <param name="value">The response content.</param>
        /// <returns>The 404 Not Found response.</returns>
        protected HttpResponseMessage CreateNotFoundResponse<T>(HttpRequestMessage req, T value)
        {
            return this.CreateResponse(req, HttpStatusCode.NotFound, value);
        }

        /// <summary>
        /// Creates a 415 Unsupported Media Type response for a request.
        /// </summary>
        /// <param name="req">The request.</param>
        /// <param name="message">The response content.</param>
        /// <returns>The 415 Unsupported Media Type response.</returns>
        protected HttpResponseMessage CreateUnsupportedMediaTypeResponse(HttpRequestMessage req, string message)
        {
            var errorResponse = new ErrorResponseModel
                                    {
                                        StatusCode = (int)HttpStatusCode.UnsupportedMediaType,
                                        Message = message
                                    };

            return this.CreateNotFoundResponse(req, errorResponse);
        }

        /// <summary>
        /// Creates a 415 Unsupported Media Type response for a request.
        /// </summary>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <param name="req">The request.</param>
        /// <param name="value">The response content.</param>
        /// <returns>The 415 Unsupported Media Type response.</returns>
        protected HttpResponseMessage CreateUnsupportedMediaTypeResponse<T>(HttpRequestMessage req, T value)
        {
            return this.CreateResponse(req, HttpStatusCode.UnsupportedMediaType, value);
        }

        /// <summary>
        /// Creates a response for a request.
        /// </summary>
        /// <typeparam name="T">Type of value.</typeparam>
        /// <param name="req">The request.</param>
        /// <param name="statusCode">The response status code.</param>
        /// <param name="value">The response content.</param>
        /// <param name="mediaType">Media type.</param>
        /// <returns>The response.</returns>
        protected HttpResponseMessage CreateResponse<T>(HttpRequestMessage req, HttpStatusCode statusCode, T value, string mediaType = null)
        {
            var formatter = yamlMediaTypes.ContainsEquivalent(mediaType)
                                ? this.ServiceLocator.GetInstance<YamlMediaTypeFormatter>() as MediaTypeFormatter
                                : this.ServiceLocator.GetInstance<JsonMediaTypeFormatter>();

            return req.CreateResponse(statusCode, value, formatter);
        }
    }
}


text:
Model trained on 10k images and 2.5k validation images to identify various
categories of materials.

<!-- asset-path: internal -->
<!-- task: image-segmentation -->
<!-- fine-tunable: true -->
<!-- format: saved_model_2 -->
<!-- language: en -->
<!-- network-architecture: resnet -->
<!-- colab: https://colab.research.google.com/github/tensorflow/models/blob/master/official/projects/waste_identification_ml/model_inference/TFHub_saved_model_inference.ipynb -->

## Overview

CircularNet is built using Mask RCNN trained with the Resnet backbone, which is
a deep learning model for instance image segmentation. This model identifies
material types such as plastics, paper etc.

The output of the model is bounding boxes, class category, probability and
the masks.

Note: These are demo models built on limited datasets. If you're interested in
updated versions of the models, or in using models trained on specific
materials, reach out to waste-innovation-external@google.com

### Inputs

A three-channel image of variable size - the model does **NOT** support
batching. The input tensor is a `tf.float32` tensor with shape `[1, height,
width, 3]` with values in `[0.0, 1.0]`.

### Outputs

The output dictionary contains:

*   `num_detections`: a `numpy.ndarray` with only one value, the number of
    detections `[N]`.
*   `detection_scores`: a `numpy.ndarray` of shape `[1, N]` containing detection
    scores.
*   `detection_classes`: a `numpy.ndarray` of shape `[1, N]` containing
    containing detection class index from the label file.
*   `detection_masks`: a `numpy.ndarray` of shape `[1, N, 28, 28]` containing
    masks of the identified objects.
*   `detection_boxes`: a `numpy.ndarray` of shape `[1, N, 4]` containing
    bounding box coordinates in the following order: `[ymin, xmin, ymax, xmax]`.

## Example use

```
import tensorflow as tf
import tensorflow_hub as hub
hub_model = hub.load("https://tfhub.dev/google/circularnet_1/1")

# get an input size of images on which an Instance Segmentation model is trained
hub_model_fn = hub_model.signatures["serving_default"]
height=hub_model_fn.structured_input_signature[1]['inputs'].shape[1]
width = hub_model_fn.structured_input_signature[1]['inputs'].shape[2]
input_size = (height, width)

# apply pre-processing functions which were applied during training the model
image_np_cp = cv2.resize(image_np[0], input_size[::-1], interpolation = cv2.INTER_AREA)
image_np = build_inputs_for_segmentation(image_np_cp)
image_np = tf.expand_dims(image_np, axis=0)

# running inference
results = hub_model_fn(image_np)
```

redpajama_set_name: RedPajamaGithub


text:
/**
 * This package contains classes and interfaces for working with entity statuses.
 */

@SPI
@CheckReturnValue
@ParametersAreNonnullByDefault
package io.spine.server.entity.status;

import com.google.errorprone.annotations.CheckReturnValue;
import io.spine.annotation.SPI;

import javax.annotation.ParametersAreNonnullByDefault;


text:
Try this file with the following commands lines;
  example.lua --help
  example.lua -o myfile -d --compress=gzip inputfile
  example.lua --__DUMP__ -o myfile -d --compress=gzip inputfile

--]]

local cli = require "../src/cliargs"

local function print_version(key, value, altkey)
  -- this is called when the flag -v or --version is set
  if key == 'version' then
    print("cli_example.lua: version 1.2.1")
    os.exit(0)
  end
end

cli:set_name("cli_example.lua")

-- Required arguments:
  cli:add_argument("INPUT", "path to the input file")
  -- cli:add_argument("OUTPUT", "path to the output file") -- Using an alias for add_argument

-- Optional (repetitive) arguments
  -- only the last argument can be optional. Being set to maximum 3 optionals.
  cli:optarg("OUTPUT", "multiple output paths", "/dev/stdout", 3)

-- Optional parameters:
  cli:add_option("-c, --compress=FILTER", "the filter to use for compressing output: gzip, lzma, bzip2, or none", "gzip")
  cli:add_option("-o FILE", "path to output file", "/dev/stdout")

-- Flags: a flag is a boolean option. Defaults to false
  -- A flag with short-key notation only
  cli:add_flag("-d", "script will run in DEBUG mode")
  -- A flag with both the short-key and --expanded-key notations, and callback function
  cli:add_flag("-v, --version", "prints the program's version and exits", print_version)
  -- A flag with --expanded-key notation only
  cli:add_flag("--verbose", "the script output will be very verbose")
  -- A flag that can be negated using --no- as a prefix, but you'll still have
  -- to access its value without that prefix. See below for an example.
  cli:add_flag('--[no-]ice-cream', 'ice cream, or not', true)

-- Parses from _G['arg']
local args = cli:parse(arg)

if not args then
  -- something wrong happened and an error was printed
  os.exit(1)
elseif not args['ice-cream'] then
  print('kernel panic: NO ICE CREAM?!11')
  os.exit(1000)
end

-- argument parsing was successful, arguments can be found in `args`
-- upon successful parsing cliargs will delete itslef to free resources
-- for k,item in pairs(args) do print(k .. " => " .. tostring(item)) end

print("Input file: " .. args["INPUT"])
print("Output file: " .. args["o"])

if #args.OUTPUT > 0 then
  print("Additional outputs:")
  if type(args.OUTPUT) == "string" then
    args.OUTPUT = { args.OUTPUT }
  end

  for i, out in ipairs(args.OUTPUT) do
    print("  " .. i .. ". " .. out)
  end
end

if #args['c'] == 0 or args['c'] == 'none' then
  print("Won't be compressing")
else
  print("Compressing using " .. args['c'])
end

if args['ice-cream'] then
  print('And, one ice cream for you.')
end


text: Rails.application.config.session_store :cookie_store, key: '_brassica_session'


text:
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";

class Item {
    firstName: string;
    lastName: string;
    dateOfBirth: string;
    gpa: string;
}

@Injectable()
export class DataService {
    apiRoot: string = 'http://localhost:4577/api/Data';

    constructor(private httpClient: Http) {
    }

    get(): Observable<Response> {
        return this.httpClient.get(this.apiRoot);
    }

    insert(model: Item): Observable<Response> {
      return this.httpClient.post(this.apiRoot, model);
    }
}


text:
require_relative '../models/init'

class LinkController < LinkShare

  # Create a dataset
  links = DB[:links]

  get '/' do
    @links = Link.all
    erb :links
  end

  get '/form' do
    erb :form
  end

  post '/add' do
    @fullurl = params[:fullurl]
    @shorturl = params[:shorturl]
    @title = params[:title]
    @description = params[:description]
    @originalposter = params[:originalposter]
    @userid = params[:userid]

    links.insert(:fullurl => @fullurl, :shorturl => @shorturl, :title => @title, :description => @description, :originalposter => @originalposter, :creation_date => Date.today, :userid => @userid )
  end
end


text:
__all__ = [
            'Calendar',
            'Date',
            'EnumSet',
            'GregorianCalendar'
          ]

from .Calendar import Calendar
from .Date import Date
from .EnumSet import EnumSet
from .GregorianCalendar import GregorianCalendar


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.Storage.Streams;
using System.Net.Http;
using Windows.UI.Xaml.Media.Imaging;
using Octokit;

namespace Grind
{
    class GitHubAPI
    {
        public string username = "";
        private GitHubClient github;
        private Octokit.User githubUser;
        public GitHubAPI(string usr, string pass)
        {
            username = usr;
            github = new GitHubClient(new ProductHeaderValue("Grind"));
            var basicAuth = new Credentials(usr, pass);
            github.Credentials = basicAuth;
            initGitHub();
        }

        private async void initGitHub()
        {
            try
            {
                githubUser = await github.User.Get(username);

            }
            catch
            {
            }
        }

        public async Task<int> getUsersPublicRepos()
        {
            if (githubUser != null)
            {
                return githubUser.PublicRepos;
            }
            else
            {
                githubUser = await github.User.Get(username);
                return githubUser.PublicRepos;
            }

        }

        public async Task<BitmapImage> getUserImage()
        {
            if (githubUser != null)
            {
                var httpClient = new HttpClient();
                var contentBytes = await httpClient.GetByteArrayAsync(githubUser.AvatarUrl);
                var ims = new InMemoryRandomAccessStream();
                var dataWriter = new DataWriter(ims);
                dataWriter.WriteBytes(contentBytes);
                await dataWriter.StoreAsync();
                ims.Seek(0);

                var bitmap = new BitmapImage();
                bitmap.SetSource(ims);
                return bitmap;
            }
            else
            {
                githubUser = await github.User.Get(username);
                var httpClient = new HttpClient();
                var contentBytes = await httpClient.GetByteArrayAsync(githubUser.AvatarUrl);
                var ims = new InMemoryRandomAccessStream();
                var dataWriter = new DataWriter(ims);
                dataWriter.WriteBytes(contentBytes);
                await dataWriter.StoreAsync();
                ims.Seek(0);

                var bitmap = new BitmapImage();
                bitmap.SetSource(ims);
                return bitmap;
            }

        }

        public async Task<string> getUserFollowing() {
            if (githubUser != null)
            {
                return githubUser.Following.ToString();
            }
            else
            {
                githubUser = await github.User.Get(username);
                return githubUser.Following.ToString();
            }
        }

        public async Task<string> getUserFollowers()
        {
            if (githubUser != null)
            {
                return githubUser.Followers.ToString();
            }
            else
            {
                githubUser = await github.User.Get(username);
                return githubUser.Followers.ToString();
            }
        }

        public async Task<string> getUserRepoCount()
        {
            if (githubUser != null)
            {
                return (githubUser.PublicRepos + githubUser.TotalPrivateRepos).ToString();
            }
            else
            {
                githubUser = await github.User.Get(username);
                return (githubUser.PublicRepos + githubUser.TotalPrivateRepos).ToString();
            }

        }
    }
}


text:
package com.vaadin.shared.ui.button;

import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.communication.ServerRpc;

/**
 * RPC interface for calls from client to server.
 *
 * @since 7.0
 */
public interface ButtonServerRpc extends ServerRpc {
    /**
     * Button click event.
     *
     * @param mouseEventDetails
     *            serialized mouse event details
     */
    public void click(MouseEventDetails mouseEventDetails);

    /**
     * Indicate to the server that the client has disabled the button as a
     * result of a click.
     */
    public void disableOnClick();
}


text:
function handle=plotu(varargin)
%PLOT Plots value of the control action
%
% ---------------------------------------------------------------------------
% DESCRIPTION
% ---------------------------------------------------------------------------
% Plots value of the PWA control law with respect to a polyhedral partition
%
% NOTE: this function only supports explicit controllers!
%
% USAGE:
%   plotu(ctrl)
%   plotu(ctrl, uind)
%   plotu(ctrl, Options)
%
% ---------------------------------------------------------------------------
% INPUT
% ---------------------------------------------------------------------------
% ctrl                    - Explicit controller (MPTCTRL object)
% uind                    - Which output to plot (for MIMO systems)
% Options.extreme_solver  - Which method to use for vertex enumeration
%                           (see 'help extreme')
% Options.lpsolver        - LP solver to be used
% Options.abs_tol         - absolute tolerance
% Options.newfigure       - If set to 1, opens a new figure window
% Options.verbose         - Level of verbosity
% Options.showPn          - If set to 1, plots on polyhedral sets Pn,
%                           (default: 0)
%
% Note: If Options is missing or some of the fields are not defined, the default
%       values from mptOptions will be used
%
% ---------------------------------------------------------------------------
% OUTPUT
% ---------------------------------------------------------------------------
% handle       - handle to the graph
%
% see also MPT_PLOTU, MPT_PLOTPWA
%

% Copyright is with the following author(s):
%
% (C) 2005 Michal Kvasnica, Automatic Control Laboratory, ETH Zurich,
%          kvasnica@control.ee.ethz.ch

% ---------------------------------------------------------------------------
% Legal note:
%          This program is free software; you can redistribute it and/or
%          modify it under the terms of the GNU General Public
%          License as published by the Free Software Foundation; either
%          version 2.1 of the License, or (at your option) any later version.
%
%          This program is distributed in the hope that it will be useful,
%          but WITHOUT ANY WARRANTY; without even the implied warranty of
%          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%          General Public License for more details.
%
%          You should have received a copy of the GNU General Public
%          License along with this library; if not, write to the
%          Free Software Foundation, Inc.,
%          59 Temple Place, Suite 330,
%          Boston, MA  02111-1307  USA
%
% ---------------------------------------------------------------------------

error(nargchk(1,3,nargin));

try
    handle = mpt_plotU(varargin{:});
catch
    rethrow(lasterror);
end
if nargout < 1,
    clear handle
end


text:
#include "modules/perception/camera/lib/obstacle/tracker/omt/omt_obstacle_tracker.h"

#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "gflags/gflags.h"

#include "modules/perception/base/box.h"
#include "modules/perception/base/distortion_model.h"
#include "modules/perception/base/object.h"
#include "modules/perception/base/object_types.h"
#include "modules/perception/camera/common/camera_frame.h"
#include "modules/perception/camera/common/object_template_manager.h"
#include "modules/perception/camera/lib/interface/base_obstacle_detector.h"
#include "modules/perception/camera/lib/interface/base_obstacle_tracker.h"
#include "modules/perception/common/geometry/common.h"
#include "modules/perception/common/io/io_util.h"

namespace apollo {
namespace perception {
namespace camera {

DEFINE_string(data_root,
              "/apollo/modules/perception/testdata/"
              "camera/lib/obstacle/tracker/omt/test_fusion_data",
              "root dir of images");
DEFINE_int32(max_img_num, 10, "max length of test images");
DEFINE_string(narrow_name, "narrow", "type of camera for projecting");
DEFINE_string(obstacle_name, "obstacle", "type of camera to be peojected");
DEFINE_string(image_root,
              "/apollo/modules/perception/testdata/"
              "camera/lib/obstacle/tracker/omt/images",
              "root dir of images");
DEFINE_int32(feature_length, 576, "size of feature");
DEFINE_string(base_camera_name, "onsemi_obstacle", "camera to be peojected");
DEFINE_string(sensor_name, "onsemi_obstacle,onsemi_narrow", "camera to use");
DEFINE_string(test_list, "test.txt", "exe image list");
DEFINE_double(camera_fps, 15, "camera_fps");
DEFINE_string(image_ext, ".jpg", "extension of image name");
DEFINE_string(image_color, "bgr", "color space of image");

int read_detections(const std::string &path, const int &feature_dim,
                    const std::string &camera_name, CameraFrame *frame) {
  const TemplateMap &kMinTemplateHWL =
      ObjectTemplateManager::Instance()->MinTemplateHWL();

  std::ifstream fin(path);
  if (!fin.is_open()) {
    AERROR << "Cannot open : " << path;
    return -1;
  }
  int frame_num = -1;
  int det_count = 0;

  int feature_size = feature_dim;
  fin >> frame_num >> det_count;
  frame->frame_id = frame_num;
  frame->track_feature_blob.reset(new base::Blob<float>);
  (frame->track_feature_blob)->Reshape({det_count, feature_size});
  float x = 0.0f;
  float y = 0.0f;
  float width = 0.0f;
  float height = 0.0f;
  float feature = 0.0f;
  float score = 0.0f;
  frame->detected_objects.clear();
  for (int i = 0; i < det_count; ++i) {
    fin >> x >> y >> width >> height >> score;
    base::BBox2DF bbox(x, y, x + width, y + height);
    base::ObjectPtr object(new base::Object);
    object->camera_supplement.box = bbox;
    object->camera_supplement.sensor_name = camera_name;
    object->sub_type = base::ObjectSubType::CAR;
    object->type = base::ObjectType::VEHICLE;
    object->size(0) = kMinTemplateHWL.at(base::ObjectSubType::CAR).at(2);
    object->size(1) = kMinTemplateHWL.at(base::ObjectSubType::CAR).at(1);
    object->size(2) = kMinTemplateHWL.at(base::ObjectSubType::CAR).at(0);
    float *data =
        frame->track_feature_blob->mutable_cpu_data() + i * feature_size;
    for (int j = 0; j < feature_size; j++) {
      fin >> feature;
      *data = feature;
      ++data;
    }
    frame->detected_objects.push_back(object);
  }
  return 0;
}

int write_track_imgs(const std::string &out_path, const cv::Mat &frame,
                     const std::vector<base::ObjectPtr> &tracked_objects) {
  cv::Mat image_mat_src = frame.clone();
  for (auto &visual_object : tracked_objects) {
    cv::Rect rect(visual_object->camera_supplement.box.xmin,
                  visual_object->camera_supplement.box.ymin,
                  visual_object->camera_supplement.box.xmax -
                      visual_object->camera_supplement.box.xmin,
                  visual_object->camera_supplement.box.ymax -
                      visual_object->camera_supplement.box.ymin);
    cv::rectangle(image_mat_src, rect, cv::Scalar(0, 255, 0), 2);
    cv::Point txt_pos;
    txt_pos.x = 0.5 * (visual_object->camera_supplement.box.xmin +
                       visual_object->camera_supplement.box.xmax);
    txt_pos.y = 0.5 * (visual_object->camera_supplement.box.ymin +
                       visual_object->camera_supplement.box.ymax);
    cv::putText(image_mat_src, std::to_string(visual_object->track_id), txt_pos,
                cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(0, 0, 255), 2);
  }
  cv::imwrite(out_path, image_mat_src);
  return 0;
}

// @description: load camera extrinsics from yaml file
bool LoadExtrinsics(const std::string &yaml_file,
                    Eigen::Matrix4d *camera_extrinsic) {
  if (!apollo::cyber::common::PathExists(yaml_file)) {
    AINFO << yaml_file << " not exist!";
    return false;
  }
  YAML::Node node = YAML::LoadFile(yaml_file);
  double qw = 0.0;
  double qx = 0.0;
  double qy = 0.0;
  double qz = 0.0;
  double tx = 0.0;
  double ty = 0.0;
  double tz = 0.0;
  try {
    if (node.IsNull()) {
      AINFO << "Load " << yaml_file << " failed! please check!";
      return false;
    }
    qw = node["transform"]["rotation"]["w"].as<double>();
    qx = node["transform"]["rotation"]["x"].as<double>();
    qy = node["transform"]["rotation"]["y"].as<double>();
    qz = node["transform"]["rotation"]["z"].as<double>();
    tx = node["transform"]["translation"]["x"].as<double>();
    ty = node["transform"]["translation"]["y"].as<double>();
    tz = node["transform"]["translation"]["z"].as<double>();
  } catch (YAML::InvalidNode &in) {
    AERROR << "load camera extrisic file " << yaml_file
           << " with error, YAML::InvalidNode exception";
    return false;
  } catch (YAML::TypedBadConversion<double> &bc) {
    AERROR << "load camera extrisic file " << yaml_file
           << " with error, YAML::TypedBadConversion exception";
    return false;
  } catch (YAML::Exception &e) {
    AERROR << "load camera extrisic file " << yaml_file
           << " with error, YAML exception:" << e.what();
    return false;
  }
  camera_extrinsic->setConstant(0);
  Eigen::Quaterniond q;
  q.x() = qx;
  q.y() = qy;
  q.z() = qz;
  q.w() = qw;
  (*camera_extrinsic).block<3, 3>(0, 0) = q.normalized().toRotationMatrix();
  (*camera_extrinsic)(0, 3) = tx;
  (*camera_extrinsic)(1, 3) = ty;
  (*camera_extrinsic)(2, 3) = tz;
  (*camera_extrinsic)(3, 3) = 1;
  return true;
}

// @description: get project matrix
bool GetProjectMatrix(
    const std::string &camera_name,
    const std::map<std::string, Eigen::Matrix4d> &extrinsic_map,
    const std::map<std::string, Eigen::Matrix3f> &intrinsic_map,
    Eigen::Matrix3d *project_matrix, double *pitch_diff = nullptr) {
  std::string base_camera_name = FLAGS_base_camera_name;
  if (camera_name == base_camera_name) {
    *project_matrix = Eigen::Matrix3d::Identity();
    return true;
  }

  *project_matrix =
      intrinsic_map.at(base_camera_name).cast<double>() *
      extrinsic_map.at(base_camera_name).block<3, 3>(0, 0).inverse() *
      extrinsic_map.at(camera_name).block<3, 3>(0, 0) *
      intrinsic_map.at(camera_name).cast<double>().inverse();
  // extract the pitch_diff = pitch_narrow - pitch_obstacle
  if (pitch_diff != nullptr) {
    Eigen::Vector3d euler =
        (extrinsic_map.at(base_camera_name).block<3, 3>(0, 0).inverse() *
         extrinsic_map.at(camera_name).block<3, 3>(0, 0))
            .eulerAngles(0, 1, 2);
    *pitch_diff = euler(0);
    AINFO << "pitch diff: " << *pitch_diff;
  }
  return true;
}

// @description: modified from common::LoadBrownCameraIntrinsic
// the original funciton return by BrownCameraDistortionModel class, but
// intrinsic_parm_ is a protected filed, cannot get directly
bool LoadCameraIntrinsics(const std::string &yaml_file,
                          Eigen::Matrix3f *camera_intrinsic) {
  if (!apollo::cyber::common::PathExists(yaml_file)) {
    AINFO << yaml_file << " not exist!";
    return false;
  }
  YAML::Node node = YAML::LoadFile(yaml_file);
  if (node.IsNull()) {
    AINFO << "Load " << yaml_file << " failed! please check!";
    return false;
  }
  try {
    for (int i = 0; i < static_cast<int>(node["K"].size()); ++i) {
      (*camera_intrinsic)(i / 3, i % 3) = node["K"][i].as<float>();
    }
  } catch (YAML::Exception &e) {
    AERROR << "load camera extrisic file " << yaml_file
           << " with error, YAML exception: " << e.what();
    return false;
  }
  return true;
}

TEST(FusionObstacleTrackerTest, FusionObstacleTracker_test) {
  // Init object template
  ObjectTemplateManagerInitOptions object_template_init_options;
  object_template_init_options.root_dir =
      "/apollo/modules/perception/testdata/"
      "camera/app/data/perception/camera/common/object_template/";
  object_template_init_options.conf_file = "object_template.pt";
  CHECK(ObjectTemplateManager::Instance()->Init(object_template_init_options));

  // Init camera list
  std::vector<std::string> camera_names;
  apollo::common::util::Split(FLAGS_sensor_name, ',', &camera_names);
  // Init data provider
  DataProvider::InitOptions data_options;
  data_options.image_height = 1080;
  data_options.image_width = 1920;
  data_options.do_undistortion = false;
  data_options.device_id = 0;
  std::map<std::string, DataProvider *> name_provider_map;

  std::vector<DataProvider> data_providers(camera_names.size());

  for (int i = 0; i < camera_names.size(); i++) {
    data_options.sensor_name = camera_names[i];
    CHECK(data_providers[i].Init(data_options));
    name_provider_map.insert(std::pair<std::string, DataProvider *>(
        camera_names[i], &data_providers[i]));
    AINFO << "Init data_provider for " << camera_names[i];
  }

  // Init extrinsic/intrinsic
  std::map<std::string, Eigen::Matrix4d> extrinsic_map;
  std::map<std::string, Eigen::Matrix3f> intrinsic_map;
  for (int i = 0; i < camera_names.size(); i++) {
    Eigen::Matrix3f intrinsic;
    ASSERT_TRUE(LoadCameraIntrinsics(
        FLAGS_data_root + "/params/" + camera_names[i] + "_intrinsics.yaml",
        &intrinsic));
    intrinsic_map[camera_names[i]] = intrinsic;
    Eigen::Matrix4d extrinsic;
    ASSERT_TRUE(LoadExtrinsics(
        FLAGS_data_root + "/params/" + camera_names[i] + "_extrinsics.yaml",
        &extrinsic));
    extrinsic_map[camera_names[i]] = extrinsic;
  }

  inference::CudaUtil::set_device_id(0);
  // init tracker
  ObstacleTrackerInitOptions init_options;
  init_options.root_dir =
      "/apollo/modules/perception/testdata/"
      "camera/lib/obstacle/tracker/omt/data/models/"
      "omt_obstacle_tracker";
  init_options.conf_file = "config.pt";
  init_options.image_height = 1080;
  init_options.image_width = 1920;
  std::unique_ptr<BaseObstacleTracker> camera_tracker(
      BaseObstacleTrackerRegisterer::GetInstanceByName("OMTObstacleTracker"));
  ASSERT_TRUE(camera_tracker->Init(init_options));
  EXPECT_EQ("OMTObstacleTracker", camera_tracker->Name());

  // read gt
  std::string filename = FLAGS_data_root + "/det_gt.txt";
  std::ifstream fin_gt(filename);
  ASSERT_TRUE(fin_gt.is_open());
  std::vector<std::vector<base::CameraObjectSupplement>> det_gts;
  std::string image_name;
  int det_count = 0;
  while (fin_gt >> image_name >> det_count) {
    std::vector<base::CameraObjectSupplement> bboxs;
    base::CameraObjectSupplement bbox;
    float x = 0.0f;
    float y = 0.0f;
    float width = 0.0f;
    float height = 0.0f;
    int id = 0;
    for (int i = 0; i < det_count; ++i) {
      fin_gt >> x >> y >> width >> height >> id;
      base::BBox2DF box(x, y, x + width, y + height);
      bbox.box = box;
      bbox.local_track_id = id;
      bboxs.push_back(bbox);
    }
    det_gts.push_back(bboxs);
  }

  std::vector<std::vector<int>> tracked_index(det_gts.size());
  std::vector<std::vector<base::CameraObjectSupplement>> tracked_results(
      det_gts.size());
  std::vector<CameraFrame> frames(det_gts.size());
  std::string line;
  std::string camera_name;
  int frame_num = 0;

  // Init input list
  std::ifstream fin;
  filename = FLAGS_data_root + "/" + FLAGS_test_list;
  fin.open(filename, std::ifstream::in);
  ASSERT_TRUE(fin.is_open());
  while (fin >> line) {
    std::vector<std::string> temp_strs;
    apollo::common::util::Split(line, '/', &temp_strs);
    if (temp_strs.size() != 2) {
      AERROR << "invaid format in " << FLAGS_test_list;
    }
    camera_name = temp_strs[0];
    image_name = temp_strs[1];

    AINFO << "image: " << image_name << " camera_name:" << camera_name;
    std::string image_path = FLAGS_image_root + "/" + camera_name + "/" +
                             image_name + FLAGS_image_ext;
    CameraFrame &frame = frames[frame_num];

    // read detections from txt
    std::string filename = FLAGS_data_root + "/detection_feature/" +
                           std::to_string(frame_num) + ".txt";
    read_detections(filename, FLAGS_feature_length, camera_name, &frame);
    AINFO << "Frame " << frame_num << " has " << frame.detected_objects.size()
          << " detection objects";
    frame.frame_id = frame_num;
    std::stringstream ss(image_name);
    frame.timestamp = 0.0;
    ss >> frame.timestamp;
    frame.timestamp *= 1e-9;
    AINFO << "Timestamp: " << frame.timestamp;
    Eigen::Matrix3d project_matrix;
    double pitch_diff = 0.0;

    ASSERT_TRUE(GetProjectMatrix(camera_name, extrinsic_map, intrinsic_map,
                                 &project_matrix, &pitch_diff));
    frame.project_matrix = project_matrix;
    frame.data_provider = name_provider_map.at(camera_name);
    AINFO << "Project Matrix: \n" << frame.project_matrix;
    ASSERT_TRUE(camera_tracker->Predict(ObstacleTrackerOptions(), &frame));
    ASSERT_TRUE(camera_tracker->Associate2D(ObstacleTrackerOptions(), &frame));
    ASSERT_TRUE(camera_tracker->Associate3D(ObstacleTrackerOptions(), &frame));
    ASSERT_TRUE(camera_tracker->Track(ObstacleTrackerOptions(), &frame));
    AINFO << "Frame " << frame_num
          << " tracked object size: " << frame.tracked_objects.size();
    for (auto &bbox_gt : det_gts[frame_num]) {
      int id = -1;
      float max_iou = 0.0f;
      Eigen::Matrix<double, 3, 1> center0, size0;
      center0[0] = bbox_gt.box.Center().x;
      size0[0] = bbox_gt.box.xmax - bbox_gt.box.xmin;
      center0[1] = bbox_gt.box.Center().y;
      size0[1] = bbox_gt.box.ymax - bbox_gt.box.ymin;
      base::CameraObjectSupplement bbox;
      for (int i = 0; i < frames[frame_num].tracked_objects.size(); i++) {
        Eigen::Matrix<double, 3, 1> center1, size1;
        base::BBox2DF temp_box;
        temp_box = frames[frame_num].tracked_objects[i]->camera_supplement.box;
        center1[0] = temp_box.Center().x;
        size1[0] = temp_box.xmax - temp_box.xmin;
        center1[1] = temp_box.Center().y;
        size1[1] = temp_box.ymax - temp_box.ymin;
        float iou = common::CalculateIou2DXY(center0, size0, center1, size1);
        AINFO << "IOU is :" << iou;
        if (iou > max_iou) {
          max_iou = iou;
          id = i;
          bbox.local_track_id = frames[frame_num].tracked_objects[i]->track_id;
        }
      }
      if (frame_num >= dynamic_cast<OMTObstacleTracker *>(camera_tracker.get())
                           ->omt_param_.target_param()
                           .tracked_life()) {
        ASSERT_GE(max_iou, 0.5);
      }
      tracked_index[frame_num].push_back(id);
      tracked_results[frame_num].push_back(bbox);
    }
    ++frame_num;
  }
  std::vector<int> ids(2, -100);
  for (frame_num = dynamic_cast<OMTObstacleTracker *>(camera_tracker.get())
                       ->omt_param_.target_param()
                       .tracked_life();
       frame_num < det_gts.size(); ++frame_num) {
    ASSERT_GE(tracked_results[frame_num].size(), 1);
    for (int i = 0; i < det_gts[frame_num].size(); ++i) {
      if (ids[i] < -50) {
        ids[i] = det_gts[frame_num][i].local_track_id -
                 tracked_results[frame_num][i].local_track_id;
      } else {
        ASSERT_EQ(ids[i], det_gts[frame_num][i].local_track_id -
                              tracked_results[frame_num][i].local_track_id);
      }
    }
  }
}

}  // namespace camera
}  // namespace perception
}  // namespace apollo


text:
package com.lovejjfg.powerrecycle;

import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.lovejjfg.powerrecycle.annotation.LoadState;
import com.lovejjfg.powerrecycle.holder.AbsBottomViewHolder;
import com.lovejjfg.powerrecycle.holder.PowerHolder;
import com.lovejjfg.powerrecycle.manager.FixedGridLayoutManager;
import java.util.List;

/**
 * Created by Joe on 2016-07-26
 * Email: lovejjfg@gmail.com
 */
public interface AdapterLoader<T> {

    /**
     * state about load more..
     */
    int STATE_LOADING = 1;
    int STATE_LASTED = 2;
    int STATE_ERROR = 3;

    int TYPE_BOTTOM = 0x80000000;
    int TYPE_EMPTY = 0x80000001;
    int TYPE_ERROR = 0x80000010;

    String PAYLOAD_REFRESH_SELECT = "SelectPowerAdapter$refresh_select";
    String PAYLOAD_REFRESH_BOTTOM = "PowerAdapter$refresh_bottom";

    /**
     * This method should be called  when you load more !
     *
     * @param holder the current holder.
     * @param loadState the current state.
     */
    void onBottomViewHolderBind(@NonNull AbsBottomViewHolder holder,
        @NonNull OnLoadMoreListener listener,
        @LoadState int loadState);

    /**
     * If you want to create the specified bottom layout,you must call this method to add your specified layout !
     * consider to use {@link AdapterLoader#createLoadMoreView(ViewGroup)}
     *
     * @param viewRes the specified bottom view layout res
     */
    @Deprecated
    void setLoadMoreView(@LayoutRes int viewRes);

    @Nullable
    View createLoadMoreView(@NonNull ViewGroup parent);

    /**
     * consider to use {@link AdapterLoader#createEmptyView(ViewGroup)}
     *
     * @param emptyView the emptyView to show
     */
    @Deprecated
    void setEmptyView(@NonNull View emptyView);

    /**
     * create the Empty
     *  LayoutInflater.from(parent.getContext()).inflate(R.layout.xxx, parent, false);
     */
    @Nullable
    View createEmptyView(@NonNull ViewGroup parent);

    /**
     * consider to use {@link AdapterLoader#createErrorView(ViewGroup)}
     *
     * @param errorView the errorView to show
     */
    @Deprecated
    void setErrorView(@NonNull View errorView);

    @Nullable
    View createErrorView(@NonNull ViewGroup parent);

    /**
     * show the empty view when data is empty.
     */
    void showEmpty();

    /**
     * show the error view when load data error.
     *
     * @param force true would show the error view don't care there was data before.false would care about.
     */
    void showError(boolean force);

    /**
     * If you want to create the specified bottom layout ,you should implements this method to create your own
     * bottomViewHolder
     *
     * @param loadMore whether is loadingMore or not..
     */
    @Nullable
    AbsBottomViewHolder onBottomViewHolderCreate(@NonNull View loadMore);

    /**
     * {@link PowerAdapter} through this method to known whether there is more data or nor.
     *
     * @return true if there is more data,  otherwise false.
     */
    boolean isHasMore();

    /**
     * refresh the bottom holder state ,this method is always called from the {@link LoadMoreScrollListener}
     */
    void updateLoadingMore();

    void loadMoreError();

    /**
     * call this method to set whether there is support loadmore or not.
     *
     * @param loadMore true: support load more false: not show load more anymore
     */
    void enableLoadMore(boolean loadMore);

    boolean isEnableLoadMore();

    /**
     * Called by RecyclerView to display the error view.
     */
    void onErrorHolderBind(@NonNull PowerHolder<T> holder);

    /**
     * Called by RecyclerView to display the empty view.
     */
    void onEmptyHolderBind(@NonNull PowerHolder<T> holder);

    /**
     * You can call this method to add data to RecycleView,if you want to append data,you should call
     * {@link #appendList(List)}, Maybe You should call setTotalCount() before setList() .
     *
     * @param data the data you want to add
     */
    void setList(@NonNull List<T> data);

    /**
     * clear current data.
     */
    void clearList();

    /**
     * clear current data.
     */
    void clearList(boolean notify);

    /**
     * @param data the data you want to add.
     */
    void appendList(@NonNull List<T> data);

    /**
     * insert the new list data within the start Position.
     *
     * @param data new list to insert
     * @param startPos the start position
     */
    void insertList(@NonNull List<T> data, int startPos);

    /**
     * check the position is illegal.
     *
     * @return true the position is out of [0,list.size()-1] ,else legal.
     */
    boolean checkIllegalPosition(int position);

    /**
     * remove the specified position in the list. If this method throw RecyclerView Exception when you delete the
     * last one.
     * consider about using the {@link com.lovejjfg.powerrecycle.manager.FixedLinearLayoutManager} or
     * {@link FixedGridLayoutManager} to avoid crash when you want to delete the lasted item.
     *
     * @param position he specified position to remove
     * @return if successful return the removed object,otherwise null
     */
    @Nullable
    T removeItem(int position);

    /**
     * call this method to update the item Holder's itemView.
     *
     * @return true find the item in current list, false otherwise.
     */
    boolean updateItem(@NonNull T item);

    /**
     * call this method to update the item Holder's itemView.
     *
     * @return true find the item in current list, false otherwise.
     */
    boolean updateItem(@NonNull T item, @Nullable Object payload);

    /**
     * get the data of list in this RecyclerView.
     * return the data in specified position, or null.
     *
     * @param position the specified position
     */
    @Nullable
    T getItem(int position);

    /**
     * remove the specified position in the list.
     *
     * @param position he specified position to remove
     */
    void insertItem(int position, @NonNull T item);

    /**
     * @param position the current pos .
     * @return the current Type.
     */
    int getItemViewTypes(int position);

    /**
     * Called by RecyclerView to display the data at the specified position. This method
     * should update the contents of the PowerHolder#itemView to reflect the item at
     * the given position.
     *
     * @param holder current holder.
     * @param position current pos.
     */
    void onViewHolderBind(@NonNull PowerHolder<T> holder, int position);

    /**
     * Called by RecyclerView to display the data at the specified position. This method
     * should update the contents of the PowerHolder#itemView to reflect the item at
     * the given position.
     *
     * @param holder The ViewHolder which should be updated to represent the contents of the
     * item at the given position in the data set.
     * @param position The position of the item within the adapter's data set.
     * @param payloads A non-null list of merged payloads. Can be empty list if requires full
     * update.
     */
    void onViewHolderBind(@NonNull PowerHolder<T> holder, int position, @NonNull List<Object> payloads);

    /**
     * Called when RecyclerView needs a new {@link PowerHolder} of the given type to represent
     * an item.
     *

     * This new ViewHolder should be constructed with a new View that can represent the items
     * of the given type. You can either create a new View manually or inflate it from an XML
     * layout file.
     *

     * The new ViewHolder will be used to display items of the adapter using
     * {@link #onViewHolderBind(PowerHolder, int, List)} (ViewHolder, int, List)}. Since it will be re-used to display
     * different items in the data set, it is a good idea to cache references to sub views of
     * the View to avoid unnecessary {@link View#findViewById(int)} calls.
     *
     * @param parent The ViewGroup into which the new View will be added after it is bound to
     * an adapter position.
     * @param viewType The view type of the new View.
     * @return A new ViewHolder that holds a View of the given view type.
     */
    PowerHolder<T> onViewHolderCreate(@NonNull ViewGroup parent, int viewType);

    /**
     * Return the current size about {@link PowerAdapter#list}.
     *
     * @return current list size!
     */
    int getItemRealCount();

    /**
     * handle the holder itemview click.
     *
     * @param holder the holder that click
     * @param position the position of holder in RecyclerView
     * @param item the data of holder.
     */
    void performClick(@NonNull PowerHolder<T> holder, int position, @NonNull T item);

    /**
     * handle the holder itemview long click.
     *
     * @param holder the holder that click
     * @param position the position of holder in RecyclerView
     * @param item the data of holder.
     */
    boolean performLongClick(@NonNull PowerHolder<T> holder, int position, @NonNull T item);

    /**
     * call this method after init RecyclerView (set LayoutManager at first).
     *
Deprecated in v2.0.0 ,you just need to  call recyclerView.setAdapter() as usually. But you should
     * always setup LayoutManager at first.

     */
    @Deprecated
    void attachRecyclerView(@NonNull RecyclerView recyclerView);

    /**
     * call this method to get the first position of the viewType
     *
     * @param viewType the viewType you set ,default is 0
     * @return the index of list
     */
    int findFirstPositionOfType(int viewType);

    /**
     * call this method to get the first position of the viewType start with the offsetPosition end to list end.
     *
     * @param viewType the viewType you set ,default is 0
     * @param offsetPosition the position to offset.
     * @return the index of list
     */
    int findFirstPositionOfType(int viewType, int offsetPosition);

    /**
     * call this method to get the last position of the viewType
     *
     * @param viewType the viewType you set ,default is 0
     * @return the index of list
     */
    int findLastPositionOfType(int viewType);

    /**
     * call this method to get the last position of the viewType start with the offsetPosition end to 0.
     *
     * @param viewType the viewType you set ,default is 0
     * @param offsetPosition the position to offset.
     * @return the index of list
     */
    int findLastPositionOfType(int viewType, int offsetPosition);

    /**
     * Register a callback to be invoked when an item in this RecyclerView has
     * been clicked.
     *
     * @param listener The callback that will be invoked.
     */
    void setOnItemClickListener(@Nullable OnItemClickListener<T> listener);

    /**
     * Interface definition for a callback to be invoked when an item in this
     * Adapter has been clicked.
     */
    interface OnItemClickListener<T> {
        /**
         * Callback method to be invoked when an item in this RecyclerView has
         * been clicked.
         *

         * Implementers can call getItemAtPosition(position) if they need
         * to access the data associated with the selected item.
         *
         * @param holder The holder within the RecyclerView that was clicked
         * @param position The position of the view in the adapter.
         * @param item The data of holder that bind.
         */
        void onItemClick(@NonNull PowerHolder<T> holder, int position, @NonNull T item);
    }

    /**
     * Register a callback to be invoked when an item in this RecyclerView has
     * been long clicked.
     *
     * @param listener The callback that will be invoked.
     */
    void setOnItemLongClickListener(@Nullable OnItemLongClickListener<T> listener);

    /**
     * Interface definition for a callback to be invoked when an item in this
     * Adapter has been long clicked.
     */
    interface OnItemLongClickListener<T> {
        /**
         * Callback method to be invoked when an item in this RecyclerView has
         * been long clicked.
         *

         * Implementers can call getItemAtPosition(position) if they need
         * to access the data associated with the selected item.
         *
         * @param holder The holder within the RecyclerView that was clicked
         * @param position The position of the view in the adapter.
         * @param item The data of holder that bind.
         */
        boolean onItemLongClick(@NonNull PowerHolder<T> holder, int position, @NonNull T item);
    }

    /**
     * Register a callback to be invoked when RecyclerView error layout has been clicked.
     *
     * @param errorClickListener The callback that will be invoked.
     */
    void setErrorClickListener(@Nullable OnErrorClickListener errorClickListener);

    /**
     * Interface definition for a callback to be invoked when error layout click
     */
    interface OnErrorClickListener {
        void onErrorClick(@NonNull View view);
    }
}


text:
@interface MainViewController ()

@property (nonatomic, strong) JSMStaticSection *managers;

@property (nonatomic, strong) JSMStaticSection *employees;

@property (nonatomic, strong) JSMStaticSection *customers;

@end

@implementation MainViewController

#pragma mark - View life cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    // Customers
    self.customers = [JSMStaticSection new];
    self.customers.headerText = @"Customers";
    self.customers.footerText = @"Tap customers to reorder.";
    [self.dataSource addSection:self.customers];

    JSMStaticRow *devina = [JSMStaticRow new];
    devina.text = @"Devina";
    [self.customers addRow:devina];

	JSMStaticRow *chase = [JSMStaticRow new];
	chase.text = @"Chase";
	[self.customers addRow:chase];

	JSMStaticRow *anthony = [JSMStaticRow new];
	anthony.text = @"Anthony";
	[self.customers addRow:anthony];

	JSMStaticRow *dominic = [JSMStaticRow new];
	dominic.text = @"Dominic";
	[self.customers addRow:dominic];

	JSMStaticRow *hatterman = [JSMStaticRow new];
	hatterman.text = @"Hatterman";
	[self.customers addRow:hatterman];

	JSMStaticRow *lydia = [JSMStaticRow new];
	lydia.text = @"Lydia";
	[self.customers addRow:lydia];

	JSMStaticRow *monica = [JSMStaticRow new];
	monica.text = @"Monica";
	[self.customers addRow:monica];

    // Managers
    self.managers = [JSMStaticSection new];
    self.managers.headerText = @"Managers";
    self.managers.footerText = @"Tap a manager to demote them.";
    [self.dataSource addSection:self.managers];

    JSMStaticRow *norma = [JSMStaticRow new];
    norma.text = @"Norma";
    norma.detailText = @"Technician";
    norma.style = UITableViewCellStyleDefault;
    [self.managers addRow:norma];

    // Employees
    self.employees = [JSMStaticSection new];
    self.employees.delegate = self;
    self.employees.headerText = @"Employees";
    self.employees.footerText = @"Tap an employee to promote them.";
    [self.dataSource addSection:self.employees];

    JSMStaticRow *jason = [JSMStaticRow new];
    jason.text = @"Jason";
    jason.detailText = @"Ticketing";
    jason.style = UITableViewCellStyleSubtitle;
    [self.employees addRow:jason];

    JSMStaticRow *becky = [JSMStaticRow new];
    becky.text = @"Becky";
    becky.detailText = @"Ticketing";
    becky.style = UITableViewCellStyleSubtitle;
    [self.employees addRow:becky];

    JSMStaticRow *melissa = [JSMStaticRow new];
    melissa.text = @"Melissa";
    melissa.detailText = @"Concessions";
    melissa.style = UITableViewCellStyleSubtitle;
    [self.employees addRow:melissa];

    JSMStaticRow *kurt = [JSMStaticRow new];
    kurt.text = @"Kurt";
    kurt.detailText = @"Janitorial";
    kurt.style = UITableViewCellStyleSubtitle;
    [self.employees addRow:kurt];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Deselect the row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Fetch the row that was selected
    JSMStaticRow *row = [self.dataSource rowAtIndexPath:indexPath];

	// Let's randomly shuffle the selected customer to a new position within the same section
	if( [row.section isEqual:self.customers] ) {
		NSUInteger oldIndex = [row.section indexForRow:row];
		NSUInteger newIndex = arc4random_uniform((uint32_t)row.section.numberOfRows);

		// So we always appear to move, we may need to fudge the new index a bit.
		// Note that the row's old index plus one would also appear not to move, so we'll need to fudge that too.
		if( newIndex == oldIndex || newIndex == oldIndex + 1 ) {
			newIndex = oldIndex + 2;
		}

		// We can simply insert the row at it's new index, and it'll move automatically.
		[tableView performUpdates:^(UITableView *tableView) {
			[tableView insertRow:row intoSection:row.section atIndex:newIndex withRowAnimation:UITableViewRowAnimationAutomatic];
		}];

		return;
	}

	// Here, we'll move people between sections
	JSMStaticSection *newSection;
	if( [row.section isEqual:self.employees] ) {
		newSection = self.managers;
	}
	else if( [row.section isEqual:self.managers] ) {
		newSection = self.employees;
	}

	// And if we recieved a section, we go forth!
    if( newSection != nil ) {
        JSMStaticSection *oldSection = row.section;
        MainViewController __weak *weakSelf = self;

        // If we removed the section we're moving to, we need to add it back in first.
        if( ! [newSection.dataSource isEqual:self.dataSource] ) {
            [tableView performUpdates:^(UITableView *tableView) {
                [tableView addSection:newSection withRowAnimation:UITableViewRowAnimationAutomatic];
            }];
        }

        // We'll add the row (or rather, move it), and then make a quick change when that's completed.
        [tableView performUpdates:^(UITableView *tableView) {
            [tableView addRow:row toSection:newSection withRowAnimation:UITableViewRowAnimationFade];
        } withCompletion:^{

            // Note that we don't have to reload when the style is changed here. That's because the row asks to
            // be reloaded, and JSMStaticTableViewController obliges automatically.
            if( newSection == weakSelf.managers ) {
                row.style = UITableViewCellStyleDefault;
            }
            else {
                row.style = UITableViewCellStyleSubtitle;
            }

        }];

		// Once we've moved the row, we can safely remove any empty sections
		[tableView performUpdates:^(UITableView *tableView) {
			if( oldSection.numberOfRows == 0 ) {
				[tableView removeSection:oldSection withRowAnimation:UITableViewRowAnimationAutomatic];
			}
			else {
				//[oldSection setNeedsReload];
			}
		}];
	}
}

#pragma mark - Static data source delegate

// Here, we use the data source delegate method to find out when it's section change and to then
// re-sort them automatically in the order we want them.

- (NSArray *)dataSource:(JSMStaticDataSource *)viewController sectionsDidChange:(NSArray *)sections {
    NSArray *sectionOrder = @[ @"Managers", @"Employees", @"Customers" ];
    return [sections sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSUInteger obj1Index = [sectionOrder indexOfObject:[(JSMStaticSection *)obj1 headerText]];
        NSUInteger obj2Index = [sectionOrder indexOfObject:[(JSMStaticSection *)obj2 headerText]];
        if( obj1Index > obj2Index ) {
            return NSOrderedDescending;
        }
        else if( obj1Index < obj2Index ) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
}

#pragma mark - Static section delegate

// We do the same with rows in the employees section, sorting alphabetically by name.

- (NSArray *)section:(JSMStaticSection *)section rowsDidChange:(NSArray *)rows {
    return [rows sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [[(JSMStaticRow *)obj1 text] compare:[(JSMStaticRow *)obj2 text]];
    }];
}

@end


text:
/**
 * @fileoverview Tests for no-inferred-method-name.
 * @author Blake Johnston
 */

'use strict';

const rule = require('../../../lib/rules/no-inferred-method-name');
const RuleTester = require('eslint').RuleTester;

const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2015 } });

const ERROR_MSG =
  '"foo" has no lexical name binding. Use syntax "foo: function foo {...}" or call with "this.foo()".';

ruleTester.run('no-inferred-method-name', rule, {
  valid: [
    { code: 'var a; a = 1; var obj = { foo: function foo() { a; } }' },
    { code: 'var obj = { foo: function foo() { foo(); } }' },
    { code: 'var obj = { otherObj: { foo: function foo() { foo(); } } }' },
    { code: 'var obj = { foo() { } }' }
  ],
  invalid: [
    {
      code: 'var obj = { foo() { foo() } };',
      errors: [{ message: ERROR_MSG, type: 'Identifier' }]
    },
    {
      code: 'var obj = { otherObj: { foo() { foo(); } } }',
      errors: [{ message: ERROR_MSG, type: 'Identifier' }]
    },
    {
      code: 'var obj = { foo() { foo(); } }',
      errors: [{ message: ERROR_MSG, type: 'Identifier' }]
    }
  ]
});


text:
package org.gearvrf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.gearvrf.scene_objects.GVRViewSceneObject;
import org.gearvrf.scene_objects.view.GVRView;
import org.gearvrf.script.IScriptable;
import org.gearvrf.utility.DockEventReceiver;
import org.gearvrf.utility.GrowBeforeQueueThreadPoolExecutor;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.Threads;
import org.gearvrf.utility.VrAppSettings;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

/**
 * The typical GVRF application will have a single Android {@link Activity},
 * which must descend from {@link GVRActivity}, not directly from
 * {@code Activity}.
 *
 * {@code GVRActivity} creates and manages the internal classes which use sensor
 * data to manage a viewpoint, and thus present an appropriate stereoscopic view
 * of your scene graph. {@code GVRActivity} also gives GVRF a full-screen window
 * in landscape orientation with no title bar.
 */
public class GVRActivity extends Activity implements IEventReceiver, IScriptable {

    static {
        System.loadLibrary("gvrf");
    }
    protected static final String TAG = "GVRActivity";

    private GVRViewManager mViewManager;
    private volatile GVRConfigurationManager mConfigurationManager;
    private GVRMain mGVRMain;
    private VrAppSettings mAppSettings;
    private static View mFullScreenView;

    // Group of views that are going to be drawn
    // by some GVRViewSceneObject to the scene.
    private ViewGroup mRenderableViewGroup;
    private IActivityNative mActivityNative;
    private boolean mPaused = true;

    // Send to listeners and scripts but not this object itself
    private static final int SEND_EVENT_MASK =
            GVREventManager.SEND_MASK_ALL & ~GVREventManager.SEND_MASK_OBJECT;

    private GVREventReceiver mEventReceiver = new GVREventReceiver(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        android.util.Log.i(TAG, "onCreate " + Integer.toHexString(hashCode()));
        super.onCreate(savedInstanceState);

        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            for (int i = 0; i < 10; ++i) {
                try {
                    inputStream = getAssets().open("backend_" + i + ".txt");
                    reader = new BufferedReader(new InputStreamReader(inputStream));

                    final String line = reader.readLine();
                    Log.i(TAG, "trying backend " + line);
                    final Class<?> aClass = Class.forName(line);

                    mDelegate = (GVRActivityDelegate) aClass.newInstance();
                    mAppSettings = mDelegate.makeVrAppSettings();
                    mDelegate.onCreate(this);

                    break;
                } catch (final Exception exc) {
                    mDelegate = null;
                }
            }

            if (null == mDelegate) {
                throw new IllegalStateException("Fatal error: no backend available");
            }
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }

        if (null != Threads.getThreadPool()) {
            Threads.getThreadPool().shutdownNow();
        }
        Threads.setThreadPool(new GrowBeforeQueueThreadPoolExecutor("gvrf"));

        /*
         * Removes the title bar and the status bar.
         */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        mRenderableViewGroup = (ViewGroup) findViewById(android.R.id.content).getRootView();

        mActivityNative = mDelegate.getActivityNative();
    }

    protected void onInitAppSettings(VrAppSettings appSettings) {
        mDelegate.onInitAppSettings(appSettings);
    }

    private void onConfigure(final String dataFilename) {
        mConfigurationManager = mDelegate.makeConfigurationManager(this);
        mConfigurationManager.configureForHeadset(GVRConfigurationManager.DEFAULT_HEADSET_MODEL);
        mDelegate.parseXmlSettings(getAssets(), dataFilename);

        onInitAppSettings(mAppSettings);
    }

    public final VrAppSettings getAppSettings() {
        return mAppSettings;
    }

    final GVRViewManager getViewManager() {
        return mViewManager;
    }

    final boolean isPaused() {
        return mPaused;
    }

    @Override
    protected void onPause() {
        android.util.Log.i(TAG, "onPause " + Integer.toHexString(hashCode()));

        mDelegate.onPause();
        mPaused = true;
        if (mViewManager != null) {
            mViewManager.onPause();

            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onPause");
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        android.util.Log.i(TAG, "onResume " + Integer.toHexString(hashCode()));

        mDelegate.onResume();
        mPaused = false;
        super.onResume();
        if (mViewManager != null) {
            mViewManager.onResume();

            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onResume");
        }
    }

    @Override
    protected void onDestroy() {
        android.util.Log.i(TAG, "onDestroy " + Integer.toHexString(hashCode()));
        if (mViewManager != null) {
            mViewManager.onDestroy();
            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onDestroy");
            mViewManager = null;
        }
        if (null != mDockEventReceiver) {
            mDockEventReceiver.stop();
        }

        if (null != mActivityNative) {
            mActivityNative.onDestroy();
            mActivityNative = null;
        }

        mDockListeners.clear();
        mGVRMain = null;
        mDelegate = null;
        mAppSettings = null;
        mRenderableViewGroup = null;
        mConfigurationManager = null;

        super.onDestroy();
    }

    /**
     * Links {@linkplain GVRMain a script} to the activity; sets the version;
     *
     * @param gvrMain
     *            An instance of {@link GVRMain} to handle callbacks on the GL
     *            thread.
     * @param dataFileName
     *            Name of the XML file containing the framebuffer parameters.
     *
     *

     *            The XML filename is relative to the application's
     *            {@code assets} directory, and can specify a file in a
     *            directory under the application's {@code assets} directory.
     */
    public void setMain(GVRMain gvrMain, String dataFileName) {
        this.mGVRMain = gvrMain;
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            onConfigure(dataFileName);
            mDelegate.setMain(gvrMain, dataFileName);

            boolean isMonoscopicMode = mAppSettings.getMonoscopicModeParams().isMonoscopicMode();
            if (!isMonoscopicMode) {
                mViewManager = mDelegate.makeViewManager();
            } else {
                mViewManager = mDelegate.makeMonoscopicViewManager();
            }
            mDelegate.setViewManager(mViewManager);

            if (mConfigurationManager.isDockListenerRequired()) {
                startDockEventReceiver();
            } else {
                handleOnDock();
            }

            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onSetMain", gvrMain);

            final GVRConfigurationManager localConfigurationManager = mConfigurationManager;
            if (!isMonoscopicMode) {
                if (null != mDockEventReceiver && localConfigurationManager.isDockListenerRequired()) {
                    getGVRContext().registerDrawFrameListener(new GVRDrawFrameListener() {
                        @Override
                        public void onDrawFrame(float frameTime) {
                            if (localConfigurationManager.isHmtConnected()) {
                                handleOnDock();
                                getGVRContext().unregisterDrawFrameListener(this);
                            }
                        }
                    });
                }
            }
        } else {
            throw new IllegalArgumentException(
                    "You can not set orientation to portrait for GVRF apps.");
        }
    }

    /**
     * Invalidating just the GVRView associated with the GVRViewSceneObject
     * incorrectly set the clip rectangle to just that view. To fix this,
     * we have to create a full screen android View and invalidate this
     * to restore the clip rectangle.
     * @return full screen View object
     */
    public View getFullScreenView() {
        if (mFullScreenView != null) {
            return mFullScreenView;
        }

        final DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final int screenWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);
        final int screenHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);

        final ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(screenWidthPixels, screenHeightPixels);
        mFullScreenView = new View(this);
        mFullScreenView.setLayoutParams(layout);
        mRenderableViewGroup.addView(mFullScreenView);

        return mFullScreenView;
    }

    /**
     * Gets the {@linkplain GVRMain} linked to the activity.
     * @return the {@link GVRMain}.
     */
    public final GVRMain getMain() {
        return mGVRMain;
    }

    /**
     * Uses the default configuration file that comes with the framework.
     * @see GVRActivity#setMain(GVRMain, String)
     */
    public final void setMain(GVRMain gvrMain) {
        setMain(gvrMain, "_gvr.xml");
    }

    /**
     * Sets whether to force rendering to be single-eye, monoscopic view.
     *
     * @param force
     *            If true, will create a OvrMonoscopicViewManager when
     *            {@linkplain GVRActivity#setMain(GVRMain, String)} is called. If false, will
     *            proceed to auto-detect whether the device supports VR
     *            rendering and choose the appropriate ViewManager. This call
     *            will only have an effect if it is called before
     *            {@linkplain #setMain(GVRMain, String) setMain()}.
     * @deprecated
     */
    @Deprecated
    public void setForceMonoscopic(boolean force) {
        mAppSettings.getMonoscopicModeParams().setMonoscopicMode(force);
    }

    /**
     * Returns whether a monoscopic view was asked to be forced during
     * {@linkplain #setMain(GVRMain, String) setMain()}.
     *
     * @see GVRActivity#setForceMonoscopic(boolean)
     * @deprecated
     */
    @Deprecated
    public final boolean getForceMonoscopic() {
        return mAppSettings.getMonoscopicModeParams().isMonoscopicMode();
    }

    final long getNative() {
        return null != mActivityNative ? mActivityNative.getNative() : 0;
    }

    final IActivityNative getActivityNative() {
        return mActivityNative;
    }

    final void setCameraRig(GVRCameraRig cameraRig) {
        if (null != mActivityNative) {
            mActivityNative.setCameraRig(cameraRig);
        }
    }

    private long mBackKeyDownTime;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        final int keyAction = event.getAction();
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            if (KeyEvent.ACTION_DOWN == keyAction) {
                if (0 == mBackKeyDownTime) {
                    mBackKeyDownTime = event.getDownTime();
                }
            } else if (KeyEvent.ACTION_UP == keyAction) {
                final long duration = event.getEventTime() - mBackKeyDownTime;
                mBackKeyDownTime = 0;
                if (!isPaused()) {
                    if (duration < 250) {
                        if (!mGVRMain.onBackPress()) {
                            if (!mDelegate.onBackPress()) {
                                mViewManager.getActivity().finish();
                            }
                        }
                    }
                }
            }
            return true;
        } else {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_VOLUME_UP:
                    if (keyAction == KeyEvent.ACTION_DOWN) {
                        final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                AudioManager.ADJUST_RAISE, 0);
                        return true;
                    }
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    if (keyAction == KeyEvent.ACTION_DOWN) {
                        final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                AudioManager.ADJUST_LOWER, 0);
                        return true;
                    }
            }
        }
        if (mViewManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mDelegate.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        if (mDelegate.onKeyLongPress(keyCode, event)) {
            return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mDelegate.onKeyUp(keyCode, event)) {
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean dispatchGenericMotionEvent(MotionEvent event) {
        boolean handled = mViewManager.dispatchMotionEvent(event);
        if (handled == false) {
            handled = super.dispatchGenericMotionEvent(event);
        }
        return handled;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        boolean handled = mViewManager.dispatchMotionEvent(event);
        if (handled == false) {
            handled = super.dispatchTouchEvent(event);// VrActivity's
        }

        mViewManager.getEventManager().sendEventWithMask(
                SEND_EVENT_MASK,
                this,
                IActivityEvents.class,
                "dispatchTouchEvent", event);

        return handled;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        mDelegate.onConfigurationChanged(newConfig);

        if (mViewManager != null) {
            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onConfigurationChanged", newConfig);
        }

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mViewManager != null) {
            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onTouchEvent", event);
        }

        return super.onTouchEvent(event);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (mViewManager != null) {
            mViewManager.getEventManager().sendEventWithMask(
                    SEND_EVENT_MASK,
                    this,
                    IActivityEvents.class,
                    "onWindowFocusChanged", hasFocus);
        }

        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            setImmersiveSticky();
        }
    }

    // Set Immersive Sticky as described here:
    // https://developer.android.com/training/system-ui/immersive.html
    private void setImmersiveSticky() {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }

    /**
     * Called from C++
     */
    final boolean updateSensoredScene() {
        return mViewManager.updateSensoredScene();
    }

    /**
     * It is a convenient function to add a {@link GVRView} to Android hierarchy
     * view. UI thread will call {@link GVRView#draw(android.graphics.Canvas)}
     * to refresh the view when necessary.
     *
     * @param view Is a {@link GVRView} that draw itself into some
     *            {@link GVRViewSceneObject}.
     */
    public final void registerView(final View view) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                /* The full screen should be updated
                otherwise just the children's bounds may be refreshed. */
                mRenderableViewGroup.setClipChildren(false);

                mRenderableViewGroup.addView(view);
            }
        });
    }

    /**
     * Remove a child view of Android hierarchy view .
     *
     * @param view View to be removed.
     */
    public final void unregisterView(final View view) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRenderableViewGroup.removeView(view);
            }
        });
    }

    public final GVRContext getGVRContext() {
        return mViewManager;
    }

    @Override
    public final GVREventReceiver getEventReceiver() {
        return mEventReceiver;
    }

    private boolean mIsDocked = false;

    protected final void handleOnDock() {
        Log.i(TAG, "handleOnDock");
        final Runnable r = new Runnable() {
            @Override
            public void run() {
                if (!mIsDocked) {
                    mIsDocked = true;

                    if (null != mActivityNative) {
                        mActivityNative.onDock();
                    }

                    for (final DockListener dl : mDockListeners) {
                        dl.onDock();
                    }
                }
            }
        };
        runOnUiThread(r);
    }

    protected final void handleOnUndock() {
        Log.i(TAG, "handleOnUndock");
        final Runnable r = new Runnable() {
            @Override
            public void run() {
                if (mIsDocked) {
                    mIsDocked = false;

                    if (null != mActivityNative) {
                        mActivityNative.onUndock();
                    }

                    for (final DockListener dl : mDockListeners) {
                        dl.onUndock();
                    }
                }
            }
        };
        runOnUiThread(r);
    }

    public GVRConfigurationManager getConfigurationManager() {
        return mConfigurationManager;
    }

    interface DockListener {
        void onDock();
        void onUndock();
    }

    private final List<DockListener> mDockListeners = new CopyOnWriteArrayList<DockListener>();

    final void addDockListener(final DockListener dl) {
        mDockListeners.add(dl);
    }

    private DockEventReceiver mDockEventReceiver;

    private void startDockEventReceiver() {
        mDockEventReceiver = mConfigurationManager.makeDockEventReceiver(this,
                new Runnable() {
                    @Override
                    public void run() {
                        handleOnDock();
                    }
                }, new Runnable() {
                    @Override
                    public void run() {
                        handleOnUndock();
                    }
                });
        if (null != mDockEventReceiver) {
            mDockEventReceiver.start();
        } else {
            Log.w(TAG, "dock listener not started");
        }
    }

    private GVRActivityDelegate mDelegate;

    GVRActivityDelegate getDelegate() {
        return mDelegate;
    }

    interface GVRActivityDelegate {
        void onCreate(GVRActivity activity);
        void onPause();
        void onResume();
        void onConfigurationChanged(final Configuration newConfig);

        boolean onKeyDown(int keyCode, KeyEvent event);
        boolean onKeyUp(int keyCode, KeyEvent event);
        boolean onKeyLongPress(int keyCode, KeyEvent event);

        void setMain(GVRMain gvrMain, String dataFileName);
        void setViewManager(GVRViewManager viewManager);
        void onInitAppSettings(VrAppSettings appSettings);

        VrAppSettings makeVrAppSettings();
        IActivityNative getActivityNative();
        GVRViewManager makeViewManager();
        GVRViewManager makeMonoscopicViewManager();
        GVRCameraRig makeCameraRig(GVRContext context);
        GVRConfigurationManager makeConfigurationManager(GVRActivity activity);
        void parseXmlSettings(AssetManager assetManager, String dataFilename);

        boolean onBackPress();
    }
}


text:
namespace drake {
namespace examples {
namespace cars {
namespace {

class SimpleCarTest : public ::testing::Test {
 protected:
  void SetUp() override {
    dut_.reset(new SimpleCar<double>);
    context_ = dut_->CreateDefaultContext();
    output_ = dut_->AllocateOutput(*context_);
    derivatives_ = dut_->AllocateTimeDerivatives();
    SetInputValue(0, 0, 0);
  }

  void SetInputValue(double steering_angle, double throttle, double brake) {
    auto value = std::make_unique<DrivingCommand<double>>();
    value->set_steering_angle(steering_angle);
    value->set_throttle(throttle);
    value->set_brake(brake);
    context_->SetInputPort(
        0, std::make_unique<systems::FreestandingInputPort>(std::move(value)));
  }

  SimpleCarState<double>* continuous_state() {
    auto result = dynamic_cast<SimpleCarState<double>*>(
        context_->get_mutable_state()->continuous_state->get_mutable_state());
    if (result == nullptr) { throw std::bad_cast(); }
    return result;
  }

  std::unique_ptr<systems::System<double>> dut_;  //< The device under test.
  std::unique_ptr<systems::ContextBase<double>> context_;
  std::unique_ptr<systems::SystemOutput<double>> output_;
  std::unique_ptr<systems::ContinuousState<double>> derivatives_;
};

TEST_F(SimpleCarTest, Topology) {
  ASSERT_EQ(1, dut_->get_num_input_ports());
  const auto& input_descriptor = dut_->get_input_ports().at(0);
  EXPECT_EQ(systems::kVectorValued, input_descriptor.get_data_type());
  EXPECT_EQ(systems::kInputPort, input_descriptor.get_face());
  EXPECT_EQ(DrivingCommandIndices::kNumCoordinates,
            input_descriptor.get_size());
  EXPECT_EQ(systems::kContinuousSampling, input_descriptor.get_sampling());

  ASSERT_EQ(1, dut_->get_num_output_ports());
  const auto& output_descriptor = dut_->get_output_ports().at(0);
  EXPECT_EQ(systems::kVectorValued, output_descriptor.get_data_type());
  EXPECT_EQ(systems::kOutputPort, output_descriptor.get_face());
  EXPECT_EQ(SimpleCarStateIndices::kNumCoordinates,
            output_descriptor.get_size());
  EXPECT_EQ(systems::kContinuousSampling, output_descriptor.get_sampling());
}

TEST_F(SimpleCarTest, Output) {
  // Grab a pointer to where the EvalOutput results end up.
  const SimpleCarState<double>* const result =
      dynamic_cast<const SimpleCarState<double>*>(output_->get_vector_data(0));
  ASSERT_NE(nullptr, result);

  // Starting state and output is all zeros.
  dut_->EvalOutput(*context_, output_.get());
  EXPECT_EQ(0.0, result->x());
  EXPECT_EQ(0.0, result->y());
  EXPECT_EQ(0.0, result->heading());
  EXPECT_EQ(0.0, result->velocity());

  // New state just propagates through.
  continuous_state()->set_x(1.0);
  continuous_state()->set_y(2.0);
  continuous_state()->set_heading(3.0);
  continuous_state()->set_velocity(4.0);
  dut_->EvalOutput(*context_, output_.get());
  EXPECT_EQ(1.0, result->x());
  EXPECT_EQ(2.0, result->y());
  EXPECT_EQ(3.0, result->heading());
  EXPECT_EQ(4.0, result->velocity());

  // The input doesn't matter.
  SetInputValue(0.3, 0.5, 0.7);
  dut_->EvalOutput(*context_, output_.get());
  EXPECT_EQ(1.0, result->x());
  EXPECT_EQ(2.0, result->y());
  EXPECT_EQ(3.0, result->heading());
  EXPECT_EQ(4.0, result->velocity());
}

TEST_F(SimpleCarTest, Derivatives) {
  const double kTolerance = 1e-10;

  // Grab a pointer to where the EvalTimeDerivatives results end up.
  const SimpleCarState<double>* const result =
      dynamic_cast<const SimpleCarState<double>*>(
          derivatives_->get_mutable_state());
  ASSERT_NE(nullptr, result);

  // Starting state is all zeros.
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_EQ(0.0, result->x());
  EXPECT_EQ(0.0, result->y());
  EXPECT_EQ(0.0, result->heading());
  EXPECT_EQ(0.0, result->velocity());

  // Half throttle yields half of the max acceleration.
  const double max_acceleration = SimpleCar1::kDefaultConfig.max_acceleration;
  SetInputValue(0.0, 0.5, 0.0);
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_EQ(0.0, result->x());
  EXPECT_EQ(0.0, result->y());
  EXPECT_EQ(0.0, result->heading());
  EXPECT_NEAR(0.5 * max_acceleration, result->velocity(), kTolerance);

  // Set speed to mid-range, with zero input.
  continuous_state()->set_velocity(10.0);
  SetInputValue(0.0, 0.0, 0.0);
  // At heading 0, we are moving along +x.
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_NEAR(10.0, result->x(), kTolerance);
  EXPECT_EQ(0.0, result->y());
  EXPECT_EQ(0.0, result->heading());
  EXPECT_EQ(0.0, result->velocity());

  // A non-zero steering_angle turns in the same direction.  We'd like to turn
  // at 0.1 rad/s at a speed of 10m/s, so we want a curvature of 0.01.
  const double wheelbase = SimpleCar1::kDefaultConfig.wheelbase;
  const double steering_angle = std::atan(0.01 * wheelbase);
  SetInputValue(steering_angle, 0.0, 0.0);
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_NEAR(10.0, result->x(), kTolerance);
  EXPECT_EQ(0.0, result->y());
  EXPECT_NEAR(0.1, result->heading(), kTolerance);
  EXPECT_EQ(0.0, result->velocity());
  SetInputValue(-steering_angle, 0.0, 0.0);
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_NEAR(10.0, result->x(), kTolerance);
  EXPECT_EQ(0.0, result->y());
  EXPECT_NEAR(-0.1, result->heading(), kTolerance);
  EXPECT_EQ(0.0, result->velocity());

  // Half brake yields half of the max acceleration.
  SetInputValue(0.0, 0.0, 0.5);
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_NEAR(10.0, result->x(), kTolerance);
  EXPECT_EQ(0.0, result->y());
  EXPECT_EQ(0.0, result->heading());
  EXPECT_NEAR(-0.5 * SimpleCar1::kDefaultConfig.max_acceleration,
              result->velocity(), kTolerance);

  // A heading of +90deg points us at +y.
  continuous_state()->set_heading(0.5 * M_PI);
  SetInputValue(0.0, 0.0, 0.0);
  dut_->EvalTimeDerivatives(*context_, derivatives_.get());
  EXPECT_NEAR(0.0, result->x(), kTolerance);
  EXPECT_NEAR(10.0, result->y(), kTolerance);
  EXPECT_EQ(0.0, result->heading());
  EXPECT_EQ(0.0, result->velocity());
}

}  // namespace
}  // namespace cars
}  // namespace examples
}  // namespace drake


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:fillAfter="false"
        android:duration="200"
        android:pivotX = "50%"
        android:pivotY = "-90%"
        />
    <translate
        android:fromYDelta="50%"
        android:toYDelta="0"
        android:duration="200"
        />

        <!--android:startOffset="200"-->
</set>


text:
"""Package contenant la commande 'appâter'."""

from primaires.interpreteur.commande.commande import Commande

class CmdAppater(Commande):

    """Commande 'appâter'"""

    def __init__(self):
        """Constructeur de la commande"""
        Commande.__init__(self, "appâter", "bait")
        self.schema = "<nom_objet>"
        self.aide_courte = "appâte un ameçon"
        self.aide_longue = \
            "Cette commande permet d'appâter un hameçon. Vous devez " \
            "tenir une canne à pêche et préciser le nom de l'appât. " \
            "Certains appâts, plus durs à trouver que d'autres, " \
            "attirent aussi plus le poisson et peuvent augmenter la " \
            "chance de pêcher une prise rare. Dès lors que vous avez " \
            "pêché quelque chose, vous devez appâter de nouveau " \
            "l'hameçon de la canne avant de la relancer."

    def ajouter(self):
        """Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
        nom_objet = self.noeud.get_masque("nom_objet")
        nom_objet.proprietes["conteneurs"] = \
                "(personnage.equipement.inventaire_simple.iter_objets_qtt(" \
                "True), )"
        nom_objet.proprietes["quantite"] = "True"
        nom_objet.proprietes["conteneur"] = "True"

    def interpreter(self, personnage, dic_masques):
        """Interprétation de la commande."""
        appat = dic_masques["nom_objet"].objet
        if not appat.est_de_type("appât"):
            personnage << "|err|Vous ne pouvez appâter {}.|ff|".format(
                    appat.get_nom())
            return

        canne = None
        for membre in personnage.equipement.membres:
            for objet in membre.equipe:
                if objet.est_de_type("canne à pêche"):
                    canne = objet
                    break

        if canne is None:
            personnage << "|err|Vous n'équipez aucune canne à pêche.|ff|"
            return

        if (getattr(canne, "appat", None) is not None
                and appat.prototype == canne.appat.prototype):
            personnage << "|err|Vous avez déjà appâté {} avec {}.|ff|".format(
                    canne.get_nom(), appat.get_nom())
            return

        personnage.agir("appater")
        appat.contenu.retirer(appat)
        a_appat = canne.appat
        if a_appat:
            importeur.objet.supprimer_objet(a_appat.identifiant)

        canne.appat = appat
        personnage << "Vous appâtez {} avec {}.".format(
                canne.get_nom(), appat.get_nom())
        personnage.salle.envoyer("{{}} appâte {} avec {}.".format(
                canne.get_nom(), appat.get_nom()), personnage)


text:
{extend name="default/template/base_index" /}

{block name="area_header"}

	<link type="text/css" rel="stylesheet" href="__CDN__/select2/4.0.0/css/select2.min.css" />
	<link type="text/css" rel="stylesheet" href="__CDN__/select2/4.0.0/css/cosmo-skin.css" />
{/block}

{block name="area_body"}
	{include file="default/Widget/topbar" /}

		{include file="default/Widget/left" /}

			{include file="default/Widget/breadcrumb" /}
			<form action="{:url('Wxuser/sendText')}" method="post" class="sendForm form-horizontal form">

					选择用户

						<select style="width:220px;padding: 10px 15px;font-size: 15px;line-height: 1.42857143;" id="user_select2" name="uid" class="form-control">
							<option value="{$vo.id}">{$vo.nickname}</option>
						</select>

					发送文本消息内容

						<textarea name="text" rows="3" class="form-control"></textarea>

                        发送

                        返回

		</form>

{/block}

{block name="area_footer"}

{/block}


text:
:- module(swish_config_sshd, []).

/** <module> Provide admin access through SSH

Provide an administrative channel to access   the SWISH server. This can
be used on anonymous installations to   apply hot fixes, load additional
libraries, etc.

Requires the pack `libssh` to be installed.
*/

:- use_module(library(ssh_server)).
:- use_module(library(broadcast)).

% If library(http/http_unix_daemon) is used we are loaded before the
% fork, but we cannot start threads before forking.  This ensures we
% are started later.

:- listen(http(pre_server_start),
          start_sshd).

start_sshd :-
    thread_property(TID,status(running)),TID=='sshd@3250',!.
start_sshd :-
    ssh_server([ port(3250),
                 bind_address(*),
                 authorized_keys_file('etc/ssh/authorized_keys')
               ]).


text:
#import "RNSVGMarkerManager.h"
#import "RNSVGMarker.h"

@implementation RNSVGMarkerManager

RCT_EXPORT_MODULE()

- (RNSVGMarker *)node
{
    return [RNSVGMarker new];
}

RCT_EXPORT_VIEW_PROPERTY(refX, RNSVGLength*)
RCT_EXPORT_VIEW_PROPERTY(refY, RNSVGLength*)
RCT_EXPORT_VIEW_PROPERTY(markerHeight, RNSVGLength*)
RCT_EXPORT_VIEW_PROPERTY(markerWidth, RNSVGLength*)
RCT_EXPORT_VIEW_PROPERTY(markerUnits, NSString*)
RCT_EXPORT_VIEW_PROPERTY(orient, NSString*)

RCT_EXPORT_VIEW_PROPERTY(minX, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(minY, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(vbWidth, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(vbHeight, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(align, NSString)
RCT_EXPORT_VIEW_PROPERTY(meetOrSlice, RNSVGVBMOS)

@end