<commit_before>/*
 * UUID-js: A js library to generate and parse UUIDs, TimeUUIDs and generate
 * TimeUUID based on dates for range selections.
 * @see http://www.ietf.org/rfc/rfc4122.txt
 **/

function UUIDjs() {
};

UUIDjs.maxFromBits = function(bits) {
  return Math.pow(2, bits);
};

UUIDjs.limitUI04 = UUIDjs.maxFromBits(4);
UUIDjs.limitUI06 = UUIDjs.maxFromBits(6);
UUIDjs.limitUI08 = UUIDjs.maxFromBits(8);
UUIDjs.limitUI12 = UUIDjs.maxFromBits(12);
UUIDjs.limitUI14 = UUIDjs.maxFromBits(14);
UUIDjs.limitUI16 = UUIDjs.maxFromBits(16);
UUIDjs.limitUI32 = UUIDjs.maxFromBits(32);
UUIDjs.limitUI40 = UUIDjs.maxFromBits(40);
UUIDjs.limitUI48 = UUIDjs.maxFromBits(48);

UUIDjs.randomUI04 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI04);
};
UUIDjs.randomUI06 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI06);
};
UUIDjs.randomUI08 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI08);
};
UUIDjs.randomUI12 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI12);
};
UUIDjs.randomUI14 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI14);
};
UUIDjs.randomUI16 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI16);
};
UUIDjs.randomUI32 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI32);
};
UUIDjs.randomUI40 = function() {
  return (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << 40 - 30)) * (1 << 30);
};
UUIDjs.randomUI48 = function() {
  return (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << 48 - 30)) * (1 << 30);
};

UUIDjs.paddedString = function(string, length, z) {
  string = String(string);
  z = (!z) ? '0' : z;
  var i = length - string.length;
  for (; i > 0; i >>>= 1, z += z) {
    if (i & 1) {
      string = z + string;
    }
  }
  return string;
};

UUIDjs.prototype.fromParts = function(timeLow, timeMid, timeHiAndVersion, clockSeqHiAndReserved, clockSeqLow, node) {
  this.version = (timeHiAndVersion >> 12) & 0xF;
  this.hex = UUIDjs.paddedString(timeLow.toString(16), 8)
             + '-'
             + UUIDjs.paddedString(timeMid.toString(16), 4)
             + '-'
             + UUIDjs.paddedString(timeHiAndVersion.toString(16), 4)
             + '-'
             + UUIDjs.paddedString(clockSeqHiAndReserved.toString(16), 2)
             + UUIDjs.paddedString(clockSeqLow.toString(16), 2)
             + '-'
             + UUIDjs.paddedString(node.toString(16), 12);
  return this;
};

UUIDjs.prototype.toString = function() {
  return this.hex;
};
UUIDjs.prototype.toURN = function() {
  return 'urn:uuid:' + this.hex;
};

UUIDjs.prototype.toBytes = function() {
  var parts = this.hex.split('-');
  var ints = [];
  var intPos = 0;
  for (var i = 0; i < parts.length; i++) {
    for (var j = 0; j < parts[i].length; j+=2) {
      ints[intPos++] = parseInt(parts[i].substr(j, 2), 16);
    }
  }
  return ints;
};

UUIDjs.prototype.equals = function(uuid) {
  if (!(uuid instanceof UUID)) {
    return false;
  }
  if (this.hex !== uuid.hex) {
    return false;
  }
  return true;
};

UUIDjs.getTimeFieldValues = function(time) {
  var ts = time - Date.UTC(1582, 9, 15);
  var hm = ((ts / 0x100000000) * 10000) & 0xFFFFFFF;
  return { low: ((ts & 0xFFFFFFF) * 10000) % 0x100000000,
            mid: hm & 0xFFFF, hi: hm >>> 16, timestamp: ts };
};

UUIDjs._create4 = function() {
  return new UUIDjs().fromParts(
    UUIDjs.randomUI32(),
    UUIDjs.randomUI16(),
    0x4000 | UUIDjs.randomUI12(),
    0x80   | UUIDjs.randomUI06(),
    UUIDjs.randomUI08(),
    UUIDjs.randomUI48()
  );
};

UUIDjs._create1 = function() {
  var now = new Date().getTime();
  var sequence = UUIDjs.randomUI14();
  var node = (UUIDjs.randomUI08() | 1) * 0x10000000000 + UUIDjs.randomUI40();
  var tick = UUIDjs.randomUI04();
  var timestamp = 0;
  var timestampRatio = 1/4;

  if (now != timestamp) {
    if (now < timestamp) {
      sequence++;
    }
    timestamp = now;
    tick = UUIDjs.randomUI04();
  } else if (Math.random() < timestampRatio && tick < 9984) {
    tick += 1 + UUIDjs.randomUI04();
  } else {
    sequence++;
  }

  var tf = UUIDjs.getTimeFieldValues(timestamp);
  var tl = tf.low + tick;
  var thav = (tf.hi & 0xFFF) | 0x1000;

  sequence &= 0x3FFF;
  var cshar = (sequence >>> 8) | 0x80;
  var csl = sequence & 0xFF;

  return new UUIDjs().fromParts(tl, tf.mid, thav, cshar, csl, node);
};

UUIDjs.create = function(version) {
  version = version || 4;
  return this['_create' + version]();
};

UUIDjs.fromTime = function(time, last) {
  last = (!last) ? false : last;
  var tf = UUIDjs.getTimeFieldValues(time);
  var tl = tf.low;
  var thav = (tf.hi & 0xFFF) | 0x1000;  // set version '0001'
  if (last === false) {
    return new UUIDjs().fromParts(tl,tf.mid,thav, 0, 0, 0);
  } else {
    return new UUIDjs().fromParts(tl,tf.mid,thav, 0x80 | UUIDjs.limitUI06, UUIDjs.limitUI08, UUIDjs.limitUI48);
  }
};

UUIDjs.firstFromTime = function(time) {
  return UUIDjs.fromTime(time, false);
};
UUIDjs.lastFromTime = function(time) {
  return UUIDjs.fromTime(time, true);
};

UUIDjs.fromURN = function(strId) {
  var r, p = /^(?:urn:uuid:|\{)?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{2})([0-9a-f]{2})-([0-9a-f]{12})(?:\})?$/i;
  if ((r = p.exec(strId))) {
    return new UUIDjs().fromParts(parseInt(r[1], 16), parseInt(r[2], 16),
                            parseInt(r[3], 16), parseInt(r[4], 16),
                            parseInt(r[5], 16), parseInt(r[6], 16));
  }
  return null;
};

UUIDjs.fromBytes = function(ints) {
  if (ints.length < 5) {
    return null;
  }
  var str = '';
  var pos = 0;
  var parts = [4, 2, 2, 2, 6];
  for (var i = 0; i < parts.length; i++) {
    for (var j = 0; j < parts[i]; j++) {
      var octet = ints[pos++].toString(16);
      if (octet.length == 1) {
        octet = '0' + octet;
      }
      str += octet;
    }
    if (parts[i] !== 6) {
      str += '-';
    }
  }
  return UUIDjs.fromURN(str);
};

UUIDjs.fromBinary = function(binary) {
  var ints = [];
  for (var i = 0; i < binary.length; i++) {
    ints[i] = binary.charCodeAt(i);
    if (ints[i] > 255 || ints[i] < 0) {
      throw new Error('Unexpected byte in binary data.');
    }
  }
  return UUIDjs.fromBytes(ints);
};

// Aliases to support legacy code. Do not use these when writing new code as
// they may be removed in future versions!
UUIDjs.new = function() {
  return this.create(4);
};
UUIDjs.newTS = function() {
  return this.create(1);
};
UUIDjs.firstUUIDForTime = function(time) {
  return UUIDjs.firstFromTime(time);
};
UUIDjs.lastUUIDForTime = function(time) {
  return UUIDjs.lastFromTime(time);
};

module.exports = UUIDjs;
<commit_msg>Add whitespaces after commata<commit_after>/*
 * UUID-js: A js library to generate and parse UUIDs, TimeUUIDs and generate
 * TimeUUID based on dates for range selections.
 * @see http://www.ietf.org/rfc/rfc4122.txt
 **/

function UUIDjs() {
};

UUIDjs.maxFromBits = function(bits) {
  return Math.pow(2, bits);
};

UUIDjs.limitUI04 = UUIDjs.maxFromBits(4);
UUIDjs.limitUI06 = UUIDjs.maxFromBits(6);
UUIDjs.limitUI08 = UUIDjs.maxFromBits(8);
UUIDjs.limitUI12 = UUIDjs.maxFromBits(12);
UUIDjs.limitUI14 = UUIDjs.maxFromBits(14);
UUIDjs.limitUI16 = UUIDjs.maxFromBits(16);
UUIDjs.limitUI32 = UUIDjs.maxFromBits(32);
UUIDjs.limitUI40 = UUIDjs.maxFromBits(40);
UUIDjs.limitUI48 = UUIDjs.maxFromBits(48);

UUIDjs.randomUI04 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI04);
};
UUIDjs.randomUI06 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI06);
};
UUIDjs.randomUI08 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI08);
};
UUIDjs.randomUI12 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI12);
};
UUIDjs.randomUI14 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI14);
};
UUIDjs.randomUI16 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI16);
};
UUIDjs.randomUI32 = function() {
  return Math.round(Math.random() * UUIDjs.limitUI32);
};
UUIDjs.randomUI40 = function() {
  return (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << 40 - 30)) * (1 << 30);
};
UUIDjs.randomUI48 = function() {
  return (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << 48 - 30)) * (1 << 30);
};

UUIDjs.paddedString = function(string, length, z) {
  string = String(string);
  z = (!z) ? '0' : z;
  var i = length - string.length;
  for (; i > 0; i >>>= 1, z += z) {
    if (i & 1) {
      string = z + string;
    }
  }
  return string;
};

UUIDjs.prototype.fromParts = function(timeLow, timeMid, timeHiAndVersion, clockSeqHiAndReserved, clockSeqLow, node) {
  this.version = (timeHiAndVersion >> 12) & 0xF;
  this.hex = UUIDjs.paddedString(timeLow.toString(16), 8)
             + '-'
             + UUIDjs.paddedString(timeMid.toString(16), 4)
             + '-'
             + UUIDjs.paddedString(timeHiAndVersion.toString(16), 4)
             + '-'
             + UUIDjs.paddedString(clockSeqHiAndReserved.toString(16), 2)
             + UUIDjs.paddedString(clockSeqLow.toString(16), 2)
             + '-'
             + UUIDjs.paddedString(node.toString(16), 12);
  return this;
};

UUIDjs.prototype.toString = function() {
  return this.hex;
};
UUIDjs.prototype.toURN = function() {
  return 'urn:uuid:' + this.hex;
};

UUIDjs.prototype.toBytes = function() {
  var parts = this.hex.split('-');
  var ints = [];
  var intPos = 0;
  for (var i = 0; i < parts.length; i++) {
    for (var j = 0; j < parts[i].length; j+=2) {
      ints[intPos++] = parseInt(parts[i].substr(j, 2), 16);
    }
  }
  return ints;
};

UUIDjs.prototype.equals = function(uuid) {
  if (!(uuid instanceof UUID)) {
    return false;
  }
  if (this.hex !== uuid.hex) {
    return false;
  }
  return true;
};

UUIDjs.getTimeFieldValues = function(time) {
  var ts = time - Date.UTC(1582, 9, 15);
  var hm = ((ts / 0x100000000) * 10000) & 0xFFFFFFF;
  return { low: ((ts & 0xFFFFFFF) * 10000) % 0x100000000,
            mid: hm & 0xFFFF, hi: hm >>> 16, timestamp: ts };
};

UUIDjs._create4 = function() {
  return new UUIDjs().fromParts(
    UUIDjs.randomUI32(),
    UUIDjs.randomUI16(),
    0x4000 | UUIDjs.randomUI12(),
    0x80   | UUIDjs.randomUI06(),
    UUIDjs.randomUI08(),
    UUIDjs.randomUI48()
  );
};

UUIDjs._create1 = function() {
  var now = new Date().getTime();
  var sequence = UUIDjs.randomUI14();
  var node = (UUIDjs.randomUI08() | 1) * 0x10000000000 + UUIDjs.randomUI40();
  var tick = UUIDjs.randomUI04();
  var timestamp = 0;
  var timestampRatio = 1/4;

  if (now != timestamp) {
    if (now < timestamp) {
      sequence++;
    }
    timestamp = now;
    tick = UUIDjs.randomUI04();
  } else if (Math.random() < timestampRatio && tick < 9984) {
    tick += 1 + UUIDjs.randomUI04();
  } else {
    sequence++;
  }

  var tf = UUIDjs.getTimeFieldValues(timestamp);
  var tl = tf.low + tick;
  var thav = (tf.hi & 0xFFF) | 0x1000;

  sequence &= 0x3FFF;
  var cshar = (sequence >>> 8) | 0x80;
  var csl = sequence & 0xFF;

  return new UUIDjs().fromParts(tl, tf.mid, thav, cshar, csl, node);
};

UUIDjs.create = function(version) {
  version = version || 4;
  return this['_create' + version]();
};

UUIDjs.fromTime = function(time, last) {
  last = (!last) ? false : last;
  var tf = UUIDjs.getTimeFieldValues(time);
  var tl = tf.low;
  var thav = (tf.hi & 0xFFF) | 0x1000;  // set version '0001'
  if (last === false) {
    return new UUIDjs().fromParts(tl, tf.mid, thav, 0, 0, 0);
  } else {
    return new UUIDjs().fromParts(tl, tf.mid, thav, 0x80 | UUIDjs.limitUI06, UUIDjs.limitUI08, UUIDjs.limitUI48);
  }
};

UUIDjs.firstFromTime = function(time) {
  return UUIDjs.fromTime(time, false);
};
UUIDjs.lastFromTime = function(time) {
  return UUIDjs.fromTime(time, true);
};

UUIDjs.fromURN = function(strId) {
  var r, p = /^(?:urn:uuid:|\{)?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{2})([0-9a-f]{2})-([0-9a-f]{12})(?:\})?$/i;
  if ((r = p.exec(strId))) {
    return new UUIDjs().fromParts(parseInt(r[1], 16), parseInt(r[2], 16),
                            parseInt(r[3], 16), parseInt(r[4], 16),
                            parseInt(r[5], 16), parseInt(r[6], 16));
  }
  return null;
};

UUIDjs.fromBytes = function(ints) {
  if (ints.length < 5) {
    return null;
  }
  var str = '';
  var pos = 0;
  var parts = [4, 2, 2, 2, 6];
  for (var i = 0; i < parts.length; i++) {
    for (var j = 0; j < parts[i]; j++) {
      var octet = ints[pos++].toString(16);
      if (octet.length == 1) {
        octet = '0' + octet;
      }
      str += octet;
    }
    if (parts[i] !== 6) {
      str += '-';
    }
  }
  return UUIDjs.fromURN(str);
};

UUIDjs.fromBinary = function(binary) {
  var ints = [];
  for (var i = 0; i < binary.length; i++) {
    ints[i] = binary.charCodeAt(i);
    if (ints[i] > 255 || ints[i] < 0) {
      throw new Error('Unexpected byte in binary data.');
    }
  }
  return UUIDjs.fromBytes(ints);
};

// Aliases to support legacy code. Do not use these when writing new code as
// they may be removed in future versions!
UUIDjs.new = function() {
  return this.create(4);
};
UUIDjs.newTS = function() {
  return this.create(1);
};
UUIDjs.firstUUIDForTime = function(time) {
  return UUIDjs.firstFromTime(time);
};
UUIDjs.lastUUIDForTime = function(time) {
  return UUIDjs.lastFromTime(time);
};

module.exports = UUIDjs;
<|endoftext|>


<commit_before>var del = require('del');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const mocha = require('gulp-spawn-mocha');
const tslint = require('gulp-tslint');
const ts = require('gulp-typescript');
var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');

const tsProject = ts.createProject('tsconfig.json');

gulp.task('clean', () => {
  return del(['coverage', 'lib']);
});

gulp.task('default', ['lint', 'scripts', 'test', 'coverage'], () => {});

gulp.task('scripts', () => {
  return gulp.src(['src/**/*.ts', 'test/**/*.ts'], { base: '.' })
    .pipe(sourcemaps.init())
    .pipe(tsProject())
    .pipe(sourcemaps.write('.', {
      sourceRoot: '..',
    }))
    .pipe(gulp.dest('lib'));
});

gulp.task('lint', ['scripts'], () => {
  return gulp.src(['src/**/*.ts', 'test/**/*.ts'])
    .pipe(tslint({
      configuration: './tslint.json',
      formatter: 'verbose',
      tslint: require('tslint'),
    }))
    .pipe(tslint.report({
      emitError: false,
      summarizeFailureOutput: true,
    }));
});

gulp.task('coverage', ['test'], () => {
  return gulp.src('coverage/coverage-final.json')
    .pipe(remapIstanbul({
      reports: {
        'text': null,
        'text-summary': null,
        'html': 'coverage/html-report',
      }
    }));
});

gulp.task('test', ['scripts'], () =>
  gulp.src('lib/test/**/*.js', {read: false})
    .pipe(mocha({
      istanbul: true,
      timeout: 15000,
    }))
);
<commit_msg>Increase mocha timeout to 30s.<commit_after>var del = require('del');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const mocha = require('gulp-spawn-mocha');
const tslint = require('gulp-tslint');
const ts = require('gulp-typescript');
var remapIstanbul = require('remap-istanbul/lib/gulpRemapIstanbul');

const tsProject = ts.createProject('tsconfig.json');

gulp.task('clean', () => {
  return del(['coverage', 'lib']);
});

gulp.task('default', ['lint', 'scripts', 'test', 'coverage'], () => {});

gulp.task('scripts', () => {
  return gulp.src(['src/**/*.ts', 'test/**/*.ts'], { base: '.' })
    .pipe(sourcemaps.init())
    .pipe(tsProject())
    .pipe(sourcemaps.write('.', {
      sourceRoot: '..',
    }))
    .pipe(gulp.dest('lib'));
});

gulp.task('lint', ['scripts'], () => {
  return gulp.src(['src/**/*.ts', 'test/**/*.ts'])
    .pipe(tslint({
      configuration: './tslint.json',
      formatter: 'verbose',
      tslint: require('tslint'),
    }))
    .pipe(tslint.report({
      emitError: false,
      summarizeFailureOutput: true,
    }));
});

gulp.task('coverage', ['test'], () => {
  return gulp.src('coverage/coverage-final.json')
    .pipe(remapIstanbul({
      reports: {
        'text': null,
        'text-summary': null,
        'html': 'coverage/html-report',
      }
    }));
});

gulp.task('test', ['scripts'], () =>
  gulp.src('lib/test/**/*.js', {read: false})
    .pipe(mocha({
      istanbul: true,
      timeout: 30000,
    }))
);
<|endoftext|>


<commit_before>// Copyright 2011 Bobby Powers. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

define(['./util', './common', './lex'], function(util, common, lex) {
    const vars = {};

    const Variable = function Variable(name, type, eqn) {
        // for subclasses, when instantiated for their prototypes
        if (arguments.length === 0)
            return;

        this.eqnOrig = eqn;
        eqn = eqn.toLowerCase();
        this.name = name;
        this.type = type;
        this.eqn = eqn;

        // for a flow or aux, we depend on variables that aren't built
        // in functions in the equation.
        this._deps = lex.identifierSet(eqn);
    }
    // returns a string of this variables initial equation. suitable for
    // exec()'ing
    Variable.prototype.initialEquation = function() {
        return this.eqn;
    }
    Variable.prototype.equation = function() {
        return this.eqn;
    }
    Variable.prototype.getDeps = function() {
        return this._deps;
    }
    Variable.prototype.lessThan = function(that) {
        if (this.name in that.getDeps()) {
            return true;
        } else {
            return false;
        }
    }

    const Stock = function Stock(name, type, eqn, inflows, outflows) {
        this.eqnOrig = eqn;
        eqn = eqn.toLowerCase();
        this.name = name;
        this.type = type;
        this.initial = eqn;
        this.inflows = inflows;
        this.outflows = outflows;

        // for a stock, the dependencies are any identifiers (that
        // aren't references to builtin functions) in the initial
        // variable string.  Deps are used for sorting equations into
        // the right order, so for now we don't add any of the flows.
        this._deps = lex.identifierSet(eqn);
    }
    Stock.prototype = new Variable();
    // returns a string of this variables initial equation. suitable for
    // exec()'ing
    Stock.prototype.initialEquation = function() {
        return this.initial;
    }
    Stock.prototype.equation = function() {
        var eqn;
        eqn = this.initial + ',';
        if (this.inflows.length > 0)
            eqn += this.inflows.join(',');
        if (this.outflows.length > 0)
            eqn += '- (' + this.outflows.join(',') + ')';
    }

    const Table = function Table(name, eqn, gf) {
        this.eqnOrig = eqn;
        eqn = eqn.toLowerCase();
        this.name = name;
        this.type = 'table';
        this.x = [];
        this.y = [];

        //console.log(name+'.ypts: '+gf.children('ypts').text());
        const sep  = gf.children('ypts').attr('sep') || ',';
        const ypts = util.numArr(gf.children('ypts').text().split(sep));

        const xmin = parseFloat(gf.children('xscale').attr('min'));
        const xmax = parseFloat(gf.children('xscale').attr('max'));
        //const ymin = parseFloat(gf.children('yscale').attr('min'));
        //const ymax = parseFloat(gf.children('yscale').attr('max'));

        var i;
        for (i = 0; i < ypts.length; i++) {
            // linear mapping of points between xmin and xmax,
            // inclusive
            var x = (i/(ypts.length-1))*(xmax-xmin) + xmin;
            //console.log('x:'+x+',y:'+ypts[i]);
            this.x.push(x);
            this.y.push(ypts[i]);
        }
        //console.log(name+'.x = ' + this.x);
        //console.log(name+'.y = ' + this.y);

        this._deps = lex.identifierSet(eqn);
    }
    Table.prototype = new Variable();

    vars.Variable = Variable;
    vars.Stock = Stock;
    vars.Table = Table;

    return vars;
});
<commit_msg>vars: remove debugging statements<commit_after>// Copyright 2011 Bobby Powers. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

define(['./util', './common', './lex'], function(util, common, lex) {
    const vars = {};

    const Variable = function Variable(name, type, eqn) {
        // for subclasses, when instantiated for their prototypes
        if (arguments.length === 0)
            return;

        this.eqnOrig = eqn;
        eqn = eqn.toLowerCase();
        this.name = name;
        this.type = type;
        this.eqn = eqn;

        // for a flow or aux, we depend on variables that aren't built
        // in functions in the equation.
        this._deps = lex.identifierSet(eqn);
    }
    // returns a string of this variables initial equation. suitable for
    // exec()'ing
    Variable.prototype.initialEquation = function() {
        return this.eqn;
    }
    Variable.prototype.equation = function() {
        return this.eqn;
    }
    Variable.prototype.getDeps = function() {
        return this._deps;
    }
    Variable.prototype.lessThan = function(that) {
        if (this.name in that.getDeps()) {
            return true;
        } else {
            return false;
        }
    }

    const Stock = function Stock(name, type, eqn, inflows, outflows) {
        this.eqnOrig = eqn;
        eqn = eqn.toLowerCase();
        this.name = name;
        this.type = type;
        this.initial = eqn;
        this.inflows = inflows;
        this.outflows = outflows;

        // for a stock, the dependencies are any identifiers (that
        // aren't references to builtin functions) in the initial
        // variable string.  Deps are used for sorting equations into
        // the right order, so for now we don't add any of the flows.
        this._deps = lex.identifierSet(eqn);
    }
    Stock.prototype = new Variable();
    // returns a string of this variables initial equation. suitable for
    // exec()'ing
    Stock.prototype.initialEquation = function() {
        return this.initial;
    }
    Stock.prototype.equation = function() {
        var eqn;
        eqn = this.initial + ',';
        if (this.inflows.length > 0)
            eqn += this.inflows.join(',');
        if (this.outflows.length > 0)
            eqn += '- (' + this.outflows.join(',') + ')';
    }

    const Table = function Table(name, eqn, gf) {
        this.eqnOrig = eqn;
        eqn = eqn.toLowerCase();
        this.name = name;
        this.type = 'table';
        this.x = [];
        this.y = [];

        const sep  = gf.children('ypts').attr('sep') || ',';
        const ypts = util.numArr(gf.children('ypts').text().split(sep));

        const xmin = parseFloat(gf.children('xscale').attr('min'));
        const xmax = parseFloat(gf.children('xscale').attr('max'));
        //const ymin = parseFloat(gf.children('yscale').attr('min'));
        //const ymax = parseFloat(gf.children('yscale').attr('max'));

        var i;
        for (i = 0; i < ypts.length; i++) {
            // linear mapping of points between xmin and xmax,
            // inclusive
            var x = (i/(ypts.length-1))*(xmax-xmin) + xmin;
            this.x.push(x);
            this.y.push(ypts[i]);
        }

        this._deps = lex.identifierSet(eqn);
    }
    Table.prototype = new Variable();

    vars.Variable = Variable;
    vars.Stock = Stock;
    vars.Table = Table;

    return vars;
});
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------------------------------

    Build Configuration
    Contributors: Luan Gjokaj

------------------------------------------------------------------------------------------------- */
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var postcss = require('gulp-postcss');
var cssnext = require('postcss-cssnext');
var partialimport = require('postcss-easy-import');
var sourcemaps = require('gulp-sourcemaps');
var cssnano = require('cssnano');
var plumber = require('gulp-plumber');
var htmlmin = require('gulp-htmlmin');
var babel = require("gulp-babel");
var fileinclude = require('gulp-file-include');
//--------------------------------------------------------------------------------------------------
/* -------------------------------------------------------------------------------------------------
    PostCSS Plugins
------------------------------------------------------------------------------------------------- */
var plugins = [
    partialimport,
    cssnext({
        warnForDuplicates: false
    }),
    cssnano()
];
//--------------------------------------------------------------------------------------------------
/* -------------------------------------------------------------------------------------------------
    Your JavaScript Files
------------------------------------------------------------------------------------------------- */
var headerJS = [
    'node_modules/aos/dist/aos.js'
];
var footerJS = [
    'node_modules/jquery/dist/jquery.js',
    'src/assets/js/**'
];
//--------------------------------------------------------------------------------------------------
/* -------------------------------------------------------------------------------------------------
    Start of Build Tasks
------------------------------------------------------------------------------------------------- */
gulp.task('build-dev', [
    'style-dev',
    'copy-images',
    'copy-fonts',
    'header-scripts-dev',
    'footer-scripts-dev',
    'process-static-files-dev',
    'watch'
], function () {
    browserSync.init({
        server: {
            baseDir: "app"
        }
    });
});

gulp.task('build-prod', [
    'style-prod',
    'copy-images',
    'copy-fonts',
    'header-scripts-prod',
    'footer-scripts-prod',
    'process-images',
    'process-static-files-prod'
]);

gulp.task('default');

gulp.task('process-static-files-dev', function () {
    return gulp.src(['src/*.html'])
        .pipe(plumber({ errorHandler: onError }))
        .pipe(fileinclude({
            filters: {
                prefix: '@@',
                basepath: '@file'
            }
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('process-static-files-prod', function () {
    return gulp.src(['src/*.html'])
        .pipe(plumber({ errorHandler: onError }))
        .pipe(fileinclude({
            filters: {
                prefix: '@@',
                basepath: '@file'
            }
        }))
        .pipe(htmlmin({
            collapseWhitespace: true,
            ignoreCustomFragments: [/<%[\s\S]*?%>/, /<\?[=|php]?[\s\S]*?\?>/]
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('footer-scripts-dev', function () {
    return gulp.src(footerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('bundle.js'))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

/* NOTE: On header scripts babel is not executed */
gulp.task('header-scripts-dev', function () {
    return gulp.src(headerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(concat('top.js'))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

gulp.task('footer-scripts-prod', function () {
    return gulp.src(footerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('bundle.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

/* NOTE: On header scripts babel is not executed */
gulp.task('header-scripts-prod', function () {
    return gulp.src(headerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(concat('top.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

gulp.task('copy-fonts', function () {
    return gulp.src('src/assets/fonts/**')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(gulp.dest('app/assets/fonts'));
});

gulp.task('copy-images', function () {
    return gulp.src('src/assets/img/**')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(gulp.dest('app/assets/img'));
});

gulp.task('process-images', function (cb) {
    return gulp.src('src/assets/img/**')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(imagemin())
        .pipe(gulp.dest('app/assets/img'));
});

gulp.task('style-dev', function () {
    return gulp.src('src/assets/style/main.css')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(postcss(plugins))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('app/assets/css'))
        .pipe(browserSync.stream({match: '**/*.css'}));
});

gulp.task('style-prod', function () {
    return gulp.src('src/assets/style/main.css')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(postcss(plugins))
        .pipe(gulp.dest('app/assets/css'));
});

var onError = function (err) {
    gutil.beep();
    console.log(err.toString());
    this.emit('end');
};

var reload = browserSync.reload();

gulp.task('reload-js', ['footer-scripts-dev'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('reload-images', ['copy-images'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('reload-fonts', ['copy-fonts'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('reload-files', ['process-static-files-dev'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('watch', function () {
    gulp.watch(['src/assets/style/**/*.css'], ['style-dev']);
    gulp.watch(['src/assets/js/*'], ['reload-js']);
    gulp.watch(['src/assets/img/*'], ['reload-images']);
    gulp.watch(['src/assets/fonts/*'], ['reload-fonts']);
    gulp.watch(['src/*.html', 'src/includes/**'], ['reload-files']);
});
/* -------------------------------------------------------------------------------------------------
    End of Build Tasks
------------------------------------------------------------------------------------------------- */
<commit_msg>Update.<commit_after>/* -------------------------------------------------------------------------------------------------

    Build Configuration
    Contributors: Luan Gjokaj

------------------------------------------------------------------------------------------------- */
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var postcss = require('gulp-postcss');
var cssnext = require('postcss-cssnext');
var partialimport = require('postcss-easy-import');
var sourcemaps = require('gulp-sourcemaps');
var cssnano = require('cssnano');
var plumber = require('gulp-plumber');
var htmlmin = require('gulp-htmlmin');
var babel = require("gulp-babel");
var fileinclude = require('gulp-file-include');
//--------------------------------------------------------------------------------------------------
/* -------------------------------------------------------------------------------------------------
    PostCSS Plugins
------------------------------------------------------------------------------------------------- */
var plugins = [
    partialimport,
    cssnext({
        warnForDuplicates: false
    }),
    cssnano()
];
//--------------------------------------------------------------------------------------------------
/* -------------------------------------------------------------------------------------------------
    Your JavaScript Files
------------------------------------------------------------------------------------------------- */
var headerJS = [
    'node_modules/aos/dist/aos.js'
];
var footerJS = [
    'node_modules/jquery/dist/jquery.js',
    'src/assets/js/**'
];
//--------------------------------------------------------------------------------------------------
/* -------------------------------------------------------------------------------------------------
    Start of Build Tasks
------------------------------------------------------------------------------------------------- */
gulp.task('build-dev', [
    'style-dev',
    'copy-images',
    'copy-fonts',
    'header-scripts-dev',
    'footer-scripts-dev',
    'process-static-files-dev',
    'watch'
], function () {
    browserSync.init({
        server: {
            baseDir: "app"
        }
    });
});

gulp.task('build-prod', [
    'style-prod',
    'copy-images',
    'copy-fonts',
    'header-scripts-prod',
    'footer-scripts-prod',
    'process-images',
    'process-static-files-prod'
]);

gulp.task('default');

gulp.task('process-static-files-dev', function () {
    return gulp.src(['src/*.html'])
        .pipe(plumber({ errorHandler: onError }))
        .pipe(fileinclude({
            filters: {
                prefix: '@@',
                basepath: '@file'
            }
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('process-static-files-prod', function () {
    return gulp.src(['src/*.html'])
        .pipe(plumber({ errorHandler: onError }))
        .pipe(fileinclude({
            filters: {
                prefix: '@@',
                basepath: '@file'
            }
        }))
        .pipe(htmlmin({
            collapseWhitespace: true,
            ignoreCustomFragments: [/<%[\s\S]*?%>/, /<\?[=|php]?[\s\S]*?\?>/]
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('footer-scripts-dev', function () {
    return gulp.src(footerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('bundle.js'))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

/* NOTE: On header scripts babel is not executed */
gulp.task('header-scripts-dev', function () {
    return gulp.src(headerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(concat('top.js'))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

gulp.task('footer-scripts-prod', function () {
    return gulp.src(footerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('bundle.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

/* NOTE: On header scripts babel is not executed */
gulp.task('header-scripts-prod', function () {
    return gulp.src(headerJS)
        .pipe(plumber({ errorHandler: onError }))
        .pipe(concat('top.js'))
        .pipe(uglify())
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest('app/assets/js'));
});

gulp.task('copy-fonts', function () {
    return gulp.src('src/assets/fonts/**')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(gulp.dest('app/assets/fonts'));
});

gulp.task('copy-images', function () {
    return gulp.src('src/assets/img/**')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(gulp.dest('app/assets/img'));
});

gulp.task('process-images', function (cb) {
    return gulp.src('src/assets/img/**')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(imagemin())
        .pipe(gulp.dest('app/assets/img'));
});

gulp.task('style-dev', function () {
    return gulp.src('src/assets/style/main.css')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(postcss(plugins))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('app/assets/css'))
        .pipe(browserSync.stream({match: '**/*.css'}));
});

gulp.task('style-prod', function () {
    return gulp.src('src/assets/style/main.css')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(postcss(plugins))
        .pipe(gulp.dest('app/assets/css'));
});

var onError = function (err) {
    gutil.beep();
    console.log(err.toString());
    this.emit('end');
};

var reload = browserSync.reload();

gulp.task('reload-js', ['footer-scripts-dev'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('reload-images', ['copy-images'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('reload-fonts', ['copy-fonts'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('reload-files', ['process-static-files-dev'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('watch', function () {
    gulp.watch(['src/assets/style/**/*.css'], ['style-dev']);
    gulp.watch(['src/assets/js/**'], ['reload-js']);
    gulp.watch(['src/assets/img/**'], ['reload-images']);
    gulp.watch(['src/assets/fonts/**'], ['reload-fonts']);
    gulp.watch(['src/*.html', 'src/includes/**'], ['reload-files']);
});
/* -------------------------------------------------------------------------------------------------
    End of Build Tasks
------------------------------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>define(function(require) {

    'use strict';

    var Texture = require('../Texture');
    var Texture2D = require('../texture/Texture2D');
    var TextureCube = require('../texture/TextureCube');
    var request = require('../core/request');
    var EnvironmentMapPass = require('../prePass/EnvironmentMap');
    var Skydome = require('../plugin/Skydome');
    var Scene = require('../Scene');

    var dds = require('./dds');
    var hdr = require('./hdr');

    var environmentMapPass = new EnvironmentMapPass();

    /**
     * @namespace qtek.util.texture
     */
    var textureUtil = {
        /**
         * @param  {string|object} path
         * @param  {Function} [onsuccess]
         * @param  {Function} [onerror]
         * @return {qtek.Texture}
         *
         * @memberOf qtek.util.texture
         */
        loadTexture : function(path, onsuccess, onerror) {
            var texture;
            if (typeof(path) === 'string') {
                if (path.match(/.hdr$/)) {
                    texture = new Texture2D({
                        width : 0,
                        height : 0
                    });
                    textureUtil._fetchTexture(
                        path,
                        function (data) {
                            hdr.parseRGBE(data, texture);
                            texture.dirty();
                            onsuccess && onsuccess(texture);
                        },
                        onerror
                    );
                    return texture;
                } else if (path.match(/.dds$/)) {
                    texture = new Texture2D({
                        width : 0,
                        height : 0
                    });
                    textureUtil._fetchTexture(
                        path,
                        function (data) {
                            dds.parse(data, texture);
                            texture.dirty();
                            onsuccess && onsuccess(texture);
                        },
                        onerror
                    );
                } else {
                    texture = new Texture2D();
                    texture.load(path);
                    texture.success(onsuccess);
                    texture.error(onerror);
                }
            } else if (typeof(path) == 'object' && typeof(path.px) !== 'undefined') {
                var texture = new TextureCube();
                texture.load(path);
                texture.success(onsuccess);
                texture.error(onerror);
            }
            return texture;
        },

        /**
         * Load a panorama texture and render it to a cube map
         * @param  {string} path
         * @param  {qtek.texture.TextureCube} cubeMap
         * @param  {qtek.Renderer} renderer
         * @param  {Function} [onsuccess]
         * @param  {Function} [onerror]
         *
         * @memberOf qtek.util.texture
         */
        loadPanorama : function(path, cubeMap, renderer, onsuccess, onerror) {
            var self = this;
            textureUtil.loadTexture(path, function(texture) {
                // PENDING
                texture.flipY = false;
                self.panoramaToCubeMap(texture, cubeMap, renderer);
                texture.dispose(renderer.gl);
                onsuccess && onsuccess(cubeMap);
            }, onerror);
        },

        /**
         * Render a panorama texture to a cube map
         * @param  {qtek.texture.Texture2D} panoramaMap
         * @param  {qtek.texture.TextureCube} cubeMap
         * @param  {qtek.Renderer} renderer
         *
         * @memberOf qtek.util.texture
         */
        panoramaToCubeMap : function(panoramaMap, cubeMap, renderer) {
            var skydome = new Skydome({
                scene : new Scene()
            });
            skydome.material.set('diffuseMap', panoramaMap);
            environmentMapPass.texture = cubeMap;
            environmentMapPass.render(renderer, skydome.scene);
            environmentMapPass.texture = null;
            return cubeMap;
        },

        _fetchTexture : function(path, onsuccess, onerror) {
            request.get({
                url : path,
                responseType : 'arraybuffer',
                onload : onsuccess,
                onerror : onerror
            });
        },

        /**
         * Create a chessboard texture
         * @param  {number} [size]
         * @param  {number} [unitSize]
         * @param  {string} [color1]
         * @param  {string} [color2]
         * @return {qtek.texture.Texture2D}
         *
         * @memberOf qtek.util.texture
         */
        createChessboard : function(size, unitSize, color1, color2) {
            size = size || 512;
            unitSize = unitSize || 64;
            color1 = color1 || 'black';
            color2 = color2 || 'white';

            var repeat = Math.ceil(size / unitSize);

            var canvas = document.createElement('canvas');
            canvas.width = size;
            canvas.height = size;
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = color2;
            ctx.fillRect(0, 0, size, size);

            ctx.fillStyle = color1;
            for (var i = 0; i < repeat; i++) {
                for (var j = 0; j < repeat; j++) {
                    var isFill = j % 2 ? (i % 2) : (i % 2 - 1);
                    if (isFill) {
                        ctx.fillRect(i * unitSize, j * unitSize, unitSize, unitSize);
                    }
                }
            }

            var texture = new Texture2D({
                image : canvas,
                anisotropic : 8
            });

            return texture;
        },

        /**
         * Create a blank pure color 1x1 texture
         * @param  {string} color
         * @return {qtek.texture.Texture2D}
         *
         * @memberOf qtek.util.texture
         */
        createBlank : function(color) {
            var canvas = document.createElement('canvas');
            canvas.width = 1;
            canvas.height = 1;
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = color;
            ctx.fillRect(0, 0, 1, 1);

            var texture = new Texture2D({
                image : canvas
            });

            return texture;
        }
    };

    return textureUtil;
});<commit_msg>More robust panoramaToCubeMap<commit_after>define(function(require) {

    'use strict';

    var Texture = require('../Texture');
    var Texture2D = require('../texture/Texture2D');
    var TextureCube = require('../texture/TextureCube');
    var request = require('../core/request');
    var EnvironmentMapPass = require('../prePass/EnvironmentMap');
    var Skydome = require('../plugin/Skydome');
    var Scene = require('../Scene');

    var dds = require('./dds');
    var hdr = require('./hdr');

    /**
     * @namespace qtek.util.texture
     */
    var textureUtil = {
        /**
         * @param  {string|object} path
         * @param  {Function} [onsuccess]
         * @param  {Function} [onerror]
         * @return {qtek.Texture}
         *
         * @memberOf qtek.util.texture
         */
        loadTexture : function(path, onsuccess, onerror) {
            var texture;
            if (typeof(path) === 'string') {
                if (path.match(/.hdr$/)) {
                    texture = new Texture2D({
                        width : 0,
                        height : 0
                    });
                    textureUtil._fetchTexture(
                        path,
                        function (data) {
                            hdr.parseRGBE(data, texture);
                            texture.dirty();
                            onsuccess && onsuccess(texture);
                        },
                        onerror
                    );
                    return texture;
                } else if (path.match(/.dds$/)) {
                    texture = new Texture2D({
                        width : 0,
                        height : 0
                    });
                    textureUtil._fetchTexture(
                        path,
                        function (data) {
                            dds.parse(data, texture);
                            texture.dirty();
                            onsuccess && onsuccess(texture);
                        },
                        onerror
                    );
                } else {
                    texture = new Texture2D();
                    texture.load(path);
                    texture.success(onsuccess);
                    texture.error(onerror);
                }
            } else if (typeof(path) == 'object' && typeof(path.px) !== 'undefined') {
                var texture = new TextureCube();
                texture.load(path);
                texture.success(onsuccess);
                texture.error(onerror);
            }
            return texture;
        },

        /**
         * Load a panorama texture and render it to a cube map
         * @param  {string} path
         * @param  {qtek.texture.TextureCube} cubeMap
         * @param  {qtek.Renderer} renderer
         * @param  {Function} [onsuccess]
         * @param  {Function} [onerror]
         *
         * @memberOf qtek.util.texture
         */
        loadPanorama : function(path, cubeMap, renderer, onsuccess, onerror) {
            var self = this;
            textureUtil.loadTexture(path, function(texture) {
                // PENDING
                texture.flipY = false;
                self.panoramaToCubeMap(texture, cubeMap, renderer);
                texture.dispose(renderer.gl);
                onsuccess && onsuccess(cubeMap);
            }, onerror);
        },

        /**
         * Render a panorama texture to a cube map
         * @param  {qtek.texture.Texture2D} panoramaMap
         * @param  {qtek.texture.TextureCube} cubeMap
         * @param  {qtek.Renderer} renderer
         *
         * @memberOf qtek.util.texture
         */
        panoramaToCubeMap : function(panoramaMap, cubeMap, renderer) {
            var environmentMapPass = new EnvironmentMapPass();
            var skydome = new Skydome({
                scene : new Scene()
            });
            skydome.material.set('diffuseMap', panoramaMap);
            environmentMapPass.texture = cubeMap;
            environmentMapPass.render(renderer, skydome.scene);
            environmentMapPass.texture = null;
            environmentMapPass.dispose(renderer.gl);
            return cubeMap;
        },

        _fetchTexture : function(path, onsuccess, onerror) {
            request.get({
                url : path,
                responseType : 'arraybuffer',
                onload : onsuccess,
                onerror : onerror
            });
        },

        /**
         * Create a chessboard texture
         * @param  {number} [size]
         * @param  {number} [unitSize]
         * @param  {string} [color1]
         * @param  {string} [color2]
         * @return {qtek.texture.Texture2D}
         *
         * @memberOf qtek.util.texture
         */
        createChessboard : function(size, unitSize, color1, color2) {
            size = size || 512;
            unitSize = unitSize || 64;
            color1 = color1 || 'black';
            color2 = color2 || 'white';

            var repeat = Math.ceil(size / unitSize);

            var canvas = document.createElement('canvas');
            canvas.width = size;
            canvas.height = size;
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = color2;
            ctx.fillRect(0, 0, size, size);

            ctx.fillStyle = color1;
            for (var i = 0; i < repeat; i++) {
                for (var j = 0; j < repeat; j++) {
                    var isFill = j % 2 ? (i % 2) : (i % 2 - 1);
                    if (isFill) {
                        ctx.fillRect(i * unitSize, j * unitSize, unitSize, unitSize);
                    }
                }
            }

            var texture = new Texture2D({
                image : canvas,
                anisotropic : 8
            });

            return texture;
        },

        /**
         * Create a blank pure color 1x1 texture
         * @param  {string} color
         * @return {qtek.texture.Texture2D}
         *
         * @memberOf qtek.util.texture
         */
        createBlank : function(color) {
            var canvas = document.createElement('canvas');
            canvas.width = 1;
            canvas.height = 1;
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = color;
            ctx.fillRect(0, 0, 1, 1);

            var texture = new Texture2D({
                image : canvas
            });

            return texture;
        }
    };

    return textureUtil;
});<|endoftext|>


<commit_before>var errors = require('./errors');

var request      = require('request'),
    FormData     = require('form-data'),
    createSchema = require('json-gate').createSchema;

require('sugar');

var url     = require('url');

var VcapClient = module.exports = function (info, callback) {
    /**
     * VCAP cloudfoundry client.
     *
     * Parameters
     *
     * - info: object containing the following
     *   - host (required): host of CF deployment
     *   - one of either:
     *     - token (access token)
     *     - email,password (two separate fields)
     */

    var self = this,
        token = info.token;

    if (! info.host) {
        return new TypeError('host must be provided');
    }

    if (! token) {
        if (! info.email || ! info.password) {
            var error =
                new TypeError('info must include host, email, and password');

            if (callback) {
                return callback(error);
            }

            throw error;
        }
    }

    var isSuccess = function (code) {
        return (code - (code % 200)) === 200;
    };

    var getPath = function () {
        var path = [].slice.call(arguments).filter(function (each) {
            return each;
        }).join('/');

        return url.format({
            protocol: 'https:',
            hostname: info.host,
            pathname: path
        });
    };

    var makeRequest = function (uri, method, json, callback) {
        if (typeof json === 'function') {
            callback = json;
            json = true;
        }

        var options = {
            uri: uri,
            method: method,
            json: json
        };

        if (token) {
            options.headers = {
                Authorization: token
            };
        }

        return request(options, function (err, resp, body) {
            if (err) {
                return callback(err);
            }

            if (isSuccess(resp.statusCode)) {
                return callback(null, body);
            }

            return callback(errors.get(resp));
        });
    };

    var authedRequest = function (uri, method, json, callback) {
        if (token) {
            return makeRequest(uri, method, json, callback);
        }

        login(function (err) {
            if (err) {
                callback(err);
                return;
            }

            return makeRequest(uri, method, json, callback);
        });
    };

    var login = function (callback) {
        makeRequest(getPath('users', info.email, 'tokens'), 'POST', { password:
            info.password }, function (err, result) {
            if (err) {
                return callback(err);
            }

            token = result.token;
            callback();
        });
    };

    var setAppState = function (name, state, callback) {
        self.apps.get(name, function (err, app) {
            if (err) {
                return callback(err);
            }

            if (app.state === state) {
                return callback();
            }

            app.state = state;
            self.apps.update(app, callback);
        });
    };

    var Collection = function (idField, collection, schema) {
        schema = schema && createSchema(schema);

            authedRequest(getPath('apps', name), 'GET', true, callback);
        },

        create: function (manifest, callback) {
            authedRequest(getPath('apps'), 'POST', manifest, function (err) {
                callback(err); // omit CF body
            });
        },

        upload: function (name, zipFile, callback) {
            var form = new FormData();
            form.append('application', require('fs').createReadStream(zipFile));
            form.append('_method', 'put');
            form.append('resources', '[]');

            form.getLength(function (err, length) {
                if (err) {
                    return callback(err);
                }

                var request = authedRequest(getPath('apps', name,
                        'application'), 'POST', true, callback);

                request.setHeader('Content-Length', length);
                request._form = form;
            });
        },

        update: function (app, callback) {
            authedRequest(getPath('apps', app.name), 'PUT', app, callback);
        },

        this.create = function (body, callback) {
            if (schema) {
                try {
                    schema.validate(body);
                } catch (err) {
                    return callback(err);
                }
            }

                self.start(name, callback);
            });
        },

        stop: function (name, callback) {
            setAppState(name, 'STOPPED', callback);
        },

        start: function (name, callback) {
            setAppState(name, 'STARTED', callback);
        },

        delete: function (name, callback) {
            authedRequest(getPath('apps', name), 'DELETE', true, callback);
        },
    };

    this.services = {
        get: function (name, callback) {
            if (typeof name === 'function') {
                callback = name;
                name = null;
            }

            authedRequest(getPath('services', name), 'GET', callback);
        },

        create: function (name, vendor, version, tier, callback) {
            authedRequest(getPath('services'), 'POST', {
                name:    name,
                vendor:  vendor,
                version: version,
                tier:    tier
            }, callback);
        },

        delete: function (name, callback) {
            authedRequest(getPath('services', name), 'DELETE', callback);
        }
    };

    if (callback) {
        login(callback);
    }
};
<commit_msg>Use v2 endpoints<commit_after>var errors = require('./errors');

var request      = require('request'),
    FormData     = require('form-data'),
    createSchema = require('json-gate').createSchema;

require('sugar');

var url     = require('url');

var VcapClient = module.exports = function (info, callback) {
    /**
     * VCAP cloudfoundry client.
     *
     * Parameters
     *
     * - info: object containing the following
     *   - host (required): host of CF deployment
     *   - one of either:
     *     - token (access token)
     *     - email,password (two separate fields)
     */

    var self = this,
        token = info.token;

    if (! info.host) {
        return new TypeError('host must be provided');
    }

    if (! token) {
        if (! info.email || ! info.password) {
            var error =
                new TypeError('info must include host, email, and password');

            if (callback) {
                return callback(error);
            }

            throw error;
        }
    }

    var isSuccess = function (code) {
        return (code - (code % 200)) === 200;
    };

    var getPath = function () {
        var path = [].slice.call(arguments).filter(function (each) {
            return each;
        }).join('/');

        return url.format({
            protocol: 'http:',
            hostname: info.host,
            pathname: 'v2/' + path
        });
    };

    var makeRequest = function (uri, method, json, callback) {
        if (typeof json === 'function') {
            callback = json;
            json = true;
        }

        var options = {
            uri: uri,
            method: method,
            json: json
        };

        if (token) {
            options.headers = {
                Authorization: token
            };
        }

        return request(options, function (err, resp, body) {
            if (err) {
                return callback(err);
            }

            if (isSuccess(resp.statusCode)) {
                return callback(null, body);
            }

            return callback(errors.get(resp));
        });
    };

    var authedRequest = function (uri, method, json, callback) {
        if (token) {
            return makeRequest(uri, method, json, callback);
        }

        login(function (err) {
            if (err) {
                callback(err);
                return;
            }

            return makeRequest(uri, method, json, callback);
        });
    };

    var login = function (callback) {
        makeRequest(getPath('users', info.email, 'tokens'), 'POST', { password:
            info.password }, function (err, result) {
            if (err) {
                return callback(err);
            }

            token = result.token;
            callback();
        });
    };

    var setAppState = function (name, state, callback) {
        self.apps.get(name, function (err, app) {
            if (err) {
                return callback(err);
            }

            if (app.state === state) {
                return callback();
            }

            app.state = state;
            self.apps.update(app, callback);
        });
    };

    var Collection = function (idField, collection, schema) {
        schema = schema && createSchema(schema);

            authedRequest(getPath('apps', name), 'GET', true, callback);
        },

        create: function (manifest, callback) {
            authedRequest(getPath('apps'), 'POST', manifest, function (err) {
                callback(err); // omit CF body
            });
        },

        upload: function (name, zipFile, callback) {
            var form = new FormData();
            form.append('application', require('fs').createReadStream(zipFile));
            form.append('_method', 'put');
            form.append('resources', '[]');

            form.getLength(function (err, length) {
                if (err) {
                    return callback(err);
                }

                var request = authedRequest(getPath('apps', name,
                        'application'), 'POST', true, callback);

                request.setHeader('Content-Length', length);
                request._form = form;
            });
        },

        update: function (app, callback) {
            authedRequest(getPath('apps', app.name), 'PUT', app, callback);
        },

        this.create = function (body, callback) {
            if (schema) {
                try {
                    schema.validate(body);
                } catch (err) {
                    return callback(err);
                }
            }

                self.start(name, callback);
            });
        },

        stop: function (name, callback) {
            setAppState(name, 'STOPPED', callback);
        },

        start: function (name, callback) {
            setAppState(name, 'STARTED', callback);
        },

        delete: function (name, callback) {
            authedRequest(getPath('apps', name), 'DELETE', true, callback);
        },
    };

    this.services = {
        get: function (name, callback) {
            if (typeof name === 'function') {
                callback = name;
                name = null;
            }

            authedRequest(getPath('services', name), 'GET', callback);
        },

        create: function (name, vendor, version, tier, callback) {
            authedRequest(getPath('services'), 'POST', {
                name:    name,
                vendor:  vendor,
                version: version,
                tier:    tier
            }, callback);
        },

        delete: function (name, callback) {
            authedRequest(getPath('services', name), 'DELETE', callback);
        }
    };

    if (callback) {
        login(callback);
    }
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    path = require('path'),
    plugins = require('gulp-load-plugins')(),
    stylish = require('jshint-stylish'),
    lodash = require('lodash'),
    Q = require('q'),
    runSequence = require('run-sequence'),
    java_path = path.resolve('node_modules/closurecompiler/jre/bin');
    process.env.PATH = java_path + ':' + process.env.PATH,
    paths = {
      tmp: '.gulptmp/',
      dest: 'cla_frontend/assets/',
      src: 'cla_frontend/assets-src/',
      icons: [],
      images: [],
      fonts: [],
      styles: [],
      ng_partials: [],
      vendor_static: [],
      scripts: {},
      guidance: []
    };

// styles
paths.styles.push(paths.src + 'stylesheets/**/*.scss');
// icons
paths.icons.push(paths.src + 'fonts/svg-icons/*.svg');
// fonts
paths.fonts.push(paths.src + 'fonts/*.{eot,svg,ttf,woff}');
paths.fonts.push(paths.tmp + 'fonts/*.{eot,svg,ttf,woff}');
// images
paths.images.push(paths.src + 'images/**/*');
// partials
paths.ng_partials.push(paths.src + 'javascripts/app/partials/**/*.html');
// partials
paths.vendor_static.push(paths.src + 'javascripts/vendor/**/*');
// scripts
paths.scripts = {
  vendor: [
    paths.src + 'vendor/lodash/dist/lodash.min.js',
    paths.src + 'vendor/jquery/dist/jquery.min.js',
    // angular specific
    paths.src + 'vendor/angular/angular.js',
    paths.src + 'vendor/angular-sanitize/angular-sanitize.js',
    paths.src + 'vendor/angular-animate/angular-animate.js',
    paths.src + 'vendor/angular-sticky/sticky.js',
    paths.src + 'vendor/angular-resource/angular-resource.js',
    paths.src + 'vendor/angular-ui-router/release/angular-ui-router.js',
    paths.src + 'vendor/angular-ui-select/dist/select.js',
    paths.src + 'vendor/angular-multi-select/angular-multi-select.js',
    paths.src + 'vendor/angular-i18n/angular-locale_en-gb.js',
    paths.src + 'vendor/moment/moment.js',
    paths.src + 'vendor/angular-moment/angular-moment.js',
    paths.src + 'vendor/lunr.js/lunr.js',
    paths.src + 'javascripts/vendor/xeditable.js',
    paths.src + 'javascripts/vendor/ui-bootstrap-custom-tpls-0.10.0.js'
  ],
  app: [
    paths.src + 'javascripts/app/js/app.js',
    paths.tmp + 'javascripts/app/partials/**/*', // dynamically generated by gulp task (ng-templates)
    paths.src + 'javascripts/app/js/**/*.js',
    paths.tmp + 'javascripts/app/js/constants.js' // dynamically generated by gulp task (ng-constants)
  ]
};
paths.guidance.push(paths.src + 'guidance/**/*.md');

// clean out assets folder
gulp.task('clean-pre', function() {
  return gulp
    .src([paths.dest, paths.tmp], {read: false})
    .pipe(plugins.clean());
});
gulp.task('clean-post', function() {
  return gulp
    .src(paths.tmp, {read: false})
    .pipe(plugins.clean());
});

// copy across web fonts
gulp.task('iconfont', ['sass-copy'], function(cb) {
  var fontName = 'cla-icons';

  return gulp.src(paths.icons)
    .pipe(plugins.iconfontCss({
      fontName: fontName,
      path: paths.src + 'stylesheets/_icons.scss',
      targetPath: '../stylesheets/_icons.scss',
      fontPath: '../fonts/'
    }))
    .pipe(plugins.iconfont({ fontName: fontName }))
    .on('codepoints', function(codepoints) {
      var options = {
        glyphs: codepoints,
        fontName: fontName,
        className: 'Icon'
      };
      // create template containing all fonts
      gulp.src(paths.src + 'fonts/icon-template.html')
        .pipe(plugins.consolidate('lodash', options))
        .pipe(plugins.rename({ basename: fontName }))
        .pipe(gulp.dest(paths.dest + 'fonts/'));
    })
    .pipe(gulp.dest(paths.tmp + 'fonts/'));
});
// copy fonts
gulp.task('fonts', ['iconfont'], function(cb) {
  gulp.src(paths.fonts)
    .pipe(gulp.dest(paths.dest + 'fonts/'));
});

// copy & compile scss
gulp.task('sass-copy', function() {
  return gulp
    .src(paths.styles)
    .pipe(gulp.dest(paths.tmp + 'stylesheets/'));
});
gulp.task('sass', ['iconfont'], function() {
  gulp
    .src(paths.tmp + 'stylesheets/**/*.scss')
    .pipe(plugins.rubySass({
      loadPath: 'node_modules/govuk_frontend_toolkit/' // add node module toolkit path
    }))
    .on('error', function (err) { console.log(err.message); })
    .pipe(gulp.dest(paths.dest + 'stylesheets/'));
});

// optimise images
gulp.task('images', function() {
  gulp
    .src(paths.images)
    .pipe(plugins.imagemin({optimizationLevel: 5}))
    .pipe(gulp.dest(paths.dest + 'images'));
});

// static vendor files
gulp.task('vendor', function() {
  gulp
    .src(paths.vendor_static)
    .pipe(gulp.dest(paths.dest + 'javascripts/vendor/'));
});

// convert django cla_common constants into angular constants
gulp.task('ng-constants', function () {
  return gulp
    .src(paths.src + 'javascripts/app/constants.json')
    .pipe(plugins.ngConstant({
      name: 'cla.constants'
    }))
    // Writes config.js to dist folder
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/js/'));
});

// angular partials
gulp.task('ng-templates', function(){
  return gulp.src(paths.ng_partials)
    .pipe(plugins.angularTemplates({module: 'cla.templates'}))
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/partials/'));
});

// concat js files
gulp.task('js-concat', ['ng-constants', 'ng-templates'], function() {
  var concat = paths.scripts.vendor
                  .concat(paths.scripts.app);

  return gulp
    .src(concat)
    .pipe(plugins.concat('cla.main.js'))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

gulp.task('js-compile', ['js-concat'], function(){
  var src_path = paths.dest + 'javascripts/cla.main.js';

  return gulp.src(src_path)
    .pipe(plugins.closureCompiler({
      compilerPath: 'node_modules/closurecompiler/compiler/compiler.jar',
      fileName: 'cla.main.min.js',
      compilerFlags: {
        language_in: 'ECMASCRIPT5',
        warning_level: 'QUIET',
        compilation_level: 'WHITESPACE_ONLY',
      }
    }))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

// jshint js code
gulp.task('lint', function() {
  var lint = paths.scripts.app
                  .concat(['!' + paths.tmp + 'javascripts/app/partials/**/*']);

  gulp
    .src(lint)
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter(stylish));
});

gulp.task('guidance-build', function() {
  var lunr = require('lunr'),
      gutil = require('gulp-util'),
      path = require('path'),
      through2 = require('through2'),
      fs = require('fs'),
      S = require('string'),
      index;

  index = lunr(function () {
    this.field('title', {boost: 10});
    this.field('tags', {boost: 8});
    this.field('body');
    this.ref('id');
  })
  index._claTitles = {};

  gulp.src(paths.guidance)
    .pipe(plugins.markdownToJson())
    .pipe(through2.obj(function (file, enc, callback) {
        // adding to index
      var jsonFile = JSON.parse(file.contents.toString()),
          fileName = path.basename(file.path, '.json');

      index.add({
        id: fileName,
        title: jsonFile.title,
        tags: jsonFile.tags,
        body: S(jsonFile.body).stripTags()
      });

      // non-standard thing
      index._claTitles[fileName] = jsonFile.title;

      // creating output file
      outputFile = new gutil.File({
        base: path.dirname(file.path),
        path: path.join(path.dirname(file.path), fileName+'.html'),
        contents: new Buffer(jsonFile.body)
      });

      this.push(outputFile);
      callback();
    }))
    .pipe(gulp.dest(paths.dest + 'guidance'))
    .pipe(gutil.buffer())
    .pipe(through2.obj(function (input, enc, callback) {
      var outputFile = fs.openSync(paths.dest + 'javascripts/guidance_index.json', 'w+'),
          indexJSON = index.toJSON();

      // non-standard thing
      indexJSON['_claTitles'] = index._claTitles;

      fs.writeSync(outputFile, JSON.stringify(indexJSON));
      fs.closeSync(outputFile);
    }));
});

// setup watches
gulp.task('watch', function() {
  var lr = require('gulp-livereload');
  lr.listen();

  gulp.watch(paths.fonts, ['fonts']);
  gulp.watch(paths.styles, ['sass']);
  gulp.watch(paths.icons, ['sass']);
  gulp.watch(paths.images, ['images']);
  gulp.watch(paths.vendor_static, ['vendor']);
  gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
  gulp.watch(paths.guidance, ['guidance-build']);
  // watch built files and send reload event
  gulp.watch(paths.dest + '**/*').on('change', lr.changed);
});

// setup default task
gulp.task('default', ['build']);
// run build
gulp.task('build', function() {
  runSequence('clean-pre', ['sass', 'fonts', 'images', 'vendor', 'guidance-build', 'lint', 'js-compile']);
});
<commit_msg>Don't load Q npm package as no longer installed<commit_after>var gulp = require('gulp'),
    path = require('path'),
    plugins = require('gulp-load-plugins')(),
    stylish = require('jshint-stylish'),
    lodash = require('lodash'),
    runSequence = require('run-sequence'),
    java_path = path.resolve('node_modules/closurecompiler/jre/bin');
    process.env.PATH = java_path + ':' + process.env.PATH,
    paths = {
      tmp: '.gulptmp/',
      dest: 'cla_frontend/assets/',
      src: 'cla_frontend/assets-src/',
      icons: [],
      images: [],
      fonts: [],
      styles: [],
      ng_partials: [],
      vendor_static: [],
      scripts: {},
      guidance: []
    };

// styles
paths.styles.push(paths.src + 'stylesheets/**/*.scss');
// icons
paths.icons.push(paths.src + 'fonts/svg-icons/*.svg');
// fonts
paths.fonts.push(paths.src + 'fonts/*.{eot,svg,ttf,woff}');
paths.fonts.push(paths.tmp + 'fonts/*.{eot,svg,ttf,woff}');
// images
paths.images.push(paths.src + 'images/**/*');
// partials
paths.ng_partials.push(paths.src + 'javascripts/app/partials/**/*.html');
// partials
paths.vendor_static.push(paths.src + 'javascripts/vendor/**/*');
// scripts
paths.scripts = {
  vendor: [
    paths.src + 'vendor/lodash/dist/lodash.min.js',
    paths.src + 'vendor/jquery/dist/jquery.min.js',
    // angular specific
    paths.src + 'vendor/angular/angular.js',
    paths.src + 'vendor/angular-sanitize/angular-sanitize.js',
    paths.src + 'vendor/angular-animate/angular-animate.js',
    paths.src + 'vendor/angular-sticky/sticky.js',
    paths.src + 'vendor/angular-resource/angular-resource.js',
    paths.src + 'vendor/angular-ui-router/release/angular-ui-router.js',
    paths.src + 'vendor/angular-ui-select/dist/select.js',
    paths.src + 'vendor/angular-multi-select/angular-multi-select.js',
    paths.src + 'vendor/angular-i18n/angular-locale_en-gb.js',
    paths.src + 'vendor/moment/moment.js',
    paths.src + 'vendor/angular-moment/angular-moment.js',
    paths.src + 'vendor/lunr.js/lunr.js',
    paths.src + 'javascripts/vendor/xeditable.js',
    paths.src + 'javascripts/vendor/ui-bootstrap-custom-tpls-0.10.0.js'
  ],
  app: [
    paths.src + 'javascripts/app/js/app.js',
    paths.tmp + 'javascripts/app/partials/**/*', // dynamically generated by gulp task (ng-templates)
    paths.src + 'javascripts/app/js/**/*.js',
    paths.tmp + 'javascripts/app/js/constants.js' // dynamically generated by gulp task (ng-constants)
  ]
};
paths.guidance.push(paths.src + 'guidance/**/*.md');

// clean out assets folder
gulp.task('clean-pre', function() {
  return gulp
    .src([paths.dest, paths.tmp], {read: false})
    .pipe(plugins.clean());
});
gulp.task('clean-post', function() {
  return gulp
    .src(paths.tmp, {read: false})
    .pipe(plugins.clean());
});

// copy across web fonts
gulp.task('iconfont', ['sass-copy'], function(cb) {
  var fontName = 'cla-icons';

  return gulp.src(paths.icons)
    .pipe(plugins.iconfontCss({
      fontName: fontName,
      path: paths.src + 'stylesheets/_icons.scss',
      targetPath: '../stylesheets/_icons.scss',
      fontPath: '../fonts/'
    }))
    .pipe(plugins.iconfont({ fontName: fontName }))
    .on('codepoints', function(codepoints) {
      var options = {
        glyphs: codepoints,
        fontName: fontName,
        className: 'Icon'
      };
      // create template containing all fonts
      gulp.src(paths.src + 'fonts/icon-template.html')
        .pipe(plugins.consolidate('lodash', options))
        .pipe(plugins.rename({ basename: fontName }))
        .pipe(gulp.dest(paths.dest + 'fonts/'));
    })
    .pipe(gulp.dest(paths.tmp + 'fonts/'));
});
// copy fonts
gulp.task('fonts', ['iconfont'], function(cb) {
  gulp.src(paths.fonts)
    .pipe(gulp.dest(paths.dest + 'fonts/'));
});

// copy & compile scss
gulp.task('sass-copy', function() {
  return gulp
    .src(paths.styles)
    .pipe(gulp.dest(paths.tmp + 'stylesheets/'));
});
gulp.task('sass', ['iconfont'], function() {
  gulp
    .src(paths.tmp + 'stylesheets/**/*.scss')
    .pipe(plugins.rubySass({
      loadPath: 'node_modules/govuk_frontend_toolkit/' // add node module toolkit path
    }))
    .on('error', function (err) { console.log(err.message); })
    .pipe(gulp.dest(paths.dest + 'stylesheets/'));
});

// optimise images
gulp.task('images', function() {
  gulp
    .src(paths.images)
    .pipe(plugins.imagemin({optimizationLevel: 5}))
    .pipe(gulp.dest(paths.dest + 'images'));
});

// static vendor files
gulp.task('vendor', function() {
  gulp
    .src(paths.vendor_static)
    .pipe(gulp.dest(paths.dest + 'javascripts/vendor/'));
});

// convert django cla_common constants into angular constants
gulp.task('ng-constants', function () {
  return gulp
    .src(paths.src + 'javascripts/app/constants.json')
    .pipe(plugins.ngConstant({
      name: 'cla.constants'
    }))
    // Writes config.js to dist folder
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/js/'));
});

// angular partials
gulp.task('ng-templates', function(){
  return gulp.src(paths.ng_partials)
    .pipe(plugins.angularTemplates({module: 'cla.templates'}))
    .pipe(gulp.dest(paths.tmp + 'javascripts/app/partials/'));
});

// concat js files
gulp.task('js-concat', ['ng-constants', 'ng-templates'], function() {
  var concat = paths.scripts.vendor
                  .concat(paths.scripts.app);

  return gulp
    .src(concat)
    .pipe(plugins.concat('cla.main.js'))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

gulp.task('js-compile', ['js-concat'], function(){
  var src_path = paths.dest + 'javascripts/cla.main.js';

  return gulp.src(src_path)
    .pipe(plugins.closureCompiler({
      compilerPath: 'node_modules/closurecompiler/compiler/compiler.jar',
      fileName: 'cla.main.min.js',
      compilerFlags: {
        language_in: 'ECMASCRIPT5',
        warning_level: 'QUIET',
        compilation_level: 'WHITESPACE_ONLY',
      }
    }))
    .pipe(gulp.dest(paths.dest + 'javascripts/'));
});

// jshint js code
gulp.task('lint', function() {
  var lint = paths.scripts.app
                  .concat(['!' + paths.tmp + 'javascripts/app/partials/**/*']);

  gulp
    .src(lint)
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter(stylish));
});

gulp.task('guidance-build', function() {
  var lunr = require('lunr'),
      gutil = require('gulp-util'),
      path = require('path'),
      through2 = require('through2'),
      fs = require('fs'),
      S = require('string'),
      index;

  index = lunr(function () {
    this.field('title', {boost: 10});
    this.field('tags', {boost: 8});
    this.field('body');
    this.ref('id');
  })
  index._claTitles = {};

  gulp.src(paths.guidance)
    .pipe(plugins.markdownToJson())
    .pipe(through2.obj(function (file, enc, callback) {
        // adding to index
      var jsonFile = JSON.parse(file.contents.toString()),
          fileName = path.basename(file.path, '.json');

      index.add({
        id: fileName,
        title: jsonFile.title,
        tags: jsonFile.tags,
        body: S(jsonFile.body).stripTags()
      });

      // non-standard thing
      index._claTitles[fileName] = jsonFile.title;

      // creating output file
      outputFile = new gutil.File({
        base: path.dirname(file.path),
        path: path.join(path.dirname(file.path), fileName+'.html'),
        contents: new Buffer(jsonFile.body)
      });

      this.push(outputFile);
      callback();
    }))
    .pipe(gulp.dest(paths.dest + 'guidance'))
    .pipe(gutil.buffer())
    .pipe(through2.obj(function (input, enc, callback) {
      var outputFile = fs.openSync(paths.dest + 'javascripts/guidance_index.json', 'w+'),
          indexJSON = index.toJSON();

      // non-standard thing
      indexJSON['_claTitles'] = index._claTitles;

      fs.writeSync(outputFile, JSON.stringify(indexJSON));
      fs.closeSync(outputFile);
    }));
});

// setup watches
gulp.task('watch', function() {
  var lr = require('gulp-livereload');
  lr.listen();

  gulp.watch(paths.fonts, ['fonts']);
  gulp.watch(paths.styles, ['sass']);
  gulp.watch(paths.icons, ['sass']);
  gulp.watch(paths.images, ['images']);
  gulp.watch(paths.vendor_static, ['vendor']);
  gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
  gulp.watch(paths.guidance, ['guidance-build']);
  // watch built files and send reload event
  gulp.watch(paths.dest + '**/*').on('change', lr.changed);
});

// setup default task
gulp.task('default', ['build']);
// run build
gulp.task('build', function() {
  runSequence('clean-pre', ['sass', 'fonts', 'images', 'vendor', 'guidance-build', 'lint', 'js-compile']);
});
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * Views controller using deepjs tools and methods
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "deepjs/deep", "deepjs/lib/errors", "./directives"], function(require, deep, errors) {
"use strict";

	/**
	 * view refresh sequence : arg = route params
	 * 	if(!initialised)
	 * 		init()
	 * 	then
	 * 		load(params);
	 * 			deepLoad what, how, where
	 * 		render(loaded);
	 * 			how(context);
	 * 		 	where(context);
	 * 		  	enhance(context);
	 * 		   	done(context);
	 *
	 * View remove sequence :
	 * 		remove each subs
	 * 		remove each dp-controlled
	 * 		remove html node
	 * 		clean();
	 */

	deep.errors.View = function(msg, report, fileName, lineNum){
		if(typeof msg === 'object')
			report = msg;
		if(!msg)
			msg = "UIError";
		return errors.Error(1500, msg, report, fileName, lineNum);
	};

	deep.View = deep.Classes(function(layer) {
		if(layer)
			deep.aup(layer, this);
	}, {
		_deep_view_: true,
		fail: function(e) {
			deep.utils.dumpError(e);
			if (!this.where)
				return e;
			if (typeof this.where === 'string')
				return deep.nodes(this.where).done(function(s) {
					if (typeof s === 'function')
						s(e.toString());
					else
						$(s).replaceWith(e.toString());
					return e;
				});
			else if (typeof this.where === 'function')
				this.where(e.toString());
			else if (typeof jQuery !== 'undefined' && this.where instanceof jQuery) // WARNING : cheerio case not managed
				$(this.where).html(e.toString());
		},
		addSubControlled:function(ctrl){
			var label = "view" + Date.now().valueOf();
			this._deep_controlled_ = this._deep_controlled_ || {};
			this._deep_controlled_[label] = ctrl;
		},
		remove: function() {
			//console.log("VIEW REMOVE : ", this.placed);
			if (this.subs)
				for (var i in this.subs)
					this.subs[i].remove();
			if (this._deep_controlled_) {
				for (var i in this._deep_controlled_)
					this._deep_controlled_[i].remove();
				this._deep_controlled_ = null;
			}
			if (this.placed)
			{
				// console.log("remove node : ", this, this.placed())
				deep.$(this.placed()).remove();
			}
			if (this.clean)
				this.clean();
			this.initialised = false;
			this.placed = null;
		},
		load: function(opt) {
			opt = opt || {};
			var params = opt.params;
			var config = this.config || {};
			//if (params && Object.keys(params).length === 0)
			//	params = null;
			if (config.scope && config.scope != "both")
				if (deep.context("isServer")) {
					if (config.scope != "server")
						return;
				} else
			if (config.scope != "browser")
				return;
			var self = this;
			if (this.init && (deep.Promise.context.concurrency || !this.initialised))
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.load({
							params: params
						});
					});
			if (this.condition === false)
				return null;
			var promises = [], ctx = { params:params, context:deep.context(), ctrl:self };
			if (this.condition)
				if (typeof this.condition === "function" && !this.condition.apply(ctx))
					return null;
			if (this.what)
				promises.push(deep.nodes(this).query("./what").deepLoad(ctx, false));
			else
				promises.push(null);

			if (typeof this.how === 'string')
				promises.push(deep.nodes(this).query("./how").deepLoad(ctx, false, true));
			else
				promises.push(this.how);

			if (this.where)
				if (typeof this.where === 'string')
					promises.push(deep.nodes(this).query("./where").deepLoad(ctx, false, true));
				else
					promises.push(this.where);

				// console.log("launch deep load");
			return deep.all(promises)
				.done(function(res) {
					//console.log("view deep load : res  : ", res);
					var result = {
						_deep_render_node_: true,
						what: res[0],
						how: res[1],
						where: res[2],
						params: params
					};
					// console.log("view deep load done : ", self.how);
					return result;
				})
				.fail(function(e) {
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				});
		},
		refresh: function(arg /* params, loaded, routeMatch */ ) {
			var config = this.config || {};
			if (config.scope && config.scope != "both")
				if (deep.isBrowser) {
					if (config.scope != "browser")
						return;
				} else
			if (config.scope != "server")
				return;
			// console.log("view refresh : params : ", params, " - loaded : ", loaded);
			var self = this;
			if (this.init && (deep.Promise.context.concurrency || !this.initialised))
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.refresh(arg);
					});
			var loaded, params, routeMatch;
			if (arg)
				if (arg._deep_render_node_) {
					loaded = arg;
					params = loaded.params;
				} else
			if (arg._deep_matched_node_) {
				loaded = arg.loaded;
				params = arg.output;

				routeMatch = arg;
			} else
				params = arg;
			params = params || this.params;
			if (params && deep.isBrowser)
				this.params = params;

			var render = function(loaded) {
				// console.log("view render : ", loaded)
				if (!loaded)
					return;
				if (self._deep_controlled_) {
					for (var i in self._deep_controlled_)
						self._deep_controlled_[i].remove();
					self._deep_controlled_ = null;
				}
				var what = null,
					how = null,
					where = null,
					rendered = null,
					placed = null;
				if (loaded.what)
					what = loaded.what;
				if (loaded.how)
					how = loaded.how;
				if (loaded.where)
					where = loaded.where;
				what = (what && what._deep_query_node_) ? what.value : what;
				how = (how && how._deep_query_node_) ? how.value : how;
				where = (where && where._deep_query_node_) ? where.value : where;

				if (what && what._deep_ocm_)
					what = what();
				if (how && how._deep_ocm_)
					how = how();
				if (where && where._deep_ocm_)
					where = where();

				loaded.what = what;
				loaded.how = how;
				loaded.where = where;
				loaded.params = params;

				placed = self.placed ? self.placed() : null;

				loaded.placed = placed;
				loaded.ctrl = self;
				// console.log("render with : how : ", how, what)
				try {
					//console.log("WHAT : ", what);
					// console.log("HOW : ", how);
					if (routeMatch) {
						loaded.route = routeMatch;
					}
					if (typeof how === 'function')
						rendered = loaded.rendered = how.call(self, loaded);
					else if(how)
						rendered = loaded.rendered = how;
					else if(what)
						rendered = loaded.rendered = what;
					if (where && typeof where === 'function')
						placed = loaded.placed = where.call(self, loaded.rendered, loaded.placed);
					else if (typeof jQuery !== 'undefined' && where instanceof jQuery)
						placed = loaded.placed = where;
					else if (typeof where === 'string' && deep.Promise.context.$)
						placed = loaded.placed = deep.Promise.context.$(where);
					/*else
						placed = loaded.placed = null;*/
				} catch (e) {
					// console.log("error while rendering :  ",e);
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				}

				if (placed && !deep.Promise.context.concurrency)
					self.placed = function() {
						// console.log("store placed : ", placed)
						return placed;
					};

				var promise = null;
				if (config.enhance !== false && placed && deep.Promise.context.$) {
					//console.log("view placed : placed = ", placed);
					if (placed._deep_html_merged_) {
						var subprom = [];
						for (var i in placed) {
							if (i === '_deep_html_merged_')
								continue;
							subprom.push(deep.ui.enhance(self, placed[i], loaded))
						}
						promise = deep.all(subprom);
					} else
						promise = deep.ui.enhance(self, placed, loaded);
				}

				//console.log("rendered : ", loaded);
				if (promise)
					return promise
						.done(function() {
							if(config.relink !== false && deep.isBrowser && placed && self.relink)
								self.relink(placed);
							if (typeof self.done === "function") {
								var done = self.done;
								if (done._deep_ocm_)
									done = done();
								return done.call(self, loaded) || loaded;
							}
							return loaded;
						})
						.fail(function(e) {
							if (typeof self.fail === 'function')
								return self.fail(e) || e;
							return e;
						});

				//if(config.relink == false)
				//	console.log("skip relink on : ", self);
				if(config.relink !== false && deep.isBrowser && placed && self.relink)
					self.relink(placed);
				if (typeof self.done === "function") {
					var done = self.done;
					if (done._deep_ocm_)
						done = done();
					return done.call(self, loaded) || loaded;
				}
				return loaded;
			};
			var p;
			if (loaded)
				p = deep.when(render(loaded))
					.fail(function(e) {
						if (typeof self.fail === 'function') {
							var fail = self.fail;
							if (fail._deep_ocm_)
								fail = fail();
							return fail.call(self, e) || e;
						}
					});
			else
				p = deep.when(this.load({
					params: params
				}))
					.done(function() {
						this.done(render)
							.fail(function(e) {
								if (typeof self.fail === 'function') {
									var fail = self.fail;
									if (fail._deep_ocm_)
										fail = fail();
									return fail.call(self, e) || e;
								}
							});
					});
			return p;
		},
		relink:function(selector){
			var app = deep.currentApp(), $ = deep.$();
			$(selector)
			.find(this.relinkSelector || "a")
			.each(function() {
				if (this._deep_rerouted_)
					return;
				this._deep_rerouted_ = true;

				var	uri = $(this).attr("href");
				if (!uri)
					return;
				if (uri.substring(0, 4) === 'http')
					return;
				if (uri[0] == '/' && uri[1] == '/') // file
					return;
				// console.log("RELINK : ", uri, this);
				$(this).click(function(e) {
					if(e && e.preventDefault)
						e.preventDefault();
					deep.app(app).when(app.views.get(uri)).elog();
					return false;
				});
			});
		}
	});

	deep.View.relink = function(selector, relinkSelector) {
		// console.log("relink : ", selector);
		return deep.View.prototype.relink.call({
			relinkSelector:relinkSelector
		}, selector);
	};
	deep.coreUnits = deep.coreUnits || [];
	deep.coreUnits.push("js::deep-views/units/views");
	return deep.View;
});<commit_msg> cocorrect deep.isBrowser in !deep.context("isServer") + no more deep.context("concurrency")<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * Views controller using deepjs tools and methods
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "deepjs/deep", "deepjs/lib/errors", "./directives"], function(require, deep, errors) {
"use strict";

	/**
	 * view refresh sequence : arg = route params
	 * 	if(!initialised)
	 * 		init()
	 * 	then
	 * 		load(params);
	 * 			deepLoad what, how, where
	 * 		render(loaded);
	 * 			how(context);
	 * 		 	where(context);
	 * 		  	enhance(context);
	 * 		   	done(context);
	 *
	 * View remove sequence :
	 * 		remove each subs
	 * 		remove each dp-controlled
	 * 		remove html node
	 * 		clean();
	 */

	deep.errors.View = function(msg, report, fileName, lineNum){
		if(typeof msg === 'object')
			report = msg;
		if(!msg)
			msg = "UIError";
		return errors.Error(1500, msg, report, fileName, lineNum);
	};

	deep.View = deep.Classes(function(layer) {
		if(layer)
			deep.aup(layer, this);
	}, {
		_deep_view_: true,
		fail: function(e) {
			deep.utils.dumpError(e);
			if (!this.where)
				return e;
			if (typeof this.where === 'string')
				return deep.nodes(this.where).done(function(s) {
					if (typeof s === 'function')
						s(e.toString());
					else
						$(s).replaceWith(e.toString());
					return e;
				});
			else if (typeof this.where === 'function')
				this.where(e.toString());
			else if (typeof jQuery !== 'undefined' && this.where instanceof jQuery) // WARNING : cheerio case not managed
				$(this.where).html(e.toString());
		},
		addSubControlled:function(ctrl){
			var label = "view" + Date.now().valueOf();
			this._deep_controlled_ = this._deep_controlled_ || {};
			this._deep_controlled_[label] = ctrl;
		},
		remove: function() {
			//console.log("VIEW REMOVE : ", this.placed);
			if (this.subs)
				for (var i in this.subs)
					this.subs[i].remove();
			if (this._deep_controlled_) {
				for (var i in this._deep_controlled_)
					this._deep_controlled_[i].remove();
				this._deep_controlled_ = null;
			}
			if (this.placed)
			{
				// console.log("remove node : ", this, this.placed())
				deep.$(this.placed()).remove();
			}
			if (this.clean)
				this.clean();
			this.initialised = false;
			this.placed = null;
		},
		load: function(opt) {
			opt = opt || {};
			var params = opt.params;
			var config = this.config || {};
			//if (params && Object.keys(params).length === 0)
			//	params = null;
			if (config.scope && config.scope != "both")
				if (deep.context("isServer")) {
					if (config.scope != "server")
						return;
				} else
			if (config.scope != "browser")
				return;
			var self = this;
			if (this.init && (deep.context("isServer") || !this.initialised))
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.load({
							params: params
						});
					});
			if (this.condition === false)
				return null;
			var promises = [], ctx = { params:params, context:deep.context(), ctrl:self };
			if (this.condition)
				if (typeof this.condition === "function" && !this.condition.apply(ctx))
					return null;
			if (this.what)
				promises.push(deep.nodes(this).query("./what").deepLoad(ctx, false));
			else
				promises.push(null);

			if (typeof this.how === 'string')
				promises.push(deep.nodes(this).query("./how").deepLoad(ctx, false, true));
			else
				promises.push(this.how);

			if (this.where)
				if (typeof this.where === 'string')
					promises.push(deep.nodes(this).query("./where").deepLoad(ctx, false, true));
				else
					promises.push(this.where);

				// console.log("launch deep load");
			return deep.all(promises)
				.done(function(res) {
					//console.log("view deep load : res  : ", res);
					var result = {
						_deep_render_node_: true,
						what: res[0],
						how: res[1],
						where: res[2],
						params: params
					};
					// console.log("view deep load done : ", self.how);
					return result;
				})
				.fail(function(e) {
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				});
		},
		refresh: function(arg /* params, loaded, routeMatch */ ) {
			var config = this.config || {};
			if (config.scope && config.scope != "both")
				if (!deep.context("isServer")) {
					if (config.scope != "browser")
						return;
				} else
			if (config.scope != "server")
				return;
			// console.log("view refresh : params : ", params, " - loaded : ", loaded);
			var self = this;
			if (this.init && (deep.context("isServer")|| !this.initialised))
				return deep.when(this.init())
					.done(function(success) {
						self.initialised = true;
						return self.refresh(arg);
					});
			var loaded, params, routeMatch;
			if (arg)
				if (arg._deep_render_node_) {
					loaded = arg;
					params = loaded.params;
				} else
			if (arg._deep_matched_node_) {
				loaded = arg.loaded;
				params = arg.output;

				routeMatch = arg;
			} else
				params = arg;
			params = params || this.params;
			if (params && !deep.context("isServer"))
				this.params = params;

			var render = function(loaded) {
				// console.log("view render : ", loaded)
				if (!loaded)
					return;
				if (self._deep_controlled_) {
					for (var i in self._deep_controlled_)
						self._deep_controlled_[i].remove();
					self._deep_controlled_ = null;
				}
				var what = null,
					how = null,
					where = null,
					rendered = null,
					placed = null;
				if (loaded.what)
					what = loaded.what;
				if (loaded.how)
					how = loaded.how;
				if (loaded.where)
					where = loaded.where;
				what = (what && what._deep_query_node_) ? what.value : what;
				how = (how && how._deep_query_node_) ? how.value : how;
				where = (where && where._deep_query_node_) ? where.value : where;

				if (what && what._deep_ocm_)
					what = what();
				if (how && how._deep_ocm_)
					how = how();
				if (where && where._deep_ocm_)
					where = where();

				loaded.what = what;
				loaded.how = how;
				loaded.where = where;
				loaded.params = params;

				placed = self.placed ? self.placed() : null;

				loaded.placed = placed;
				loaded.ctrl = self;
				// console.log("render with : how : ", how, what)
				try {
					//console.log("WHAT : ", what);
					// console.log("HOW : ", how);
					if (routeMatch) {
						loaded.route = routeMatch;
					}
					if (typeof how === 'function')
						rendered = loaded.rendered = how.call(self, loaded);
					else if(how)
						rendered = loaded.rendered = how;
					else if(what)
						rendered = loaded.rendered = what;
					if (where && typeof where === 'function')
						placed = loaded.placed = where.call(self, loaded.rendered, loaded.placed);
					else if (typeof jQuery !== 'undefined' && where instanceof jQuery)
						placed = loaded.placed = where;
					else if (typeof where === 'string' && deep.Promise.context.$)
						placed = loaded.placed = deep.Promise.context.$(where);
					/*else
						placed = loaded.placed = null;*/
				} catch (e) {
					// console.log("error while rendering :  ",e);
					if (typeof self.fail === 'function')
						return self.fail(e) || e;
					return e;
				}

				if (placed && !deep.context("isServer"))
					self.placed = function() {
						// console.log("store placed : ", placed)
						return placed;
					};

				var promise = null;
				if (config.enhance !== false && placed && deep.Promise.context.$) {
					//console.log("view placed : placed = ", placed);
					if (placed._deep_html_merged_) {
						var subprom = [];
						for (var i in placed) {
							if (i === '_deep_html_merged_')
								continue;
							subprom.push(deep.ui.enhance(self, placed[i], loaded))
						}
						promise = deep.all(subprom);
					} else
						promise = deep.ui.enhance(self, placed, loaded);
				}

				//console.log("rendered : ", loaded);
				if (promise)
					return promise
						.done(function() {
							if(config.relink !== false && !deep.context("isServer") && placed && self.relink)
								self.relink(placed);
							if (typeof self.done === "function") {
								var done = self.done;
								if (done._deep_ocm_)
									done = done();
								return done.call(self, loaded) || loaded;
							}
							return loaded;
						})
						.fail(function(e) {
							if (typeof self.fail === 'function')
								return self.fail(e) || e;
							return e;
						});

				//if(config.relink == false)
				//	console.log("skip relink on : ", self);
				if(config.relink !== false && !deep.context("isServer") && placed && self.relink)
					self.relink(placed);
				if (typeof self.done === "function") {
					var done = self.done;
					if (done._deep_ocm_)
						done = done();
					return done.call(self, loaded) || loaded;
				}
				return loaded;
			};
			var p;
			if (loaded)
				p = deep.when(render(loaded))
					.fail(function(e) {
						if (typeof self.fail === 'function') {
							var fail = self.fail;
							if (fail._deep_ocm_)
								fail = fail();
							return fail.call(self, e) || e;
						}
					});
			else
				p = deep.when(this.load({
					params: params
				}))
					.done(function() {
						this.done(render)
							.fail(function(e) {
								if (typeof self.fail === 'function') {
									var fail = self.fail;
									if (fail._deep_ocm_)
										fail = fail();
									return fail.call(self, e) || e;
								}
							});
					});
			return p;
		},
		relink:function(selector){
			var app = deep.currentApp(), $ = deep.$();
			$(selector)
			.find(this.relinkSelector || "a")
			.each(function() {
				if (this._deep_rerouted_)
					return;
				this._deep_rerouted_ = true;

				var	uri = $(this).attr("href");
				if (!uri)
					return;
				if (uri.substring(0, 4) === 'http')
					return;
				if (uri[0] == '/' && uri[1] == '/') // file
					return;
				// console.log("RELINK : ", uri, this);
				$(this).click(function(e) {
					if(e && e.preventDefault)
						e.preventDefault();
					deep.app(app).when(app.views.get(uri)).elog();
					return false;
				});
			});
		}
	});

	deep.View.relink = function(selector, relinkSelector) {
		// console.log("relink : ", selector);
		return deep.View.prototype.relink.call({
			relinkSelector:relinkSelector
		}, selector);
	};
	deep.coreUnits = deep.coreUnits || [];
	deep.coreUnits.push("js::deep-views/units/views");
	return deep.View;
});<|endoftext|>