text:
The `gemfire` object is returned by `require("gemfire")` and is the global entry point into node-gemfire.

### gemfire.connected()

Returns true if the GemFire client is connected to a GemFire distributed system, and false if not.

Example:

```javascript
var gemfire = require('gemfire');
gemfire.connected(); // returns false

gemfire.configure("config/gemfire.xml");
gemfire.connected(); // returns true

// ... network troubles cause a disconnection ...

gemfire.connected(); // returns false

// ... client automatically reconnects to the GemFire system ...

gemfire.connected(); // returns true
```

### gemfire.configure(xmlFilePath)

Tells gemfire which cache configuration file to use. `xmlFilePath` can be either absolute or relative to the current working directory in the application's environment. Once set, the configuration cannot be changed.

For more information on cache configuration files, see [the documentation](http://gemfire.docs.pivotal.io/latest/userguide/gemfire_nativeclient/cache-init-file/chapter-overview.html#chapter-overview).

Example:

```javascript
var gemfire = require('gemfire');

gemfire.configure("config/myGemfireConfiguration.xml");
gemfire.configure("config/anotherGemfireConfiguration.xml"); // throws an error
```

### gemfire.gemfireVersion

Returns the version of the GemFire C++ Native Client that has been compiled into node-gemfire.

Example:

```javascript
var gemfire = require('gemfire');
gemfire.gemfireVersion // returns "8.0.0.1"
```

### gemfire.getCache()

Returns the cache singleton object. `gemfire.configure()` must have been called prior to calling `gemfire.getCache()`.

> **Warning:** Due to a limitation of the GemFire C++ Native Client library that backs the Cache, there can only be one Cache instance in the lifetime of a Node process. If you want to construct a new cache instance, you must restart your application.

Example:

```javascript
var gemfire = require('gemfire');

gemfire.getCache(); // throws an error, because gemfire has not been configured yet

gemfire.configure("config/gemfire.xml");

gemfire.getCache(); // returns the cache singleton object
gemfire.getCache(); // returns the same cache singleton object on subsequent calls
```

### gemfire.version

Returns the version of node-gemfire.

Example:

```javascript
var gemfire = require('gemfire');
gemfire.gemfireVersion // returns "0.0.15"
```

## Cache

The GemFire cache is an in-memory data store singleton object composed of many Regions. The cache instance is configured with an XML configuration file via `gemfire.configure()` and returned by calling `gemfire.getCache()`:

### cache.createRegion(regionName, options)

Adds a region to the GemFire cache. Once the region is created, it will remain in the client for the lifetime of the process. The `regionName` should be a string and the `options` object has a required type property.

 * `options.type`: the type of GemFire region to create. The value should be the string name of one of the GemFire region shortcuts, such as "LOCAL", "PROXY", or "CACHING_PROXY". See the GemFire documentation for [Region Shortcuts](http://gemfire.docs.pivotal.io/latest/userguide/gemfire_nativeclient/client-cache/region-shortcuts.html) and the [gemfire::RegionShortcut C++ enumeration](http://gemfire.docs.pivotal.io/latest/cpp_api/cppdocs/namespacegemfire.html#596bc5edab9d1e7c232e53286b338183) for more details.
 * `options.poolName`: the name of the GemFire pool the region is in. If not specified, a default pool will be used.

> **Warning:** If options.poolName is not specified, the default pool will be used. The default pool usually expects a GemFire server to be running on localhost on port 40404. If you are trying to connect to a GemFire cluster with a different configuration then you must specify options.poolName.

Example:

```javascript
cache.getRegion("myRegion") // returns undefined

var myRegion = cache.createRegion("myRegion", {type: "PROXY", poolName: "myPool"});

cache.getRegion("myRegion") // returns the same region as myRegion
```

### cache.executeFunction(functionName, options)

Executes a Java function on a server in the cluster containing the cache. `functionName` is the full Java class name of the function that will be called. Options may be either an array of arguments, or an options object.

 * `options.arguments`: the arguments to be passed to the Java function
 * `options.poolName`: the name of the GemFire pool where the function should be run
 * `options.synchronous`: if true, the function will not run asynchronously.

> **Note**: Unlike region.executeFunction(), `options.filter` is not allowed.

> **Warning:** Due to a workaround for a bug in Gemfire 8.0.0.0, when `options.poolName` is not specified, functions executed by cache.executeFunction() will be executed on exactly one server in the first pool defined in the XML configuration file.

cache.executeFunction returns an EventEmitter which emits the following events:

 * `data`: Emitted once for each result sent by the Java function.
 * `error`: Emitted if the function throws or returns an Exception.
 * `end`: Called after the Java function has finally returned.

> **Warning:** As of GemFire 8.0.0.0, there are some situations where the Java function can throw an uncaught Exception, but the node `error` callback never gets called. This is due to a known bug in how the GemFire 8.0.0.0 Native Client handles exceptions. This bug is only present for cache.executeFunction. region.executeFunction works as expected.

Example:

```javascript
cache.executeFunction("com.example.FunctionName",
    {
      arguments: [1, 2, 3],
      poolName: "myPool"
    }
  )
  .on("error", function(error) { throw error; })
  .on("data", function(result) {
    // ...
  })
  .on("end", function() {
    // ...
  });
```

For more information, please see the [GemFire documentation for Function Execution](http://gemfire.docs.pivotal.io/latest/userguide/developing/function_exec/chapter_overview.html).

### cache.executeFunction(functionName, arguments)

Shorthand for `executeFunction` with an array of arguments. Equivalent to:

```javascript
cache.executeFunction(functionName, { arguments: arguments })
```

### cache.executeQuery(query, [parameters], [options], callback)

Executes an OQL query on the cluster. The callback will be called with an `error` argument and a `response` argument.

 * `query`: a string representing a GemFire OQL query
 * `parameters`: an array of parameters for the query string
 * `options.poolName`: the name of the GemFire pool where the query should be executed

The `response` argument is an object responding to `toArray` and `each`.

 * `response.toArray()`: Return the entire result set as an Array.
 * `response.each(callback)`: Call the callback with a `result` argument, once for each result.

> **Warning:** Due to a workaround for a bug in Gemfire 8.0.0.0, when `options.poolName` is not specified, functions executed by cache.executeQuery() will be executed on exactly one server in the first pool defined in the XML configuration file.

Example:

```javascript
cache.executeQuery("SELECT DISTINCT * FROM /exampleRegion WHERE foo = $1 OR foo = $2", ['bar', 'baz'], {poolName: "myPool"}, function(error, response) {
  if(error) { throw error; }

  var results = response.toArray();
  // allResults could now be this:
  //   [ { foo: 'bar' }, { foo: 'baz' } ]

  // alternately, you could use the `each` iterator:
  response.each(function(result) {
  	// this callback will be called with { foo: 'bar' } then { foo: 'baz' }
  });
}
```

For more information on OQL, see [the documentation](http://gemfire.docs.pivotal.io/latest/userguide/developing/querying_basics/chapter_overview.html).

### cache.getRegion(regionName)

Retrieves a Region from the Cache. An error will be thrown if the region is not present.

Example:

```javascript
var region = cache.getRegion('exampleRegion');
```

### cache.rootRegions()

Retrieves an array of all root Regions from the Cache.

Example:

```javascript
var regions = cache.rootRegions();
// if there are three Regions defined in your cache, regions could now be:
// [firstRegionName, secondRegionName, thirdRegionName]
```

## Region

A GemFire region is a collection of key-value pair entries. The most common way to get a region is to call `cache.getRegion('regionName')` on a Cache.

### region.attributes

Returns an object describing the attributes of the GemFire region. This can be useful for debugging your region configuration.

Several of these values are described in the [GemFire documentation for region attributes](http://gemfire.docs.pivotal.io/latest/userguide/gemfire_nativeclient/client-cache/region-attributes.html).

Example output of `region.attributes`:

```javascript
{
  cachingEnabled: true,
  clientNotificationEnabled: true,
  concurrencyChecksEnabled: true,
  concurrencyLevel: 16,
  diskPolicy: 'none',
  entryIdleTimeout: 0,
  entryTimeToLive: 0,
  initialCapacity: 10000,
  loadFactor: 0.75,
  lruEntriesLimit: 0,
  lruEvicationAction: 'LOCAL_DESTROY',
  poolName: 'default_gemfireClientPool',
  regionIdleTimeout: 0,
  regionTimeToLive: 0,
  scope: 'DISTRIBUTED_NO_ACK'
}
```

### region.clear([callback])

Removes all entries from the region. The callback will be called with an `error` argument. If the callback is not supplied, and an error occurs, the region will emit an `error` event.

Example:

```javascript
region.clear(function(error){
  if(error) { throw error; }
  // region is empty
});
```

### region.destroyRegion([callback])

Destroys the region, deleting all entries. The callback will be called with an `error` argument. If the callback is not supplied, and an error occurs, the region will emit an `error` event.

> **Warning:** Destroying a `PROXY` or `CACHING_PROXY` region via `destroyRegion` also destroys the corresponding region on the GemFire cluster. If you don't want this behavior, call `region.localDestroyRegion()` instead.

Example:

```javascript
region.destroyRegion(function(error){
  if(error) { throw error; }
  // region is destroyed
  region.put("foo", "bar", callbackFn); // throws gemfire::RegionDestroyedException
});
```

See also `region.localDestroyRegion`.

### region.executeFunction(functionName, options)

Executes a Java function on any servers in the cluster containing the region. `functionName` is the full Java class name of the function that will be called. Options may be either an array of arguments, or an options object.

 * `options.arguments`: the arguments to be passed to the Java function
 * `options.filter`: an array of keys to be sent to the Java function as the filter

region.executeFunction returns an EventEmitter which emits the following events:

 * `data`: Emitted once for each result sent by the Java function.
 * `error`: Emitted if the function throws or returns an Exception.
 * `end`: Called after the Java function has finally returned.

Example:

```javascript
region.executeFunction("com.example.FunctionName",
    { arguments: [1, 2, 3], filters: ["key1", "key2"] }
  )
  .on("error", function(error) { throw error; })
  .on("data", function(result) {
    // ...
  })
  .on("end", function() {
    // ...
  });
```

For more information, please see the [GemFire documentation for Function Execution](http://gemfire.docs.pivotal.io/latest/userguide/developing/function_exec/chapter_overview.html).

### region.executeFunction(functionName, arguments)

Shorthand for `executeFunction` with an array of arguments. Equivalent to:

```javascript
region.executeFunction(functionName, { arguments: arguments })
```

### region.existsValue(predicate, callback)

Indicates whether or not a value matching the OQL predicate `predicate` is present in the region. The callback will be called with an `error` and the boolean `response`.

In the predicate, you can use `this` to refer to the entire value. If you use any other expression, it will be treated as a field name on object values.

Example:

```javascript
region.existsValue("this = 'value1'", function(error, response) {
  if(error) { throw error; }
  // response will be set to true if any value is the string 'value1'
});

region.existsValue("foo > 2", function(error, response) {
  if(error) { throw error; }
  // response will be set to true if any value is an object such
  // as { foo: 3 } where the value of foo is greater than 2.
});
```

See also `region.query` and `region.selectValue`.

### region.get(key, callback)

Retrieves the value of an entry in the Region. The callback will be called with an `error` and the `value`. If the key is not present in the Region, an error will be passed to the callback.

Example:

```javascript
region.get("key", function(error, value){
  if(error) { throw error; }
  // an entry was found and its value is now accessible
});
```

### region.getSync(key)

Retrieves the value of an entry in the Region synchronously.

Example:

```javascript
  var value = region.getSync("key");
});
```

### region.getAll(keys, callback)

Retrieves the values of multiple keys in the Region. The keys should be passed in as an `Array`. The callback will be called with an `error` and a `values` object. If one or more keys are not present in the region, their values will be returned as null.

Example:

```javascript
region.getAll(["key1", "key2", "unknownKey"], function(error, values){
  if(error) { throw error; }
  // if key1 and key2 are present in the region, but unknownKey is not,
  // then values may look like this:
  // { key1: 'value1', key2: { foo: 'bar' }, unknownKey: null }
});
```

### region.keys(callback)

Retrieves all keys in the local cache of the Region. The callback will be called with an `error` argument, and an Array of keys.

Example:

```javascript
region.keys(function(error, keys) {
  if(error) { throw error; }
  // keys is now an array of all keys in the region, for example:
  //   [ 'key1', 'key2', 'key3' ]
});
```

### region.keys(callback)

Retrieves all keys on the Gemfire server for the Region. The callback will be called with an `error` argument, and an Array of keys.

Example:

```javascript
region.serverKeys(function(error, keys) {
  if(error) { throw error; }
  // keys is now an array of all keys in the region, for example:
  //   [ 'key1', 'key2', 'key3' ]
});
```

### values(callback)

Retrieves all values on the local cache of the Region. The callback will be called with an `error` argument, and an Array of values.

Example:

```javascript
region.values(function(error, keys) {
  if(error) { throw error; }
  // values is now an array of all values in the region, for example:
  //   [ 'value1', 'value2', 'value3' ]
});
```

### entries(callback)

Retrieves all key-value pairs on the local cache of the Region. The callback will be called with an `error` argument, and an Array of values.

Example:

```javascript
region.entries(function(error, keys) {
  if(error) { throw error; }
  // values is now an array of all values in the region, for example:
  //   [ { 'key': 'key1', 'value' : 'value1', { 'key' : 'key2', 'value' : 'value2' } ]
});
```

### region.localDestroyRegion([callback])

Destroys the local region, deleting all entries. The callback will be called with an `error` argument. If the callback is not supplied, and an error occurs, the region will emit an `error` event.

> **Note:** Destroying a `PROXY` or `CACHING_PROXY` region via `localDestoryRegion` does not destroy the corresponding region on the GemFire cluster. If you want this behavior, call `region.destroyRegion()` instead.

Example:

```javascript
region.localDestroyRegion(function(error){
  if(error) { throw error; }
  // local region is destroyed
  region.put("foo", "bar", callbackFn); // throws gemfire::RegionDestroyedException
});
```

See also `region.destroyRegion`.

### region.name

Returns the name of the region.

### region.put(key, value, callback)

Stores an entry in the region. The callback will be called with an `error` argument.

GemFire supports most JavaScript types for the value. Some types, such as `Function` and `null` cannot be stored.

GemFire supports several JavaScript types for the key, but the safest choice is to always use a `String`.

Example:

```javascript
region.put('key', { foo: 'bar' }, function(error) {
  if(error) { throw error; }
  // the entry at key "key" now has value { foo: 'bar' }
});
```

### region.putSync(key, value)

Stores an entry in the region. Works the same way as `put` but does not take a callback or emit events.

Example:

```javascript
region.putSync('key', { foo: 'bar' });
// the entry at key "key" now has value { foo: 'bar' }
});
```

### region.putAll(entries, [callback])

Stores multiple entries in the region. The callback will be called with an `error` argument. If the callback is not supplied, and an error occurs, the Region will emit an `error` event.

**NOTE**: Keys on a JavaScript object are always strings. Thus, all entries will have string keys.

Example:

```javascript
region.putAll(
  {
    key1: 'value1',
    key2: { foo: 'bar' }
    3: "three"
  },
  function(error) {
    if(error) { throw error; }
    // the entry at key "key1" now has value "value1"
    // the entry at key "key2" now has value { foo: 'bar' }
    // the entry at key 3 (Number) is unaffected
    // the entry at key "3" (String) now has value "three"
  }
);
```

### region.putAllSync(entries)

Stores multiple entries in the region. Executes synchronously.

Example:

```javascript
region.putAllSync(
  {
    key1: 'value1',
    key2: { foo: 'bar' }
    3: "three"
  }
);
```

### region.query(predicate, callback)

Retrieves all values from the Region matching the OQL `predicate`. The callback will be called with an `error` argument, and a `response` object. For more information on `response` objects, please see `cache.executeQuery`.

Example:

```javascript
region.query("this like '% Smith'", function(error, response) {
  if(error) { throw error; }

  var results = response.toArray();
  // results will now be an array of all values in the region ending in " Smith"

  response.each(function(result) {
    // this callback will be passed each value in the region ending in " Smith", one at a time
  });
});
```

See also `region.selectValue` and `region.existsValue`.

### region.registerAllKeys()

Tells the GemFire server to trigger events for entry operations that were triggered by other clients in the system. By default, region entry operations (`region.put`, `region.remove`, etc.) that happen within a single Node process trigger events *only* within that same process. After calling `region.registerAllKeys`, all entry operations on the region will trigger events. In other words, the GemFire server will push notifications back to the Node process.

Example:

```javascript
region.on("create", function(event) {
  // handle event
});

// another client creates an entry in the region, and the callback is not triggered

region.registerAllKeys();

// another client creates an entry in the region, and the callback is triggered
```

See also Events and `region.unregisterAllKeys`.

### region.remove(key, [callback])

Removes the entry specified by the indicated key from the Region, or, if no such entry is present, passes an `error` to the callback. If the argument is not supplied, and an error occurs, the Region will emit an `error` event.

Example:

```javascript
region.remove('key1', function(error) {
  if(error) { throw error; }
  // the entry with key 'key1' has been removed from the region
});
```

### region.selectValue(predicate, callback)

Retrieves exactly one entry from the Region matching the OQL `predicate`. The callback will be called with an `error` argument, and a `result`.

If more than one result matches the predicate, an error will be passed to the callback. If you want to select multiple results for a predicate, see `region.query`.

Example:

```javascript
region.selectValue("this = 'value1'", function(error, result) {
  if(error) { throw error; }
  // if there is exactly one entry with value 'value1' in the region,
  // result will now be set to 'value1'
});
```

See also `region.query` and `region.existsValue`.

### region.unregisterAllKeys()

Tells the GemFire server *not* to trigger events for entry operations that were triggered by other clients in the system.

Example:

```javascript
region.registerAllKeys();

region.on("create", function(event) {
  // handle event
}

// another client creates an entry in the region, and the callback is triggered

region.unregisterAllKeys();

// another client creates an entry in the region, and the callback is not triggered
```

See also Events and `region.registerAllKeys`.

### Event: 'error'

* error: `Error` object.

Emitted when an error occurs and no callback was passed to the method that caused the error.

Example:

```javascript
region.on("error", function(error) {
  // handle errors
});

// emits an error because null is not a supported value for put()
region.put("foo", null);

// does not emit an error, because a callback was passed
region.put("foo", null, function(error) {});
```

### Event: 'create'

* event: GemFire event payload object.
  * event.key: The key that was inserted.
  * event.oldValue: Always `null` because there is no old value.
  * event.newValue: The value that was inserted.

Emitted when an entry is added to the region. Not emitted when an existing entry's value is updated.

Example:

```javascript
region.on("create", function(event) {
  // process event
});

// emits an event because "foo" is a new entry in the region
region.put("foo", "bar");

// does not emit an event because "foo" is already an entry in the region
region.put("foo", "baz");
```

See also `region.registerAllKeys`.

### Event: 'destroy'

* event: GemFire event payload object.
  * event.key: The key that was destroyed.
  * event.oldValue: The previous value before the destruction.
  * event.newValue: Always `null` because there is no new value.

Emitted when an existing entry is destroyed.

Example:

```javascript
region.on("destroy", function(event) {
  // process event
});

region.remove("foo");
```

See also `region.registerAllKeys`.

### Event: 'update'

* event: GemFire event payload object.
  * event.key: The key that was updated.
  * event.oldValue: The previous value before the update.
  * event.newValue: The new value after the update.

Emitted when an existing entry's value is updated. Not emitted when an entry is added to the region.

Example:

```javascript
region.on("update", function(event) {
  // process event
});

// does not emit an event because "foo" is a new entry in the region
region.put("foo", "bar");

// emits an event because "foo" is already an entry in the region
region.put("foo", "baz");
```

See also `region.registerAllKeys`.


text:
var collection_1 = require('angular2/src/facade/collection');
var lang_1 = require('angular2/src/facade/lang');
/**
 * A wrapper around zones that lets you schedule tasks after it has executed a task.
 *
 * The wrapper maintains an "inner" and an "mount" `Zone`. The application code will executes
 * in the "inner" zone unless `runOutsideAngular` is explicitely called.
 *
 * A typical application will create a singleton `NgZone`. The outer `Zone` is a fork of the root
 * `Zone`. The default `onTurnDone` runs the Angular change detection.
 *
 * @exportedAs angular2/core
 */
var NgZone = (function () {
    /**
     * Associates with this
     *
     * - a "root" zone, which the one that instantiated this.
     * - an "inner" zone, which is a child of the root zone.
     *
     * @param {bool} enableLongStackTrace whether to enable long stack trace. They should only be
     *               enabled in development mode as they significantly impact perf.
     */
    function NgZone(_a) {
        var enableLongStackTrace = _a.enableLongStackTrace;
        this._inVmTurnDone = false;
        this._onTurnStart = null;
        this._onTurnDone = null;
        this._onErrorHandler = null;
        this._pendingMicrotasks = 0;
        this._hasExecutedCodeInInnerZone = false;
        this._nestedRun = 0;
        if (lang_1.global.zone) {
            this._disabled = false;
            this._mountZone = lang_1.global.zone;
            this._innerZone = this._createInnerZone(this._mountZone, enableLongStackTrace);
        }
        else {
            this._disabled = true;
            this._mountZone = null;
        }
    }
    /**
     * Initializes the zone hooks.
     *
     * @param {() => void} onTurnStart called before code executes in the inner zone for each VM turn
     * @param {() => void} onTurnDone called at the end of a VM turn if code has executed in the inner
     * zone
     * @param {(error, stack) => void} onErrorHandler called when an exception is thrown by a macro or
     * micro task
     */
    NgZone.prototype.initCallbacks = function (_a) {
        var _b = _a === void 0 ? {} : _a, onTurnStart = _b.onTurnStart, onTurnDone = _b.onTurnDone, onErrorHandler = _b.onErrorHandler;
        this._onTurnStart = lang_1.normalizeBlank(onTurnStart);
        this._onTurnDone = lang_1.normalizeBlank(onTurnDone);
        this._onErrorHandler = lang_1.normalizeBlank(onErrorHandler);
    };
    /**
     * Runs `fn` in the inner zone and returns whatever it returns.
     *
     * In a typical app where the inner zone is the Angular zone, this allows one to make use of the
     * Angular's auto digest mechanism.
     *
     * ```
     * var zone: NgZone = [ref to the application zone];
     *
     * zone.run(() => {
     *   // the change detection will run after this function and the microtasks it enqueues have
     * executed.
     * });
     * ```
     */
    NgZone.prototype.run = function (fn) {
        if (this._disabled) {
            return fn();
        }
        else {
            return this._innerZone.run(fn);
        }
    };
    /**
     * Runs `fn` in the outer zone and returns whatever it returns.
     *
     * In a typical app where the inner zone is the Angular zone, this allows one to escape Angular's
     * auto-digest mechanism.
     *
     * ```
     * var zone: NgZone = [ref to the application zone];
     *
     * zone.runOusideAngular(() => {
     *   element.onClick(() => {
     *     // Clicking on the element would not trigger the change detection
     *   });
     * });
     * ```
     */
    NgZone.prototype.runOutsideAngular = function (fn) {
        if (this._disabled) {
            return fn();
        }
        else {
            return this._mountZone.run(fn);
        }
    };
    NgZone.prototype._createInnerZone = function (zone, enableLongStackTrace) {
        var ngZone = this;
        var errorHandling;
        if (enableLongStackTrace) {
            errorHandling = collection_1.StringMapWrapper.merge(Zone.longStackTraceZone, { onError: function (e) { ngZone._onError(this, e); } });
        }
        else {
            errorHandling = { onError: function (e) { ngZone._onError(this, e); } };
        }
        return zone.fork(errorHandling)
            .fork({
            '$run': function (parentRun) {
                return function () {
                    try {
                        ngZone._nestedRun++;
                        if (!ngZone._hasExecutedCodeInInnerZone) {
                            ngZone._hasExecutedCodeInInnerZone = true;
                            if (ngZone._onTurnStart) {
                                parentRun.call(ngZone._innerZone, ngZone._onTurnStart);
                            }
                        }
                        return parentRun.apply(this, arguments);
                    }
                    finally {
                        ngZone._nestedRun--;
                        // If there are no more pending microtasks, we are at the end of a VM turn (or in
                        // onTurnStart)
                        // _nestedRun will be 0 at the end of a macrotasks (it could be > 0 when there are
                        // nested calls
                        // to run()).
                        if (ngZone._pendingMicrotasks == 0 && ngZone._nestedRun == 0 &&
                            !this._inVmTurnDone) {
                            if (ngZone._onTurnDone && ngZone._hasExecutedCodeInInnerZone) {
                                try {
                                    this._inVmTurnDone = true;
                                    parentRun.call(ngZone._innerZone, ngZone._onTurnDone);
                                }
                                finally {
                                    this._inVmTurnDone = false;
                                    ngZone._hasExecutedCodeInInnerZone = false;
                                }
                            }
                        }
                    }
                };
            },
            '$scheduleMicrotask': function (parentScheduleMicrotask) {
                return function (fn) {
                    ngZone._pendingMicrotasks++;
                    var microtask = function () {
                        try {
                            fn();
                        }
                        finally {
                            ngZone._pendingMicrotasks--;
                        }
                    };
                    parentScheduleMicrotask.call(this, microtask);
                };
            },
            _innerZone: true
        });
    };
    NgZone.prototype._onError = function (zone, e) {
        if (lang_1.isPresent(this._onErrorHandler)) {
            var trace = [lang_1.normalizeBlank(e.stack)];
            while (zone && zone.constructedAtException) {
                trace.push(zone.constructedAtException.get());
                zone = zone.parent;
            }
            this._onErrorHandler(e, trace);
        }
        else {
            console.log('## _onError ##');
            console.log(e.stack);
            throw e;
        }
    };
    return NgZone;
})();
exports.NgZone = NgZone;
exports.__esModule = true;
//# sourceMappingURL=ng_zone.js.map

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace TimeDilation;

use Cron\CronExpression;
use Phutler\Tasks\Task;

TimeMachine::infectNamespace("Phutler");
TimeMachine::infectNamespace("React\\EventLoop\\Timer");
TimeMachine::infectNamespace("Cron");

class TaskTest extends \PHPUnit_Framework_TestCase
{

	function testCronMethods()
	{
		TimeMachine::setNow("2013-03-03 09:59:00",200);
		$loop=\React\EventLoop\Factory::create();
		$someTask=new SomeTask(new \stdClass(),$loop, new \Monolog\Logger("test"),$this->getMock('Phutler\\Persistence\\Persistor'));
		TimeMachine::fastForward(60);
		$loop->tick();

		$this->assertTrue($someTask->doAtSunday10aClockExecuted);
	}

}

class SomeTask extends Task
{
	public $doAtSunday10aClockExecuted=false;

	/**
	 * @cron 0 10 * * SUN *
	 */
	function doAtSunday10aClock()
	{
		$this->doAtSunday10aClockExecuted=true;
	}

}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}

module Eventful.ProjectionCache.Memory
  ( ProjectionMap
  , emptyProjectionMap
  , projectionMapTVar
  , tvarProjectionCache
  , embeddedStateProjectionCache
  , module Eventful.ProjectionCache.Types
  ) where

import Control.Concurrent.STM
import Control.Monad.State.Class hiding (state)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

import Eventful.ProjectionCache.Types

-- | A 'ProjectionMap' just stores the latest snapshot for each UUID.
type ProjectionMap key position serialized = Map key (position, serialized)

emptyProjectionMap :: ProjectionMap key position serialized
emptyProjectionMap = Map.empty

projectionMapTVar :: IO (TVar (ProjectionMap key position serialized))
projectionMapTVar = newTVarIO emptyProjectionMap

storeProjectionInMap
  :: (Ord key)
  => key
  -> position
  -> serialized
  -> ProjectionMap key position serialized
  -> ProjectionMap key position serialized
storeProjectionInMap uuid version state = Map.insert uuid (version, state)

-- | A 'ProjectionCache' that uses a 'TVar' and runs in 'STM'.
tvarProjectionCache
  :: (Ord key)
  => TVar (ProjectionMap key position serialized)
  -> ProjectionCache key position serialized STM
tvarProjectionCache tvar =
  let
    storeProjectionSnapshot uuid version projState = modifyTVar' tvar (storeProjectionInMap uuid version projState)
    loadProjectionSnapshot uuid = Map.lookup uuid <$> readTVar tvar
  in ProjectionCache{..}

-- | A 'ProjectionCache' for some 'MonadState' that contains a 'ProjectionMap'.
embeddedStateProjectionCache
  :: (MonadState s m, Ord key)
  => (s -> ProjectionMap key position serialized)
  -> (s -> ProjectionMap key position serialized -> s)
  -> ProjectionCache key position serialized m
embeddedStateProjectionCache getMap setMap =
  let
    storeProjectionSnapshot uuid version projState = modify' (storeProjectionSnapshot' uuid version projState)
    loadProjectionSnapshot uuid = Map.lookup uuid <$> gets getMap
  in ProjectionCache{..}
  where
    storeProjectionSnapshot' uuid version projState state =
      setMap state $ storeProjectionInMap uuid version projState $ getMap state


text:
namespace lemon { namespace io {
        enum class errc
        {
            operation_canceled,io_service_closed
        };

        class io_error_category : public std::error_category
        {
        private:

            const char *name() const throw()
            {
                return "lemon::os::os_error_category";
            }

            std::string message(int val) const
            {
                switch ((errc)val)
                {
                case errc::operation_canceled:
                    return "io operation canceled";
                case errc::io_service_closed:
                    return "io service closed";
                }

				return "unknown";
            }

            std::error_condition default_error_condition(int _Errval) const throw()
            {
                return std::error_condition(_Errval, *this);
            }

            bool equivalent(int _Errval, const std::error_condition& _Cond) const throw()
            {
                return _Errval == _Cond.value();
            }

            bool equivalent(const std::error_code& _Code, int _Errval) const throw()
            {
                return _Errval == _Code.value();
            }
        };

        inline std::error_code make_error_code(errc err) noexcept
        {
            static io_error_category io_error_category;

            return std::error_code(static_cast<int>(err), io_error_category);
        }
    }}

namespace std {
    template<> struct is_error_code_enum<::lemon::io::errc> : true_type {};
}
#endif //LEMON_IO_ERRORS_HPP


text:
/**
 * @see https://developer.github.com/v3/oauth/
 */
Accounts.ui.config({
  requestPermissions: {
    github: ['user', 'public_repo', 'write:repo_hook']
  }
});


text:
var alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
var base = alphabet.length

function encode(num){
  var encoded = ''
  while (num){
    var remainder = num % base
    num = Math.floor(num / base)
    encoded = alphabet[remainder].toString() + encoded
  }
  return encoded
}

function decode(str){
  var decoded = 0
  while (str){
    var index = alphabet.indexOf(str[0])
    var power = str.length - 1
    decoded += index * (Math.pow(base, power))
    str = str.substring(1)
  }
  return decoded
}

function validURL(s) {
   var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
   return regexp.test(s);
}

module.exports.encode = encode
module.exports.decode = decode
module.exports.validURL = validURL


text:
import { filter, isNumber, omit } from 'lodash'
import {
    radiansToDegrees,
    absoluteAngleDegrees,
    degreesToRadians,
    positionFromAngle,
} from '@nivo/core'
import { defaultProps } from './props'
import {
    AnnotationPositionGetter,
    AnnotationDimensionsGetter,
    BoundAnnotation,
    AnnotationMatcher,
    AnnotationInstructions,
} from './types'
import { isCircleAnnotation, isRectAnnotation } from './utils'

export const bindAnnotations = <
    Datum = {
        x: number
        y: number
    }
>({
    data,
    annotations,
    getPosition,
    getDimensions,
}: {
    data: Datum[]
    annotations: AnnotationMatcher<Datum>[]
    getPosition: AnnotationPositionGetter<Datum>
    getDimensions: AnnotationDimensionsGetter<Datum>
}): BoundAnnotation<Datum>[] =>
    annotations.reduce((acc: BoundAnnotation<Datum>[], annotation) => {
        const offset = annotation.offset || 0

        return [
            ...acc,
            ...filter<Datum>(data, annotation.match).map(datum => {
                const position = getPosition(datum)
                const dimensions = getDimensions(datum)

                if (isCircleAnnotation(annotation) || isRectAnnotation(annotation)) {
                    dimensions.size = dimensions.size + offset * 2
                    dimensions.width = dimensions.width + offset * 2
                    dimensions.height = dimensions.height + offset * 2
                }

                // acc.push({
                //     ...omit(annotation, ['match', 'offset']),
                //     ...position,
                //     ...dimensions,
                //     size: annotation.size || dimensions.size,
                //     datum,
                // } as any)
                // return [
                //     ...acc,
                //     {
                //         ...omit(annotation, ['match', 'offset']),
                //         ...position,
                //         ...dimensions,
                //         size: annotation.size || dimensions.size,
                //         datum,
                //     },
                // ]
                return {
                    ...omit(annotation, ['match', 'offset']),
                    ...position,
                    ...dimensions,
                    size: annotation.size || dimensions.size,
                    datum,
                } as Required<BoundAnnotation<Datum>>
            }),
        ]

        // return acc
    }, [])

export const getLinkAngle = (
    sourceX: number,
    sourceY: number,
    targetX: number,
    targetY: number
) => {
    const angle = Math.atan2(targetY - sourceY, targetX - sourceX)

    return absoluteAngleDegrees(radiansToDegrees(angle))
}

export const computeAnnotation = <Datum>(
    annotation: BoundAnnotation<Datum>
): AnnotationInstructions => {
    const {
        x,
        y,
        noteX,
        noteY,
        noteWidth = defaultProps.noteWidth,
        noteTextOffset = defaultProps.noteTextOffset,
    } = annotation

    let computedNoteX: number
    let computedNoteY: number

    if (isNumber(noteX)) {
        computedNoteX = x + noteX
    } else if (noteX.abs !== undefined) {
        computedNoteX = noteX.abs
    } else {
        throw new Error(`noteX should be either a number or an object containing an 'abs' property`)
    }

    if (isNumber(noteY)) {
        computedNoteY = y + noteY
    } else if (noteY.abs !== undefined) {
        computedNoteY = noteY.abs
    } else {
        throw new Error(`noteY should be either a number or an object containing an 'abs' property`)
    }

    let computedX = x
    let computedY = y

    const angle = getLinkAngle(x, y, computedNoteX, computedNoteY)

    if (isCircleAnnotation<Datum>(annotation)) {
        const position = positionFromAngle(degreesToRadians(angle), annotation.size / 2)
        computedX += position.x
        computedY += position.y
    }

    if (isRectAnnotation<Datum>(annotation)) {
        const eighth = Math.round((angle + 90) / 45) % 8
        if (eighth === 0) {
            computedY -= annotation.height / 2
        }
        if (eighth === 1) {
            computedX += annotation.width / 2
            computedY -= annotation.height / 2
        }
        if (eighth === 2) {
            computedX += annotation.width / 2
        }
        if (eighth === 3) {
            computedX += annotation.width / 2
            computedY += annotation.height / 2
        }
        if (eighth === 4) {
            computedY += annotation.height / 2
        }
        if (eighth === 5) {
            computedX -= annotation.width / 2
            computedY += annotation.height / 2
        }
        if (eighth === 6) {
            computedX -= annotation.width / 2
        }
        if (eighth === 7) {
            computedX -= annotation.width / 2
            computedY -= annotation.height / 2
        }
    }

    let textX = computedNoteX
    const textY = computedNoteY - noteTextOffset

    let noteLineX = computedNoteX
    const noteLineY = computedNoteY

    if ((angle + 90) % 360 > 180) {
        textX -= noteWidth
        noteLineX -= noteWidth
    } else {
        noteLineX += noteWidth
    }

    return {
        points: [
            [computedX, computedY],
            [computedNoteX, computedNoteY],
            [noteLineX, noteLineY],
        ] as [number, number][],
        text: [textX, textY],
        angle: angle + 90,
    }
}


text:
package org.apache.camel.dataformat.xstream;

import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.QNameMap;
import com.thoughtworks.xstream.io.xml.StaxReader;
import com.thoughtworks.xstream.io.xml.StaxWriter;
import org.apache.camel.Exchange;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.util.IOHelper;

/**
 * A data format
 * ({@link DataFormat}) using XStream to marshal to and from XML
 */
public class XStreamDataFormat extends AbstractXStreamWrapper  {
    private String encoding;

    public XStreamDataFormat() {
    }

    public XStreamDataFormat(XStream xstream) {
        super(xstream);
    }

    @Override
    public String getDataFormatName() {
        return "xstream";
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public String getEncoding() {
        return encoding;
    }

    @Override
    public void marshal(Exchange exchange, Object body, OutputStream stream) throws Exception {
        super.marshal(exchange, body, stream);

        if (isContentTypeHeader()) {
            if (exchange.hasOut()) {
                exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/xml");
            } else {
                exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/xml");
            }
        }
    }

    /**
     * A factory method which takes a collection of types to be annotated
     */
    @Deprecated
    public static XStreamDataFormat processAnnotations(ClassResolver resolver, Iterable<Class<?>> types) {
        XStreamDataFormat answer = new XStreamDataFormat();
        XStream xstream = answer.getXStream(resolver);
        for (Class<?> type : types) {
            xstream.processAnnotations(type);
        }
        return answer;
    }

    /**
     * A factory method which takes a number of types to be annotated
     */
    @Deprecated
    public static XStreamDataFormat processAnnotations(ClassResolver resolver, Class<?>... types) {
        XStreamDataFormat answer = new XStreamDataFormat();
        XStream xstream = answer.getXStream(resolver);
        for (Class<?> type : types) {
            xstream.processAnnotations(type);
        }
        return answer;
    }

    // just make sure the exchange property can override the xmlstream encoding setting
    protected void updateCharactorEncodingInfo(Exchange exchange) {
        if (exchange.getProperty(Exchange.CHARSET_NAME) == null && encoding != null) {
            exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.normalizeCharset(encoding));
        }
    }

    protected HierarchicalStreamWriter createHierarchicalStreamWriter(Exchange exchange, Object body, OutputStream stream) throws XMLStreamException {
        updateCharactorEncodingInfo(exchange);
        if (getXstreamDriver() != null) {
            return getXstreamDriver().createWriter(stream);
        }
        XMLStreamWriter xmlWriter = getStaxConverter().createXMLStreamWriter(stream, exchange);
        return new StaxWriter(new QNameMap(), xmlWriter);
    }

    protected HierarchicalStreamReader createHierarchicalStreamReader(Exchange exchange, InputStream stream) throws XMLStreamException {
        updateCharactorEncodingInfo(exchange);
        if (getXstreamDriver() != null) {
            return getXstreamDriver().createReader(stream);
        }
        XMLStreamReader xmlReader = getStaxConverter().createXMLStreamReader(stream, exchange);
        return new StaxReader(new QNameMap(), xmlReader);
    }
}


text:
#ifndef InspectorCounters_h
#define InspectorCounters_h

#include <wtf/FastAllocBase.h>
#include <wtf/UnusedParam.h>

#if !ASSERT_DISABLED
#include <wtf/MainThread.h>
#endif

namespace WebCore {

class InspectorCounters {
public:
    enum CounterType {
        DocumentCounter,
        NodeCounter,
        JSEventListenerCounter,
        CounterTypeLength
    };

    static inline void incrementCounter(CounterType type)
    {
        ASSERT(isMainThread());
        ++s_counters[type];
    }

    static inline void decrementCounter(CounterType type)
    {
        ASSERT(isMainThread());
        --s_counters[type];
    }

    static int counterValue(CounterType);

private:
    InspectorCounters();

    static int s_counters[CounterTypeLength];
};

class ThreadLocalInspectorCounters {
    WTF_MAKE_FAST_ALLOCATED;
public:
    enum CounterType {
        JSEventListenerCounter,
        CounterTypeLength
    };
    ThreadLocalInspectorCounters();

    inline void incrementCounter(CounterType type)
    {
        ++m_counters[type];
    }

    inline void decrementCounter(CounterType type)
    {
        --m_counters[type];
    }

    int counterValue(CounterType);

    static ThreadLocalInspectorCounters& current();

private:
    int m_counters[CounterTypeLength];
};

} // namespace WebCore

#endif // !defined(InspectorCounters_h)


text:
<?php

namespace phpDocumentor\Translator;

/**
 * Test class for \phpDocumentor\Translator\Translator.
 *
 * @covers phpDocumentor\Translator\Translator
 */
class TranslatorTest extends \PHPUnit_Framework_TestCase
{
    const TEST_KEY = 'KEY';

    const TEST_VALUE = 'value';

    const LOCALE_NL = 'nl';

    /** @var Translator $fixture */
    protected $fixture = null;

    /** @var string Name of the file where an example translation file is stored. */
    protected $filename;

    /** @var string Name of the file where an example domain specific translation file is stored. */
    protected $domainFilename;

    /**
     * Instantiates a new Translator for use as fixture.
     *
     * @return void
     */
    protected function setUp()
    {
        $this->fixture = new Translator();

        $this->filename = sys_get_temp_dir() . '/en.php';
        $this->domainFilename = sys_get_temp_dir() . '/domain.en.php';
        file_put_contents(
            $this->filename,
            <<<TRANSLATION_FILE
<?php
return array(
    'KEY' => 'value',
);
TRANSLATION_FILE
        );
        file_put_contents(
            $this->domainFilename,
            <<<TRANSLATION_FILE
<?php
return array(
    'KEY' => 'domain',
);
TRANSLATION_FILE
        );
    }

    /**
     * Destroys the test translation file.
     *
     * @return void
     */
    protected function tearDown()
    {
        unlink($this->filename);
    }

    /**
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testTranslationReturnsKeyForUnknownTranslation()
    {
        $this->assertEquals(self::TEST_KEY, $this->fixture->translate(self::TEST_KEY));
    }

    /**
     * @covers phpDocumentor\Translator\Translator::addTranslations
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testCanUseTranslationFromIndividualFile()
    {
        $this->fixture->addTranslations($this->filename);

        $this->assertEquals(self::TEST_VALUE, $this->fixture->translate(self::TEST_KEY));
    }

    /**
     * @covers phpDocumentor\Translator\Translator::addTranslations
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testCanUseTranslationFromIndividualFileWithAlternateLocale()
    {
        $this->fixture->addTranslations($this->filename, self::LOCALE_NL);

        $this->assertEquals(
            self::TEST_VALUE,
            $this->fixture->translate(self::TEST_KEY, Translator::DEFAULT_DOMAIN, self::LOCALE_NL)
        );
    }

    /**
     * @covers phpDocumentor\Translator\Translator::addTranslations
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testTranslateWithAlternateDefaultLocale()
    {
        $this->fixture->addTranslations($this->filename, self::LOCALE_NL);
        $this->fixture->setLocale(self::LOCALE_NL);

        $this->assertEquals(self::TEST_VALUE, $this->fixture->translate(self::TEST_KEY));
    }

    /**
     * @covers phpDocumentor\Translator\Translator::addTranslations
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testCanUseTranslationFromIndividualFileWithFallbackToEnglish()
    {
        $this->fixture->addTranslations($this->filename, Translator::DEFAULT_LOCALE);

        $this->assertEquals(
            self::TEST_VALUE,
            $this->fixture->translate(self::TEST_KEY, Translator::DEFAULT_DOMAIN, self::LOCALE_NL)
        );
    }

    /**
     * @covers phpDocumentor\Translator\Translator::addTranslationFolder
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testCanUseTranslationFromFolder()
    {
        $this->fixture->addTranslationFolder(dirname($this->filename));

        $this->assertEquals(self::TEST_VALUE, $this->fixture->translate(self::TEST_KEY));
    }

    /**
     * @covers phpDocumentor\Translator\Translator::addTranslationFolder
     * @covers phpDocumentor\Translator\Translator::translate
     */
    public function testCanUseTranslationsFromASpecificDomainOrCatalogue()
    {
        $this->fixture->addTranslationsUsingPattern(dirname($this->domainFilename), 'domain');

        $this->assertEquals('domain', $this->fixture->translate(self::TEST_KEY, 'domain'));
    }
}


text:
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace System.Security
{
    public sealed partial class SecureString : IDisposable
    {
        private const int MaxLength = 65536;
        private readonly object _methodLock = new object();
        private bool _readOnly;
        private int _decryptedLength;

        public unsafe SecureString()
        {
            InitializeSecureString(null, 0);
        }

        [CLSCompliant(false)]
        public unsafe SecureString(char* value, int length)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (length > MaxLength)
            {
                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Length);
            }

            InitializeSecureString(value, length);
        }

        public int Length
        {
            get
            {
                lock (_methodLock)
                {
                    EnsureNotDisposed();
                    return _decryptedLength;
                }
            }
        }

        public void AppendChar(char c)
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                EnsureNotReadOnly();
                AppendCharCore(c);
            }
        }

        // clears the current contents. Only available if writable
        public void Clear()
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                EnsureNotReadOnly();
                ClearCore();
            }
        }

        // Do a deep-copy of the SecureString
        public SecureString Copy()
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                return new SecureString(this);
            }
        }

        public void Dispose()
        {
            lock (_methodLock)
            {
                DisposeCore();
            }
        }

        public void InsertAt(int index, char c)
        {
            lock (_methodLock)
            {
                if (index < 0 || index > _decryptedLength)
                {
                    throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexString);
                }

                EnsureNotDisposed();
                EnsureNotReadOnly();

                InsertAtCore(index, c);
            }
        }

        public bool IsReadOnly()
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                return _readOnly;
            }
        }

        public void MakeReadOnly()
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                _readOnly = true;
            }
        }

        public void RemoveAt(int index)
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                EnsureNotReadOnly();

                if (index < 0 || index >= _decryptedLength)
                {
                    throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexString);
                }

                RemoveAtCore(index);
            }
        }

        public void SetAt(int index, char c)
        {
            lock (_methodLock)
            {
                if (index < 0 || index >= _decryptedLength)
                {
                    throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexString);
                }
                Debug.Assert(index <= Int32.MaxValue / sizeof(char));

                EnsureNotDisposed();
                EnsureNotReadOnly();

                SetAtCore(index, c);
            }
        }

        private void EnsureNotReadOnly()
        {
            if (_readOnly)
            {
                throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
            }
        }

        internal unsafe IntPtr MarshalToString(bool globalAlloc, bool unicode)
        {
            lock (_methodLock)
            {
                EnsureNotDisposed();
                return MarshalToStringCore(globalAlloc, unicode);
            }
        }

        private static void MarshalFree(IntPtr ptr, bool globalAlloc)
        {
            if (globalAlloc)
            {
                Marshal.FreeHGlobal(ptr);
            }
            else
            {
                Marshal.FreeCoTaskMem(ptr);
            }
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: LogShortBase</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>

OR-Tools
    9.4

Public Member Functions |
List of all members

LogShortBase

Detailed Description

Definition at line 84 of file container_logging.h.

Public Member Functions

void 	LogOpening (std::ostream &out) const

void 	LogClosing (std::ostream &out) const

void 	LogFirstSeparator (std::ostream &out) const

void 	LogSeparator (std::ostream &out) const

template<typename ElementT >

void 	Log (std::ostream &out, const ElementT &element) const

void 	LogEllipsis (std::ostream &out) const

Member Function Documentation

◆ Log()

          void Log
          (
          std::ostream &
          out,

          const ElementT &
          element

          )
          	 const

inlineinherited

Definition at line 76 of file container_logging.h.

◆ LogClosing()

          void LogClosing
          (
          std::ostream &
          out	)
           const

inline

Definition at line 86 of file container_logging.h.

◆ LogEllipsis()

          void LogEllipsis
          (
          std::ostream &
          out	)
           const

inlineinherited

Definition at line 79 of file container_logging.h.

◆ LogFirstSeparator()

          void LogFirstSeparator
          (
          std::ostream &
          out	)
           const

inline

Definition at line 87 of file container_logging.h.

◆ LogOpening()

          void LogOpening
          (
          std::ostream &
          out	)
           const

inline

Definition at line 85 of file container_logging.h.

◆ LogSeparator()

          void LogSeparator
          (
          std::ostream &
          out	)
           const

inline

Definition at line 88 of file container_logging.h.

The documentation for this struct was generated from the following file:

container_logging.h

gtl

internal

LogShortBase

Generated by

     1.9.4


text:
<?php

namespace Krixon\Math;

class Decimal
{
    /**
     * Default scale used when none is specified.
     */
    const SCALE = 20;

    /**
     * @var string
     */
    private $characteristic;

    /**
     * @var string|null
     */
    private $mantissa;

    /**
     * @var string
     */
    private $value;

    /**
     * @var Decimal
     */
    private static $zero;

    /**
     * @var Decimal
     */
    private static $one;

    /**
     * @param string $value
     * @param int    $scale
     */
    public function __construct(string $value, int $scale = null)
    {
        if (!preg_match('#^(?<s>[+-])?(?<c>\d*)(?:\.(?<m>\d+))?$#', $value, $matches)) {
            throw new \InvalidArgumentException("Cannot create Decimal from invalid string '$value'.");
        }

        $sign           = $matches['s'] ?? '';
        $characteristic = $matches['c'] ?? '0';

        // Multiply by 1 to be sure of having consistent leading zeroes (just one).
        $characteristic = bcmul($characteristic, 1);
        $mantissa       = $matches['m'] ?? null;

        // bccomp has some weird behaviour where it treats -0.0 as < 0. We don't want to distinguish between the two
        // as the difference is only relevant in things like floating point numbers. If the value is 0 and a sign is
        // included, strip the sign out.
        if ($sign === '-' && $characteristic === '0' && (null === $mantissa || bccomp($mantissa, '0') === 0)) {
            $sign = '';
        } elseif ($sign === '+') {
            $sign = '';
        }

        if (null !== $scale) {
            $mantissa = self::scaleMantissa($mantissa, $scale);
        }

        // The sign is added separately because bcmul might lose it for number such as -0.1 due to the mantissa.
        $this->characteristic = $sign . $characteristic;
        $this->mantissa       = $mantissa;
        $this->value          = $this->characteristic . (null !== $mantissa ? ".$mantissa" : '');
    }

    /**
     * @return Decimal
     */
    public static function zero() : Decimal
    {
        if (null === static::$zero) {
            static::$zero = new static('0');
        }

        return static::$zero;
    }

    /**
     * @return Decimal
     */
    public static function one() : Decimal
    {
        if (null === static::$one) {
            static::$one = new static('1');
        }

        return static::$one;
    }

    /**
     * General purpose static factory for creating an instance from any supported type.
     *
     * @param mixed    $value
     * @param int|null $scale
     *
     * @return Decimal
     */
    public static function create($value, int $scale = null) : Decimal
    {
        if (is_int($value)) {
            return static::fromInteger($value);
        }

        if (is_float($value)) {
            return static::fromFloat($value, $scale);
        }

        if (is_string($value)) {
            return static::fromString($value, $scale);
        }

        if ($value instanceof Decimal) {
            return static::fromDecimal($value, $scale);
        }

        if ($value instanceof Ratio) {
            return static::fromRatio($value, $scale);
        }

        throw new \InvalidArgumentException('Decimal can only be created from an int, float or string.');
    }

    /**
     * @param int $value
     *
     * @return Decimal
     */
    public static function fromInteger(int $value) : Decimal
    {
        return new static((string)$value, 0);
    }

    /**
     * @param float $value
     * @param int   $scale
     *
     * @return Decimal
     */
    public static function fromFloat(float $value, int $scale = null) : Decimal
    {
        if (INF === $value || -INF === $value) {
            throw new \InvalidArgumentException('Support for infinite Decimals is not implemented.');
        }

        if (is_nan($value)) {
            throw new \InvalidArgumentException('Cannot create a Decimal from NaN.');
        }

        if (null === $scale) {
            $scale = self::SCALE;
        }

        $value = number_format($value, $scale, '.', '');

        return new static($value);
    }

    /**
     * Creates a new instance from a decimal string.
     *
     * @param string   $value
     * @param int|null $scale
     *
     * @return Decimal
     */
    public static function fromString(string $value, int $scale = null) : Decimal
    {
        return new static($value, $scale);
    }

    /**
     * Creates a new instance from an existing instance.
     *
     * Note that if the scale is not specified the original instance will be returned since it represents the same
     * value.
     *
     * @param Decimal  $decimal
     * @param int|null $scale
     *
     * @return Decimal
     */
    public static function fromDecimal(Decimal $decimal, int $scale = null) : Decimal
    {
        if (null === $scale) {
            return $decimal;
        }

        return $decimal->scale($scale);
    }

    /**
     * Creates a new instance from a Ratio.
     *
     * @param Ratio    $ratio
     * @param int|null $scale
     *
     * @return Decimal
     */
    public static function fromRatio(Ratio $ratio, int $scale = null) : Decimal
    {
        return $ratio->toDecimal($scale);
    }

    /**
     * The characteristic (integer component) of the decimal.
     *
     * @return string
     */
    public function characteristic() : string
    {
        return $this->characteristic;
    }

    /**
     * The mantissa (fractional component) of the decimal.
     *
     * @return string|null
     */
    public function mantissa()
    {
        return $this->mantissa;
    }

    /**
     * Determines if this instance is equal to another.
     *
     * @param Decimal $other
     * @param int     $scale
     *
     * @return bool
     */
    public function equals(Decimal $other, int $scale = null) : bool
    {
        if ($other === $this) {
            return true;
        }

        if (get_class($this) !== get_class($other)) {
            return false;
        }

        if (null === $scale) {
            $scale = max($this->numberOfDecimalPlaces(), $other->numberOfDecimalPlaces());
        }

        return $this->compare($other, $scale) === 0;
    }

    /**
     * @param Decimal  $other
     * @param int|null $scale
     *
     * @return bool
     */
    public function isLessThan(Decimal $other, int $scale = null) : bool
    {
        return -1 === $this->compare($other, $scale);
    }

    /**
     * @param Decimal  $other
     * @param int|null $scale
     *
     * @return bool
     */
    public function isLessThanOrEqualTo(Decimal $other, int $scale = null) : bool
    {
        return $this->equals($other, $scale) || $this->isLessThan($other, $scale);
    }

    /**
     * @param Decimal  $other
     * @param int|null $scale
     *
     * @return bool
     */
    public function isGreaterThan(Decimal $other, int $scale = null) : bool
    {
        return 1 === $this->compare($other, $scale);
    }

    /**
     * @param Decimal  $other
     * @param int|null $scale
     *
     * @return bool
     */
    public function isGreaterThanOrEqualTo(Decimal $other, int $scale = null) : bool
    {
        return $this->equals($other, $scale) || $this->isGreaterThan($other, $scale);
    }

    /**
     * Compares the Decimal with another at the specified scale.
     *
     * @param Decimal $other
     * @param int     $scale
     *
     * @return int An integer less than, equal to or greater than 0 when this instance is respectively less than,
     *             equal to or greater than the $other instance.
     */
    public function compare(Decimal $other, int $scale = null) : int
    {
        if ($this === $other) {
            return 0;
        }

        $scale = $this->resolveMinimumScale($scale, $other);

        return bccomp($this->toString(), $other->toString(), $scale);
    }

    /**
     * @return bool
     */
    public function isNegative() : bool
    {
        return $this->compare(static::zero()) < 0;
    }

    /**
     * @return bool
     */
    public function isZero() : bool
    {
        return $this->compare(static::zero()) === 0;
    }

    /**
     * @return bool
     */
    public function isOne() : bool
    {
        return $this->compare(static::one()) === 0;
    }

    /**
     * @return bool
     */
    public function isPositive() : bool
    {
        return $this->compare(static::zero()) > 0;
    }

    /**
     * Determines if the decimal is an integer.
     *
     * Note that values such as 10.0 are not considered integers because the .0 is a significant digit. A value is
     * only an integer if it does not have a mantissa at all.
     *
     * @return bool
     */
    public function isInteger() : bool
    {
        return null === $this->mantissa;
    }

    /**
     * Counts the number of decimal places.
     *
     * Note that this is not the same thing as significant digits. The number of decimal places is simply the number
     * of digits after the decimal point.
     *
     * @return int
     */
    public function numberOfDecimalPlaces() : int
    {
        return strlen($this->mantissa);
    }

    /**
     * Counts the number of significant digits of $decimal.
     *
     * Zeros before other digits are not significant. 0.046 has 2 significant digits.
     *
     * Zeros between other digits are always significant. 4009 has 4 significant digits.
     *
     * Zeros behind other digits and a decimal point are always significant. 7.90 has 3 significant digits.
     *
     * It's technically impossible to tell if zeros at the end of a number but in front of the decimal point are
     * significant. 4200 could have 2, 3 or 4 significant digits. For the purposes of this calculation, they are
     * counted, so 4200 has 4 significant digits.
     *
     * @return int
     */
    public function numberOfSignificantDigits() : int
    {
        $characteristicDigits = strlen(ltrim($this->characteristic, '-0'));

        if (0 === $characteristicDigits) {
            $mantissaDigits = strlen(ltrim($this->mantissa, '0'));
        } else {
            $mantissaDigits = strlen($this->mantissa);
        }

        return $characteristicDigits + $mantissaDigits;
    }

    /**
     * Scales the decimal to the specified precision.
     *
     * @param int $scale
     *
     * @return Decimal
     */
    public function scale(int $scale) : Decimal
    {
        if ($scale === $this->numberOfDecimalPlaces()) {
            return $this;
        }

        return static::fromString($this->toString($scale));
    }

    /**
     * Rounds the decimal to the specified number of decimal places.
     *
     * @param int $decimalPlaces
     *
     * @return Decimal
     */
    public function round(int $decimalPlaces = 0) : Decimal
    {
        // FIXME: Support other rounding modes aside from just ROUND_HALF_UP.

        if ($decimalPlaces === $this->numberOfDecimalPlaces()) {
            return $this;
        }

        $mantissa = str_repeat('0', $decimalPlaces) . '5';
        $value    = bcadd($this->toString(), "0.$mantissa", $decimalPlaces + 1);
        $value    = bcdiv($value, '1.0', $decimalPlaces);

        if (strpos($value, '.') !== false) {
            $value = rtrim($value, '0');
            $value = rtrim($value, '.');
        }

        return static::fromString($value);
    }

    /**
     * Returns a decimal with the absolute value of this decimal.
     *
     * @return Decimal
     */
    public function abs() : Decimal
    {
        if ($this->isPositive()) {
            return $this;
        }

        return static::fromString(bcmul($this->value, '-1', $this->numberOfDecimalPlaces()));
    }

    /**
     * Adds another decimal to this.
     *
     * @param Decimal  $addend
     * @param int|null $scale
     *
     * @return Decimal
     */
    public function plus(Decimal $addend, int $scale = null) : Decimal
    {
        if (null === $scale) {
            $scale = max($this->numberOfDecimalPlaces(), $addend->numberOfDecimalPlaces());
        }

        $result = bcadd($this->value, $addend->value, $scale);

        return new static($result);
    }

    /**
     * Subtracts another decimal from this.
     *
     * @param Decimal  $subtrahend
     * @param int|null $scale
     *
     * @return Decimal
     */
    public function minus(Decimal $subtrahend, int $scale = null) : Decimal
    {
        if (null === $scale) {
            $scale = max($this->numberOfDecimalPlaces(), $subtrahend->numberOfDecimalPlaces());
        }

        $result = bcsub($this->value, $subtrahend->value, $scale);

        return new static($result);
    }

    /**
     * Multiplies this decimal by another.
     *
     * @param Decimal $factor
     * @param null    $scale
     *
     * @return Decimal
     */
    public function multiplyBy(Decimal $factor, $scale = null) : Decimal
    {
        if ($factor->isZero()) {
            return static::zero();
        }

        if (null === $scale) {
            $scale = $this->numberOfDecimalPlaces() + $factor->numberOfDecimalPlaces();
        }

        $result = bcmul($this->value, $factor->value, $scale);

        return new static($result);
    }

    /**
     * Divides this decimal by another.
     *
     * @param Decimal $other
     * @param int     $scale
     *
     * @return Decimal
     */
    public function divideBy(Decimal $other, int $scale = null) : Decimal
    {
        if ($other->isZero()) {
            throw new \LogicException('Cannot divide by zero.');
        }

        if ($other->isOne()) {
            return $this;
        }

        if (null === $scale) {
            // Determine a reasonable scale to avoid too much loss of precision.

            $abs        = $this->abs();
            $otherAbs   = $other->abs();
            $otherLog10 = self::computeLog10($otherAbs->value, $otherAbs->numberOfDecimalPlaces(), 1);
            $log10      = self::computeLog10($abs->value, $abs->numberOfDecimalPlaces(), 1) - $otherLog10;

            $totalDecimalPlaces   = $this->numberOfDecimalPlaces() + $other->numberOfDecimalPlaces();
            $maxSignificantDigits = max($this->numberOfSignificantDigits(), $other->numberOfSignificantDigits());

            $scale = (int)max(
                $totalDecimalPlaces,
                $maxSignificantDigits - max(ceil($log10), 0),
                ceil(-$log10) + 1
            );
        }

        $result = bcdiv($this->value, $other->value, $scale);

        return static::fromString($result);
    }

    /**
     * Converts the decimal to a string.
     *
     * @param int $scale
     *
     * @return string
     */
    public function toString(int $scale = null) : string
    {
        if ($scale !== null) {
            $value    = $this->characteristic;
            $mantissa = self::scaleMantissa($this->mantissa, $scale);

            if (null !== $mantissa) {
                $value .= ".$mantissa";
            }

            return $value;
        }

        return $this->value;
    }

    /**
     * Converts the decimal to a string, with magic!
     *
     * @return string
     */
    public function __toString() : string
    {
        return $this->toString();
    }

    /**
     * Converts this decimal to a ratio.
     *
     * For example, given the decimal 1.5 this will return the ratio 2:1.
     *
     * @return Ratio
     */
    public function toRatio() : Ratio
    {
        $ratio = new Ratio($this, new Decimal('1'));

        return $ratio->simplify();
    }

    /**
     * @param int|null  $scale
     * @param Decimal[] ...$others
     *
     * @return int|mixed
     */
    private function resolveMinimumScale(int $scale = null, Decimal ...$others)
    {
        if (null !== $scale) {
            return $scale;
        }

        $others[] = $this;

        return max(array_map(function (Decimal $other) {
            return $other->numberOfDecimalPlaces();
        }, $others));
    }

    /**
     * Computes the base-10 logarithm of the specified value.
     *
     * @param string $value
     * @param int    $inputScale
     * @param int    $scale
     *
     * @return string
     */
    private static function computeLog10(string $value, int $inputScale, int $scale)
    {
        $length = strlen($value);

        switch (bccomp($value, '1', $inputScale)) {
            case 1:
                $approxLog10 = $length - ($inputScale > 0 ? ($inputScale + 2) : 1);

                return bcadd(
                    $approxLog10,
                    log10(bcdiv($value, bcpow('10', $approxLog10), min($length, $scale))),
                    $scale
                );
            case -1:
                preg_match('/^0*\.(0*)[1-9][0-9]*$/', $value, $matches);

                $approxLog10 = -strlen($matches[1]) - 1;

                return bcadd(
                    $approxLog10,
                    log10(bcmul($value, bcpow('10', -$approxLog10), $inputScale + $approxLog10)),
                    $scale
                );
        }

        return '0';
    }

    private static function scaleMantissa($mantissa, int $scale)
    {
        if (0 === $scale) {
            return null;
        }

        if (null === $mantissa) {
            return str_repeat('0', $scale);
        }

        $decimals = strlen($mantissa);

        // Mantissa is the correct scale.
        if ($scale === $decimals) {
            return $mantissa;
        }

        // Mantissa is too long, use bcmul to truncate to the correct scale.
        if ($scale < $decimals) {
            return substr($mantissa, 0, $scale);
        }

        // Mantissa is too short, pad with zeroes to the correct scale.
        return sprintf("%0-{$scale}s", $mantissa);
    }
}


text:
package com.sc.td.business.dao.scregistbroker;

import java.util.List;

import com.sc.td.business.base.BaseDao;
import com.sc.td.business.entity.scregistbroker.ScRegistBroker;

public interface ScRegistBrokerDao extends BaseDao<ScRegistBroker> {

	List<ScRegistBroker> findByBrokerType(String brokerType);
}


text:
package com.linkedin.thirdeye.datasource;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;
import com.linkedin.thirdeye.constant.MetricAggFunction;
import com.linkedin.thirdeye.datalayer.dto.DatasetConfigDTO;
import com.linkedin.thirdeye.datalayer.dto.MetricConfigDTO;

public class MetricFunction implements Comparable<MetricFunction> {

  private MetricAggFunction functionName;
  private String metricName;
  private Long metricId;
  private String dataset;
  private MetricConfigDTO metricConfig;
  private DatasetConfigDTO datasetConfig;

  public MetricFunction() {

  }

  public MetricFunction(@JsonProperty("functionName") MetricAggFunction functionName,
      @JsonProperty("metricName") String metricName, @JsonProperty("metricId") Long metricId,
      @JsonProperty("dataset") String dataset, @JsonProperty("metricConfig") MetricConfigDTO metricConfig,
      @JsonProperty("datasetConfig") DatasetConfigDTO datasetConfig) {
    this.functionName = functionName;
    this.metricName = metricName;
    this.metricId = metricId;
    this.dataset = dataset;
    this.metricConfig = metricConfig;
    this.datasetConfig = datasetConfig;
  }

  private String format(String functionName, String metricName) {
    return String.format("%s_%s", functionName, metricName);
  }

  @Override
  public String toString() {
    // TODO this is hardcoded for pinot's return column name, but there's no binding contract that
    // clients need to return response objects with these keys.
   return format(functionName.name(), metricName);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(functionName, metricName, metricId, dataset);
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof MetricFunction)) {
      return false;
    }
    MetricFunction mf = (MetricFunction) obj;
    return Objects.equal(functionName, mf.functionName)
        && Objects.equal(metricName, mf.metricName)
        && Objects.equal(metricId, mf.metricId)
        && Objects.equal(dataset, mf.dataset);
  }

  @Override
  public int compareTo(MetricFunction o) {
    return this.toString().compareTo(o.toString());
  }

  public MetricAggFunction getFunctionName() {
    return functionName;
  }

  public String getMetricName() {
    return metricName;
  }

  public void setMetricName(String metricName) {
    this.metricName = metricName;
  }

  public void setFunctionName(MetricAggFunction functionName) {
    this.functionName = functionName;
  }

  public Long getMetricId() {
    return metricId;
  }

  public void setMetricId(Long metricId) {
    this.metricId = metricId;
  }

  public String getDataset() {
    return dataset;
  }

  public void setDataset(String dataset) {
    this.dataset = dataset;
  }

  public MetricConfigDTO getMetricConfig() {
    return metricConfig;
  }

  public void setMetricConfig(MetricConfigDTO metricConfig) {
    this.metricConfig = metricConfig;
  }

  public DatasetConfigDTO getDatasetConfig() {
    return datasetConfig;
  }

  public void setDatasetConfig(DatasetConfigDTO datasetConfig) {
    this.datasetConfig = datasetConfig;
  }

}


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CONTENT_BROWSER_ANDROID_EDGE_EFFECT_H_
#define CONTENT_BROWSER_ANDROID_EDGE_EFFECT_H_

#include "base/basictypes.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "ui/gfx/size_f.h"

namespace cc {
class Layer;
}

namespace content {

/* |EdgeEffect| mirrors its Android counterpart, EdgeEffect.java.
 * The primary difference is ownership; the Android version manages render
 * resources directly, while this version simply applies the effect to
 * existing resources. Conscious tradeoffs were made to align this as closely
 * as possible with the original Android java version.
 * All coordinates and dimensions are in device pixels.
 */
class EdgeEffect {
public:
  enum Edge {
    EDGE_TOP = 0,
    EDGE_LEFT,
    EDGE_BOTTOM,
    EDGE_RIGHT,
    EDGE_COUNT
  };

  EdgeEffect(scoped_refptr<cc::Layer> edge, scoped_refptr<cc::Layer> glow);
  ~EdgeEffect();

  void Pull(base::TimeTicks current_time, float delta_distance);
  void Absorb(base::TimeTicks current_time, float velocity);
  bool Update(base::TimeTicks current_time);
  void Release(base::TimeTicks current_time);

  void Finish();
  bool IsFinished() const;

  void ApplyToLayers(gfx::SizeF window_size,
                     Edge edge,
                     float edge_height,
                     float glow_height,
                     float offset);

private:

  enum State {
    STATE_IDLE = 0,
    STATE_PULL,
    STATE_ABSORB,
    STATE_RECEDE,
    STATE_PULL_DECAY
  };

  scoped_refptr<cc::Layer> edge_;
  scoped_refptr<cc::Layer> glow_;

  float edge_alpha_;
  float edge_scale_y_;
  float glow_alpha_;
  float glow_scale_y_;

  float edge_alpha_start_;
  float edge_alpha_finish_;
  float edge_scale_y_start_;
  float edge_scale_y_finish_;
  float glow_alpha_start_;
  float glow_alpha_finish_;
  float glow_scale_y_start_;
  float glow_scale_y_finish_;

  base::TimeTicks start_time_;
  base::TimeDelta duration_;

  State state_;

  float pull_distance_;

  DISALLOW_COPY_AND_ASSIGN(EdgeEffect);
};

}  // namespace content

#endif  // CONTENT_BROWSER_ANDROID_EDGE_EFFECT_H_


text:
<?xml version='1.0'?>

<ui:UiBinder
  xmlns:ui="urn:ui:com.google.gwt.uibinder"
  xmlns:gwt="urn:import:com.google.gwt.user.client.ui"
>
  <ui:with field="res"
    type="org.waveprotocol.wave.client.widget.popup.desktopchrome.DropdownPopupChrome.Resources" />
  <gwt:HTMLPanel ui:field='frame' >

  </gwt:HTMLPanel>
</ui:UiBinder>


text:
#ifndef __WmeBRegistry_H__
#define __WmeBRegistry_H__

#include "BBase.h"

namespace WinterMute {

class CBRegistry : public CBBase {
public:
	void SetIniName(char *Name);
	char *GetIniName();
	bool WriteBool(const AnsiString &subKey, const AnsiString &key, bool Value);
	bool ReadBool(const AnsiString &subKey, const AnsiString &key, bool init = false);
	bool WriteInt(const AnsiString &subKey, const AnsiString &key, int value);
	int ReadInt(const AnsiString &subKey, const AnsiString &key, int init = 0);
	bool WriteString(const AnsiString &subKey, const AnsiString &key, const AnsiString &value);
	AnsiString ReadString(const AnsiString &subKey, const AnsiString &key, const AnsiString &init = "");
	CBRegistry(CBGame *inGame);
	virtual ~CBRegistry();

	void SetBasePath(const char *basePath);
	AnsiString GetBasePath() const {
		return m_BasePath;
	}

	void LoadValues(bool local);
	void SaveValues();

private:
	char *m_IniName;

	typedef std::map<AnsiString, AnsiString> KeyValuePair;
	typedef std::map<AnsiString, KeyValuePair> PathValueMap;

	PathValueMap m_LocalValues;
	PathValueMap m_Values;

	AnsiString m_BasePath;

	void LoadXml(const AnsiString fileName, PathValueMap &values);
	void SaveXml(const AnsiString fileName, PathValueMap &values);

	AnsiString GetValue(PathValueMap &values, const AnsiString path, const AnsiString &key, bool &found);
};

} // end of namespace WinterMute

#endif


text:
package com.cyss.android.lib;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.cyss.android.lib.utils.CYLog;
import com.cyss.android.lib.utils.ScreenUtils;

/**
 * Created by cyjss on 2015/9/1.
 */
public class CYSlidingMenu extends HorizontalScrollView {

    private View contentView;
    private View leftMenuView;
    private LinearLayout container;
    private FrameLayout leftMenuContainer;
    private LinearLayout contentContainer;

    private int mTouchSlop;

    private int paddingLeft = 100;
    private int leftMenuWidth;
    private Boolean leftMenuOpen = false;
    private float downX = 0;
    private float downY = 0;
    private float downOffsetX = 0;
    private boolean allowSlidingLeft = false;

    private boolean initFlag = false;

    public CYSlidingMenu(Context context) {
        super(context);
        this.init();
    }

    public CYSlidingMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init();
    }

    public CYSlidingMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CYSlidingMenu(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.init();
    }

    private void init() {
        this.mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        this.container = new LinearLayout(getContext());
        this.container.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this.container.setOrientation(LinearLayout.HORIZONTAL);
        this.addView(this.container);
        this.setOverScrollMode(OVER_SCROLL_ALWAYS);
        this.setHorizontalScrollBarEnabled(false);

        this.contentContainer = new LinearLayout(getContext());
        this.container.addView(this.contentContainer);

        this.leftMenuContainer = new FrameLayout(getContext());
        this.container.addView(this.leftMenuContainer, 0);
    }

    private void addContentView() {
        this.contentContainer.addView(this.contentView);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.contentView.getLayoutParams();
        lp.width = LayoutParams.MATCH_PARENT;
        lp.height = LayoutParams.MATCH_PARENT;
        this.contentView.setLayoutParams(lp);
    }

    private void addLeftMenu() {
        this.leftMenuContainer.addView(this.leftMenuView);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) this.leftMenuView.getLayoutParams();
        lp.width = LayoutParams.MATCH_PARENT;
        lp.height = LayoutParams.MATCH_PARENT;
        this.leftMenuView.setLayoutParams(lp);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean flag = false;
        float x = ev.getX();
        float y = ev.getY();
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            this.downX = ev.getX();
            this.downY = ev.getY();
            this.downOffsetX = this.getScrollX();
            flag = leftMenuOpen;
            int offsetX = leftMenuWidth - this.getScrollX();
            if (ev.getX() < offsetX + paddingLeft && ev.getX() > offsetX) {
                allowSlidingLeft = true;
            }
        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            float dy = y - this.downY;
            float dx = x - this.downX;
            boolean canScrollVertically = canScrollVertically(this.contentContainer, (int) dy, (int) x, (int) y);
            if (Math.abs(dy) >= mTouchSlop && canScrollVertically) {
                requestDisallowInterceptTouchEvent(true);
                return false;
            } else {
                boolean canScrollHorizontally = canScrollHorizontally(this.contentContainer, (int) dx, (int) x, (int) y);
                flag = Math.abs(dx) >= mTouchSlop && allowSlidingLeft && !canScrollHorizontally;
            }
        }
        return flag;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            this.downX = ev.getX();
            this.downY = ev.getY();
            int offsetX = leftMenuWidth - this.getScrollX();
            this.downOffsetX = this.getScrollX();
            if (this.downX < offsetX + paddingLeft && this.downX > offsetX) {
                allowSlidingLeft = true;
            }
        } else if (ev.getAction() == MotionEvent.ACTION_UP
                || ev.getAction() == MotionEvent.ACTION_CANCEL
                || ev.getAction() == MotionEvent.ACTION_OUTSIDE) {
            int offsetX = leftMenuWidth - this.getScrollX();
            if (Math.round(this.downX) == Math.round(ev.getX()) && leftMenuOpen && ((this.downX < offsetX + paddingLeft && this.downX > offsetX))) {
                this.closeLeftMenu();
            } else {
                if (this.getScrollX() < leftMenuWidth / 2) {
                    this.openLeftMenu();
                } else {
                    this.closeLeftMenu();
                }
            }
            allowSlidingLeft = false;
            getParent().requestDisallowInterceptTouchEvent(false);
        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            if (allowSlidingLeft) {
                getParent().requestDisallowInterceptTouchEvent(true);
                scrollTo((int) (this.downX - ev.getX() + this.downOffsetX), 0);
            }
        }
        return true;
    }

    protected final boolean canScrollVertically(View v, int dy, int x, int y) {
        if (v instanceof ViewGroup) {
            final ViewGroup viewGroup = (ViewGroup) v;
            final int scrollX = v.getScrollX();
            final int scrollY = v.getScrollY();

            final int childCount = viewGroup.getChildCount();
            for (int index = 0; index < childCount; index++) {
                View child = viewGroup.getChildAt(index);
                final int left = child.getLeft();
                final int top = child.getTop();
                if (x + scrollX >= left
                        && x + scrollX < child.getRight()
                        && y + scrollY >= top
                        && y + scrollY < child.getBottom()
                        && View.VISIBLE == child.getVisibility()
                        && canScrollVertically(
                        child, dy, x + scrollX - left, y + scrollY
                                - top)) {
                    return true;
                }
            }
        }
        return ViewCompat.canScrollVertically(v, -dy);
    }

    protected final boolean canScrollHorizontally(View v, int dx, int x, int y) {
        if (v instanceof ViewGroup) {
            final ViewGroup viewGroup = (ViewGroup) v;
            final int scrollX = v.getScrollX();
            final int scrollY = v.getScrollY();

            final int childCount = viewGroup.getChildCount();
            for (int index = 0; index < childCount; index++) {
                View child = viewGroup.getChildAt(index);
                final int left = child.getLeft();
                final int top = child.getTop();
                if (x + scrollX >= left
                        && x + scrollX < child.getRight()
                        && y + scrollY >= top
                        && y + scrollY < child.getBottom()
                        && View.VISIBLE == child.getVisibility()
                        && canScrollHorizontally(
                        child, dx, x + scrollX - left, y + scrollY
                                - top)) {
                    return true;
                }
            }
        }
        return ViewCompat.canScrollHorizontally(v, -dx);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int w = MeasureSpec.getSize(widthMeasureSpec);
        int wMode = MeasureSpec.getMode(widthMeasureSpec);
        if (wMode == MeasureSpec.UNSPECIFIED) {
            w = ScreenUtils.getScreenSize(getContext())[0];
        }
        LinearLayout.LayoutParams lp = null;

        lp = (LinearLayout.LayoutParams) this.contentContainer.getLayoutParams();
        lp.width = w;
        lp.height = LinearLayout.LayoutParams.MATCH_PARENT;

        lp = (LinearLayout.LayoutParams) this.leftMenuContainer.getLayoutParams();
        lp.width = w - paddingLeft;
        lp.height = LinearLayout.LayoutParams.MATCH_PARENT;
        this.leftMenuWidth = lp.width;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (!initFlag) {
            initFlag = !initFlag;
            this.scrollTo(leftMenuWidth, 0);
        }
    }

    public void openLeftMenu() {
        smoothScrollTo(0, 0);
        this.leftMenuOpen = true;
    }

    public void closeLeftMenu() {
        smoothScrollTo(leftMenuWidth, 0);
        this.leftMenuOpen = false;
    }

    public void setContentView(View view) {
        this.contentView = view;
        this.addContentView();
    }

    public void setContentView(int layout) {
        this.contentView = LayoutInflater.from(getContext()).inflate(layout, null);
        this.addContentView();
    }

    public void setLeftMenuView(View menuView) {
        this.leftMenuView = menuView;
        this.addLeftMenu();
    }

    public void setLeftMenuView(int layout) {
        this.leftMenuView = LayoutInflater.from(getContext()).inflate(layout, null);
        this.addLeftMenu();
    }
}


text:
namespace Woo {
	namespace Graphics {
		class VertexArray {
		private:
			GLuint m_arrayID;
			std::vector<VertexBuffer*> m_buffers;
		public:
			VertexArray();
			~VertexArray();
			void Bind() const;
			void UnBind() const;
			void AddBuffer(VertexBuffer* newBuffer, GLuint index);

		};
	}
}


text:
"""
A subclass of `Trainer` specific to Question-Answering tasks
"""
import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import Seq2SeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics

if is_torch_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm
    import torch_xla.debug.metrics as met

class QuestionAnsweringSeq2SeqTrainer(Seq2SeqTrainer):
    def __init__(self, *args, eval_examples=None, post_process_function=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.eval_examples = eval_examples
        self.post_process_function = post_process_function

    # def evaluate(self, eval_dataset=None, eval_examples=None, ignore_keys=None, metric_key_prefix: str = "eval"):
    def evaluate(
        self,
        eval_dataset: Optional[Dataset] = None,
        eval_examples=None,
        ignore_keys: Optional[List[str]] = None,
        metric_key_prefix: str = "eval",
        **gen_kwargs,
    ) -> Dict[str, float]:
        gen_kwargs = gen_kwargs.copy()
        gen_kwargs["max_length"] = (
            gen_kwargs["max_length"] if gen_kwargs.get("max_length") is not None else self.args.generation_max_length
        )
        gen_kwargs["num_beams"] = (
            gen_kwargs["num_beams"] if gen_kwargs.get("num_beams") is not None else self.args.generation_num_beams
        )
        self._gen_kwargs = gen_kwargs

        eval_dataset = self.eval_dataset if eval_dataset is None else eval_dataset
        eval_dataloader = self.get_eval_dataloader(eval_dataset)
        eval_examples = self.eval_examples if eval_examples is None else eval_examples

        # Temporarily disable metric computation, we will do it in the loop here.
        compute_metrics = self.compute_metrics
        self.compute_metrics = None
        start_time = time.time()
        eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
        try:
            output = eval_loop(
                eval_dataloader,
                description="Evaluation",
                # No point gathering the predictions if there are no metrics, otherwise we defer to
                # self.args.prediction_loss_only
                prediction_loss_only=True if compute_metrics is None else None,
                ignore_keys=ignore_keys,
            )
        finally:
            self.compute_metrics = compute_metrics
        total_batch_size = self.args.eval_batch_size * self.args.world_size
        output.metrics.update(
            speed_metrics(
                metric_key_prefix,
                start_time,
                num_samples=output.num_samples,
                num_steps=math.ceil(output.num_samples / total_batch_size),
            )
        )

        if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
            # Only the main node write the results by default
            eval_preds = self.post_process_function(eval_examples, eval_dataset, output)
            metrics = self.compute_metrics(eval_preds)

            # Prefix all keys with metric_key_prefix + '_'
            for key in list(metrics.keys()):
                if not key.startswith(f"{metric_key_prefix}_"):
                    metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)

            output.metrics.update(metrics)
        else:
            metrics = {}

        if self.args.should_log:
            # Only the main node log the results by default
            self.log(metrics)

        if self.args.tpu_metrics_debug or self.args.debug:
            # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
            xm.master_print(met.metrics_report())

        self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)
        return metrics

    def predict(
        self, predict_dataset, predict_examples, ignore_keys=None, metric_key_prefix: str = "test", **gen_kwargs
    ):
        self._gen_kwargs = gen_kwargs.copy()

        predict_dataloader = self.get_test_dataloader(predict_dataset)

        # Temporarily disable metric computation, we will do it in the loop here.
        compute_metrics = self.compute_metrics
        self.compute_metrics = None
        eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
        try:
            output = eval_loop(
                predict_dataloader,
                description="Prediction",
                # No point gathering the predictions if there are no metrics, otherwise we defer to
                # self.args.prediction_loss_only
                prediction_loss_only=True if compute_metrics is None else None,
                ignore_keys=ignore_keys,
            )
        finally:
            self.compute_metrics = compute_metrics

        if self.post_process_function is None or self.compute_metrics is None:
            return output

        predictions = self.post_process_function(predict_examples, predict_dataset, output.predictions, "predict")
        metrics = self.compute_metrics(predictions)

        # Prefix all keys with metric_key_prefix + '_'
        for key in list(metrics.keys()):
            if not key.startswith(f"{metric_key_prefix}_"):
                metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)

        return PredictionOutput(predictions=predictions.predictions, label_ids=predictions.label_ids, metrics=metrics)


text:
<button><!-- ko text: btnText -->Test<!-- /ko --></button>
<button><!-- ko text: btnText --><!-- /ko --></button>


text:
package controllers.auth

import controllers.traits.auth.LoginCtrl
import services.LoginService

class LoginController extends LoginCtrl {
  val loginService = LoginService
}