<commit_before>var assert = require('assert')
var base58check = require('bs58check')
var bcrypto = require('./crypto')
var crypto = require('crypto')
var typeForce = require('typeforce')
var networks = require('./networks')

var BigInteger = require('bigi')
var ECKey = require('./eckey')
var ECPubKey = require('./ecpubkey')

var ecurve = require('ecurve')
var curve = ecurve.getCurveByName('secp256k1')

function findBIP32NetworkByVersion(version) {
  for (var name in networks) {
    var network = networks[name]

    if (version === network.bip32.private ||
        version === network.bip32.public) {

      return network
    }
  }

  assert(false, 'Could not find network for ' + version.toString(16))
}

function HDNode(K, chainCode, network) {
  network = network || networks.bitcoin

  typeForce('Buffer', chainCode)

  assert.equal(chainCode.length, 32, 'Expected chainCode length of 32, got ' + chainCode.length)
  assert(network.bip32, 'Unknown BIP32 constants for network')

  this.chainCode = chainCode
  this.depth = 0
  this.index = 0
  this.parentFingerprint = 0x00000000
  this.network = network

  if (K instanceof BigInteger) {
    this.privKey = new ECKey(K, true)
    this.pubKey = this.privKey.pub
  } else {
    this.pubKey = new ECPubKey(K, true)
  }
}

HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
HDNode.HIGHEST_BIT = 0x80000000
HDNode.LENGTH = 78

HDNode.fromSeedBuffer = function(seed, network) {
  typeForce('Buffer', seed)

  assert(seed.length >= 16, 'Seed should be at least 128 bits')
  assert(seed.length <= 64, 'Seed should be at most 512 bits')

  var I = crypto.createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
  var IL = I.slice(0, 32)
  var IR = I.slice(32)

  // In case IL is 0 or >= n, the master key is invalid
  // This is handled by `new ECKey` in the HDNode constructor
  var pIL = BigInteger.fromBuffer(IL)

  return new HDNode(pIL, IR, network)
}

HDNode.fromSeedHex = function(hex, network) {
  return HDNode.fromSeedBuffer(new Buffer(hex, 'hex'), network)
}

HDNode.fromBase58 = function(string, network) {
  return HDNode.fromBuffer(base58check.decode(string), network, true)
}

// FIXME: remove in 2.x.y
HDNode.fromBuffer = function(buffer, network, __ignoreDeprecation) {
  if (!__ignoreDeprecation) {
    console.warn('HDNode.fromBuffer() is deprecated for removal in 2.x.y, use fromBase58 instead')
  }

  assert.strictEqual(buffer.length, HDNode.LENGTH, 'Invalid buffer length')

  // 4 byte: version bytes
  var version = buffer.readUInt32BE(0)

  if (network) {
    assert(version === network.bip32.private || version === network.bip32.public, 'Network doesn\'t match')

  // auto-detect
  } else {
    network = findBIP32NetworkByVersion(version)
  }

  // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
  var depth = buffer.readUInt8(4)

  // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
  var parentFingerprint = buffer.readUInt32BE(5)
  if (depth === 0) {
    assert.strictEqual(parentFingerprint, 0x00000000, 'Invalid parent fingerprint')
  }

  // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
  // This is encoded in MSB order. (0x00000000 if master key)
  var index = buffer.readUInt32BE(9)
  assert(depth > 0 || index === 0, 'Invalid index')

  // 32 bytes: the chain code
  var chainCode = buffer.slice(13, 45)
  var data, hd

  // 33 bytes: private key data (0x00 + k)
  if (version === network.bip32.private) {
    assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key')
    data = buffer.slice(46, 78)
    var d = BigInteger.fromBuffer(data)
    hd = new HDNode(d, chainCode, network)

  // 33 bytes: public key data (0x02 + X or 0x03 + X)
  } else {
    data = buffer.slice(45, 78)
    var Q = ecurve.Point.decodeFrom(curve, data)
    assert.equal(Q.compressed, true, 'Invalid public key')

    // Verify that the X coordinate in the public point corresponds to a point on the curve.
    // If not, the extended public key is invalid.
    curve.validate(Q)

    hd = new HDNode(Q, chainCode, network)
  }

  hd.depth = depth
  hd.index = index
  hd.parentFingerprint = parentFingerprint

  return hd
}

// FIXME: remove in 2.x.y
HDNode.fromHex = function(hex, network) {
  return HDNode.fromBuffer(new Buffer(hex, 'hex'), network)
}

HDNode.prototype.getIdentifier = function() {
  return bcrypto.hash160(this.pubKey.toBuffer())
}

HDNode.prototype.getFingerprint = function() {
  return this.getIdentifier().slice(0, 4)
}

HDNode.prototype.getAddress = function() {
  return this.pubKey.getAddress(this.network)
}

HDNode.prototype.neutered = function() {
  var neutered = new HDNode(this.pubKey.Q, this.chainCode, this.network)
  neutered.depth = this.depth
  neutered.index = this.index
  neutered.parentFingerprint = this.parentFingerprint

  return neutered
}

HDNode.prototype.toBase58 = function(isPrivate) {
  return base58check.encode(this.toBuffer(isPrivate, true))
}

// FIXME: remove in 2.x.y
HDNode.prototype.toBuffer = function(isPrivate, __ignoreDeprecation) {
  if (isPrivate === undefined) {
    isPrivate = !!this.privKey

  // FIXME: remove in 2.x.y
  } else {
    console.warn('isPrivate flag is deprecated, please use the .neutered() method instead')
  }

  if (!__ignoreDeprecation) {
    console.warn('HDNode.toBuffer() is deprecated for removal in 2.x.y, use toBase58 instead')
  }

  // Version
  var version = isPrivate ? this.network.bip32.private : this.network.bip32.public
  var buffer = new Buffer(HDNode.LENGTH)

  // 4 bytes: version bytes
  buffer.writeUInt32BE(version, 0)

  // Depth
  // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
  buffer.writeUInt8(this.depth, 4)

  // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
  buffer.writeUInt32BE(this.parentFingerprint, 5)

  // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
  // This is encoded in Big endian. (0x00000000 if master key)
  buffer.writeUInt32BE(this.index, 9)

  // 32 bytes: the chain code
  this.chainCode.copy(buffer, 13)

  // 33 bytes: the public key or private key data
  if (isPrivate) {
    // FIXME: remove in 2.x.y
    assert(this.privKey, 'Missing private key')

    // 0x00 + k for private keys
    buffer.writeUInt8(0, 45)
    this.privKey.d.toBuffer(32).copy(buffer, 46)
  } else {

    // X9.62 encoding for public keys
    this.pubKey.toBuffer().copy(buffer, 45)
  }

  return buffer
}

// FIXME: remove in 2.x.y
HDNode.prototype.toHex = function(isPrivate) {
  return this.toBuffer(isPrivate).toString('hex')
}

// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
HDNode.prototype.derive = function(index) {
  var isHardened = index >= HDNode.HIGHEST_BIT
  var indexBuffer = new Buffer(4)
  indexBuffer.writeUInt32BE(index, 0)

  var data

  // Hardened child
  if (isHardened) {
    assert(this.privKey, 'Could not derive hardened child key')

    // data = 0x00 || ser256(kpar) || ser32(index)
    data = Buffer.concat([
      this.privKey.d.toBuffer(33),
      indexBuffer
    ])

  // Normal child
  } else {
    // data = serP(point(kpar)) || ser32(index)
    //      = serP(Kpar) || ser32(index)
    data = Buffer.concat([
      this.pubKey.toBuffer(),
      indexBuffer
    ])
  }

  var I = crypto.createHmac('sha512', this.chainCode).update(data).digest()
  var IL = I.slice(0, 32)
  var IR = I.slice(32)

  var pIL = BigInteger.fromBuffer(IL)

  // In case parse256(IL) >= n, proceed with the next value for i
  if (pIL.compareTo(curve.n) >= 0) {
    return this.derive(index + 1)
  }

  // Private parent key -> private child key
  var hd
  if (this.privKey) {
    // ki = parse256(IL) + kpar (mod n)
    var ki = pIL.add(this.privKey.d).mod(curve.n)

    // In case ki == 0, proceed with the next value for i
    if (ki.signum() === 0) {
      return this.derive(index + 1)
    }

    hd = new HDNode(ki, IR, this.network)

  // Public parent key -> public child key
  } else {
    // Ki = point(parse256(IL)) + Kpar
    //    = G*IL + Kpar
    var Ki = curve.G.multiply(pIL).add(this.pubKey.Q)

    // In case Ki is the point at infinity, proceed with the next value for i
    if (curve.isInfinity(Ki)) {
      return this.derive(index + 1)
    }

    hd = new HDNode(Ki, IR, this.network)
  }

  hd.depth = this.depth + 1
  hd.index = index
  hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)

  return hd
}

HDNode.prototype.deriveHardened = function(index) {
  // Only derives hardened private keys by default
  return this.derive(index + HDNode.HIGHEST_BIT)
}

HDNode.prototype.toString = HDNode.prototype.toBase58

module.exports = HDNode
<commit_msg>Allow constructing HDNode from an ECPubKey.<commit_after>var assert = require('assert')
var base58check = require('bs58check')
var bcrypto = require('./crypto')
var crypto = require('crypto')
var typeForce = require('typeforce')
var networks = require('./networks')

var BigInteger = require('bigi')
var ECKey = require('./eckey')
var ECPubKey = require('./ecpubkey')

var ecurve = require('ecurve')
var curve = ecurve.getCurveByName('secp256k1')

function findBIP32NetworkByVersion(version) {
  for (var name in networks) {
    var network = networks[name]

    if (version === network.bip32.private ||
        version === network.bip32.public) {

      return network
    }
  }

  assert(false, 'Could not find network for ' + version.toString(16))
}

function HDNode(K, chainCode, network) {
  network = network || networks.bitcoin

  typeForce('Buffer', chainCode)

  assert.equal(chainCode.length, 32, 'Expected chainCode length of 32, got ' + chainCode.length)
  assert(network.bip32, 'Unknown BIP32 constants for network')

  this.chainCode = chainCode
  this.depth = 0
  this.index = 0
  this.parentFingerprint = 0x00000000
  this.network = network

  if (K instanceof BigInteger) {
    this.privKey = new ECKey(K, true)
    this.pubKey = this.privKey.pub
  } else if (K instanceof ECPubKey) {
    this.pubKey = K
  } else {
    this.pubKey = new ECPubKey(K, true)
  }
}

HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
HDNode.HIGHEST_BIT = 0x80000000
HDNode.LENGTH = 78

HDNode.fromSeedBuffer = function(seed, network) {
  typeForce('Buffer', seed)

  assert(seed.length >= 16, 'Seed should be at least 128 bits')
  assert(seed.length <= 64, 'Seed should be at most 512 bits')

  var I = crypto.createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
  var IL = I.slice(0, 32)
  var IR = I.slice(32)

  // In case IL is 0 or >= n, the master key is invalid
  // This is handled by `new ECKey` in the HDNode constructor
  var pIL = BigInteger.fromBuffer(IL)

  return new HDNode(pIL, IR, network)
}

HDNode.fromSeedHex = function(hex, network) {
  return HDNode.fromSeedBuffer(new Buffer(hex, 'hex'), network)
}

HDNode.fromBase58 = function(string, network) {
  return HDNode.fromBuffer(base58check.decode(string), network, true)
}

// FIXME: remove in 2.x.y
HDNode.fromBuffer = function(buffer, network, __ignoreDeprecation) {
  if (!__ignoreDeprecation) {
    console.warn('HDNode.fromBuffer() is deprecated for removal in 2.x.y, use fromBase58 instead')
  }

  assert.strictEqual(buffer.length, HDNode.LENGTH, 'Invalid buffer length')

  // 4 byte: version bytes
  var version = buffer.readUInt32BE(0)

  if (network) {
    assert(version === network.bip32.private || version === network.bip32.public, 'Network doesn\'t match')

  // auto-detect
  } else {
    network = findBIP32NetworkByVersion(version)
  }

  // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
  var depth = buffer.readUInt8(4)

  // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
  var parentFingerprint = buffer.readUInt32BE(5)
  if (depth === 0) {
    assert.strictEqual(parentFingerprint, 0x00000000, 'Invalid parent fingerprint')
  }

  // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
  // This is encoded in MSB order. (0x00000000 if master key)
  var index = buffer.readUInt32BE(9)
  assert(depth > 0 || index === 0, 'Invalid index')

  // 32 bytes: the chain code
  var chainCode = buffer.slice(13, 45)
  var data, hd

  // 33 bytes: private key data (0x00 + k)
  if (version === network.bip32.private) {
    assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key')
    data = buffer.slice(46, 78)
    var d = BigInteger.fromBuffer(data)
    hd = new HDNode(d, chainCode, network)

  // 33 bytes: public key data (0x02 + X or 0x03 + X)
  } else {
    data = buffer.slice(45, 78)
    var Q = ecurve.Point.decodeFrom(curve, data)
    assert.equal(Q.compressed, true, 'Invalid public key')

    // Verify that the X coordinate in the public point corresponds to a point on the curve.
    // If not, the extended public key is invalid.
    curve.validate(Q)

    hd = new HDNode(Q, chainCode, network)
  }

  hd.depth = depth
  hd.index = index
  hd.parentFingerprint = parentFingerprint

  return hd
}

// FIXME: remove in 2.x.y
HDNode.fromHex = function(hex, network) {
  return HDNode.fromBuffer(new Buffer(hex, 'hex'), network)
}

HDNode.prototype.getIdentifier = function() {
  return bcrypto.hash160(this.pubKey.toBuffer())
}

HDNode.prototype.getFingerprint = function() {
  return this.getIdentifier().slice(0, 4)
}

HDNode.prototype.getAddress = function() {
  return this.pubKey.getAddress(this.network)
}

HDNode.prototype.neutered = function() {
  var neutered = new HDNode(this.pubKey.Q, this.chainCode, this.network)
  neutered.depth = this.depth
  neutered.index = this.index
  neutered.parentFingerprint = this.parentFingerprint

  return neutered
}

HDNode.prototype.toBase58 = function(isPrivate) {
  return base58check.encode(this.toBuffer(isPrivate, true))
}

// FIXME: remove in 2.x.y
HDNode.prototype.toBuffer = function(isPrivate, __ignoreDeprecation) {
  if (isPrivate === undefined) {
    isPrivate = !!this.privKey

  // FIXME: remove in 2.x.y
  } else {
    console.warn('isPrivate flag is deprecated, please use the .neutered() method instead')
  }

  if (!__ignoreDeprecation) {
    console.warn('HDNode.toBuffer() is deprecated for removal in 2.x.y, use toBase58 instead')
  }

  // Version
  var version = isPrivate ? this.network.bip32.private : this.network.bip32.public
  var buffer = new Buffer(HDNode.LENGTH)

  // 4 bytes: version bytes
  buffer.writeUInt32BE(version, 0)

  // Depth
  // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
  buffer.writeUInt8(this.depth, 4)

  // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
  buffer.writeUInt32BE(this.parentFingerprint, 5)

  // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
  // This is encoded in Big endian. (0x00000000 if master key)
  buffer.writeUInt32BE(this.index, 9)

  // 32 bytes: the chain code
  this.chainCode.copy(buffer, 13)

  // 33 bytes: the public key or private key data
  if (isPrivate) {
    // FIXME: remove in 2.x.y
    assert(this.privKey, 'Missing private key')

    // 0x00 + k for private keys
    buffer.writeUInt8(0, 45)
    this.privKey.d.toBuffer(32).copy(buffer, 46)
  } else {

    // X9.62 encoding for public keys
    this.pubKey.toBuffer().copy(buffer, 45)
  }

  return buffer
}

// FIXME: remove in 2.x.y
HDNode.prototype.toHex = function(isPrivate) {
  return this.toBuffer(isPrivate).toString('hex')
}

// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
HDNode.prototype.derive = function(index) {
  var isHardened = index >= HDNode.HIGHEST_BIT
  var indexBuffer = new Buffer(4)
  indexBuffer.writeUInt32BE(index, 0)

  var data

  // Hardened child
  if (isHardened) {
    assert(this.privKey, 'Could not derive hardened child key')

    // data = 0x00 || ser256(kpar) || ser32(index)
    data = Buffer.concat([
      this.privKey.d.toBuffer(33),
      indexBuffer
    ])

  // Normal child
  } else {
    // data = serP(point(kpar)) || ser32(index)
    //      = serP(Kpar) || ser32(index)
    data = Buffer.concat([
      this.pubKey.toBuffer(),
      indexBuffer
    ])
  }

  var I = crypto.createHmac('sha512', this.chainCode).update(data).digest()
  var IL = I.slice(0, 32)
  var IR = I.slice(32)

  var pIL = BigInteger.fromBuffer(IL)

  // In case parse256(IL) >= n, proceed with the next value for i
  if (pIL.compareTo(curve.n) >= 0) {
    return this.derive(index + 1)
  }

  // Private parent key -> private child key
  var hd
  if (this.privKey) {
    // ki = parse256(IL) + kpar (mod n)
    var ki = pIL.add(this.privKey.d).mod(curve.n)

    // In case ki == 0, proceed with the next value for i
    if (ki.signum() === 0) {
      return this.derive(index + 1)
    }

    hd = new HDNode(ki, IR, this.network)

  // Public parent key -> public child key
  } else {
    // Ki = point(parse256(IL)) + Kpar
    //    = G*IL + Kpar
    var Ki = curve.G.multiply(pIL).add(this.pubKey.Q)

    // In case Ki is the point at infinity, proceed with the next value for i
    if (curve.isInfinity(Ki)) {
      return this.derive(index + 1)
    }

    hd = new HDNode(Ki, IR, this.network)
  }

  hd.depth = this.depth + 1
  hd.index = index
  hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)

  return hd
}

HDNode.prototype.deriveHardened = function(index) {
  // Only derives hardened private keys by default
  return this.derive(index + HDNode.HIGHEST_BIT)
}

HDNode.prototype.toString = HDNode.prototype.toBase58

module.exports = HDNode
<|endoftext|>


<commit_before>;(function() {

    var container = null;
    var markers = null;

    SVG.extend(SVG.Element, {
        connectable: function(options, elmTarget) {

            var con = {};

            if (elmTarget === undefined) {
                elmTarget = options;
                options = {};
            }

            container = container || options.container;
            var elmSource = this;
            markers = markers || options.markers;

            var marker = markers.marker(10, 10);
            var markerId = "triangle-" + Math.random().toString(16);
            var line = container.line().attr("marker-end", "url(#" + markerId + ")");

            marker.attr({
                id: markerId,
                viewBox: "0 0 10 10",
                refX: "0",
                refY: "5",
                markerUnits: "strokeWidth",
                markerWidth: "4",
                markerHeight: "5"
            });

            marker.path().attr({
                d: "M 0 0 L 10 5 L 0 10 z"
            });

            // Source and target positions
            var sPos = {};
            var tPos = {};

            con.source = elmSource;
            con.target = elmTarget;
            con.line = line;
            con.marker = marker;

            con.computeLineCoordinates = function (con) {

                sPos = con.source.transform();
                tPos = con.target.transform();

                var x1 = sPos.x;
                var y1 = sPos.y;
                var x2 = tPos.x;
                var y2 = tPos.y;

                var dx = x2 - x1;
                var dy = y2 - y1;

                if (Math.abs(dy) < 200) {
                    if (dx < 0) {
                        x1 -= 25;
                        x2 += 30;
                    } else {
                        x2 -= 30;
                        x1 += 25;
                    }
                } else {
                    if (dy < 0) {
                        y1 -= 25;
                        y2 += 30;
                    } else {
                        y2 -= 30;
                        y1 += 25;
                    }
                }

                return {
                    x1: x1,
                    y1: y1,
                    x2: x2,
                    y2: y2
                };
            }

            function updateLine() {
                line.attr(con.computeLineCoordinates(con));
            }

            updateLine();

            elmSource.dragmove = updateLine;
            elmTarget.dragmove = updateLine;
            return con;
        }
    });
}).call(this);
<commit_msg>Simpler computing by default<commit_after>;(function() {

    var container = null;
    var markers = null;

    SVG.extend(SVG.Element, {
        connectable: function(options, elmTarget) {

            var con = {};

            if (elmTarget === undefined) {
                elmTarget = options;
                options = {};
            }

            container = container || options.container;
            var elmSource = this;
            markers = markers || options.markers;

            var marker = markers.marker(10, 10);
            var markerId = "triangle-" + Math.random().toString(16);
            var line = container.line().attr("marker-end", "url(#" + markerId + ")");

            marker.attr({
                id: markerId,
                viewBox: "0 0 10 10",
                refX: "0",
                refY: "5",
                markerUnits: "strokeWidth",
                markerWidth: "4",
                markerHeight: "5"
            });

            marker.path().attr({
                d: "M 0 0 L 10 5 L 0 10 z"
            });

            // Source and target positions
            var sPos = {};
            var tPos = {};

            con.source = elmSource;
            con.target = elmTarget;
            con.line = line;
            con.marker = marker;

            con.computeLineCoordinates = function (con) {

                var sPos = con.source.transform();
                var tPos = con.target.transform();

                var x1 = sPos.x;
                var y1 = sPos.y;
                var x2 = tPos.x;
                var y2 = tPos.y;

                return {
                    x1: x1,
                    y1: y1,
                    x2: x2,
                    y2: y2
                };
            };

            con.computeLineCoordinates = function (con) {

                var sPos = con.source.transform();
                var tPos = con.target.transform();

                var x1 = sPos.x;
                var y1 = sPos.y;
                var x2 = tPos.x;
                var y2 = tPos.y;

                var dx = x2 - x1;
                var dy = y2 - y1;

                if (Math.abs(dy) < 200) {
                    if (dx < 0) {
                        x1 -= 25;
                        x2 += 30;
                    } else {
                        x2 -= 30;
                        x1 += 25;
                    }
                } else {
                    if (dy < 0) {
                        y1 -= 25;
                        y2 += 30;
                    } else {
                        y2 -= 30;
                        y1 += 25;
                    }
                }

                return {
                    x1: x1,
                    y1: y1,
                    x2: x2,
                    y2: y2
                };
            }

            function updateLine() {
                line.attr(con.computeLineCoordinates(con));
            }

            updateLine();

            elmSource.dragmove = updateLine;
            elmTarget.dragmove = updateLine;
            return con;
        }
    });
}).call(this);
<|endoftext|>


<commit_before>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

var __inherit = function(cls, name, prototyping) {

    if (name === undefined) {
        throw __builtins__.PY$TypeError("The function __inherit must get exactly 2 arguments");
    }

    var res = function() {
        var x = res.PY$__create__;
        if (x !== undefined) {
            return res.PY$__create__.apply(null, [res].concat(Array.prototype.slice.call(arguments)));
        } else {
            throw __builtins__.PY$AttributeError("Class " + name + " does not have __create__ method");
        }
    };

    for (var o in cls) {
        res[o] = cls[o];
    }

    res.PY$__name__  = name;
    res.PY$__super__ = cls;
    res.prototyping  = prototyping;
    return res;
};

var object = __inherit(null, "object");

__builtins__.PY$object = object;

object.PY$__init__ = function() {
};

object.PY$__create__ = function(cls) {
    var args = Array.prototype.slice.call(arguments, 1);

    var obj = function() {
        var x = cls.PY$__call__;
        if (x !== undefined) {
            return cls.PY$__call__.apply(cls, args);
        } else {
            throw __builtins__.PY$AttributeError("Object " + js(cls.PY$__name__) + " does not have __call__ method");
        }
    };

    if (obj.__proto__ === undefined) {
        if (cls.prototyping) {
            var x = function() {};
            x.prototype = cls;
            obj = new x();
        } else {
            for (var o in cls) {
                obj[o] = cls[o];
            }
        }
    } else {
        obj.__proto__ = cls;
    };

    obj.PY$__class__ = cls;
    obj.id = prng();
    obj.PY$__init__.apply(obj, args);
    return obj;
};

object.PY$__setattr__ = function(k, v) {
    this["PY$" + k] = v;
};

object.PY$__getattr__ = function(k) {
    var q = this["PY$" + k];
    if ((typeof q === 'function') && (q.PY$__class__ === undefined) && (k !== '__class__') && arguments[1] !== false) {
        var that = this;
        if (this.PY$__class__ === undefined && !q.__static) {
            var t = function() { return q.apply(arguments[0], Array.prototype.slice.call(arguments, 1)); };
        } else {
            if (q.PY$__super__ !== undefined) {
                return q;
            } else {
                var t = function() { return q.apply(that, arguments); };
            }
        }
        return t;
    } else if (k === '__name__') {
        return str(this.PY$__name__);
    } else {
        if (q === undefined) {
            throw __builtins__.PY$AttributeError(js(this.PY$__repr__()) + " does not have attribute '" + js(k) + "'");
        } else {
            return q;
        }
    }
};

object.PY$__delattr__ = function(k) {
    delete this["PY$" + k];
};

object.PY$__repr__ = function() {
    if (this.PY$__class__) {
        return str("<instance of " + this.PY$__class__.PY$__name__ + " at 0x" + this.id.toString(16) + ">");
    } else if (this.PY$__name__) {
        return str("<type '" + this.PY$__name__ + "'>");
    } else {
        return str("<javascript: " + this + ">");
    }
};

object.PY$__str__ = object.PY$__repr__;

object.PY$__eq__ = function(other) {
    return this === other ? True : False;
};

object.PY$__ne__ = function (other) {
    return $PY.__not__(this.PY$__eq__(other));
};

object.PY$__gt__ = function(other) {
    if (this.PY$__class__ === undefined) {
        return this.PY$__name__ > other.PY$__name__ ? True : False;
    } else {
        return this.PY$__class__.PY$__name__ > other.PY$__class__.PY$__name__ ? True : False;
    }
};

object.PY$__lt__ = function(other) {
    if (other === this) {
        return False;
    } else {
        if (this.PY$__class__ === undefined) {
            return this.PY$__name__ < other.PY$__name__ ? True : False;
        } else {
            return this.PY$__class__.PY$__name__ < other.PY$__class__.PY$__name__ ? True : False;
        }
    }
};

object.PY$__ge__ = function(other) {
    return this.PY$__lt__(other) === False ? True : False;
};

object.PY$__le__ = function(other) {
    return this.PY$__gt__(other) === False ? True : False;
};

object.PY$__cmp__ = function (y) {
    if (this.PY$__gt__(y) === True) {
        return $c1;
    } else {
        if (this.PY$__lt__(y) === True) {
            return $cn1;
        } else {
            return $c0;
        }
    }
};

object.toString = function () {
    return js(this.PY$__str__());
};

object.valueOf = function () {
    return js(this);
};
<commit_msg> * Bugfix: Ensure that __super__ is undefined on instances, so we can tell classes and instances apart<commit_after>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

var __inherit = function(cls, name, prototyping) {

    if (name === undefined) {
        throw __builtins__.PY$TypeError("The function __inherit must get exactly 2 arguments");
    }

    var res = function() {
        var x = res.PY$__create__;
        if (x !== undefined) {
            return res.PY$__create__.apply(null, [res].concat(Array.prototype.slice.call(arguments)));
        } else {
            throw __builtins__.PY$AttributeError("Class " + name + " does not have __create__ method");
        }
    };

    for (var o in cls) {
        res[o] = cls[o];
    }

    res.PY$__name__  = name;
    res.PY$__super__ = cls;
    res.prototyping  = prototyping;
    return res;
};

var object = __inherit(null, "object");

__builtins__.PY$object = object;

object.PY$__init__ = function() {
};

object.PY$__create__ = function(cls) {
    var args = Array.prototype.slice.call(arguments, 1);

    var obj = function() {
        var x = cls.PY$__call__;
        if (x !== undefined) {
            return cls.PY$__call__.apply(cls, args);
        } else {
            throw __builtins__.PY$AttributeError("Object " + js(cls.PY$__name__) + " does not have __call__ method");
        }
    };

    if (obj.__proto__ === undefined) {
        if (cls.prototyping) {
            var x = function() {};
            x.prototype = cls;
            obj = new x();
        } else {
            for (var o in cls) {
                obj[o] = cls[o];
            }
        }
    } else {
        obj.__proto__ = cls;
    };

    obj.PY$__class__ = cls;
    obj.PY$__super__ = undefined;
    obj.id = prng();
    obj.PY$__init__.apply(obj, args);
    return obj;
};

object.PY$__setattr__ = function(k, v) {
    this["PY$" + k] = v;
};

object.PY$__getattr__ = function(k) {
    var q = this["PY$" + k];
    if ((typeof q === 'function') && (q.PY$__class__ === undefined) && (k !== '__class__') && arguments[1] !== false) {
        var that = this;
        if (this.PY$__class__ === undefined && !q.__static) {
            var t = function() { return q.apply(arguments[0], Array.prototype.slice.call(arguments, 1)); };
        } else {
            if (q.PY$__super__ !== undefined) {
                return q;
            } else {
                var t = function() { return q.apply(that, arguments); };
            }
        }
        return t;
    } else if (k === '__name__') {
        return str(this.PY$__name__);
    } else {
        if (q === undefined) {
            throw __builtins__.PY$AttributeError(js(this.PY$__repr__()) + " does not have attribute '" + js(k) + "'");
        } else {
            return q;
        }
    }
};

object.PY$__delattr__ = function(k) {
    delete this["PY$" + k];
};

object.PY$__repr__ = function() {
    if (this.PY$__class__) {
        return str("<instance of " + this.PY$__class__.PY$__name__ + " at 0x" + this.id.toString(16) + ">");
    } else if (this.PY$__name__) {
        return str("<type '" + this.PY$__name__ + "'>");
    } else {
        return str("<javascript: " + this + ">");
    }
};

object.PY$__str__ = object.PY$__repr__;

object.PY$__eq__ = function(other) {
    return this === other ? True : False;
};

object.PY$__ne__ = function (other) {
    return $PY.__not__(this.PY$__eq__(other));
};

object.PY$__gt__ = function(other) {
    if (this.PY$__class__ === undefined) {
        return this.PY$__name__ > other.PY$__name__ ? True : False;
    } else {
        return this.PY$__class__.PY$__name__ > other.PY$__class__.PY$__name__ ? True : False;
    }
};

object.PY$__lt__ = function(other) {
    if (other === this) {
        return False;
    } else {
        if (this.PY$__class__ === undefined) {
            return this.PY$__name__ < other.PY$__name__ ? True : False;
        } else {
            return this.PY$__class__.PY$__name__ < other.PY$__class__.PY$__name__ ? True : False;
        }
    }
};

object.PY$__ge__ = function(other) {
    return this.PY$__lt__(other) === False ? True : False;
};

object.PY$__le__ = function(other) {
    return this.PY$__gt__(other) === False ? True : False;
};

object.PY$__cmp__ = function (y) {
    if (this.PY$__gt__(y) === True) {
        return $c1;
    } else {
        if (this.PY$__lt__(y) === True) {
            return $cn1;
        } else {
            return $c0;
        }
    }
};

object.toString = function () {
    return js(this.PY$__str__());
};

object.valueOf = function () {
    return js(this);
};
<|endoftext|>


<commit_before>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const commandExists = require('command-exists').sync;
const cowsay = require('cowsay');
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const stripIndent = require('strip-indent');
const yosay = require('yosay');

module.exports = class extends Generator {
    /**
     * Constructor
     * @param {String|Array} args
     * @param {Object} opts
     */
    constructor(args, opts) {
        // Noinspection JSAnnotator
        super(args, opts);

        // Check for newer versions of this generator and notify
        updateNotifier({pkg}).notify();

        this.argument('name', {
            type: String,
            required: false,
            description: 'The name of the project. If not set then you will be prompted.'
        });
    }

    /**
     * Sets the app name
     * @param {string} name
     * @private
     */
    _setAppName(name) {
        this.appName = name.replace(/\s+/g, '-').toLowerCase();
    }

    /**
     * Initialization
     */
    initializing() {
        // Initialize configuration
        this.appName = 'Website';

        // If the app name was passed as an argument then set it here
        if (typeof this.options.name !== 'undefined') {
            this._setAppName(this.options.name);
        }
    }

    /**
     * Questions
     * @returns {Promise.<TResult>|Promise}
     */
    prompting() {
        // Have Yeoman greet the user.
        this.log(yosay('Starting the ' + chalk.red('Cacao BranchCMS') + ' website generator!'));

        var prompts = [];

        // Ask for the website project name if it's not already set
        if (typeof this.options.name === 'undefined') {
            prompts.push({
                type: 'input',
                name: 'name',
                message: 'What is the name of the website project?'
            });
        }

        // Is this a theme website for BranchCMS?
        prompts.push({
            type: 'list',
            name: 'istheme',
            message: 'Is this a new theme website?',
            choices: ['Yes', 'No'],
            default: 'No'
        });

        // Front-end libraries to include
        prompts.push({
            type: 'checkbox',
            name: 'libraries',
            message: 'Check which libraries to include',
            choices: [
                {name: 'Magnific Popup', value: 'magnific', checked: true},
                {name: 'Slick slider', value: 'slick', checked: true},
                {name: 'Drift image zoom', value: 'driftzoom'}
            ]
        });

        // BranchCMS App templates to include
        prompts.push({
            type: 'checkbox',
            name: 'apps',
            message: 'Check which BranchCMS apps you will use for this website',
            choices: [
                {name: 'Blog', value: 'blog'},
                {name: 'Store', value: 'store'}
            ]
        });

        return this.prompt(prompts).then(answers => {
            // Set the app name if it was asked
            if (typeof answers.name !== 'undefined') {
                this._setAppName(answers.name);
            }

            // Tests to see if a value was selected in an answer
            const hasAnswer = (val, test) => val && val.indexOf(test) !== -1;

            this.isThemeWebsite = answers.istheme.toLowerCase() === 'yes';

            this.includeMagnific = hasAnswer(answers.libraries, 'magnific');
            this.includeSlick = hasAnswer(answers.libraries, 'slick');
            this.includeDrift = hasAnswer(answers.libraries, 'driftzoom');

            this.appBlog = hasAnswer(answers.apps, 'blog');
            this.appStore = hasAnswer(answers.apps, 'store');
        });
    }

    /**
     * Create the source files
     */
    writing() {
        this.log('\n' + chalk.bold('Writing files') + '\n');

        this._setupConfigFiles();
        this._copySourceFiles();
        this._copyTemplateFiles();
    }

    /**
     * Sets up the package.json and other config files
     * @private
     */
    _setupConfigFiles() {
        // Editor Config
        this.fs.copy(
            this.templatePath('_editorconfig'),
            this.destinationPath('.editorconfig')
        );

        // Gitignore
        this.fs.copy(
            this.templatePath('_gitignore'),
            this.destinationPath('.gitignore')
        );

        // Package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            {
                name: this.appName,
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick
            }
        );

        // Stylelint
        this.fs.copy(
            this.templatePath('_stylelintrc'),
            this.destinationPath('.stylelintrc')
        );

        this.fs.copyTpl(
            this.templatePath() + '/gulp/**/*',
            this.destinationPath() + '/gulp',
            {
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick,
                isThemeWebsite: this.isThemeWebsite
            }
        );

        // Gulpfile.js
        this.fs.copyTpl(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js'),
            {
                isThemeWebsite: this.isThemeWebsite
            }
        );
    }

    /**
     * Copies the boilerplate images, CSS and Javascript files
     */
    _copySourceFiles() {
        this.fs.copy(
            this.templatePath() + '/src/**/*',
            this.destinationPath() + '/src'
        );

        if (this.isThemeWebsite) {
            // Include the theme files in the main css file
            let themeInclude = `
                    /**
                     * Theme configuration
                     */

                    @import './theme';`;
            this.fs.append(this.destinationPath() + '/src/css/main.css', stripIndent(themeInclude));

            // Include the theme config files
            this.fs.copy(
                this.templatePath() + '/theme-starter/css/**/*',
                this.destinationPath() + '/src/css'
            );
        }
    }

    /**
     * Copy the BranchCMS template files
     * @private
     */
    _copyTemplateFiles() {
        const src = this.templatePath() + '/theme/';
        const dest = this.destinationPath() + '/src/theme/';

        // Copy the theme.json file
        this.fs.copy(
            src + 'theme.json',
            this.destinationPath() + '/src/theme.json'
        );

        // Copy the default site template
        this.fs.copy(
            src + 'one-column.twig',
            dest + 'one-column.twig'
        );
        this.fs.copy(
            src + 'two-column.twig',
            dest + 'two-column.twig'
        );

        // Copy the app templates
        let apps = [
            'content-builder',
            'forms',
            'navigation',
            'search',
            'snippets'
        ];
        if (this.appBlog) {
            apps.push('blog');
        }

        if (this.appStore) {
            apps.push('store');
        }

        for (let app of apps) {
            this.fs.copy(
                src + app + '/**/*',
                dest + app
            );
        }
    }

    /**
     * Installation via yarn or npm
     */
    install() {
        this.log('\n');
        if (commandExists('yarn')) {
            this.yarnInstall();
        } else {
            this.npmInstall();
        }
    }

    /**
     * Finish
     */
    end() {
        this._build();
    }

    /**
     * Runs the gulp build
     * @private
     */
    _build() {
        this.log('\n\n' + chalk.bold('Running ' + chalk.yellow('gulp `build`') + ' task'));
        this.spawnCommand('gulp', ['build']).on('close', () => {
            this._done();
        });
    }

    /**
     * Output the closing message
     * @private
     */
    _done() {
        const cows = [
            'default',
            'cheese',
            'dragon-and-cow',
            'dragon',
            'elephant',
            'eyes',
            'ghostbusters',
            'goat',
            'hedgehog',
            'kitty',
            'koala',
            'luke-koala',
            'mech-and-cow',
            'meow',
            'milk',
            'moofasa',
            'moose',
            'sheep',
            'small',
            'squirrel',
            'stegosaurus',
            'turtle',
            'tux',
            'vader-koala',
            'vader',
            'whale',
            'www'
        ];
        const cow = cows[Math.floor(Math.random() * cows.length)];
        this.log(cowsay.say({
            text: '\nAll Done! Now go and build something great!\n',
            f: cow
        }) + '\n');
    }
};
<commit_msg>Fixed issue where content layout templates were not included in the list of templates to export<commit_after>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const commandExists = require('command-exists').sync;
const cowsay = require('cowsay');
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const stripIndent = require('strip-indent');
const yosay = require('yosay');

module.exports = class extends Generator {
    /**
     * Constructor
     * @param {String|Array} args
     * @param {Object} opts
     */
    constructor(args, opts) {
        // Noinspection JSAnnotator
        super(args, opts);

        // Check for newer versions of this generator and notify
        updateNotifier({pkg}).notify();

        this.argument('name', {
            type: String,
            required: false,
            description: 'The name of the project. If not set then you will be prompted.'
        });
    }

    /**
     * Sets the app name
     * @param {string} name
     * @private
     */
    _setAppName(name) {
        this.appName = name.replace(/\s+/g, '-').toLowerCase();
    }

    /**
     * Initialization
     */
    initializing() {
        // Initialize configuration
        this.appName = 'Website';

        // If the app name was passed as an argument then set it here
        if (typeof this.options.name !== 'undefined') {
            this._setAppName(this.options.name);
        }
    }

    /**
     * Questions
     * @returns {Promise.<TResult>|Promise}
     */
    prompting() {
        // Have Yeoman greet the user.
        this.log(yosay('Starting the ' + chalk.red('Cacao BranchCMS') + ' website generator!'));

        var prompts = [];

        // Ask for the website project name if it's not already set
        if (typeof this.options.name === 'undefined') {
            prompts.push({
                type: 'input',
                name: 'name',
                message: 'What is the name of the website project?'
            });
        }

        // Is this a theme website for BranchCMS?
        prompts.push({
            type: 'list',
            name: 'istheme',
            message: 'Is this a new theme website?',
            choices: ['Yes', 'No'],
            default: 'No'
        });

        // Front-end libraries to include
        prompts.push({
            type: 'checkbox',
            name: 'libraries',
            message: 'Check which libraries to include',
            choices: [
                {name: 'Magnific Popup', value: 'magnific', checked: true},
                {name: 'Slick slider', value: 'slick', checked: true},
                {name: 'Drift image zoom', value: 'driftzoom'}
            ]
        });

        // BranchCMS App templates to include
        prompts.push({
            type: 'checkbox',
            name: 'apps',
            message: 'Check which BranchCMS apps you will use for this website',
            choices: [
                {name: 'Blog', value: 'blog'},
                {name: 'Store', value: 'store'}
            ]
        });

        return this.prompt(prompts).then(answers => {
            // Set the app name if it was asked
            if (typeof answers.name !== 'undefined') {
                this._setAppName(answers.name);
            }

            // Tests to see if a value was selected in an answer
            const hasAnswer = (val, test) => val && val.indexOf(test) !== -1;

            this.isThemeWebsite = answers.istheme.toLowerCase() === 'yes';

            this.includeMagnific = hasAnswer(answers.libraries, 'magnific');
            this.includeSlick = hasAnswer(answers.libraries, 'slick');
            this.includeDrift = hasAnswer(answers.libraries, 'driftzoom');

            this.appBlog = hasAnswer(answers.apps, 'blog');
            this.appStore = hasAnswer(answers.apps, 'store');
        });
    }

    /**
     * Create the source files
     */
    writing() {
        this.log('\n' + chalk.bold('Writing files') + '\n');

        this._setupConfigFiles();
        this._copySourceFiles();
        this._copyTemplateFiles();
    }

    /**
     * Sets up the package.json and other config files
     * @private
     */
    _setupConfigFiles() {
        // Editor Config
        this.fs.copy(
            this.templatePath('_editorconfig'),
            this.destinationPath('.editorconfig')
        );

        // Gitignore
        this.fs.copy(
            this.templatePath('_gitignore'),
            this.destinationPath('.gitignore')
        );

        // Package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            {
                name: this.appName,
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick
            }
        );

        // Stylelint
        this.fs.copy(
            this.templatePath('_stylelintrc'),
            this.destinationPath('.stylelintrc')
        );

        this.fs.copyTpl(
            this.templatePath() + '/gulp/**/*',
            this.destinationPath() + '/gulp',
            {
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick,
                isThemeWebsite: this.isThemeWebsite
            }
        );

        // Gulpfile.js
        this.fs.copyTpl(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js'),
            {
                isThemeWebsite: this.isThemeWebsite
            }
        );
    }

    /**
     * Copies the boilerplate images, CSS and Javascript files
     */
    _copySourceFiles() {
        this.fs.copy(
            this.templatePath() + '/src/**/*',
            this.destinationPath() + '/src'
        );

        if (this.isThemeWebsite) {
            // Include the theme files in the main css file
            let themeInclude = `
                    /**
                     * Theme configuration
                     */

                    @import './theme';`;
            this.fs.append(this.destinationPath() + '/src/css/main.css', stripIndent(themeInclude));

            // Include the theme config files
            this.fs.copy(
                this.templatePath() + '/theme-starter/css/**/*',
                this.destinationPath() + '/src/css'
            );
        }
    }

    /**
     * Copy the BranchCMS template files
     * @private
     */
    _copyTemplateFiles() {
        const src = this.templatePath() + '/theme/';
        const dest = this.destinationPath() + '/src/theme/';

        // Copy the theme.json file
        this.fs.copy(
            src + 'theme.json',
            this.destinationPath() + '/src/theme.json'
        );

        // Copy the default site template
        this.fs.copy(
            src + 'one-column.twig',
            dest + 'one-column.twig'
        );
        this.fs.copy(
            src + 'two-column.twig',
            dest + 'two-column.twig'
        );

        // Copy the app templates
        let apps = [
            'content-builder',
            'content-layouts',
            'forms',
            'navigation',
            'search',
            'snippets'
        ];
        if (this.appBlog) {
            apps.push('blog');
        }

        if (this.appStore) {
            apps.push('store');
        }

        for (let app of apps) {
            this.fs.copy(
                src + app + '/**/*',
                dest + app
            );
        }
    }

    /**
     * Installation via yarn or npm
     */
    install() {
        this.log('\n');
        if (commandExists('yarn')) {
            this.yarnInstall();
        } else {
            this.npmInstall();
        }
    }

    /**
     * Finish
     */
    end() {
        this._build();
    }

    /**
     * Runs the gulp build
     * @private
     */
    _build() {
        this.log('\n\n' + chalk.bold('Running ' + chalk.yellow('gulp `build`') + ' task'));
        this.spawnCommand('gulp', ['build']).on('close', () => {
            this._done();
        });
    }

    /**
     * Output the closing message
     * @private
     */
    _done() {
        const cows = [
            'default',
            'cheese',
            'dragon-and-cow',
            'dragon',
            'elephant',
            'eyes',
            'ghostbusters',
            'goat',
            'hedgehog',
            'kitty',
            'koala',
            'luke-koala',
            'mech-and-cow',
            'meow',
            'milk',
            'moofasa',
            'moose',
            'sheep',
            'small',
            'squirrel',
            'stegosaurus',
            'turtle',
            'tux',
            'vader-koala',
            'vader',
            'whale',
            'www'
        ];
        const cow = cows[Math.floor(Math.random() * cows.length)];
        this.log(cowsay.say({
            text: '\nAll Done! Now go and build something great!\n',
            f: cow
        }) + '\n');
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import ErrorPaths from '../constants/ErrorPaths';

const REPOSITORY_ERRORS = [
  'EmptyPackageImport',
  'IndexNotFound',
  'InvalidRepositoryUri',
  'PackageFileMissing',
  'PackageFileNotJson',
  'RepositoryNotPresent',
  'RepositoryUriConnection',
  'RepositoryUriSyntax'
];

class CosmosErrorMessage extends React.Component {
  getHeader() {
    let {header, headerClass} = this.props;
    if (!header) {
      return null;
    }

    return (

        {header}

    );
  }

  getMessage() {
    let {type, message, data} = this.props.error;
    let children = [];

    // Append reference to repository page, since repository related errors
    // can occur at any request to Cosmos
    if (REPOSITORY_ERRORS.includes(type)) {
      message = this.appendRepositoryLink(message);
    }

    // The message is always there
    children.push(

          {message}

      );

    // Check if we should additionally append
    // the error details as an unordered list
    if (data && data.errors) {

      // Get an array of array of errors for every individual path
      let errorsDetails = data.errors.map(function ({path, errors}) {
        return errors.map(function (error) {
          return (

{ErrorPaths[path] || path}: {error}

            );
        });
      });

      // Flatten elemens array
      errorsDetails = errorsDetails.reduce(function (a, b) {
        return a.concat(b);
      });

      // Append an error details
 to the childrens
      children.push(

            {errorsDetails}

        );

    }

    // Return collected items
    return (

          {children}

      );

  }

  appendRepositoryLink(message) {
    return (

        {`${message} You can go to the `}
        Repositories Settings
        {' page to change installed repositories.'}

    );
  }

  render() {
    return (

        {this.getHeader()}

          {this.getMessage()}

    );
  }
};

CosmosErrorMessage.defaultProps = {
  className: 'text-overflow-break-word column-small-8 column-small-offset-2 column-medium-6 column-medium-offset-3',
  error: {message: 'Please try again.'},
  header: 'An Error Occured',
  headerClass: 'h3 text-align-center flush-top',
  wrapperClass: 'row'
};

CosmosErrorMessage.propTypes = {
  className: React.PropTypes.string,
  error: React.PropTypes.shape({
    message: React.PropTypes.string,
    type: React.PropTypes.string,
    data: React.PropTypes.shape({
      errors: React.PropTypes.array
    })
  }),
  header: React.PropTypes.string,
  headerClass: React.PropTypes.string,
  wrapperClass: React.PropTypes.string
};

module.exports = CosmosErrorMessage;
<commit_msg>Making message/data an object to be more generic<commit_after>import React from 'react';
import ErrorPaths from '../constants/ErrorPaths';

const REPOSITORY_ERRORS = [
  'EmptyPackageImport',
  'IndexNotFound',
  'InvalidRepositoryUri',
  'PackageFileMissing',
  'PackageFileNotJson',
  'RepositoryNotPresent',
  'RepositoryUriConnection',
  'RepositoryUriSyntax'
];

class CosmosErrorMessage extends React.Component {
  getHeader() {
    let {header, headerClass} = this.props;
    if (!header) {
      return null;
    }

    return (

        {header}

    );
  }

  getMessage() {
    let {type, message, data} = this.props.error;
    let children = [];

    // Append reference to repository page, since repository related errors
    // can occur at any request to Cosmos
    if (REPOSITORY_ERRORS.includes(type)) {
      message = this.appendRepositoryLink(message);
    }

    // The message is always there
    children.push(

          {message}

      );

    // Check if we should additionally append
    // the error details as an unordered list
    if (data && data.errors) {

      // Get an array of array of errors for every individual path
      let errorsDetails = data.errors.map(function ({path, errors}) {
        return errors.map(function (error) {
          return (

{ErrorPaths[path] || path}: {error}

            );
        });
      });

      // Flatten elemens array
      errorsDetails = errorsDetails.reduce(function (a, b) {
        return a.concat(b);
      });

      // Append an error details
 to the childrens
      children.push(

            {errorsDetails}

        );

    }

    // Return collected items
    return (

          {children}

      );

  }

  appendRepositoryLink(message) {
    return (

        {`${message} You can go to the `}
        Repositories Settings
        {' page to change installed repositories.'}

    );
  }

  render() {
    return (

        {this.getHeader()}

          {this.getMessage()}

    );
  }
};

CosmosErrorMessage.defaultProps = {
  className: 'text-overflow-break-word column-small-8 column-small-offset-2 column-medium-6 column-medium-offset-3',
  error: {message: 'Please try again.'},
  header: 'An Error Occured',
  headerClass: 'h3 text-align-center flush-top',
  wrapperClass: 'row'
};

CosmosErrorMessage.propTypes = {
  className: React.PropTypes.string,
  error: React.PropTypes.shape({
    message: React.PropTypes.string,
    type: React.PropTypes.string,
    data: React.PropTypes.object
  }),
  header: React.PropTypes.string,
  headerClass: React.PropTypes.string,
  wrapperClass: React.PropTypes.string
};

module.exports = CosmosErrorMessage;
<|endoftext|>


<commit_before>import Ember from 'ember';
import mapBboxController from 'mobility-playground/mixins/map-bbox-controller';

export default Ember.Controller.extend(mapBboxController, {
	queryParams: ['bbox'],
	bbox: null,
	place: null,
	bounds: Ember.computed('bbox', function(){
		if (this.get('bbox') === null){
			// -122.54287719726562%2C37.706911598228466%2C-122.29568481445312%2C37.84259697150785
			var defaultBoundsArray = [];
			defaultBoundsArray.push([37.706911598228466, -122.54287719726562]);
			defaultBoundsArray.push([37.84259697150785, -122.29568481445312]);
			return defaultBoundsArray;
		} else {
			var coordinateArray = [];
			var bboxString = this.get('bbox');
			var tempArray = [];
			var boundsArray = [];

			coordinateArray = bboxString.split(',');

			for (var i = 0; i < coordinateArray.length; i++){
				tempArray.push(parseFloat(coordinateArray[i]));
			}

			var arrayOne = [];
			var arrayTwo = [];
			arrayOne.push(tempArray[1]);
			arrayOne.push(tempArray[0]);
			arrayTwo.push(tempArray[3]);
			arrayTwo.push(tempArray[2]);
			boundsArray.push(arrayOne);
			boundsArray.push(arrayTwo);
			return boundsArray;
		}
	}),
	icon: L.icon({
		iconUrl: 'assets/images/marker.png',
		iconSize: (20, 20)
	}),

	actions: {
		updatebbox(e) {
			var newbox = e.target.getBounds();
			this.set('bbox', newbox.toBBoxString());
		},
		searchRepo(term) {
      if (Ember.isBlank(term)) { return []; }
      const url = `http://search.mapzen.com/v1/autocomplete?api_key=search-ab7NChg&sources=wof&text=${term}`;
      return Ember.$.ajax({ url }).then(json => json.features);
    },

  // to debounce:

	// searchRepo(term) {
  //   	return new Ember.RSVP.Promise((resolve, reject) => {
  //     	run.debounce(this, this._performSearch, term, resolve, reject, 600);
  //     });
  //   },

  //   performSearch(term, resolve, reject) {
  //     if (isBlank(term)) { return resolve([]); }
  //     	this.get('ajax').request(`http://search.mapzen.com/v1/autocomplete?api_key=search-ab7NChg&sources=wof&text=${term}`)
  //       .then(json => resolve(json.features), reject);
  //   }

  	setPlace: function(selected){
  		this.set('place', selected);
  		this.set('bbox', selected.bbox);
  	}

  }
});<commit_msg>change search query endpoint from http to https<commit_after>import Ember from 'ember';
import mapBboxController from 'mobility-playground/mixins/map-bbox-controller';

export default Ember.Controller.extend(mapBboxController, {
	queryParams: ['bbox'],
	bbox: null,
	place: null,
	bounds: Ember.computed('bbox', function(){
		if (this.get('bbox') === null){
			// -122.54287719726562%2C37.706911598228466%2C-122.29568481445312%2C37.84259697150785
			var defaultBoundsArray = [];
			defaultBoundsArray.push([37.706911598228466, -122.54287719726562]);
			defaultBoundsArray.push([37.84259697150785, -122.29568481445312]);
			return defaultBoundsArray;
		} else {
			var coordinateArray = [];
			var bboxString = this.get('bbox');
			var tempArray = [];
			var boundsArray = [];

			coordinateArray = bboxString.split(',');

			for (var i = 0; i < coordinateArray.length; i++){
				tempArray.push(parseFloat(coordinateArray[i]));
			}

			var arrayOne = [];
			var arrayTwo = [];
			arrayOne.push(tempArray[1]);
			arrayOne.push(tempArray[0]);
			arrayTwo.push(tempArray[3]);
			arrayTwo.push(tempArray[2]);
			boundsArray.push(arrayOne);
			boundsArray.push(arrayTwo);
			return boundsArray;
		}
	}),
	icon: L.icon({
		iconUrl: 'assets/images/marker.png',
		iconSize: (20, 20)
	}),

	actions: {
		updatebbox(e) {
			var newbox = e.target.getBounds();
			this.set('bbox', newbox.toBBoxString());
		},
		searchRepo(term) {
      if (Ember.isBlank(term)) { return []; }
      const url = `https://search.mapzen.com/v1/autocomplete?api_key=search-ab7NChg&sources=wof&text=${term}`;
      return Ember.$.ajax({ url }).then(json => json.features);
    },

  // to debounce:

	// searchRepo(term) {
  //   	return new Ember.RSVP.Promise((resolve, reject) => {
  //     	run.debounce(this, this._performSearch, term, resolve, reject, 600);
  //     });
  //   },

  //   performSearch(term, resolve, reject) {
  //     if (isBlank(term)) { return resolve([]); }
  //     	this.get('ajax').request(`http://search.mapzen.com/v1/autocomplete?api_key=search-ab7NChg&sources=wof&text=${term}`)
  //       .then(json => resolve(json.features), reject);
  //   }

  	setPlace: function(selected){
  		this.set('place', selected);
  		this.set('bbox', selected.bbox);
  	}

  }
});<|endoftext|>


<commit_before>'use strict';
var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var gitConfig = require('git-config');

const licenses = [
  {name: 'CC BY Attribution 4.0 License', value: 'CC-BY-4.0'},
  {name: 'CC BY-SA Attribution-ShareAlike 4.0 License', value: 'CC-BY-SA-4.0'},
  {name: 'CC BY-ND Attribution-NoDerivs 4.0 License', value: 'CC-BY-ND-4.0'},
  {name: 'CC BY-NC Attribution-NonCommercial 4.0 License', value: 'CC-BY-NC-4.0'},
  {name: 'CC BY-NC-SA Attribution-NonCommercial-ShareAlike 4.0 License', value: 'CC-BY-NC-SA-4.0'},
  {name: 'CC BY-NC-ND Attribution-NonCommercial-NoDerivs 4.0 License', value: 'CC-BY-NC-ND-4.0'},
  {name: 'CC0 Public Domain 1.0 - Waive all copyright', value: 'CC0-1.0'}
];

module.exports = Generator.extend({

  constructor: function () {
    Generator.apply(this, arguments);

    // define all options/arguments for generator
    this.option('name', {
      type: String,
      desc: 'Author\'s Name',
      required: true
    });

    this.option('work', {
      type: String,
      desc: 'Licensed Work Title',
      required: true
    });

    this.option('email', {
      type: String,
      desc: 'Author\'s Email',
      required: false
    });

    this.option('website', {
      type: String,
      desc: 'Author\'s Website',
      required: false
    });

    this.option('year', {
      type: String,
      desc: 'Year(s) to include on the license (e.g. 2016-2017)',
      required: true,
      defaults: (new Date()).getFullYear()
    });

    this.option('licensePrompt', {
      type: String,
      desc: 'License prompt text',
      required: true,
      defaults: 'Choose a Creative Commons license:'
    });

    this.option('license', {
      type: String,
      desc: 'License to Generate: CC-BY-4.0, CC-BY-SA-4.0, CC-BY-ND-4.0, CC-BY-NC-4.0, CC-BY-NC-SA-4.0, CC-BY-NC-ND-4.0, CC0-1.0',
      required: true
    });

    this.option('output', {
      type: String,
      desc: 'Output file',
      default: 'LICENSE',
      required: true
    });
  },

  initializing: function () {
    // init git config
    this.gitc = gitConfig.sync();
    // get name via argument or fallback to git
    if (this._initOptions.name) {
      this.options.name = this._initOptions.name;
    } else if (this.gitc.user) {
      this.options.name = this.gitc.user.name;
    }

    // get email via argument or fallback to git
    if (this._initOptions.email) {
      this.options.email = this._initOptions.email;
    } else if (this.gitc.user) {
      this.options.email = this.gitc.user.email;
    }

    this.options.work = this._initOptions.work;
    this.options.year = this._initOptions.year;
    this.options.website = this._initOptions.website;
    this.options.output = this._initOptions.output || this.options.output;

    // Have Yeoman greet the user.
    this.log(yosay(
      'Generate Creative Commons LICENSE with ' +
        chalk.red('license-cc') + ' generator!'
    ));
  },

  prompting: {
    requiredPrompt() {
      var prompts = [
        {
          name: 'name',
          message: 'Author\'s Name:',
          default: this.options.name,
          when: !this._initOptions.name
        },
        {
          name: 'work',
          message: 'Licensed Work Title:',
          default: this.options.work,
          when: !this._initOptions.work
        },
        {
          name: 'year',
          message: 'Year(s) to include on the license (e.g. 2016-2017)',
          default: this.options.year,
          when: !this.options.year
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        if (answers.name) {
          this.options.name = answers.name.trim();
        }

        if (answers.work) {
          this.options.work = answers.work.trim();
        }

        if (answers.year) {
          this.options.year = answers.year;
        }
      }.bind(this));
    },
    contactConfirmPrompt() {
      var prompts = [
        {
          type: 'confirm',
          name: 'contactDetails',
          message: 'Would you like to add contact details?',
          default: true,
          when: !this._initOptions.email && !this._initOptions.website
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        this.options.contactDetails = answers.contactDetails;
      }.bind(this));
    },

    contactEmailPrompt() {
      if (this.options.contactDetails && !this._initOptions.email) {
        var prompts = [
          {
            name: 'email',
            message: 'Author\'s Email:',
            default: this.options.email
          }
        ];

        return this.prompt(prompts).then(function (answers) {
          this.options.email = answers.email;
        }.bind(this));
      }
    },

    contactWebsitePrompt() {
      if (this.options.contactDetails && !this._initOptions.website) {
        var prompts = [
          {
            name: 'website',
            message: 'Author\'s Website:',
            default: this.options.website
          }
        ];

        return this.prompt(prompts).then(function (answers) {
          this.options.website = answers.website;
        }.bind(this));
      }
    },
    licensePrompt() {
      var prompts = [
        {
          type: 'list',
          name: 'license',
          message: this.options.licensePrompt,
          default: this.options.license,
          choices: licenses,
          when: !this._initOptions.license
        },
        {
          name: 'output',
          message: 'Output file:',
          default: 'LICENSE',
          when: !this._initOptions.output
        }

      ];

      return this.prompt(prompts).then(function (answers) {
        if (answers.license) {
          this.options.license = answers.license;
        }

        if (answers.output) {
          this.options.output = answers.output;
        }
      }.bind(this));
    }
  },

  writing: function () {
    // check license file
    var filename = this.options.license + '.txt';
    if (!this.fs.exists(this.templatePath(filename))) {
      throw new Error('License \'' + filename + '\' NOT FOUND!');
    }

    // combine author data
    let author = this.options.name;
    if (this.options.email) {
      author += ' <' + this.options.email + '>';
    }
    if (this.options.website) {
      author += ' (' + this.options.website + ')';
    }

    // generate LICENSE from teplate file
    this.fs.copyTpl(
      this.templatePath(filename),
      this.destinationPath(this.options.output),
      {
        year: this.options.year,
        author: author,
        work: this.options.work
      }
    );
  },

  install: function () {
  }
});
<commit_msg>remove git-config<commit_after>'use strict';
var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

const licenses = [
  {name: 'CC BY Attribution 4.0 License', value: 'CC-BY-4.0'},
  {name: 'CC BY-SA Attribution-ShareAlike 4.0 License', value: 'CC-BY-SA-4.0'},
  {name: 'CC BY-ND Attribution-NoDerivs 4.0 License', value: 'CC-BY-ND-4.0'},
  {name: 'CC BY-NC Attribution-NonCommercial 4.0 License', value: 'CC-BY-NC-4.0'},
  {name: 'CC BY-NC-SA Attribution-NonCommercial-ShareAlike 4.0 License', value: 'CC-BY-NC-SA-4.0'},
  {name: 'CC BY-NC-ND Attribution-NonCommercial-NoDerivs 4.0 License', value: 'CC-BY-NC-ND-4.0'},
  {name: 'CC0 Public Domain 1.0 - Waive all copyright', value: 'CC0-1.0'}
];

module.exports = Generator.extend({

  constructor: function () {
    Generator.apply(this, arguments);

    // define all options/arguments for generator
    this.option('name', {
      type: String,
      desc: 'Author\'s Name',
      required: true
    });

    this.option('work', {
      type: String,
      desc: 'Licensed Work Title',
      required: true
    });

    this.option('email', {
      type: String,
      desc: 'Author\'s Email',
      required: false
    });

    this.option('website', {
      type: String,
      desc: 'Author\'s Website',
      required: false
    });

    this.option('year', {
      type: String,
      desc: 'Year(s) to include on the license (e.g. 2016-2017)',
      required: true,
      defaults: (new Date()).getFullYear()
    });

    this.option('licensePrompt', {
      type: String,
      desc: 'License prompt text',
      required: true,
      defaults: 'Choose a Creative Commons license:'
    });

    this.option('license', {
      type: String,
      desc: 'License to Generate: CC-BY-4.0, CC-BY-SA-4.0, CC-BY-ND-4.0, CC-BY-NC-4.0, CC-BY-NC-SA-4.0, CC-BY-NC-ND-4.0, CC0-1.0',
      required: true
    });

    this.option('output', {
      type: String,
      desc: 'Output file',
      default: 'LICENSE',
      required: true
    });
  },

  initializing: function () {
    // get name via argument or fallback to git
    if (this._initOptions.name) {
      this.options.name = this._initOptions.name;
    }

    // get email via argument or fallback to git
    if (this._initOptions.email) {
      this.options.email = this._initOptions.email;
    }

    this.options.work = this._initOptions.work;
    this.options.year = this._initOptions.year;
    this.options.website = this._initOptions.website;
    this.options.output = this._initOptions.output || this.options.output;

    // Have Yeoman greet the user.
    this.log(yosay(
      'Generate Creative Commons LICENSE with ' +
        chalk.red('license-cc') + ' generator!'
    ));
  },

  prompting: {
    requiredPrompt() {
      var prompts = [
        {
          name: 'name',
          message: 'Author\'s Name:',
          default: this.options.name,
          when: !this._initOptions.name
        },
        {
          name: 'work',
          message: 'Licensed Work Title:',
          default: this.options.work,
          when: !this._initOptions.work
        },
        {
          name: 'year',
          message: 'Year(s) to include on the license (e.g. 2016-2017)',
          default: this.options.year,
          when: !this.options.year
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        if (answers.name) {
          this.options.name = answers.name.trim();
        }

        if (answers.work) {
          this.options.work = answers.work.trim();
        }

        if (answers.year) {
          this.options.year = answers.year;
        }
      }.bind(this));
    },
    contactConfirmPrompt() {
      var prompts = [
        {
          type: 'confirm',
          name: 'contactDetails',
          message: 'Would you like to add contact details?',
          default: true,
          when: !this._initOptions.email && !this._initOptions.website
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        this.options.contactDetails = answers.contactDetails;
      }.bind(this));
    },

    contactEmailPrompt() {
      if (this.options.contactDetails && !this._initOptions.email) {
        var prompts = [
          {
            name: 'email',
            message: 'Author\'s Email:',
            default: this.options.email
          }
        ];

        return this.prompt(prompts).then(function (answers) {
          this.options.email = answers.email;
        }.bind(this));
      }
    },

    contactWebsitePrompt() {
      if (this.options.contactDetails && !this._initOptions.website) {
        var prompts = [
          {
            name: 'website',
            message: 'Author\'s Website:',
            default: this.options.website
          }
        ];

        return this.prompt(prompts).then(function (answers) {
          this.options.website = answers.website;
        }.bind(this));
      }
    },
    licensePrompt() {
      var prompts = [
        {
          type: 'list',
          name: 'license',
          message: this.options.licensePrompt,
          default: this.options.license,
          choices: licenses,
          when: !this._initOptions.license
        },
        {
          name: 'output',
          message: 'Output file:',
          default: 'LICENSE',
          when: !this._initOptions.output
        }

      ];

      return this.prompt(prompts).then(function (answers) {
        if (answers.license) {
          this.options.license = answers.license;
        }

        if (answers.output) {
          this.options.output = answers.output;
        }
      }.bind(this));
    }
  },

  writing: function () {
    // check license file
    var filename = this.options.license + '.txt';
    if (!this.fs.exists(this.templatePath(filename))) {
      throw new Error('License \'' + filename + '\' NOT FOUND!');
    }

    // combine author data
    let author = this.options.name;
    if (this.options.email) {
      author += ' <' + this.options.email + '>';
    }
    if (this.options.website) {
      author += ' (' + this.options.website + ')';
    }

    // generate LICENSE from teplate file
    this.fs.copyTpl(
      this.templatePath(filename),
      this.destinationPath(this.options.output),
      {
        year: this.options.year,
        author: author,
        work: this.options.work
      }
    );
  },

  install: function () {
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'react-router';

import DCOSStore from '../stores/DCOSStore';

class ServicesBreadcrumb extends React.Component {
  constructor() {
    super();
  }

  render() {
    const {serviceTreeItem, taskID} = this.props;
    const groupId = serviceTreeItem.getId();
    const breadcrumbIcon = (

    );

    let breadcrumbNodes = [(

        <Link to="services-page">Services</Link>

    )];

    if (groupId === '/') {
      breadcrumbNodes[0] = (
        Services
      );
    }

    breadcrumbNodes = breadcrumbNodes.concat(
      DCOSStore.serviceTree.reduceItems(function (memo, item) {
        const id = item.getId();
        if (groupId.startsWith(id)) {
          const name = item.getName();

          let breadCrumbNode = (
            <Link
              to="services-detail"
              params={{id: encodeURIComponent(id)}}
              title={name}>
              {name}
            </Link>
          );

          if (id === groupId && taskID == null) {
            breadCrumbNode = (
              {name}
            );
          }

          memo.push(

              {breadcrumbIcon}
              {breadCrumbNode}

          );
        }

        return memo;
      }, [])
    );

    return (

          {breadcrumbNodes}

    );
  }
}

ServicesBreadcrumb.propTypes = {
  serviceTreeItem: React.PropTypes.object.isRequired,
  taskID: React.PropTypes.string
};

module.exports = ServicesBreadcrumb;
<commit_msg>Show task id in breadcrumbs<commit_after>import React from 'react';
import {Link} from 'react-router';

import DCOSStore from '../stores/DCOSStore';

class ServicesBreadcrumb extends React.Component {
  constructor() {
    super();
  }

  render() {
    const {serviceTreeItem, taskID} = this.props;
    const groupId = serviceTreeItem.getId();
    const breadcrumbIcon = (

    );

    let breadcrumbNodes = [(

        <Link to="services-page">Services</Link>

    )];

    if (groupId === '/') {
      breadcrumbNodes[0] = (
        Services
      );
    }

    breadcrumbNodes = breadcrumbNodes.concat(
      DCOSStore.serviceTree.reduceItems(function (memo, item) {
        const id = item.getId();
        if (groupId.startsWith(id)) {
          const name = item.getName();

          let breadCrumbNode = (
            <Link
              to="services-detail"
              params={{id: encodeURIComponent(id)}}
              title={name}>
              {name}
            </Link>
          );

          if (id === groupId && taskID == null) {
            breadCrumbNode = (
              {name}
            );
          }

          memo.push(

              {breadcrumbIcon}
              {breadCrumbNode}

          );
        }

        return memo;
      }, [])
    );

    if (taskID != null) {
      breadcrumbNodes.push(

          {breadcrumbIcon}
          {taskID}

      );
    }

    return (

          {breadcrumbNodes}

    );
  }
}

ServicesBreadcrumb.propTypes = {
  serviceTreeItem: React.PropTypes.object.isRequired,
  taskID: React.PropTypes.string
};

module.exports = ServicesBreadcrumb;
<|endoftext|>


<commit_before>var yeoman = require('yeoman-generator');

module.exports = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);

        var options = require('./options/index');

        this.description = "Yeoman generator for scaffolding Sails REST API with predefined features";

        Object.keys(options).forEach(function (name) {
            this.option(name, options[name]);
        }.bind(this));

        this.config.save();
    },

    initializing: require('./steps/initializing'),
    prompting: require('./steps/prompting'),
    configuring: require('./steps/configuring'),
    writing: require('./steps/writing'),
    conflicts: require('./steps/conflicts'),
    install: require('./steps/install'),
    end: require('./steps/end')
});
<commit_msg>Update description with more detailed description<commit_after>var yeoman = require('yeoman-generator');

module.exports = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);

        var options = require('./options/index');

        this.description = "Yeoman generator that provides already configured and optimized Sails REST API with bundle of predefined features";

        Object.keys(options).forEach(function (name) {
            this.option(name, options[name]);
        }.bind(this));

        this.config.save();
    },

    initializing: require('./steps/initializing'),
    prompting: require('./steps/prompting'),
    configuring: require('./steps/configuring'),
    writing: require('./steps/writing'),
    conflicts: require('./steps/conflicts'),
    install: require('./steps/install'),
    end: require('./steps/end')
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var fs = require('fs');
var vm = require('vm');
var path = require('path');

global.window = global;
global.document = {
  window: global
};

// Initializing FOAM_BOOT_DIR.
global.FOAM_BOOT_DIR = '';
if (process.argv[2]) {
  global.FOAM_BOOT_DIR = path.normalize(process.argv[2]);
}

// Loading all FOAM models.
var modelsfiles = fs.readFileSync(path.join(FOAM_BOOT_DIR, 'FOAMmodels.js'));
vm.runInThisContext(modelsfiles);

for (var i = 0; i < files.length; i++) {
  var filename = files[i] + '.js';
  var filedata = fs.readFileSync(path.join(FOAM_BOOT_DIR, filename));
  vm.runInThisContext(filedata, filename);
}

// Needed so that scripts can require other nodejs modules.
global.require = require;

// For command line processing, run as
// $ node bootFOAMnode.js <FOAM_BOOT_DIR> <script> <script args>
// Arguments are passed to the script as a global.argv array.
if (process.argv[3]) {
  var scriptPathname = path.normalize(process.argv[3]);
  global.argv = process.argv.slice(4);
  filedata = fs.readFileSync(scriptPathname);
  vm.runInThisContext(filedata, scriptPathname);
}
<commit_msg>Revert "Undoing bootFOAMNode.js changes from revision 1ad89af3ec0b."<commit_after>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var fs = require('fs');
var vm = require('vm');
var path = require('path');

// Initializing FOAM_BOOT_DIR.
global.FOAM_BOOT_DIR = __dirname;

// Needed so that scripts run through runInThisContext can require other nodejs
// modules.
global.require = require;

var foamLoader = fs.readFileSync(
    path.join(global.FOAM_BOOT_DIR, 'foam_context_loader.js'));
vm.runInThisContext(foamLoader);

<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  // prompting: function () {
  //   var done = this.async();

  //   // Have Yeoman greet the user.
  //   this.log(yosay(
  //     'Welcome to the perfect ' + chalk.red('generator-frdmn-bootstrap') + ' generator!'
  //   ));

  //   var prompts = [{
  //     type: 'confirm',
  //     name: 'someOption',
  //     message: 'Would you like to enable this option?',
  //     default: true
  //   }];

  //   this.prompt(prompts, function (props) {
  //     this.props = props;
  //     // To access props later use this.props.someOption;

  //     done();
  //   }.bind(this));
  // },

  writing: {
    git: function () {
      this.fs.copy(
        this.templatePath('gitignore'),
        this.destinationPath('.gitignore')
      );
    },

    gulpfile: function () {
      this.fs.copyTpl(
        this.templatePath('gulpfile.js'),
        this.destinationPath('gulpfile.js')
      );
    },

    packageJSON: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
    },

  writing: function () {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  },

  install: function () {
    this.installDependencies();
  }
});
<commit_msg>Copy all template files<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({
  // prompting: function () {
  //   var done = this.async();

  //   // Have Yeoman greet the user.
  //   this.log(yosay(
  //     'Welcome to the perfect ' + chalk.red('generator-frdmn-bootstrap') + ' generator!'
  //   ));

  //   var prompts = [{
  //     type: 'confirm',
  //     name: 'someOption',
  //     message: 'Would you like to enable this option?',
  //     default: true
  //   }];

  //   this.prompt(prompts, function (props) {
  //     this.props = props;
  //     // To access props later use this.props.someOption;

  //     done();
  //   }.bind(this));
  // },

  writing: {
    git: function () {
      this.fs.copy(
        this.templatePath('gitignore'),
        this.destinationPath('.gitignore')
      );
    },

    gulpfile: function () {
      this.fs.copyTpl(
        this.templatePath('gulpfile.js'),
        this.destinationPath('gulpfile.js')
      );
    },

    packageJSON: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
    },

    bower: function () {
      this.fs.copyTpl(
        this.templatePath('bower.json'),
        this.destinationPath('bower.json')
      );
    },

    assets: function () {
      this.fs.copyTpl(
        this.templatePath('assets/js/app.js'),
        this.destinationPath('assets/js/app.js')
      );

      this.fs.copyTpl(
        this.templatePath('assets/css/style.scss'),
        this.destinationPath('assets/css/style.scss')
      );

      this.fs.copyTpl(
        this.templatePath('assets/css/_example.scss'),
        this.destinationPath('assets/css/_example.scss')
      );
    },

    indexHTML: function () {
      this.fs.copyTpl(
        this.templatePath('index.html'),
        this.destinationPath('index.html')
      );
    },

    misc: function () {
      mkdirp('assets/images');
      mkdirp('fonts/fonts');
    }
  },

  install: function () {
    this.installDependencies();
  },

  end: function () {
    var completeMsg =
      '\nRun ' +
      chalk.yellow.bold('gulp') +
      ' to compile the assets and complete the setup.';

    this.log(completeMsg);
    return;
  }
});
<|endoftext|>


<commit_before>'use strict';

const fountain = require('fountain-generator');

module.exports = fountain.Base.extend({
  prompting: {
    fountain() {
      this.options.framework = 'angular1';
      this.fountainPrompting();
    },

    sample() {
      const done = this.async();

      this.option('sample', {type: Boolean, required: false});

      const prompts = [{
        when: !this.options.sample,
        type: 'list',
        name: 'sample',
        message: 'Do you want a sample app?',
        choices: [
          {name: 'A working landing page', value: 'techs'},
          {name: 'Just a Hello World', value: 'hello'}
        ]
      }];

      this.prompt(prompts, props => {
        Object.assign(this.props, this.props, props);
        done();
      });
    }
  },

  configuring() {
    this.mergeJson('package.json', {
      dependencies: {
        angular: '^1.5.0'
      },
      devDependencies: {
        'angular-mocks': '^1.5.0',
        'gulp-angular-templatecache': '^1.8.0'
      }
    });
  },

  composing() {
    this.composeWith(`fountain-angular1:${this.props.sample}`, {options: this.props}, {
      local: require.resolve(`../${this.props.sample}/${this.props.modules === 'inject' ? 'inject' : 'modules'}`)
    });
    this.composeWith('fountain-gulp', {options: this.props}, {
      local: require.resolve('generator-fountain-gulp/generators/app')
    });
  },

  writing() {
    this.copyTemplate('src/index.html', 'src/index.html');
  }
});
<commit_msg>Select options for composeWith<commit_after>'use strict';

const fountain = require('fountain-generator');

module.exports = fountain.Base.extend({
  prompting: {
    fountain() {
      this.options.framework = 'angular1';
      this.fountainPrompting();
    },

    sample() {
      const done = this.async();

      this.option('sample', {type: Boolean, required: false});

      const prompts = [{
        when: !this.options.sample,
        type: 'list',
        name: 'sample',
        message: 'Do you want a sample app?',
        choices: [
          {name: 'A working landing page', value: 'techs'},
          {name: 'Just a Hello World', value: 'hello'}
        ]
      }];

      this.prompt(prompts, props => {
        Object.assign(this.props, this.props, props);
        done();
      });
    }
  },

  configuring() {
    this.mergeJson('package.json', {
      dependencies: {
        angular: '^1.5.0'
      },
      devDependencies: {
        'angular-mocks': '^1.5.0',
        'gulp-angular-templatecache': '^1.8.0'
      }
    });
  },

  composing() {
    const options = {
      framework: this.props.framework,
      modules: this.props.modules,
      js: this.props.js,
      css: this.props.css
    };

    this.composeWith(`fountain-angular1:${this.props.sample}`, {options}, {
      local: require.resolve(`../${this.props.sample}/${this.props.modules === 'inject' ? 'inject' : 'modules'}`)
    });
    this.composeWith('fountain-gulp', {options}, {
      local: require.resolve('generator-fountain-gulp/generators/app')
    });
  },

  writing() {
    this.copyTemplate('src/index.html', 'src/index.html');
  }
});
<|endoftext|>