<commit_before>function Spiral(graphType) {
  this.graphType = graphType || "points";
  this.numberOfPoints = null,
  this.period = null,
  this.margin = {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  this.svgHeight = 0,
  this.svgWidth = 0,
  this.spacing = 1,
  this.targetElement = "body",
  this.width = this.svgWidth - this.margin.left - this.margin.right,
  this.height = this.svgHeight - this.margin.top - this.margin.bottom,
  this.data = [],
  this.x = d3.scale.linear().range([0, 730]).domain([-740, 740]), // TODO : x.domain([-this.height-this.margin.bottom, this.height+this.margin.top]);
  this.y = d3.scale.linear().range([480, 0]).domain([-490, 490]), // TODO : y.domain([-this.height-this.margin.bottom, this.height+this.margin.top]);
  this.cartesian = function(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = this.x(radius * Math.cos(angle));
    var yPos = this.y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  },
  this.render = function() {
    var svg = d3.select(this.targetElement)
      .append("svg")
      .attr("width", this.svgWidth)
      .attr("height", this.svgHeight)

    if (this.graphType === "points") {
      svg.append("g")
        .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");

      svg.selectAll("g").selectAll("dot")
        .data(this.data)
          .enter().append("circle")
            .attr("r", function(d) { return d[2]; })
            .attr("cx", function(d) { return d[0]; })
            .attr("cy", function(d) { return d[1]; });
    } else if (this.graphType === "arcs") {
      svg.append("g")
        .attr("transform", "translate(" + (this.width * 0.5 + this.margin.left) + "," + (this.height * 0.5 + this.margin.top) + ")");

      svg.selectAll("g").selectAll("path")
        .data(this.data)
          .enter().append("path")
          .attr("d", d3.svg.arc()
          .outerRadius(function(d){return y(d[3]+10)})
          .innerRadius(function(d){return y(d[3]-10)})
          .startAngle(function(d) { return d[5] > 0 ? d[5] : 0; })
          .endAngle(function(d) { return d[6]; }))
          .attr("opacity", function(d){return d[2]/5})
    } else if (this.graphType === "paths") {

      var line = d3.svg.line()
          .interpolate("basis");

      svg.append("g")
        .attr("transform", "translate(" + (this.margin.left) + "," + (this.margin.top) + ")");

      svg.selectAll("g").selectAll("path")
          .data(quad(sample(line(this.data), this.numberOfPoints, this.period))) // ***** Need to figure out the proper precision to map data crrectly
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("stroke", function(d) { return "black"; })
          .style("opacity", function(d) {return d.data/6})
          .attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 10); });

      // Sample the SVG path string "d" uniformly with the specified precision.
      function sample(d, numberDataPoints, periodicity) {
        var path = document.createElementNS(d3.ns.prefix.svg, "path");
        path.setAttribute("d", d);

        var n = path.getTotalLength();
        var t = [0];
        var i = 1;
        var dt = Math.ceil(i/periodicity)*2;
        var lastSample = 0;
        while (lastSample + dt < n) {
          dt = Math.ceil(i/periodicity)*2;
          t.push(lastSample + dt);
          lastSample = lastSample + dt;
          i++;
        }
        t.push(n);

        return t.map(function(t, index) {
          var p = path.getPointAtLength(t);
          var a = data[index] ? [p.x, p.y, data[index][2]] : [p.x, p.y, 0];
          return a;
        });
      }

      // Compute quads of adjacent points [p0, p1, p2, p3].
      function quad(points) {
        return d3.range(points.length - 1).map(function(i) {
          var a = [points[i - 1], points[i], points[i + 1], points[i + 2]];
          a.data = points[i][2];
          return a;
        });
      }

      // Compute stroke outline for segment p12.
      function lineJoin(p0, p1, p2, p3, width) {
        var u12 = perp(p1, p2),
            r = width / 2,
            a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
            b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
            c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r],
            d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r];

        if (p0) { // clip ad and dc using average of u01 and u12
          var u01 = perp(p0, p1), e = [p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1]];
          a = lineIntersect(p1, e, a, b);
          d = lineIntersect(p1, e, d, c);
        }

        if (p3) { // clip ab and dc using average of u12 and u23
          var u23 = perp(p2, p3), e = [p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1]];
          b = lineIntersect(p2, e, a, b);
          c = lineIntersect(p2, e, d, c);
        }

        return "M" + a + "L" + b + " " + c + " " + d + "Z";
      }

      // Compute intersection of two infinite lines ab and cd.
      function lineIntersect(a, b, c, d) {
        var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3;
        var y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3;
        var ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
        return [x1 + ua * x21, y1 + ua * y21];
      }

      // Compute unit vector perpendicular to p01.
      function perp(p0, p1) {
        var u01x = p0[1] - p1[1];
        var u01y = p1[0] - p0[0];
        var u01d = Math.sqrt(u01x * u01x + u01y * u01y);
        return [u01x / u01d, u01y / u01d];
      }
    } else if (this.graphType === "custom-path") {
      var pathWidth = 50;
      var spiralContext = this;

      this.data.forEach(function(datum, t, dataSet){
        var start = startAngle(t, spiralContext.period);
        var end = endAngle(t, spiralContext.period);

        var startInnerRadius = radius(spiralContext.spacing, start) - pathWidth*0.5;
        var startOuterRadius = radius(spiralContext.spacing, start) + pathWidth*0.5;
        var endInnerRadius = radius(spiralContext.spacing, end) - pathWidth*0.5;
        var endOuterRadius = radius(spiralContext.spacing, end) + pathWidth*0.5;

        var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
        var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
        var innerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) - pathWidth*0.5 + ctrlInnerRad, theta(t, spiralContext.period));
        var outerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) + pathWidth*0.5 + ctrlOuterRad, theta(t, spiralContext.period));

        var startPoint = spiralContext.cartesian(startInnerRadius, start); // Bottom right of arc
        var point2 = spiralContext.cartesian(startOuterRadius, start); // Top right of arc
        var point3 = spiralContext.cartesian(endOuterRadius, end); // Top left of arc
        var point4 = spiralContext.cartesian(endInnerRadius, end); // Bottom left of arc
        var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
        arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
        arcPath += "L" + point4[0] + " " + point4[1];
        arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
        datum[1] = arcPath
        console.log(datum)
      });

      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");
      svg.selectAll("g").selectAll("path")
        .data(spiralContext.data.slice(100))
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("opacity", function(d) {return d[2]/9})
          .attr("d", function(d) { return d[1]});
    } else if (this.graphType === "non-spiral") {
      // --------------------vvv Standard Line Graph vvv---------------------------
      var x2 = d3.scale.linear().range([0, 730]);
      var y2 = d3.scale.linear().range([480, 0]);
      x2.domain(d3.extent(this.data, function(d) { return d[0]; }));
      y2.domain(d3.extent(this.data, function(d) { return d[1]; }));

      var xAxis = d3.svg.axis().scale(x2)
        .orient("bottom").ticks(5);

      var yAxis = d3.svg.axis().scale(y2)
        .orient("left").ticks(5);

      var line = d3.svg.line()
        .x(function(d) { return x2(d[0]); })
        .y(function(d) { return y2(d[1]); });

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+this.margin.left+"," + 480 + ")")
        .call(xAxis)
        .append("text")
          .attr("x", 710)
          .attr("y", -3)
          .attr("dy", "-.35em")
          .style("text-anchor", "middle")
          .text("time");

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+this.margin.left+",0)")
        .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Signal (a.u.)");

      svg.append("path")
        .datum(this.data)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke-width", "1")
        .attr("stroke", "steelblue")
        .attr("transform", "translate("+this.margin.left+",0)")
    }
  },
  this.randomData = function() {
    for (var i=0; i<this.numberOfPoints; i++){
      var angle = theta(i, this.period);
      var rad = radius(this.spacing, angle);
      var size = 1 + Math.random()*1.5;
      if (i % 10 === 0) {
        size = 5.5 + Math.random()*3;
      }

      if (this.graphType === 'points' || this.graphType === "custom-path") {
        this.data.push(this.cartesian(rad, angle, size, startAngle(i, this.period), endAngle(i, this.period)));
      } else if (this.graphType === 'non-spiral') {
        this.data.push([i, size*this.period, 2])
      }
    }
  }
}

// For time point #t, calculate the angle to the center of the arc
// period is the number of time points per revolution (2 PI)
function theta(t, period) {
  return 2 * Math.PI / (period) * t;
}

function startAngle(t, period){
  return (theta(t-1, period) + theta(t, period))/2;
}

function endAngle(t, period){
  return (theta(t+1, period) + theta(t, period))/2;
}

function radius(spacing, angle) {
  return spacing * angle;
}

var spiral1 = new Spiral('points');
spiral1.numberOfPoints = 1000;
spiral1.period = 100;
spiral1.svgHeight = 500;
spiral1.svgWidth = 750;
spiral1.spacing = 8;
spiral1.randomData();
spiral1.render();

var spiral2 = new Spiral('custom-path')
spiral2.numberOfPoints = 1000;
spiral2.period = 100;
spiral2.svgHeight = 500;
spiral2.svgWidth = 750;
spiral2.spacing = 8;
spiral2.randomData();
spiral2.render();

// spiral('custom-path');
//spiral('paths');
//spiral('arcs');<commit_msg>Update randomData function<commit_after>function Spiral(graphType) {
  this.graphType = graphType || "points";
  this.numberOfPoints = null,
  this.period = null,
  this.margin = {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  this.svgHeight = 0,
  this.svgWidth = 0,
  this.spacing = 1,
  this.targetElement = "body",
  this.width = this.svgWidth - this.margin.left - this.margin.right,
  this.height = this.svgHeight - this.margin.top - this.margin.bottom,
  this.data = [],
  this.x = d3.scale.linear().range([0, 730]).domain([-740, 740]), // TODO : x.domain([-this.height-this.margin.bottom, this.height+this.margin.top]);
  this.y = d3.scale.linear().range([480, 0]).domain([-490, 490]), // TODO : y.domain([-this.height-this.margin.bottom, this.height+this.margin.top]);
  this.cartesian = function(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = this.x(radius * Math.cos(angle));
    var yPos = this.y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  },
  this.render = function() {
    var svg = d3.select(this.targetElement)
      .append("svg")
      .attr("width", this.svgWidth)
      .attr("height", this.svgHeight)

    if (this.graphType === "points") {
      svg.append("g")
        .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");

      svg.selectAll("g").selectAll("dot")
        .data(this.data)
          .enter().append("circle")
            .attr("r", function(d) { return d[2]; })
            .attr("cx", function(d) { return d[0]; })
            .attr("cy", function(d) { return d[1]; });
    } else if (this.graphType === "arcs") {
      svg.append("g")
        .attr("transform", "translate(" + (this.width * 0.5 + this.margin.left) + "," + (this.height * 0.5 + this.margin.top) + ")");

      svg.selectAll("g").selectAll("path")
        .data(this.data)
          .enter().append("path")
          .attr("d", d3.svg.arc()
          .outerRadius(function(d){return y(d[3]+10)})
          .innerRadius(function(d){return y(d[3]-10)})
          .startAngle(function(d) { return d[5] > 0 ? d[5] : 0; })
          .endAngle(function(d) { return d[6]; }))
          .attr("opacity", function(d){return d[2]/5})
    } else if (this.graphType === "paths") {

      var line = d3.svg.line()
          .interpolate("basis");

      svg.append("g")
        .attr("transform", "translate(" + (this.margin.left) + "," + (this.margin.top) + ")");

      svg.selectAll("g").selectAll("path")
          .data(quad(sample(line(this.data), this.numberOfPoints, this.period))) // ***** Need to figure out the proper precision to map data crrectly
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("stroke", function(d) { return "black"; })
          .style("opacity", function(d) {return d.data/6})
          .attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 10); });

      // Sample the SVG path string "d" uniformly with the specified precision.
      function sample(d, numberDataPoints, periodicity) {
        var path = document.createElementNS(d3.ns.prefix.svg, "path");
        path.setAttribute("d", d);

        var n = path.getTotalLength();
        var t = [0];
        var i = 1;
        var dt = Math.ceil(i/periodicity)*2;
        var lastSample = 0;
        while (lastSample + dt < n) {
          dt = Math.ceil(i/periodicity)*2;
          t.push(lastSample + dt);
          lastSample = lastSample + dt;
          i++;
        }
        t.push(n);

        return t.map(function(t, index) {
          var p = path.getPointAtLength(t);
          var a = data[index] ? [p.x, p.y, data[index][2]] : [p.x, p.y, 0];
          return a;
        });
      }

      // Compute quads of adjacent points [p0, p1, p2, p3].
      function quad(points) {
        return d3.range(points.length - 1).map(function(i) {
          var a = [points[i - 1], points[i], points[i + 1], points[i + 2]];
          a.data = points[i][2];
          return a;
        });
      }

      // Compute stroke outline for segment p12.
      function lineJoin(p0, p1, p2, p3, width) {
        var u12 = perp(p1, p2),
            r = width / 2,
            a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
            b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
            c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r],
            d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r];

        if (p0) { // clip ad and dc using average of u01 and u12
          var u01 = perp(p0, p1), e = [p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1]];
          a = lineIntersect(p1, e, a, b);
          d = lineIntersect(p1, e, d, c);
        }

        if (p3) { // clip ab and dc using average of u12 and u23
          var u23 = perp(p2, p3), e = [p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1]];
          b = lineIntersect(p2, e, a, b);
          c = lineIntersect(p2, e, d, c);
        }

        return "M" + a + "L" + b + " " + c + " " + d + "Z";
      }

      // Compute intersection of two infinite lines ab and cd.
      function lineIntersect(a, b, c, d) {
        var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3;
        var y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3;
        var ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
        return [x1 + ua * x21, y1 + ua * y21];
      }

      // Compute unit vector perpendicular to p01.
      function perp(p0, p1) {
        var u01x = p0[1] - p1[1];
        var u01y = p1[0] - p0[0];
        var u01d = Math.sqrt(u01x * u01x + u01y * u01y);
        return [u01x / u01d, u01y / u01d];
      }
    } else if (this.graphType === "custom-path") {
      var pathWidth = 50;
      var spiralContext = this;

      this.data.forEach(function(datum, t, dataSet){
        var start = startAngle(t, spiralContext.period);
        var end = endAngle(t, spiralContext.period);

        var startInnerRadius = radius(spiralContext.spacing, start) - pathWidth*0.5;
        var startOuterRadius = radius(spiralContext.spacing, start) + pathWidth*0.5;
        var endInnerRadius = radius(spiralContext.spacing, end) - pathWidth*0.5;
        var endOuterRadius = radius(spiralContext.spacing, end) + pathWidth*0.5;

        var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
        var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
        var innerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) - pathWidth*0.5 + ctrlInnerRad, theta(t, spiralContext.period));
        var outerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) + pathWidth*0.5 + ctrlOuterRad, theta(t, spiralContext.period));

        var startPoint = spiralContext.cartesian(startInnerRadius, start); // Bottom right of arc
        var point2 = spiralContext.cartesian(startOuterRadius, start); // Top right of arc
        var point3 = spiralContext.cartesian(endOuterRadius, end); // Top left of arc
        var point4 = spiralContext.cartesian(endInnerRadius, end); // Bottom left of arc
        var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
        arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
        arcPath += "L" + point4[0] + " " + point4[1];
        arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
        datum[1] = arcPath
        console.log(datum)
      });

      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");
      svg.selectAll("g").selectAll("path")
        .data(spiralContext.data.slice(100))
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("opacity", function(d) {return d[2]/9})
          .attr("d", function(d) { return d[1]});
    } else if (this.graphType === "non-spiral") {
      // --------------------vvv Standard Line Graph vvv---------------------------
      var x2 = d3.scale.linear().range([0, 730]);
      var y2 = d3.scale.linear().range([480, 0]);
      x2.domain(d3.extent(this.data, function(d) { return d[0]; }));
      y2.domain(d3.extent(this.data, function(d) { return d[1]; }));

      var xAxis = d3.svg.axis().scale(x2)
        .orient("bottom").ticks(5);

      var yAxis = d3.svg.axis().scale(y2)
        .orient("left").ticks(5);

      var line = d3.svg.line()
        .x(function(d) { return x2(d[0]); })
        .y(function(d) { return y2(d[1]); });

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+this.margin.left+"," + 480 + ")")
        .call(xAxis)
        .append("text")
          .attr("x", 710)
          .attr("y", -3)
          .attr("dy", "-.35em")
          .style("text-anchor", "middle")
          .text("time");

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+this.margin.left+",0)")
        .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Signal (a.u.)");

      svg.append("path")
        .datum(this.data)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke-width", "1")
        .attr("stroke", "steelblue")
        .attr("transform", "translate("+this.margin.left+",0)")
    }
  },
  this.randomData = function() {
    for (var i=0; i<this.numberOfPoints; i++){
      var angle = theta(i, this.period);
      var rad = radius(this.spacing, angle);
      var size = 1 + Math.random()*1.5;
      if (i % 10 === 0) {
        size = 5.5 + Math.random()*3;
      }

      if (this.graphType === 'non-spiral') {
        this.data.push([i, size*this.period, 2])
      } else {
        this.data.push(this.cartesian(rad, angle, size, startAngle(i, this.period), endAngle(i, this.period)));
      }
    }
  }
}

// For time point #t, calculate the angle to the center of the arc
// period is the number of time points per revolution (2 PI)
function theta(t, period) {
  return 2 * Math.PI / (period) * t;
}

function startAngle(t, period){
  return (theta(t-1, period) + theta(t, period))/2;
}

function endAngle(t, period){
  return (theta(t+1, period) + theta(t, period))/2;
}

function radius(spacing, angle) {
  return spacing * angle;
}

var spiral1 = new Spiral('points');
spiral1.numberOfPoints = 1000;
spiral1.period = 100;
spiral1.svgHeight = 500;
spiral1.svgWidth = 750;
spiral1.spacing = 8;
spiral1.randomData();
spiral1.render();

var spiral2 = new Spiral('arcs')
spiral2.numberOfPoints = 1000;
spiral2.period = 100;
spiral2.svgHeight = 500;
spiral2.svgWidth = 750;
spiral2.spacing = 8;
spiral2.randomData();
spiral2.render();

// spiral('custom-path');
//spiral('paths');
//spiral('arcs');<|endoftext|>


<commit_before>'use strict';
//var async = require('async');
//var deepExtend = require('deep-extend');
var log = require('debug')('routes');

module.exports = function (app) {
    var path = require('path');
    var serverPath = path.join(__dirname,'../modules');

    app.get('/widget/get-domain-list', function (req, res) {
        log('Retrieving dwDomains');
        //JReeme sez: setMaxListeners so we don't have to see that ridiculous memory leak warning
        app.models.DwDomain.getDataSource().setMaxListeners(0);

        var dwDomain = app.models.DwDomain;

        dwDomain.find(function (err, domains) {
            var domainItems = [];
            domains.forEach(function (domain) {
                domainItems.push({name:domain.name,description: domain.description});
            });
            var renderPath = serverPath.concat('/domainWidget/main');
            res.render(renderPath, {
                "pageTitle": 'Domain Listing',
                "domainList": domainItems
            });
        });
    });

    app.get('/widget/get-url-entities', function (req, res) {
        log('Retrieving Url Entities');
        //JReeme sez: setMaxListeners so we don't have to see that ridiculous memory leak warning
        app.models.DwTrailUrl.getDataSource().setMaxListeners(0);

        var dwTrailUrl = app.models.DwTrailUrl;

        var whereClause={
            "order":"timestamp DESC",
            "where":{"url":req.query.trailUrl},
            "include":[{"relation":"urlExtractions","scope":{"where": {"extractorTypes": {"nin":["text"]}}, "order":"occurrences DESC"}}]
        };

        dwTrailUrl.findOne(whereClause,function (err, trailUrl) {
            trailUrl.urlExtractions(function(err,urlExt){
                var renderPath = serverPath.concat('/extractedEntityWidget/main');
                res.render(renderPath, {
                    "pageTitle": 'Extracted Entities',
                    "extractedEntities": urlExt
                });
            })

        });
    });
};

<commit_msg>check for trail and trail urls after findOne<commit_after>'use strict';
//var async = require('async');
//var deepExtend = require('deep-extend');
var log = require('debug')('routes');

module.exports = function (app) {
    var path = require('path');
    var serverPath = path.join(__dirname,'../modules');

    app.get('/widget/get-domain-list', function (req, res) {
        log('Retrieving dwDomains');
        //JReeme sez: setMaxListeners so we don't have to see that ridiculous memory leak warning
        app.models.DwDomain.getDataSource().setMaxListeners(0);

        var dwDomain = app.models.DwDomain;

        dwDomain.find(function (err, domains) {
            var domainItems = [];
            domains.forEach(function (domain) {
                domainItems.push({name:domain.name,description: domain.description});
            });
            var renderPath = serverPath.concat('/domainWidget/main');
            res.render(renderPath, {
                "pageTitle": 'Domain Listing',
                "domainList": domainItems
            });
        });
    });

    app.get('/widget/get-url-entities', function (req, res) {
        log('Retrieving Url Entities');
        //JReeme sez: setMaxListeners so we don't have to see that ridiculous memory leak warning
        app.models.DwTrailUrl.getDataSource().setMaxListeners(0);

        var dwTrailUrl = app.models.DwTrailUrl;

        var whereClause={
            "order":"timestamp DESC",
            "where":{"url":req.query.trailUrl},
            "include":[{"relation":"urlExtractions","scope":{"where": {"extractorTypes": {"nin":["text"]}}, "order":"occurrences DESC"}}]
        };

        dwTrailUrl.findOne(whereClause,function (err, trailUrl) {
            if(err || !trailUrl || !trailUrl.urlExtractions){
                return;
            }
            trailUrl.urlExtractions(function(err,urlExt){
                var renderPath = serverPath.concat('/extractedEntityWidget/main');
                    res.render(renderPath, {
                        "pageTitle": 'Extracted Entities',
                        "extractedEntities": urlExt
                    });
                }
            )
        });
    });
};

<|endoftext|>


<commit_before>var p = require('../package.json'),
    version = p.version.split('.').shift();
module.exports = {
    restApiRoot: '/api' + (version > 0 ? '/v' + version : ''),
    host: process.env.API_HOST || '0.0.0.0',
    port: process.env.API_PORT || 8888,
    'remoting': {
        'context': {
            'enableHttpContext': true
        },
        'rest': {
            'normalizeHttpPath': false,
            'xml': false
        },
        'json': {
            'strict': false,
            'limit': '100kb'
        },
        'urlencoded': {
            'extended': true,
            'limit': '100kb'
        },
        'cors': false,
        'errorHandler': {
            'disableStackTrace': false
        }
    },
    'webapp_url': process.env.WEBAPP_EXPOSED_URL || null,
    'pubsub_url': process.env.PS_EXPOSED_URL || null,
    'pubsub_api_token': process.env.PS_API_TOKEN || '8629c101-4db7-4a0a-9bf1-33c5fc3cff23',
    'cookieSecret': process.env.COOKIE_SECRECT || 'cce6829c-328e-4e38-aa5c-f4714ac93914',
    'legacyExplorer': false
};
<commit_msg>Add default pubsub url<commit_after>var p = require('../package.json'),
    version = p.version.split('.').shift();
module.exports = {
    restApiRoot: '/api' + (version > 0 ? '/v' + version : ''),
    host: process.env.API_HOST || '0.0.0.0',
    port: process.env.API_PORT || 8888,
    'remoting': {
        'context': {
            'enableHttpContext': true
        },
        'rest': {
            'normalizeHttpPath': false,
            'xml': false
        },
        'json': {
            'strict': false,
            'limit': '100kb'
        },
        'urlencoded': {
            'extended': true,
            'limit': '100kb'
        },
        'cors': false,
        'errorHandler': {
            'disableStackTrace': false
        }
    },
    'webapp_url': process.env.WEBAPP_EXPOSED_URL || null,
    'pubsub_url': process.env.PS_EXPOSED_URL || 'http://0.0.0.0:8889/faye',
    'pubsub_api_token': process.env.PS_API_TOKEN || '8629c101-4db7-4a0a-9bf1-33c5fc3cff23',
    'cookieSecret': process.env.COOKIE_SECRECT || 'cce6829c-328e-4e38-aa5c-f4714ac93914',
    'legacyExplorer': false
};
<|endoftext|>


<commit_before>Meteor.startup(function () {
	'use strict';

	if (Progressor.categories.find().count() === 0
			&& Progressor.exercises.find().count() === 0
			&& Progressor.results.find().count() === 0
			&& Progressor.examinations.find().count() === 0
			&& Progressor.executions.find().count() === 0) {

		const solutions = {
			java: 'public String helloWorld() { return "Hello, World!"; }',
			cpp: 'string helloWorld() { return "Hello, World!"; }',
			csharp: 'public string helloWorld() => "Hello, World!";',
			python: 'def helloWorld(): return "Hello, World!"',
			kotlin: 'fun helloWorld() = "Hello, World!"'
		};

		_.each(Progressor.getProgrammingLanguages(), l => {
			Progressor.categories.insert(
				{
					programmingLanguage: l._id,
					names: [
						{ language: 'en', name: 'Basics' },
						{ language: 'de', name: 'Grundlagen' }
					],
					descriptions: [
						{ language: 'en', description: 'The basic syntax of a programming language is shown by means of a simple Hello World exercise.' },
						{ language: 'en', description: 'Die Grundlagen einer Programmiersprache werden am besten mit einer einfachen Hallo Welt-Aufgabe gezeigt.' }
					],
					lastEdited: new Date()
				});
			Progressor.exercises.insert(
				{
					names: [
						{ language: 'en', name: 'Hello, World!' },
						{ language: 'de', name: 'Hallo, Welt!' }
					],
					programmingLanguage: l._id,
					category_id: Progressor.categories.findOne({ programmingLanguage: l._id })._id,
					difficulty: 1,
					type: 1,
					descriptions: [
						{ language: 'en', description: 'Return **Hello, World!**.' },
						{ language: 'de', description: 'Gib __Hello, World!__ zurück.' }
					],
					functions: [
						{
							name: 'helloWorld',
							inputNames: [],
							inputTypes: [],
							outputNames: ['return'],
							outputTypes: ['string']
						}
					],
					testCases: [
						{
							functionName: 'helloWorld',
							inputValues: [],
							expectedOutputValues: ['Hello, World!'],
							visible: true
						}
					],
					solution: solutions[l._id],
					solutionVisible: true,
					released: {
						requested: new Date(),
						confirmed: new Date()
					},
					lastEdited: new Date()
				});
		});

		Progressor.examinations.insert(
			{
				names: [
					{ language: 'en', name: 'Basics' },
					{ language: 'de', name: 'Grundlagen' }
				],
				exercises: _.map(Progressor.exercises.find().fetch(), exercise => ({
					exercise_id: exercise._id,
					weight: Math.floor(Random.fraction() * 12 + 1)
				})),
				durationMinutes: 365 * 24 * 60,
				lastEdited: new Date()
			});

		_.each(Progressor.examinations.find().fetch(), e => Progressor.executions.insert(
			{
				_id: 'Xh3YGewf9JT5AGoav',
				examination_id: e._id,
				names: [
					{ language: 'en', name: `Basics - ${new Date().getFullYear()}` },
					{ language: 'de', name: `Basics - ${new Date().getFullYear()}` }
				],
				descriptions: e.descriptions,
				startTime: new Date(new Date().getFullYear(), 0, 1),
				durationMinutes: e.durationMinutes,
				exercises: _.chain(e.exercises).map(exercise => ({
					weight: exercise.weight,
					base_id: exercise.exercise_id,
					exercise_id: Progressor.exercises.insert(_.extend(_.omit(Progressor.exercises.findOne({ _id: exercise.exercise_id }), '_id', 'category_id', 'difficulty', 'released', 'archived'), {
						execution_id: 'Xh3YGewf9JT5AGoav'
					}))
				})).sortBy(() => Random.fraction()).value(),
				lastEdited: new Date()
			}));
	}

});
<commit_msg>data fix<commit_after>Meteor.startup(function () {
	'use strict';

	if (Progressor.categories.find().count() === 0
			&& Progressor.exercises.find().count() === 0
			&& Progressor.results.find().count() === 0
			&& Progressor.examinations.find().count() === 0
			&& Progressor.executions.find().count() === 0) {

		const solutions = {
			java: 'public String helloWorld() { return "Hello, World!"; }',
			cpp: 'string helloWorld() { return "Hello, World!"; }',
			csharp: 'public string helloWorld() => "Hello, World!";',
			python: 'def helloWorld(): return "Hello, World!"',
			kotlin: 'fun helloWorld() = "Hello, World!"'
		};

		_.each(Progressor.getProgrammingLanguages(), l => {
			Progressor.categories.insert(
				{
					programmingLanguage: l._id,
					names: [
						{ language: 'en', name: 'Basics' },
						{ language: 'de', name: 'Grundlagen' }
					],
					descriptions: [
						{ language: 'en', description: 'The basic syntax of a programming language is shown by means of a simple Hello World exercise.' },
						{ language: 'en', description: 'Die Grundlagen einer Programmiersprache werden am besten mit einer einfachen Hallo Welt-Aufgabe gezeigt.' }
					],
					lastEdited: new Date()
				});
			Progressor.exercises.insert(
				{
					names: [
						{ language: 'en', name: 'Hello, World!' },
						{ language: 'de', name: 'Hallo, Welt!' }
					],
					programmingLanguage: l._id,
					category_id: Progressor.categories.findOne({ programmingLanguage: l._id })._id,
					difficulty: 1,
					type: 1,
					descriptions: [
						{ language: 'en', description: 'Return **Hello, World!**.' },
						{ language: 'de', description: 'Gib __Hello, World!__ zurück.' }
					],
					functions: [
						{
							name: 'helloWorld',
							inputNames: [],
							inputTypes: [],
							outputNames: ['return'],
							outputTypes: ['string']
						}
					],
					testCases: [
						{
							functionName: 'helloWorld',
							inputValues: [],
							expectedOutputValues: ['Hello, World!'],
							visible: true
						}
					],
					solution: solutions[l._id],
					solutionVisible: true,
					released: {
						requested: new Date(),
						confirmed: new Date()
					},
					lastEdited: new Date()
				});
		});

		Progressor.examinations.insert(
			{
				names: [
					{ language: 'en', name: 'Basics' },
					{ language: 'de', name: 'Grundlagen' }
				],
				exercises: _.map(Progressor.exercises.find().fetch(), exercise => ({
					exercise_id: exercise._id,
					weight: Math.floor(Random.fraction() * 12 + 1)
				})),
				durationMinutes: 365 * 24 * 60,
				lastEdited: new Date()
			});

		_.each(Progressor.examinations.find().fetch(), e => Progressor.executions.insert(
			{
				_id: 'Xh3YGewf9JT5AGoav',
				examination_id: e._id,
				names: [
					{ language: 'en', name: `Basics - ${new Date().getFullYear()}` },
					{ language: 'de', name: `Basics - ${new Date().getFullYear()}` }
				],
				descriptions: [
					{ language: 'en', description: 'The basic syntax of a programming language is shown by means of a simple Hello World exercise.' },
					{ language: 'en', description: 'Die Grundlagen einer Programmiersprache werden am besten mit einer einfachen Hallo Welt-Aufgabe gezeigt.' }
				],
				startTime: new Date(new Date().getFullYear(), 0, 1),
				durationMinutes: e.durationMinutes,
				exercises: _.chain(e.exercises).map(exercise => ({
					weight: exercise.weight,
					base_id: exercise.exercise_id,
					exercise_id: Progressor.exercises.insert(_.extend(_.omit(Progressor.exercises.findOne({ _id: exercise.exercise_id }), '_id', 'category_id', 'difficulty', 'released', 'archived'), {
						execution_id: 'Xh3YGewf9JT5AGoav'
					}))
				})).sortBy(() => Random.fraction()).value(),
				lastEdited: new Date()
			}));
	}

});
<|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global esprima require define console module*/
//Api version of JSDepend. Suitable for calling directly from JavaScript code.

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(function(require, exports, module) {

var parser = require("./parser");
var findReferences = require("./reference-finder").findReferences;
var eachk = require("./utils").eachk;
var getModuleType = require('./module-types').getModuleType;
var when = require('when');

//function dumpTree(parseTree) {
//	console.log(JSON.stringify(parseTree, null, "  "));
//}

function fromConfig(conf, name, type) {
	var it = conf[name];
	if (!it) {
		throw "jsdepend/api conf must provide a definition for '"+name+"'";
	}
	if (type && typeof(it)!==type) {
		throw "jsdepend/api conf must provide a '"+type+"' for '"+name+"'";
	}
	return it;
}

/**
 * wraps a callback function so that is logs the value passed to the callback
 * in JSON.stringified form.
 */
function logBack(msg, callback) {
	return function (result) {
		console.log(msg);
		console.log(JSON.stringify(result, null, "  "));
		callback(result);
	};
}

/**
 * This function 'creates' the API. It requires a configuration object.
 */
function configure(config) {

	var getContents = fromConfig(config, 'getContents', 'function');
	var resolve = require("./resolver").configure(config).resolve;
	var getConf = require('./dot-scripted').configure(config).getConfiguration;
	var retrieveNearestFile = require('./retrieve-nearest-file').configure(config).retrieveNearestFile;
	var findGlobalDependencies = require('./global-dependencies-finder').configure(config);

//	console.log('jsdepend/api is using encoding: '+encoding);

	function getReferences(handle, moduleType, tree, callback) {
		findReferences(handle, moduleType, tree, callback);
	}

	function getDependencies(handle, callback) {
		//callback = logBack("getDependencies("+handle+") ==> ", callback);
		getContents(handle,
			function (contents) {
				var tree = parser.parse(contents);
				var moduleType = getModuleType(tree);
				findReferences(tree, moduleType, function (refs) {
					resolve(handle, refs, function (resolvedRefs) {
						callback(resolvedRefs, moduleType);
					});
				});
			},
			function (err) {
				console.error(err);
				callback([], 'unknown');
			}
		);
	}

    /**
	 * Create a 'store' to record the result of getDGraph function.
	 */
	function makeGraphStore() {
		var graph = {};
		var seen = {}; //The properties of this are path strings. It is assumed that the a path uniquely identifies
					   //modules we have already seen (i.e. we have already processed them, or are currently processing them).
					   //This is used to detect and break cycles.
					   //We can't use the graph itself for this because nodes are only added to the graph after
					   //all their children have been processed.

		return {
			/**
			 * Mark a given file handle as being processed. The function returns true if the mark was succesfully
			 * added (i.e. it was not 'marked' before).
			 *
			 * @param String handle
			 * @return boolean
			 */
			mark: function (handle, mark) {
				var notMarked = !seen.hasOwnProperty(handle);
				if (notMarked) {
					seen[handle] = true;
				}
				return notMarked;
			},
			/**
			 * Add a node to the graph. It is assumed the node doesn't exist yet, but we
			 * do not check this!
			 */
			addNode: function (path, node) {
				graph[path] = node;
			},
			/**
			 * Retrieve all the dependencies in the order they where added.
			 *
			 * @return Array.<Dependency>
			 */
			getGraph: function () {
				return graph;
			}
		};
	}

	function buildGraph(handle, store, k) {
		if (handle && store.mark(handle)) {
			getDependencies(handle, function (deps, kind) {
				var refs = {};
				var node = {
					kind: kind,
					refs: refs
				};
				eachk(deps, function (dep, k) {
						refs[dep.name] = dep;
						buildGraph(dep.path, store, k);
					},
					function () {
						//all deps have been processed
						store.addNode(handle, node);
						k();
					}
				);
			});
		} else {
			k();
		}
	}

	function getDGraph(handle, callback) {
		callback = logBack('getDGraph '+handle+ ' => ', callback);
		var store = makeGraphStore();
		buildGraph(handle, store, function () {
			var graph = store.getGraph();
			if (graph[handle].kind === 'unknown') {
				//This means we didn't get a dependency graph, the start node was of 'unknown' type.
				//So now let's try looking for global dependencies.
				when(findGlobalDependencies(handle),
					callback,
					function (error) {
//						console.error(Array.isArray(error)
//							? JSON.stringify(error, null, '  ')
//							: error
//						);
						callback(store.getGraph());
					}
				);
			} else {
				callback(store.getGraph());
			}
		});
	}

	getDGraph.remoteType =  ['JSON', 'callback'];
	getDependencies.remoteType = ['JSON', 'callback'];
	getContents.remoteType = ['JSON', 'callback', 'errback'];
	getConf.remoteType = ['JSON', 'callback'];
	retrieveNearestFile.remoteType = ['JSON', 'JSON', 'JSON', 'callback'];

	//Creates the API object containing all exported operations for this API.
	return {
		getContents: getContents,
		getDependencies: getDependencies,
		getDGraph: getDGraph,
		getConf: getConf,
		retrieveNearestFile: retrieveNearestFile
	};
}

exports.configure = configure;

});

<commit_msg>Cleanup logging code<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global esprima require define console module*/
//Api version of JSDepend. Suitable for calling directly from JavaScript code.

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(function(require, exports, module) {

var parser = require("./parser");
var findReferences = require("./reference-finder").findReferences;
var eachk = require("./utils").eachk;
var getModuleType = require('./module-types').getModuleType;
var when = require('when');

//function dumpTree(parseTree) {
//	console.log(JSON.stringify(parseTree, null, "  "));
//}

function fromConfig(conf, name, type) {
	var it = conf[name];
	if (!it) {
		throw "jsdepend/api conf must provide a definition for '"+name+"'";
	}
	if (type && typeof(it)!==type) {
		throw "jsdepend/api conf must provide a '"+type+"' for '"+name+"'";
	}
	return it;
}

/**
 * wraps a callback function so that is logs the value passed to the callback
 * in JSON.stringified form.
 */
function logBack(msg, callback) {
	return function (result) {
		console.log(msg);
		console.log(JSON.stringify(result, null, "  "));
		callback(result);
	};
}

/**
 * This function 'creates' the API. It requires a configuration object.
 */
function configure(config) {

	var getContents = fromConfig(config, 'getContents', 'function');
	var resolve = require("./resolver").configure(config).resolve;
	var getConf = require('./dot-scripted').configure(config).getConfiguration;
	var retrieveNearestFile = require('./retrieve-nearest-file').configure(config).retrieveNearestFile;
	var findGlobalDependencies = require('./global-dependencies-finder').configure(config);

//	console.log('jsdepend/api is using encoding: '+encoding);

	function getReferences(handle, moduleType, tree, callback) {
		findReferences(handle, moduleType, tree, callback);
	}

	function getDependencies(handle, callback) {
		//callback = logBack("getDependencies("+handle+") ==> ", callback);
		getContents(handle,
			function (contents) {
				var tree = parser.parse(contents);
				var moduleType = getModuleType(tree);
				findReferences(tree, moduleType, function (refs) {
					resolve(handle, refs, function (resolvedRefs) {
						callback(resolvedRefs, moduleType);
					});
				});
			},
			function (err) {
				console.error(err);
				callback([], 'unknown');
			}
		);
	}

    /**
	 * Create a 'store' to record the result of getDGraph function.
	 */
	function makeGraphStore() {
		var graph = {};
		var seen = {}; //The properties of this are path strings. It is assumed that the a path uniquely identifies
					   //modules we have already seen (i.e. we have already processed them, or are currently processing them).
					   //This is used to detect and break cycles.
					   //We can't use the graph itself for this because nodes are only added to the graph after
					   //all their children have been processed.

		return {
			/**
			 * Mark a given file handle as being processed. The function returns true if the mark was succesfully
			 * added (i.e. it was not 'marked' before).
			 *
			 * @param String handle
			 * @return boolean
			 */
			mark: function (handle, mark) {
				var notMarked = !seen.hasOwnProperty(handle);
				if (notMarked) {
					seen[handle] = true;
				}
				return notMarked;
			},
			/**
			 * Add a node to the graph. It is assumed the node doesn't exist yet, but we
			 * do not check this!
			 */
			addNode: function (path, node) {
				graph[path] = node;
			},
			/**
			 * Retrieve all the dependencies in the order they where added.
			 *
			 * @return Array.<Dependency>
			 */
			getGraph: function () {
				return graph;
			}
		};
	}

	function buildGraph(handle, store, k) {
		if (handle && store.mark(handle)) {
			getDependencies(handle, function (deps, kind) {
				var refs = {};
				var node = {
					kind: kind,
					refs: refs
				};
				eachk(deps, function (dep, k) {
						refs[dep.name] = dep;
						buildGraph(dep.path, store, k);
					},
					function () {
						//all deps have been processed
						store.addNode(handle, node);
						k();
					}
				);
			});
		} else {
			k();
		}
	}

	function getDGraph(handle, callback) {
		//callback = logBack('getDGraph '+handle+ ' => ', callback);
		var store = makeGraphStore();
		buildGraph(handle, store, function () {
			var graph = store.getGraph();
			if (graph[handle].kind === 'unknown') {
				//This means we didn't get a dependency graph, the start node was of 'unknown' type.
				//So now let's try looking for global dependencies.
				when(findGlobalDependencies(handle),
					callback,
					function (error) {
//						console.error(Array.isArray(error)
//							? JSON.stringify(error, null, '  ')
//							: error
//						);
						callback(store.getGraph());
					}
				);
			} else {
				callback(store.getGraph());
			}
		});
	}

	getDGraph.remoteType =  ['JSON', 'callback'];
	getDependencies.remoteType = ['JSON', 'callback'];
	getContents.remoteType = ['JSON', 'callback', 'errback'];
	getConf.remoteType = ['JSON', 'callback'];
	retrieveNearestFile.remoteType = ['JSON', 'JSON', 'JSON', 'callback'];

	//Creates the API object containing all exported operations for this API.
	return {
		getContents: getContents,
		getDependencies: getDependencies,
		getDGraph: getDGraph,
		getConf: getConf,
		retrieveNearestFile: retrieveNearestFile
	};
}

exports.configure = configure;

});

<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) );

/**
* @name Complex64Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex64}
*/
setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) );

/**
* @name Complex128Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex128}
*/
setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) );

/**
* @name convertArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert}
*/
setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) );

/**
* @name convertArraySame
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert-same}
*/
setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) );

/**
* @name arrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/ctors}
*/
setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) );

/**
* @name arrayDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtype}
*/
setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) );

/**
* @name arrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtypes}
*/
setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) );

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) );

/**
* @name iterator2array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/from-iterator}
*/
setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) );

/**
* @name arrayMinDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/min-dtype}
*/
setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) );

/**
* @name arrayNextDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/next-dtype}
*/
setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) );

/**
* @name typedarraypool
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/pool}
*/
setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) );

/**
* @name arrayPromotionRules
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/promotion-rules}
*/
setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) );

/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) );

/**
* @name arraySafeCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/safe-casts}
*/
setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) );

/**
* @name arraySameKindCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/same-kind-casts}
*/
setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) );

/**
* @name arrayShape
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/shape}
*/
setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) );

/**
* @name SharedArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/shared-buffer}
*/
setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) );

/**
* @name circarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-circular-iterator}
*/
setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) );

/**
* @name array2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator}
*/
setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) );

/**
* @name array2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator-right}
*/
setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) );

/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) );

/**
* @name sparsearray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator}
*/
setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) );

/**
* @name sparsearray2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator-right}
*/
setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) );

/**
* @name stridedarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-strided-iterator}
*/
setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) );

/**
* @name typedarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) );

/**
* @name typedarrayComplexCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-ctors}
*/
setReadOnly( ns, 'typedarrayComplexCtors', require( '@stdlib/array/typed-complex-ctors' ) );

/**
* @name typedarrayComplexDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-dtypes}
*/
setReadOnly( ns, 'typedarrayComplexDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) );

/**
* @name typedarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-ctors}
*/
setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) );

/**
* @name typedarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-dtypes}
*/
setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) );

/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) );

/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) );

/**
* @name constants
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/constants/array}
*/
setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) );

/**
* @name Complex64Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex64}
*/
setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) );

/**
* @name Complex128Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex128}
*/
setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) );

/**
* @name convertArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert}
*/
setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) );

/**
* @name convertArraySame
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert-same}
*/
setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) );

/**
* @name arrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/ctors}
*/
setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) );

/**
* @name arrayDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtype}
*/
setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) );

/**
* @name arrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtypes}
*/
setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) );

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) );

/**
* @name iterator2array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/from-iterator}
*/
setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) );

/**
* @name arrayMinDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/min-dtype}
*/
setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) );

/**
* @name arrayNextDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/next-dtype}
*/
setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) );

/**
* @name typedarraypool
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/pool}
*/
setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) );

/**
* @name arrayPromotionRules
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/promotion-rules}
*/
setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) );

/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) );

/**
* @name arraySafeCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/safe-casts}
*/
setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) );

/**
* @name arraySameKindCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/same-kind-casts}
*/
setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) );

/**
* @name arrayShape
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/shape}
*/
setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) );

/**
* @name SharedArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/shared-buffer}
*/
setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) );

/**
* @name circarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-circular-iterator}
*/
setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) );

/**
* @name array2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator}
*/
setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) );

/**
* @name array2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator-right}
*/
setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) );

/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) );

/**
* @name sparsearray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator}
*/
setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) );

/**
* @name sparsearray2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator-right}
*/
setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) );

/**
* @name stridedarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-strided-iterator}
*/
setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) );

/**
* @name arrayview2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator}
*/
setReadOnly( ns, 'arrayview2iterator', require( '@stdlib/array/to-view-iterator' ) );

/**
* @name typedarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) );

/**
* @name typedarrayComplexCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-ctors}
*/
setReadOnly( ns, 'typedarrayComplexCtors', require( '@stdlib/array/typed-complex-ctors' ) );

/**
* @name typedarrayComplexDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-dtypes}
*/
setReadOnly( ns, 'typedarrayComplexDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) );

/**
* @name typedarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-ctors}
*/
setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) );

/**
* @name typedarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-dtypes}
*/
setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) );

/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) );

/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) );

/**
* @name constants
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/constants/array}
*/
setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>/*
 * Xibo - Digitial Signage - http://www.xibo.org.uk
 * Copyright (C) 2006,2007,2008 Daniel Garner and James Packer
 *
 * This file is part of Xibo.
 *
 * Xibo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * Xibo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
 */
function week_change(value) {
	var field = document.getElementById("3");

	field.value = parseInt(field.value) + parseInt(value);

	return;
}

function month_change(value) {
	var field = document.getElementById("4");

	field.value = parseInt(field.value) + parseInt(value);

	return;
}

function reset_time() {
	document.getElementById("3").value = 0;
	document.getElementById("4").value = 0;
}<commit_msg>[server] Fixed problem with media manger homepage on first load.<commit_after>/*
 * Xibo - Digitial Signage - http://www.xibo.org.uk
 * Copyright (C) 2011 Daniel Garner
 *
 * This file is part of Xibo.
 *
 * Xibo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * Xibo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
 */
function week_change(value) {
	var field = document.getElementById("3");

	field.value = parseInt(field.value) + parseInt(value);

	return;
}

function month_change(value) {
	var field = document.getElementById("4");

	field.value = parseInt(field.value) + parseInt(value);

	return;
}

function reset_time() {
	document.getElementById("3").value = 0;
	document.getElementById("4").value = 0;
}

var text_callback = function()
{
    // Conjure up a text editor
    $("#ta_text").ckeditor();

    // Make sure when we close the dialog we also destroy the editor
    $("#div_dialog").bind("dialogclose.xibo", function(event, ui){
        $("#ta_text").ckeditorGet().destroy();
        $("#div_dialog").unbind("dialogclose.xibo");
    })

    var regionid = $("#iRegionId").val();
    var width = $("#region_"+regionid).width();
    var height = $("#region_"+regionid).height();

    // Min width
    if (width < 800) width = 800;

    // Adjust the width and height
    width = width + 80;
    height = height + 295;

    $('#div_dialog').height(height+"px");
    $('#div_dialog').dialog('option', 'width', width);
    $('#div_dialog').dialog('option', 'height', height);
    $('#div_dialog').dialog('option', 'position', 'center');

    return false; //prevent submit
}

var microblog_callback = function()
{
    // Conjure up a text editor
    $("#ta_template").ckeditor();
    $("#ta_nocontent").ckeditor();

    // Make sure when we close the dialog we also destroy the editor
    $("#div_dialog").bind("dialogclose.xibo", function(event, ui){
        $("#ta_template").ckeditorGet().destroy();
        $("#ta_nocontent").ckeditorGet().destroy();

        $("#div_dialog").unbind("dialogclose.xibo");
    })

    var regionid = $("#iRegionId").val();
    var width = $("#region_"+regionid).width();
    var height = $("#region_"+regionid).height();

    //Min width
    if (width < 800) width = 800;
    height = height - 170;

    // Min height
    if (height < 300) height = 300;

    width = width + 80;
    height = height + 480;

    $('#div_dialog').height(height+"px");
    $('#div_dialog').dialog('option', 'width', width);
    $('#div_dialog').dialog('option', 'height', height);
    $('#div_dialog').dialog('option', 'position', 'center');

    return false; //prevent submit
}

var datasetview_callback = function()
{
    $("#columnsIn, #columnsOut").sortable({
		connectWith: '.connectedSortable',
		dropOnEmpty: true
	}).disableSelection();

    return false; //prevent submit
}

var DataSetViewSubmit = function() {
    // Serialise the form and then submit it via Ajax.
    var href = $("#ModuleForm").attr('action') + "&ajax=true";

    // Get the two lists
    serializedData = $("#columnsIn").sortable('serialize') + "&" + $("#ModuleForm").serialize();

    $.ajax({
        type: "post",
        url: href,
        cache: false,
        dataType: "json",
        data: serializedData,
        success: XiboSubmitResponse
    });

    return;
}<|endoftext|>


<commit_before>/*
Notes:

* It takes fewer steps to animate fast springs than slow springs. In other words,
  steps-per-ms is constant. What changes is how drastically the states
  change at each step.

*/

function spring(options) {
  /* Create a new spring object. Override any property with your own options
  object.

  Returns an object with all required spring properties. */
  return {
    mass: options.mass || 0,
    stiffness: options.stiffness || 0,
    friction: options.friction || 1,
    speed: options.speed || 0,
    anchorPos: options.anchorPos || 0,
    position: options.position || 0
  };
}

function tickSpring(spring) {
  /* Mutates a spring object, updating it to its next state. */
  var distance = spring.position - spring.anchorPos;
  var dampingForce = (-1 * spring.friction) * spring.speed;
  var springForce = (-1 * spring.stiffness) * distance;
  var totalForce = springForce + dampingForce;
  var acceleration = totalForce / spring.mass;

  spring.speed += acceleration;
  spring.position += spring.speed / 100;

  return spring;
}

function isSpringAtRest(spring) {
  /* Find out whether a spring is at rest. Returns a boolean. */
  return Math.round(spring.position) === spring.anchorPos && Math.abs(spring.speed) < 0.2;
}

/*
module.exports = {
  extend: extend,
  spring: spring,
  tickSpring: tickSpring,
  isSpringAtRest: isSpringAtRest,
};
*/<commit_msg>Calculate by distance from spring center<commit_after>/*
Notes:

* It takes fewer steps to animate fast springs than slow springs. In other words,
  steps-per-ms is constant. What changes is how drastically the states
  change at each step.

*/

function spring(options) {
  /* Create a new spring object. Override any property with your own options
  object.

  Returns an object with all required spring properties. */
  return {
    distance: options.distance || 0,
    mass: options.mass || 0,
    stiffness: options.stiffness || 0,
    friction: options.friction || 1,
    speed: options.speed || 0
  };
}

function tickSpring(spring) {
  /* Mutates a spring object, updating it to its next state. */
  // AnchorPos is constant.
  var dampingForce = (-1 * spring.friction) * spring.speed;
  var springForce = (-1 * spring.stiffness) * spring.distance;
  var totalForce = springForce + dampingForce;
  var acceleration = totalForce / spring.mass;

  spring.speed += acceleration;
  spring.distance += spring.speed / 100;

  return spring;
}

function isSpringAtRest(spring) {
  /* Find out whether a spring is at rest. Returns a boolean. */
  return Math.round(spring.distance) === 0 && Math.abs(spring.speed) < 0.2;
}

/*
module.exports = {
  extend: extend,
  spring: spring,
  tickSpring: tickSpring,
  isSpringAtRest: isSpringAtRest,
};
*/<|endoftext|>


<commit_before>import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);

import ScheduledCommand from '../src/commandScheduling/scheduledCommand.js';

describe('Scheduled Command', () => {
  it('should be constructable', async() => {
    let command = new ScheduledCommand();
  });

  it('should be due when past ')
});

<commit_msg>Fix accidentally erased command handler tests.<commit_after>import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);

import Aggregate from '../src/aggregate.js';
import Command from '../src/command.js';
import Event from '../src/event.js';
import CommandHandler from '../src/aggregateCommandHandler.js';
import ValidationError from '../src/validationError.js';

describe('Command Handler', () => {
  it('should throw on a failed command validation', async() => {
    let handler = new CommandHandler(TestCommand_FailValidation);

    await expect(handler.handle({}, new TestAggregate())).to.be.rejectedWith('Failed Validation');
  });

  it('should throw on a failed aggregate validation', async() => {
    let handler = new CommandHandler(TestCommand);

    await expect(handler.handle({}, new TestAggregate_FailsValidation())).to.be.rejectedWith('Failed Aggregate Validation');
  });

  it('should apply events to aggregate', async() => {
    let handler = new CommandHandler(TestCommand);

    let aggregate = new TestAggregate();

    handler = new TestCommandHandler(TestCommand);
    await handler.handle(new TestCommand({ message: 'Successful test' }), aggregate);

    expect(aggregate.lastMessage).to.equal('Successful test');

  });
});

class TestCommandHandler extends CommandHandler {
  execute = async(command, aggregate) => [new TestEvent({ message: command.message })];
}

// TODO: build a test domain
class TestCommand_FailValidation extends Command {
  validate = async() => {
    throw new ValidationError(null, this, 'Failed Validation');
  }
}

class TestCommand extends Command {
  constructor(data = {}) {
    super(data);
    this.message = data.message;
  }

  validate = async() => true
}

class TestEvent extends Event {
  type = 'TestEvent'

  constructor(data = {}) {
    super(data);
    this.message = data.message;
  }
}

class TestAggregate extends Aggregate {
  constructor(id, events) {
    super(id, events);
  }
  update(event) {
    switch (event.type) {
    case 'TestEvent':
      {
        this.lastMessage = event.message;
        break;
      }
    }
  }
}

class TestAggregate_FailsValidation extends Aggregate {
  validate = command => {
    console.log('fail');
    throw new ValidationError(this, command, 'Failed Aggregate Validation');
  }
}
<|endoftext|>


<commit_before>exports.config = {
    baseUrl: 'http://localhost:8085/src',

    framework: 'jasmine',

    chromeDriver: "../../node_modules/webdriver-manager/selenium/chromedriver_2.31.exe",
    seleniumServerJar: "../../node_modules/webdriver-manager/selenium/selenium-server-standalone-3.5.2.jar",

    specs: [
        '../e2e/javascript-getting-started/example-js.spec.js',
        '../e2e/javascript-grid-tool-panel/toolPanelExample.spec.js'
    ]
};
<commit_msg>CI Work<commit_after>exports.config = {
    baseUrl: 'http://localhost:8085/src',

    framework: 'jasmine',

    chromeDriver: "../../node_modules/webdriver-manager/selenium/chromedriver_2.31.exe",
    seleniumServerJar: "../../node_modules/webdriver-manager/selenium/selenium-server-standalone-3.5.2.jar",

    specs: [
        '../e2e/javascript-getting-started/example-js.spec.js',
        '../e2e/javascript-grid-tool-panel/toolPanelExample.spec.js'
    ]
};
s<|endoftext|>


<commit_before>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>chore(sequelize orm db setup): fix style issues in models index file<commit_after>'use strict';

const fs        = require('fs');
const path      = require('path');
const Sequelize = require('sequelize');
const basename  = path.basename(module.filename);
const env       = process.env.NODE_ENV || 'development';
const config    = require(__dirname + '/../config/config.json')[env];
const db        = {};
let sequelize;

if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach((file) => {
    let model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>


<commit_before>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
require('sequelize-hierarchy')(Sequelize);
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var db        = {};

if (process.env.HEROKU_POSTGRESQL_PURPLE_URL) {
    // the application is executed on Heroku ... use the postgres database
    console.log('process.env.HEROKU_POSTGRESQL_BRONZE_URL: ', typeof process.env.HEROKU_POSTGRESQL_BRONZE_URL);
    sequelize = new Sequelize(process.env.HEROKU_POSTGRESQL_BRONZE_URL, {
      dialect:  'postgres',
      protocol: 'postgres'
    })
  } else {
  var config    = require(__dirname + '/../config/config.json')[env];
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>updated path<commit_after>'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
require('sequelize-hierarchy')(Sequelize);
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var db        = {};

if (process.env.HEROKU_POSTGRESQL_PURPLE_URL) {
    // the application is executed on Heroku ... use the postgres database
    console.log('process.env.HEROKU_POSTGRESQL_BRONZE_URL: ', typeof process.env.HEROKU_POSTGRESQL_PURPLE_URL);
    sequelize = new Sequelize(process.env.HEROKU_POSTGRESQL_PURPLE_URL, {
      dialect:  'postgres',
      protocol: 'postgres'
    })
  } else {
  var config    = require(__dirname + '/../config/config.json')[env];
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>


<commit_before>function ddg_spice_github_jobs(github) {
	var query = DDG.get_query();
	if(github.length > 0) {
		console.log(github);
		var out = '', more = '';
		out += '

';
		more += out;
		for(var i = 0;i < github.length;i++) {
			var bullet = '
' + github[i].title +
					' in ' + github[i].location + ' (' + github[i].company + ')
';
			if(i < 5) {
				out += bullet;
			} else {
				more += bullet;
			}
		}
		out += '
';
		more += '
';
		var items = [[],[]];
		items[0]['a'] = out;
		items[0]['h'] = query + ' (Github Jobs)';
		items[0]['s'] = 'Github';
		items[0]['u'] = 'https://jobs.github.com/';
		items[0]['f'] = 1;
		items[0]['force_big_header'] = true;

		if(github.length > 5) {
			items[1]['a'] = more;
			items[1]['t'] = 'More jobs';
			items[1]['s'] = 'Github';
			items[1]['u'] = 'https://jobs.github.com/';
			items[1]['f'] = 1;
		}
		nra(items);
	}
}<commit_msg>Minor tweak<commit_after>function ddg_spice_github_jobs(github) {
	if(github.length > 0) {
		var query = DDG.get_query();
		console.log(github);
		var out = '', more = '';
		out += '

';
		more += out;
		for(var i = 0;i < github.length;i++) {
			var bullet = '
' + github[i].title +
					' in ' + github[i].location + ' (' + github[i].company + ')
';
			if(i < 5) {
				out += bullet;
			} else {
				more += bullet;
			}
		}
		out += '
';
		more += '
';
		var items = [[],[]];
		items[0]['a'] = out;
		items[0]['h'] = query + ' (Github Jobs)';
		items[0]['s'] = 'Github';
		items[0]['u'] = 'https://jobs.github.com/';
		items[0]['f'] = 1;
		items[0]['force_big_header'] = true;

		if(github.length > 5) {
			items[1]['a'] = more;
			items[1]['t'] = 'More jobs';
			items[1]['s'] = 'Github';
			items[1]['u'] = 'https://jobs.github.com/';
			items[1]['f'] = 1;
		}
		nra(items);
	}
}<|endoftext|>


<commit_before>function ddg_spice_google_plus(google) {
	console.log(google);

	var out = '';
	if(google.kind === "plus#peopleFeed") {
		var tmp, div, div2, link, img, item;

		//Sometimes, the API returns a lot of results even if we
		//asked for only five. (e.g. coke)
		if(google['items'].length > 5) {
			google['items'].length = 5;
		}

		for (var i = 0;i < google['items'].length;i++) {
		    item = google.items[i];

		    div = d.createElement("div");
		    div2 = d.createElement("div");

		    link = d.createElement("a");
		    link.href = '/?q=google%2B+' + item.id;

		    if (item.displayName.length >= 10) {
				item.displayName = item.displayName.substring(0,8) + "...";
			}

		    img = d.createElement('img');
		    img.src = item.image.url;
		    YAHOO.util.Dom.setStyle(img, "margin", '0 auto 0 auto');
		    YAHOO.util.Dom.setStyle(div,'margin-bottom', '10px');
		    YAHOO.util.Dom.setStyle(div,'text-align', 'center');
		    link.appendChild(img);
		    div.appendChild(link);

		    link = d.createElement('a');
		    link.href = '/?q=google%2B+' + item.id;
		    link.innerHTML = item.displayName;
		    div.appendChild(link);
		    div.appendChild(d.createElement('br'));

		    YAHOO.util.Dom.addClass(div, 'inline highlight_zero_click1 highlight_zero_click_wrapper');
		    YAHOO.util.Dom.setStyle(div, "float", "left");
		    YAHOO.util.Dom.setStyle(div, "margin", "10px 20px 10px 0px");
		    YAHOO.util.Dom.setStyle(div, "padding", "5px");
		    YAHOO.util.Dom.setStyle(div, "max-width", "80px");

		    div2.appendChild(div);

		    out += div2.innerHTML;
		}

		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out;
		items[0]['h'] = '';
		items[0]['s'] = 'Google+';
		items[0]['f'] = 1;
		items[0]['u'] = 'http://plus.google.com';
		nra(items,1,1);
	} else if(google.kind === "plus#person") {
		//Check if the user has a tagline
		//Tagline or the about me page can be displayed here.
		if (google.aboutMe) {
			out += '
Introduction: ' + google.aboutMe + '
';
		}

		//Check for organizations
		if(google.organizations) {
			var orgs = '';
			for(var i=0;i < google.organizations.length && i < 2;i++) {
				orgs += google.organizations[i].name +
					(google.organizations[i].title ? ', ' + google.organizations[i].title : '')
					+ '
';
			}
			out += '
Organizations:
' + orgs + '
';
		}
		//Check if the person has links to show.
		if(google.urls) {
			var links = '';
			if(google.urls.length > 2) {
				google.urls.length -= 2;
				for(var i=0;i < google.urls.length && i < 2;i++) {
					links += '' + google.urls[i].value +
						'
';
				}
				out += '
Links:
' + links + '
';
			}
		}
		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		items[0]['h'] = google.displayName;
		items[0]['s'] = google.displayName;
		items[0]['u'] = google.url;
		items[0]['f'] = 1;
		items[0]['i'] =	google.image.url;
		nra(items);
	}
}
<commit_msg>Set a limit variable, added clear div, changed More at X<commit_after>function ddg_spice_google_plus(google) {
	console.log(google);

	var out = '';
	if(google.kind === "plus#peopleFeed") {
		var tmp, div, div2, link, img, item, limit;

		//Sometimes, the API returns a lot of results even if we
		//asked for only five. (e.g. coke)
		if(google['items'].length > 5) {
			limit = 5;
		} else {
			limit = google['items'].length;
		}

		for (var i = 0;i < limit;i++) {
		    item = google.items[i];

		    div = d.createElement("div");
		    div2 = d.createElement("div");

		    link = d.createElement("a");
		    link.href = '/?q=google%2B+' + item.id;

		    if (item.displayName.length >= 10) {
				item.displayName = item.displayName.substring(0,8) + "...";
			}

		    img = d.createElement('img');
		    img.src = item.image.url;
		    YAHOO.util.Dom.setStyle(img, "margin", '0 auto 0 auto');
		    YAHOO.util.Dom.setStyle(div,'margin-bottom', '10px');
		    YAHOO.util.Dom.setStyle(div,'text-align', 'center');
		    link.appendChild(img);
		    div.appendChild(link);

		    link = d.createElement('a');
		    link.href = '/?q=google%2B+' + item.id;
		    link.innerHTML = item.displayName;
		    div.appendChild(link);
		    div.appendChild(d.createElement('br'));

		    YAHOO.util.Dom.addClass(div, 'inline highlight_zero_click1 highlight_zero_click_wrapper');
		    YAHOO.util.Dom.setStyle(div, "float", "left");
		    YAHOO.util.Dom.setStyle(div, "margin", "10px 20px 10px 0px");
		    YAHOO.util.Dom.setStyle(div, "padding", "5px");
		    YAHOO.util.Dom.setStyle(div, "max-width", "80px");

		    div2.appendChild(div);

		    out += div2.innerHTML;
		}

		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		var query = DDG.get_query();
		items[0]['h'] = 'Google+ Users (' + query + ')';
		items[0]['s'] = 'Google+';
		items[0]['f'] = 1;
		items[0]['u'] = 'http://plus.google.com';
		nra(items,1,1);
	} else if(google.kind === "plus#person") {
		//Check if the user has a tagline
		//Tagline or the about me page can be displayed here.
		if (google.aboutMe) {
			out += '
Introduction: ' + google.aboutMe + '
';
		}

		//Check for organizations
		if(google.organizations) {
			var orgs = '';
			for(var i=0;i < google.organizations.length && i < 2;i++) {
				orgs += google.organizations[i].name +
					(google.organizations[i].title ? ', ' + google.organizations[i].title : '')
					+ '
';
			}
			out += '
Organizations:
' + orgs + '
';
		}
		//Check if the person has links to show.
		if(google.urls) {
			var links = '';
			if(google.urls.length > 2) {
				google.urls.length -= 2;
				for(var i=0;i < google.urls.length && i < 2;i++) {
					links += '' + google.urls[i].value +
						'
';
				}
				out += '
Links:
' + links + '
';
			}
		}
		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		items[0]['h'] = google.displayName;
		items[0]['s'] = 'Google+';
		items[0]['u'] = google.url;
		items[0]['f'] = 1;
		items[0]['i'] =	google.image.url;
		nra(items);
	}
}
<|endoftext|>


<commit_before>function ddg_spice_google_plus(google) {
	console.log(google);
	var out = '';
	if(google.kind === "plus#peopleFeed" && google.items.length > 0) {
		var tmp, div, div2, link, img, item, limit;

		//Sometimes, the API returns a lot of results even if we
		//asked for only five. (e.g. coke)
		if(google['items'].length > 5) {
			limit = 5;
		} else {
			limit = google['items'].length;
		}

		for (var i = 0;i < limit;i++) {
		    item = google.items[i];

		    div = d.createElement("div");
		    div2 = d.createElement("div");

		    link = d.createElement("a");
		    link.href = '/?q=google%2B+userid:' + item.id;

		 //    if (item.displayName.length >= 10) {
			// 	item.displayName = item.displayName.substring(0,8) + "...";
			// }

		    img = d.createElement('img');
		    img.src = item.image.url;
		    YAHOO.util.Dom.setStyle(img, "margin", '0 auto 0 auto');
		    YAHOO.util.Dom.setStyle(div,'margin-bottom', '10px');
		    YAHOO.util.Dom.setStyle(div,'text-align', 'center');
		    link.appendChild(img);
		    div.appendChild(link);

		    link = d.createElement('a');
		    link.href = '/?q=google%2B+userid:' + item.id;
		    link.innerHTML = item.displayName;
		    div.appendChild(link);
		    div.appendChild(d.createElement('br'));

		    YAHOO.util.Dom.addClass(div, 'inline highlight_zero_click1 highlight_zero_click_wrapper');
		    YAHOO.util.Dom.setStyle(div, "float", "left");
		    YAHOO.util.Dom.setStyle(div, "margin", "10px 20px 10px 0px");
		    YAHOO.util.Dom.setStyle(div, "padding", "5px");
		    YAHOO.util.Dom.setStyle(div, "max-width", "80px");

		    div2.appendChild(div);

		    out += div2.innerHTML;
		}

		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		var query = DDG.get_query(); //"google+ this is a test";
		var query = query.replace(/\s*(google\+|google\splus|g\+|gplus|\+)\s*/, "");
		items[0]['h'] = 'Google+ Users (' + query + ')';
		items[0]['s'] = 'Google+';
		items[0]['f'] = 1;
		items[0]['u'] = 'http://plus.google.com/s/' + query;
		nra(items,1,1);
	} else if(google.kind === "plus#person") {
		//Check if the user has a tagline
		//Tagline or the about me page can be displayed here.
		if (google.tagline) {
			out += '
Introduction:  ' + google.tagline + '
';
		} else if(google.aboutMe) {
			out += '
Introduction:  ' + google.aboutMe.substring(0, 200) + '...
';
		}

		//Check for organizations
		if(google.organizations) {
			var orgs = '';
			for(var i=0;i < google.organizations.length && i < 2;i++) {
				orgs += google.organizations[i].name +
					(google.organizations[i].title ? ' (' + google.organizations[i].title + ')' : '');
				if(i !== google.organizations.length-1) {
					orgs += ', ';
				}
			}
			out += '
Organizations: ' + orgs + '
';
		}
		//Check if the person has links to show.
		if(google.urls) {
			var links = '';
			if(google.urls.length > 2) {
				google.urls.length -= 2;
				for(var i=0;i < google.urls.length && i < 2;i++) {
					links += '' + google.urls[i].value
						+ '';
					if(i !== google.urls.length-1 && i !== 1) {
						links += ', ';
					}
				}
				out += '
Links: ' + links + '
';
			}
		}
		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		items[0]['h'] = google.displayName;
		items[0]['s'] = 'Google+';
		items[0]['u'] = google.url;
		items[0]['f'] = 1;
		items[0]['i'] =	google.image.url.substring(0, google.image.url.length-6);
		nra(items);
	}
}
<commit_msg>Shorten links<commit_after>function ddg_spice_google_plus(google) {
	console.log(google);
	var out = '';
	if(google.kind === "plus#peopleFeed" && google.items.length > 0) {
		var tmp, div, div2, link, img, item, limit;

		//Sometimes, the API returns a lot of results even if we
		//asked for only five. (e.g. coke)
		if(google['items'].length > 5) {
			limit = 5;
		} else {
			limit = google['items'].length;
		}

		for (var i = 0;i < limit;i++) {
		    item = google.items[i];

		    div = d.createElement("div");
		    div2 = d.createElement("div");

		    link = d.createElement("a");
		    link.href = '/?q=google%2B+userid:' + item.id;

		 //    if (item.displayName.length >= 10) {
			// 	item.displayName = item.displayName.substring(0,8) + "...";
			// }

		    img = d.createElement('img');
		    img.src = item.image.url;
		    YAHOO.util.Dom.setStyle(img, "margin", '0 auto 0 auto');
		    YAHOO.util.Dom.setStyle(div,'margin-bottom', '10px');
		    YAHOO.util.Dom.setStyle(div,'text-align', 'center');
		    link.appendChild(img);
		    div.appendChild(link);

		    link = d.createElement('a');
		    link.href = '/?q=google%2B+userid:' + item.id;
		    link.innerHTML = item.displayName;
		    div.appendChild(link);
		    div.appendChild(d.createElement('br'));

		    YAHOO.util.Dom.addClass(div, 'inline highlight_zero_click1 highlight_zero_click_wrapper');
		    YAHOO.util.Dom.setStyle(div, "float", "left");
		    YAHOO.util.Dom.setStyle(div, "margin", "10px 20px 10px 0px");
		    YAHOO.util.Dom.setStyle(div, "padding", "5px");
		    YAHOO.util.Dom.setStyle(div, "max-width", "80px");

		    div2.appendChild(div);

		    out += div2.innerHTML;
		}

		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		var query = DDG.get_query(); //"google+ this is a test";
		var query = query.replace(/\s*(google\+|google\splus|g\+|gplus|\+)\s*/, "");
		items[0]['h'] = 'Google+ Users (' + query + ')';
		items[0]['s'] = 'Google+';
		items[0]['f'] = 1;
		items[0]['u'] = 'http://plus.google.com/s/' + query;
		nra(items,1,1);
	} else if(google.kind === "plus#person") {
		//Check if the user has a tagline
		//Tagline or the about me page can be displayed here.
		if (google.tagline) {
			out += '
Introduction:  ' + google.tagline + '
';
		} else if(google.aboutMe) {
			out += '
Introduction:  ' + google.aboutMe.substring(0, 200) + '...
';
		}

		//Check for organizations
		if(google.organizations) {
			var orgs = '';
			for(var i=0;i < google.organizations.length && i < 2;i++) {
				orgs += google.organizations[i].name +
					(google.organizations[i].title ? ' (' + google.organizations[i].title + ')' : '');
				if(i !== google.organizations.length-1) {
					orgs += ', ';
				}
			}
			out += '
Organizations: ' + orgs + '
';
		}
		//Check if the person has links to show.
		if(google.urls) {
			var links = '';
			if(google.urls.length > 2) {
				google.urls.length -= 2;
				for(var i=0;i < google.urls.length;i++) {
					var re = /(?:https?:\/\/)?(?:www\.)?([^\.]+).*/;
					var string =  google.urls[i].value;
					string = string.replace(re, "$1");
					string = string.charAt(0).toUpperCase() + string.slice(1)
					links += '' + string
						+ '';
					if(i !== google.urls.length-1) {
						links += ', ';
					}
				}
				out += '
Links: ' + links + '
';
			}
		}
		var items = new Array();
		items[0] = new Array();
		items[0]['a'] = out += '

';
		items[0]['h'] = google.displayName;
		items[0]['s'] = 'Google+';
		items[0]['u'] = google.url;
		items[0]['f'] = 1;
		items[0]['i'] =	google.image.url.substring(0, google.image.url.length-6);
		nra(items);
	}
}
<|endoftext|>