<commit_before>;(function(undefined) {
  'use strict';

  if (typeof sigma === 'undefined')
    throw 'sigma is not declared';

  if (typeof conrad === 'undefined')
    throw 'conrad is not declared';

  // Initialize packages:
  sigma.utils.pkg('sigma.renderers');

  /**
   * This function is the constructor of the canvas sigma's renderer.
   *
   * @param  {sigma.classes.graph}            graph    The graph to render.
   * @param  {sigma.classes.camera}           camera   The camera.
   * @param  {configurable}           settings The sigma instance settings
   *                                           function.
   * @param  {object}                 object   The options object.
   * @return {sigma.renderers.canvas}          The renderer instance.
   */
  sigma.renderers.canvas = function(graph, camera, settings, options) {
    if (typeof options !== 'object')
      throw 'sigma.renderers.canvas: Wrong arguments.';

    if (!(options.container instanceof HTMLElement))
      throw 'Container not found.';

    var k,
        i,
        l,
        a,
        fn,
        self = this;

    sigma.classes.dispatcher.extend(this);

    // Initialize main attributes:
    Object.defineProperty(this, 'conradId', {
      value: sigma.utils.id()
    });
    this.graph = graph;
    this.camera = camera;
    this.contexts = {};
    this.domElements = {};
    this.options = options;
    this.container = this.options.container;
    this.settings = (
        typeof options.settings === 'object' &&
        options.settings
      ) ?
        settings.embedObjects(options.settings) :
        settings;

    // Node indexes:
    this.nodesOnScreen = [];
    this.edgesOnScreen = [];

    // Conrad related attributes:
    this.jobs = {};

    // Find the prefix:
    this.options.prefix = 'renderer' + this.conradId + ':';

    // Initialize the DOM elements:
    if (
      !this.settings('batchEdgesDrawing')
    ) {
      this.initDOM('canvas', 'scene');
      this.contexts.edges = this.contexts.scene;
      this.contexts.nodes = this.contexts.scene;
      this.contexts.labels = this.contexts.scene;
    } else {
      this.initDOM('canvas', 'edges');
      this.initDOM('canvas', 'scene');
      this.contexts.nodes = this.contexts.scene;
      this.contexts.labels = this.contexts.scene;
    }

    this.initDOM('canvas', 'mouse');
    this.contexts.hover = this.contexts.mouse;

    // Initialize captors:
    this.captors = [];
    a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch];
    for (i = 0, l = a.length; i < l; i++) {
      fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]];
      this.captors.push(
        new fn(
          this.domElements.mouse,
          this.camera,
          this.settings
        )
      );
    }

    // Bind resize:
    window.addEventListener('resize', function() {
      self.resize();
    });

    // Deal with sigma events:
    sigma.misc.bindEvents.call(this, this.options.prefix);
    sigma.misc.drawHovers.call(this, this.options.prefix);

    this.resize(false);
  };

  /**
   * This method renders the graph on the canvases.
   *
   * @param  {?object}                options Eventually an object of options.
   * @return {sigma.renderers.canvas}         Returns the instance itself.
   */
  sigma.renderers.canvas.prototype.render = function(options) {
    options = options || {};

    var a,
        i,
        k,
        l,
        o,
        id,
        end,
        job,
        start,
        edges,
        renderers,
        rendererType,
        batchSize,
        index = {},
        graph = this.graph,
        nodes = this.graph.nodes,
        prefix = this.options.prefix || '',
        drawEdges = this.settings(options, 'drawEdges'),
        drawNodes = this.settings(options, 'drawNodes'),
        drawLabels = this.settings(options, 'drawLabels'),
        embedSettings = this.settings.embedObjects(options, {
          prefix: this.options.prefix
        });

    // Check the 'hideEdgesOnMove' setting:
    if (this.settings(options, 'hideEdgesOnMove'))
      if (this.camera.isAnimated || this.camera.isMoving)
        drawEdges = false;

    // Apply the camera's view:
    this.camera.applyView(
      undefined,
      this.options.prefix,
      {
        width: this.width,
        height: this.height
      }
    );

    // Clear canvases:
    this.clear();

    // Kill running jobs:
    for (k in this.jobs)
      if (conrad.hasJob(k))
        conrad.killJob(k);

    // Find which nodes are on screen:
    this.edgesOnScreen = [];
    this.nodesOnScreen = this.camera.quadtree.area(
      this.camera.getRectangle(this.width, this.height)
    );

    for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
      index[a[i].id] = a[i];

    // Draw edges:
    // - If settings('batchEdgesDrawing') is true, the edges are displayed per
    //   batches. If not, they are drawn in one frame.
    if (drawEdges) {
      // First, let's identify which edges to draw. To do this, we just keep
      // every edges that have at least one extremity displayed according to
      // the quadtree and the "hidden" attribute. We also do not keep hidden
      // edges.
      for (a = graph.edges(), i = 0, l = a.length; i < l; i++) {
        o = a[i];
        if (
          (index[o.source] || index[o.target]) &&
          (!o.hidden && !nodes(o.source).hidden && !nodes(o.target).hidden)
        )
          this.edgesOnScreen.push(o);
      }

      // If the "batchEdgesDrawing" settings is true, edges are batched:
      if (this.settings(options, 'batchEdgesDrawing')) {
        id = 'edges_' + this.conradId;
        batchSize = embedSettings('canvasEdgesBatchSize');

        edges = this.edgesOnScreen;
        l = edges.length;

        start = 0;
        end = Math.min(edges.length, start + batchSize);

        job = function() {
          renderers = sigma.canvas.edges;
          for (i = start; i < end; i++) {
            o = edges[i];
            rendererType = renderers[o.type] || renderers.def;
            (rendererType[o.head] || rendererType.def)(
              o,
              graph.nodes(o.source),
              graph.nodes(o.target),
              this.contexts.edges,
              embedSettings
            );
          }

          // Catch job's end:
          if (end === edges.length) {
            delete this.jobs[id];
            return false;
          }

          start = end + 1;
          end = Math.min(edges.length, start + batchSize);
          return true;
        };

        this.jobs[id] = job;
        conrad.addJob(id, job.bind(this));

      // If not, they are drawn in one frame:
      } else {
        renderers = sigma.canvas.edges;
        for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) {
          o = a[i];
          rendererType = renderers[o.type] || renderers.def;
          (rendererType[o.head] || rendererType.def)(
            o,
            graph.nodes(o.source),
            graph.nodes(o.target),
            this.contexts.edges,
            embedSettings
          );
        }
      }
    }

    // Draw nodes:
    // - No batching
    if (drawNodes) {
      renderers = sigma.canvas.nodes;
      for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
        if (!a[i].hidden)
          (renderers[o.type] || renderers.def)(
            a[i],
            this.contexts.nodes,
            embedSettings
          );
    }

    // Draw labels:
    // - No batching
    if (drawLabels) {
      renderers = sigma.canvas.labels;
      for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
        if (!a[i].hidden)
          (renderers[a[i].type] || renderers.def)(
            a[i],
            this.contexts.labels,
            embedSettings
          );
    }

    this.dispatchEvent('render');

    return this;
  };

  /**
   * This method creates a DOM element of the specified type, switches its
   * position to "absolute", references it to the domElements attribute, and
   * finally appends it to the container.
   *
   * @param  {string} tag The label tag.
   * @param  {string} id  The id of the element (to store it in "domElements").
   */
  sigma.renderers.canvas.prototype.initDOM = function(tag, id) {
    var dom = document.createElement(tag);

    dom.style.position = 'absolute';
    dom.setAttribute('class', 'sigma-' + id);

    this.domElements[id] = dom;
    this.container.appendChild(dom);

    if (tag.toLowerCase() === 'canvas')
      this.contexts[id] = dom.getContext('2d');
  };

  /**
   * This method resizes each DOM elements in the container and stores the new
   * dimensions. Then, it renders the graph.
   *
   * @param  {?number}                width  The new width of the container.
   * @param  {?number}                height The new height of the container.
   * @return {sigma.renderers.canvas}        Returns the instance itself.
   */
  sigma.renderers.canvas.prototype.resize = function(w, h) {
    var k,
        oldWidth = this.width,
        oldHeight = this.height,
        pixelRatio = 1;
        // TODO:
        // *****
        // This pixelRatio is the solution to display with the good definition
        // on canvases on Retina displays (ie oversampling). Unfortunately, it
        // has a huge performance cost...
        //  > pixelRatio = window.devicePixelRatio || 1;

    if (w !== undefined && h !== undefined) {
      this.width = w;
      this.height = h;
    } else {
      this.width = this.container.offsetWidth;
      this.height = this.container.offsetHeight;

      w = this.width;
      h = this.height;
    }

    if (oldWidth !== this.width || oldHeight !== this.height) {
      for (k in this.domElements) {
        this.domElements[k].style.width = w + 'px';
        this.domElements[k].style.height = h + 'px';

        if (this.domElements[k].tagName.toLowerCase() === 'canvas') {
          this.domElements[k].setAttribute('width', (w * pixelRatio) + 'px');
          this.domElements[k].setAttribute('height', (h * pixelRatio) + 'px');

          if (pixelRatio !== 1)
            this.contexts[k].scale(pixelRatio, pixelRatio);
        }
      }
    }

    return this;
  };

  /**
   * This method clears each canvas.
   *
   * @return {sigma.renderers.canvas} Returns the instance itself.
   */
  sigma.renderers.canvas.prototype.clear = function() {
    var k;

    for (k in this.domElements)
      if (this.domElements[k].tagName === 'CANVAS')
        this.domElements[k].width = this.domElements[k].width;

    return this;
  };

  /**
   * The labels, nodes and edges renderers are stored in the three following
   * objects. When an element is drawn, its type will be checked and if a
   * renderer with the same name exists, it will be used. If not found, the
   * default renderer will be used instead.
   *
   * They are stored in different files, in the "./canvas" folder.
   */
  sigma.utils.pkg('sigma.canvas.nodes');
  sigma.utils.pkg('sigma.canvas.edges');
  sigma.utils.pkg('sigma.canvas.labels');
}).call(this);
<commit_msg>Fix issue with incorrect node type renderer.<commit_after>;(function(undefined) {
  'use strict';

  if (typeof sigma === 'undefined')
    throw 'sigma is not declared';

  if (typeof conrad === 'undefined')
    throw 'conrad is not declared';

  // Initialize packages:
  sigma.utils.pkg('sigma.renderers');

  /**
   * This function is the constructor of the canvas sigma's renderer.
   *
   * @param  {sigma.classes.graph}            graph    The graph to render.
   * @param  {sigma.classes.camera}           camera   The camera.
   * @param  {configurable}           settings The sigma instance settings
   *                                           function.
   * @param  {object}                 object   The options object.
   * @return {sigma.renderers.canvas}          The renderer instance.
   */
  sigma.renderers.canvas = function(graph, camera, settings, options) {
    if (typeof options !== 'object')
      throw 'sigma.renderers.canvas: Wrong arguments.';

    if (!(options.container instanceof HTMLElement))
      throw 'Container not found.';

    var k,
        i,
        l,
        a,
        fn,
        self = this;

    sigma.classes.dispatcher.extend(this);

    // Initialize main attributes:
    Object.defineProperty(this, 'conradId', {
      value: sigma.utils.id()
    });
    this.graph = graph;
    this.camera = camera;
    this.contexts = {};
    this.domElements = {};
    this.options = options;
    this.container = this.options.container;
    this.settings = (
        typeof options.settings === 'object' &&
        options.settings
      ) ?
        settings.embedObjects(options.settings) :
        settings;

    // Node indexes:
    this.nodesOnScreen = [];
    this.edgesOnScreen = [];

    // Conrad related attributes:
    this.jobs = {};

    // Find the prefix:
    this.options.prefix = 'renderer' + this.conradId + ':';

    // Initialize the DOM elements:
    if (
      !this.settings('batchEdgesDrawing')
    ) {
      this.initDOM('canvas', 'scene');
      this.contexts.edges = this.contexts.scene;
      this.contexts.nodes = this.contexts.scene;
      this.contexts.labels = this.contexts.scene;
    } else {
      this.initDOM('canvas', 'edges');
      this.initDOM('canvas', 'scene');
      this.contexts.nodes = this.contexts.scene;
      this.contexts.labels = this.contexts.scene;
    }

    this.initDOM('canvas', 'mouse');
    this.contexts.hover = this.contexts.mouse;

    // Initialize captors:
    this.captors = [];
    a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch];
    for (i = 0, l = a.length; i < l; i++) {
      fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]];
      this.captors.push(
        new fn(
          this.domElements.mouse,
          this.camera,
          this.settings
        )
      );
    }

    // Bind resize:
    window.addEventListener('resize', function() {
      self.resize();
    });

    // Deal with sigma events:
    sigma.misc.bindEvents.call(this, this.options.prefix);
    sigma.misc.drawHovers.call(this, this.options.prefix);

    this.resize(false);
  };

  /**
   * This method renders the graph on the canvases.
   *
   * @param  {?object}                options Eventually an object of options.
   * @return {sigma.renderers.canvas}         Returns the instance itself.
   */
  sigma.renderers.canvas.prototype.render = function(options) {
    options = options || {};

    var a,
        i,
        k,
        l,
        o,
        id,
        end,
        job,
        start,
        edges,
        renderers,
        rendererType,
        batchSize,
        index = {},
        graph = this.graph,
        nodes = this.graph.nodes,
        prefix = this.options.prefix || '',
        drawEdges = this.settings(options, 'drawEdges'),
        drawNodes = this.settings(options, 'drawNodes'),
        drawLabels = this.settings(options, 'drawLabels'),
        embedSettings = this.settings.embedObjects(options, {
          prefix: this.options.prefix
        });

    // Check the 'hideEdgesOnMove' setting:
    if (this.settings(options, 'hideEdgesOnMove'))
      if (this.camera.isAnimated || this.camera.isMoving)
        drawEdges = false;

    // Apply the camera's view:
    this.camera.applyView(
      undefined,
      this.options.prefix,
      {
        width: this.width,
        height: this.height
      }
    );

    // Clear canvases:
    this.clear();

    // Kill running jobs:
    for (k in this.jobs)
      if (conrad.hasJob(k))
        conrad.killJob(k);

    // Find which nodes are on screen:
    this.edgesOnScreen = [];
    this.nodesOnScreen = this.camera.quadtree.area(
      this.camera.getRectangle(this.width, this.height)
    );

    for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
      index[a[i].id] = a[i];

    // Draw edges:
    // - If settings('batchEdgesDrawing') is true, the edges are displayed per
    //   batches. If not, they are drawn in one frame.
    if (drawEdges) {
      // First, let's identify which edges to draw. To do this, we just keep
      // every edges that have at least one extremity displayed according to
      // the quadtree and the "hidden" attribute. We also do not keep hidden
      // edges.
      for (a = graph.edges(), i = 0, l = a.length; i < l; i++) {
        o = a[i];
        if (
          (index[o.source] || index[o.target]) &&
          (!o.hidden && !nodes(o.source).hidden && !nodes(o.target).hidden)
        )
          this.edgesOnScreen.push(o);
      }

      // If the "batchEdgesDrawing" settings is true, edges are batched:
      if (this.settings(options, 'batchEdgesDrawing')) {
        id = 'edges_' + this.conradId;
        batchSize = embedSettings('canvasEdgesBatchSize');

        edges = this.edgesOnScreen;
        l = edges.length;

        start = 0;
        end = Math.min(edges.length, start + batchSize);

        job = function() {
          renderers = sigma.canvas.edges;
          for (i = start; i < end; i++) {
            o = edges[i];
            rendererType = renderers[o.type] || renderers.def;
            (rendererType[o.head] || rendererType.def)(
              o,
              graph.nodes(o.source),
              graph.nodes(o.target),
              this.contexts.edges,
              embedSettings
            );
          }

          // Catch job's end:
          if (end === edges.length) {
            delete this.jobs[id];
            return false;
          }

          start = end + 1;
          end = Math.min(edges.length, start + batchSize);
          return true;
        };

        this.jobs[id] = job;
        conrad.addJob(id, job.bind(this));

      // If not, they are drawn in one frame:
      } else {
        renderers = sigma.canvas.edges;
        for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) {
          o = a[i];
          rendererType = renderers[o.type] || renderers.def;
          (rendererType[o.head] || rendererType.def)(
            o,
            graph.nodes(o.source),
            graph.nodes(o.target),
            this.contexts.edges,
            embedSettings
          );
        }
      }
    }

    // Draw nodes:
    // - No batching
    if (drawNodes) {
      renderers = sigma.canvas.nodes;
      for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
        if (!a[i].hidden)
          (renderers[a[i].type] || renderers.def)(
            a[i],
            this.contexts.nodes,
            embedSettings
          );
    }

    // Draw labels:
    // - No batching
    if (drawLabels) {
      renderers = sigma.canvas.labels;
      for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++)
        if (!a[i].hidden)
          (renderers[a[i].type] || renderers.def)(
            a[i],
            this.contexts.labels,
            embedSettings
          );
    }

    this.dispatchEvent('render');

    return this;
  };

  /**
   * This method creates a DOM element of the specified type, switches its
   * position to "absolute", references it to the domElements attribute, and
   * finally appends it to the container.
   *
   * @param  {string} tag The label tag.
   * @param  {string} id  The id of the element (to store it in "domElements").
   */
  sigma.renderers.canvas.prototype.initDOM = function(tag, id) {
    var dom = document.createElement(tag);

    dom.style.position = 'absolute';
    dom.setAttribute('class', 'sigma-' + id);

    this.domElements[id] = dom;
    this.container.appendChild(dom);

    if (tag.toLowerCase() === 'canvas')
      this.contexts[id] = dom.getContext('2d');
  };

  /**
   * This method resizes each DOM elements in the container and stores the new
   * dimensions. Then, it renders the graph.
   *
   * @param  {?number}                width  The new width of the container.
   * @param  {?number}                height The new height of the container.
   * @return {sigma.renderers.canvas}        Returns the instance itself.
   */
  sigma.renderers.canvas.prototype.resize = function(w, h) {
    var k,
        oldWidth = this.width,
        oldHeight = this.height,
        pixelRatio = 1;
        // TODO:
        // *****
        // This pixelRatio is the solution to display with the good definition
        // on canvases on Retina displays (ie oversampling). Unfortunately, it
        // has a huge performance cost...
        //  > pixelRatio = window.devicePixelRatio || 1;

    if (w !== undefined && h !== undefined) {
      this.width = w;
      this.height = h;
    } else {
      this.width = this.container.offsetWidth;
      this.height = this.container.offsetHeight;

      w = this.width;
      h = this.height;
    }

    if (oldWidth !== this.width || oldHeight !== this.height) {
      for (k in this.domElements) {
        this.domElements[k].style.width = w + 'px';
        this.domElements[k].style.height = h + 'px';

        if (this.domElements[k].tagName.toLowerCase() === 'canvas') {
          this.domElements[k].setAttribute('width', (w * pixelRatio) + 'px');
          this.domElements[k].setAttribute('height', (h * pixelRatio) + 'px');

          if (pixelRatio !== 1)
            this.contexts[k].scale(pixelRatio, pixelRatio);
        }
      }
    }

    return this;
  };

  /**
   * This method clears each canvas.
   *
   * @return {sigma.renderers.canvas} Returns the instance itself.
   */
  sigma.renderers.canvas.prototype.clear = function() {
    var k;

    for (k in this.domElements)
      if (this.domElements[k].tagName === 'CANVAS')
        this.domElements[k].width = this.domElements[k].width;

    return this;
  };

  /**
   * The labels, nodes and edges renderers are stored in the three following
   * objects. When an element is drawn, its type will be checked and if a
   * renderer with the same name exists, it will be used. If not found, the
   * default renderer will be used instead.
   *
   * They are stored in different files, in the "./canvas" folder.
   */
  sigma.utils.pkg('sigma.canvas.nodes');
  sigma.utils.pkg('sigma.canvas.edges');
  sigma.utils.pkg('sigma.canvas.labels');
}).call(this);
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Voteopt = mongoose.model('Voteopt'),
  Polltag = mongoose.model('Polltag'),
  Polluser = mongoose.model('Polluser'),
  Like = mongoose.model('Like'),
  errorHandler = require(path.resolve(
    './modules/core/server/controllers/errors.server.controller'
  )),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll
    .save()
    .then(_poll => {
      poll = _poll;
      tags.forEach(tag => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach(opt => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      var _polluser = new Polluser({ poll: poll._id, user: req.user._id });
      return _polluser.save();
    }, handleError)
    .then(_polluser => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner =
    req.user &&
    poll.user &&
    poll.user._id.toString() === req.user._id.toString();
  poll.canEdit =
    req.user &&
    req.user.roles &&
    req.user.roles.length &&
    req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll
    .save()
    .then(_poll => {
      poll = _poll;
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach(tag => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach(opt => {
        if (opt._id) {
          var _opt = new Opt(opt);
          promises.push(() => {
            Opt.findById(opt._id).exec()
            .then(_opt => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(_opts => {
      console.log('result', _opts);
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll
    .remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find()
    .sort('-created')
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .exec(function(err, polls) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(polls);
      }
    });
};

/**
 * List of Offset
 */
exports.findPolls = function(req, res) {
  var page = req.params.page || 0;
  Poll.find()
    .sort('-created')
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .skip(10 * page)
    .limit(10)
    .exec(function(err, polls) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(polls);
      }
    });
};

/**
 * List of Hot
 */
exports.findHotPolls = function(req, res) {
  var page = req.params.page || 0;
  Poll.find()
    .sort('-likeCnt')
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .skip(10 * page)
    .limit(10)
    .exec(function(err, polls) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(polls);
      }
    });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id)
    .populate('user', 'displayName')
    .exec(function(err, opts) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(opts);
      }
    });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  var page = req.params.page || 0;
  Poll.findCmts(req.poll._id)
    .sort('-created')
    .populate('user', 'displayName profileImageURL')
    .skip(10 * page)
    .limit(10)
    .exec(function(err, cmts) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(cmts);
      }
    });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip =
      req.headers['X-Forwarded-For'] ||
      req.headers['x-forwarded-for'] ||
      req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {}, ids;
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      ids = _.pluck(_votes, '_id');
      Voteopt.find({ vote: { $in: ids } }).exec(function(err, opts) {
        if (err) {
          handleError(err);
        } else {
          rs.voteopts = opts;
          res.jsonp(rs);
        }
      });
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Get Like of user on this poll
 */
exports.findPollLike = function(req, res) {
  var condition = { poll: req.poll._id, user: req.user._id };
  Like.findOne(condition).exec(function(err, like) {
    if (err) {
      handleError(err);
    } else {
      res.jsonp(like);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Find pollusers
 */
exports.findPolluser = function(req, res) {
  Polluser.findOne({
    poll: req.poll._id,
    user: req.user._id
  }).exec((err, _polluser) => {
    if (err) {
      handleError(err);
    } else {
      res.jsonp(_polluser);
    }
  });
  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id)
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .exec(function(err, poll) {
      if (err) {
        return next(err);
      } else if (!poll) {
        return res.status(404).send({
          message: 'No Poll with that identifier has been found'
        });
      }
      req.poll = poll;
      next();
    });
};
<commit_msg>Commited from lenh at Thu, Jun 29, 2017  7:01:22 PM<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Voteopt = mongoose.model('Voteopt'),
  Polltag = mongoose.model('Polltag'),
  Polluser = mongoose.model('Polluser'),
  Like = mongoose.model('Like'),
  errorHandler = require(path.resolve(
    './modules/core/server/controllers/errors.server.controller'
  )),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll
    .save()
    .then(_poll => {
      poll = _poll;
      tags.forEach(tag => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach(opt => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      var _polluser = new Polluser({ poll: poll._id, user: req.user._id });
      return _polluser.save();
    }, handleError)
    .then(_polluser => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner =
    req.user &&
    poll.user &&
    poll.user._id.toString() === req.user._id.toString();
  poll.canEdit =
    req.user &&
    req.user.roles &&
    req.user.roles.length &&
    req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll
    .save()
    .then(_poll => {
      poll = _poll;
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach(tag => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach(opt => {
        if (opt._id) {
          var _opt = new Opt(opt);
          promises.push(() => {
            Opt.findById(opt._id).exec()
            .then(_opt => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(_opts => {
      _opts.forEach(obj => {
        console.log('result', obj);
      });
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll
    .remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find()
    .sort('-created')
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .exec(function(err, polls) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(polls);
      }
    });
};

/**
 * List of Offset
 */
exports.findPolls = function(req, res) {
  var page = req.params.page || 0;
  Poll.find()
    .sort('-created')
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .skip(10 * page)
    .limit(10)
    .exec(function(err, polls) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(polls);
      }
    });
};

/**
 * List of Hot
 */
exports.findHotPolls = function(req, res) {
  var page = req.params.page || 0;
  Poll.find()
    .sort('-likeCnt')
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .skip(10 * page)
    .limit(10)
    .exec(function(err, polls) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(polls);
      }
    });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id)
    .populate('user', 'displayName')
    .exec(function(err, opts) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(opts);
      }
    });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  var page = req.params.page || 0;
  Poll.findCmts(req.poll._id)
    .sort('-created')
    .populate('user', 'displayName profileImageURL')
    .skip(10 * page)
    .limit(10)
    .exec(function(err, cmts) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.jsonp(cmts);
      }
    });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip =
      req.headers['X-Forwarded-For'] ||
      req.headers['x-forwarded-for'] ||
      req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {}, ids;
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      ids = _.pluck(_votes, '_id');
      Voteopt.find({ vote: { $in: ids } }).exec(function(err, opts) {
        if (err) {
          handleError(err);
        } else {
          rs.voteopts = opts;
          res.jsonp(rs);
        }
      });
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Get Like of user on this poll
 */
exports.findPollLike = function(req, res) {
  var condition = { poll: req.poll._id, user: req.user._id };
  Like.findOne(condition).exec(function(err, like) {
    if (err) {
      handleError(err);
    } else {
      res.jsonp(like);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Find pollusers
 */
exports.findPolluser = function(req, res) {
  Polluser.findOne({
    poll: req.poll._id,
    user: req.user._id
  }).exec((err, _polluser) => {
    if (err) {
      handleError(err);
    } else {
      res.jsonp(_polluser);
    }
  });
  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id)
    .populate('category', 'name icon')
    .populate('user', 'displayName profileImageURL')
    .exec(function(err, poll) {
      if (err) {
        return next(err);
      } else if (!poll) {
        return res.status(404).send({
          message: 'No Poll with that identifier has been found'
        });
      }
      req.poll = poll;
      next();
    });
};
<|endoftext|>


<commit_before>function getHost() {
 var port = window.location.port;
 return window.location.protocol + "//" + window.location.hostname + (port? ":" + port: "") ;
}

var urlShaclex = getHost();

console.log("urlShaclex: " + urlShaclex);

var codeMirrorData ;
var codeMirrorSchema ;
var codeMirrorShapeMap ;
// var codeMirrorNodes = new Array();
// var codeMirrorShapes = new Array();
// var inputRows = 0;
/*
function newCodeMirrorNode(n) {
 var nodeId = document.getElementById("node" + n);
 if (nodeId) {
  var codeMirrorNode = CodeMirror.fromTextArea(nodeId, {
  lineNumbers: false,
   mode: "turtle",
   scrollbarStyle: "null",
   tabindex: 2*n,
   height: 1,
   extraKeys: { Tab: false }
  });
  codeMirrorNode.on("beforeChange", noNewLine);
  codeMirrorNode.setSize(null,"1.5em");
  codeMirrorNodes.push(codeMirrorNode);
 } else {
   console.log("Not found node" + n);
 }
}

function newCodeMirrorShape(n) {
 var shapeId = document.getElementById("shape" + n);
 if (shapeId) {
  var codeMirrorShape = CodeMirror.fromTextArea(shapeId, {
   lineNumbers: false,
   mode: "turtle",
   scrollbarStyle: "null",
   tabindex: 2*n+1,
   height: 1,
   extraKeys: { Tab: false }
  });
 codeMirrorShape.on("beforeChange", noNewLine);
 codeMirrorShape.setSize(null,"1.5em");
 console.log("Current codeMirrorShapes: " + codeMirrorShapes.length);
 codeMirrorShapes.push(codeMirrorShape);
 } else {
   console.log("Not found shape" + n);
 }
}

function getInputRows() {
 return $("#rowsCounter").data("value");
}

function setInputRows(n) {
 $("#rowsCounter").data("value",n);
}

function incrementInputRows() {
 inputRows = getInputRows();
 inputRows++
 setInputRows(inputRows);
 return inputRows;
}

function addNodeShapeEntry() {
  inputRows = incrementInputRows();
  var nodeEntry =  "
Node<textarea placeholder='Node' id='node" + inputRows + "' placeholder='Node...'></textarea>
"
  var shapeEntry = "
Shape<textarea placeholder='Shape' id='shape" + inputRows + "' placeholder='Shape...'></textarea>

"
  console.log("Setting styles... on #nodeDiv" + inputRows);
  $("#nodeDiv"+inputRows).css("float","left");
  $("#nodeDiv"+inputRows).css("width","30%");
  $("#shapeDiv"+inputRows).css("float","right");
  $("#shapeDiv"+inputRows).css("width","30%");
  $("#nodeShapeContainer").append(nodeEntry);
  $("#nodeShapeContainer").append(shapeEntry);
  $("#nodeShapeContainer").append("
");
  newCodeMirrorNode(inputRows);
  newCodeMirrorShape(inputRows);
  console.log("Added row " + inputRows);
}

function removeNodeShapeEntry() {
  $inputRows = getInputRows();
  switch (inputRows)  {
   case 0: console.log("Cleaning entries when 0 input rows");
           break;
   case 1: codeMirrorNodes[0].setValue("");
           codeMirrorShapes[0].setValue("");
           console.log("Cleaning entries when 1 input rows");
           break;
   default: if (inputRows > 1) {
             console.log("Removing entry..."+ inputRows);
             $("#shapeDiv" + inputRows).remove();
             $("#nodeDiv" + inputRows).remove();
             codeMirrorNodes.pop();
             codeMirrorShapes.pop();
             inputRows--;
             setInputRows(inputRows);
             console.log("Removing one row. New value: " + inputRows);
            } else {
             console.log("Unknown value of inputRows: " + inputRows);
            }
  }
}

// Don't allow newline before change in CodeMirror
function noNewLine(instance,change) {
    var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
    change.update(change.from, change.to, [newtext]);
    return true;
}
*/

function changeMode(element,syntax) {
 var mode = "turtle";
 switch (syntax.toUpperCase()) {
  case "TURTLE": mode = "turtle" ;
                break ;
  case "N-TRIPLES": mode = "turtle" ;
                break ;
  case "RDF/XML": mode = "xml" ;
                break ;
  case "TRIX": mode = "xml" ;
                break ;
  case "SHEXJ" : mode = "javascript" ;
                break ;
  case "RDF/JSON" : mode = "javascript" ;
                break ;
  case "JSON-LD" : mode = "javascript" ;
                 break ;
  case "SHEXC": mode = "shex" ;
                break ;
 }
 element.setOption("mode",mode);
}

function changeTheme(theme) {
 codeMirrorData.setOption("theme",theme);
 codeMirrorSchema.setOption("theme",theme);
 codeMirrorShapeMap.setOption("theme",theme);
}

function changeSchemaSeparated(value) {
 console.log("Changing schemaSeparated: " + value);
 if (value==="on") {
  $("#schemaDiv").show();
 } else {
  $("#schemaDiv").hide();
 }
}

function changeTriggerMode(value) {
 if (value) {
 console.log("Changing triggermode: " + value);
 switch (value.toUpperCase()) {
  case "TARGETDECLS":
//    $("#nodeShapeContainer").hide();
    $("#shapeMapDiv").hide();
//    console.log("Hiding all: " + value);
    break;
/*  case "NODESHAPE":
    $("#nodeShapeContainer").show();
    console.log("Showing all: " + value);
    break;
  case "NODESTART":
    $("#nodeShapeContainer").show();
    console.log("Showing node only: " + value);
    break; */
  case "SHAPEMAP":
//    $("#nodeShapeContainer").show();
    $("#shapeMapDiv").show();
    console.log("Showing shape map: " + value);
    break;

  }
 }
}

function resetResult(result) {
 console.log("Reset result: " + JSON.stringify(result));
  $("#resultDiv").empty();
  $("#resultDiv").data("result", result);
}

function showResult(result) {
 result = $("#resultDiv").data("result");
 console.log("Show result: " + JSON.stringify(result));
 console.log("Result.nodesPrefixMap: " + JSON.stringify(result.nodesPrefixMap));
 var nodesPrefixMap = result.nodesPrefixMap ;
 var shapesPrefixMap = result.shapesPrefixMap ;
 console.log("nodesPrefixMap: " + JSON.stringify(nodesPrefixMap));
 console.log("shapesPrefixMap: " + JSON.stringify(shapesPrefixMap));
 if(result) {
  if (result.isValid || result.valid) {
   $("#resultDiv").removeClass("notValid").addClass("valid");
  } else {
   $("#resultDiv").removeClass("valid").addClass("notValid");
  }
  $("#resultDiv").append($("
").text("Result"));
  $("#resultDiv").append($("
").text(result.message));
  result.solutions.forEach(function(solution) {
   showSolution(solution,nodesPrefixMap,shapesPrefixMap);
  });
  showErrors(result.errors);
  var pre = $("
").text(JSON.stringify(result,undefined,2));
  var details = $("").append(pre);
  $("#resultDiv").append(details);
 }
}

function showQualify(node, prefix) {
 if (node.match(/^[0-9\"\'\_]/)) return node;
 for (var key in prefix) {
     if (node.startsWith(prefix[key])) {
         return "" + key + ":" + node.slice(prefix[key].length) + "";
     }
 }
 return "<" + node + ">" ;
}

function showSolution(solution,nodesPrefixMap, shapesPrefixMap) {
 console.log("Solution: " + JSON.stringify(solution));
 console.log("Solution, nodesPrefixMap: " + JSON.stringify(nodesPrefixMap));
 console.log("Solution, shapesPrefixMap: " + JSON.stringify(shapesPrefixMap));
 var table = "";

 table += "
Node	Shape	Evidences	";
 $.each(solution.solution, function(node,infoNodes) {
   console.log("node: " + JSON.stringify(node) + " infoNodes: " + JSON.stringify(infoNodes));
   $.each(infoNodes.hasShapes, function(shape,explanation) {
     console.log("Row..." + node + ". shape: " + shape + " Explanation: " + escapeHtml(explanation));
     table += "
" + showQualify(node, nodesPrefixMap) + "	" +
                "+ " + showQualify(shape, shapesPrefixMap) + "	" +
                "" + escapeHtml(explanation) + "
" ;
   });
   $.each(infoNodes.hasNoShapes, function(shape,explanation) {
     console.log("Row..." + node + ". noShape: " + shape + " Explanation: " + escapeHtml(explanation));
     table += "
" + showQualify(node, nodesPrefixMap) + "	" +
              "- " + showQualify(shape, shapesPrefixMap) + "	" +
              "" + escapeHtml(explanation) + "
" ;
   });
 });
 $("#resultDiv").append("
Solution

" + table + "
");
}

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": ''',
  '/': '/',
  '`': '`',
  '=': '=',
  '\n': '
'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/\n]/g, function (s) {
    return entityMap[s];
  });
}

function showErrors(errors) {
 if (errors.length > 0) {
  var table = "";
  table += ""
  console.log("Errors" + JSON.stringify(errors));
  $.each(errors, function(i,e) {
   console.log("Error" + JSON.stringify(e));
   table += "

" + escapeHtml(e.error) + "

";
  });
  $("#resultDiv").append("
Errors

" + table + "
");
 }
}

function getDataFormat(element) {
 var format = element.options[element.selectedIndex].value;
 window.alert("Data format of " + element + " format: " + format);
}

/*
function prepareShapeMap() {
 console.log("Preparing shape map:" );
 inputRows = getInputRows();
 console.log("codeMirrorNodes:" + codeMirrorNodes.length + " inputRows: " + inputRows);
 var pairs = [];
 for (i=0; i< inputRows; i++) {
   var node = codeMirrorNodes[i].getValue();
   var shape = codeMirrorShapes[i].getValue();
   pairs.push(encodeURIComponent(node) + "@" + encodeURIComponent(shape));
   console.log("Current pairs: " + JSON.stringify(pairs));
 }
 var str = pairs.join(",");
 console.log("pairs: " + JSON.stringify(pairs) + ". Shape-map = " + str);
 return str;
}
*/
$(document).ready(function(){

// When loading document get result from data-result attribute and show it
var result = $("#resultDiv").data("result");
showResult(result);

console.log("Main Url = " + urlShaclex);

var schemaSeparatedValue = $("#schemaSeparated").val();
console.log("Schema separated = " + schemaSeparatedValue);
changeSchemaSeparated(schemaSeparatedValue);

$("#schemaSeparated").change(function() {
 if (this.checked) {
     changeSchemaSeparated("on");
 } else {
     changeSchemaSeparated("off");
 }
});

var triggerModeValue = $("#triggerMode").val();
console.log("Trigger mode = " + triggerModeValue);
changeTriggerMode(triggerModeValue);

var rdfData = document.getElementById("rdfData");
if (rdfData) {
 codeMirrorData = CodeMirror.fromTextArea(rdfData, {
  lineNumbers: true,
  mode: "turtle",
  viewportMargin: Infinity,
  matchBrackets: true,
 });
}
var schema = document.getElementById("schema")
if (schema) {
 codeMirrorSchema = CodeMirror.fromTextArea(schema, {
   lineNumbers: true,
   mode: "shex",
   viewportMargin: Infinity,
   matchBrackets: true
 });
}

var shapeMap = document.getElementById("shapeMap")
if (shapeMap) {
 codeMirrorShapeMap = CodeMirror.fromTextArea(shapeMap, {
   lineNumbers: true,
   mode: "shex",
   viewportMargin: Infinity,
   matchBrackets: true
 });
 codeMirrorShapeMap.setSize(null,"5em");
}

/*
var inputRows = getInputRows();
console.log("Creating " + inputRows + " codeMirrors");

for(i = 0; i < inputRows; i++) {
 console.log("Creating codeMirror " + i);
 newCodeMirrorNode(i);
 newCodeMirrorShape(i);
}

console.log("Adding empty node shape entry..."); // Adds an empty entry
addNodeShapeEntry();
*/

console.log("Adding handler to validateButton...");
$("#validateButton").click(function(e){
    e.preventDefault();
    console.log("click on validating...");
    var data = codeMirrorData.getValue();
    var schema = codeMirrorSchema.getValue();
    var dataFormat = $("#dataFormat").find(":selected").text();
    var schemaFormat = $("#schemaFormat").find(":selected").text();
    var schemaEngine = $("#schemaEngine").find(":selected").text();
    var triggerMode = $("#triggerMode").find(":selected").text();
    var shapeMap = codeMirrorShapeMap.getValue(); // prepareShapeMap();
    var schemaSeparated = $("#schemaSeparated").val();
    if (schemaSeparated !== "on") {
      schema = "";
    }
    console.log("Trigger mode in AJAX query:" + triggerMode);
//    var shapeMap = prepareShapeMap();
    var location = "/validate?" +
                    "data=" + encodeURIComponent(data) +
                    "&dataFormat=" + encodeURIComponent(dataFormat) +
                    "&schema=" + encodeURIComponent(schema) +
                    "&schemaFormat=" + encodeURIComponent(schemaFormat) +
                    "&schemaEngine=" + encodeURIComponent(schemaEngine) +
                    "&triggerMode=" + encodeURIComponent(triggerMode) +
                    "&schemaSeparated=" + encodeURIComponent(schemaSeparated) +
                    "&shapeMap=" + encodeURIComponent(shapeMap);

     $.ajax({ url: urlShaclex + "/api/validate",
      data: {
        data: data,
        schema: schema,
        dataFormat: dataFormat,
        schemaFormat: schemaFormat,
        shapeMap: shapeMap,
        schemaEngine: schemaEngine,
        triggerMode: triggerMode,
        schemaSeparated: schemaSeparated
     },
    type: "GET",
    dataType : "json"
  })
  .done(function(result) {
     console.log("Done!: " + JSON.stringify(result));
     resetResult(result);
     console.log("After reseting result: " + JSON.stringify(result));
     showResult(result);
     history.pushState({},"validate",location);
  })
  .fail(function( xhr, status, errorThrown ) {
    $("#resultDiv").html("
" + errorThrown + "

" + xhr.responseText + "

" + status + "
" );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
  })
  });

 });
<commit_msg>Repaired abbr<commit_after>function getHost() {
 var port = window.location.port;
 return window.location.protocol + "//" + window.location.hostname + (port? ":" + port: "") ;
}

var urlShaclex = getHost();

console.log("urlShaclex: " + urlShaclex);

var codeMirrorData ;
var codeMirrorSchema ;
var codeMirrorShapeMap ;
// var codeMirrorNodes = new Array();
// var codeMirrorShapes = new Array();
// var inputRows = 0;
/*
function newCodeMirrorNode(n) {
 var nodeId = document.getElementById("node" + n);
 if (nodeId) {
  var codeMirrorNode = CodeMirror.fromTextArea(nodeId, {
  lineNumbers: false,
   mode: "turtle",
   scrollbarStyle: "null",
   tabindex: 2*n,
   height: 1,
   extraKeys: { Tab: false }
  });
  codeMirrorNode.on("beforeChange", noNewLine);
  codeMirrorNode.setSize(null,"1.5em");
  codeMirrorNodes.push(codeMirrorNode);
 } else {
   console.log("Not found node" + n);
 }
}

function newCodeMirrorShape(n) {
 var shapeId = document.getElementById("shape" + n);
 if (shapeId) {
  var codeMirrorShape = CodeMirror.fromTextArea(shapeId, {
   lineNumbers: false,
   mode: "turtle",
   scrollbarStyle: "null",
   tabindex: 2*n+1,
   height: 1,
   extraKeys: { Tab: false }
  });
 codeMirrorShape.on("beforeChange", noNewLine);
 codeMirrorShape.setSize(null,"1.5em");
 console.log("Current codeMirrorShapes: " + codeMirrorShapes.length);
 codeMirrorShapes.push(codeMirrorShape);
 } else {
   console.log("Not found shape" + n);
 }
}

function getInputRows() {
 return $("#rowsCounter").data("value");
}

function setInputRows(n) {
 $("#rowsCounter").data("value",n);
}

function incrementInputRows() {
 inputRows = getInputRows();
 inputRows++
 setInputRows(inputRows);
 return inputRows;
}

function addNodeShapeEntry() {
  inputRows = incrementInputRows();
  var nodeEntry =  "
Node<textarea placeholder='Node' id='node" + inputRows + "' placeholder='Node...'></textarea>
"
  var shapeEntry = "
Shape<textarea placeholder='Shape' id='shape" + inputRows + "' placeholder='Shape...'></textarea>

"
  console.log("Setting styles... on #nodeDiv" + inputRows);
  $("#nodeDiv"+inputRows).css("float","left");
  $("#nodeDiv"+inputRows).css("width","30%");
  $("#shapeDiv"+inputRows).css("float","right");
  $("#shapeDiv"+inputRows).css("width","30%");
  $("#nodeShapeContainer").append(nodeEntry);
  $("#nodeShapeContainer").append(shapeEntry);
  $("#nodeShapeContainer").append("
");
  newCodeMirrorNode(inputRows);
  newCodeMirrorShape(inputRows);
  console.log("Added row " + inputRows);
}

function removeNodeShapeEntry() {
  $inputRows = getInputRows();
  switch (inputRows)  {
   case 0: console.log("Cleaning entries when 0 input rows");
           break;
   case 1: codeMirrorNodes[0].setValue("");
           codeMirrorShapes[0].setValue("");
           console.log("Cleaning entries when 1 input rows");
           break;
   default: if (inputRows > 1) {
             console.log("Removing entry..."+ inputRows);
             $("#shapeDiv" + inputRows).remove();
             $("#nodeDiv" + inputRows).remove();
             codeMirrorNodes.pop();
             codeMirrorShapes.pop();
             inputRows--;
             setInputRows(inputRows);
             console.log("Removing one row. New value: " + inputRows);
            } else {
             console.log("Unknown value of inputRows: " + inputRows);
            }
  }
}

// Don't allow newline before change in CodeMirror
function noNewLine(instance,change) {
    var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
    change.update(change.from, change.to, [newtext]);
    return true;
}
*/

function changeMode(element,syntax) {
 var mode = "turtle";
 switch (syntax.toUpperCase()) {
  case "TURTLE": mode = "turtle" ;
                break ;
  case "N-TRIPLES": mode = "turtle" ;
                break ;
  case "RDF/XML": mode = "xml" ;
                break ;
  case "TRIX": mode = "xml" ;
                break ;
  case "SHEXJ" : mode = "javascript" ;
                break ;
  case "RDF/JSON" : mode = "javascript" ;
                break ;
  case "JSON-LD" : mode = "javascript" ;
                 break ;
  case "SHEXC": mode = "shex" ;
                break ;
 }
 element.setOption("mode",mode);
}

function changeTheme(theme) {
 codeMirrorData.setOption("theme",theme);
 codeMirrorSchema.setOption("theme",theme);
 codeMirrorShapeMap.setOption("theme",theme);
}

function changeSchemaSeparated(value) {
 console.log("Changing schemaSeparated: " + value);
 if (value==="on") {
  $("#schemaDiv").show();
 } else {
  $("#schemaDiv").hide();
 }
}

function changeTriggerMode(value) {
 if (value) {
 console.log("Changing triggermode: " + value);
 switch (value.toUpperCase()) {
  case "TARGETDECLS":
//    $("#nodeShapeContainer").hide();
    $("#shapeMapDiv").hide();
//    console.log("Hiding all: " + value);
    break;
/*  case "NODESHAPE":
    $("#nodeShapeContainer").show();
    console.log("Showing all: " + value);
    break;
  case "NODESTART":
    $("#nodeShapeContainer").show();
    console.log("Showing node only: " + value);
    break; */
  case "SHAPEMAP":
//    $("#nodeShapeContainer").show();
    $("#shapeMapDiv").show();
    console.log("Showing shape map: " + value);
    break;

  }
 }
}

function resetResult(result) {
 console.log("Reset result: " + JSON.stringify(result));
  $("#resultDiv").empty();
  $("#resultDiv").data("result", result);
}

function showResult(result) {
 result = $("#resultDiv").data("result");
 console.log("Show result: " + JSON.stringify(result));
 console.log("Result.nodesPrefixMap: " + JSON.stringify(result.nodesPrefixMap));
 var nodesPrefixMap = result.nodesPrefixMap ;
 var shapesPrefixMap = result.shapesPrefixMap ;
 console.log("nodesPrefixMap: " + JSON.stringify(nodesPrefixMap));
 console.log("shapesPrefixMap: " + JSON.stringify(shapesPrefixMap));
 if(result) {
  if (result.isValid || result.valid) {
   $("#resultDiv").removeClass("notValid").addClass("valid");
  } else {
   $("#resultDiv").removeClass("valid").addClass("notValid");
  }
  $("#resultDiv").append($("
").text("Result"));
  $("#resultDiv").append($("
").text(result.message));
  result.solutions.forEach(function(solution) {
   showSolution(solution,nodesPrefixMap,shapesPrefixMap);
  });
  showErrors(result.errors);
  var pre = $("
").text(JSON.stringify(result,undefined,2));
  var details = $("").append(pre);
  $("#resultDiv").append(details);
 }
}

function showQualify(node, prefix) {
 if (node.match(/^[0-9\"\'\_]/)) return node;
 for (var key in prefix) {
     if (node.startsWith(prefix[key])) {
         return "" + key + ":" + node.slice(prefix[key].length) + "";
     }
 }
 return "<" + node + ">" ;
}

function showSolution(solution,nodesPrefixMap, shapesPrefixMap) {
 console.log("Solution: " + JSON.stringify(solution));
 console.log("Solution, nodesPrefixMap: " + JSON.stringify(nodesPrefixMap));
 console.log("Solution, shapesPrefixMap: " + JSON.stringify(shapesPrefixMap));
 var table = "";

 table += "
Node	Shape	Evidences	";
 $.each(solution.solution, function(node,infoNodes) {
   console.log("node: " + JSON.stringify(node) + " infoNodes: " + JSON.stringify(infoNodes));
   $.each(infoNodes.hasShapes, function(shape,explanation) {
     console.log("Row..." + node + ". shape: " + shape + " Explanation: " + escapeHtml(explanation));
     table += "
" + showQualify(node, nodesPrefixMap) + "	" +
                "+ " + showQualify(shape, shapesPrefixMap) + "	" +
                "" + escapeHtml(explanation) + "
" ;
   });
   $.each(infoNodes.hasNoShapes, function(shape,explanation) {
     console.log("Row..." + node + ". noShape: " + shape + " Explanation: " + escapeHtml(explanation));
     table += "
" + showQualify(node, nodesPrefixMap) + "	" +
              "- " + showQualify(shape, shapesPrefixMap) + "	" +
              "" + escapeHtml(explanation) + "
" ;
   });
 });
 $("#resultDiv").append("
Solution

" + table + "
");
}

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": ''',
  '/': '/',
  '`': '`',
  '=': '=',
  '\n': '
'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/\n]/g, function (s) {
    return entityMap[s];
  });
}

function showErrors(errors) {
 if (errors.length > 0) {
  var table = "";
  table += ""
  console.log("Errors" + JSON.stringify(errors));
  $.each(errors, function(i,e) {
   console.log("Error" + JSON.stringify(e));
   table += "

" + escapeHtml(e.error) + "

";
  });
  $("#resultDiv").append("
Errors

" + table + "
");
 }
}

function getDataFormat(element) {
 var format = element.options[element.selectedIndex].value;
 window.alert("Data format of " + element + " format: " + format);
}

/*
function prepareShapeMap() {
 console.log("Preparing shape map:" );
 inputRows = getInputRows();
 console.log("codeMirrorNodes:" + codeMirrorNodes.length + " inputRows: " + inputRows);
 var pairs = [];
 for (i=0; i< inputRows; i++) {
   var node = codeMirrorNodes[i].getValue();
   var shape = codeMirrorShapes[i].getValue();
   pairs.push(encodeURIComponent(node) + "@" + encodeURIComponent(shape));
   console.log("Current pairs: " + JSON.stringify(pairs));
 }
 var str = pairs.join(",");
 console.log("pairs: " + JSON.stringify(pairs) + ". Shape-map = " + str);
 return str;
}
*/
$(document).ready(function(){

// When loading document get result from data-result attribute and show it
var result = $("#resultDiv").data("result");
showResult(result);

console.log("Main Url = " + urlShaclex);

var schemaSeparatedValue = $("#schemaSeparated").val();
console.log("Schema separated = " + schemaSeparatedValue);
changeSchemaSeparated(schemaSeparatedValue);

$("#schemaSeparated").change(function() {
 if (this.checked) {
     changeSchemaSeparated("on");
 } else {
     changeSchemaSeparated("off");
 }
});

var triggerModeValue = $("#triggerMode").val();
console.log("Trigger mode = " + triggerModeValue);
changeTriggerMode(triggerModeValue);

var rdfData = document.getElementById("rdfData");
if (rdfData) {
 codeMirrorData = CodeMirror.fromTextArea(rdfData, {
  lineNumbers: true,
  mode: "turtle",
  viewportMargin: Infinity,
  matchBrackets: true,
 });
}
var schema = document.getElementById("schema")
if (schema) {
 codeMirrorSchema = CodeMirror.fromTextArea(schema, {
   lineNumbers: true,
   mode: "shex",
   viewportMargin: Infinity,
   matchBrackets: true
 });
}

var shapeMap = document.getElementById("shapeMap")
if (shapeMap) {
 codeMirrorShapeMap = CodeMirror.fromTextArea(shapeMap, {
   lineNumbers: true,
   mode: "shex",
   viewportMargin: Infinity,
   matchBrackets: true
 });
 codeMirrorShapeMap.setSize(null,"5em");
}

/*
var inputRows = getInputRows();
console.log("Creating " + inputRows + " codeMirrors");

for(i = 0; i < inputRows; i++) {
 console.log("Creating codeMirror " + i);
 newCodeMirrorNode(i);
 newCodeMirrorShape(i);
}

console.log("Adding empty node shape entry..."); // Adds an empty entry
addNodeShapeEntry();
*/

console.log("Adding handler to validateButton...");
$("#validateButton").click(function(e){
    e.preventDefault();
    console.log("click on validating...");
    var data = codeMirrorData.getValue();
    var schema = codeMirrorSchema.getValue();
    var dataFormat = $("#dataFormat").find(":selected").text();
    var schemaFormat = $("#schemaFormat").find(":selected").text();
    var schemaEngine = $("#schemaEngine").find(":selected").text();
    var triggerMode = $("#triggerMode").find(":selected").text();
    var shapeMap = codeMirrorShapeMap.getValue(); // prepareShapeMap();
    var schemaSeparated = $("#schemaSeparated").val();
    if (schemaSeparated !== "on") {
      schema = "";
    }
    console.log("Trigger mode in AJAX query:" + triggerMode);
//    var shapeMap = prepareShapeMap();
    var location = "/validate?" +
                    "data=" + encodeURIComponent(data) +
                    "&dataFormat=" + encodeURIComponent(dataFormat) +
                    "&schema=" + encodeURIComponent(schema) +
                    "&schemaFormat=" + encodeURIComponent(schemaFormat) +
                    "&schemaEngine=" + encodeURIComponent(schemaEngine) +
                    "&triggerMode=" + encodeURIComponent(triggerMode) +
                    "&schemaSeparated=" + encodeURIComponent(schemaSeparated) +
                    "&shapeMap=" + encodeURIComponent(shapeMap);

     $.ajax({ url: urlShaclex + "/api/validate",
      data: {
        data: data,
        schema: schema,
        dataFormat: dataFormat,
        schemaFormat: schemaFormat,
        shapeMap: shapeMap,
        schemaEngine: schemaEngine,
        triggerMode: triggerMode,
        schemaSeparated: schemaSeparated
     },
    type: "GET",
    dataType : "json"
  })
  .done(function(result) {
     console.log("Done!: " + JSON.stringify(result));
     resetResult(result);
     console.log("After reseting result: " + JSON.stringify(result));
     showResult(result);
     history.pushState({},"validate",location);
  })
  .fail(function( xhr, status, errorThrown ) {
    $("#resultDiv").html("
" + errorThrown + "

" + xhr.responseText + "

" + status + "
" );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
  })
  });

 });
<|endoftext|>


<commit_before>'use strict';

var find = require('lodash.find');
var path = require('path');

module.exports = function (options) {
    var properties = ['border', 'border-bottom', 'border-left', 'border-right', 'border-top'];
    var filename = path.basename(options.path);
    var config = options.config;
    var node = options.node;
    var property;
    var message;
    var value;

    // Bail if the linter isn't wanted
    if (config.borderZero && !config.borderZero.enabled) {
        return null;
    }

    // Not applicable, bail
    if (node.type !== 'declaration') {
        return null;
    }

    property = find(node.content, function (element) {
        if (element.type === 'property') {
            return true;
        }

        return false;
    });

    // Not a border* property, bail
    if (properties.indexOf(property.content[0].content) === -1) {
        return null;
    }

    value = find(node.content, function (element) {
        if (element.type === 'value') {
            return true;
        }

        return false;
    });

    // Bail if it's an actual border
    if (value.content[0].content !== '0' && value.content[0].content !== 'none') {
        return null;
    }

    switch (config.borderZero.style) {
        case 'none':
            if (value.content[0].content === '0') {
                message = 'Border properties should use "none" instead of 0.';
            }

            break;
        case 'zero':
            if (value.content[0].content === 'none') {
                message = 'Border properties should use 0 instead of "none".';
            }

            break;
        default:
            throw new Error(
                'Invalid setting value for borderZero: ' + config.borderZero.style
            );
    }

    if (message) {
        return {
            column: value.start.column,
            file: filename,
            line: value.start.line,
            linter: 'borderZero',
            message: message
        };
    }

    return true;
};
<commit_msg>borderZero: Use gonzales methods instead of searching on our own<commit_after>'use strict';

var path = require('path');

module.exports = function (options) {
    var properties = ['border', 'border-bottom', 'border-left', 'border-right', 'border-top'];
    var filename = path.basename(options.path);
    var config = options.config;
    var node = options.node;
    var property;
    var message;
    var value;

    // Bail if the linter isn't wanted
    if (config.borderZero && !config.borderZero.enabled) {
        return null;
    }

    // Not applicable, bail
    if (node.type !== 'declaration') {
        return null;
    }

    property = node.first('property');

    // Not a border* property, bail
    if (properties.indexOf(property.content[0].content) === -1) {
        return null;
    }

    value = node.first('value');

    // Bail if it's an actual border
    if ((value.content[0].content !== '0' && value.content[0].content !== 'none')) {
        return null;
    }

    switch (config.borderZero.style) {
        case 'none':
            if (value.content[0].content === '0') {
                message = 'Border properties should use "none" instead of 0.';
            }

            break;
        case 'zero':
            if (value.content[0].content === 'none') {
                message = 'Border properties should use 0 instead of "none".';
            }

            break;
        default:
            throw new Error(
                'Invalid setting value for borderZero: ' + config.borderZero.style
            );
    }

    if (message) {
        return {
            column: value.start.column,
            file: filename,
            line: value.start.line,
            linter: 'borderZero',
            message: message
        };
    }

    return true;
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
	mongoose = require('mongoose'),
	Site = mongoose.model('Site'),
	errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
	_ = require('lodash');

/**
 * Create a Site
 */
exports.create = function (req, res) {
	var site = new Site(req.body);
	site.user = req.user;

	site.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(site);
		}
	});
};

/**
 * Show the current Site
 */
exports.read = function (req, res) {
	res.jsonp(req.site);
};

/**
 * Update a Site
 */
exports.update = function (req, res) {
	var site = req.site;

	site = _.extend(site, req.body);

	site.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(site);
		}
	});
};

/**
 * Delete an Site
 */
exports.delete = function (req, res) {
	var site = req.site;

	site.remove(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(site);
		}
	});
};

/**
 * List of Sites
 */
exports.list = function (req, res) {

	var sort;
	var sortObject = {};
	var count = req.query.count || 5;
	var page = req.query.page || 1;

	var filter = {
		filters: {
			mandatory: {
				contains: req.query.filter
			}
		}
	};

	var pagination = {
		start: (page - 1) * count,
		count: count
	};

	if (req.query.sorting) {
		var sortKey = Object.keys(req.query.sorting)[0];
		var sortValue = req.query.sorting[sortKey];
		sortObject[sortValue] = sortKey;
	}
	else {
		sortObject.desc = '_id';
	}

	sort = {
		sort: sortObject
	};

	Site
		.find()
		.filter(filter)
		.order(sort)
		.page(pagination, function (err, sites) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			}
			else {
				res.jsonp(sites);
			}
		});

};

exports.all = function (req, res) {

	Site
	.find({
		is_active: true
	})
	.sort('name')
	.exec(function (err, sites) {
		console.log(sites);

		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(sites);
		}
	});
};

/**
 * Site middleware
 */
exports.siteByID = function (req, res, next, id) {

	if (!mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'Site is invalid'
		});
	}

	Site.findById(id).populate('user', 'displayName').exec(function (err, site) {
		if (err) return next(err);
		if (!site) return next(new Error('Failed to load Site ' + id));
		req.site = site;
		next();
	});
};
<commit_msg>Remove debug message<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
	mongoose = require('mongoose'),
	Site = mongoose.model('Site'),
	errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
	_ = require('lodash');

/**
 * Create a Site
 */
exports.create = function (req, res) {
	var site = new Site(req.body);
	site.user = req.user;

	site.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(site);
		}
	});
};

/**
 * Show the current Site
 */
exports.read = function (req, res) {
	res.jsonp(req.site);
};

/**
 * Update a Site
 */
exports.update = function (req, res) {
	var site = req.site;

	site = _.extend(site, req.body);

	site.save(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(site);
		}
	});
};

/**
 * Delete an Site
 */
exports.delete = function (req, res) {
	var site = req.site;

	site.remove(function (err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(site);
		}
	});
};

/**
 * List of Sites
 */
exports.list = function (req, res) {

	var sort;
	var sortObject = {};
	var count = req.query.count || 5;
	var page = req.query.page || 1;

	var filter = {
		filters: {
			mandatory: {
				contains: req.query.filter
			}
		}
	};

	var pagination = {
		start: (page - 1) * count,
		count: count
	};

	if (req.query.sorting) {
		var sortKey = Object.keys(req.query.sorting)[0];
		var sortValue = req.query.sorting[sortKey];
		sortObject[sortValue] = sortKey;
	}
	else {
		sortObject.desc = '_id';
	}

	sort = {
		sort: sortObject
	};

	Site
		.find()
		.filter(filter)
		.order(sort)
		.page(pagination, function (err, sites) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			}
			else {
				res.jsonp(sites);
			}
		});

};

exports.all = function (req, res) {

	Site
	.find({
		is_active: true
	})
	.sort('name')
	.exec(function (err, sites) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		else {
			res.jsonp(sites);
		}
	});
};

/**
 * Site middleware
 */
exports.siteByID = function (req, res, next, id) {

	if (!mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'Site is invalid'
		});
	}

	Site.findById(id).populate('user', 'displayName').exec(function (err, site) {
		if (err) return next(err);
		if (!site) return next(new Error('Failed to load Site ' + id));
		req.site = site;
		next();
	});
};
<|endoftext|>


<commit_before>var _ = require('underscore'),
    async = require('async'),
    exec = require('child_process').exec,
    jsdom = require('jsdom').jsdom,
    lumbar = require('lumbar'),
    fu = lumbar.fileUtil;

module.exports = {
  priority: 80,

  generateToken: function(command, callback) {
    if (!command) {
      return callback(undefined, '');
    }

    exec(command, {cwd: lumbar.fileUtil.lookupPath()}, function(err, stdout, stderr) {
      callback(err, (stdout || '').replace(/\n/g, ''));
    });
  },

  updateHtmlReferences: function(context, content, callback) {
    function updateResources(mode, query, create) {
      return function(callback) {
        async.forEach(_.clone(doc.querySelectorAll(query)), function(el, callback) {
          var module = (el.src || el.href).replace(/^module:/, '');
          context.fileNamesForModule(mode, module, function(err, fileNames) {
            if (err) {
              return callback(err);
            }

            // Generate replacement elements for each of the entries
            var content = fileNames.map(function(fileName) {
              return create(context.config.loadPrefix() + fileName.fileName.path + '.' + fileName.fileName.extension);
            });

            // Output and kill the original
            content.forEach(function(replace) {
              el.parentNode.insertBefore(replace, el);
            });
            el.parentNode.removeChild(el);

            callback();
          });
        },
        callback);
      }
    }
    var doc = jsdom(content, null, { features: { ProcessExternalResources: false, QuerySelector: true } });
    async.parallel([
      updateResources('scripts', 'script[src^="module:"]', function(href) {
          var script = doc.createElement('script');
          script.type = 'text/javascript';
          script.src = href;
          return script;
        }),
      updateResources('styles', 'link[href^="module:"]', function(href) {
          var link = doc.createElement('link');
          link.rel = 'stylesheet';
          link.type = 'text/css';
          link.href = href;
          return link;
        })
      ],
      function(err) {
        callback(err, doc.doctype + doc.innerHTML);
      });
  },

  fileName: function(context, next, complete) {
    // Prepend the cache buster value
    next(function(err, ret) {
      if (err) {
        return complete(err);
      }

      function generatePath(err, token) {
        if (ret && token && (context.mode !== 'static' || !context.resource['no-expires-token'])) {
          // Move the expires token after the platform path if that is the start of the path
          if (ret.path.indexOf(context.platformPath) === 0) {
            ret.path = ret.path.substring(context.platformPath.length);
            token = context.platformPath + token;
          }
          ret.path = token + '/' + ret.path;
        }
        complete(err, ret);
      }

      if (context.configCache.longExpires) {
        generatePath(undefined, context.configCache.longExpires);
      } else {
        module.exports.generateToken(
          context.config.attributes['long-expires'],
          generatePath);
      }
    });
  },

  resource: function(context, next, complete) {
    var resource = context.resource;
    if (context.mode === 'static' && resource['update-externals']) {
      next(function(err, resource) {
        function generator(callback) {
          // Load the source data
          fu.loadResource(resource, function(err, file) {
            if (err) {
              return complete(err);
            }

            // Update the content
            module.exports.updateHtmlReferences(context, file.content, function(err, data) {
              callback(err, {
                data: data,
                inputs: file.inputs
              });
            });
          });
        }

        // Include any attributes that may have been defined on the base entry
        if (!_.isString(resource)) {
          _.extend(generator, resource);
        }
        complete(undefined, generator);
      });
    } else {
      next(complete);
    }
  }
};
<commit_msg>Update for new resource signature<commit_after>var _ = require('underscore'),
    async = require('async'),
    exec = require('child_process').exec,
    jsdom = require('jsdom').jsdom,
    lumbar = require('lumbar'),
    fu = lumbar.fileUtil;

module.exports = {
  priority: 80,

  generateToken: function(command, callback) {
    if (!command) {
      return callback(undefined, '');
    }

    exec(command, {cwd: lumbar.fileUtil.lookupPath()}, function(err, stdout, stderr) {
      callback(err, (stdout || '').replace(/\n/g, ''));
    });
  },

  updateHtmlReferences: function(context, content, callback) {
    function updateResources(mode, query, create) {
      return function(callback) {
        async.forEach(_.clone(doc.querySelectorAll(query)), function(el, callback) {
          var module = (el.src || el.href).replace(/^module:/, '');
          context.fileNamesForModule(mode, module, function(err, fileNames) {
            if (err) {
              return callback(err);
            }

            // Generate replacement elements for each of the entries
            var content = fileNames.map(function(fileName) {
              return create(context.config.loadPrefix() + fileName.fileName.path + '.' + fileName.fileName.extension);
            });

            // Output and kill the original
            content.forEach(function(replace) {
              el.parentNode.insertBefore(replace, el);
            });
            el.parentNode.removeChild(el);

            callback();
          });
        },
        callback);
      }
    }
    var doc = jsdom(content, null, { features: { ProcessExternalResources: false, QuerySelector: true } });
    async.parallel([
      updateResources('scripts', 'script[src^="module:"]', function(href) {
          var script = doc.createElement('script');
          script.type = 'text/javascript';
          script.src = href;
          return script;
        }),
      updateResources('styles', 'link[href^="module:"]', function(href) {
          var link = doc.createElement('link');
          link.rel = 'stylesheet';
          link.type = 'text/css';
          link.href = href;
          return link;
        })
      ],
      function(err) {
        callback(err, doc.doctype + doc.innerHTML);
      });
  },

  fileName: function(context, next, complete) {
    // Prepend the cache buster value
    next(function(err, ret) {
      if (err) {
        return complete(err);
      }

      function generatePath(err, token) {
        if (ret && token && (context.mode !== 'static' || !context.resource['no-expires-token'])) {
          // Move the expires token after the platform path if that is the start of the path
          if (ret.path.indexOf(context.platformPath) === 0) {
            ret.path = ret.path.substring(context.platformPath.length);
            token = context.platformPath + token;
          }
          ret.path = token + '/' + ret.path;
        }
        complete(err, ret);
      }

      if (context.configCache.longExpires) {
        generatePath(undefined, context.configCache.longExpires);
      } else {
        module.exports.generateToken(
          context.config.attributes['long-expires'],
          generatePath);
      }
    });
  },

  resource: function(context, next, complete) {
    var resource = context.resource;
    if (context.mode === 'static' && resource['update-externals']) {
      next(function(err, resource) {
        function generator(context, callback) {
          // Load the source data
          fu.loadResource(context, resource, function(err, file) {
            if (err) {
              return complete(err);
            }

            // Update the content
            module.exports.updateHtmlReferences(context, file.content, function(err, data) {
              callback(err, {
                data: data,
                inputs: file.inputs
              });
            });
          });
        }

        // Include any attributes that may have been defined on the base entry
        if (!_.isString(resource)) {
          _.extend(generator, resource);
        }
        complete(undefined, generator);
      });
    } else {
      next(complete);
    }
  }
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chalk = require('chalk');
var symbol = require('log-symbols');

/**
 * Resolve conflicts between helpers and data
 * properties before rendering.
 */

module.exports = function conflict_(verb) {
  var conflicts = verb.get('argv.conflicts');
  var verbose = verb.get('argv.verbose');

  if (conflicts && verbose) {
    console.log();
    console.log(chalk.yellow('Checking for conflicts…'));
  }

  return function (file, next) {
    if (!conflicts) return next();

    var str = file.content;
    var res = helpers(str);
    var conflicting = problematic(verb, file, res, verbose);
    var h = {};

    if (!conflicting.length) {
      return next();
    }

    var ctx = {};
    ctx.options = _.extend({}, verb.options, file.options);
    ctx.context = file.locals || {};
    ctx.app = verb;

    file.locals = file.locals || {};
    file.locals.__ = file.locals.__ || {};

    for (var i = 0; i < conflicting.length; i++) {
      var name = conflicting[i];
      file.content = namespace(file.content, name);
      var syncFn = verb._.helpers[name];
      if (syncFn) {
        h[name] = _.bind(syncFn, ctx);
        file.locals.__[name] = _.bind(syncFn, ctx);
        verb.helpers({__: h});
        delete verb._.helpers[name];
      }

      var asyncFn = verb._.asyncHelpers[name];
      if (asyncFn) {
        h[name] = _.bind(asyncFn, ctx);
        file.locals.__[name] = _.bind(asyncFn, ctx);
        verb.asyncHelpers({__: h});
        delete verb._.asyncHelpers[name];
      }

      if (!asyncFn && !syncFn) {
        h[name] = noop(name);
        file.locals.__[name] = noop(name);
        verb.helpers({__: h});
      }
    }
    next();
  };
};

function noop(name) {
  return function () {
    var msg = '';
    msg += 'ERROR! Cannot find the {%= ';
    msg += name;
    msg += '() %} helper. Helpers may be ';
    msg += 'registered using `verb.helper()`.';
    // console.log(chalk.red(msg));
  };
}

function namespace(str, name) {
  return str.split('{%= ' + name).join('{%= __.' + name);
}

function helpers(str) {
  var re = /\{%=\s*((?!__\.)[\w.]+)(?:\(\)|\(([^)]*?)\))\s*%}/gm;
  var res = [], match;

  while (match = re.exec(str)) {
    if (res.indexOf(match[1]) === -1) {
      res.push(match[1].trim());
    }
  }
  return res;
}

function problematic(verb, file, helpers, verbose) {
  var dataKeys = Object.keys(verb.cache.data);
  dataKeys = _.union(dataKeys, Object.keys(file.data));

  var registered = Object.keys(verb._.asyncHelpers);
  registered = _.union(registered, Object.keys(verb._.helpers));

  var h = [], d = [];
  var len = helpers.length;

  while (len--) {
    var helper = helpers[len];
    // if the helper name is also a data prop, it's a conflict
    if (dataKeys.indexOf(helper) !== -1) {
      d.push(helper);
    }

    // if the helper is not registered, it's a conflict
    if (registered.indexOf(helper) === -1) {
      h.push(helper);
    }
  }

  message(h, d, verbose, file);
  return _.union(h, d);
}

function message(h, d, verbose, file) {
  if (!verbose) return;
  var fp = file.path.split(/[\\\/]/).slice(-2).join('/');

  var hlen = h.length;
  var dlen = d.length;

  if (hlen > 0) {
    console.log(' ', symbol.error, chalk.red(hlen + ' missing helper' + s(hlen) + ' found in', fp));
    h.forEach(function (ele) {
      console.log(' - ' + ele);
    });
  }

  if (dlen > 0) {
    console.log(' ', symbol.error, chalk.red(dlen + ' conflict' + s(dlen) + ' found in', fp));
    d.forEach(function (ele) {
      console.log('  -', ele, chalk.gray('(found both a helper and a data property with this name)'));
    });
  }
}

function s(len) {
  return len > 1 ? 's' : '';
}
<commit_msg>better logging<commit_after>'use strict';

var _ = require('lodash');
var chalk = require('chalk');
var symbol = require('log-symbols');

/**
 * Resolve conflicts between helpers and data
 * properties before rendering.
 */

module.exports = function conflict_(verb) {
  var verbose = verb.get('argv.verbose');

  if (verbose) {
    console.log();
    console.log(chalk.bold.underline('Checking for conflicts…'));
    console.log();
  }

  return function (file, next) {
    var str = file.content;
    var res = helpers(str);
    var conflicting = problematic(verb, file, res, verbose);
    var h = {};

    if (!conflicting.length) {
      return next();
    }

    var ctx = {};
    ctx.options = _.extend({}, verb.options, file.options);
    ctx.context = _.merge({}, verb.cache.data, file.locals, file.data);
    ctx.app = verb;

    file.locals = file.locals || {};
    file.locals.__ = file.locals.__ || {};

    // console.log('actual:', verb._.helpers)
    for (var i = 0; i < conflicting.length; i++) {
      var name = conflicting[i];
      // console.log('missing:', name)
      file.content = namespace(file.content, name);

      var syncFn = verb._.helpers[name];
      if (syncFn) {
        h[name] = _.bind(syncFn, ctx);
        file.locals.__[name] = _.bind(syncFn, ctx);
        verb.helpers({__: h});
        delete verb._.helpers[name];
      }

      var asyncFn = verb._.asyncHelpers[name];
      if (asyncFn) {
        h[name] = _.bind(asyncFn, ctx);
        file.locals.__[name] = _.bind(asyncFn, ctx);
        verb.asyncHelpers({__: h});
        delete verb._.asyncHelpers[name];
      }

      if (!asyncFn && !syncFn) {
        h[name] = noop(name);
        file.locals.__[name] = noop(name);
        verb.helpers({__: h});
      }
    }
    next();
  };
};

function noop(name) {
  return function () {
    var msg = '';
    msg += 'ERROR! Cannot find the {%= ' + name + '() %} helper. Helpers may be ';
    msg += 'registered using `verb.helper()`.';
    // console.log(chalk.red(msg));
  };
}

function namespace(str, name) {
  return str.split('{%= ' + name).join('{%= __.' + name);
}

function helpers(str) {
  var re = /\{%=\s*((?!__\.)[\w.]+)(?:\(\)|\(([^)]*?)\))\s*%}/gm;
  var res = [], match;

  while (match = re.exec(str)) {
    if (res.indexOf(match[1]) === -1) {
      res.push(match[1].trim());
    }
  }
  return res;
}

function problematic(verb, file, helpers, verbose) {
  var dataKeys = Object.keys(verb.cache.data);
  dataKeys = _.union(dataKeys, Object.keys(file.data));

  var registered = Object.keys(verb._.asyncHelpers);
  registered = _.union(registered, Object.keys(verb._.helpers));

  var h = [], d = [];
  var len = helpers.length;

  while (len--) {
    var helper = helpers[len];
    // if the helper name is also a data prop, it's a conflict
    if (dataKeys.indexOf(helper) !== -1) {
      d.push(helper);
    }

    // if the helper is not registered, it's a conflict
    if (registered.indexOf(helper) === -1) {
      h.push(helper);
    }
  }

  message(h, d, verbose, file);
  return _.union(h, d);
}

function message(h, d, verbose, file) {
  if (!verbose) return;
  var fp = file.path.split(/[\\\/]/).slice(-2).join('/');

  var hlen = h.length;
  var dlen = d.length;

  if (hlen > 0) {
    console.log(symbol.error, '', chalk.red(hlen + ' missing helper' + s(hlen) + ' found in', fp));
    h.forEach(function (ele) {
      console.log('   -', ele);
    });
    console.log();
  }

  if (dlen > 0) {
    console.log(symbol.warning, '', chalk.yellow(dlen + ' data/helper conflict' + s(dlen) + ' found in', fp));
    d.forEach(function (ele) {
      console.log('   -', ele);
    });
    console.log();
  }
}

function s(len) {
  return len > 1 ? 's' : '';
}
<|endoftext|>