text:
import { isArray, isMatrix, isString, typeOf } from '../../utils/is';
import { clone } from '../../utils/object';
import { factory } from '../../utils/factory';
var name = 'ImmutableDenseMatrix';
var dependencies = ['smaller', 'DenseMatrix'];
export var createImmutableDenseMatrixClass =
/* #__PURE__ */
factory(name, dependencies, function (_ref) {
  var smaller = _ref.smaller,
      DenseMatrix = _ref.DenseMatrix;

  function ImmutableDenseMatrix(data, datatype) {
    if (!(this instanceof ImmutableDenseMatrix)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }

    if (datatype && !isString(datatype)) {
      throw new Error('Invalid datatype: ' + datatype);
    }

    if (isMatrix(data) || isArray(data)) {
      // use DenseMatrix implementation
      var matrix = new DenseMatrix(data, datatype); // internal structures

      this._data = matrix._data;
      this._size = matrix._size;
      this._datatype = matrix._datatype;
      this._min = null;
      this._max = null;
    } else if (data && isArray(data.data) && isArray(data.size)) {
      // initialize fields from JSON representation
      this._data = data.data;
      this._size = data.size;
      this._datatype = data.datatype;
      this._min = typeof data.min !== 'undefined' ? data.min : null;
      this._max = typeof data.max !== 'undefined' ? data.max : null;
    } else if (data) {
      // unsupported type
      throw new TypeError('Unsupported type of data (' + typeOf(data) + ')');
    } else {
      // nothing provided
      this._data = [];
      this._size = [0];
      this._datatype = datatype;
      this._min = null;
      this._max = null;
    }
  }

  ImmutableDenseMatrix.prototype = new DenseMatrix();
  /**
   * Attach type information
   */

  ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix';
  ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true;
  /**
   * Get a subset of the matrix, or replace a subset of the matrix.
   *
   * Usage:
   *     const subset = matrix.subset(index)               // retrieve subset
   *     const value = matrix.subset(index, replacement)   // replace subset
   *
   * @param {Index} index
   * @param {Array | ImmutableDenseMatrix | *} [replacement]
   * @param {*} [defaultValue=0]      Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be filled with zeros.
   */

  ImmutableDenseMatrix.prototype.subset = function (index) {
    switch (arguments.length) {
      case 1:
        {
          // use base implementation
          var m = DenseMatrix.prototype.subset.call(this, index); // check result is a matrix

          if (isMatrix(m)) {
            // return immutable matrix
            return new ImmutableDenseMatrix({
              data: m._data,
              size: m._size,
              datatype: m._datatype
            });
          }

          return m;
        }
      // intentional fall through

      case 2:
      case 3:
        throw new Error('Cannot invoke set subset on an Immutable Matrix instance');

      default:
        throw new SyntaxError('Wrong number of arguments');
    }
  };
  /**
   * Replace a single element in the matrix.
   * @param {Number[]} index   Zero-based index
   * @param {*} value
   * @param {*} [defaultValue]        Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be left undefined.
   * @return {ImmutableDenseMatrix} self
   */

  ImmutableDenseMatrix.prototype.set = function () {
    throw new Error('Cannot invoke set on an Immutable Matrix instance');
  };
  /**
   * Resize the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (resize in place).
   *
   * @param {Number[]} size           The new size the matrix should have.
   * @param {*} [defaultValue=0]      Default value, filled in on new entries.
   *                                  If not provided, the matrix elements will
   *                                  be filled with zeros.
   * @param {boolean} [copy]          Return a resized copy of the matrix
   *
   * @return {Matrix}                 The resized matrix
   */

  ImmutableDenseMatrix.prototype.resize = function () {
    throw new Error('Cannot invoke resize on an Immutable Matrix instance');
  };
  /**
   * Disallows reshaping in favor of immutability.
   *
   * @throws {Error} Operation not allowed
   */

  ImmutableDenseMatrix.prototype.reshape = function () {
    throw new Error('Cannot invoke reshape on an Immutable Matrix instance');
  };
  /**
   * Create a clone of the matrix
   * @return {ImmutableDenseMatrix} clone
   */

  ImmutableDenseMatrix.prototype.clone = function () {
    return new ImmutableDenseMatrix({
      data: clone(this._data),
      size: clone(this._size),
      datatype: this._datatype
    });
  };
  /**
   * Get a JSON representation of the matrix
   * @returns {Object}
   */

  ImmutableDenseMatrix.prototype.toJSON = function () {
    return {
      mathjs: 'ImmutableDenseMatrix',
      data: this._data,
      size: this._size,
      datatype: this._datatype
    };
  };
  /**
   * Generate a matrix from a JSON object
   * @param {Object} json  An object structured like
   *                       `{"mathjs": "ImmutableDenseMatrix", data: [], size: []}`,
   *                       where mathjs is optional
   * @returns {ImmutableDenseMatrix}
   */

  ImmutableDenseMatrix.fromJSON = function (json) {
    return new ImmutableDenseMatrix(json);
  };
  /**
   * Swap rows i and j in Matrix.
   *
   * @param {Number} i       Matrix row index 1
   * @param {Number} j       Matrix row index 2
   *
   * @return {Matrix}        The matrix reference
   */

  ImmutableDenseMatrix.prototype.swapRows = function () {
    throw new Error('Cannot invoke swapRows on an Immutable Matrix instance');
  };
  /**
   * Calculate the minimum value in the set
   * @return {Number | undefined} min
   */

  ImmutableDenseMatrix.prototype.min = function () {
    // check min has been calculated before
    if (this._min === null) {
      // minimum
      var m = null; // compute min

      this.forEach(function (v) {
        if (m === null || smaller(v, m)) {
          m = v;
        }
      });
      this._min = m !== null ? m : undefined;
    }

    return this._min;
  };
  /**
   * Calculate the maximum value in the set
   * @return {Number | undefined} max
   */

  ImmutableDenseMatrix.prototype.max = function () {
    // check max has been calculated before
    if (this._max === null) {
      // maximum
      var m = null; // compute max

      this.forEach(function (v) {
        if (m === null || smaller(m, v)) {
          m = v;
        }
      });
      this._max = m !== null ? m : undefined;
    }

    return this._max;
  };

  return ImmutableDenseMatrix;
}, {
  isClass: true
});


text:
package org.smartdata.actions.hdfs.move;

/**
 * Smart agent based move runner.
 */
public class AgentBasedMoveRunner extends MoveRunner {

  @Override
  public void move(String file) throws Exception {

  }

  @Override
  public void move(String[] files) throws Exception {

  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Registration views — django-registration v0.8 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="django-registration v0.8 documentation" href="index.html" />
    <link rel="next" title="Custom signals used by django-registration" href="signals.html" />
    <link rel="prev" title="Forms for user registration" href="forms.html" />

Navigation

          index

          modules |

          next |

          previous |

django-registration v0.8 documentation »

Registration views¶

In order to allow users to register using whatever workflow is
implemented by the registration backend in use,
django-registration provides two views. Both are designed to allow
easy configurability without writing or rewriting view code.

<tt class="descclassname">registration.views.</tt><tt class="descname">activate</tt><big>(</big>request, backend[, template_name[, success_url[, extra_context[, **kwargs]]]]<big>)</big>¶

Activate a user’s account, for workflows which require a separate
activation step.

The actual activation of the account will be delegated to the
backend specified by the <tt class="docutils literal">backend</tt> keyword argument; the
backend’s <tt class="docutils literal">activate()</tt> method will be called, passing the
<tt class="docutils literal">HttpRequest</tt> and any keyword arguments captured from the URL,
and will be assumed to return a <tt class="docutils literal">User</tt> if activation was
successful, or a value which evaluates to <tt class="xref docutils literal">False</tt> in boolean
context if not.

Upon successful activation, the backend’s
<tt class="docutils literal">post_activation_redirect()</tt> method will be called, passing the
<tt class="docutils literal">HttpRequest</tt> and the activated <tt class="docutils literal">User</tt> to determine the URL to
redirect the user to. To override this, pass the argument
<tt class="docutils literal">success_url</tt> (see below).

On unsuccessful activation, will render the template
<tt class="docutils literal">registration/activate.html</tt> to display an error message; to
override thise, pass the argument <tt class="docutils literal">template_name</tt> (see below).

Context

The context will be populated from the keyword arguments captured
in the URL. This view uses <tt class="docutils literal">RequestContext</tt>, so variables
populated by context processors will also be present in the
context.

<col class="field-name" />
<col class="field-body" />

Parameters:

backend (string) – The dotted Python path to the backend class to use.

extra_context (dict) – Optionally, variables to add to the template
context. Any callable object in this dictionary will be called
to produce the final result which appears in the context.

template_name (string) – Optional. A custom template name to use. If
not specified, this will default to
<tt class="docutils literal">registration/activate.html</tt>.

**kwargs –
Any keyword arguments captured from the URL, such
as an activation key, which will be passed to the backend’s
<tt class="docutils literal">activate()</tt> method.

<tt class="descclassname">registration.views.</tt><tt class="descname">register</tt><big>(</big>request, backend[, success_url[, form_class[, disallowed_url[, template_name[, extra_context]]]]]<big>)</big>¶

Allow a new user to register an account.

The actual registration of the account will be delegated to the
backend specified by the <tt class="docutils literal">backend</tt> keyword argument. The backend
is used as follows:

The backend’s <tt class="docutils literal">registration_allowed()</tt> method will be called,
passing the <tt class="docutils literal">HttpRequest</tt>, to determine whether registration
of an account is to be allowed; if not, a redirect is issued to
a page indicating that registration is not permitted.

The form to use for account registration will be obtained by
calling the backend’s <tt class="docutils literal">get_form_class()</tt> method, passing the
<tt class="docutils literal">HttpRequest</tt>. To override this, pass the keyword argument
<tt class="docutils literal">form_class</tt>.

If valid, the form’s <tt class="docutils literal">cleaned_data</tt> will be passed (as keyword
arguments, and along with the <tt class="docutils literal">HttpRequest</tt>) to the backend’s
<tt class="docutils literal">register()</tt> method, which should return a <tt class="docutils literal">User</tt> object
representing the new account.

Upon successful registration, the backend’s
<tt class="docutils literal">post_registration_redirect()</tt> method will be called, passing
the <tt class="docutils literal">HttpRequest</tt> and the new <tt class="docutils literal">User</tt>, to determine the URL
to redirect to. To override this, pass the keyword argument
<tt class="docutils literal">success_url</tt>.

Context

<tt class="docutils literal">form</tt>

The form instance being used to collect registration data.

This view uses <tt class="docutils literal">RequestContext</tt>, so variables populated by
context processors will also be present in the context.

<col class="field-name" />
<col class="field-body" />

Parameters:

backend (string) – The dotted Python path to the backend class to use.

disallowed_url (string) – The URL to redirect to if registration is
not permitted (e.g., if registration is closed). This should be
a string suitable for passing as the <tt class="docutils literal">to</tt> argument to
Django’s “redirect” shortcut. If
not specified, this will default to <tt class="docutils literal">registration_disallowed</tt>.

extra_context (dict) – Optionally, variables to add to the template
context. Any callable object in this dictionary will be called
to produce the final result which appears in the context.

form_class (subclass of <tt class="docutils literal">django.forms.Form</tt>) – The form class to use for registration; this
should be some subclass of <tt class="docutils literal">django.forms.Form</tt>. If not
specified, the backend’s <tt class="docutils literal">get_form_class()</tt> method will be
called to obtain the form class.

success_url (string) –
The URL to redirect to after successful
registration. This should be a string suitable for passing as
the <tt class="docutils literal">to</tt> argument to Django’s “redirect” shortcut. If
not specified, the backend’s <tt class="docutils literal">post_registration_redirect()</tt>
method will be called to obtain the URL.

template_name (string) – Optional. A custom template name to use. If
not specified, this will default to
<tt class="docutils literal">registration/registration_form.html</tt>.

Previous topic

Forms for user registration

Next topic

Custom signals used by django-registration

This Page

Show Source

Quick search

              <form class="search" action="search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

              Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

django-registration v0.8 documentation »

      © Copyright 2009, James Bennett.
      Created using Sphinx 0.6.3.


text:
using System.Collections.Generic;
using System.Web.Mvc;
using Nop.Web.Framework;

namespace Nop.Plugin.Shipping.Fedex.Models
{
    public class FedexShippingModel
    {
        public FedexShippingModel()
        {
            CarrierServicesOffered = new List<string>();
            AvailableCarrierServices = new List<string>();
        }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.Url")]
        public string Url { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.Key")]
        public string Key { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.Password")]
        public string Password { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.AccountNumber")]
        public string AccountNumber { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.MeterNumber")]
        public string MeterNumber { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.UseResidentialRates")]
        public bool UseResidentialRates { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.ApplyDiscounts")]
        public bool ApplyDiscounts { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.AdditionalHandlingCharge")]
        public decimal AdditionalHandlingCharge { get; set; }

        public IList<string> CarrierServicesOffered { get; set; }
        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.CarrierServices")]
        public IList<string> AvailableCarrierServices { get; set; }
        public string[] CheckedCarrierServices { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.PassDimensions")]
        public bool PassDimensions { get; set; }

        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.PackingPackageVolume")]
        public int PackingPackageVolume { get; set; }

        public int PackingType { get; set; }
        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.PackingType")]
        public SelectList PackingTypeValues { get; set; }

        public int DropoffType { get; set; }
        [NopResourceDisplayName("Plugins.Shipping.Fedex.Fields.DropoffType")]
        public SelectList AvailableDropOffTypes { get; set; }
    }
}


text:
package org.zstack.resourceconfig;

import org.springframework.http.HttpMethod;
import org.zstack.core.Platform;
import org.zstack.header.message.APIParam;
import org.zstack.header.message.APISyncCallMessage;
import org.zstack.header.rest.RestRequest;
import org.zstack.header.vo.ResourceVO;

/**
 * Created by MaJin on 2019/2/23.
 */

@RestRequest(path = "/resource-configurations/{resourceUuid}/{category}/{name}",
        method = HttpMethod.GET, responseClass = APIGetResourceConfigReply.class)
public class APIGetResourceConfigMsg extends APISyncCallMessage implements ResourceConfigMessage {
    @APIParam
    private String category;
    @APIParam
    private String name;
    @APIParam(resourceType = ResourceVO.class, checkAccount = true)
    private String resourceUuid;

    @Override
    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public String getResourceUuid() {
        return resourceUuid;
    }

    public void setResourceUuid(String resourceUuid) {
        this.resourceUuid = resourceUuid;
    }

    public static APIGetResourceConfigMsg __example__() {
        APIGetResourceConfigMsg msg = new APIGetResourceConfigMsg();
        msg.category = "host";
        msg.name = "cpu.overProvisioning.ratio";
        msg.resourceUuid = Platform.getUuid();
        return msg;
    }
}


text:
APX
==========

## Kado

STOP AND READ THIS

APX or Apex is no longer maintained and is superseded by Kado.

A new package is available to handle all your JavaScript needs.
See [kado.org](https://kado.org) for details.

## APX API Server

APX *(pronounced 'apex')* is a non-opinionated, pluggable, modern API server designed to serve
multiple communication mediums. The core APX plugins rely on popular community packages such as
[express](https://github.com/visionmedia/express),
[kue](https://github.com/learnboost/kue),
[socket.io](https://github.com/learnboost/socket.io),
[winston](https://github.com/flatiron/winston),
[object-manage](https://github.com/snailjs/object-manage)
to make configuration and two-way communication a breeze.

APX is built to be test friendly out of the box and comes with a `testing`
mode in the configuration that will use mock services and increase testing speed.

## Why

Well we have evaluated and contributed to several other API servers and just kept
running into deficiencies, such as failure to use a popular library and not light-weight enough.

Thus, we created APX. It's light-weight, uses lots of modern packages, and wires them all
together in an extensible stateful environment.

## Usage

APX can be used homogeneously or through our
[generator](https://github.com/snailjs/generator-apx).

### Homogeneous
```
$ npm install apx apx-express-socket.io --save
```

**app.js**

```js
var apx = require('apx')

apx.once('ready',function(){
  console.log('APX is ready!')
})

//pass options and configure
apx.start({
  cwd: __dirname,
  translators: ['apx-express-socket.io'],
  express: {
    routes: [
      {get: {path: '/foo', file: 'actions/foo.js'}}
    ]
  },
  'socket-io': {
    enabled: false
  }
})
```

**actions/foo.js**

```js
exports.name = 'foo'
exports.description = 'Example Foo Action'
exports.run = function(apx,req,res,next){
  res.set('status','alive')
  next()
}
```

Run the application

`$ node app`

Check the result of the action `http://localhost:3000/foo`

### Generator

Our [generator](https://github.com/snailjs/generator-apx)
is a [yeoman](https://github.com/yeoman) generator instance
that will scaffold your entire API server.

**NOTICE** As of 0.6.0 the generator has not been completed yet.
We are waiting for the API to solidify before creating the generator.
This notice will be removed when the generator has been completed.

```
//install the generator
$ npm install generator-apx
//scaffold the initial app
$ yo apx
//scaffold a new action (with test)
$ yo apx:action <name>
//scaffold a new helper (with test)
$ yo apx:helper <name>
//scaffold a new initializer
$ yo apx:initializer <name>
//scaffold a new model
$ yo apx:model <name>
//scaffold a new service (with test)
$ yo apx:service <name>
//scaffold a new test (with test)
$ yo apx:task <name>
//scaffold a new translator
$ yo apx:translator <name>
```

## Structure

APX consists of several well-known idioms

* actions
* helpers
* initializers
* middleware
* models
* services
* tasks
* translators

### Actions

Actions are the bread and butter of an API server they serve all
requests and build responses. Actions are also in charge of firing
non-periodic tasks and utilizing services.

### Helpers

Helpers do not get loaded by the APX loading service however helpers
are meant to be common modules that assist actions and tasks. Generally
these are libraries that augment the `req`,`res` variables.

### Initializers

Initializers get executed when the server starts up and are only executed
once. These are useful for setting up database connections and loading
additional items into the environment.

### Middleware

Middleware is inspired by the idea of Connect Middleware and uses the same
principle format.

Middleware is executed before actions are fired and is passed the **Request** and
**Response** objects for augmentation.

Middleware is also the prescribed location to setup authentication handlers.

### Models

Models are optional, but since using models to store data has become so common
it seems silly not to support them in context and generators. Models do
not get loaded by the APX framework, but can be added during an initializer
or per action or task.

### Services

Services are just libraries that are treated as singletons. Services should
be used to maintain in-memory information, and/or provide access to data providers.
Models are services but services are not necessarily models.

### Tasks

Tasks are jobs which are run either periodically or scheduled to run by an action.
Tasks are considered headless and while they consume request data. They do not
provide response data. They can, however, log using [winston](https://github.com/flatiron/winston).

### Translators

In other frameworks these are sometimes called "servers". Translators are the
middleware that consumes connections and produce generic `Request` and `Response`
objects. An example of a translator would be an *express HTTP server*.

## Plugin Format

All parts of the structure are implemented in plugins. APX follows a simple plugin format
that is similar in all parts of user space. The main APX package only provides the plugin
loader and depends on plugins to add functionality to the system. This allows APX to be
non-opinionated.

#### Plugin Verbs / Nouns

There are a couple common verbs used in plugins.

* **run** -- Used to execute a function on a call event such as an action or task
* **start** -- Used in initializers and translators to start instances / listeners
* **stop** -- Used in initializers and translators to stop instances / listeners, and shutdown cleanly
* **pre** -- Used in middleware to be executed before the action
* **post** -- Used in middleware to be executed after the action

### Actions

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of task' //verbose description for generating maps
exports.run = function(apx,req,res,next){} //code to be executed by apx and fire the next(err) at the end
```

### Helpers

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of model' //verbose description for generating maps
exports.helper = {} //object exported by the helper can also be a constructor
```

### Initializers

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of initializer' //verbose description for generating maps
exports.start = function(apx,next){} //code to be executed to start the initializer, firing next(err) at the end
exports.stop = function(apx,next){} //code to be executed to stop the initializer, firing next(err) at the end
```

### Middleware

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of middleware' //verbose description for generating maps
//pre only
exports.run = function(apx,req,res,next){} //constructor function with a prototype for instantiation (for pre run only)
//-- or --
//pre and post
exports.pre = function(apx,req,res,next){} //run this function before the action
exports.post = function(apx,req,res,next){} //runt this function after the action
```

### Models

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of model' //verbose description for generating maps
exports.schema = {} //schema used to create the model
exports.model = {} //model object created by desired database software
```

### Services

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of service' //verbose description for generating maps
exports.service = function(){} //constructor function with a prototype for instantiation
```

### Translators

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of action or task' //verbose description for generating maps
exports.start = function(apx,next){} //code to be executed to start the translator, firing next(err) at the end
exports.stop = function(apx,next){} //code to be executed to stop the translator, firing next(err) at the end
```

### Tasks

```js
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of task' //verbose description for generating maps
exports.run = function(apx,req,next){} //code to be executed by apx and fire the next(err) at the end
```

## Clustering

Clustering in APX is a breeze. Simply use
[cluster-master](https://github.com/isaacs/cluster-master)

Here is a quick example

**app.js**

```js
var apx = require('./apx')

apx.once('ready',function(apx){
  console.log('APX is ready!',apx)
})

apx.start({
  cwd: __dirname + '/app',
  config: ['config.json'],
  initializers: ['apx-kue'],
  tasks: ['tasks/*.js'],
  translators: ['apx-express-socket.io']
  express: {
    port: 3000
  }
})
```

**server.js**

```js
var clusterMaster = require('cluster-master')

clusterMaster({
  exec: 'app.js',
  env: {NODE_ENV: 'production'},
  repl: {address: '127.0.0.1', port: 3002}
})
```

To start the cluster simply run

```
$ node server
```

## Events

APX is an **EventEmitter** and will emit various actions during its
lifecycle that can be used to hook for additional functionality.

**NOTE** The event emitter for APX is a singleton so be careful when
registering events as they may get fired by more than one instance. Thus,
its important to use the `once` operator on a lot of one-off events. Then
use the `dead` event to re-arm.

### readyStateChange

Fired each time the readyState of the system changes.

```js
var apx = require('apx')
apx.on('readyStateChange',function(readyState){
  console.log('APX changed ready state to ' + readyState)
})
```

The following ready states are supported.

* 0 - Dead (not started or stopped)
* 1 - Ready (completed init and ready to accept operations)
* 2 - Configured (finished configuring and ready to start)
* 3 - Starting (before init actions are fired)
* 4 - Stopping (before shutdown actions are fired)

### error

Fired any time an error occurs.

```js
var apx = require('apx')
apx.on('error',function(err){
  console.log('APX had an error',err)
})
```

### ready

Fired when configuration and init is completed

```js
var apx = require('apx')
apx.on('ready',function(inst){
  console.log('APX is ready',instance)
})
```

The instance after init is passed to the event.

### dead

Fired after shutdown has been completed.

```js
var apx = require('apx')
apx.on('dead',function(inst){
  console.log('APX has died',instance)
})
```

The instance after shutdown is passed to the event.

### runActionBefore

Fired before running an action.

```js
var apx = require('apx')
apx.on('runActionBefore',function(action){
  console.log('APX action before',action)
})
```

The action object is passed to the event.

### runActionAfter

Fired after running an action.

```js
var apx = require('apx')
apx.on('runActionAfter',function(action){
  console.log('APX action after',action)
})
```

The action object is passed to the event.

### runTaskBefore

Fired before running a task.

```js
var apx = require('apx')
apx.on('runTaskBefore',function(task){
  console.log('APX task before',task)
})
```

The task object is passed to the event.

### runTaskAfter

Fired after running a task.

```js
var apx = require('apx')
apx.on('runTaskAfter',function(task){
  console.log('APX task after',task)
})
```

The task object is passed to the event.

**NOTE** the instance is destroyed after this event.

## Configuration

APX uses [object-manage](https://github.com/snailjs/object-manage) to load
and manage configuration data.

This also means the APX instance emits the events from object-manage see below.

[object-manage Events](https://github.com/snailjs/object-manage#events)

### Schema

#### Testing
* Variable `testing`
* Default `false`

Testing mode will use [fakeredis](https://github.com/hdachev/fakeredis)
as much as possible and will not start listening on
any ports. However it will still offer a full featured
environment for writing tests. Testing mode will also
not start Kue which should not be needed to test tasks.

#### CWD (current working directory)
* Variable `cwd`
* Default `''`

The current working directory is used when loading
actions, services, and tasks.

#### Initializers
* Variable `initializers`
* Default `[]`

An array of [globs](https://github.com/isaacs/node-glob)
or objects or absolute file paths. That should be
executed when the server is started.

#### Tasks
* Variable `tasks`
* Default `[]`

An array of [globs](https://github.com/isaacs/node-glob)
or objects or absolute file paths. That will resolve
to tasks.

This must be provided at config time to they can be
loaded into Kue and scheduled if needed.

#### Translators
* Variable `translators`
* Default `[]`

An array of [globs](https://github.com/isaacs/node-glob)
or objects or absolute file paths. That will resolve
to translators that should be started when the
server is started

## Lifecycle API

The lifecycle functions control how APX is started, stopped and configured.

### Setup

Pass configuration parameters and instantiate the library. Does not
start initializers or translators.

```js
apx.setup({
  cwd: __dirname
})
```

### Start

Starts the APX server by starting initializers and translators. Once that is compelte
it fires the `ready` event which is passed the instance of APX.

```js
apx.setup({
  cwd: __dirname
})
apx.start()

//or for more convenience
apx.start({
  cwd: __dirname
})
```

**Note** If no object is passed to start and setup has not been called APX will
throw an exception `Tried to start APX without setting it up`

### Stop

Stops the APX server by stopping initializers and translators. Once that is complete
it fires the `dead` event and destroys the instance.

```js
apx.once('dead',function(){
  console.log('APX is now dead')
})
apx.once('ready',function(){
  apx.stop()
})
apx.start({cwd: __dirname})
```

### Restart

Restart the APX server by stopping initializers and translators and then restarting them.
Stop will fire the `dead` event.
Start will fire the `ready` event.

```js
apx.on('dead',function(){
  console.log('APX is now dead')
})
apx.on('ready',function(){
  console.log('APX is now ready')
})
apx.once('ready',function(){
  apx.restart()
})
apx.start({cwd: __dirname})
```

### Apx

Reference to the Apx constructor and its prototype. Useful for overriding prototypes before startup.

```js
console.log(apx.Apx.prototype.readyState) //0
```

### Instance

The current instance of APX is stored here. This can be use for mocking testing and passing the instance
instead of having APX do it manually.

```js
var initializer = require('apx-mongoose')
initializer.start(apx.instance,function(){
  console.log('Manually started apx-mongoose')
})
```

**Note** the instance will be `null` by default when APX has either yet to be started or after being stopped.

## Request and Response Objects

In APX the request and response objects create the common layer that translators iterate. They are instances of
[object-manage](https://github.com/snailjs/object-manage) and expose all the available methods. These objects,
however, **are not streams**. This is a limitation in some cases but it is the only to make the call stack for
middleware usable.

Nearly all API servers implement commands and it is up to the translator to supply any uploaded files which should
be written to temporary files using a tool like [formidable](https://github.com/felixge/node-formidable). After
that the action can direct the file to the correct location or transfer it to a storage cluster.

The request and response objects support a file object that points to an incoming temporary file or a file that should
be streamed to a file.

If there is a situation where file support is more important than command support then raw stream iteration should be
implemented in the translator. It is easy to take existing translators and modify them in userspace.

### Request

The request object contains information that is passed along from the request paths from the translator and is supplied
in object notation. Thus, `req.get('propertyName')` is the most common usage to retrieve information. However to allow
for the receiving of files there is a `req.files` array that shall be populated with files that were written to
temporary files during the request.

In order to access parts of the translator for more control over specific access mediums like the HTTP server the raw
request object shall be provided via `req.raw`

Example
```js
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
  req.get('foo') //bar
  req.raw.query.foo //bar
  res.success()
  next()
}
```

#### Add File

As a convenience for translators to add files to the request object the `addFile()` method exists.

Example
```js
var req = new Request()
req.addFile('foo.txt')
req.addFile('bar.txt')
```

### Response

The response object is built by the action and middleware which is then passed on to the user through the translators
desired output format. In most cases the output format is JSON but this is sometimes configurable at the translator
level.

#### Add Body Content

To allow the sending of raw data rather than JSON or any other format that can be transformed from an object the `add()`
method comes in handy.

Example
```js
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
  res.add('content to show')
  res.add('more content to show')
  next()
}
```

#### Success

As a convenience method `success()` exists to signal success to the client. This method uses a standard response format.
That resembles the following. Success also accepts a few argument combinations to allow more structured responses
without additional function calls.

Format
```json
{"status": "ok", "message": "success", "code": "0"}
```

Example
```js
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
  res.success() //sends message: 'success', code: '0'
  res.success('foo') //sends message: 'foo', code: '0'
  res.success('foo',4) //send message: 'foo', code: '4'
  res.success('foo',4,{id: 'bar'}) //sends message: 'foo', code: '4', id: 'bar'
  res.success('foo',{id: 'bar'}) //sends message: 'foo', code: '0', id: 'bar'
  res.success({id: 'bar'}) //sends message: 'success', code: '0', id: 'bar'
  next()
}
```

#### Error

For easier error handling the error method can be used to pass an erroneous response to the client and accepts a
few different combinations of arguments to supply the user with information about the error.

Format
```json
{"status": "error", "message": "error", "code": "1"}
```

Example
```js
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
  res.error() //sends message: 'An error has occurred', code: '1'
  res.error('foo') //sends message: 'foo', code: '1'
  res.error('foo',4) //send message: 'foo', code: '4'
  res.error('foo',4,{id: 'bar'}) //sends message: 'foo', code: '4', id: 'bar'
  res.error('foo',{id: 'bar'}) //sends message: 'foo', code: '1', id: 'bar'
  res.error({id: 'bar'}) //sends message: 'An error has occurred', code: '1', id: 'bar'
  next()
}
```

#### Send File

Sometimes it is useful to send clients a file thus the `sendFile(path)` method exists. This will notify the translator
that a file should be sent to the user and allows the translator to properly handle streaming the file to the user.

When a file by that path cannot be found it will throw an exception.

**NOTE** Whenever this method is called it will supersede any other output that has been queued to be sent to the user
by using `add()` or `set()`. Unless the translator is capable of sending multipart responses.

Example
```js
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
  res.sendFile('/tmp/foo','home.html',{tmpFile: true}) //setting tmpFile to true will delete the file after sending
  next()
}
```

#### Render

In order for translators to properly handle sending data to their clients there are 3 scenarios which apply to how
the render function will respond.

* **format** this is the format of the response which will be **object**, **raw**, or **file**
* **mimeType** the detected or manually set mime type of the response should be used to respond in various
formats when using the **object** type.
* **body** this is the content container for the **raw** format
* **data** this is the content container for the **object** format and contains the data object to be exported
* **file** this is a reference to the file object when using the **file** format

#### Example

In this example the output will simply be logged to the console.

```js
var xml = require('xml')
  , fs = require('fs')
  , Response = require('apx/lib/Response')
  , res = new Response()

//create our response handler
var responseHandler = function(err,response){
  if(err) throw err
  if('object' === response.format){
    if('text/json' === response.mimeType){
      console.log(JSON.stringify(response.data))
    } else if('text/xml' === response.mimeType){
      console.log(xml(response.data))
    } else {
      console.warn('desired output type of ' + response.mimeType + ' is not supported defaulting to JSON')
      console.log(JSON.stringify(response.data))
    }
  } else if('raw' === response.format){
    console.log(response.body)
  } else if('file' === response.format){
    var stream = fs.createReadStream(response.file.path)
    stream.on('readable',function(){
      var chunk
      while(null !== (chunk = stream.read())){
        console.log(chunk)
      }
    }
  } else {
    console.warn('desired output format of ' + response.format + ' is not supported, not sending output')
  }
}

//implement the handler
res.render(responseHandler)
```

## Changelog

### 0.7.2
* Fixed #5 where the post chain is broken by legacy middleware.

### 0.7.1
* Changed the way runAction and runTask populate the request to prevent object merging issues

### 0.7.0
* Upgraded to object-manage 0.7.0 which changes how the constructor and load accept arguments
* APX, Request, and Response all inherit the changed constructor functionality of object-manage

### 0.6.1
* Added support for charsets in Response object
* Changed the default mimeType from text/json to application/json
* Fixed small bug with passing arrays to runAction and runTask as data

### 0.6.0
* Request objects now implement the file object
* Response objects now implement the file object
* Response.send() removed in favor of the existing **object-manage** functions
* In order to support `pre` and `post` middleware translators need to fire the `Response.render()` method and then send
the rendered response to their client
* Upgraded **middleware**, **model**, **service** and **helper** plugin format. This will require upgrading of existing
plugins and makes this version incompatible with older plugins.
* Added `Response.sendFile(path)` to allow sending of files to the user. Using this method still requires calling `next()`
and will supersede any existing output.
* Improved `Response.success()` and `Response.error()` to accept a better combination of arguments to produce
usable responses with a single function call.

### 0.5.0

* Implementation of APX authentication system [#3](https://github.com/snailjs/apx/issues/3)
* APX now loads packages exactly like Node's `require()`. Except for the addition of parsing
globs. [see this](http://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders)
* Middleware now supports `pre` and `post` actions with a default of `run` which will be fired before
the action.

### 0.4.0
* Usage no longer involves `new Apx` the returned object is now an event emitter
* Changed lifecycle management and abstract usage of the APX library. This changes
usage of APX and will require upgrading.
* SysLog added for core level logging. Winston should be used for user-space logging.
* Kue removed from core package and abstracted to [apx-kue](https://github.com/snailjs/apx-kue)
* Winston removed from core package and abstracted to [apx-winston](https://github.com/snailjs/apx-winston)
* Tasks are no longer initialized by the core should be implemented in an initializer
* Updated plugin format (this means existing initializer/translator/service plugins will need to upgrade) see the README
for the prescribed plugin format.
* Added `'use strict';` statements to all files and removed testing init file
* APX is now an event emitter and `onReady` has been removed see README for events
* Response object no longer accepts a callback and actions should fire next explictly with any errors. See
plugin format in the README for details.
* Added the idea of middleware that is executed in order before each action process.

### 0.3.4
* Updated to **object-manage** 0.4.0
* Restored `Request.data` and `Response.data` as references to the managed objects.
* Fixed issue with tasks being passed the entire `job` object instead of `job.data`

### 0.3.3
* Updated to **object-manage** 0.3.0

### 0.3.2
* Final fix for redis in testing mode

### 0.3.1
* Fixed using real redis during testing mode

### 0.3.0
* Fixes [#2](https://github.com/snailjs/apx/issues/1) - Objects are now disallowed from being passed to the config
* Loading framework now more async friendly
* Init is handled completely async
* Fixed minor issue with Response object not rendering JSON properly
* Removed unused dependencies
* Updated object-manage upstream

### 0.2.1
* Fixes [#1](https://github.com/snailjs/apx/issues/1) - Fails when loading required translator

### 0.2.0
* Dropped convict in favor of object-manage

### 0.1.0
* Initial release


text:
#include "sp/Common.h"
#include "Mesh.h"

namespace sp { namespace graphics {

	struct SP_API RendererUniform
	{
		String uniform;
		byte* value;
	};

	struct SP_API RenderCommand
	{
		Mesh* mesh;
		maths::mat4 transform;
		API::Shader* shader;
		maths::mat4 bones[64];
		std::vector<RendererUniform> uniforms;
	};

} }


text:
using namespace std;
namespace xx {

Bullet::Bullet():
    mVelX(5),
    mVelY(5),
    mRange(0),
    mExist(false),
    mBody(NULL),
    mLoadedImg(false),
    mPlayer(NULL),
    mInitialAngle(0),
    mNoRender(false)
{}

Bullet::~Bullet() {
}

void Bullet::free() {
    if (mLoadedImg) {
        img.free();
    }
}

void Bullet::destroy() {
    if (mExist) {
        if (mBody == NULL) {
            return;
        }
        cpShape *shape = mBody->shapeList;
        cpSpace *space = cpBodyGetSpace( mBody );

        cpSpaceRemoveShape( space, shape );
        cpSpaceRemoveBody( space, mBody );
        cpShapeFree( shape );
        cpBodyFree( mBody );

        mBody = NULL;
        mExist = false;

    }
    mRange = 0;
}

void Bullet::createBullet(SDL_Renderer *r, cpSpace *space, double range, Player * player, bool noRender) {
    mNoRender = noRender;
    //printf("in bullet %d\n", player);
    mVelX = player->velX();
    mVelY = player->velY();
    cpVect v = cpv(mVelX, mVelY);
    cpVect resV = cpvmult(cpvmult(v, 1./cpvlength(cpv(mVelX, mVelY))), BULLET_SPEED);
    mVelX = resV.x;
    mVelY = resV.y;
    mInitialAngle = player->angle();
    mPosX = player->posX();
    mPosY = player->posY();
    //mX = player->sensor();
    mPlayer = player;

    if (!mNoRender && !mLoadedImg) {
        mLoadedImg = true;
        img.loadFromFile(r, BULLET_IMG);
    }

    mExist = true;
    mRange = range;
    mBody = cpBodyNew(0.1f, INFINITY);

    mBody->p.x = mPosX;
    mBody->p.y = mPosY;

    //printf("%d \n",mBody->userData);

    cpBodySetCenterOfGravity(mBody, cpv(BULLET_WIDTH/2, BULLET_HEIGHT/2));
    cpShape *shape;

    shape = cpBoxShapeNew(mBody, BULLET_WIDTH, BULLET_HEIGHT, 0);
    cpShapeSetCollisionType(shape, BULLET_TYPE);
    //cpShapeSetSensor(shape, true);
    cpSpaceAddShape(space, shape);
    cpSpaceAddBody(space, mBody);

    cpBodySetAngle(mBody, mInitialAngle);
    cpBodySetUserData(mBody, this);

    cpBodySetVelocity(mBody, cpv(v.x, 100));
    cpBodyApplyImpulseAtLocalPoint(mBody, cpv(0, -60), cpv(0, -BULLET_HEIGHT/2));
    if (mInitialAngle < M_PI) {
        cpBodySetAngularVelocity(mBody, 1);
    } else {
        cpBodySetAngularVelocity(mBody, -1);
    }
}

void Bullet::render(SDL_Renderer * r) {
    cpVect pos = cpBodyGetPosition(mBody);
    cpVect cog = cpBodyGetCenterOfGravity(mBody);
    cpFloat angle = cpBodyGetAngle(mBody);
    //cpShape *shape = mBody->shapeList;
    //cpBody * b = shape->body;
    if (!mNoRender) {
        img.render(r, (int)pos.x - cog.x, (int)pos.y - cog.y, NULL ,(double)rad2deg(angle), NULL, SDL_FLIP_NONE);
    }
}

void Bullet::move() {
    //mBody->p.x += mVelX;
    //mBody->p.y += mVelY;
    //cpBodySetAngle(mBody, cpvtoangle(cpv(mVelX, mVelY)));
    if ((cpBodyGetAngle(mBody) > M_PI) xor (mInitialAngle > M_PI)) {
        cpBodySetAngle(mBody, M_PI);
    }
    cpVect v = cpBodyGetVelocity(mBody);
    if (abs(v.y) <= 10) {
        cpBodySetVelocity(mBody, cpv(v.x, 100));
    }

    if(cpvdist(cpBodyGetPosition(mBody), cpv(mPosX, mPosY)) > mRange) {
       destroy();
    }
}

}//Ns end


text:
package com.google.security.zynamics.zylib.disassembly;

public interface IReplacement {
  @Override
  String toString();
}


text:
void string_tests()
{
    compile_time_tests((std::string*) 0);

    HASH_NAMESPACE::hash<std::string> x1;
    HASH_NAMESPACE::hash<std::string> x2;

    BOOST_TEST(x1("Hello") == x2(std::string("Hel") + "lo"));
    BOOST_TEST(x1("") == x2(std::string()));

#if defined(TEST_EXTENSIONS)
    std::string value1;
    std::string value2("Hello");

    BOOST_TEST(x1(value1) == HASH_NAMESPACE::hash_value(value1));
    BOOST_TEST(x1(value2) == HASH_NAMESPACE::hash_value(value2));
    BOOST_TEST(HASH_NAMESPACE::hash_value(value1) ==
            HASH_NAMESPACE::hash_range(value1.begin(), value1.end()));
    BOOST_TEST(HASH_NAMESPACE::hash_value(value2) ==
            HASH_NAMESPACE::hash_range(value2.begin(), value2.end()));
#endif
}

#if !defined(BOOST_NO_STD_WSTRING)
void wstring_tests()
{
    compile_time_tests((std::wstring*) 0);

    HASH_NAMESPACE::hash<std::wstring> x1;
    HASH_NAMESPACE::hash<std::wstring> x2;

    BOOST_TEST(x1(L"Hello") == x2(std::wstring(L"Hel") + L"lo"));
    BOOST_TEST(x1(L"") == x2(std::wstring()));

#if defined(TEST_EXTENSIONS)
    std::wstring value1;
    std::wstring value2(L"Hello");

    BOOST_TEST(x1(value1) == HASH_NAMESPACE::hash_value(value1));
    BOOST_TEST(x1(value2) == HASH_NAMESPACE::hash_value(value2));
    BOOST_TEST(HASH_NAMESPACE::hash_value(value1) ==
            HASH_NAMESPACE::hash_range(value1.begin(), value1.end()));
    BOOST_TEST(HASH_NAMESPACE::hash_value(value2) ==
            HASH_NAMESPACE::hash_range(value2.begin(), value2.end()));
#endif
}
#endif

int main()
{
    string_tests();
#if !defined(BOOST_NO_STD_WSTRING)
    wstring_tests();
#endif
    return boost::report_errors();
}


text:
from __future__ import absolute_import, print_function, unicode_literals

from .default import *  # NOQA

AUTH_PASSWORD_VALIDATORS = []

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
XML Schema API: Interface  XSAttributeGroupDefinition
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.xerces.xs

Interface  XSAttributeGroupDefinition

All Superinterfaces:
XSObject

public interface XSAttributeGroupDefinition
extends XSObject

This interface represents the Attribute Group Definition schema component.

Method Summary

 XSAnnotation
getAnnotation()

          An annotation if it exists, otherwise null.

 XSObjectList
getAnnotations()

          A sequence of [annotations] or an empty XSObjectList.

 XSObjectList
getAttributeUses()

          A set of [attribute uses] if it exists, otherwise an empty
 XSObjectList.

 XSWildcard
getAttributeWildcard()

          A [wildcard] if it exists, otherwise null.

Methods inherited from interface org.apache.xerces.xs.XSObject

getName, getNamespace, getNamespaceItem, getType

Method Detail

getAttributeUses

public XSObjectList getAttributeUses()

A set of [attribute uses] if it exists, otherwise an empty
 XSObjectList.

getAttributeWildcard

public XSWildcard getAttributeWildcard()

A [wildcard] if it exists, otherwise null.

getAnnotation

public XSAnnotation getAnnotation()

An annotation if it exists, otherwise null. If not null
 then the first [annotation] from the sequence of annotations.

getAnnotations

public XSObjectList getAnnotations()

A sequence of [annotations] or an empty XSObjectList.

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/*!
 * Next JS
 * Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved.
 * http://www.xenophy.com
 */

// {{{ NX.server.Worker.init

module.exports = function(config) {

    config = config || {};

    NX.applyIf(this.config, config);

};

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */


text:
<?php

namespace Psy\Readline;

/**
 * A Readline interface implementation for GNU Readline.
 *
 * This is by far the coolest way to do it, but it doesn't work with new PHP.
 *
 * Oh well.
 */
class GNUReadline implements Readline
{
    protected $historyFile;
    protected $historySize;
    protected $eraseDups;

    /**
     * GNU Readline is supported iff `readline_list_history` is defined. PHP
     * decided it would be awesome to swap out GNU Readline for Libedit, but
     * they ended up shipping an incomplete implementation. So we've got this.
     *
     * @return bool
     */
    public static function isSupported()
    {
        return function_exists('readline_list_history');
    }

    /**
     * GNU Readline constructor.
     */
    public function __construct($historyFile = null, $historySize = 0, $eraseDups = false)
    {
        $this->historyFile = $historyFile;
        $this->historySize = $historySize;
        $this->eraseDups = $eraseDups;
    }

    /**
     * {@inheritDoc}
     */
    public function addHistory($line)
    {
        if ($res = readline_add_history($line)) {
            $this->writeHistory();
        }

        return $res;
    }

    /**
     * {@inheritDoc}
     */
    public function clearHistory()
    {
        if ($res = readline_clear_history()) {
            $this->writeHistory();
        }

        return $res;
    }

    /**
     * {@inheritDoc}
     */
    public function listHistory()
    {
        return readline_list_history();
    }

    /**
     * {@inheritDoc}
     */
    public function readHistory()
    {
        readline_read_history();
        readline_clear_history();

        return readline_read_history($this->historyFile);
    }

    /**
     * {@inheritDoc}
     */
    public function readline($prompt = null)
    {
        return readline($prompt);
    }

    /**
     * {@inheritDoc}
     */
    public function redisplay()
    {
        readline_redisplay();
    }

    /**
     * {@inheritDoc}
     */
    public function writeHistory()
    {
        // We have to write history first, since it is used
        // by Libedit to list history
        $res = readline_write_history($this->historyFile);
        if (!$res || !$this->eraseDups && !$this->historySize > 0) {
            return $res;
        }

        $hist = $this->listHistory();
        if (!$hist) {
            return true;
        }

        if ($this->eraseDups) {
            // flip-flip technique: removes duplicates, latest entries win.
            $hist = array_flip(array_flip($hist));
            // sort on keys to get the order back
            ksort($hist);
        }

        if ($this->historySize > 0) {
            $histsize = count($hist);
            if ($histsize > $this->historySize) {
                $hist = array_slice($hist, $histsize - $this->historySize);
            }
        }

        readline_clear_history();
        foreach ($hist as $line) {
            readline_add_history($line);
        }

        return readline_write_history($this->historyFile);
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @ignore
 * getScript support for css and js callback after load
 * @author yiminghe@gmail.com, lifesinger@gmail.com
 */
(function (S) {

    var MILLISECONDS_OF_SECOND = 1000,
        doc = S.Env.host.document,
        utils = S.Loader.Utils,
        Path = S.Path,
        jsCssCallbacks = {},
        UA = S.UA,
    // onload for webkit 535.23  Firefox 9.0
    // https://bugs.webkit.org/show_activity.cgi?id=38995
    // https://bugzilla.mozilla.org/show_bug.cgi?id=185236
    // https://developer.mozilla.org/en/HTML/Element/link#Stylesheet_load_events
    // phantomjs 1.7 == webkit 534.34
        isOldWebKit = UA.webkit < 536;

    S.mix(S, {
        /**
         * Load a javascript/css file from the server using a GET HTTP request,
         * then execute it.
         *
         * for example:
         *      @example
         *      getScript(url, success, charset);
         *      // or
         *      getScript(url, {
         *          charset: string
         *          success: fn,
         *          error: fn,
         *          timeout: number
         *      });
         *
         * Note 404/500 status in ie<9 will trigger success callback.
         * If you want a jsonp operation, please use {@link KISSY.IO} instead.
         *
         * @param {String} url resource's url
         * @param {Function|Object} [success] success callback or config
         * @param {Function} [success.success] success callback
         * @param {Function} [success.error] error callback
         * @param {Number} [success.timeout] timeout (s)
         * @param {String} [success.charset] charset of current resource
         * @param {String} [charset] charset of current resource
         * @return {HTMLElement} script/style node
         * @member KISSY
         */
        getScript: function (url, success, charset) {
            // can not use KISSY.Uri, url can not be encoded for some url
            // eg: /??dom.js,event.js , ? , should not be encoded
            var config = success,
                css = 0,
                error,
                timeout,
                attrs,
                callbacks,
                timer;

            if (S.startsWith(Path.extname(url).toLowerCase(), '.css')) {
                css = 1;
            }

            if (S.isPlainObject(config)) {
                success = config['success'];
                error = config['error'];
                timeout = config['timeout'];
                charset = config['charset'];
                attrs = config['attrs'];
            }

            callbacks = jsCssCallbacks[url] = jsCssCallbacks[url] || [];

            callbacks.push([success, error]);

            if (callbacks.length > 1) {
                // S.log(' queue js : ' + callbacks.length + ' : for :' + url + ' by ' + (config.source || ''));
                return callbacks.node;
            } else {
                // S.log('init getScript : by ' + config.source);
            }

            var head = utils.docHead(),
                node = doc.createElement(css ? 'link' : 'script'),
                clearTimer = function () {
                    if (timer) {
                        timer.cancel();
                        timer = undefined;
                    }
                };

            if (attrs) {
                S.each(attrs, function (v, n) {
                    node.setAttribute(n, v);
                });
            }

            if (css) {
                node.href = url;
                node.rel = 'stylesheet';
            } else {
                node.src = url;
                node.async = true;
            }

            callbacks.node = node;

            if (charset) {
                node.charset = charset;
            }

            var end = function (error) {
                    var index = error,
                        fn;
                    clearTimer();
                    S.each(jsCssCallbacks[url], function (callback) {
                        if (fn = callback[index]) {
                            fn.call(node);
                        }
                    });
                    delete jsCssCallbacks[url];
                },
                useNative = !css;

            if (css) {
                if (isOldWebKit) {
                    useNative = false;
                } else {
                    useNative = 'onload' in node;
                }
            }

            //标准浏览器 css and all script
            if (useNative) {
                node.onload = node.onreadystatechange = function () {
                    var readyState = node.readyState;
                    if (!readyState ||
                        readyState == "loaded" ||
                        readyState == "complete") {
                        node.onreadystatechange = node.onload = null;
                        end(0)
                    }
                };
                node.onerror = function () {
                    node.onerror = null;
                    end(1);
                };
            }
            // old chrome/firefox for css
            else {
                utils.pollCss(node, function () {
                    end(0);
                });
            }

            if (timeout) {
                timer = S.later(function () {
                    end(1);
                }, timeout * MILLISECONDS_OF_SECOND);
            }
            if (css) {
                // css order matters
                // so can not use css in head
                head.appendChild(node);
            } else {
                // can use js in head
                head.insertBefore(node, head.firstChild);
            }
            return node;
        }
    });

})(KISSY);
/*
 yiminghe@gmail.com refactor@2012-03-29
 - 考虑连续重复请求单个 script 的情况,内部排队

 yiminghe@gmail.com 2012-03-13
 - getScript
 - 404 in ie<9 trigger success , others trigger error
 - syntax error in all trigger success
 */


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui;

import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.internal.statistic.service.fus.collectors.UIEventLogger;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowManagerListener;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.components.fields.ExtendableTextField;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.speedSearch.SpeedSearch;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.Alarm;
import com.intellij.util.text.NameUtilCore;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ListIterator;
import java.util.NoSuchElementException;

import static com.intellij.util.ReflectionUtil.getMethodDeclaringClass;

/**
 * Use {@link com.intellij.ui.speedSearch.SpeedSearchUtil} in renderer to highlight matching results
 */
public abstract class SpeedSearchBase<Comp extends JComponent> extends SpeedSearchSupply {
  private static final Logger LOG = Logger.getInstance(SpeedSearchBase.class);

  protected static final Border BORDER = new CustomLineBorder(JBColor.namedColor("SpeedSearch.borderColor", JBColor.LIGHT_GRAY), JBUI.insets(1));
  protected static final Color FOREGROUND_COLOR = JBColor.namedColor("SpeedSearch.foreground", UIUtil.getToolTipForeground());
  protected static final Color BACKGROUND_COLOR = JBColor.namedColor("SpeedSearch.background", new JBColor(Gray.xFF, Gray._111));
  protected static final Color ERROR_FOREGROUND_COLOR = JBColor.namedColor("SpeedSearch.errorForeground", JBColor.RED);

  private static final Key<String> SEARCH_TEXT_KEY = Key.create("SpeedSearch.searchText");

  private SearchPopup mySearchPopup;
  private JLayeredPane myPopupLayeredPane;
  protected final Comp myComponent;
  private final ToolWindowManagerListener myWindowManagerListener = new ToolWindowManagerListener() {
    @Override
    public void stateChanged(@NotNull ToolWindowManager toolWindowManager) {
        if (!isInsideActiveToolWindow(toolWindowManager)) {
          manageSearchPopup(null);
        }
    }

    private boolean isInsideActiveToolWindow(@NotNull ToolWindowManager toolWindowManager) {
      ToolWindow toolWindow = toolWindowManager.getToolWindow(toolWindowManager.getActiveToolWindowId());
      return toolWindow != null && SwingUtilities.isDescendingFrom(myComponent, toolWindow.getComponent());
    }
  };
  private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this);
  private String myRecentEnteredPrefix;
  private SpeedSearchComparator myComparator = new SpeedSearchComparator(false);
  private boolean myClearSearchOnNavigateNoMatch;

  private Disposable myListenerDisposable;
  private Alarm myProcessKeyEventAlarm = null;

  public SpeedSearchBase(@NotNull Comp component) {
    myComponent = component;

    myComponent.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentHidden(ComponentEvent event) {
        if (isPopupActive()) {
          manageSearchPopup(null);
        }
      }

      @Override
      public void componentMoved(ComponentEvent event) {
        moveSearchPopup();
      }

      @Override
      public void componentResized(ComponentEvent event) {
        moveSearchPopup();
      }
    });
    myComponent.addFocusListener(new FocusAdapter() {
      @Override
      public void focusLost(FocusEvent e) {
        manageSearchPopup(null);
      }

      @Override
      public void focusGained(FocusEvent e) {
        if (!isStickySearch()) return;
        String text = UIUtil.getClientProperty(myComponent, SEARCH_TEXT_KEY);
        if (StringUtil.isEmpty(text)) return;
        ApplicationManager.getApplication().invokeLater(() -> {
          if (myComponent.hasFocus()) {
            manageSearchPopup(createPopup(text)); // keep selection
          }
        });
      }
    });
    myComponent.addKeyListener(new KeyAdapter() {
      @Override
      public void keyTyped(KeyEvent e) {
        processKeyEvent(e);
      }

      @Override
      public void keyPressed(KeyEvent e) {
        processKeyEvent(e);
      }
    });

    new AnAction() {
      @Override
      public void actionPerformed(@NotNull AnActionEvent e) {
        final String prefix = getEnteredPrefix();
        assert prefix != null;
        final String[] strings = NameUtilCore.splitNameIntoWords(prefix);
        final String last = strings[strings.length - 1];
        final int i = prefix.lastIndexOf(last);
        mySearchPopup.mySearchField.setText(prefix.substring(0, i).trim());
      }

      @Override
      public void update(@NotNull AnActionEvent e) {
        e.getPresentation().setEnabled(isPopupActive() && !StringUtil.isEmpty(getEnteredPrefix()));
      }
    }.registerCustomShortcutSet(CustomShortcutSet.fromString(SystemInfo.isMac ? "meta BACK_SPACE" : "control BACK_SPACE"), myComponent);

    installSupplyTo(component);
  }

  protected boolean isStickySearch() {
    return false;
  }

  @Nullable
  public JTextField getSearchField() {
    if (mySearchPopup != null) {
      return mySearchPopup.mySearchField;
    }
    return null;
  }

  public static boolean hasActiveSpeedSearch(JComponent component) {
    return getSupply(component) != null;
  }

  public void setClearSearchOnNavigateNoMatch(boolean clearSearchOnNavigateNoMatch) {
    myClearSearchOnNavigateNoMatch = clearSearchOnNavigateNoMatch;
  }

  @Override
  public boolean isPopupActive() {
    return mySearchPopup != null && mySearchPopup.isVisible() ||
           isStickySearch() && StringUtil.isNotEmpty(UIUtil.getClientProperty(myComponent, SEARCH_TEXT_KEY));
  }

  @Override
  public Iterable<TextRange> matchingFragments(@NotNull String text) {
    if (!isPopupActive()) return null;
    final SpeedSearchComparator comparator = getComparator();
    final String recentSearchText = comparator.getRecentSearchText();
    return StringUtil.isNotEmpty(recentSearchText) ? comparator.matchingFragments(recentSearchText, text) : null;
  }

  /**
   * Returns visual (view) selection index.
   */
  protected abstract int getSelectedIndex();

  /** @deprecated Please implement {@link #getElementCount()} and {@link #getElementAt(int)} instead. */
  @ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
  @Deprecated
  protected Object @NotNull [] getAllElements() {
    throw new UnsupportedOperationException("See `SpeedSearchBase.getElementIterator(int)` javadoc");
  }

  @Nullable
  protected abstract String getElementText(Object element);

  protected int getElementCount() {
    LOG.warn("Please implement getElementCount() and getElementAt(int) in " + getClass().getName());
    return getAllElements().length;
  }

  protected Object getElementAt(int viewIndex) {
    throw new UnsupportedOperationException();
  }

  /** @deprecated Please implement {@link #getElementCount()} and {@link #getElementAt(int)} instead. */
  @ApiStatus.ScheduledForRemoval(inVersion = "2022.1")
  @Deprecated
  protected int convertIndexToModel(final int viewIndex) {
    return viewIndex;
  }

  /**
   * @param element Element to select. Don't forget to convert model index to view index if needed (i.e. table.convertRowIndexToView(modelIndex), etc.).
   * @param selectedText search text
   */
  protected abstract void selectElement(Object element, String selectedText);

  /**
   * The main method for items traversal.
   *
   * Implementations can override it or use the default implementation
   * that uses {@link #getElementAt(int)} and {@link #getElementCount()} methods.
   *
   * The old and now deprecated API uses {@link #getAllElements()} and {@link #convertIndexToModel(int)} methods.
   */
  @NotNull
  protected ListIterator<Object> getElementIterator(int startingViewIndex) {
    return new MyListIterator(this, startingViewIndex);
  }

  @Override
  public void addChangeListener(@NotNull PropertyChangeListener listener) {
    myChangeSupport.addPropertyChangeListener(listener);
  }

  @Override
  public void removeChangeListener(@NotNull PropertyChangeListener listener) {
    myChangeSupport.removePropertyChangeListener(listener);
  }

  @ApiStatus.Internal
  protected void fireStateChanged() {
    String enteredPrefix = getEnteredPrefix();
    myChangeSupport.firePropertyChange(ENTERED_PREFIX_PROPERTY_NAME, myRecentEnteredPrefix, enteredPrefix);
    myRecentEnteredPrefix = enteredPrefix;
  }

  protected boolean isMatchingElement(Object element, String pattern) {
    String str = getElementText(element);
    return str != null && compare(str, pattern);
  }

  protected boolean compare(@NotNull String text, @Nullable String pattern) {
    return pattern != null && myComparator.matchingFragments(pattern, text) != null;
  }

  public SpeedSearchComparator getComparator() {
    return myComparator;
  }

  public void setComparator(final SpeedSearchComparator comparator) {
    myComparator = comparator;
  }

  protected @Nullable Object findPreviousElement(String s) {
    final int index = getSelectedIndex();

    final ListIterator<Object> iterator = getElementIterator(index);

    final Object currentElement = getCurrentElement(iterator);
    final Object element = doFindPreviousElement(iterator, s.trim(), UISettings.getInstance().getCycleScrolling());

    if (element != null) return element;

    return currentElement != null && isMatchingElement(currentElement, s) ? currentElement : null;
  }

  private @Nullable Object doFindPreviousElement(@NotNull ListIterator<Object> iterator,
                                                 @NotNull String pattern,
                                                 boolean cycleScrolling) {
    while (iterator.hasPrevious()) {
      final Object previous = iterator.previous();
      if (isMatchingElement(previous, pattern)) {
        return previous;
      }
    }

    if (cycleScrolling) {
      while (iterator.hasNext()) {
        iterator.next();
      }
      return doFindPreviousElement(iterator, pattern, false);
    }

    return null;
  }

  protected @Nullable Object findNextElement(String s) {
    final int index = getSelectedIndex();
    final ListIterator<Object> iterator = getElementIterator(index + 1);

    final Object currentElement = getCurrentElement(iterator);

    final Object element = doFindNextElement(iterator, s.trim(), UISettings.getInstance().getCycleScrolling());
    if (element != null) return element;

    return currentElement != null && isMatchingElement(currentElement, s) ? currentElement : null;
  }

  private @Nullable Object doFindNextElement(@NotNull ListIterator<Object> iterator,
                                             @NotNull String pattern,
                                             boolean cycleScrolling) {

    while (iterator.hasNext()) {
      final Object next = iterator.next();
      if (isMatchingElement(next, pattern)) {
        return next;
      }
    }
    if (cycleScrolling) {
      while (iterator.hasPrevious()) {
        iterator.previous();
      }
      return doFindNextElement(iterator, pattern, false);
    }

    return null;
  }

  private static @Nullable Object getCurrentElement(ListIterator<Object> iterator) {
    final Object current;
    if (iterator.hasPrevious()) {
      current = iterator.previous();
      iterator.next();
    }
    else if (iterator.hasNext()) {
      current = iterator.next();
      iterator.previous();
    }
    else {
      current = null;
    }
    return current;
  }

  @Nullable
  protected Object findElement(@NotNull String s) {
    int selectedIndex = getSelectedIndex();
    if (selectedIndex < 0) {
      selectedIndex = 0;
    }
    final ListIterator<Object> iterator = getElementIterator(selectedIndex);
    final String _s = s.trim();
    while (iterator.hasNext()) {
      final Object element = iterator.next();
      if (isMatchingElement(element, _s)) {
        return element;
      }
    }
    if (selectedIndex > 0) {
      while (iterator.hasPrevious()) iterator.previous();
      while (iterator.hasNext() && iterator.nextIndex() != selectedIndex) {
        final Object element = iterator.next();
        if (isMatchingElement(element, _s)) {
          return element;
        }
      }
    }
    return null;
  }

  @Nullable
  private Object findFirstElement(String s) {
    final String pattern = s.trim();
    final ListIterator<Object> iterator = getElementIterator(0);
    while (iterator.hasNext()) {
      final Object element = iterator.next();
      if (isMatchingElement(element, pattern)) return element;
    }
    return null;
  }

  @Nullable
  private Object findLastElement(String s) {
    final String pattern = s.trim();
    final ListIterator<Object> iterator = getElementIterator(getElementCount() - 1);
    while (iterator.hasPrevious()) {
      final Object element = iterator.previous();
      if (isMatchingElement(element, pattern)) return element;
    }
    return null;
  }

  public void showPopup(String searchText) {
    manageSearchPopup(createPopup(searchText));
    if (mySearchPopup != null && myComponent.isDisplayable()) {
      mySearchPopup.refreshSelection();
    }
  }

  public void showPopup() {
    showPopup("");
  }

  public void hidePopup() {
    JTextField field = getSearchField();
    if (field != null) field.setText("");
    manageSearchPopup(null);
  }

  protected void processKeyEvent(KeyEvent e) {
    if (e.isAltDown()) return;
    if (e.isShiftDown() && isNavigationKey(e.getKeyCode())) return;
    if (mySearchPopup != null) {
      mySearchPopup.processKeyEvent(e);
      return;
    }
    if (!isSpeedSearchEnabled()) return;
    if (e.getID() == KeyEvent.KEY_TYPED) {
      if (!UIUtil.isReallyTypedEvent(e)) return;

      char c = e.getKeyChar();
      if (Character.isLetterOrDigit(c) || !Character.isWhitespace(c) && SpeedSearch.PUNCTUATION_MARKS.indexOf(c) != -1) {
        showPopup(String.valueOf(c));
        e.consume();
      }
    }
  }

  @NotNull
  protected SpeedSearchBase<Comp>.SearchPopup createPopup(String s) {
    return new SearchPopup(s);
  }

  public Comp getComponent() {
    return myComponent;
  }

  protected boolean isSpeedSearchEnabled() {
    return true;
  }

  @Override
  @Nullable
  @NlsSafe
  public String getEnteredPrefix() {
    return mySearchPopup != null ? mySearchPopup.mySearchField.getText() : null;
  }

  @Override
  public void refreshSelection() {
    if ( mySearchPopup != null ) mySearchPopup.refreshSelection();
  }

  @Override
  public void findAndSelectElement(@NotNull String searchQuery) {
    selectElement(findElement(searchQuery), searchQuery);
  }

  public boolean adjustSelection(int keyCode, @NotNull String searchQuery) {
    if (isUpDownHomeEnd(keyCode)) {
      UIEventLogger.IncrementalSearchNextPrevItemSelected.log(myComponent.getClass());
      Object element = findTargetElement(keyCode, searchQuery);
      if (element != null) {
        selectElement(element, searchQuery);
        return true;
      }
    }
    return false;
  }

  @Nullable
  private Object findTargetElement(int keyCode, @NotNull String searchPrefix) {
    if (keyCode == KeyEvent.VK_UP) {
      return findPreviousElement(searchPrefix);
    }
    else if (keyCode == KeyEvent.VK_DOWN) {
      return findNextElement(searchPrefix);
    }
    else if (keyCode == KeyEvent.VK_HOME) {
      return findFirstElement(searchPrefix);
    }
    else {
      assert keyCode == KeyEvent.VK_END;
      return findLastElement(searchPrefix);
    }
  }

  protected class SearchPopup extends JPanel implements Disposable {
    protected final SearchField mySearchField;
    private String myLastPattern = "";

    protected SearchPopup(String initialString) {
      mySearchField = new SearchField();
      mySearchField.setBorder(null);
      mySearchField.setBackground(BACKGROUND_COLOR);
      mySearchField.setForeground(FOREGROUND_COLOR);

      mySearchField.setDocument(new PlainDocument() {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
          String oldText;
          try {
            oldText = getText(0, getLength());
          }
          catch (BadLocationException e1) {
            oldText = "";
          }

          String newText = oldText.substring(0, offs) + str + oldText.substring(offs);
          super.insertString(offs, str, a);
          handleInsert(newText);
        }
      });

      setBorder(BORDER);
      setBackground(BACKGROUND_COLOR);
      setLayout(new BorderLayout());
      add(mySearchField, BorderLayout.CENTER);
      mySearchField.setText(initialString);

      updateLastPattern();
    }

    private void updateLastPattern() {
      String pattern = StringUtil.notNullize(mySearchField.getText());
      if (!pattern.equals(myLastPattern)) {
        myLastPattern = pattern;
        onSearchFieldUpdated(pattern);
      }
    }

    protected void handleInsert(String newText) {
    }

    @Override
    public void processKeyEvent(KeyEvent e) {
      mySearchField.processKeyEvent(e);
      if (e.isConsumed()) {
        updateLastPattern();
        String s = mySearchField.getText();
        int keyCode = e.getKeyCode();
        Object element;
        if (isUpDownHomeEnd(keyCode)) {
          element = findTargetElement(keyCode, s);
          if (myClearSearchOnNavigateNoMatch && element == null) {
            manageSearchPopup(null);
            element = findTargetElement(keyCode, "");
          }
          updateSelection(element);
          return;
        }
        UIEventLogger.IncrementalSearchKeyTyped.log(myComponent.getClass());
        if (mySearchPopup != null) {
          mySearchPopup.setSize(mySearchPopup.getPreferredSize());
          mySearchPopup.validate();
        }

        if (myProcessKeyEventAlarm == null || myProcessKeyEventAlarm.isDisposed()) return;

        myProcessKeyEventAlarm.cancelAllRequests();
        myProcessKeyEventAlarm.addRequest(this::updateSelection, 300L);
      }
    }

    void refreshSelection() {
      findAndSelectElement(mySearchField.getText());
    }

    private void updateSelection() {
      updateSelection(findElement(mySearchField.getText()));
    }

    private void updateSelection(Object element) {
      if (element != null) {
        selectElement(element, mySearchField.getText());
        mySearchField.setForeground(FOREGROUND_COLOR);
      }
      else {
        mySearchField.setForeground(ERROR_FOREGROUND_COLOR);
      }

      fireStateChanged();
    }

    @Override
    public void dispose() {
    }
  }

  protected void onSearchFieldUpdated(String pattern) {
    if (Registry.is("ide.speed.search.close.when.empty") && StringUtil.isEmpty(pattern)) hidePopup();
  }

  protected class SearchField extends ExtendableTextField {
    SearchField() {
      setFocusable(false);
      ExtendableTextField.Extension leftExtension = new Extension() {
        @Override
        public Icon getIcon(boolean hovered) {
          return AllIcons.Actions.Search;
        }

        @Override
        public boolean isIconBeforeText() {
          return true;
        }

        @Override
        public int getIconGap() {
          return JBUIScale.scale(10);
        }
      };

      addExtension(leftExtension);
    }

    @Override
    public void setForeground(Color color) {
      super.setForeground(color);
    }

    @Override
    public Dimension getPreferredSize() {
      Dimension dim = super.getPreferredSize();
      Insets m = getMargin();
      dim.width = getFontMetrics(getFont()).stringWidth(getText()) + 10 + m.left + m.right;
      return dim;
    }

    /**
     * I made this method public in order to be able to call it from the outside.
     * This is needed for delegating calls.
     */
    @Override
    public void processKeyEvent(KeyEvent e) {
      int i = e.getKeyCode();
      if (i == KeyEvent.VK_BACK_SPACE && getDocument().getLength() == 0) {
        e.consume();
        return;
      }
      if (
        i == KeyEvent.VK_ENTER ||
        i == KeyEvent.VK_PAGE_UP ||
        i == KeyEvent.VK_PAGE_DOWN ||
        i == KeyEvent.VK_LEFT ||
        i == KeyEvent.VK_RIGHT
        ) {
        if (!isStickySearch()) {
          manageSearchPopup(null);
        }
        return;
      }
      if (i == KeyEvent.VK_ESCAPE) {
        hidePopup();
        e.consume();
        return;
      }

      if (isUpDownHomeEnd(i)) {
        e.consume();
        return;
      }

      super.processKeyEvent(e);
      if (i == KeyEvent.VK_BACK_SPACE) {
        e.consume();
      }
    }

  }

  private static boolean isUpDownHomeEnd(int keyCode) {
    return keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_END || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN;
  }

  private static boolean isPgUpPgDown(int keyCode) {
    return keyCode == KeyEvent.VK_PAGE_UP || keyCode == KeyEvent.VK_PAGE_DOWN;
  }

  private static boolean isNavigationKey(int keyCode) {
    return isPgUpPgDown(keyCode) || isUpDownHomeEnd(keyCode);
  }

  private void manageSearchPopup(@Nullable SearchPopup searchPopup) {
    Project project = null;
    if (ApplicationManager.getApplication() != null && !ApplicationManager.getApplication().isDisposed()) {
      project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myComponent));
    }
    if (project != null && project.isDefault()) {
      project = null;
    }
    if (mySearchPopup != null) {
      UIEventLogger.IncrementalSearchCancelled.log(project, myComponent.getClass());
      if (myPopupLayeredPane != null) {
        myPopupLayeredPane.remove(mySearchPopup);
        myPopupLayeredPane.validate();
        myPopupLayeredPane.repaint();
        myPopupLayeredPane = null;
      }

      if (myListenerDisposable != null) {
        Disposer.dispose(myListenerDisposable);
        myListenerDisposable = null;
      }
      if (isStickySearch()) {
        UIUtil.putClientProperty(myComponent, SEARCH_TEXT_KEY, StringUtil.nullize(getEnteredPrefix()));
      }
      Disposer.dispose(mySearchPopup);
      myComparator = new SpeedSearchComparator(false);
    }
    else if (searchPopup != null) {
      FeatureUsageTracker.getInstance().triggerFeatureUsed("ui.tree.speedsearch");
      UIEventLogger.IncrementalSearchActivated.log(project, myComponent.getClass());
    }

    mySearchPopup = myComponent.isShowing() ? searchPopup : null;

    fireStateChanged();

    //select here!

    if (mySearchPopup == null || !myComponent.isDisplayable()) return;

    if (project != null) {
      myListenerDisposable = Disposer.newDisposable();
      project.getMessageBus().connect(myListenerDisposable).subscribe(ToolWindowManagerListener.TOPIC, myWindowManagerListener);
    }

    myProcessKeyEventAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, mySearchPopup);

    JRootPane rootPane = myComponent.getRootPane();
    myPopupLayeredPane = rootPane == null ? null : rootPane.getLayeredPane();
    if (myPopupLayeredPane == null) {
      LOG.error(this + " in " + myComponent);
      return;
    }
    myPopupLayeredPane.add(mySearchPopup, JLayeredPane.POPUP_LAYER);
    moveSearchPopup();
  }

  private void moveSearchPopup() {
    if (myComponent == null || mySearchPopup == null || myPopupLayeredPane == null) return;
    Point lPaneP = myPopupLayeredPane.getLocationOnScreen();
    Point componentP = getComponentLocationOnScreen();
    Rectangle r = getComponentVisibleRect();
    Dimension prefSize = mySearchPopup.getPreferredSize();
    Window window = (Window)SwingUtilities.getAncestorOfClass(Window.class, myComponent);
    Point windowP;
    if (window instanceof JDialog) {
      windowP = ((JDialog)window).getContentPane().getLocationOnScreen();
    }
    else if (window instanceof JFrame) {
      windowP = ((JFrame)window).getContentPane().getLocationOnScreen();
    }
    else {
      windowP = window.getLocationOnScreen();
    }
    int y = r.y + componentP.y - lPaneP.y - prefSize.height;
    y = Math.max(y, windowP.y - lPaneP.y);
    mySearchPopup.setLocation(componentP.x - lPaneP.x + r.x, y);
    mySearchPopup.setSize(prefSize);
    mySearchPopup.setVisible(true);
    mySearchPopup.validate();
  }

  protected Rectangle getComponentVisibleRect() {
    return myComponent.getVisibleRect();
  }

  protected Point getComponentLocationOnScreen() {
    return myComponent.getLocationOnScreen();
  }

  // TODO remove after the transition period
  private final boolean myElementAtImplemented;
  {
    boolean elementAtImplemented;
    try {
      elementAtImplemented = getMethodDeclaringClass(getClass(), "getElementAt", Integer.TYPE) != SpeedSearchBase.class;
    }
    catch (Exception ex) {
      elementAtImplemented = false;
    }
    myElementAtImplemented = elementAtImplemented;
    boolean elementIteratorImplemented = false;
    boolean elementCountImplemented = false;
    try {
      elementCountImplemented = getMethodDeclaringClass(getClass(), "getElementCount") != SpeedSearchBase.class;
      elementIteratorImplemented = getMethodDeclaringClass(getClass(), "getElementIterator", Integer.TYPE) != SpeedSearchBase.class;
    }
    catch (Exception ignore) { }
    if (!elementIteratorImplemented && !(elementAtImplemented && elementCountImplemented)) {
      LOG.warn("Please implement getElementAt(int)" +
               (elementCountImplemented? "" : " and getElementCount()" ) + " in " + getClass().getName());
    }
  }

  private static final class MyListIterator implements ListIterator<Object> {
    private final SpeedSearchBase<?> mySpeedSearch;
    private int myCurrentIndex;
    private final int myElementCount;

    private Object[] myElements;

    MyListIterator(@NotNull SpeedSearchBase<?> speedSearch, int startIndex) {
      mySpeedSearch = speedSearch;
      myCurrentIndex = startIndex;

      if (!mySpeedSearch.myElementAtImplemented) {
        myElements = speedSearch.getAllElements();
        myElementCount = myElements.length;
      }
      else {
        myElementCount = speedSearch.getElementCount();
      }

      if (startIndex < 0 || startIndex > myElementCount) {
        throw new IndexOutOfBoundsException("Index: " + startIndex + " in: " + speedSearch.getClass());
      }
    }

    @Override
    public boolean hasPrevious() {
      return myCurrentIndex != 0;
    }

    @Override
    public Object previous() {
      int i = myCurrentIndex - 1;
      if (i < 0) throw new NoSuchElementException();
      Object previous = getElementAt(i);
      myCurrentIndex = i;
      return previous;
    }

    private Object getElementAt(int i) {
      if (mySpeedSearch.myElementAtImplemented) {
        return mySpeedSearch.getElementAt(i);
      }
      int index = mySpeedSearch.convertIndexToModel(i);
      return myElements[index];
    }

    @Override
    public int nextIndex() {
      return myCurrentIndex;
    }

    @Override
    public int previousIndex() {
      return myCurrentIndex - 1;
    }

    @Override
    public boolean hasNext() {
      return myCurrentIndex != myElementCount;
    }

    @Override
    public Object next() {
      if (myCurrentIndex + 1 > myElementCount) throw new NoSuchElementException();
      return getElementAt(myCurrentIndex++);
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("Not implemented in: " + getClass().getCanonicalName());
    }

    @Override
    public void set(Object o) {
      throw new UnsupportedOperationException("Not implemented in: " + getClass().getCanonicalName());
    }

    @Override
    public void add(Object o) {
      throw new UnsupportedOperationException("Not implemented in: " + getClass().getCanonicalName());
    }
  }
}


text:
require File.join(File.dirname(__FILE__), "..", "..", "test_helper")

require 'mocha/parameter_matchers/instance_of'
require 'mocha/inspect'

class InstanceOfTest < Test::Unit::TestCase

  include Mocha::ParameterMatchers

  def test_should_match_object_that_is_an_instance_of_specified_class
    matcher = instance_of(String)
    assert matcher == 'string'
  end

  def test_should_not_match_object_that_is_not_an_instance_of_specified_class
    matcher = instance_of(String)
    assert matcher != 99
  end

  def test_should_describe_matcher
    matcher = instance_of(String)
    assert_equal "instance_of(String)", matcher.mocha_inspect
  end

end


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

#nullable disable

namespace StyleCop.Analyzers.MaintainabilityRules
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Immutable;
    using System.Diagnostics.CodeAnalysis;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;
    using Microsoft.CodeAnalysis.Diagnostics;
    using StyleCop.Analyzers.Helpers;

    /// <summary>
    /// A Code Analysis SuppressMessage attribute does not include a justification.
    /// </summary>
    /// <remarks>
    /// <para>A violation of this rule occurs when the code contains a Code Analysis
    /// <see cref="SuppressMessageAttribute"/> attribute, but a justification for the suppression has not been provided
    /// within the attribute. Whenever a Code Analysis rule is suppressed, a justification should be provided. This can
    /// increase the long-term maintainability of the code.</para>
    ///
    /// <code language="csharp">
    /// [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", Justification = "Used during unit testing")]
    /// public bool Enable()
    /// {
    /// }
    /// </code>
    /// </remarks>
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal class SA1404CodeAnalysisSuppressionMustHaveJustification : DiagnosticAnalyzer
    {
        /// <summary>
        /// The placeholder to insert as part of the code fix.
        /// </summary>
        public const string JustificationPlaceholder = "<Pending>";

        /// <summary>
        /// The ID for diagnostics produced by the <see cref="SA1404CodeAnalysisSuppressionMustHaveJustification"/>
        /// analyzer.
        /// </summary>
        public const string DiagnosticId = "SA1404";
        private const string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1404.md";
        private static readonly LocalizableString Title = new LocalizableResourceString(nameof(MaintainabilityResources.SA1404Title), MaintainabilityResources.ResourceManager, typeof(MaintainabilityResources));
        private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(MaintainabilityResources.SA1404MessageFormat), MaintainabilityResources.ResourceManager, typeof(MaintainabilityResources));
        private static readonly LocalizableString Description = new LocalizableResourceString(nameof(MaintainabilityResources.SA1404Description), MaintainabilityResources.ResourceManager, typeof(MaintainabilityResources));

        private static readonly DiagnosticDescriptor Descriptor =
            new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.MaintainabilityRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);

        private static readonly Action<CompilationStartAnalysisContext> CompilationStartAction = HandleCompilationStart;

        /// <inheritdoc/>
        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
            ImmutableArray.Create(Descriptor);

        /// <inheritdoc/>
        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            context.RegisterCompilationStartAction(CompilationStartAction);
        }

        private static void HandleCompilationStart(CompilationStartAnalysisContext context)
        {
            AnalyzerInstance instance = new AnalyzerInstance(context.Compilation.GetOrCreateUsingAliasCache());
            context.RegisterSyntaxNodeAction(instance.HandleAttributeNode, SyntaxKind.Attribute);
        }

        /// <summary>
        /// This class holds analyzer state information for analysis within a particular <see cref="Compilation"/>.
        /// </summary>
        private sealed class AnalyzerInstance
        {
            private readonly ConcurrentDictionary<SyntaxTree, bool> usingAliasCache;

            /// <summary>
            /// A lazily-initialized reference to <see cref="SuppressMessageAttribute"/> within the context of a
            /// particular <see cref="Compilation"/>.
            /// </summary>
            private INamedTypeSymbol suppressMessageAttribute;

            public AnalyzerInstance(ConcurrentDictionary<SyntaxTree, bool> usingAliasCache)
            {
                this.usingAliasCache = usingAliasCache;
            }

            public void HandleAttributeNode(SyntaxNodeAnalysisContext context)
            {
                var attribute = (AttributeSyntax)context.Node;

                // Return fast if the name doesn't match and the file doesn't contain any using alias directives
                if (!attribute.SyntaxTree.ContainsUsingAlias(this.usingAliasCache))
                {
                    if (!(attribute.Name is SimpleNameSyntax simpleNameSyntax))
                    {
                        QualifiedNameSyntax qualifiedNameSyntax = attribute.Name as QualifiedNameSyntax;
                        simpleNameSyntax = qualifiedNameSyntax.Right;
                    }

                    if (simpleNameSyntax.Identifier.ValueText != nameof(SuppressMessageAttribute)
                        && simpleNameSyntax.Identifier.ValueText != "SuppressMessage")
                    {
                        return;
                    }
                }

                SymbolInfo symbolInfo = context.SemanticModel.GetSymbolInfo(attribute);
                ISymbol symbol = symbolInfo.Symbol;
                if (symbol != null)
                {
                    if (this.suppressMessageAttribute == null)
                    {
                        this.suppressMessageAttribute = context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(SuppressMessageAttribute).FullName);
                    }

                    if (Equals(symbol.ContainingType, this.suppressMessageAttribute))
                    {
                        foreach (var attributeArgument in attribute.ArgumentList.Arguments)
                        {
                            if (attributeArgument.NameEquals?.Name?.Identifier.ValueText == nameof(SuppressMessageAttribute.Justification))
                            {
                                // Check if the justification is not empty
                                var value = context.SemanticModel.GetConstantValue(attributeArgument.Expression);

                                // If value does not have a value the expression is not constant -> Compilation error
                                if (!value.HasValue || (!string.IsNullOrWhiteSpace(value.Value as string) && (value.Value as string) != JustificationPlaceholder))
                                {
                                    return;
                                }

                                // Empty, Whitespace, placeholder, or null justification provided
                                context.ReportDiagnostic(Diagnostic.Create(Descriptor, attributeArgument.GetLocation()));
                                return;
                            }
                        }

                        // No justification set
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, attribute.GetLocation()));
                    }
                }
            }
        }
    }
}


text:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
import store from './store'
import * as filters from './filters' // 全局filter
import './icons' // icon
import './permission' // 权限
import md5 from 'js-md5';

Vue.prototype.md5 = md5;

Vue.use(ElementUI)

// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})