text:
class PopulateAlertClasses < ActiveRecord::Migration[5.2]
  def change
    if AlertType.any?
        AlertType.find_by(title: 'Thermostatic Control').update(class_name: 'AlertThermostaticControl')
        AlertType.find_by(title: 'Weekend gas consumption').update(class_name: 'AlertWeekendGasConsumptionShortTerm')
        AlertType.find_by(title: 'Electricity baseload too high').update(class_name: 'AlertElectricityBaseloadVersusBenchmark')
        AlertType.find_by(title: 'Holiday coming up').update(class_name: 'AlertImpendingHoliday')
        AlertType.find_by(title: 'Turn heating on/off').update(class_name: 'AlertHeatingOnOff')
        AlertType.find_by(title: 'Electricity baseload has changed').update(class_name: 'AlertChangeInElectricityBaseloadShortTerm')
        AlertType.find_by(title: 'Electricity consumption has changed').update(class_name: 'AlertChangeInDailyElectricityShortTerm')
        AlertType.find_by(title: 'Electricity out of hours usage too high').update(class_name: 'AlertOutOfHoursElectricityUsage')
        AlertType.find_by(title: 'Gas out of hours usage too high').update(class_name: 'AlertOutOfHoursGasUsage')
        AlertType.find_by(title: 'Electricity usage high').update(class_name: 'AlertElectricityAnnualVersusBenchmark')
        AlertType.find_by(title: 'Gas usage high').update(class_name: 'AlertGasAnnualVersusBenchmark')
        AlertType.find_by(title: 'Heating coming on too early in the morning').update(class_name: 'AlertHeatingComingOnTooEarly')
        AlertType.find_by(title: 'Gas consumption has changed').update(class_name: 'AlertChangeInDailyGasShortTerm')
        AlertType.find_by(title: 'Hot water efficiency').update(class_name: 'AlertHotWaterEfficiency')
    end
  end
end


text:
<action-sheet>

    <ion-title>{{ title }}</ion-title>

      <ion-list no-lines class="bp-list">

          <ion-icon>

          </ion-icon>
          {{ walletsByKey[0].walletGroupName }}

          <wallet-item-content [wallet]="wallet"></wallet-item-content>

      </ion-list>

      <ion-list no-lines class="bp-list">

          <ion-icon>

          </ion-icon>
          {{ coinbaseData.user.name }}'s Coinbase Account

          <ion-list no-lines class="bp-list">
            <button ion-item detail-none (click)="optionClicked(ac.id, true)">
              <coin-icon [coin]="ac.currency.code.toLowerCase()" [network]="livenet" item-left></coin-icon>
              <ion-label>
                {{ac.name}}
              </ion-label>
              <ion-note item-end>

{{ac.balance.amount | number:'1.2-8'}}

                  {{ ac.nativeCurrencyStr }}

              </ion-note>
            </button>
          </ion-list>

      </ion-list>

  <ng-template #noWallets>

      {{'No wallets available' | translate}}

  </ng-template>
  <ion-item-divider></ion-item-divider>
</action-sheet>

redpajama_set_name: RedPajamaGithub


text:
typedef void (*RegisterFunc)(void);
typedef char*(*NameFunc)(void);

static TList* TmpEplList;
extern int console_output;

//---------------------------------------------------------
static int Epopeia_LoadPlugin(char* FileName)
{
    HINSTANCE hdll;
    RegisterFunc RegisterType;
    NameFunc GetPluginName;
    UINT Mode;

    Mode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);

    hdll = LoadLibrary(FileName);
    if(!hdll)
    {
        char ctemp[400];
        sprintf(ctemp, "Error al cargar %s.\n", FileName);
        Epopeia_Print(ctemp);
        return -1;
    }

    RegisterType = (RegisterFunc)GetProcAddress(hdll, "Epopeia_RegisterType");
    if(!RegisterType)
    {
        Epopeia_Print("Error al intentar registrar el plugin.\n");
        return -2;
    }

    GetPluginName = (NameFunc)GetProcAddress(hdll, "Epopeia_PluginName");
    if(!GetPluginName)
    {
        Epopeia_Print("Error al intentar registrar el plugin.\n");
        return -2;
    }

    Epopeia_Print("Dando de alta plugin: ");
    Epopeia_Print(GetPluginName());
    Epopeia_Print("\n");

    SetErrorMode(Mode);

    RegisterType();

    return 0;
}

//---------------------------------------------------------
static int Epopeia_LoadPluginsFromPAK(void)
{
    int hay_ficheros = 0;

    TmpEplList = List_New(AlwaysLesser);
    hay_ficheros = pak_list_reset();

    while(hay_ficheros)
    {
        char* filename = pak_list_current_filename();
        int size = pak_list_current_size();
        char* tmpdir = getenv("TMP");
        char* tmpname, *tmpname2;
        FILE* fp;
        PFILE* pf;
        int count;
        void* buffer;

        if(strlen(filename) > 4 &&
           filename[strlen(filename)-1] == 'l' &&
           filename[strlen(filename)-2] == 'p' &&
           filename[strlen(filename)-3] == 'e' &&
           filename[strlen(filename)-4] == '.')
        {
            if(tmpdir == NULL)
                tmpdir = "c:\\";

            buffer = malloc(size);
            if(buffer == NULL)
            {
                return 1;
            }

            // Leer EPL
            pf = pak_open(filename, "rb");
            if(pf == NULL)
            {
                return 2;
            }

            count = pak_read(buffer, 1, size, pf);
            if(count != size)
            {
                pak_close(pf);
                free(buffer);
                return 3;
            }
            pak_close(pf);

            // Escribir EPL
            tmpname = _tempnam(tmpdir, "epl");
            tmpname2= (char*)malloc(strlen(tmpname)+4+1);
            strcpy(tmpname2, tmpname);
            strcat(tmpname2, ".epl");
            free(tmpname);
            tmpname=tmpname2;
            tmpname2=NULL;
            fp = fopen(tmpname, "wb");
            if(fp == NULL)
            {
                free(buffer);
                free(tmpname);
                return 4;
            }

            count = fwrite(buffer, 1, size, fp);
            if(count != size)
            {
                free(tmpname);
                fclose(fp);
                pak_close(pf);
                free(buffer);
                return 5;
            }
            fclose(fp);
            free(buffer);

            Epopeia_LoadPlugin(tmpname);
            //rename(tmpname, "epl99999.epl");
            //remove("epo99999.epl");

            // Alistar para librar y borrar en la descarga
            List_Insert(TmpEplList, tmpname);
//            unlink(tmpname);
//            free(tmpname);
        }
        hay_ficheros = pak_list_next();
    }
    return 0;
}
//---------------------------------------------------------
static int Epopeia_UnLoadPluginsFromPAK(void)
{
    List_Reset(TmpEplList);
    while(!List_EOF(TmpEplList))
    {
        char* filename;

        filename= List_Current(TmpEplList);
        FreeLibrary(GetModuleHandle(filename));
        remove(filename);
        free(filename);

        List_Next(TmpEplList);
    }
    List_Delete(TmpEplList);
    return 0;
}
//---------------------------------------------------------
static int Epopeia_LoadPluginsFromDirectory(void)
{
    WIN32_FIND_DATA FileData;
    HANDLE hSearch;
    char szDirPath[] = "plugin\\";
    char szNewPath[MAX_PATH];

    hSearch = FindFirstFile("plugin\\*.epl", &FileData);
    if (hSearch == INVALID_HANDLE_VALUE)
        return 0;

    for(;;)
    {
	int error;

        lstrcpy(szNewPath, szDirPath);
        lstrcat(szNewPath, FileData.cFileName);

        error = Epopeia_LoadPlugin(szNewPath);
        if(error)
            return error;

        if (!FindNextFile(hSearch, &FileData))
        {
            if (GetLastError() == ERROR_NO_MORE_FILES)
            {
                FindClose(hSearch);
                return 0;
            }
            else
            {
                FindClose(hSearch);
                return 1;
            }
        }
    }

}
//---------------------------------------------------------
EPOPEIA_API int Epopeia_LoadPlugins(void)
{
    int error = 0;
    error = Epopeia_LoadPluginsFromPAK();
    if(!error)
        error = Epopeia_LoadPluginsFromDirectory();
    return error;
}
//---------------------------------------------------------
EPOPEIA_API int Epopeia_UnLoadPlugins(void)
{
    int error;
    error = Epopeia_UnLoadPluginsFromPAK();
    return error;
}

#endif //WIN32


text:
<?php

namespace Drupal\field\Plugin\migrate\source\d7;

use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;

/**
 * Drupal 7 field source from database.
 *
 * @MigrateSource(
 *   id = "d7_field"
 * )
 */
class Field extends DrupalSqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('field_config', 'fc')
      ->distinct()
      ->fields('fc')
      ->fields('fci', array('entity_type'))
      ->condition('fc.active', 1)
      ->condition('fc.deleted', 0)
      ->condition('fc.storage_active', 1);
    $query->join('field_config_instance', 'fci', 'fc.id = fci.field_id');

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return array(
      'field_name' => $this->t('The name of this field.'),
      'type' => $this->t('The type of this field.'),
      'module' => $this->t('The module that implements the field type.'),
      'storage' => $this->t('The field storage.'),
      'locked' => $this->t('Locked'),
      'cardinality' => $this->t('Cardinality'),
      'translatable' => $this->t('Translatable'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row, $keep = TRUE) {
    foreach (unserialize($row->getSourceProperty('data')) as $key => $value) {
      $row->setSourceProperty($key, $value);
    }
    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return array(
      'field_name' => array(
        'type' => 'string',
        'alias' => 'fc',
      ),
      'entity_type' => array(
        'type' => 'string',
        'alias' => 'fci',
      ),
    );
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Mus. nac. B. Aires, Ser. 3 13: 445 (1910)

#### Original name
Coniothecium argentinense Speg.

### Remarks
null


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M13.35,17.825H1.675V6.15H13.35V10.475H22.525V13.5H13.35Z"/>
</vector>


text:
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]

CORS is a node.js package for providing a [Connect](http://www.senchalabs.org/connect/)/[Express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options.

**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)**

* [Installation](#installation)
* [Usage](#usage)
  * [Simple Usage](#simple-usage-enable-all-cors-requests)
  * [Enable CORS for a Single Route](#enable-cors-for-a-single-route)
  * [Configuring CORS](#configuring-cors)
  * [Configuring CORS w/ Dynamic Origin](#configuring-cors-w-dynamic-origin)
  * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)
  * [Configuring CORS Asynchronously](#configuring-cors-asynchronously)
* [Configuration Options](#configuration-options)
* [Demo](#demo)
* [License](#license)
* [Author](#author)

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```sh
$ npm install cors
```

## Usage

### Simple Usage (Enable *All* CORS Requests)

```javascript
var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
```

### Enable CORS for a Single Route

```javascript
var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
```

### Configuring CORS

```javascript
var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
```

### Configuring CORS w/ Dynamic Origin

This module supports validating the origin dynamically using a function provided
to the `origin` option. This function will be passed a string that is the origin
(or `undefined` if the request has no origin), and a `callback` with the signature
`callback(error, origin)`.

The `origin` argument to the callback can be any value allowed for the `origin`
option of the middleware, except a function. See the
[configuration options](#configuration-options) section for more information on all
the possible value types.

This function is designed to allow the dynamic loading of allowed origin(s) from
a backing datasource, like a database.

```javascript
var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: function (origin, callback) {
    // db.loadOrigins is an example call to load
    // a list of origins from a backing database
    db.loadOrigins(function (error, origins) {
      callback(error, origins)
    })
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
```

### Enabling CORS Pre-Flight

Certain CORS requests are considered 'complex' and require an initial
`OPTIONS` request (called the "pre-flight request"). An example of a
'complex' CORS request is one that uses an HTTP verb other than
GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable
pre-flighting, you must add a new OPTIONS handler for the route you want
to support:

```javascript
var express = require('express')
var cors = require('cors')
var app = express()

app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
```

You can also enable pre-flight across-the-board like so:

```javascript
app.options('*', cors()) // include before other routes
```

NOTE: When using this middleware as an application level middleware (for
example, `app.use(cors())`), pre-flight requests are already handled for all
routes.

### Configuring CORS Asynchronously

```javascript
var express = require('express')
var cors = require('cors')
var app = express()

var allowlist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (allowlist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  } else {
    corsOptions = { origin: false } // disable CORS for this request
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
}

app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
```

## Configuration Options

* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values:
  - `Boolean` - set `origin` to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS.
  - `String` - set `origin` to a specific origin. For example if you set it to `"http://example.com"` only requests from "http://example.com" will be allowed.
  - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com".
  - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com".
  - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as `callback(err, origin)`, where `origin` is a non-function value of the `origin` option) as the second.
* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`).
* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header.
* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed.
* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.
* `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted.
* `preflightContinue`: Pass the CORS preflight response to the next handler.
* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`.

The default configuration is the equivalent of:

```json
{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}
```

For details on the effect of each CORS header, read [this](http://www.html5rocks.com/en/tutorials/cors/) article on HTML5 Rocks.

## Demo

A demo that illustrates CORS working (and not working) using React is available here: [https://node-cors-client.netlify.com](https://node-cors-client.netlify.com)

Code for that demo can be found here:

* Client: [https://github.com/troygoode/node-cors-client](https://github.com/troygoode/node-cors-client)
* Server: [https://github.com/troygoode/node-cors-server](https://github.com/troygoode/node-cors-server)

## License

[MIT License](http://www.opensource.org/licenses/mit-license.php)

## Author

[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))

[coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg
[coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master
[downloads-image]: https://img.shields.io/npm/dm/cors.svg
[downloads-url]: https://npmjs.org/package/cors
[npm-image]: https://img.shields.io/npm/v/cors.svg
[npm-url]: https://npmjs.org/package/cors
[travis-image]: https://img.shields.io/travis/expressjs/cors/master.svg
[travis-url]: https://travis-ci.org/expressjs/cors


text:
function(definitions, model) {
    var templateDataModel = { data: {}, valid: true , errors: []},
        viewInstance = null,
        count = 0,
        list = null;

    function exctractValue(attrName, id, view) {
        return definitions.extractEnumValues(attrName, id, view, model.external);
    }

    function flattenArray(array) {
        var result = [],
            count = array.length;

        while(count--) {
            result = result.concat(array[count]);
        }

        return result;
    }

    // === Title + comment  section (3.1) ====
    templateDataModel.data.title = model.name;

    // === Load balancing section (3.2) ====

    try {
        viewInstance = model.data.execution[0];
        templateDataModel.data.load_balance = {
            method      : exctractValue('LoadBalance', 'loadbalance.method',     viewInstance),
            diagnostics : exctractValue('LoadBalance', 'loadbalance.diagnostics', viewInstance)
        };
    } catch(error) {
        templateDataModel.errors.push("Load balancing not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    // === Load curve section (3.3) ====
    // TODO / FIXME

    // === Materials section (3.4) ====
    try {
        templateDataModel.data.materials = [];
        list = model.data.material;
        count = list.length;
        while(count--) {
            templateDataModel.data.materials.push({
                rho      : list[count].Material['material.rho'],
                cp       : list[count].Material['material.cp'],
                cv       : list[count].Material['material.cv'],
                k        : list[count].Material['material.k'],
                mu       : list[count].Material['material.mu'],
                tref     : list[count].Material['material.tref'],
                // FIXME MISSING GAMMA
                beta     : list[count].Material['material.beta'],
                rigid    : exctractValue('Material', 'material.rigid', list[count]),
                vel      : list[count].Material['material.vel'],
                blockids : flattenArray(exctractValue('Material', 'block.tags', list[count])),
                type     : exctractValue('Material', 'material.type', list[count]),
                name     : list[count].name
            });
        }
    } catch(error) {
        templateDataModel.errors.push("Material section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    // === Execution control section (3.5) ===
    try {
        templateDataModel.data.exe_control = {
            nstep : model.data.execution[0].ExecutionControl['executioncontrol.nstep']
        };
    } catch(error) {
        templateDataModel.errors.push("Execution control section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    // === Output section (3.6) ===
    try {
        viewInstance = model.data.output[0];
        templateDataModel.data.output = {
            dump       : model.data.output[0].Output['dump.ndump'],
            plti       : model.data.output[0].Output['plot.nplot'],
            prtlev     : exctractValue('Output', 'ascii.prtlev', viewInstance),
            prti       : model.data.output[0].Output['ascii.prti'], // Only if previous is Verbose
            thti       : model.data.output[0].Output['timehistory.nstep'],
            ttyi       : model.data.output[0].Output['velocityminmax.nstep'],
            pltype     : exctractValue('Plot', 'plot.pltype', viewInstance),
            filetype   : exctractValue('Plot', 'plot.filetype', viewInstance),
            histvar    : { TimeHistoryElem: [], TimeHistoryNode: [], TimeHistorySide: [] },
            plotvar    : {
                elem: exctractValue('Plot', 'plot.evariables', viewInstance),
                node: exctractValue('Plot', 'plot.nvariables', viewInstance),
                side: []
            }
        };
    } catch(error) {
        templateDataModel.errors.push("Output section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    // === histvar section (3.6.3) ===
    try {
        list = model.data.histvar;
        count = list ? list.length : 0;
        while(count--) {
            var activeAttr = definitions.extractOrSelection(list[count])[0];

            templateDataModel.data.output.histvar[activeAttr].push({
                ids: flattenArray(exctractValue(activeAttr, 'timehistory.tags', list[count])),
                vars: [].concat(exctractValue(activeAttr, 'timehistory.variables', list[count]))
            });
        }
    } catch(error) {
        templateDataModel.errors.push("Time History (histvar) section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    // === plotvar section (3.6.4) ===
    if(model.data.plotvar) { // Maybe no side plot
        try {
            list = model.data.plotvar;
            count = list.length;
            while(count--) {
                console.log('++++++++++++++');
                console.log(list[count].PlotSide);
                console.log('++++++++++++++');
                templateDataModel.data.output.plotvar.side.push({
                    ids:  exctractValue('PlotSide', 'face.tags',       list[count]),
                    vars: exctractValue('PlotSide', 'plot.svariables', list[count])
                });
            }
        } catch(error) {
            templateDataModel.errors.push("Plot Variable (plotvar) section not valid");
            templateDataModel.errors.push("=> " + error.message);
            templateDataModel.valid = false;
    }
    }

    // === Time Step and Time Integration section (3.7 + 4.11) ====

    try {
        templateDataModel.data.time = {
            nsteps  : model.data.time[0].Time['time.nstep'],
            deltat  : model.data.time[0].Time['time.deltat'],
            term    : model.data.time[0].Time['time.term'],
            type    : exctractValue('TimeIntegration', 'timeintegration.type', model.data.time[0]),
            CFLinit : model.data.time[0].TimeIntegration['timeintegration.CFLinit'],
            CFLmax  : model.data.time[0].TimeIntegration['timeintegration.CFLmax'],
            dtmax   : model.data.time[0].TimeIntegration['timeintegration.dtmax'],
            dtscale : model.data.time[0].TimeIntegration['timeintegration.dtscale'],
            thetaa  : model.data.time[0].TimeIntegration['timeintegration.thetaA'],
            thetak  : model.data.time[0].TimeIntegration['timeintegration.thetaK'],
            thetaf  : model.data.time[0].TimeIntegration['timeintegration.thetaF']
        };
    } catch(error) {
        templateDataModel.errors.push("Time Step and Time integration section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== Turbulence Statistics section (3.8) ====

    try {
        templateDataModel.data.plotstatvar = {
            elem         : [].concat(exctractValue('TurbulenceStatistics', 'turbulencestatistics.evariables', model.data.output[0])),
            node         : [].concat(exctractValue('TurbulenceStatistics', 'turbulencestatistics.nvariables', model.data.output[0])),
            side         : [],
            starttime    : model.data.output[0].TurbulenceStatistics['turbulencestatistics.starttime'],
            endtime      : model.data.output[0].TurbulenceStatistics['turbulencestatistics.endtime'],
            plotwinsize  : model.data.output[0].TurbulenceStatistics['turbulencestatistics.plotwinsize']
        };

        if(model.data.plotstatvar) {
            list = model.data.plotstatvar;
            count = list.length;
            while(count--) {
                templateDataModel.data.plotstatvar.side.push({
                    ids:  exctractValue('TurbulenceStatisticsSide', 'face.tags', list[count]),
                    vars: exctractValue('TurbulenceStatisticsSide', 'turbulencestatistics.svariables', list[count])
                });
            }
        }
    } catch(error) {
        templateDataModel.errors.push("Turbulence Statistics section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== Cell-centered incompressible Navier-Stokes section (4) ====

    //- ==== Energy section (4.2) ====

    try {
        templateDataModel.data.energy = {
            form : exctractValue('Energy', 'energy.form', model.data.solvers[0])
        };
    } catch(error) {
        templateDataModel.errors.push("Energy section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== Hydrostat section (4.3) ====

    try {
        templateDataModel.data.hstat = [
            // { ids: [1,4,7,9],   curveId: 1, amplitude: 5.2354 },  // Fake data to test output
            // { ids: [2,3,5,6,8], curveId: 2, amplitude: 0.9235 }   // Fake data to test output
        ];
    } catch(error) {
        templateDataModel.errors.push("Hydrostat section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }
    // FIXME add nodeset => { ids: [], curveId: 34, amplitude: 2.567 }

    //- ==== Initial conditions section (4.4) ====

    try {
        templateDataModel.data.initial = {
            vel          : model.data.initial[0].Initial['initial.vel'],
            tke          : model.data.initial[0].Initial['initial.tke'],
            eps          : model.data.initial[0].Initial['initial.eps'],
            omega        : model.data.initial[0].Initial['initial.omega'],
            turbnu       : model.data.initial[0].Initial['initial.turbnu'],
            temperature  : model.data.initial[0].Initial['initial.temperature'],
            enthalpy     : model.data.initial[0].Initial['initial.enthalpy'],
            init_energy  : model.data.initial[0].Initial['initial.init_energy']
        };
    } catch(error) {
        templateDataModel.errors.push("Initial conditions section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== Forces section (4.5) ====

    try {
        templateDataModel.data.forces = {
            body_force: [
                // { force: [ 1.2, 0.2, 5.6], curveId: 34, id: 1, comment: "fake data"},     // Fake data to test output
                // { force: [12.3, 0.2, 5.6], curveId: 34, comment: "fake data" },           // Fake data to test output
                // { force: [23.4, 0.2, 5.6], comment: "fake data" }                         // Fake data to test output
            ],
            boussinesqforce: [
                // { gravity: [ 1.2, 0.2, 5.6], curveId: 33, id: 2, comment: "fake data"},   // Fake data to test output
                // { gravity: [12.3, 0.2, 5.6], curveId: 33, comment: "fake data" },         // Fake data to test output
                // { gravity: [23.4, 0.2, 5.6], comment: "fake data" }                       // Fake data to test output
            ],
            porous_drag: [
                // { amplitude: 1.23, curveId: 33, id: 2, comment: "fake data"},             // Fake data to test output
                // { amplitude: 2.34, curveId: 33, comment: "fake data" },                   // Fake data to test output
                // { amplitude: 3.45, comment: "fake data" }                                 // Fake data to test output
            ]
        };
        // FIXME: Manage OR on "forces" view [ BodyForce, BoussinesqForce, PorousDragForce ].
    } catch(error) {
        templateDataModel.errors.push("Forces section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== Boundary Conditions section (4.6) ====

    try {
        templateDataModel.data.boundary_conditions = {
             //  inside a group { ids: [2], curveId: -1, amplitude: 3.665, comment: "fake data"}
        };
        // FIXME: Manage OR on "boundary" view
        // [ "ScalarDirichlet", "VelocityDirichlet", "SymmetryVelocity",
        //   "HeatFlux", "PassiveOutflow", "PressureOutflow", "User-DefinedVelocity" ].
        list = model.data.boundary;
        count = list ? list.length : 0;
        while(count--) {
            var activeAttr = definitions.extractOrSelection(list[count])[0];

            if(["ScalarDirichlet", "VelocityDirichlet", "SymmetryVelocity", "HeatFlux"].indexOf(activeAttr) !== -1) {
                var groupName = definitions.definition.definitions[activeAttr].value;

                if(groupName === undefined) {
                    console.log("No groupName => scalar");
                    console.log(activeAttr);
                    console.log(list[count]);
                    groupName = exctractValue(activeAttr, 'scalar', list[count]);
                }

                if(templateDataModel.data.boundary_conditions[groupName] === undefined) {
                    templateDataModel.data.boundary_conditions[groupName] = [];
                }

                templateDataModel.data.boundary_conditions[groupName].push({
                    comment: list[count].name,
                    ids: flattenArray(exctractValue(activeAttr, 'face.tags', list[count])),
                    curveId: list[count][activeAttr]['name'],
                    amplitude: list[count][activeAttr]['amplitude']
                });

            } else if(["PassiveOutflow", "PressureOutflow", "User-DefinedVelocity"].indexOf(activeAttr) !== -1) {
                var groupName = definitions.definition.definitions[activeAttr].value;

                if(templateDataModel.data.boundary_conditions[groupName] === undefined) {
                    templateDataModel.data.boundary_conditions[groupName] = [];
                }

                templateDataModel.data.boundary_conditions[groupName].push({
                    comment: list[count].name,
                    ids: flattenArray(exctractValue(activeAttr, 'face.tags', list[count]))
                });
            }
        }

        // Add heatflux too
    } catch(error) {
        templateDataModel.errors.push("Boundary Conditions section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== User-defined Velocity boundary conditions section (4.7)
    //- NOT SUPPORTED YET

    //- ==== Heat sources section (4.8) ===

    try {
        templateDataModel.data.heat_sources = [
            // { amplitude: 1.23, curveId: 33, id: 2, comment: "fake data"},             // Fake data to test output
            // { amplitude: 2.34, curveId: 33, comment: "fake data" },                   // Fake data to test output
            // { amplitude: 3.45, comment: "fake data" }                                 // Fake data to test output
        ];
        // FIXME
    } catch(error) {
        templateDataModel.errors.push("Heat sources section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== Pressure, Momentum and Transport Solvers section (4.9) ===

    try {
        templateDataModel.data.ppesolver = {
            trunc_factor        : model.data.solvers[0].HypreBoomerAMG['hypreboomeramg.trunc_factor'],
            pmax_elements       : model.data.solvers[0].HypreBoomerAMG['hypreboomeramg.pmax_elements'],
            agg_num_levels      : model.data.solvers[0].HypreBoomerAMG['hypreboomeramg.agg_num_levels'],
            agg_num_paths       : model.data.solvers[0].HypreBoomerAMG['hypreboomeramg.agg_num_paths'],
            strong_threshold    : model.data.solvers[0].HypreBoomerAMG['hypreboomeramg.strong_threshold'],
            max_rowsum          : model.data.solvers[0].HypreBoomerAMG['hypreboomeramg.max_rowsum'],
            smoother            : exctractValue('MLAMG', 'mlamg.smoother', model.data.solvers[0]),
            pre_smooth          : model.data.solvers[0].Pressure['pressuresolver.pre_smooth'],
            post_smooth         : model.data.solvers[0].Pressure['pressuresolver.post_smooth'],
            levels              : model.data.solvers[0].Pressure['pressuresolver.levels'],
            itmax               : model.data.solvers[0].Pressure['pressuresolver.itmax'],
            itchk               : model.data.solvers[0].Pressure['pressuresolver.itchk'],
            eps                 : model.data.solvers[0].Pressure['pressuresolver.eps'],
            zeropivot           : model.data.solvers[0].Pressure['pressuresolver.pivot'],

            type                : exctractValue( 'Pressure', 'pressuresolver.type',                     model.data.solvers[0]),
            amgpc               : exctractValue( 'Pressure', 'pressuresolver.amgpc',                    model.data.solvers[0]),
            hypre_type          : exctractValue( 'Pressure', 'pressuresolver.hypre_type',               model.data.solvers[0]),
            diagnostics         : exctractValue( 'Pressure', 'pressuresolver.diagnostics',              model.data.solvers[0]),
            convergence         : exctractValue( 'Pressure', 'pressuresolver.convergence',              model.data.solvers[0]),
            cycle               : exctractValue( 'Pressure', 'pressuresolver.cycle',                    model.data.solvers[0]),
            solver              : exctractValue( 'Pressure', 'pressuresolver.solver',                   model.data.solvers[0]),
            hypre_coarsen_type  : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.hypre_coarsen_type', model.data.solvers[0]),
            hypre_smoother      : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.hypre_smoother',     model.data.solvers[0]),
            hypre_smoother_dn   : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.hypre_smoother_dn',  model.data.solvers[0]),
            hypre_smoother_up   : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.hypre_smoother_up',  model.data.solvers[0]),
            hypre_smoother_co   : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.hypre_smoother_co',  model.data.solvers[0]),
            interp_type         : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.interp_type',        model.data.solvers[0]),
            hypre_nodal         : exctractValue( 'HypreBoomerAMG', 'hypreboomeramg.hypre_nodal',        model.data.solvers[0])
        };

        templateDataModel.data.momentumsolver = {
            restart       : model.data.solvers[0].Momentum['momentumsolver.restart'],
            itmax         : model.data.solvers[0].Momentum['momentumsolver.itmax'],
            itchk         : model.data.solvers[0].Momentum['momentumsolver.itchk'],
            eps           : model.data.solvers[0].Momentum['momentumsolver.eps'],

            type          : exctractValue('Momentum', 'momentumsolver.type',        model.data.solvers[0]),
            diagnostics   : exctractValue('Momentum', 'momentumsolver.diagnostics', model.data.solvers[0]),
            convergence   : exctractValue('Momentum', 'momentumsolver.convergence', model.data.solvers[0])
        };

        templateDataModel.data.transportsolver = {
            restart       : model.data.solvers[0].TransportSolver['transportsolver.restart'],
            itmax         : model.data.solvers[0].TransportSolver['transportsolver.itmax'],
            itchk         : model.data.solvers[0].TransportSolver['transportsolver.itchk'],
            eps           : model.data.solvers[0].TransportSolver['transportsolver.eps'],

            type          : exctractValue('TransportSolver', 'transportsolver.type',        model.data.solvers[0]),
            diagnostics   : exctractValue('TransportSolver', 'transportsolver.diagnostics', model.data.solvers[0]),
            convergence   : exctractValue('TransportSolver', 'transportsolver.convergence', model.data.solvers[0])
        };
    } catch(error) {
        templateDataModel.errors.push("Pressure, Momentum and Transport Solvers section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== solution_method section (4.10) ====

    try {
        templateDataModel.data.solution = {
            itmax            : model.data.solution[0].SolutionMethod['solutionmethod.nitmax'],
            nvec             : model.data.solution[0].SolutionMethod['solutionmethod.nvec'],
            eps              : model.data.solution[0].SolutionMethod['solutionmethod.eps'],
            eps_dist         : model.data.solution[0].SolutionMethod['solutionmethod.eps_dist'],
            eps_p0           : model.data.solution[0].SolutionMethod['solutionmethod.eps_p0'],
            drop_tol         : model.data.solution[0].SolutionMethod['solutionmethod.drop_tol'],

            strategy         : exctractValue('SolutionMethod', 'solutionmethod.strategy',         model.data.solution[0]),
            error_norm       : exctractValue('SolutionMethod', 'solutionmethod.error_norm',       model.data.solution[0]),
            timestep_control : exctractValue('SolutionMethod', 'solutionmethod.timestep_control', model.data.solution[0]),
            convergence      : exctractValue('SolutionMethod', 'solutionmethod.convergence',      model.data.solution[0]),
            subcycle         : exctractValue('SolutionMethod', 'solutionmethod.subcycle',         model.data.solution[0]),
            diagnostics      : exctractValue('SolutionMethod', 'solutionmethod.diagnostics',      model.data.solution[0])
        };
    } catch(error) {
        templateDataModel.errors.push("Solution method section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    //- ==== time_integration section (4.11) ====

    // Extracted previously in Time (3.7)

    //- ==== Turbulence models section (4.12) ====

    try {
        var modelType = definitions.extractOrSelection(model.data.turbulence[0])[0];

        templateDataModel.data.turbulence = {
            model             : definitions.definition.definitions[modelType].value,
            timescale_limiter : exctractValue('RNG_ke', 'rgn_ke.timescale_limiter', model.data.turbulence[0]),
            c_s               : model.data.turbulence[0].Smagorinsky['smagorinsky.c_s'],
            prandtl_s         : model.data.turbulence[0].Smagorinsky['smagorinsky.prandtl'],
            schmidt_s         : model.data.turbulence[0].Smagorinsky['smagorinsky.schmidt'],
            c_w               : model.data.turbulence[0].WALE['wale.c_w'],
            prandtl_w         : model.data.turbulence[0].WALE['wale.prandtl'],
            schmidt_w         : model.data.turbulence[0].WALE['wale.schmidt']
        };
    } catch(error) {
        templateDataModel.errors.push("Turbulence models section not valid");
        templateDataModel.errors.push("=> " + error.message);
        templateDataModel.valid = false;
    }

    console.log(model);
    console.log(templateDataModel);

    return templateDataModel;
}


text:
namespace VRTK.UnityEventHelper
{
    using UnityEngine;
    using UnityEngine.Events;

    [RequireComponent(typeof(VRTK_ControllerActions))]
    public class VRTK_ControllerActions_UnityEvents : MonoBehaviour
    {
        private VRTK_ControllerActions ca;

        [System.Serializable]
        public class UnityObjectEvent : UnityEvent<object, ControllerActionsEventArgs> { };

        /// <summary>
        /// Emits the ControllerModelVisible class event.
        /// </summary>
        public UnityObjectEvent OnControllerModelVisible;
        /// <summary>
        /// Emits the ControllerModelInvisible class event.
        /// </summary>
        public UnityObjectEvent OnControllerModelInvisible;

        private void SetControllerAction()
        {
            if (ca == null)
            {
                ca = GetComponent<VRTK_ControllerActions>();
            }
        }

        private void OnEnable()
        {
            SetControllerAction();
            if (ca == null)
            {
                Debug.LogError("The VRTK_ControllerActions_UnityEvents script requires to be attached to a GameObject that contains a VRTK_ControllerActions script");
                return;
            }

            ca.ControllerModelVisible += ControllerModelVisible;
            ca.ControllerModelInvisible += ControllerModelInvisible;
        }

        private void ControllerModelVisible(object o, ControllerActionsEventArgs e)
        {
            OnControllerModelVisible.Invoke(o, e);
        }

        private void ControllerModelInvisible(object o, ControllerActionsEventArgs e)
        {
            OnControllerModelInvisible.Invoke(o, e);
        }

        private void OnDisable()
        {
            if (ca == null)
            {
                return;
            }

            ca.ControllerModelVisible -= ControllerModelVisible;
            ca.ControllerModelInvisible -= ControllerModelInvisible;
        }
    }
}


text:
${scheduleTout.message}

    ${scheduleTout.ctaLabel}

<sly data-sly-call="${template.placeholder @ isEmpty=!hasContent, classAppend='author-msg'}"></sly>


text:
module SnapshotAssociation
  class Snapshot
    attr_reader :base_klass, :snapshot_klass, :old_column_mapping
    def initialize(scope, snapshot_klass, column_mapping={})
      @base_klass = scope
      @snapshot_klass = snapshot_klass
      @old_column_mapping = column_mapping
    end

    def register_callback(callback_name: nil)
      @base_klass.class_exec(self) do |scope|
        method_name = "snapshot_#{scope.snapshot_klass.to_s.downcase}_fields".to_sym
        define_method method_name do
          SnapshotAssociation::Snapshot.snapshot_fields(self, scope.snapshot_klass, scope.old_column_mapping)
        end

        callback_name = :before_create if callback_name.nil?
        raise 'Must define a valid ActiveRecord::Callback on a snapshot association' unless ActiveRecord::Callbacks::CALLBACKS.include? callback_name.to_sym

        callback_type = callback_name.to_s.split('_')[1]
        raise 'Snapshot associations only valid on create or save callbacks.' unless ['save', 'create'].include? callback_type

        send(callback_name, method_name)
      end
    end

    def self.snapshot_fields(scope, snapshot_klass, old_column_mapping={})
      shared_columns = shared_columns(scope.class, snapshot_klass)
      shared_columns.reject!{ |name| old_column_mapping.keys.include? "#{snapshot_klass.to_s.downcase}_#{name}".to_sym }
      association_name = snapshot_klass.to_s.downcase
      old_column_mapping.values.each { |v| shared_columns.delete(v) }
      write_columns(scope, shared_columns, old_column_mapping, association_name)
    end

    def self.shared_columns(base_klass, snapshot_klass)
      prefix = "#{snapshot_klass.to_s.downcase}_"
      base_klass_columns = base_klass.columns.map(&:name)
      snapshot_klass_columns = snapshot_klass.columns.map{ |name| "#{prefix}#{name.name}" }
      cols = base_klass_columns & snapshot_klass_columns
    end

    def shared_columns(base_klass, snapshot_klass)
      SnapshotAssociation::Snapshot.shared_columns(base_klass, snapshot_klass)
    end

    def self.write_columns(scope, shared_columns, old_column_mapping, association_name)
      shared_columns.each do |name|
        scope.write_attribute(name, scope.send(association_name).send(name.sub("#{association_name}_", "")))
      end

      base_cols = scope.class.columns.map(&:name).grep(Regexp.new "#{association_name}_")
      old_column_mapping.each do |snapshot_klass_col, base_class_col|
        scope.write_attribute(base_class_col, scope.send(association_name).send(snapshot_klass_col)) if base_cols.include? base_class_col
      end
    end
  end
end


text:
#ifndef SkFontMgr_android_parser_DEFINED
#define SkFontMgr_android_parser_DEFINED

#include "SkString.h"
#include "SkTDArray.h"

#include <climits>
#include <limits>

/** \class SkLanguage

    The SkLanguage class represents a human written language, and is used by
    text draw operations to determine which glyph to draw when drawing
    characters with variants (ie Han-derived characters).
*/
class SkLanguage {
public:
    SkLanguage() { }
    SkLanguage(const SkString& tag) : fTag(tag) { }
    SkLanguage(const char* tag) : fTag(tag) { }
    SkLanguage(const char* tag, size_t len) : fTag(tag, len) { }
    SkLanguage(const SkLanguage& b) : fTag(b.fTag) { }

    /** Gets a BCP 47 language identifier for this SkLanguage.
        @return a BCP 47 language identifier representing this language
    */
    const SkString& getTag() const { return fTag; }

    /** Performs BCP 47 fallback to return an SkLanguage one step more general.
        @return an SkLanguage one step more general
    */
    SkLanguage getParent() const;

    bool operator==(const SkLanguage& b) const {
        return fTag == b.fTag;
    }
    bool operator!=(const SkLanguage& b) const {
        return fTag != b.fTag;
    }
    SkLanguage& operator=(const SkLanguage& b) {
        fTag = b.fTag;
        return *this;
    }

private:
    //! BCP 47 language identifier
    SkString fTag;
};

enum FontVariants {
   kDefault_FontVariant = 0x01,
   kCompact_FontVariant = 0x02,
   kElegant_FontVariant = 0x04,
   kLast_FontVariant = kElegant_FontVariant,
};
typedef uint32_t FontVariant;

// Must remain trivially movable (can be memmoved).
struct FontFileInfo {
    FontFileInfo() : fIndex(0), fWeight(0), fStyle(Style::kAuto) { }

    SkString fFileName;
    int fIndex;
    int fWeight;
    enum class Style { kAuto, kNormal, kItalic } fStyle;
    struct Axis {
        Axis() : fTag(SkSetFourByteTag('\0','\0','\0','\0')), fValue(0) { }
        SkFourByteTag fTag;
        SkFixed fValue;
    };
    SkTArray<Axis, true> fAxes;
};

/**
 * A font family provides one or more names for a collection of fonts, each of
 * which has a different style (normal, italic) or weight (thin, light, bold,
 * etc).
 * Some fonts may occur in compact variants for use in the user interface.
 * Android distinguishes "fallback" fonts to support non-ASCII character sets.
 */
struct FontFamily {
    FontFamily(const SkString& basePath, bool isFallbackFont)
        : fVariant(kDefault_FontVariant)
        , fOrder(-1)
        , fIsFallbackFont(isFallbackFont)
        , fBasePath(basePath)
    { }

    SkTArray<SkString, true> fNames;
    SkTArray<FontFileInfo, true> fFonts;
    SkLanguage fLanguage;
    FontVariant fVariant;
    int fOrder; // internal to the parser, not useful to users.
    bool fIsFallbackFont;
    const SkString fBasePath;
};

namespace SkFontMgr_Android_Parser {

/** Parses system font configuration files and appends result to fontFamilies. */
void GetSystemFontFamilies(SkTDArray<FontFamily*>& fontFamilies);

/** Parses font configuration files and appends result to fontFamilies. */
void GetCustomFontFamilies(SkTDArray<FontFamily*>& fontFamilies,
                           const SkString& basePath,
                           const char* fontsXml,
                           const char* fallbackFontsXml,
                           const char* langFallbackFontsDir = NULL);

} // SkFontMgr_Android_Parser namespace

/** Parses a null terminated string into an integer type, checking for overflow.
 *  http://www.w3.org/TR/html-markup/datatypes.html#common.data.integer.non-negative-def
 *
 *  If the string cannot be parsed into 'value', returns false and does not change 'value'.
 */
template <typename T> static bool parse_non_negative_integer(const char* s, T* value) {
    SK_COMPILE_ASSERT(std::numeric_limits<T>::is_integer, T_must_be_integer);

    if (*s == '\0') {
        return false;
    }

    const T nMax = std::numeric_limits<T>::max() / 10;
    const T dMax = std::numeric_limits<T>::max() - (nMax * 10);
    T n = 0;
    for (; *s; ++s) {
        // Check if digit
        if (*s < '0' || '9' < *s) {
            return false;
        }
        T d = *s - '0';
        // Check for overflow
        if (n > nMax || (n == nMax && d > dMax)) {
            return false;
        }
        n = (n * 10) + d;
    }
    *value = n;
    return true;
}

/** Parses a null terminated string into a signed fixed point value with bias N.
 *
 *  Like http://www.w3.org/TR/html-markup/datatypes.html#common.data.float-def ,
 *  but may start with '.' and does not support 'e'. '-?((:digit:+(.:digit:+)?)|(.:digit:+))'
 *
 *  Checks for overflow.
 *  Low bit rounding is not defined (is currently truncate).
 *  Bias (N) required to allow for the sign bit and 4 bits of integer.
 *
 *  If the string cannot be parsed into 'value', returns false and does not change 'value'.
 */
template <int N, typename T> static bool parse_fixed(const char* s, T* value) {
    SK_COMPILE_ASSERT(std::numeric_limits<T>::is_integer, T_must_be_integer);
    SK_COMPILE_ASSERT(std::numeric_limits<T>::is_signed, T_must_be_signed);
    SK_COMPILE_ASSERT(sizeof(T) * CHAR_BIT - N >= 5, N_must_leave_four_bits_plus_sign);

    bool negate = false;
    if (*s == '-') {
        ++s;
        negate = true;
    }
    if (*s == '\0') {
        return false;
    }

    const T nMax = (std::numeric_limits<T>::max() >> N) / 10;
    const T dMax = (std::numeric_limits<T>::max() >> N) - (nMax * 10);
    T n = 0;
    T frac = 0;
    for (; *s; ++s) {
        // Check if digit
        if (*s < '0' || '9' < *s) {
            // If it wasn't a digit, check if it is a '.' followed by something.
            if (*s != '.' || s[1] == '\0') {
                return false;
            }
            // Find the end, verify digits.
            for (++s; *s; ++s) {
                if (*s < '0' || '9' < *s) {
                    return false;
                }
            }
            // Read back toward the '.'.
            for (--s; *s != '.'; --s) {
                T d = *s - '0';
                frac = (frac + (d << N)) / 10; // This requires four bits overhead.
            }
            break;
        }
        T d = *s - '0';
        // Check for overflow
        if (n > nMax || (n == nMax && d > dMax)) {
            return false;
        }
        n = (n * 10) + d;
    }
    if (negate) {
        n = -n;
        frac = -frac;
    }
    *value = (n << N) + frac;
    return true;
}

#endif /* SkFontMgr_android_parser_DEFINED */


text:
/*
 * Class: Layouts.Radial
 *
 * Implements a Radial Layout.
 *
 * Implemented By:
 *
 * <RGraph>, <Hypertree>
 *
 */
Layouts.Radial = new Class({

  /*
   * Method: compute
   *
   * Computes nodes' positions.
   *
   * Parameters:
   *
   * property - _optional_ A <Graph.Node> position property to store the new
   * positions. Possible values are 'pos', 'end' or 'start'.
   *
   */
  compute : function(property) {
    var prop = $.splat(property || [ 'current', 'start', 'end' ]);
    NodeDim.compute(this.graph, prop, this.config);
    this.graph.computeLevels(this.root, 0, "ignore");
    var lengthFunc = this.createLevelDistanceFunc();
    this.computeAngularWidths(prop);
    this.computePositions(prop, lengthFunc);
  },

  /*
   * computePositions
   *
   * Performs the main algorithm for computing node positions.
   */
  computePositions : function(property, getLength) {
    var propArray = property;
    var graph = this.graph;
    var root = graph.getNode(this.root);
    var parent = this.parent;
    var config = this.config;

    for ( var i=0, l=propArray.length; i < l; i++) {
      var pi = propArray[i];
      root.setPos($P(0, 0), pi);
      root.setData('span', Math.PI * 2, pi);
    }

    root.angleSpan = {
      begin : 0,
      end : 2 * Math.PI
    };

    graph.eachBFS(this.root, function(elem) {
      var angleSpan = elem.angleSpan.end - elem.angleSpan.begin;
      var angleInit = elem.angleSpan.begin;
      var len = getLength(elem);
      //Calculate the sum of all angular widths
      var totalAngularWidths = 0, subnodes = [], maxDim = {};
      elem.eachSubnode(function(sib) {
        totalAngularWidths += sib._treeAngularWidth;
        //get max dim
        for ( var i=0, l=propArray.length; i < l; i++) {
          var pi = propArray[i], dim = sib.getData('dim', pi);
          maxDim[pi] = (pi in maxDim)? (dim > maxDim[pi]? dim : maxDim[pi]) : dim;
        }
        subnodes.push(sib);
      }, "ignore");
      //Maintain children order
      //Second constraint for <http://bailando.sims.berkeley.edu/papers/infovis01.htm>
      if (parent && parent.id == elem.id && subnodes.length > 0
          && subnodes[0].dist) {
        subnodes.sort(function(a, b) {
          return (a.dist >= b.dist) - (a.dist <= b.dist);
        });
      }
      //Calculate nodes positions.
      for (var k = 0, ls=subnodes.length; k < ls; k++) {
        var child = subnodes[k];
        if (!child._flag) {
          var angleProportion = child._treeAngularWidth / totalAngularWidths * angleSpan;
          var theta = angleInit + angleProportion / 2;

          for ( var i=0, l=propArray.length; i < l; i++) {
            var pi = propArray[i];
            child.setPos($P(theta, len), pi);
            child.setData('span', angleProportion, pi);
            child.setData('dim-quotient', child.getData('dim', pi) / maxDim[pi], pi);
          }

          child.angleSpan = {
            begin : angleInit,
            end : angleInit + angleProportion
          };
          angleInit += angleProportion;
        }
      }
    }, "ignore");
  },

  /*
   * Method: setAngularWidthForNodes
   *
   * Sets nodes angular widths.
   */
  setAngularWidthForNodes : function(prop) {
    this.graph.eachBFS(this.root, function(elem, i) {
      var diamValue = elem.getData('angularWidth', prop[0]) || 5;
      elem._angularWidth = diamValue / i;
    }, "ignore");
  },

  /*
   * Method: setSubtreesAngularWidth
   *
   * Sets subtrees angular widths.
   */
  setSubtreesAngularWidth : function() {
    var that = this;
    this.graph.eachNode(function(elem) {
      that.setSubtreeAngularWidth(elem);
    }, "ignore");
  },

  /*
   * Method: setSubtreeAngularWidth
   *
   * Sets the angular width for a subtree.
   */
  setSubtreeAngularWidth : function(elem) {
    var that = this, nodeAW = elem._angularWidth, sumAW = 0;
    elem.eachSubnode(function(child) {
      that.setSubtreeAngularWidth(child);
      sumAW += child._treeAngularWidth;
    }, "ignore");
    elem._treeAngularWidth = Math.max(nodeAW, sumAW);
  },

  /*
   * Method: computeAngularWidths
   *
   * Computes nodes and subtrees angular widths.
   */
  computeAngularWidths : function(prop) {
    this.setAngularWidthForNodes(prop);
    this.setSubtreesAngularWidth();
  }

});


text:
module Google
  module Cloud
    module Bigtable
      VERSION = "0.5.0".freeze
    end
  end
end


text:
namespace caffe {

template <typename Dtype>
void DropoutLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  NeuronLayer<Dtype>::SetUp(bottom, top);
  // Set up the cache for random number generation
  rand_vec_.reset(new Blob<unsigned int>(bottom[0]->num(),
      bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()));
  threshold_ = this->layer_param_.dropout_param().dropout_ratio();
  DCHECK(threshold_ > 0.);
  DCHECK(threshold_ < 1.);
  scale_ = 1. / (1. - threshold_);
  uint_thres_ = static_cast<unsigned int>(UINT_MAX * threshold_);
}

template <typename Dtype>
Dtype DropoutLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {
  const Dtype* bottom_data = bottom[0]->cpu_data();
  Dtype* top_data = (*top)[0]->mutable_cpu_data();
  unsigned int* mask = rand_vec_->mutable_cpu_data();
  const int count = bottom[0]->count();
  if (Caffe::phase() == Caffe::TRAIN) {
    // Create random numbers
    caffe_rng_bernoulli(count, 1. - threshold_, mask);
    for (int i = 0; i < count; ++i) {
      top_data[i] = bottom_data[i] * mask[i] * scale_;
    }
  } else {
    caffe_copy(bottom[0]->count(), bottom_data, top_data);
  }
  return Dtype(0);
}

template <typename Dtype>
void DropoutLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down,
    vector<Blob<Dtype>*>* bottom) {
  if (propagate_down[0]) {
    const Dtype* top_diff = top[0]->cpu_diff();
    Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
    if (Caffe::phase() == Caffe::TRAIN) {
      const unsigned int* mask = rand_vec_->cpu_data();
      const int count = (*bottom)[0]->count();
      for (int i = 0; i < count; ++i) {
        bottom_diff[i] = top_diff[i] * mask[i] * scale_;
      }
    } else {
      caffe_copy(top[0]->count(), top_diff, bottom_diff);
    }
  }
}

INSTANTIATE_CLASS(DropoutLayer);

}  // namespace caffe


text:
import { other } from "./inner-reexport";

console.log.bind(console, other);


text:
fiddle-0004-CurlDownload
======

![Screenshot](screenshot.png)

### Title

curl download CDN file

### Creation Date

06-24-15

### Location

Chicago, IL

### Description

Bash script testing whether curl can be used to download CDN hosted JavaScript libraries.  In this case,
the debug version of the extJS 5.1 is downloaded from cache fly.

### Tags

bash, curl, -o


text:
package com.hubspot.jinjava.lib.filter;

import com.hubspot.jinjava.doc.annotations.JinjavaDoc;
import com.hubspot.jinjava.doc.annotations.JinjavaParam;
import com.hubspot.jinjava.doc.annotations.JinjavaSnippet;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;

@JinjavaDoc(
  value = "Convert a value to lowercase",
  input = @JinjavaParam(value = "s", desc = "String to make lowercase", required = true),
  snippets = { @JinjavaSnippet(code = "{{ \"Text to MAKE Lowercase\"|lowercase }}") }
)
public class LowerFilter implements Filter {

  @Override
  public Object filter(Object object, JinjavaInterpreter interpreter, String... arg) {
    if (object instanceof String) {
      String value = (String) object;
      return value.toLowerCase();
    }
    return object;
  }

  @Override
  public String getName() {
    return "lower";
  }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _pmlogger = require('pmlogger');

var _pmlogger2 = _interopRequireDefault(_pmlogger);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var opt = {};
opt.id = '84344732';
opt.url = 'http://future.sankuai.com/monitor/logstore/log/';
opt.repeat = 1;
opt.combo = true;
opt.delay = 1000;
var pmlogger = null;

if (!pmlogger) {
    pmlogger = new _pmlogger2.default(opt);
}

var PmLogger = function PmLogger(msg) {
    _classCallCheck(this, PmLogger);

    try {
        pmlogger.info({
            msg: msg,
            type: 8
        });
    } catch (err) {
        pmlogger.error({
            msg: err.toString(),
            type: 2
        });
    }
};

exports.default = PmLogger;


text:
var gulp = require('gulp');
var cache = require('gulp-cached');
var less = require('gulp-less');
var csslint = require('gulp-csslint');
var minifyCSS = require('gulp-minify-css');
var prefix = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var livereload = require('gulp-livereload');
var runSequence = require('run-sequence');
var errors = require('./errors');

gulp.task('csslint', function() {
    return gulp.src('less/master.less')
        .pipe(less().on('error', errors.onTaskError))
        .pipe(cache('csslint'))
        .on('error', errors.onTaskError)
        .pipe(csslint('.csslintrc'))
        .pipe(errors.onStreamError())
        .pipe(csslint.reporter());
});

gulp.task('less-compile', function() {
    return gulp.src(['less/vendor.less', 'less/master.less'])
        .pipe(cache('less-compile'))
        .pipe(concat('master.css'))
        .pipe(less().on('error', function() {}))
        .pipe(prefix())
        .pipe(minifyCSS({keepSpecialComments: 0}))
        .pipe(gulp.dest('assets/css'))
        .pipe(livereload());
});

gulp.task('less', function() {
    return runSequence('csslint', 'less-compile');
});


text:
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <asm/atomic.h>
#include <asm/cpu-features.h>
#include <asm/errno.h>
#include <asm/semaphore.h>
#include <asm/war.h>
/*
 * Atomically update sem->count.
 * This does the equivalent of the following:
 *
 *	old_count = sem->count;
 *	tmp = MAX(old_count, 0) + incr;
 *	sem->count = tmp;
 *	return old_count;
 *
 * On machines without lld/scd we need a spinlock to make the manipulation of
 * sem->count and sem->waking atomic.  Scalability isn't an issue because
 * this lock is used on UP only so it's just an empty variable.
 */
static inline int __sem_update_count(struct semaphore *sem, int incr)
{
	int old_count, tmp;

	if (cpu_has_llsc && R10000_LLSC_WAR) {
		__asm__ __volatile__(
		"	.set	mips3					\n"
		"1:	ll	%0, %2		# __sem_update_count	\n"
		"	sra	%1, %0, 31				\n"
		"	not	%1					\n"
		"	and	%1, %0, %1				\n"
		"	addu	%1, %1, %3				\n"
		"	sc	%1, %2					\n"
		"	beqzl	%1, 1b					\n"
		"	.set	mips0					\n"
		: "=&r" (old_count), "=&r" (tmp), "=m" (sem->count)
		: "r" (incr), "m" (sem->count));
	} else if (cpu_has_llsc) {
		__asm__ __volatile__(
		"	.set	mips3					\n"
		"1:	ll	%0, %2		# __sem_update_count	\n"
		"	sra	%1, %0, 31				\n"
		"	not	%1					\n"
		"	and	%1, %0, %1				\n"
		"	addu	%1, %1, %3				\n"
		"	sc	%1, %2					\n"
		"	beqz	%1, 1b					\n"
		"	.set	mips0					\n"
		: "=&r" (old_count), "=&r" (tmp), "=m" (sem->count)
		: "r" (incr), "m" (sem->count));
	} else {
		static DEFINE_SPINLOCK(semaphore_lock);
		unsigned long flags;

		spin_lock_irqsave(&semaphore_lock, flags);
		old_count = atomic_read(&sem->count);
		tmp = max_t(int, old_count, 0) + incr;
		atomic_set(&sem->count, tmp);
		spin_unlock_irqrestore(&semaphore_lock, flags);
	}

	return old_count;
}

void __up(struct semaphore *sem)
{
	/*
	 * Note that we incremented count in up() before we came here,
	 * but that was ineffective since the result was <= 0, and
	 * any negative value of count is equivalent to 0.
	 * This ends up setting count to 1, unless count is now > 0
	 * (i.e. because some other cpu has called up() in the meantime),
	 * in which case we just increment count.
	 */
	__sem_update_count(sem, 1);
	wake_up(&sem->wait);
}

EXPORT_SYMBOL(__up);

/*
 * Note that when we come in to __down or __down_interruptible,
 * we have already decremented count, but that decrement was
 * ineffective since the result was < 0, and any negative value
 * of count is equivalent to 0.
 * Thus it is only when we decrement count from some value > 0
 * that we have actually got the semaphore.
 */
void __sched __down(struct semaphore *sem)
{
	struct task_struct *tsk = current;
	DECLARE_WAITQUEUE(wait, tsk);

	__set_task_state(tsk, TASK_UNINTERRUPTIBLE);
	add_wait_queue_exclusive(&sem->wait, &wait);

	/*
	 * Try to get the semaphore.  If the count is > 0, then we've
	 * got the semaphore; we decrement count and exit the loop.
	 * If the count is 0 or negative, we set it to -1, indicating
	 * that we are asleep, and then sleep.
	 */
	while (__sem_update_count(sem, -1) <= 0) {
		schedule();
		set_task_state(tsk, TASK_UNINTERRUPTIBLE);
	}
	remove_wait_queue(&sem->wait, &wait);
	__set_task_state(tsk, TASK_RUNNING);

	/*
	 * If there are any more sleepers, wake one of them up so
	 * that it can either get the semaphore, or set count to -1
	 * indicating that there are still processes sleeping.
	 */
	wake_up(&sem->wait);
}

EXPORT_SYMBOL(__down);

int __sched __down_interruptible(struct semaphore * sem)
{
	int retval = 0;
	struct task_struct *tsk = current;
	DECLARE_WAITQUEUE(wait, tsk);

	__set_task_state(tsk, TASK_INTERRUPTIBLE);
	add_wait_queue_exclusive(&sem->wait, &wait);

	while (__sem_update_count(sem, -1) <= 0) {
		if (signal_pending(current)) {
			/*
			 * A signal is pending - give up trying.
			 * Set sem->count to 0 if it is negative,
			 * since we are no longer sleeping.
			 */
			__sem_update_count(sem, 0);
			retval = -EINTR;
			break;
		}
		schedule();
		set_task_state(tsk, TASK_INTERRUPTIBLE);
	}
	remove_wait_queue(&sem->wait, &wait);
	__set_task_state(tsk, TASK_RUNNING);

	wake_up(&sem->wait);
	return retval;
}

EXPORT_SYMBOL(__down_interruptible);


text:
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("node_id", ev.target.id);
    var node_id = ev.dataTransfer.getData("node_id");
    var node = document.getElementById(node_id);
    markPossibleMovesByPiece(node)
}

function markPossibleMovesByPiece(piece){
    var possible_moves = getPossibleMovesByPiece(piece);
    highlightPossibleSquares(possible_moves);
    console.log(possible_moves);
}

function getPossibleMovesByPiece(piece){
    console.log(piece);
    if( piece.type == "pawn"){
        return getPossibleMovesByPawn(piece);
    }
    return null;
}

function highlightPossibleSquares(squares){
    for(var s = 0; s < squares.length; s++){
        square = document.getElementById(squares[s]);
        square.className = "highlight square";
    }
}

function resetHighlight(){
    for(var i=0; i < squares.length; i++){
        squares[i].className="square";
    }
}

function getPossibleMovesByPawn(pawn){
    var moves = [];
    if(pawn.first_move){
        moves.push(pawn.current_square.column_letter + (pawn.direction*2+parseInt(pawn.current_square.row_number)));
    }
    moves.push((pawn.current_square.column_letter + (pawn.direction*1+parseInt(pawn.current_square.row_number))));

    return moves;
}

function drop(ev) {
    ev.preventDefault();
    resetHighlight();
    var node_id = ev.dataTransfer.getData("node_id");
    var node = document.getElementById(node_id);
    var square = ev.target;
    if( !square.is_square ){
        square = square.parentNode;
    }
           /* movePiece(node.current_square, square);*/

}

function movePiece(origin_square, target_square){
    var child = origin_square.firstChild;
    target_square.appendChild(child);
    child.current_square = square;
}

var squares = document.getElementsByClassName("square");
for( var i = 0; i < squares.length; i++){
    var square = squares[i];
    new Square(square);
}

var pawns = document.getElementsByClassName("pawn");
for( var i = 0; i < pawns.length; i++){
    var pawn = pawns[i];
    new Pawn(pawn, pawn.parentNode);
}

function Square(node){
    node.is_square = true;
    node.empty = function(){
        return node.innerHTML == "";
    };
    node.row_number = node.getAttribute("data-row-number");
    node.column_letter = node.getAttribute("data-column-letter");
    node.id = node.column_letter + node.row_number;
    return node;
}

function Pawn(node, current_square){
    return new Piece(node, "pawn", current_square)
}

function Piece(node, type, current_square){
    node.type = type;
    node.current_square = current_square;
    node.first_move = true;
    node.color = node.getAttribute("data-color");
    node.direction = node.color == "white" ? 1 : -1 ;
    return node;
}


text:
package org.pathvisio.core.view;

import java.net.URL;

import org.pathvisio.core.model.Pathway;
import org.pathvisio.core.model.PathwayElement;

/**
 * Represents a template that consists of graphics and
 * can be added to a pathway.
 * @author thomas
 */
public interface Template {
	/**
	 * Create and add the pathway elements for this template to the given pathway.
	 * Coordinates mx and my represent the point where the template
	 * has to be inserted (in model coordinates)
	 * @param mx	The x coordinate of the base point
	 * @param my	The y coordinate of the base point
	 * @return A list with the elements that where added by the template
	 */
	PathwayElement[] addElements(Pathway p, double mx, double my);

	/**
	 * Get the element that will be used to drag the template after
	 * adding (e.g. the South-East handle in case of a DataNode)
	 * @return The drag element of the last added template graphics
	 */
	VPathwayElement getDragElement(VPathway vp);

	/**
	 * Get the name for this template
	 * @return
	 */
	String getName();

	/**
	 * Get the description for this template
	 * @return
	 */
	String getDescription();

	/**
	 * Get the location of the icon for this template
	 * @return The icon location, or null if the template doesn't have an icon
	 */
	URL getIconLocation();

	void postInsert(PathwayElement[] newElements);
}


text:
class CreateContactCenterAgents < ActiveRecord::Migration
  def change
    create_table :contact_center_agents do |t|
      t.string :username,     null: false
      t.string :status,       default: 'offline'
      t.string :name,         null: false
      t.string :phone_type,   default: 'twilio_client'
      t.string :phone_number
      t.string :phone_ext
      t.string :sip_uri

      t.timestamps null: false
    end

    add_index :contact_center_agents, :username
  end
end