<commit_before>var Module = require('./module');
var autoAnnotate = require('./annotation').parse;
var annotate = require('./annotation').annotate;

var Injector = function(modules, parent) {
  parent = parent || {
    get: function(name) {
      currentlyResolving.push(name);
      throw error('No provider for "' + name + '"!');
    }
  };

  var currentlyResolving = [];
  var providers = this._providers = Object.create(parent._providers || null);
  var instances = this._instances = Object.create(null);

  var self = instances.injector = this;

  var error = function(msg) {
    var stack = currentlyResolving.join(' -> ');
    currentlyResolving.length = 0;
    return new Error(stack ? msg + ' (Resolving: ' + stack + ')' : msg);
  };

  var get = function(name) {
    if (!providers[name] && name.indexOf('.') !== -1) {
      var parts = name.split('.');
      var pivot = get(parts.shift());

      while(parts.length) {
        pivot = pivot[parts.shift()];
      }

      return pivot;
    }

    if (Object.hasOwnProperty.call(instances, name)) {
      return instances[name];
    }

    if (Object.hasOwnProperty.call(providers, name)) {
      if (currentlyResolving.indexOf(name) !== -1) {
        currentlyResolving.push(name);
        throw error('Can not resolve circular dependency!');
      }

      currentlyResolving.push(name);
      instances[name] = providers[name][0](providers[name][1]);
      currentlyResolving.pop();

      return instances[name];
    }

    return parent.get(name);
  };

  var instantiate = function(Type) {
    var instance = Object.create(Type.prototype);
    var returned = invoke(Type, instance);

    return typeof returned === 'object' ? returned : instance;
  };

  var invoke = function(fn, context) {
    if (typeof fn !== 'function') {
      throw error('Can not invoke "' + fn + '". Expected a function!');
    }

    var inject = fn.$inject && fn.$inject || autoAnnotate(fn);
    var dependencies = inject.map(function(dep) {
      return get(dep);
    });

    // TODO(vojta): optimize without apply
    return fn.apply(context, dependencies);
  };

  var createPrivateInjectorFactory = function(privateChildInjector) {
    return annotate(function(key) {
      return privateChildInjector.get(key);
    });
  };

  var createChild = function(modules, forceNewInstances) {
    if (forceNewInstances && forceNewInstances.length) {
      var fromParentModule = Object.create(null);
      var matchedScopes = Object.create(null);

      var privateInjectorsCache = [];
      var privateChildInjectors = [];
      var privateChildFactories = [];

      var provider;
      var cacheIdx;
      var privateChildInjector;
      var privateChildInjectorFactory;
      for (var name in providers) {
        provider = providers[name];

        if (forceNewInstances.indexOf(name) !== -1) {
          if (provider[2] === 'private') {
            cacheIdx = privateInjectorsCache.indexOf(provider[3]);
            if (cacheIdx === -1) {
              privateChildInjector = provider[3].createChild([], forceNewInstances);
              privateChildInjectorFactory = createPrivateInjectorFactory(privateChildInjector);
              privateInjectorsCache.push(provider[3]);
              privateChildInjectors.push(privateChildInjector);
              privateChildFactories.push(privateChildInjectorFactory);
              fromParentModule[name] = [privateChildInjectorFactory, name, 'private', privateChildInjector];
            } else {
              fromParentModule[name] = [privateChildFactories[cacheIdx], name, 'private', privateChildInjectors[cacheIdx]];
            }
          } else {
            fromParentModule[name] = [provider[2], provider[1]];
          }
          matchedScopes[name] = true;
        }

        if ((provider[2] === 'factory' || provider[2] === 'type') && provider[1].$scope) {
          forceNewInstances.forEach(function(scope) {
            if (provider[1].$scope.indexOf(scope) !== -1) {
              fromParentModule[name] = [provider[2], provider[1]];
              matchedScopes[scope] = true;
            }
          });
        }
      }

      forceNewInstances.forEach(function(scope) {
        if (!matchedScopes[scope]) {
          throw new Error('No provider for "' + scope + '". Can not use provider from the parent!');
        }
      });

      modules.unshift(fromParentModule);
    }

    return new Injector(modules, self);
  };

  var factoryMap = {
    factory: invoke,
    type: instantiate,
    value: function(value) {
      return value;
    }
  };

  modules.forEach(function(module) {
    // TODO(vojta): handle wrong inputs (modules)
    if (module instanceof Module) {
      module.forEach(function(provider) {
        var name = provider[0];
        var type = provider[1];
        var value = provider[2];

        providers[name] = [factoryMap[type], value, type];
      });
    } else if (typeof module === 'object') {
      if (module.__exports__) {
        var clonedModule = Object.keys(module).reduce(function(m, key) {
          if (key.substring(0, 2) !== '__') {
            m[key] = module[key];
          }
          return m;
        }, Object.create(null));

        var privateInjector = new Injector((module.__modules__ || []).concat([clonedModule]), self);
        var getFromPrivateInjector = annotate(function(key) {
          return privateInjector.get(key);
        });
        module.__exports__.forEach(function(key) {
          providers[key] = [getFromPrivateInjector, key, 'private', privateInjector];
        });
      } else {
        Object.keys(module).forEach(function(name) {
          if (module[name][2] === 'private') {
            providers[name] = module[name];
            return;
          }

          var type = module[name][0];
          var value = module[name][1];

          providers[name] = [factoryMap[type], value, type];
        });
      }
    }
  });

  // public API
  this.get = get;
  this.invoke = invoke;
  this.instantiate = instantiate;
  this.createChild = createChild;
};

module.exports = Injector;
<commit_msg>refactor: cleanup<commit_after>var Module = require('./module');
var autoAnnotate = require('./annotation').parse;
var annotate = require('./annotation').annotate;

var Injector = function(modules, parent) {
  parent = parent || {
    get: function(name) {
      currentlyResolving.push(name);
      throw error('No provider for "' + name + '"!');
    }
  };

  var currentlyResolving = [];
  var providers = this._providers = Object.create(parent._providers || null);
  var instances = this._instances = Object.create(null);

  var self = instances.injector = this;

  var error = function(msg) {
    var stack = currentlyResolving.join(' -> ');
    currentlyResolving.length = 0;
    return new Error(stack ? msg + ' (Resolving: ' + stack + ')' : msg);
  };

  var get = function(name) {
    if (!providers[name] && name.indexOf('.') !== -1) {
      var parts = name.split('.');
      var pivot = get(parts.shift());

      while(parts.length) {
        pivot = pivot[parts.shift()];
      }

      return pivot;
    }

    if (Object.hasOwnProperty.call(instances, name)) {
      return instances[name];
    }

    if (Object.hasOwnProperty.call(providers, name)) {
      if (currentlyResolving.indexOf(name) !== -1) {
        currentlyResolving.push(name);
        throw error('Can not resolve circular dependency!');
      }

      currentlyResolving.push(name);
      instances[name] = providers[name][0](providers[name][1]);
      currentlyResolving.pop();

      return instances[name];
    }

    return parent.get(name);
  };

  var instantiate = function(Type) {
    var instance = Object.create(Type.prototype);
    var returned = invoke(Type, instance);

    return typeof returned === 'object' ? returned : instance;
  };

  var invoke = function(fn, context) {
    if (typeof fn !== 'function') {
      throw error('Can not invoke "' + fn + '". Expected a function!');
    }

    var inject = fn.$inject || autoAnnotate(fn);
    var dependencies = inject.map(function(dep) {
      return get(dep);
    });

    // TODO(vojta): optimize without apply
    return fn.apply(context, dependencies);
  };

  var createPrivateInjectorFactory = function(privateChildInjector) {
    return annotate(function(key) {
      return privateChildInjector.get(key);
    });
  };

  var createChild = function(modules, forceNewInstances) {
    if (forceNewInstances && forceNewInstances.length) {
      var fromParentModule = Object.create(null);
      var matchedScopes = Object.create(null);

      var privateInjectorsCache = [];
      var privateChildInjectors = [];
      var privateChildFactories = [];

      var provider;
      var cacheIdx;
      var privateChildInjector;
      var privateChildInjectorFactory;
      for (var name in providers) {
        provider = providers[name];

        if (forceNewInstances.indexOf(name) !== -1) {
          if (provider[2] === 'private') {
            cacheIdx = privateInjectorsCache.indexOf(provider[3]);
            if (cacheIdx === -1) {
              privateChildInjector = provider[3].createChild([], forceNewInstances);
              privateChildInjectorFactory = createPrivateInjectorFactory(privateChildInjector);
              privateInjectorsCache.push(provider[3]);
              privateChildInjectors.push(privateChildInjector);
              privateChildFactories.push(privateChildInjectorFactory);
              fromParentModule[name] = [privateChildInjectorFactory, name, 'private', privateChildInjector];
            } else {
              fromParentModule[name] = [privateChildFactories[cacheIdx], name, 'private', privateChildInjectors[cacheIdx]];
            }
          } else {
            fromParentModule[name] = [provider[2], provider[1]];
          }
          matchedScopes[name] = true;
        }

        if ((provider[2] === 'factory' || provider[2] === 'type') && provider[1].$scope) {
          forceNewInstances.forEach(function(scope) {
            if (provider[1].$scope.indexOf(scope) !== -1) {
              fromParentModule[name] = [provider[2], provider[1]];
              matchedScopes[scope] = true;
            }
          });
        }
      }

      forceNewInstances.forEach(function(scope) {
        if (!matchedScopes[scope]) {
          throw new Error('No provider for "' + scope + '". Can not use provider from the parent!');
        }
      });

      modules.unshift(fromParentModule);
    }

    return new Injector(modules, self);
  };

  var factoryMap = {
    factory: invoke,
    type: instantiate,
    value: function(value) {
      return value;
    }
  };

  modules.forEach(function(module) {
    // TODO(vojta): handle wrong inputs (modules)
    if (module instanceof Module) {
      module.forEach(function(provider) {
        var name = provider[0];
        var type = provider[1];
        var value = provider[2];

        providers[name] = [factoryMap[type], value, type];
      });
    } else if (typeof module === 'object') {
      if (module.__exports__) {
        var clonedModule = Object.keys(module).reduce(function(m, key) {
          if (key.substring(0, 2) !== '__') {
            m[key] = module[key];
          }
          return m;
        }, Object.create(null));

        var privateInjector = new Injector((module.__modules__ || []).concat([clonedModule]), self);
        var getFromPrivateInjector = annotate(function(key) {
          return privateInjector.get(key);
        });
        module.__exports__.forEach(function(key) {
          providers[key] = [getFromPrivateInjector, key, 'private', privateInjector];
        });
      } else {
        Object.keys(module).forEach(function(name) {
          if (module[name][2] === 'private') {
            providers[name] = module[name];
            return;
          }

          var type = module[name][0];
          var value = module[name][1];

          providers[name] = [factoryMap[type], value, type];
        });
      }
    }
  });

  // public API
  this.get = get;
  this.invoke = invoke;
  this.instantiate = instantiate;
  this.createChild = createChild;
};

module.exports = Injector;
<|endoftext|>


<commit_before>node = {
    complex : { // Interface class for all complex nodes
        addNodes : function (node) {
            if (!node) return;

            if (helper.isArray(node)) {
                this.nodes = this.nodes.concat(node);
                return;
            }

            // If the node is complex it has to be disassembled
            if (node.pureVirtual) { //node instanceof virtualComplexNode) { -- this typing is not working, using duck typing
                var increment=this.nodes.length;
                for (var i=0;i<node.nodes.length;i++)
                    this.nodes.push(node.nodes[i]);
                // copy variables
                for (var i=0;i<node.edges.length;i++) {
                    this.edges.push(new edge.single(node.edges[i].nodeFrom===-1?-1:node.edges[i].nodeFrom+increment, portFrom,
                                                            node.edges[i].nodeTo===-1?-1:node.edges[i].nodeTo+increment, portTo));
                }
            } else
                this.nodes.push(node);
        },
        toXML : function (id) {
            var innerXML = '';
            var i;
            var data = {type:this.type};
            if (typeof this.fields !== "undefined") for (i=0; i<this.fields.length; i++) data[this.fields[i]] = this[this.fields[i]];

            for (i=0; i<this.inPorts.length; i++) innerXML += graphmlgen.port('in' + i);
            for (i=0; i<this.outPorts.length; i++) innerXML += graphmlgen.port('out' + i);
            for (i=0; i<this.nodes.length; i++) innerXML += this.nodes[i].toXML(id + '::n' + i);
            for (i=0; i<this.edges.length; i++) innerXML += edge.toXML(id, this.edges[i]);
            return graphmlgen.node(id, data, graphmlgen.subgraph(id + ':', innerXML));
        },
        execute : function () {
            for (var i=0; i<this.nodes.length; i++) {
              if (this.nodes[i].execute) this.nodes[i].execute();
            }
        },
        toText : function () {
            var inFree = 0, outFree = 0; // Number of non-assigned input and output ports
            for (i=0; i<this.outPorts.length; i++)
                if (!this.outPorts.value) outFree++;
            for (i=0; i<this.inPorts.length; i++)
                if (!this.inPorts.value) inFree++;
            if (inFree === 0) {
                return this.outPorts.toString();
            } else {
                return this.inPorts.toString() + " -> " + this.outPorts.toString();
            }
        }
    },
    simple : {
        toXML : function (id) {
            var innerXML = '';
            var i;
            var data = {type:this.type};
            if (typeof this.fields !== "undefined") for (i=0; i<this.fields.length; i++) data[this.fields[i]] = this[this.fields[i]];

            for (i=0; i<this.inPorts.length; i++) innerXML += graphmlgen.port('in' + i);
            for (i=0; i<this.outPorts.length; i++) innerXML += graphmlgen.port('out' + i);
            return graphmlgen.node(id, data, innerXML);
        }
    }
}
node.virtualComplex = function () {
        this.nodes = [];
        this.edges = [];
        this.pureVirtual = true;
    }

node.virtualComplex.prototype = node.complex;

node.func = function (name, inPorts, outPorts) {
        var self = this;
        this.type = "function";
        this.name = name;
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
        this.fields = ["name"];
    }

node.func.prototype = node.complex;

node.loopBody = function (inPorts, outPorts) {
        this.type = "loopBody";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
    }

node.loopBody.prototype = node.complex;

node.loopReturn = function (name, inPorts, outPorts) {
        this.type = "loopReturn";
        this.name = name;
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
    }

node.loopReturn.prototype = node.complex;

node.rangeGen = function (inPorts, outPorts) {
        this.type = "rangeGen";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
    }

node.rangeGen.prototype = node.complex;

node.forAll = function (range, body, returns, inPorts, outPorts) {
        this.type = "forall";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [range, body, returns];
        this.edges = []; // There are no explicit connections also
    }

node.forAll.prototype = node.complex;

node.binary = function (op, inPorts, outPorts) {
        this.type = "binary";
        this.op = op;
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.fields = ["op"];
    }

node.binary.prototype = node.simple;

node.element = function (inPorts, outPorts) {
        this.type = "element";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
    }

node.element.prototype = node.simple;

node.range = function (inPorts, outPorts) {
        this.type = "range";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
    }

node.range.prototype = node.simple;

node.scatter = function (inPort, outPort) {
        this.type = "scatter";
        this.inPorts = [inPort];
        this.outPorts = [outPort];
    }

node.scatter.prototype = node.simple;

node.identifier = function (id, color) { // port with name
        this.type = "id";
        this.inPorts = [];
        this.outPorts = [new port.colored(color)];
        this.id = id;
        this.color = color;
    }

node.identifier.prototype = node.simple;

node.constant = function (value, color) { // port with name
        var self = this;
        this.type = "constant";
        this.inPorts = [];
        this.outPorts = [new port.colored(color)];
        this.value = value;
        this.color = color;
        this.fields = ["value"];
        this.toText = function () {return this.value;}
    }

node.constant.prototype = node.simple;

node.fake = function (color) {
        this.inPorts = [];
        this.outPorts = [];
        this.color = color;
        this.fake = 1;
    }

node.fake.prototype = node.simple;

node.sisalir = function(ast){ // constructs sisal IR from Abstract syntax tree
    var irGen = new irGenerator();
    var self = this;

    this.nodes=[];
    this.inPorts = [];
    this.outPorts = [];

    for (var i=0;i<ast.length;i++) {
        this.addNodes(irGen.parse(ast[i]));
    }
    this.toGraphML = function () {
        var xmlstr = '';
        for (var i=0; i<self.nodes.length; i++) {
           xmlstr += self.nodes[i].toXML("n" + i);
        }
        return graphmlgen.headers(xmlstr);
    }
}

node.sisalir.prototype=node.complex;
<commit_msg>works for constants now<commit_after>node = {
    complex : { // Interface class for all complex nodes
        addNodes : function (node) {
            if (!node) return;

            if (helper.isArray(node)) {
                this.nodes = this.nodes.concat(node);
                return;
            }

            // If the node is complex it has to be disassembled
            if (node.pureVirtual) { //node instanceof virtualComplexNode) { -- this typing is not working, using duck typing
                var increment=this.nodes.length;
                for (var i=0;i<node.nodes.length;i++)
                    this.nodes.push(node.nodes[i]);
                // copy variables
                for (var i=0;i<node.edges.length;i++) {
                    this.edges.push(new edge.single(node.edges[i].nodeFrom===-1?-1:node.edges[i].nodeFrom+increment, portFrom,
                                                            node.edges[i].nodeTo===-1?-1:node.edges[i].nodeTo+increment, portTo));
                }
            } else
                this.nodes.push(node);
        },
        toXML : function (id) {
            var innerXML = '';
            var i;
            var data = {type:this.type};
            if (typeof this.fields !== "undefined") for (i=0; i<this.fields.length; i++) data[this.fields[i]] = this[this.fields[i]];

            for (i=0; i<this.inPorts.length; i++) innerXML += graphmlgen.port('in' + i);
            for (i=0; i<this.outPorts.length; i++) innerXML += graphmlgen.port('out' + i);
            for (i=0; i<this.nodes.length; i++) innerXML += this.nodes[i].toXML(id + '::n' + i);
            for (i=0; i<this.edges.length; i++) innerXML += edge.toXML(id, this.edges[i]);
            return graphmlgen.node(id, data, graphmlgen.subgraph(id + ':', innerXML));
        },
        execute : function () {
            for (var i=0; i<this.nodes.length; i++) {
              if (this.nodes[i].execute) this.nodes[i].execute();
            }
        },
        toText : function () {
            var inFree = 0, outFree = 0; // Number of non-assigned input and output ports
            for (i=0; i<this.outPorts.length; i++)
                if (!this.outPorts.value) outFree++;
            for (i=0; i<this.inPorts.length; i++)
                if (!this.inPorts.value) inFree++;
            if (inFree === 0) {
                return this.outPorts.toString();
            } else {
                return this.inPorts.toString() + " -> " + this.outPorts.toString();
            }
        }
    },
    simple : {
        toXML : function (id) {
            var innerXML = '';
            var i;
            var data = {type:this.type};
            if (typeof this.fields !== "undefined") for (i=0; i<this.fields.length; i++) data[this.fields[i]] = this[this.fields[i]];

            for (i=0; i<this.inPorts.length; i++) innerXML += graphmlgen.port('in' + i);
            for (i=0; i<this.outPorts.length; i++) innerXML += graphmlgen.port('out' + i);
            return graphmlgen.node(id, data, innerXML);
        }
    }
}
node.virtualComplex = function () {
        this.nodes = [];
        this.edges = [];
        this.pureVirtual = true;
    }

node.virtualComplex.prototype = node.complex;

node.func = function (name, inPorts, outPorts) {
        var self = this;
        this.type = "function";
        this.name = name;
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
        this.fields = ["name"];
    }

node.func.prototype = node.complex;

node.loopBody = function (inPorts, outPorts) {
        this.type = "loopBody";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
    }

node.loopBody.prototype = node.complex;

node.loopReturn = function (name, inPorts, outPorts) {
        this.type = "loopReturn";
        this.name = name;
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
    }

node.loopReturn.prototype = node.complex;

node.rangeGen = function (inPorts, outPorts) {
        this.type = "rangeGen";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [];
        this.edges = [];
    }

node.rangeGen.prototype = node.complex;

node.forAll = function (range, body, returns, inPorts, outPorts) {
        this.type = "forall";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.nodes = [range, body, returns];
        this.edges = []; // There are no explicit connections also
    }

node.forAll.prototype = node.complex;

node.binary = function (op, inPorts, outPorts) {
        this.type = "binary";
        this.op = op;
        this.inPorts = inPorts;
        this.outPorts = outPorts;
        this.fields = ["op"];
    }

node.binary.prototype = node.simple;

node.element = function (inPorts, outPorts) {
        this.type = "element";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
    }

node.element.prototype = node.simple;

node.range = function (inPorts, outPorts) {
        this.type = "range";
        this.inPorts = inPorts;
        this.outPorts = outPorts;
    }

node.range.prototype = node.simple;

node.scatter = function (inPort, outPort) {
        this.type = "scatter";
        this.inPorts = [inPort];
        this.outPorts = [outPort];
    }

node.scatter.prototype = node.simple;

node.identifier = function (id, color) { // port with name
        this.type = "id";
        this.inPorts = [];
        this.outPorts = [new port.colored(color)];
        this.id = id;
        this.color = color;
    }

node.identifier.prototype = node.simple;

node.constant = function (value, color) { // port with name
        var self = this;
        this.type = "constant";
        this.inPorts = [];
        this.outPorts = [new port.colored(color)];
        this.value = value;
        this.color = color;
        this.fields = ["value"];
        this.toText = function () {return this.value;}
    }

node.constant.prototype = node.simple;

node.fake = function (color) {
        this.inPorts = [];
        this.outPorts = [];
        this.color = color;
        this.fake = 1;
    }

node.fake.prototype = node.simple;

node.sisalir = function(ast){ // constructs sisal IR from Abstract syntax tree
    var irGen = new irGenerator();
    var self = this;

    this.nodes=[];
    this.inPorts = [];
    this.outPorts = [];

    for (var i=0;i<ast.length;i++) {
        this.addNodes(irGen.parse(ast[i]));
    }
    this.toGraphML = function () {
        var xmlstr = '';
        for (var i=0; i<self.nodes.length; i++) {
           xmlstr += self.nodes[i].toXML("n" + i);
        }
        return graphmlgen.headers(xmlstr);
    }
    this.toText = function () {
        var str = '';
        for (var i=0; i<self.nodes.length; i++) {
           str += self.nodes[i].toText();
        }
        return str;
    }
}

node.sisalir.prototype=node.complex;
<|endoftext|>


<commit_before>/**
 * Converts JSON object to XML string.
 *
 *
 * Copyright(c) 2011 Etienne Lachance <et@etiennelachance.com>
 * MIT Licensed
 */

/*
 * Modifications (Ivo Georgiev <ivo@linvo.org>):
 *  Escape XML entities to avoid breaking the XML if any string in the JSON contains a special char
 *  Ignore special objects - objects that inherit other objects (in practice, when working with a third-party library, most of those are circular structures)
 */

 /*
 *  Modifications (Alan Clarke <hi@alz.so>):
 *  added unit tests, ability to add xml node attributes, xml header option and simplified syntax
 *  removed root node, this is already covered by the module's default functionality
 */

var util = require('util');

var settings = {
    attributes_key: false,
    header: false
};

module.exports = function xml(json, opts) {
    'use strict';

    if (opts) {
        Object.keys(settings).forEach(function (k) {
            if (opts[k] === undefined) {
                opts[k] = settings[k];
            }
        });
    } else {
        opts = settings;
    }

    var result = opts.header ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
    opts.header = false;

    if (!!json.length && typeof json !== 'string') { //Array
        json.forEach(function (node) {
            result += xml(node, opts);
        });
    } else if (typeof json === 'object') {
        Object.keys(json).forEach(function (key) {
            if (key !== opts.attributes_key) {
                var node = json[key],
                    attributes = '';

                if (node === undefined || node === null) {
                    node = '';
                }

                if (opts.attributes_key && json[opts.attributes_key]) {
                    Object.keys(json[opts.attributes_key]).forEach(function (k) {
                        attributes += util.format(' %s="%s"', k, json[opts.attributes_key][k]);
                    });
                }
                var inner = xml(node, opts);

                if (inner) {
                    result += util.format("<%s%s>%s</%s>", key, attributes, xml(node, opts), key);
                } else {
                    result += util.format("<%s%s/>", key, attributes);
                }
            }
        });
    } else {
        if (json.match(/<\!\[CDATA\[.*]]>/)) {
            return json.toString();
        }
        return json.toString().replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
    }

    return result;
};
<commit_msg>check start and end line matching<commit_after>/**
 * Converts JSON object to XML string.
 *
 *
 * Copyright(c) 2011 Etienne Lachance <et@etiennelachance.com>
 * MIT Licensed
 */

/*
 * Modifications (Ivo Georgiev <ivo@linvo.org>):
 *  Escape XML entities to avoid breaking the XML if any string in the JSON contains a special char
 *  Ignore special objects - objects that inherit other objects (in practice, when working with a third-party library, most of those are circular structures)
 */

 /*
 *  Modifications (Alan Clarke <hi@alz.so>):
 *  added unit tests, ability to add xml node attributes, xml header option and simplified syntax
 *  removed root node, this is already covered by the module's default functionality
 */

var util = require('util');

var settings = {
    attributes_key: false,
    header: false
};

module.exports = function xml(json, opts) {
    'use strict';

    if (opts) {
        Object.keys(settings).forEach(function (k) {
            if (opts[k] === undefined) {
                opts[k] = settings[k];
            }
        });
    } else {
        opts = settings;
    }

    var result = opts.header ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
    opts.header = false;

    if (!!json.length && typeof json !== 'string') { //Array
        json.forEach(function (node) {
            result += xml(node, opts);
        });
    } else if (typeof json === 'object') {
        Object.keys(json).forEach(function (key) {
            if (key !== opts.attributes_key) {
                var node = json[key],
                    attributes = '';

                if (node === undefined || node === null) {
                    node = '';
                }

                if (opts.attributes_key && json[opts.attributes_key]) {
                    Object.keys(json[opts.attributes_key]).forEach(function (k) {
                        attributes += util.format(' %s="%s"', k, json[opts.attributes_key][k]);
                    });
                }
                var inner = xml(node, opts);

                if (inner) {
                    result += util.format("<%s%s>%s</%s>", key, attributes, xml(node, opts), key);
                } else {
                    result += util.format("<%s%s/>", key, attributes);
                }
            }
        });
    } else {
        if (json.match(/^<\!\[CDATA\[.*]]>$/)) {
            return json.toString();
        }
        return json.toString().replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
    }

    return result;
};
<|endoftext|>


<commit_before>/*global module, exports, require*/
/*jslint vars:true, evil:true*/
/* JSONPath 0.8.0 - XPath for JSON
 *
 * Copyright (c) 2007 Stefan Goessner (goessner.net)
 * Licensed under the MIT (MIT-LICENSE.txt) licence.
 */

'use strict';

var vm = require('vm');
var _ = require("lodash");

var arrayset = require('./arrayset');

var append = arrayset.append;

function push(arr, elem) {
    arr = arr.slice();
    arr.push(elem);
    return arr;
}

var properties = function (obj) {
    if (Array.isArray(obj)) {
        return _.range(obj.length);
    } else if (typeof obj === 'object') {
        return Object.keys(obj);
    } else {
        return null;
    }
};

var sliceToProperties = function (expr, obj) {
    var len = obj.length;
    var parts = expr.split(':');
    var start = (parts[0] && parseInt(parts[0], 10)) || 0;
    var end = (parts[1] && parseInt(parts[1], 10)) || len;
    var step = (parts[2] && parseInt(parts[2], 10)) || 1;
    start = (start < 0) ? Math.max(0, start + len) : Math.min(len, start);
    end = (end < 0) ? Math.max(0, end + len) : Math.min(len, end);
    return _.range(start, end, step);
};

var asPath = function (path) {
    var i, n, x = path,
        p = '$';
    for (i = 1, n = x.length; i < n; i++) {
        p += /^[0-9*]+$/.test(x[i]) ? ('[' + x[i] + ']') : ("['" + x[i] + "']");
    }
    return p;
};

var normalize = exports.normalize = function (expr) {
    var exprList = [];
    var index = 0;
    var length = expr.length;
    var lastIndex = 0;
    while (index < length) {
        var c = expr.charAt(index);
        if (c === '.') {
            var cp1 = expr.charAt(index + 1);
            if (lastIndex !== index) {
                var subExpr = expr.substring(lastIndex, index);
                exprList.push(subExpr);
            }
            if (cp1 === '.') {
                exprList.push('..');
                ++index;
            }
            ++index;
            lastIndex = index;
            continue;
        }
        if (c === '[') {
            if (lastIndex !== index) {
                var subExprLB = expr.substring(lastIndex, index);
                exprList.push(subExprLB);
            }
            var openBrackets = 1;
            ++index;
            lastIndex = index;
            while (index < length) {
                var cinside = expr.charAt(index);
                if (cinside === '[') {
                    ++openBrackets;
                    ++index;
                    continue;
                }
                if (cinside === ']') {
                    --openBrackets;
                    if (openBrackets === 0) {
                        var subExprInside = expr.substring(lastIndex, index);
                        exprList.push(subExprInside);
                        ++index;
                        lastIndex = index;
                        break;
                    }
                }
                ++index;
            }
            continue;
        }
        if ((c === '^') || (c === '$')) {
            if (lastIndex !== index) {
                var subExprUC = expr.substring(lastIndex, index);
                exprList.push(subExprUC);
            }
            exprList.push(c);
            ++index;
            lastIndex = index;
            continue;
        }
        ++index;
    }
    if (lastIndex < index) {
        var subExprFinal = expr.substring(lastIndex, index);
        exprList.push(subExprFinal);
    }
    return exprList;
};

var processOptions = function (opts) {
    return {
        resultType: (opts && opts.resultType && opts.resultType.toLowerCase()) || 'value',
        flatten: (opts && opts.flatten) || false,
        wrap: (opts && opts.hasOwnProperty('wrap')) ? opts.wrap : true,
        sandbox: (opts && opts.sandbox) || {}
    };
};

var jsonPathMethods = {
    evaluate: function (obj, exprList) {
        this._obj = obj;
        if (exprList && obj) {
            if (exprList[0] === '$' && exprList.length > 1) {
                exprList.shift();
            }
            var result = this.trace(exprList, obj, ['$']);
            return result;
        }
    },
    allProperties: function (actions, obj, path) {
        var ps = properties(obj);
        return this.traceProperties(ps, actions, obj, path);
    },
    traceProperties: function (properties, actions, obj, path) {
        var result = [];
        if (properties) {
            properties.forEach(function (p) {
                var v = this.traceProperty(p, actions, obj, path);
                append(result, v);
            }, this);
        }
        return this.transferResult(obj, result);
    },
    traceProperty: function (property, actions, obj, path) {
        var result = [];
        if (obj && obj.hasOwnProperty(property)) {
            var v = this.trace(actions, obj[property], push(path, property));
            append(result, v);
        }
        return this.transferResult(obj, result);
    },
    allDeepProperties: function (actions, obj, path) {
        var result = [];
        var rootResult = this.trace(actions, obj, path);
        append(result, rootResult);
        var ps = properties(obj);
        if (ps) {
            ps = ps.filter(function (p) {
                return typeof obj[p] === 'object';
            });
        }
        if (ps) {
            ps.forEach(function (p) {
                var v = this.allDeepProperties(actions, obj[p], push(path, p));
                append(result, v);
            }, this);
        }
        return this.transferResult(obj, result);
    },
    expressionProperties: function (expression) {
        return function (actions, obj, path) {
            var result = [];
            var property = this.eval(expression, obj, path[path.length], path);
            return this.traceProperty(property, actions, obj, path);
        };
    },
    filteredProperties: function (expression) {
        return function (actions, obj, path) {
            var ps = properties(obj);
            if (ps) {
                var locHere = expression.replace(/^\?\((.*?)\)$/, '$1');
                ps = ps.filter(function (p) {
                    return this.eval(locHere, obj[p], p, path);
                }, this);
            }
            return this.traceProperties(ps, actions, obj, path);
        };
    },
    listProperties: function (listExpression) {
        var properties = listExpression.split(',');
        return function (actions, obj, path) {
            return this.traceProperties(properties, actions, obj, path);
        };
    },
    indexProperties: function (indicesExpression) {
        return function (actions, obj, path) {
            var psPy = sliceToProperties(indicesExpression, obj);
            return this.traceProperties(psPy, actions, obj, path);
        };
    },
    tracePropertyFn: function (property) {
        return function (actions, obj, path) {
            return this.traceProperty(property, actions, obj, path);
        };
    },
    toParent: function (actions, obj, path) {
        return path.length ? [{
            path: path.slice(0, -1),
            expr: actions,
            isParentSelector: true
        }] : [];
    },
    trace: function (actions, val, path) {
        if (!actions.length) {
            return [{
                path: path,
                value: val
            }];
        }
        var action = actions[0];
        var remainingActions = actions.slice(1);

        return action.call(this, remainingActions, val, path);
    },
    // We check the resulting values for parent selections. For parent
    // selections we discard the value object and continue the trace with the
    // current val object
    transferResult: function (obj, result) {
        var self = this;
        return result.reduce(function (all, ea) {
            if (ea.isParentSelector) {
                var v = self.trace(ea.expr, obj, ea.path);
                return all.concat(v);
            } else {
                all.push(ea);
                return all;
            }
        }, []);
    },
    eval: function (code, _v, _vname, path) {
        if (!this._obj || !_v) {
            return false;
        }
        if (code.indexOf('@path') > -1) {
            this.sandbox._$_path = asPath(path.concat([_vname]));
            code = code.replace(/@path/g, '_$_path');
        }
        if (code.indexOf('@') > -1) {
            this.sandbox._$_v = _v;
            code = code.replace(/@/g, '_$_v');
        }
        try {
            return vm.runInNewContext(code, this.sandbox);
        } catch (e) {
            console.log(e);
            throw new Error('jsonPath: ' + e.message + ': ' + code);
        }
    }
};

var processResult = function (result, options) {
    result = result.filter(function (ea) {
        return ea && !ea.isParentSelector;
    });
    if (!result.length) {
        return options.wrap ? [] : false;
    }
    if (result.length === 1 && !options.wrap && !Array.isArray(result[0].value)) {
        return result[0][options.resultType] || false;
    }
    return result.reduce(function (result, ea) {
        var valOrPath = ea[options.resultType];
        if (options.resultType === 'path') {
            valOrPath = asPath(valOrPath);
        }
        if (options.flatten && Array.isArray(valOrPath)) {
            result = result.concat(valOrPath);
        } else {
            result.push(valOrPath);
        }
        return result;
    }, []);
};

exports.instance = function (inputExpr, opts) {
    var exprToFn = function (expr) {
        if (expr === '*') {
            return jsonPathMethods.allProperties;
        } else if (expr === '..') {
            return jsonPathMethods.allDeepProperties;
        } else if (expr[0] === '(') {
            return jsonPathMethods.expressionProperties(expr);
        } else if (expr.indexOf('?(') === 0) { // [?(expr)]
            return jsonPathMethods.filteredProperties(expr);
        } else if (expr.indexOf(',') > -1) { // [name1,name2,...]
            return jsonPathMethods.listProperties(expr);
        } else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(expr)) { // [start:end:step]  Python slice syntax
            return jsonPathMethods.indexProperties(expr);
        } else if (expr === '^') {
            return jsonPathMethods.toParent;
        } else if (expr === '$') {
            return expr;
        } else {
            return jsonPathMethods.tracePropertyFn(expr);
        }
    };

    opts = processOptions(opts);
    if ((opts.resultType !== 'value') && (opts.resultType !== 'path')) {
        throw new Error('Invalid option resultType: ' + opts.resultType);
    }
    if (!inputExpr) {
        throw new Error('An input expression is required.');
    }

    var exprList = normalize(inputExpr).map(exprToFn);

    return function (obj) {
        var exprListCopy = exprList.slice();
        var jsonPath = Object.create(jsonPathMethods);
        jsonPath.sandbox = opts.sandbox;

        var ret = jsonPath.evaluate(obj, exprListCopy);
        ret = processResult(ret, opts);
        return ret;
    };
};
<commit_msg>code cleaning<commit_after>/*global module, exports, require*/
/*jslint vars:true, evil:true*/
/* JSONPath 0.8.0 - XPath for JSON
 *
 * Copyright (c) 2007 Stefan Goessner (goessner.net)
 * Licensed under the MIT (MIT-LICENSE.txt) licence.
 */

'use strict';

var vm = require('vm');
var _ = require("lodash");

var arrayset = require('./arrayset');

var append = arrayset.append;

function push(arr, elem) {
    arr = arr.slice();
    arr.push(elem);
    return arr;
}

var properties = function (obj) {
    if (Array.isArray(obj)) {
        return _.range(obj.length);
    } else if (typeof obj === 'object') {
        return Object.keys(obj);
    } else {
        return null;
    }
};

var asPath = function (path) {
    var i, n, x = path,
        p = '$';
    for (i = 1, n = x.length; i < n; i++) {
        p += /^[0-9*]+$/.test(x[i]) ? ('[' + x[i] + ']') : ("['" + x[i] + "']");
    }
    return p;
};

var normalize = exports.normalize = function (expr) {
    var exprList = [];
    var index = 0;
    var length = expr.length;
    var lastIndex = 0;
    while (index < length) {
        var c = expr.charAt(index);
        if (c === '.') {
            var cp1 = expr.charAt(index + 1);
            if (lastIndex !== index) {
                var subExpr = expr.substring(lastIndex, index);
                exprList.push(subExpr);
            }
            if (cp1 === '.') {
                exprList.push('..');
                ++index;
            }
            ++index;
            lastIndex = index;
            continue;
        }
        if (c === '[') {
            if (lastIndex !== index) {
                var subExprLB = expr.substring(lastIndex, index);
                exprList.push(subExprLB);
            }
            var openBrackets = 1;
            ++index;
            lastIndex = index;
            while (index < length) {
                var cinside = expr.charAt(index);
                if (cinside === '[') {
                    ++openBrackets;
                    ++index;
                    continue;
                }
                if (cinside === ']') {
                    --openBrackets;
                    if (openBrackets === 0) {
                        var subExprInside = expr.substring(lastIndex, index);
                        exprList.push(subExprInside);
                        ++index;
                        lastIndex = index;
                        break;
                    }
                }
                ++index;
            }
            continue;
        }
        if ((c === '^') || (c === '$')) {
            if (lastIndex !== index) {
                var subExprUC = expr.substring(lastIndex, index);
                exprList.push(subExprUC);
            }
            exprList.push(c);
            ++index;
            lastIndex = index;
            continue;
        }
        ++index;
    }
    if (lastIndex < index) {
        var subExprFinal = expr.substring(lastIndex, index);
        exprList.push(subExprFinal);
    }
    return exprList;
};

var processOptions = function (opts) {
    return {
        resultType: (opts && opts.resultType && opts.resultType.toLowerCase()) || 'value',
        flatten: (opts && opts.flatten) || false,
        wrap: (opts && opts.hasOwnProperty('wrap')) ? opts.wrap : true,
        sandbox: (opts && opts.sandbox) || {}
    };
};

var jsonPathMethods = {
    evaluate: function (obj, exprList) {
        this._obj = obj;
        if (exprList && obj) {
            if (exprList[0] === '$' && exprList.length > 1) {
                exprList.shift();
            }
            var result = this.trace(exprList, obj, ['$']);
            return result;
        }
    },
    allProperties: function (actions, obj, path) {
        var ps = properties(obj);
        return this.traceProperties(ps, actions, obj, path);
    },
    traceProperties: function (properties, actions, obj, path) {
        var result = [];
        if (properties) {
            properties.forEach(function (p) {
                var v = this.traceProperty(p, actions, obj, path);
                append(result, v);
            }, this);
        }
        return this.transferResult(obj, result);
    },
    traceProperty: function (property, actions, obj, path) {
        var result = [];
        if (obj && obj.hasOwnProperty(property)) {
            var v = this.trace(actions, obj[property], push(path, property));
            append(result, v);
        }
        return this.transferResult(obj, result);
    },
    allDeepProperties: function (actions, obj, path) {
        var result = [];
        var rootResult = this.trace(actions, obj, path);
        append(result, rootResult);
        var ps = properties(obj);
        if (ps) {
            ps = ps.filter(function (p) {
                return typeof obj[p] === 'object';
            });
        }
        if (ps) {
            ps.forEach(function (p) {
                var v = this.allDeepProperties(actions, obj[p], push(path, p));
                append(result, v);
            }, this);
        }
        return this.transferResult(obj, result);
    },
    toParent: function (actions, obj, path) {
        return path.length ? [{
            path: path.slice(0, -1),
            expr: actions,
            isParentSelector: true
        }] : [];
    },
    trace: function (actions, val, path) {
        if (!actions.length) {
            return [{
                path: path,
                value: val
            }];
        }
        var action = actions[0];
        var remainingActions = actions.slice(1);

        return action.call(this, remainingActions, val, path);
    },
    // We check the resulting values for parent selections. For parent
    // selections we discard the value object and continue the trace with the
    // current val object
    transferResult: function (obj, result) {
        var self = this;
        return result.reduce(function (all, ea) {
            if (ea.isParentSelector) {
                var v = self.trace(ea.expr, obj, ea.path);
                return all.concat(v);
            } else {
                all.push(ea);
                return all;
            }
        }, []);
    },
    eval: function (code, _v, _vname, path) {
        if (!this._obj || !_v) {
            return false;
        }
        if (code.indexOf('@path') > -1) {
            this.sandbox._$_path = asPath(path.concat([_vname]));
            code = code.replace(/@path/g, '_$_path');
        }
        if (code.indexOf('@') > -1) {
            this.sandbox._$_v = _v;
            code = code.replace(/@/g, '_$_v');
        }
        try {
            return vm.runInNewContext(code, this.sandbox);
        } catch (e) {
            console.log(e);
            throw new Error('jsonPath: ' + e.message + ': ' + code);
        }
    }
};

var exprToJsonPathMethod = {
    jsExprProperty: function (expr) {
        return function (actions, obj, path) {
            var result = [];
            var property = this.eval(expr, obj, path[path.length], path);
            return this.traceProperty(property, actions, obj, path);
        };
    },
    filteredProperties: function (expr) {
        var jsExpr = expr.replace(/^\?\((.*?)\)$/, '$1');
        return function (actions, obj, path) {
            var ps = properties(obj);
            if (ps) {
                ps = ps.filter(function (p) {
                    return this.eval(jsExpr, obj[p], p, path);
                }, this);
            }
            return this.traceProperties(ps, actions, obj, path);
        };
    },
    commaDelimitedProperties: function (expr) {
        var properties = expr.split(',');
        return function (actions, obj, path) {
            return this.traceProperties(properties, actions, obj, path);
        };
    },
    arrayRange: function (expr) {
        var indices = expr.split(':');
        var start = (indices[0] && parseInt(indices[0], 10)) || 0;
        var end = (indices[1] && parseInt(indices[1], 10)) || null;
        var step = (indices[2] && parseInt(indices[2], 10)) || 1;

        return function (actions, obj, path) {
            var length = obj.length;
            var localStart = (start < 0) ? Math.max(0, start + length) : Math.min(length, start);
            var localEnd = (end === null) ? length : end;
            localEnd = (localEnd < 0) ? Math.max(0, localEnd + length) : Math.min(length, localEnd);
            var range = _.range(localStart, localEnd, step);
            return this.traceProperties(range, actions, obj, path);
        };
    },
    property: function (property) {
        return function (actions, obj, path) {
            return this.traceProperty(property, actions, obj, path);
        };
    },
};

var processResult = function (result, options) {
    result = result.filter(function (ea) {
        return ea && !ea.isParentSelector;
    });
    if (!result.length) {
        return options.wrap ? [] : false;
    }
    if (result.length === 1 && !options.wrap && !Array.isArray(result[0].value)) {
        return result[0][options.resultType] || false;
    }
    return result.reduce(function (result, ea) {
        var valOrPath = ea[options.resultType];
        if (options.resultType === 'path') {
            valOrPath = asPath(valOrPath);
        }
        if (options.flatten && Array.isArray(valOrPath)) {
            result = result.concat(valOrPath);
        } else {
            result.push(valOrPath);
        }
        return result;
    }, []);
};

exports.instance = function (inputExpr, opts) {
    var exprToFn = function (expr) {
        if (expr === '*') {
            return jsonPathMethods.allProperties;
        } else if (expr === '..') {
            return jsonPathMethods.allDeepProperties;
        } else if (expr[0] === '(') {
            return exprToJsonPathMethod.jsExprProperty(expr);
        } else if (expr.indexOf('?(') === 0) { // [?(expr)]
            return exprToJsonPathMethod.filteredProperties(expr);
        } else if (expr.indexOf(',') > -1) { // [name1,name2,...]
            return exprToJsonPathMethod.commaDelimitedProperties(expr);
        } else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(expr)) { // [start:end:step]  Python slice syntax
            return exprToJsonPathMethod.arrayRange(expr);
        } else if (expr === '^') {
            return jsonPathMethods.toParent;
        } else if (expr === '$') {
            return expr;
        } else {
            return exprToJsonPathMethod.property(expr);
        }
    };

    opts = processOptions(opts);
    if ((opts.resultType !== 'value') && (opts.resultType !== 'path')) {
        throw new Error('Invalid option resultType: ' + opts.resultType);
    }
    if (!inputExpr) {
        throw new Error('An input expression is required.');
    }

    var exprList = normalize(inputExpr).map(exprToFn);

    return function (obj) {
        var exprListCopy = exprList.slice();
        var jsonPath = Object.create(jsonPathMethods);
        jsonPath.sandbox = opts.sandbox;

        var ret = jsonPath.evaluate(obj, exprListCopy);
        ret = processResult(ret, opts);
        return ret;
    };
};
<|endoftext|>


<commit_before>import React from 'react';

import DescriptionList from './DescriptionList';
import EnvironmentList from './EnvironmentList';
import ServiceConfigUtil from '../utils/ServiceConfigUtil';

class PodContainerSpecView extends React.Component {
  getArtifactsSection() {
    let {container: {artifacts=[]}} = this.props;

    if (artifacts.length === 0) {
      return null;
    }

    let keysMapping = {
      uri: 'URI',
      extract: 'Extract',
      executable: 'Executable',
      cache: 'Cache',
      destPath: 'Destination Path'
    };

    let nodes = artifacts.map(function (artifact, i) {
      return (
        <DescriptionList
          key={i}
          hash={artifact}
          renderKeys={keysMapping} />
      );
    });

    return (

          Artifacts

        {nodes}

    );
  }

  getGeneralDetails() {
    let hash = Object.assign({}, this.props.container);

    // Handled separately
    delete hash.endpoints;
    delete hash.artifacts;
    delete hash.volumeMounts;
    delete hash.environment;

    // Unwrap command
    if (hash.exec) {
      hash.command = ServiceConfigUtil.getCommandString(hash);
      delete hash.exec;
    }

    let keysMapping = {
      name: 'Name',
      cpus: 'CPUs',
      gpus: 'GPUs',
      mem: 'Memory (MiB)',
      disk: 'Disk Space (Mib)',
      command: 'Command',
      gracePeriodSeconds: 'Grace Period (seconds)',
      intervalSeconds: 'Interval (seconds)',
      maxConsecutiveFailures: 'Max Consecutive Failures',
      timeoutSeconds: 'Timeout (seconds)',
      delaySeconds: 'Delay (seconds)',
      killGracePeriodSeconds: 'SIGKILL Grace Period (seconds)'
    };

    return <DescriptionList hash={hash} renderKeys={keysMapping} />;
  }

  getEnvironmentSection() {
    let {container: {environment={}}} = this.props;

    if (Object.keys(environment).length === 0) {
      return null;
    }

    return (

Environment Variables

        <EnvironmentList environment={environment} />

    );
  }

  getEndpointsSection() {
    let {container: {id, endpoints=[]}} = this.props;

    if (!endpoints.length) {
      return null;
    }

    let portConfigurations = ServiceConfigUtil.getPortDefinitionGroups(
        id, endpoints, function (content, linkTo) {
          return {content};
        }
      ).map(function ({hash, headline}, index) {
        return (
          <DescriptionList className="nested-description-list"
            hash={hash}
            headline={headline}
            key={index} />
        );
      });

    return (

Port Definitions

        {portConfigurations}

    );
  }

  getVolumesSection() {
    let {container: {volumeMounts=[]}} = this.props;

    if (volumeMounts.length === 0) {
      return null;
    }

    let keysMapping = {
      name: 'Name',
      mountPath: 'Mount Path',
      readOnly: 'Read Only'
    };

    let nodes = volumeMounts.map(function (volumeMount, i) {
      return (
        <DescriptionList
          key={i}
          hash={volumeMount}
          renderKeys={keysMapping} />
      );
    });

    return (

          Volume Mounts

        {nodes}

    );
  }

  render() {
    let {container: {name}} = this.props;

    return (

          {name}

        {this.getGeneralDetails()}
        {this.getEnvironmentSection()}
        {this.getArtifactsSection()}
        {this.getVolumesSection()}
        {this.getEndpointsSection()}

    );
  }
};

PodContainerSpecView.propTypes = {
  container: React.PropTypes.object.isRequired
};

module.exports = PodContainerSpecView;
<commit_msg>Use Util.omit<commit_after>import React from 'react';

import DescriptionList from './DescriptionList';
import EnvironmentList from './EnvironmentList';
import ServiceConfigUtil from '../utils/ServiceConfigUtil';
import Util from '../utils/Util';

class PodContainerSpecView extends React.Component {
  getArtifactsSection() {
    let {container: {artifacts=[]}} = this.props;

    if (artifacts.length === 0) {
      return null;
    }

    let keysMapping = {
      uri: 'URI',
      extract: 'Extract',
      executable: 'Executable',
      cache: 'Cache',
      destPath: 'Destination Path'
    };

    let nodes = artifacts.map(function (artifact, i) {
      return (
        <DescriptionList
          key={i}
          hash={artifact}
          renderKeys={keysMapping} />
      );
    });

    return (

          Artifacts

        {nodes}

    );
  }

  getGeneralDetails() {
    let hash = Util.omit(this.props.container, [
      'endpoints',
      'artifacts',
      'volumeMounts',
      'environment'
    ]);

    // Unwrap command
    if (hash.exec) {
      hash.command = ServiceConfigUtil.getCommandString(hash);
      delete hash.exec;
    }

    let keysMapping = {
      name: 'Name',
      cpus: 'CPUs',
      gpus: 'GPUs',
      mem: 'Memory (MiB)',
      disk: 'Disk Space (Mib)',
      command: 'Command',
      gracePeriodSeconds: 'Grace Period (seconds)',
      intervalSeconds: 'Interval (seconds)',
      maxConsecutiveFailures: 'Max Consecutive Failures',
      timeoutSeconds: 'Timeout (seconds)',
      delaySeconds: 'Delay (seconds)',
      killGracePeriodSeconds: 'SIGKILL Grace Period (seconds)'
    };

    return <DescriptionList hash={hash} renderKeys={keysMapping} />;
  }

  getEnvironmentSection() {
    let {container: {environment={}}} = this.props;

    if (Object.keys(environment).length === 0) {
      return null;
    }

    return (

Environment Variables

        <EnvironmentList environment={environment} />

    );
  }

  getEndpointsSection() {
    let {container: {id, endpoints=[]}} = this.props;

    if (!endpoints.length) {
      return null;
    }

    let portConfigurations = ServiceConfigUtil.getPortDefinitionGroups(
        id, endpoints, function (content, linkTo) {
          return {content};
        }
      ).map(function ({hash, headline}, index) {
        return (
          <DescriptionList className="nested-description-list"
            hash={hash}
            headline={headline}
            key={index} />
        );
      });

    return (

Port Definitions

        {portConfigurations}

    );
  }

  getVolumesSection() {
    let {container: {volumeMounts=[]}} = this.props;

    if (volumeMounts.length === 0) {
      return null;
    }

    let keysMapping = {
      name: 'Name',
      mountPath: 'Mount Path',
      readOnly: 'Read Only'
    };

    let nodes = volumeMounts.map(function (volumeMount, i) {
      return (
        <DescriptionList
          key={i}
          hash={volumeMount}
          renderKeys={keysMapping} />
      );
    });

    return (

          Volume Mounts

        {nodes}

    );
  }

  render() {
    let {container: {name}} = this.props;

    return (

          {name}

        {this.getGeneralDetails()}
        {this.getEnvironmentSection()}
        {this.getArtifactsSection()}
        {this.getVolumesSection()}
        {this.getEndpointsSection()}

    );
  }
};

PodContainerSpecView.propTypes = {
  container: React.PropTypes.object.isRequired
};

module.exports = PodContainerSpecView;
<|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2014-2019
 * We believe in an open Internet of Things
 */

const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const databasemanager = require('./databasemanager');
const nedbmanager = require('./nedbmanager');
const storiesmanager = require('./storiesmanager');
const imagesmanager = require('./imagesmanager');

const HTTP_PORT = 3000;
const DEFAULT_USE_CORS = true;

/**
 * JSONSilo Class
 * Contextual data silo for the IoT and the Physical Web.
 */
class JSONSilo {

  /**
   * JSONSilo constructor
   * @param {Object} options The configuration options.
   * @constructor
   */
  constructor(options) {
    let self = this;
    options = options || {};
    self.specifiedHttpPort = options.httpPort || HTTP_PORT;
    self.httpPort = process.env.PORT || self.specifiedHttpPort;
    self.useCors = options.useCors || DEFAULT_USE_CORS;

    self.app = express();

    self.database = new databasemanager(options);
    self.stories = new storiesmanager(options, self.database);
    self.images = new imagesmanager(options);
    self.server = http.createServer(self.app);
    self.router = express.Router();

    self.app.use(bodyParser.json());

     if(self.useCors) {
       self.app.use(cors());
     }

    self.app.use(function(req, res, next) {
      req.jsonsilo = self;
      next();
    });

    self.app.use('/stories', require('./routes/stories'));
    self.app.use('/images', require('./routes/images'));
    self.app.use('/', self.router);
    self.app.use('/', express.static(path.resolve(__dirname + '/../web')));

    self.server.listen(self.httpPort, function(){
      console.log('reelyActive json-silo listening on port', self.httpPort);
    })

  }

}

module.exports = JSONSilo;
<commit_msg>Removed unused route<commit_after>/**
 * Copyright reelyActive 2014-2019
 * We believe in an open Internet of Things
 */

const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const databasemanager = require('./databasemanager');
const nedbmanager = require('./nedbmanager');
const storiesmanager = require('./storiesmanager');
const imagesmanager = require('./imagesmanager');

const HTTP_PORT = 3000;
const DEFAULT_USE_CORS = true;

/**
 * JSONSilo Class
 * Contextual data silo for the IoT and the Physical Web.
 */
class JSONSilo {

  /**
   * JSONSilo constructor
   * @param {Object} options The configuration options.
   * @constructor
   */
  constructor(options) {
    let self = this;
    options = options || {};
    self.specifiedHttpPort = options.httpPort || HTTP_PORT;
    self.httpPort = process.env.PORT || self.specifiedHttpPort;
    self.useCors = options.useCors || DEFAULT_USE_CORS;

    self.app = express();

    self.database = new databasemanager(options);
    self.stories = new storiesmanager(options, self.database);
    self.images = new imagesmanager(options);
    self.server = http.createServer(self.app);
    self.router = express.Router();

    self.app.use(bodyParser.json());

     if(self.useCors) {
       self.app.use(cors());
     }

    self.app.use(function(req, res, next) {
      req.jsonsilo = self;
      next();
    });

    self.app.use('/stories', require('./routes/stories'));
    self.app.use('/images', require('./routes/images'));
    self.app.use('/', express.static(path.resolve(__dirname + '/../web')));

    self.server.listen(self.httpPort, function() {
      console.log('reelyActive json-silo listening on port', self.httpPort);
    })

  }

}

module.exports = JSONSilo;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import connectToStores from '../utils/connectToStores';
import translate from '../i18n/Translate';
import LoginActionCreators from '../actions/LoginActionCreators';
import LocaleStore from '../stores/LocaleStore';
import ProfileStore from '../stores/ProfileStore';
import RegisterStore from '../stores/RegisterStore';
import InputSelectImage from '../components/RegisterFields/InputSelectImage/InputSelectImage.js';
import StepsBar from '../components/ui/StepsBar/StepsBar.js';
import TopNavBar from '../components/TopNavBar/TopNavBar.js';
import * as UserActionCreators from '../actions/UserActionCreators';
import '../../scss/pages/leisure-profile-hobbies.scss';

function requestData(props) {
    if (!props.metadata) {
        UserActionCreators.requestMetadata();
    }
}

function getState() {
    const interfaceLanguage = LocaleStore.locale;
    const metadata = ProfileStore.getMetadata();
    const choices = metadata && metadata.hobbies ? metadata.hobbies.choices : [];
    const user = RegisterStore.user;
    const username = user && user.username ? user.username : null;
    const profile = RegisterStore.profile;

    return {
        interfaceLanguage,
        choices,
        profile,
        username
    };
}

@translate('LeisureProfileHobbiesPage')
@connectToStores([LocaleStore, ProfileStore, RegisterStore], getState)
export default class LeisureProfileHobbiesPage extends Component {

    static propTypes = {
        // Injected by @translate:
        strings          : PropTypes.object,
        // Injected by @connectToStores:
        choices          : PropTypes.array,
        profile          : PropTypes.object,
        username         : PropTypes.string,
        interfaceLanguage: PropTypes.string
    };

    static contextTypes = {
        router: PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);

        this.onChange = this.onChange.bind(this);
        this.goToLeisureProfileGamesPage = this.goToLeisureProfileGamesPage.bind(this);
    }

    componentDidMount() {
        if (!this.props.username) {
            this.context.router.push('/answer-username');
        }
        requestData(this.props);
    }

    goToLeisureProfileGamesPage() {
        this.context.router.push('/leisure-profile-games');
    }

    onChange(choices) {
        const {profile} = this.props;

        LoginActionCreators.preRegisterProfile({...profile, ...{hobbies: choices}});
    }

    render() {
        const {choices, profile, strings} = this.props;
        const canContinue = profile && profile.hobbies && profile.hobbies.length > 0;

        return (

                    <TopNavBar iconLeft={'arrow-left'} textCenter={strings.sportsAndGames} textSize={'small'}/>

{strings.title}

                        <InputSelectImage options={choices}
                                          placeholder={strings.searchHobby}
                                          searchIcon={true}
                                          size={'small'}
                                          onClickHandler={this.onChange}/>

                <StepsBar color={'pink'} canContinue={canContinue} cantContinueText={strings.addHobby} continueText={strings.continue} currentStep={1} totalSteps={3} onClickHandler={this.goToLeisureProfileGamesPage}/>

        );
    }

}

LeisureProfileHobbiesPage.defaultProps = {
    strings: {
        sportsAndGames: 'Sports, Games & Hobbies',
        title         : 'What hobbies do you like to practice in your free time?',
        searchHobby   : 'Search hobby',
        addHobby      : 'Add a hobby to continue',
        continue      : 'Continue'
    }
};<commit_msg>Fix hobbies type in registry<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import connectToStores from '../utils/connectToStores';
import translate from '../i18n/Translate';
import LoginActionCreators from '../actions/LoginActionCreators';
import LocaleStore from '../stores/LocaleStore';
import ProfileStore from '../stores/ProfileStore';
import RegisterStore from '../stores/RegisterStore';
import StepsBar from '../components/ui/StepsBar/StepsBar.js';
import TopNavBar from '../components/TopNavBar/TopNavBar.js';
import * as UserActionCreators from '../actions/UserActionCreators';
import '../../scss/pages/leisure-profile-hobbies.scss';
import * as TagSuggestionsActionCreators from "../actions/TagSuggestionsActionCreators";
import TagSuggestionsStore from "../stores/TagSuggestionsStore";
import InputTag from '../components/RegisterFields/InputTag/InputTag.js';

function requestData(props) {
    if (!props.metadata) {
        UserActionCreators.requestMetadata();
    }
}

function resetTagSuggestions() {
    TagSuggestionsActionCreators.resetTagSuggestions();
}

function getState() {
    const interfaceLanguage = LocaleStore.locale;
    const tags = TagSuggestionsStore.tags || [];
    const tagValues = tags.map(tag => tag.name);
    const user = RegisterStore.user;
    const username = user && user.username ? user.username : null;
    const profile = RegisterStore.profile;

    return {
        interfaceLanguage,
        tagValues,
        profile,
        username
    };
}

@translate('LeisureProfileHobbiesPage')
@connectToStores([LocaleStore, ProfileStore, RegisterStore], getState)
export default class LeisureProfileHobbiesPage extends Component {

    static propTypes = {
        // Injected by @translate:
        strings          : PropTypes.object,
        // Injected by @connectToStores:
        choices          : PropTypes.array,
        profile          : PropTypes.object,
        username         : PropTypes.string,
        interfaceLanguage: PropTypes.string
    };

    static contextTypes = {
        router: PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);

        this.onChange = this.onChange.bind(this);
        this.goToLeisureProfileGamesPage = this.goToLeisureProfileGamesPage.bind(this);
    }

    componentDidMount() {
        if (!this.props.username) {
            this.context.router.push('/answer-username');
        }
        resetTagSuggestions();
        requestData(this.props);
    }

    goToLeisureProfileGamesPage() {
        this.context.router.push('/leisure-profile-games');
    }

    onChange(tags) {
        const {profile} = this.props;

        resetTagSuggestions();
        LoginActionCreators.preRegisterProfile({...profile, ...{hobbies: tags}});
    }

    onChangeText(text) {
        if (text) {
            TagSuggestionsActionCreators.requestProfileTagSuggestions(text, 'hobbies');
        } else {
            resetTagSuggestions();
        }
    }

    render() {
        const {tagValues, profile, strings} = this.props;
        const canContinue = profile && profile.hobbies && profile.hobbies.length > 0;

        return (

                    <TopNavBar iconLeft={'arrow-left'} textCenter={strings.sportsAndGames} textSize={'small'}/>

{strings.title}

                        <InputTag tags={tagValues}
                                  placeholder={strings.searchHobby}
                                  searchIcon={true}
                                  size={'small'}
                                  chipsColor={'pink'}
                                  onChangeHandler={this.onChangeText}
                                  onClickHandler={this.onChange}
                                  selectedLabel={strings.selected}/>

                <StepsBar color={'pink'} canContinue={canContinue} cantContinueText={strings.addHobby} continueText={strings.continue} currentStep={1} totalSteps={3} onClickHandler={this.goToLeisureProfileGamesPage}/>

        );
    }

}

LeisureProfileHobbiesPage.defaultProps = {
    strings: {
        sportsAndGames: 'Sports, Games & Hobbies',
        title         : 'What hobbies do you like to practice in your free time?',
        searchHobby   : 'Search hobby',
        addHobby      : 'Add a hobby to continue',
        continue      : 'Continue'
    }
};<|endoftext|>


<commit_before>/*****************************************************************************/
/* Imports */
/*****************************************************************************/
var Url = Iron.Url;

/*****************************************************************************/
/* Private */
/*****************************************************************************/
var current = null;
var dep = new Deps.Dependency;
var handlers = {go: [], popState: []};

var isIE9 = function () {
  return /MSIE 9/.test(navigator.appVersion);
};

var isIE8 = function () {
  return /MSIE 8/.test(navigator.appVersion);
};

var usingAppcache = function() {
  return !! Package.appcache;
}

var replaceStateUndefined = function() {
  return (typeof history === "undefined")  || (typeof history.pushState !== "function");
}

var shouldUseHashPaths = function () {
  return Location.options.useHashPaths || isIE8() || isIE9() || usingAppcache() || replaceStateUndefined();
};

var isUsingHashPaths = function () {
  return !!Location.options.useHashPaths;
};

var runHandlers = function(name, state) {
  _.each(handlers[name], function(cb) {
    cb.call(state);
  });
}

var set = function (state) {
  if (!(state instanceof State))
    throw new Error("Expected a State instance");

  if (!state.equals(current)) {
    current = state;
    dep.changed();

    // return true to indicate state was set to a new value.
    return true;
  }

  // state not set
  return false;
};

var setStateFromEventHandler = function () {
  var href = location.href;
  var state;

  if (isUsingHashPaths()) {
    state = new State(urlFromHashStyle(href));
  } else {
    state = new State(href, {historyState: history.state});
  }

  runHandlers('popState', state);
  set(state);
};

var fireOnClick = function (e) {
  var handler = onClickHandler;
  handler && handler(e);
};

/**
 * Go to a url.
 */
var go = function (url, options) {
  options = options || {};

  var state = new State(url, options);

  runHandlers('go', state);

  if (set(state)) {
    Deps.afterFlush(function () {
      // if after we've flushed if nobody has cancelled the state then change
      // the url.
      if (!state.isCancelled()) {
        if (isUsingHashPaths()) {
          location.hash = fixHashPath(url);
        } else {
          if (options.replaceState === true)
            history.replaceState(options.historyState, null, url);
          else
            history.pushState(options.historyState, null, url);
        }
      }
    });
  }
};

var onClickHandler = function (e) {
  try {
    var el = e.currentTarget;
    var href = el.href;
    var path = el.pathname + el.search + el.hash;

    // ie9 omits the leading slash in pathname - so patch up if it's missing
    path = path.replace(/(^\/?)/,"/");

    // haven't been cancelled already
    if (e.isDefaultPrevented()) {
      e.preventDefault();
      return;
    }

    // with no meta key pressed
    if (e.metaKey || e.ctrlKey || e.shiftKey)
      return;

    // aren't targeting a new window
    if (el.target)
      return;

    // aren't external to the app
    if (!Url.isSameOrigin(href, location.href))
      return;

    // note that we _do_ handle links which point to the current URL
    // and links which only change the hash.
    e.preventDefault();

    // manage setting the new state and maybe pushing onto the pushState stack
    go(path);
  } catch (err) {
    // make sure we can see any errors that are thrown before going to the
    // server.
    e.preventDefault();
    throw err;
  }
};

/*****************************************************************************/
/* Location API */
/*****************************************************************************/

/**
 * Main Location object. Reactively respond to url changes. Normalized urls
 * between hash style (ie8/9) and normal style using pushState.
 */
Location = {};

/**
 * Default options.
 */
Location.options = {
  linkSelector: 'a[href]',
  useHashPaths: false
};

/**
 * Set options on the Location object.
 */
Location.configure = function (options) {
  _.extend(this.options, options || {});
};

/**
 * Reactively get the current state.
 */
Location.get = function () {
  dep.depend();
  return current;
};

/**
 * Set the initial state and start listening for url events.
 */
Location.start = function () {
  if (this._isStarted)
    return;

  var parts = Url.parse(location.href);

  // if we're using the /#/items/5 style then start off at the root url but
  // store away the pathname, query and hash into the hash fragment so when the
  // client gets the response we can render the correct page.
  if (shouldUseHashPaths()) {
    // if we have any pathname like /items/5 take a trip to the server to get us
    // back a root url.
    if (parts.pathname.length > 1) {
      var url = urlToHashStyle(location.href);
      window.location = url;
    }

    // ok good to go
    this.configure({useHashPaths: true});
  }
  // set initial state
  var href = location.href;

  if (isUsingHashPaths()) {
    var state = new State(urlFromHashStyle(href));
    set(state);
  } else {
    // if we started at a URL in the /#!items/5 style then we have picked up a
    // URL from an non-HTML5 user. Let's redirect to /items/5
    if (parts.hash.replace('#', '')[0] === '!') {
      var href = urlFromHashStyle(href);
    }

    // store the fact that this is the first route we hit.
    // this serves two purposes
    //   1. We can tell when we've reached an unhandled route and need to show a
    //      404 (rather than bailing out to let the server handle it)
    //   2. Users can look at the state to tell if the history.back() will stay
    //      inside the app (this is important for mobile apps).
    var historyState = {initial: true}
    history.replaceState(historyState, null, href);
    var state = new State(href, {historyState: historyState});
    set(state);
  }

  // bind the event handlers
  $(window).on('popstate.iron-location', setStateFromEventHandler);
  $(window).on('hashchange.iron-location', setStateFromEventHandler);

  // make sure we have a document before binding the click handler
  Meteor.startup(function () {
    $(document).on('click.iron-location', Location.options.linkSelector, fireOnClick);
  });

  this._isStarted = true;
};

/**
 * Stop the Location from listening for url changes.
 */
Location.stop = function () {
  if (!this._isStarted)
    return;

  $(window).on('popstate.iron-location');
  $(window).on('hashchange.iron-location');
  $(document).off('click.iron-location');

  this._isStarted = false;
};

/**
 * Assign a different click handler.
 */
Location.onClick = function (fn) {
  onClickHandler = fn;
};

/**
 * Go to a new url.
 */
Location.go = function (url, options) {
  return go(url, options);
};

/**
 * Run the supplied callback whenever we "go" to a new location.
 *
 * Argument: cb - function, called with no arguments,
 * `this` is the state that's being set, _may_ be modified.
 */
Location.onGo = function (cb) {
  handlers.go.push(cb);
};

/**
 * Run the supplied callback whenever we "popState" to an old location.
 *
 * Argument: cb - function, called with no arguments,
 * `this` is the state that's being set, _may_ be modified.
 */
Location.onPopState = function (cb) {
  handlers.popState.push(cb);
};

/**
 * Automatically start Iron.Location
 */
Location.start();

/*****************************************************************************/
/* Namespacing */
/*****************************************************************************/
Iron.Location = Location;
<commit_msg>Don't break when processing SVG links<commit_after>/*****************************************************************************/
/* Imports */
/*****************************************************************************/
var Url = Iron.Url;

/*****************************************************************************/
/* Private */
/*****************************************************************************/
var current = null;
var dep = new Deps.Dependency;
var handlers = {go: [], popState: []};

var isIE9 = function () {
  return /MSIE 9/.test(navigator.appVersion);
};

var isIE8 = function () {
  return /MSIE 8/.test(navigator.appVersion);
};

var usingAppcache = function() {
  return !! Package.appcache;
}

var replaceStateUndefined = function() {
  return (typeof history === "undefined")  || (typeof history.pushState !== "function");
}

var shouldUseHashPaths = function () {
  return Location.options.useHashPaths || isIE8() || isIE9() || usingAppcache() || replaceStateUndefined();
};

var isUsingHashPaths = function () {
  return !!Location.options.useHashPaths;
};

var runHandlers = function(name, state) {
  _.each(handlers[name], function(cb) {
    cb.call(state);
  });
}

var set = function (state) {
  if (!(state instanceof State))
    throw new Error("Expected a State instance");

  if (!state.equals(current)) {
    current = state;
    dep.changed();

    // return true to indicate state was set to a new value.
    return true;
  }

  // state not set
  return false;
};

var setStateFromEventHandler = function () {
  var href = location.href;
  var state;

  if (isUsingHashPaths()) {
    state = new State(urlFromHashStyle(href));
  } else {
    state = new State(href, {historyState: history.state});
  }

  runHandlers('popState', state);
  set(state);
};

var fireOnClick = function (e) {
  var handler = onClickHandler;
  handler && handler(e);
};

/**
 * Go to a url.
 */
var go = function (url, options) {
  options = options || {};

  var state = new State(url, options);

  runHandlers('go', state);

  if (set(state)) {
    Deps.afterFlush(function () {
      // if after we've flushed if nobody has cancelled the state then change
      // the url.
      if (!state.isCancelled()) {
        if (isUsingHashPaths()) {
          location.hash = fixHashPath(url);
        } else {
          if (options.replaceState === true)
            history.replaceState(options.historyState, null, url);
          else
            history.pushState(options.historyState, null, url);
        }
      }
    });
  }
};

var onClickHandler = function (e) {
  try {
    var el = e.currentTarget, href, path;

    // Support both regular and SVG links
    if( el.href instanceof SVGAnimatedString ) {
      href = el.href.animVal;
      path = href;
    }
    else {
      href = el.href;
      path = el.pathname + el.search + el.hash;
    }

    // ie9 omits the leading slash in pathname - so patch up if it's missing
    path = path.replace(/(^\/?)/,"/");

    // haven't been cancelled already
    if (e.isDefaultPrevented()) {
      e.preventDefault();
      return;
    }

    // with no meta key pressed
    if (e.metaKey || e.ctrlKey || e.shiftKey)
      return;

    // aren't targeting a new window
    if (el.target)
      return;

    // aren't external to the app
    if (!Url.isSameOrigin(href, location.href))
      return;

    // note that we _do_ handle links which point to the current URL
    // and links which only change the hash.
    e.preventDefault();

    // manage setting the new state and maybe pushing onto the pushState stack
    go(path);
  } catch (err) {
    // make sure we can see any errors that are thrown before going to the
    // server.
    e.preventDefault();
    throw err;
  }
};

/*****************************************************************************/
/* Location API */
/*****************************************************************************/

/**
 * Main Location object. Reactively respond to url changes. Normalized urls
 * between hash style (ie8/9) and normal style using pushState.
 */
Location = {};

/**
 * Default options.
 */
Location.options = {
  linkSelector: 'a[href]',
  useHashPaths: false
};

/**
 * Set options on the Location object.
 */
Location.configure = function (options) {
  _.extend(this.options, options || {});
};

/**
 * Reactively get the current state.
 */
Location.get = function () {
  dep.depend();
  return current;
};

/**
 * Set the initial state and start listening for url events.
 */
Location.start = function () {
  if (this._isStarted)
    return;

  var parts = Url.parse(location.href);

  // if we're using the /#/items/5 style then start off at the root url but
  // store away the pathname, query and hash into the hash fragment so when the
  // client gets the response we can render the correct page.
  if (shouldUseHashPaths()) {
    // if we have any pathname like /items/5 take a trip to the server to get us
    // back a root url.
    if (parts.pathname.length > 1) {
      var url = urlToHashStyle(location.href);
      window.location = url;
    }

    // ok good to go
    this.configure({useHashPaths: true});
  }
  // set initial state
  var href = location.href;

  if (isUsingHashPaths()) {
    var state = new State(urlFromHashStyle(href));
    set(state);
  } else {
    // if we started at a URL in the /#!items/5 style then we have picked up a
    // URL from an non-HTML5 user. Let's redirect to /items/5
    if (parts.hash.replace('#', '')[0] === '!') {
      var href = urlFromHashStyle(href);
    }

    // store the fact that this is the first route we hit.
    // this serves two purposes
    //   1. We can tell when we've reached an unhandled route and need to show a
    //      404 (rather than bailing out to let the server handle it)
    //   2. Users can look at the state to tell if the history.back() will stay
    //      inside the app (this is important for mobile apps).
    var historyState = {initial: true}
    history.replaceState(historyState, null, href);
    var state = new State(href, {historyState: historyState});
    set(state);
  }

  // bind the event handlers
  $(window).on('popstate.iron-location', setStateFromEventHandler);
  $(window).on('hashchange.iron-location', setStateFromEventHandler);

  // make sure we have a document before binding the click handler
  Meteor.startup(function () {
    $(document).on('click.iron-location', Location.options.linkSelector, fireOnClick);
  });

  this._isStarted = true;
};

/**
 * Stop the Location from listening for url changes.
 */
Location.stop = function () {
  if (!this._isStarted)
    return;

  $(window).on('popstate.iron-location');
  $(window).on('hashchange.iron-location');
  $(document).off('click.iron-location');

  this._isStarted = false;
};

/**
 * Assign a different click handler.
 */
Location.onClick = function (fn) {
  onClickHandler = fn;
};

/**
 * Go to a new url.
 */
Location.go = function (url, options) {
  return go(url, options);
};

/**
 * Run the supplied callback whenever we "go" to a new location.
 *
 * Argument: cb - function, called with no arguments,
 * `this` is the state that's being set, _may_ be modified.
 */
Location.onGo = function (cb) {
  handlers.go.push(cb);
};

/**
 * Run the supplied callback whenever we "popState" to an old location.
 *
 * Argument: cb - function, called with no arguments,
 * `this` is the state that's being set, _may_ be modified.
 */
Location.onPopState = function (cb) {
  handlers.popState.push(cb);
};

/**
 * Automatically start Iron.Location
 */
Location.start();

/*****************************************************************************/
/* Namespacing */
/*****************************************************************************/
Iron.Location = Location;
<|endoftext|>