<commit_before>var entries = require('../dictionary.json').data;
var utils = require('./utils');
var dom = require('./dom-helper');
var Dropdown = require('./dropdown');

function AutoComplete(container, opt) {
  var self = this;

  // Internal option object
  this._opt = {
    searchResultsToShow: (opt && opt.searchResultsToShow) || 5,
    onTagsUpdate: opt && opt.onTagsUpdate
  };
  // Internal state object
  this._state = {
    tags: []
  };
  this.dom = {
    rootContainerNode: this._createRootContainer(),
    tagsContainerNode: this._createTagsContainer(),
    inputNode: this._createInputBox()
  };
  this.dom.rootContainerNode.appendChild(this.dom.tagsContainerNode);
  this.dom.rootContainerNode.appendChild(this.dom.inputNode);

  // Create dropdown menu
  this.dropdown = new Dropdown([], {
    onItemClick: function(item) {
      self._onTagSelect(item.value);
    }
  });

  this._initializeEventHandlers();

  // Replace target container with a brand new root-container
  dom.renderTo(this.dom.rootContainerNode, container);

  // Render dropdown to the input element
  this.dropdown.renderTo(this.dom.rootContainerNode);
}
AutoComplete.prototype._initializeEventHandlers = function() {
  var self = this;

  // Extend input click area to entire root-container
  this.dom.rootContainerNode.addEventListener('click', function(event) {
    if (event.target == this) {
      // Focus on inputbox when click hits on rootContainer
      self.dom.inputNode.focus();
    }
  });

  // Listen to input box's input event for typing callback
  this.dom.inputNode.addEventListener('input', function(event) {
    var text = event.currentTarget.value;
    if (text === '') {
      self.dropdown.hide();
      return;
    }
    var firstIndex = utils.findFirstElement(entries, text);
    if (firstIndex >= 0) {
      var itemsToShow = utils.getItemsFromArray(
        entries,
        firstIndex,
        self._opt.searchResultsToShow
      );
      self.dropdown.updateItems(itemsToShow);
      self.dropdown.show();
    }
  });
  // Listen to input box's keydown event for functional keys
  this.dom.inputNode.addEventListener('keydown', function(event) {
    switch (event.code) {
      case 'ArrowDown':
        self.dropdown.moveToNextItem();
        break;
      case 'ArrowUp':
        self.dropdown.moveToPrevItem();
        break;
      case 'Escape':
        self.dropdown.hide();
        break;
      case 'Enter':
        // Add new tag
        var item = self.dropdown.getCurrentItem();
        if (item) {
          var itemText = dom.getTextNodeFromElement(item);
          self._onTagSelect(itemText);
        }
        break;
    }
  });
};
AutoComplete.prototype._createRootContainer = function() {
  var divNode = dom.createElement('div', {
    class: 'autocomplete-root-container'
  });
  return divNode;
};
AutoComplete.prototype._createTagsContainer = function() {
  var ulNode = dom.createElement('ul', {
    class: 'autocomplete-tags-container'
  });
  return ulNode;
};
AutoComplete.prototype._createTag = function(text) {
  var self = this;
  var createCloseButton = function() {
    var buttonNode = dom.createElement('button', {
      class: 'autocomplete-tag-close-button',
      text: 'X'
    });
    return buttonNode;
  };
  var liNode = dom.createElement('li', {
    class: 'autocomplete-tag',
    text: text || ''
  });
  var uuid = dom.autoAttachUUID(liNode);
  var closeButtonNode = createCloseButton();
  // Close button's onClick event handler
  closeButtonNode.addEventListener('click', function(event) {
    dom.removeElementByUUID(uuid);
    // Remove UUID from state
    var tagIdx = self._state.tags.indexOf(uuid);
    if (tagIdx >= 0) self._state.tags.splice(tagIdx, 1);
    // Invoke onTagsUpdate callback
    self._onTagsUpdate();
  });
  liNode.appendChild(closeButtonNode);
  return liNode;
};
AutoComplete.prototype._createInputBox = function() {
  var inputNode = dom.createElement('input', {
    class: 'autocomplete-input'
  });
  return inputNode;
};
AutoComplete.prototype._addTag = function(tagNode) {
  // Push UUID into state
  this._state.tags.push(dom.getElementUUID(tagNode));
  this.dom.tagsContainerNode.appendChild(tagNode);
  // Invoke onTagsUpdate callback
  this._onTagsUpdate();
};
AutoComplete.prototype._onTagSelect = function(itemText) {
  this._addTag(this._createTag(itemText));
  // Clean up inputbox
  this.dom.inputNode.value = '';
  // Reset dropdown menu
  this.dropdown.hide();
  this.dropdown.reset();
};
/** Return current tags label */
AutoComplete.prototype.getTags = function() {
  return this._state.tags.map(function(uuid) {
    return dom.getTextNodeFromElement(dom.findElementByUUID(uuid));
  });
};
AutoComplete.prototype._onTagsUpdate = function() {
  var tags = this.getTags();
  this._opt.onTagsUpdate.call(this, tags);
};
module.exports = AutoComplete;
<commit_msg>Replace mock data with real input<commit_after>var utils = require('./utils');
var dom = require('./dom-helper');
var Dropdown = require('./dropdown');

function AutoComplete(container, entries, opt) {
  var self = this;

  // Check params at first
  if (!container)
    throw new Error('You must assign an element to render on page!');
  if (!entries || entries.length === 0)
    throw new Error('Entries must be an non-empty array!');

  // Internal option object
  this._opt = {
    searchResultsToShow: (opt && opt.searchResultsToShow) || 5,
    onTagsUpdate: opt && opt.onTagsUpdate
  };
  // Internal state object
  this._state = {
    tags: [],
    entries: entries
  };
  // Interval DOM references
  this.dom = {
    rootContainerNode: this._createRootContainer(),
    tagsContainerNode: this._createTagsContainer(),
    inputNode: this._createInputBox()
  };
  this.dom.rootContainerNode.appendChild(this.dom.tagsContainerNode);
  this.dom.rootContainerNode.appendChild(this.dom.inputNode);

  // Create dropdown menu
  this.dropdown = new Dropdown([], {
    onItemClick: function(item) {
      self._onTagSelect(item.value);
    }
  });

  this._initializeEventHandlers();

  // Replace target container with a brand new root-container
  dom.renderTo(this.dom.rootContainerNode, container);
  // Render dropdown to the input element
  this.dropdown.renderTo(this.dom.rootContainerNode);
}
AutoComplete.prototype._initializeEventHandlers = function() {
  var self = this;

  // Extend input click area to entire root-container
  this.dom.rootContainerNode.addEventListener('click', function(event) {
    if (event.target == this) {
      // Focus on inputbox when click hits on rootContainer
      self.dom.inputNode.focus();
    }
  });

  // Listen to input box's input event for typing callback
  this.dom.inputNode.addEventListener('input', function(event) {
    var text = event.currentTarget.value;
    if (text === '') {
      self.dropdown.hide();
      return;
    }
    var firstIndex = utils.findFirstElement(self._state.entries, text);
    if (firstIndex >= 0) {
      var itemsToShow = utils.getItemsFromArray(
        self._state.entries,
        firstIndex,
        self._opt.searchResultsToShow
      );
      self.dropdown.updateItems(itemsToShow);
      self.dropdown.show();
    }
  });
  // Listen to input box's keydown event for functional keys
  this.dom.inputNode.addEventListener('keydown', function(event) {
    switch (event.code) {
      case 'ArrowDown':
        self.dropdown.moveToNextItem();
        break;
      case 'ArrowUp':
        self.dropdown.moveToPrevItem();
        break;
      case 'Escape':
        self.dropdown.hide();
        break;
      case 'Enter':
        // Add new tag
        var item = self.dropdown.getCurrentItem();
        if (item) {
          var itemText = dom.getTextNodeFromElement(item);
          self._onTagSelect(itemText);
        }
        break;
    }
  });
};
AutoComplete.prototype._createRootContainer = function() {
  var divNode = dom.createElement('div', {
    class: 'autocomplete-root-container'
  });
  return divNode;
};
AutoComplete.prototype._createTagsContainer = function() {
  var ulNode = dom.createElement('ul', {
    class: 'autocomplete-tags-container'
  });
  return ulNode;
};
AutoComplete.prototype._createTag = function(text) {
  var self = this;
  var createCloseButton = function() {
    var buttonNode = dom.createElement('button', {
      class: 'autocomplete-tag-close-button',
      text: 'X'
    });
    return buttonNode;
  };
  var liNode = dom.createElement('li', {
    class: 'autocomplete-tag',
    text: text || ''
  });
  var uuid = dom.autoAttachUUID(liNode);
  var closeButtonNode = createCloseButton();
  // Close button's onClick event handler
  closeButtonNode.addEventListener('click', function(event) {
    dom.removeElementByUUID(uuid);
    // Remove UUID from state
    var tagIdx = self._state.tags.indexOf(uuid);
    if (tagIdx >= 0) self._state.tags.splice(tagIdx, 1);
    // Invoke onTagsUpdate callback
    self._onTagsUpdate();
  });
  liNode.appendChild(closeButtonNode);
  return liNode;
};
AutoComplete.prototype._createInputBox = function() {
  var inputNode = dom.createElement('input', {
    class: 'autocomplete-input'
  });
  return inputNode;
};
AutoComplete.prototype._addTag = function(tagNode) {
  // Push UUID into state
  this._state.tags.push(dom.getElementUUID(tagNode));
  this.dom.tagsContainerNode.appendChild(tagNode);
  // Invoke onTagsUpdate callback
  this._onTagsUpdate();
};
AutoComplete.prototype._onTagSelect = function(itemText) {
  this._addTag(this._createTag(itemText));
  // Clean up inputbox
  this.dom.inputNode.value = '';
  // Reset dropdown menu
  this.dropdown.hide();
  this.dropdown.reset();
};
/** Return current tags label */
AutoComplete.prototype.getTags = function() {
  return this._state.tags.map(function(uuid) {
    return dom.getTextNodeFromElement(dom.findElementByUUID(uuid));
  });
};
AutoComplete.prototype._onTagsUpdate = function() {
  var tags = this.getTags();
  this._opt.onTagsUpdate.call(this, tags);
};
module.exports = AutoComplete;
<|endoftext|>


<commit_before>/*
 * @file This PaperScript file controls the secondary paper instance in the app
 * for adjustment and preview of autotraced import user content before it gets
 * placed into the editor.
 */
 /* globals
   $, _, paper, Layer, Group, Raster, view, project, autoTraceLoadedInit, app,
   Shape, Point, mainWindow
 */
 var jimp = require('jimp');

// Localize autotrace to be the parent window object (holds settings, paths).
var autotrace = mainWindow.overlay.windows.autotrace;
paper.strokeWidth = 5; // Custom

// Layer Management
var sepLayer = project.getActiveLayer();
var shape = new Shape.Rectangle(
  new Point(view.center.x, 0),
  new Point(view.center.x+2, view.bounds.height)
);
shape.fillColor = 'white';

var imageLayer = new Layer(); // Behind the active layer
var tempLayer = new Layer(); // Hidden Temporary layer.
tempLayer.visible = false;

var svgLayer = new Layer(); // Everything is drawn here to output
paper.svgLayer = svgLayer;

// Load Salient Helpers
_.each(['utils', 'autotrace'], function(helperName) {
  paper[helperName] = require('./helpers/helper.' + helperName)(paper);
});

// Initialize the colors to snap to based on the pancake shades.
paper.utils.snapColorSetup(app.constants.pancakeShades);

/**
 * Initially load and size the input trace image, rasterizing and outputting
 * an intermediary file at a fixed size.
 * @return {Promise}
 *   When promise is resolved, autotrace.tracebmp is saved & ready.
 */
paper.loadTraceImage = function() {
  imageLayer.removeChildren();
  imageLayer.activate();

  // Return promise to manage execution/failure.
  return new Promise(function(resolve, reject) {
    try {
      paper.traceImg = new Group([new Raster({
        source: autotrace.source,
        position: view.center
      })]);

      paper.traceImg.img = paper.traceImg.children[0];

      // When the image actually loads...
      paper.traceImg.img.onLoad = function() {
        // Size the image down
        var scale = {
          x: (view.bounds.width * 0.4) / this.width,
          y: (view.bounds.height * 0.8) / this.height
        };

        paper.traceImg.pInitialBounds = this.bounds;

        // Use the smallest scale.
        scale = (scale.x < scale.y ? scale.x : scale.y);
        paper.traceImg.scale(scale);
        paper.traceImg.position.x = view.bounds.width / 4;

        // Finish off by saving the image out as a base resized PNG.
        var tmpFile = autotrace.intermediary;
        paper.utils.saveRasterImage(paper.traceImg, 72, tmpFile).then(resolve);
      };
    } catch(e) {
      reject(Error(e));
    }
  });
};

/**
 * Render the trace raster intermediary image through jimp for extra processing
 * to create the final raster for tracing.
 * @param {String} [sourceFile=autotrace.intermediary]
 *   Souce input file to be converted to output BMP for tracing. If not given,
 *   will default to autotrace.intermediary.
 * @param {Object} [extraOptions={}]
 *   Optional extra options to be added for output.
 * @return {Promise}
 *   When promise is resolved, autotrace.tracebmp is saved & ready.
 */
paper.renderTraceImage = function(
  sourceFile = autotrace.intermediary,
  extraOptions = {}
) {

  return new Promise(function(resolve) {
    jimp.read(sourceFile)
    .then(function(img){
      if (extraOptions.mask) {
        return paper.maskImage(img, extraOptions.mask);
      } else {
        return img;
      }
    })
    .then(function(img) {
      // Background color
      var intColor = parseInt(
        autotrace.settings.transparent.replace('#', '0x') + 'FF'
      );
      img.background(intColor);

      // Blur.
      if (autotrace.settings.blur !== '0') {
        img.blur(parseInt(autotrace.settings.blur));
      }

      // Invert
      if (autotrace.settings.invert) {
        img.invert();
      }

      // Write final file.
      img.write(autotrace.tracebmp, function() {
        resolve();
      });
    });
  });
};

/**
 * Given a JIMP image, mask transparency given a bw/image given in mask object.
 * @param  {JIMP.image} img
 *   Image to be masked.
 * @param  {Object} mask
 *   Object containing offset {x, y} & mask.image JIMP image.
 * @return {Promise}
 *   Resolved promise returns image with mask applied.
 */
paper.maskImage = function(img, mask) {
  return new Promise(function(resolve) {
    jimp.read(mask.image).then(function(maskImg) {
      resolve(img.mask(maskImg, mask.offset.x, mask.offset.y));
    });
  });
};

/**
 * Render and display trace..
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
paper.renderTraceVector = function() {
  tempLayer.activate();
  tempLayer.removeChildren();

  switch (autotrace.settings.tracetype) {
    case 'mixed':
      return renderMixedVector();
    case 'fills':
      return renderFillsVector();
    case 'lines':
      return renderLinesVector();
  }
};

/**
 * Cleanup the image specific bits so we don't see them on next load.
 */
paper.cleanup = function() {
  svgLayer.removeChildren();
  imageLayer.removeChildren();
  $('div.trace-preview img.trace').remove();
};

//==============================================================================

/**
 * Render a fill only vector trace from the source bitmap.
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
function renderFillsVector() {
  var fills;
  var options = {
    backgroundColor: autotrace.settings.transparent.substr(1),
    colorCount: autotrace.settings.posterize,
  };

  var img = autotrace.tracebmp;
  return new Promise(function(resolve, reject) {
    paper.autotrace.getImageFills(img, options).then(function(data) {
      fills = tempLayer.importSVG(data);
      if (fills) {
        autotrace.paper.activate();
        paper.tracedGroup = fills;

        paper.tracedGroup.position.y = view.center.y;
        paper.tracedGroup.position.x = (view.bounds.width / 4) * 3;

        // Remove any previous work and append built data to svgLayer.
        svgLayer.removeChildren();
        svgLayer.addChild(paper.tracedGroup);

        // Normalize & recolor the final trace.
        normalizeSVG();

        // Resolve the promise.
        resolve();
      } else {
        reject(Error('No data returned from trace.'));
      }
    });
  });
}

/**
 * Render a centerline only vector trace from the source bitmap.
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
function renderLinesVector() {
  var lines;
  var options = {
    backgroundColor: autotrace.settings.transparent.substr(1),
    colorCount: autotrace.settings.posterize,
  };

  var img = autotrace.tracebmp;
  return new Promise(function(resolve, reject) {
    paper.autotrace.getImageLines(img, options).then(function(data) {
      lines = tempLayer.importSVG(data);
      if (lines) {
        lines.strokeWidth = 5;
        autotrace.paper.activate();
        paper.utils.recursiveLengthCull(lines, 8);
        paper.tracedGroup = lines;

        paper.tracedGroup.position.y = view.center.y;
        paper.tracedGroup.position.x = (view.bounds.width / 4) * 3;

        // Remove any previous work and append built data to svgLayer.
        svgLayer.removeChildren();
        svgLayer.addChild(paper.tracedGroup);

        // Normalize & recolor the final trace.
        normalizeSVG();

        // Resolve the promise.
        resolve();
      } else {
        reject(Error('No data returned from trace.'));
      }
    });
  });
}

/**
 * Render a mixed line/fill vector trace from the source bitmap.
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
function renderMixedVector() {
  var lines, fills;
  var options = {
    backgroundColor: autotrace.settings.transparent.substr(1),
    colorCount: autotrace.settings.posterize,
  };

  var img = autotrace.tracebmp;
  return new Promise(function(resolve, reject) {
    paper.autotrace.getImageLines(img, options).then(function(data) {
      lines = tempLayer.importSVG(data);
      autotrace.paper.activate();
      paper.tracedGroup = new Group([lines]);
      lines.strokeWidth = 5;
      paper.utils.recursiveLengthCull(lines, 8); // Clean up noise lines.
      return paper.autotrace.getImageFills(img, options);
    }).then(function(data) {
      fills = tempLayer.importSVG(data);

      // Reject the promise at this point as we have no lines or fills.
      if (!fills && !lines) {
        reject(Error('No data returned from trace.'));
      }

      paper.utils.flattenSubtractLayer(fills);
      paper.utils.destroyThinFeatures(fills, autotrace.offset);
      paper.tracedGroup.addChildren(fills.children);

      paper.tracedGroup.position.y = view.center.y;
      paper.tracedGroup.position.x = (view.bounds.width / 4) * 3;

      // Remove any previous work and append built data to svgLayer.
      svgLayer.removeChildren();
      svgLayer.addChild(paper.tracedGroup);

      normalizeSVG();

      // Resolve the promise.
      resolve();
    });
  });
}

/**
 * Normalize, cleanup & colorize the SVG created by the trace functions.
 */
function normalizeSVG() {
  autotrace.paper.activate();
  paper.utils.ungroupAllGroups(svgLayer);

  // Limit available autocolors for 1 color (2p) traces to the lightest shade.
  var limit = 4;
  if (autotrace.settings.posterize === '2') {
    limit = 1;
  }
  paper.utils.autoColor(svgLayer, limit);

  // Generate raster preview.
  var previewRaster = svgLayer.rasterize(72);
  autotrace.previewRasterData = previewRaster.toDataURL();
  previewRaster.remove();
// HOVER/CLICK REMOVE ==========================================================
// =============================================================================
var hitOptions = {
  stroke: true,
  fill: true,
  tolerance: 5
};

function onMouseDown(event) { /* jshint ignore:line */
  var hitResult = project.hitTest(event.point, hitOptions);
  if (!hitResult) return;

  if (hitResult) {
    hitResult.item.remove();
    paper.renderPreviewRaster();
    autotrace.clonePreview();
  }
}

function onMouseMove(event) { /* jshint ignore:line */
  svgLayer.selected = false;
  if (event.item && event.item.parent === svgLayer) {
    event.item.selected = true;
  }
}

// Autotrace preview should be done loading, trigger loadInit
autoTraceLoadedInit();
<commit_msg>Flatten subtract on fill only trace<commit_after>/*
 * @file This PaperScript file controls the secondary paper instance in the app
 * for adjustment and preview of autotraced import user content before it gets
 * placed into the editor.
 */
 /* globals
   $, _, paper, Layer, Group, Raster, view, project, autoTraceLoadedInit, app,
   Shape, Point, mainWindow
 */
 var jimp = require('jimp');

// Localize autotrace to be the parent window object (holds settings, paths).
var autotrace = mainWindow.overlay.windows.autotrace;
paper.strokeWidth = 5; // Custom

// Layer Management
var sepLayer = project.getActiveLayer();
var shape = new Shape.Rectangle(
  new Point(view.center.x, 0),
  new Point(view.center.x+2, view.bounds.height)
);
shape.fillColor = 'white';

var imageLayer = new Layer(); // Behind the active layer
var tempLayer = new Layer(); // Hidden Temporary layer.
tempLayer.visible = false;

var svgLayer = new Layer(); // Everything is drawn here to output
paper.svgLayer = svgLayer;

// Load Salient Helpers
_.each(['utils', 'autotrace'], function(helperName) {
  paper[helperName] = require('./helpers/helper.' + helperName)(paper);
});

// Initialize the colors to snap to based on the pancake shades.
paper.utils.snapColorSetup(app.constants.pancakeShades);

/**
 * Initially load and size the input trace image, rasterizing and outputting
 * an intermediary file at a fixed size.
 * @return {Promise}
 *   When promise is resolved, autotrace.tracebmp is saved & ready.
 */
paper.loadTraceImage = function() {
  imageLayer.removeChildren();
  imageLayer.activate();

  // Return promise to manage execution/failure.
  return new Promise(function(resolve, reject) {
    try {
      paper.traceImg = new Group([new Raster({
        source: autotrace.source,
        position: view.center
      })]);

      paper.traceImg.img = paper.traceImg.children[0];

      // When the image actually loads...
      paper.traceImg.img.onLoad = function() {
        // Size the image down
        var scale = {
          x: (view.bounds.width * 0.4) / this.width,
          y: (view.bounds.height * 0.8) / this.height
        };

        paper.traceImg.pInitialBounds = this.bounds;

        // Use the smallest scale.
        scale = (scale.x < scale.y ? scale.x : scale.y);
        paper.traceImg.scale(scale);
        paper.traceImg.position.x = view.bounds.width / 4;

        // Finish off by saving the image out as a base resized PNG.
        var tmpFile = autotrace.intermediary;
        paper.utils.saveRasterImage(paper.traceImg, 72, tmpFile).then(resolve);
      };
    } catch(e) {
      reject(Error(e));
    }
  });
};

/**
 * Render the trace raster intermediary image through jimp for extra processing
 * to create the final raster for tracing.
 * @param {String} [sourceFile=autotrace.intermediary]
 *   Souce input file to be converted to output BMP for tracing. If not given,
 *   will default to autotrace.intermediary.
 * @param {Object} [extraOptions={}]
 *   Optional extra options to be added for output.
 * @return {Promise}
 *   When promise is resolved, autotrace.tracebmp is saved & ready.
 */
paper.renderTraceImage = function(
  sourceFile = autotrace.intermediary,
  extraOptions = {}
) {

  return new Promise(function(resolve) {
    jimp.read(sourceFile)
    .then(function(img){
      if (extraOptions.mask) {
        return paper.maskImage(img, extraOptions.mask);
      } else {
        return img;
      }
    })
    .then(function(img) {
      // Background color
      var intColor = parseInt(
        autotrace.settings.transparent.replace('#', '0x') + 'FF'
      );
      img.background(intColor);

      // Blur.
      if (autotrace.settings.blur !== '0') {
        img.blur(parseInt(autotrace.settings.blur));
      }

      // Invert
      if (autotrace.settings.invert) {
        img.invert();
      }

      // Write final file.
      img.write(autotrace.tracebmp, function() {
        resolve();
      });
    });
  });
};

/**
 * Given a JIMP image, mask transparency given a bw/image given in mask object.
 * @param  {JIMP.image} img
 *   Image to be masked.
 * @param  {Object} mask
 *   Object containing offset {x, y} & mask.image JIMP image.
 * @return {Promise}
 *   Resolved promise returns image with mask applied.
 */
paper.maskImage = function(img, mask) {
  return new Promise(function(resolve) {
    jimp.read(mask.image).then(function(maskImg) {
      resolve(img.mask(maskImg, mask.offset.x, mask.offset.y));
    });
  });
};

/**
 * Render and display trace..
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
paper.renderTraceVector = function() {
  tempLayer.activate();
  tempLayer.removeChildren();

  switch (autotrace.settings.tracetype) {
    case 'mixed':
      return renderMixedVector();
    case 'fills':
      return renderFillsVector();
    case 'lines':
      return renderLinesVector();
  }
};

/**
 * Cleanup the image specific bits so we don't see them on next load.
 */
paper.cleanup = function() {
  svgLayer.removeChildren();
  imageLayer.removeChildren();
  $('div.trace-preview img.trace').remove();
};

//==============================================================================

/**
 * Render a fill only vector trace from the source bitmap.
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
function renderFillsVector() {
  var fills;
  var options = {
    backgroundColor: autotrace.settings.transparent.substr(1),
    colorCount: autotrace.settings.posterize,
  };

  var img = autotrace.tracebmp;
  return new Promise(function(resolve, reject) {
    paper.autotrace.getImageFills(img, options).then(function(data) {
      fills = tempLayer.importSVG(data);
      if (fills) {
        autotrace.paper.activate();
        paper.tracedGroup = fills;

        paper.tracedGroup.position.y = view.center.y;
        paper.tracedGroup.position.x = (view.bounds.width / 4) * 3;

        // Remove any previous work and append built data to svgLayer.
        svgLayer.removeChildren();
        svgLayer.addChild(paper.tracedGroup);

        // Normalize & recolor the final trace.
        normalizeSVG();

        paper.utils.flattenSubtractLayer(svgLayer);

        // Resolve the promise.
        resolve();
      } else {
        reject(Error('No data returned from trace.'));
      }
    });
  });
}

/**
 * Render a centerline only vector trace from the source bitmap.
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
function renderLinesVector() {
  var lines;
  var options = {
    backgroundColor: autotrace.settings.transparent.substr(1),
    colorCount: autotrace.settings.posterize,
  };

  var img = autotrace.tracebmp;
  return new Promise(function(resolve, reject) {
    paper.autotrace.getImageLines(img, options).then(function(data) {
      lines = tempLayer.importSVG(data);
      if (lines) {
        lines.strokeWidth = 5;
        autotrace.paper.activate();
        paper.utils.recursiveLengthCull(lines, 8);
        paper.tracedGroup = lines;

        paper.tracedGroup.position.y = view.center.y;
        paper.tracedGroup.position.x = (view.bounds.width / 4) * 3;

        // Remove any previous work and append built data to svgLayer.
        svgLayer.removeChildren();
        svgLayer.addChild(paper.tracedGroup);

        // Normalize & recolor the final trace.
        normalizeSVG();

        // Resolve the promise.
        resolve();
      } else {
        reject(Error('No data returned from trace.'));
      }
    });
  });
}

/**
 * Render a mixed line/fill vector trace from the source bitmap.
 * @return {Promise}
 *   When promise is resolved, tracing is complete.
 */
function renderMixedVector() {
  var lines, fills;
  var options = {
    backgroundColor: autotrace.settings.transparent.substr(1),
    colorCount: autotrace.settings.posterize,
  };

  var img = autotrace.tracebmp;
  return new Promise(function(resolve, reject) {
    paper.autotrace.getImageLines(img, options).then(function(data) {
      lines = tempLayer.importSVG(data);
      autotrace.paper.activate();
      paper.tracedGroup = new Group([lines]);
      lines.strokeWidth = 5;
      paper.utils.recursiveLengthCull(lines, 8); // Clean up noise lines.
      return paper.autotrace.getImageFills(img, options);
    }).then(function(data) {
      fills = tempLayer.importSVG(data);

      // Reject the promise at this point as we have no lines or fills.
      if (!fills && !lines) {
        reject(Error('No data returned from trace.'));
      }

      paper.utils.flattenSubtractLayer(fills);
      paper.utils.destroyThinFeatures(fills, autotrace.offset);
      paper.tracedGroup.addChildren(fills.children);

      paper.tracedGroup.position.y = view.center.y;
      paper.tracedGroup.position.x = (view.bounds.width / 4) * 3;

      // Remove any previous work and append built data to svgLayer.
      svgLayer.removeChildren();
      svgLayer.addChild(paper.tracedGroup);

      normalizeSVG();

      // Resolve the promise.
      resolve();
    });
  });
}

/**
 * Normalize, cleanup & colorize the SVG created by the trace functions.
 */
function normalizeSVG() {
  autotrace.paper.activate();
  paper.utils.ungroupAllGroups(svgLayer);

  // Limit available autocolors for 1 color (2p) traces to the lightest shade.
  var limit = 4;
  if (autotrace.settings.posterize === '2') {
    limit = 1;
  }
  paper.utils.autoColor(svgLayer, limit);

  // Generate raster preview.
  var previewRaster = svgLayer.rasterize(72);
  autotrace.previewRasterData = previewRaster.toDataURL();
  previewRaster.remove();
// HOVER/CLICK REMOVE ==========================================================
// =============================================================================
var hitOptions = {
  stroke: true,
  fill: true,
  tolerance: 5
};

function onMouseDown(event) { /* jshint ignore:line */
  var hitResult = project.hitTest(event.point, hitOptions);
  if (!hitResult) return;

  if (hitResult) {
    hitResult.item.remove();
    paper.renderPreviewRaster();
    autotrace.clonePreview();
  }
}

function onMouseMove(event) { /* jshint ignore:line */
  svgLayer.selected = false;
  if (event.item && event.item.parent === svgLayer) {
    event.item.selected = true;
  }
}

// Autotrace preview should be done loading, trigger loadInit
autoTraceLoadedInit();
<|endoftext|>


<commit_before>import path from 'path'
import express from 'express'
import bodyParser from 'body-parser'
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express'

import { enableGraphiQL } from '../config'
import schema from './schema'
import serverRender from '../front-end/server'
import logFileApi from './log-file-api'

const app = express()

app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }))

if (enableGraphiQL) {
  app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }))
}

app.use(express.static(path.join(__dirname, '../../dist/public')))

app.use(logFileApi())

app.use(serverRender())

export default app
<commit_msg>Add caching to static files<commit_after>import path from 'path'
import express from 'express'
import bodyParser from 'body-parser'
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express'

import { enableGraphiQL } from '../config'
import schema from './schema'
import serverRender from '../front-end/server'
import logFileApi from './log-file-api'

const app = express()

app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }))

if (enableGraphiQL) {
  app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }))
}

app.use(express.static(
  path.join(__dirname, '../../dist/public'),
  { maxAge: '1y' }
))

app.use(logFileApi())

app.use(serverRender())

export default app
<|endoftext|>


<commit_before>var olapi = "https://openlayers.org/en/v4.6.5/apidoc/";
var lfapi = "http://leafletjs.com/reference-1.3.1.html";
var mbglapi = "https://www.mapbox.com/mapbox-gl-js/api/";
var mapv = "https://github.com/huiyan-fe/mapv/blob/master/src/";
var classicapi="http://iclient.supermap.io/libs/iclient8c/apidoc/files/SuperMap"
var geojsonapi = "http://geojson.org";
var typeLinks = {
    //openlayers
    "ol.Map": olapi + "ol.Map.html",
    "ol.View": olapi + "ol.View.html",
    "ol.extent": olapi + "ol.extent.html",
    "ol.feature": olapi + "ol.feature.html",
    "ol.geom.Polygon": olapi + "ol.geom.Polygon.html",
    "ol.geom.LineString": olapi + "ol.geom.LineString.html",
    "ol.geom.Point": olapi + "ol.geom.Point.html",
    "ol.geom.Geometry":olapi + "ol.geom.Geometry.html",
    "ol.format.GeoJSON": olapi + "ol.format.GeoJSON.html",
    "ol.proj.Projection": olapi + "ol.proj.Projection",
    "ol.Observable": olapi + "ol.Observable",
    "ol.style.Image": olapi + "ol.style.Image",
    "ol.style.Fill": olapi + "ol.style.Fill",
    "ol.style.Stroke": olapi + "ol.style.Stroke",
    "ol.Object": olapi + "ol.Object",
    "ol.source.ImageCanvas": olapi + "ol.source.ImageCanvas",
    "ol.source.TileImage": olapi + "ol.source.TileImage",
    "ol.source.WMTS": olapi + "ol.source.WMTS",
    "ol.source.XYZ": olapi + "ol.source.XYZ",
    "ol.source.Vector": olapi + "ol.source.Vector",
    "ol.source.VectorTile": olapi + "ol.source.VectorTile",
    "ol.Pixel": olapi + "ol.html#.Pixel",
    "ol.source.State": olapi + "ol.source.html#.State",
    "ol.layer.Layer": olapi + "ol.layer.Layer.html",
    "ol.FeatureStyleFunction": olapi + "ol.html#.FeatureStyleFunction",
    "ol.StyleFunction": olapi + "ol.html#.StyleFunction",
    "ol.control.ScaleLine": olapi + "ol.control.ScaleLine",

    //leaflet
    "L.Marker": lfapi + '#marker',
    "L.Bounds": lfapi + "#bounds",
    "L.Polygon": lfapi + "#polygon",
    "L.Polyline": lfapi + "#polyline",
    "L.Point": lfapi + "#point",
    "L.LatLng": lfapi + "#latlng",
    "L.GeoJSON": lfapi + "#geojson",
    "L.Control": lfapi + "#control",
    "L.Class": lfapi + "#class",
    "L.GridLayer": lfapi + '#gridlayer',
    "L.Path": lfapi + '#path',
    "L.SVG": lfapi + '#svg',
    "L.Canvas": lfapi + '#canvas',
    "L.Layer": lfapi + '#layer',
    "L.LayerGroup": lfapi + '#layergroup',
    "L.TileLayer": lfapi + '#tilelayer',
    "L.CircleMarker": lfapi + '#circlemarker',
    "L.Path-option": lfapi + '#path-option',
    "L.Rectangle": lfapi + '#rectangle',
    'L.LatLngBounds': lfapi+ '#latlngbounds',
    'L.Map': lfapi + '#map-example',
    'L.Evented':lfapi +'#evented',

    //mapboxgl
    "mapboxgl.Evented": mbglapi + '#Evented',
    "mapboxgl.Map": mbglapi + '#map',
    "mapboxgl.LngLatbounds": mbglapi + '#lnglatbounds',
    //mapv
    "Mapv.DataSet": mapv + 'data/DataSet.md',
    "Mapv.BaiduMapLayer": mapv + 'map/baidu-map/Layer.md',

    //classic
    "SuperMap.Layer":classicapi + '/Layer-js.html',
    "SuperMap.Layer.Graph": classicapi + '/Layer/Theme/Graph-js.html#SuperMap.Layer.Graph',

	//GeoJSON
    "GeoJSONObject": geojsonapi

}
exports.typeLinks = typeLinks;<commit_msg>【fix】更新api链接地址  review by liqian<commit_after>var olapi = "https://openlayers.org/en/v4.6.5/apidoc/";
var lfapi = "http://leafletjs.com/reference-1.5.1.html";
var mbglapi = "https://www.mapbox.com/mapbox-gl-js/api/";
var mapv = "https://github.com/huiyan-fe/mapv/blob/master/src/";
var classicapi="http://iclient.supermap.io/libs/iclient8c/apidoc/files/SuperMap"
var geojsonapi = "http://geojson.org";
var typeLinks = {
    //openlayers
    "ol.Map": olapi + "ol.Map.html",
    "ol.View": olapi + "ol.View.html",
    "ol.extent": olapi + "ol.extent.html",
    "ol.feature": olapi + "ol.feature.html",
    "ol.geom.Polygon": olapi + "ol.geom.Polygon.html",
    "ol.geom.LineString": olapi + "ol.geom.LineString.html",
    "ol.geom.Point": olapi + "ol.geom.Point.html",
    "ol.geom.Geometry":olapi + "ol.geom.Geometry.html",
    "ol.format.GeoJSON": olapi + "ol.format.GeoJSON.html",
    "ol.proj.Projection": olapi + "ol.proj.Projection",
    "ol.Observable": olapi + "ol.Observable",
    "ol.style.Image": olapi + "ol.style.Image",
    "ol.style.Fill": olapi + "ol.style.Fill",
    "ol.style.Stroke": olapi + "ol.style.Stroke",
    "ol.Object": olapi + "ol.Object",
    "ol.source.ImageCanvas": olapi + "ol.source.ImageCanvas",
    "ol.source.TileImage": olapi + "ol.source.TileImage",
    "ol.source.WMTS": olapi + "ol.source.WMTS",
    "ol.source.XYZ": olapi + "ol.source.XYZ",
    "ol.source.Vector": olapi + "ol.source.Vector",
    "ol.source.VectorTile": olapi + "ol.source.VectorTile",
    "ol.Pixel": olapi + "ol.html#.Pixel",
    "ol.source.State": olapi + "ol.source.html#.State",
    "ol.layer.Layer": olapi + "ol.layer.Layer.html",
    "ol.FeatureStyleFunction": olapi + "ol.html#.FeatureStyleFunction",
    "ol.StyleFunction": olapi + "ol.html#.StyleFunction",
    "ol.control.ScaleLine": olapi + "ol.control.ScaleLine",

    //leaflet
    "L.Marker": lfapi + '#marker',
    "L.Bounds": lfapi + "#bounds",
    "L.Polygon": lfapi + "#polygon",
    "L.Polyline": lfapi + "#polyline",
    "L.Point": lfapi + "#point",
    "L.LatLng": lfapi + "#latlng",
    "L.GeoJSON": lfapi + "#geojson",
    "L.Control": lfapi + "#control",
    "L.Class": lfapi + "#class",
    "L.GridLayer": lfapi + '#gridlayer',
    "L.Path": lfapi + '#path',
    "L.SVG": lfapi + '#svg',
    "L.Canvas": lfapi + '#canvas',
    "L.Layer": lfapi + '#layer',
    "L.LayerGroup": lfapi + '#layergroup',
    "L.TileLayer": lfapi + '#tilelayer',
    "L.CircleMarker": lfapi + '#circlemarker',
    "L.Path-option": lfapi + '#path-option',
    "L.Rectangle": lfapi + '#rectangle',
    'L.LatLngBounds': lfapi+ '#latlngbounds',
    'L.Map': lfapi + '#map-example',
    'L.Evented':lfapi +'#evented',

    //mapboxgl
    "mapboxgl.Evented": mbglapi + '#Evented',
    "mapboxgl.Map": mbglapi + '#map',
    "mapboxgl.LngLatbounds": mbglapi + '#lnglatbounds',
    //mapv
    "Mapv.DataSet": mapv + 'data/DataSet.md',
    "Mapv.BaiduMapLayer": mapv + 'map/baidu-map/Layer.md',

    //classic
    "SuperMap.Layer":classicapi + '/Layer-js.html',
    "SuperMap.Layer.Graph": classicapi + '/Layer/Theme/Graph-js.html#SuperMap.Layer.Graph',

	//GeoJSON
    "GeoJSONObject": geojsonapi

}
exports.typeLinks = typeLinks;<|endoftext|>


<commit_before>import { useState, useCallback, useEffect } from 'react';

const useMediaQuery = width => {
  const [targetReached, setTargetReached] = useState(false);
  const updateTarget = useCallback(e => {
    if (e.matches) {
      setTargetReached(true);
    } else {
      setTargetReached(false);
    }
  }, []);
  useEffect(() => {
    const media = window.matchMedia(`(max-width: ${width}px)`);
    media.addListener(updateTarget); // Check on mount (callback is not called until a change occurs)

    if (media.matches) {
      setTargetReached(true);
    }

    return () => media.removeListener(updateTarget);
  }, []);
  return targetReached;
};

const useIsMobile = () => {
  return useMediaQuery(640);
};

export { useMediaQuery, useIsMobile };<commit_msg>docs: fix documentation menu breakpoint<commit_after>import { useState, useCallback, useEffect } from 'react'

const useMediaQuery = width => {
  const [targetReached, setTargetReached] = useState(false)
  const updateTarget = useCallback(e => {
    if (e.matches) {
      setTargetReached(true)
    } else {
      setTargetReached(false)
    }
  }, [])
  useEffect(() => {
    const media = window.matchMedia(`(max-width: ${width}px)`)
    media.addListener(updateTarget) // Check on mount (callback is not called until a change occurs)

    if (media.matches) {
      setTargetReached(true)
    }

    return () => media.removeListener(updateTarget)
  }, [])
  return targetReached
}

const useIsMobile = () => {
  return useMediaQuery(1024)
}

export { useMediaQuery, useIsMobile }
<|endoftext|>


<commit_before>/** Menu module for showing nice context menus */
var menu = (function (){
var menu = {};

/** Menu id */
var _menuId = 'inline-menu';

/** Escape HTML Entitites */
function htmlEntities(str) {
  return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

/** Launch a menu under element el */
menu.launch = function(el){
  var x, y;
  x = menu.posLeft(el);
  y = menu.posTop(el) + el.offsetHeight;
  menu.launchAt(x, y);
};

/** Populate menu
 * links is a list of JSON objects with href, title, icon, text
 */
menu.populate = function(links){
  var content = ""
  for(var i = 0; i < links.length; i++){
    var link = links[i];
    var icon = wwwroot + "/static/icons/" + link.icon + ".png";
    content += "";
    content += htmlEntities(link.text) + "";
  }
  var m = document.getElementById(_menuId);
  m.innerHTML = content;
};

/** Launch menu at x, y */
menu.launchAt = function(x, y){
  var m = document.getElementById(_menuId);
  m.style.left    = x + "px";
  m.style.top     = y + "px";
  m.style.display = 'block';
};

/** Find position of el from top */
menu.posTop = function(el){
  var top = 0;
  do{
    top += el.offsetTop;
  }while(el = el.offsetParent);
  return top;
};

/** Find position of el from left */
menu.posLeft = function(el){
  var left = 0;
  do{
    left += el.offsetLeft;
  }while(el = el.offsetParent);
  return left;
};

/** Hide menu */
menu.hide = function(){
  var m = document.getElementById(_menuId);
  m.style.display = 'none';
};

/** Initialize module */
window.addEventListener('load', function(){
  // On mousedown we hide the menu
  window.addEventListener('mousedown', menu.hide, false);

  // Stop event from propergating to window
  var m = document.getElementById(_menuId);
  m.addEventListener('mousedown', function(e) {
    e.stopPropagation();
  }, false);
}, false);

// Export menu as defined here
return menu;
}());
<commit_msg>Hide the popup menu when the user follows a link<commit_after>/** Menu module for showing nice context menus */
var menu = (function (){
var menu = {};

/** Menu id */
var _menuId = 'inline-menu';

/** Escape HTML Entitites */
function htmlEntities(str) {
  return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

/** Launch a menu under element el */
menu.launch = function(el){
  var x, y;
  x = menu.posLeft(el);
  y = menu.posTop(el) + el.offsetHeight;
  menu.launchAt(x, y);
};

/** Populate menu
 * links is a list of JSON objects with href, title, icon, text
 */
menu.populate = function(links){
  var content = ""
  for(var i = 0; i < links.length; i++){
    var link = links[i];
    var icon = wwwroot + "/static/icons/" + link.icon + ".png";
    content += "";
    content += htmlEntities(link.text) + "";
  }
  var m = document.getElementById(_menuId);
  m.innerHTML = content;
};

/** Launch menu at x, y */
menu.launchAt = function(x, y){
  var m = document.getElementById(_menuId);
  m.style.left    = x + "px";
  m.style.top     = y + "px";
  m.style.display = 'block';
};

/** Find position of el from top */
menu.posTop = function(el){
  var top = 0;
  do{
    top += el.offsetTop;
  }while(el = el.offsetParent);
  return top;
};

/** Find position of el from left */
menu.posLeft = function(el){
  var left = 0;
  do{
    left += el.offsetLeft;
  }while(el = el.offsetParent);
  return left;
};

/** Hide menu */
menu.hide = function(){
  var m = document.getElementById(_menuId);
  m.style.display = 'none';
};

/** Initialize module */
window.addEventListener('load', function(){
  // On mousedown we hide the menu
  window.addEventListener('mousedown', menu.hide, false);

  // Stop event from propergating to window
  var m = document.getElementById(_menuId);
  m.addEventListener('mousedown', function(e) {
    e.stopPropagation();
  }, false);
}, false);

// Export menu as defined here
return menu;
}());
<|endoftext|>


<commit_before>"use strict";

import {StructureAlignmentUtils} from "./structure-alignment-utils";
import {StructureUtils} from "./stucture-utils";

export class LinkablePositionUtils {

    static getRenderedDistanceArray( renderedLinks, linkExclusionHandler ) {

        let distanceArray = [ ];
        let UDRsCounted = { };

        if( renderedLinks.crosslinks ) {
            for (let i = 0; i < renderedLinks['crosslinks'].length; i++) {

                const link = renderedLinks['crosslinks'][i]['link'];

                if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                    LinkablePositionUtils.addCrosslinkToCountedUDRs({UDRsCounted, link})

                    distanceArray.push(parseFloat(renderedLinks['crosslinks'][i]['link']['length']));
                }
            }
        }

        if( renderedLinks.looplinks ) {
            for (let i = 0; i < renderedLinks['looplinks'].length; i++) {

                const link = renderedLinks['looplinks'][i]['link'];

                if( !LinkablePositionUtils.isUDRinRenderedUDRs( {
                    renderedUDRs: UDRsCounted,
                    protein1: link.protein1,
                    protein2: link.protein1,
                    position1: link.position1,
                    position2: link.position2 } )) {
                    if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {

                        console.log( 'added looplink:' );
                        console.log( link );

                        distanceArray.push(parseFloat(renderedLinks['looplinks'][i]['link']['length']));
                    }
                }
            }
        }

        return distanceArray;
    }

    static getRenderedUDRs({ renderedLinks, linkExclusionHandler }) {

        let renderedUDRs = { };

        if( renderedLinks.crosslinks ) {
            for (let i = 0; i < renderedLinks['crosslinks'].length; i++) {

                const link = renderedLinks['crosslinks'][i]['link'];

                if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                    LinkablePositionUtils.addCrosslinkToCountedUDRs({UDRsCounted: renderedUDRs, link})
                }
            }
        }

        if( renderedLinks.looplinks ) {
            for (let i = 0; i < renderedLinks['looplinks'].length; i++) {

                const link = renderedLinks['looplinks'][i]['link'];

                if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                    LinkablePositionUtils.addLooplinkToCountedUDRs({UDRsCounted: renderedUDRs, link})
                }
            }
        }

        return renderedUDRs;
    }

    static addCrosslinkToCountedUDRs({UDRsCounted,link}) {
        const protein1 = link['protein1'];
        const protein2 = link['protein2'];
        const position1 = link['position1'];
        const position2 = link['position2'];

        // add this to the list of UDRs we've counted so we can calculated total unique UDRs among cross- and loop-links
        if( !( protein1 in UDRsCounted ) ) { UDRsCounted[ protein1 ] = { }; }
        if( !( protein2 in UDRsCounted[ protein1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ] = { }; }
        if( !( position1 in UDRsCounted[ protein1 ][ protein2 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ] = { }; };
        if( !( position2 in UDRsCounted[ protein1 ][ protein2 ][ position1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ][ position2 ] = { }; };
    }

    static addLooplinkToCountedUDRs({UDRsCounted,link}) {
        const protein1 = link['protein1'];
        const protein2 = link['protein1'];
        const position1 = link['position1'];
        const position2 = link['position2'];

        // add this to the list of UDRs we've counted so we can calculated total unique UDRs among cross- and loop-links
        if( !( protein1 in UDRsCounted ) ) { UDRsCounted[ protein1 ] = { }; }
        if( !( protein2 in UDRsCounted[ protein1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ] = { }; }
        if( !( position1 in UDRsCounted[ protein1 ][ protein2 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ] = { }; };
        if( !( position2 in UDRsCounted[ protein1 ][ protein2 ][ position1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ][ position2 ] = { }; };
    }

    static isUDRinRenderedUDRs({ renderedUDRs, protein1, protein2, position1, position2 } ) {

        // console.log( renderedUDRs );
        // console.log( protein1 );
        // console.log( protein2 );
        // console.log( position1 );
        // console.log( position2 );
        // console.log( "=============" );
        // console.log( renderedUDRs[ protein1 ] );
        // console.log( renderedUDRs[ protein1 ][ protein2 ] );
        // console.log( renderedUDRs[ protein1 ][ protein2 ][ position1 ] );
        // console.log( renderedUDRs[ protein1 ][ protein2 ][ position1 ][ position2 ] );
        // console.log( "=============" );

        if( protein1 in renderedUDRs ) {

            if( protein2 in renderedUDRs[ protein1 ] &&
            position1 in renderedUDRs[ protein1 ][ protein2 ] &&
            position2 in renderedUDRs[ protein1 ][ protein2 ][ position1 ] ) {
                return true;
            }

            // test swapping positions if it's within the same protein
            if( protein1 === protein2 ) {
                if( protein2 in renderedUDRs[ protein1 ] &&
                    position2 in renderedUDRs[ protein1 ][ protein2 ] &&
                    position1 in renderedUDRs[ protein1 ][ protein2 ][ position2 ] ) {
                    return true;
                }
            }

        } else if( protein1 !== protein2 && protein2 in renderedUDRs ) {

            if( protein1 in renderedUDRs[ protein2 ] &&
                position2 in renderedUDRs[ protein2 ][ protein1 ] &&
                position1 in renderedUDRs[ protein2 ][ protein1 ][ position2 ] ) {
                return true;
            }

        }

        return false;
    }

    static getDistanceArrayFromLinkablePositions( {
                                                      data,
                                                      visibleProteinsMap,
                                                      onlyShortest,
                                                      alignments,
                                                      structure,
                                                      linkExclusionHandler,
                                                      renderedLinks
                                                    }) {

        const pdbDistanceArray = [ ];

        for( let i = 0; i < data.length; i++ ) {

            // all the actually-rendered UDRs. Do not include the distance for a non-rendered UDR
            const renderedUDRs = LinkablePositionUtils.getRenderedUDRs({ renderedLinks, linkExclusionHandler } );

            const protein1 =  parseInt(data[ i ][ 'protein1' ]);
            const protein2 =  parseInt(data[ i ][ 'protein2' ]);

            const position1 = parseInt(data[ i ][ 'position1' ]);
            const position2 = parseInt(data[ i ][ 'position2' ]);

            // don't included excluded things
            if( ( linkExclusionHandler.isCrosslinkExcluded( protein1, position1, protein2, position2 ) ||
                linkExclusionHandler.isLooplinkExcluded( protein1, position1, position2 ) ) &&
                !LinkablePositionUtils.isUDRinRenderedUDRs( { renderedUDRs, protein1, protein2, position1, position2 } ) ) {
                continue;
            }

            const chains1 = visibleProteinsMap[ protein1 ];
            const chains2 = visibleProteinsMap[ protein2 ];

            let shortestDistance = -1;

            if( !chains1 || chains1 == undefined || chains1.length < 1 ) {
                console.log( "ERROR: Got no chains for protein: " + protein1 );
                return;
            }

            if( !chains2 || chains2 == undefined || chains2.length < 1 ) {
                console.log( "ERROR: Got no chains for protein: " + protein2 );
                return;
            }

            for( let j = 0; j < chains1.length; j++ ) {
                const chain1 = chains1[ j ];

                const coordsArray1 = StructureAlignmentUtils.findCACoords( protein1, position1, [ chain1 ], alignments, structure );
                if( coordsArray1 == undefined || coordsArray1.length < 1 ) { continue; }

                for( let k = 0; k < chains2.length; k++ ) {
                    const chain2 = chains2[ k ];

                    if( chain1 == chain2 && protein1 == protein2 && position1 == position2 ) { continue; }

                    const coordsArray2 = StructureAlignmentUtils.findCACoords( protein2, position2, [ chain2 ], alignments, structure );
                    if( coordsArray1 == undefined || coordsArray2.length < 1 ) { continue; }

                    const distance = StructureUtils.calculateDistance( coordsArray1[ 0 ], coordsArray2[ 0 ] );

                    if( !onlyShortest ) {

                        pdbDistanceArray.push( distance );

                    } else {

                        if( shortestDistance === -1 || shortestDistance > distance ) {
                            shortestDistance = distance;
                        }

                    }
                }
            }

            if( onlyShortest ) {
                if( shortestDistance != -1 ) {
                    pdbDistanceArray.push(shortestDistance);
                }
            }
        }

        return pdbDistanceArray;
    }

}<commit_msg>Remove debugging messages.<commit_after>"use strict";

import {StructureAlignmentUtils} from "./structure-alignment-utils";
import {StructureUtils} from "./stucture-utils";

export class LinkablePositionUtils {

    static getRenderedDistanceArray( renderedLinks, linkExclusionHandler ) {

        let distanceArray = [ ];
        let UDRsCounted = { };

        if( renderedLinks.crosslinks ) {
            for (let i = 0; i < renderedLinks['crosslinks'].length; i++) {

                const link = renderedLinks['crosslinks'][i]['link'];

                if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                    LinkablePositionUtils.addCrosslinkToCountedUDRs({UDRsCounted, link})

                    distanceArray.push(parseFloat(renderedLinks['crosslinks'][i]['link']['length']));
                }
            }
        }

        if( renderedLinks.looplinks ) {
            for (let i = 0; i < renderedLinks['looplinks'].length; i++) {

                const link = renderedLinks['looplinks'][i]['link'];

                if( !LinkablePositionUtils.isUDRinRenderedUDRs( {
                    renderedUDRs: UDRsCounted,
                    protein1: link.protein1,
                    protein2: link.protein1,
                    position1: link.position1,
                    position2: link.position2 } )) {
                    if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                        distanceArray.push(parseFloat(renderedLinks['looplinks'][i]['link']['length']));
                    }
                }
            }
        }

        return distanceArray;
    }

    static getRenderedUDRs({ renderedLinks, linkExclusionHandler }) {

        let renderedUDRs = { };

        if( renderedLinks.crosslinks ) {
            for (let i = 0; i < renderedLinks['crosslinks'].length; i++) {

                const link = renderedLinks['crosslinks'][i]['link'];

                if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                    LinkablePositionUtils.addCrosslinkToCountedUDRs({UDRsCounted: renderedUDRs, link})
                }
            }
        }

        if( renderedLinks.looplinks ) {
            for (let i = 0; i < renderedLinks['looplinks'].length; i++) {

                const link = renderedLinks['looplinks'][i]['link'];

                if( !linkExclusionHandler || !linkExclusionHandler.isLinkExcluded( link ) ) {
                    LinkablePositionUtils.addLooplinkToCountedUDRs({UDRsCounted: renderedUDRs, link})
                }
            }
        }

        return renderedUDRs;
    }

    static addCrosslinkToCountedUDRs({UDRsCounted,link}) {
        const protein1 = link['protein1'];
        const protein2 = link['protein2'];
        const position1 = link['position1'];
        const position2 = link['position2'];

        // add this to the list of UDRs we've counted so we can calculated total unique UDRs among cross- and loop-links
        if( !( protein1 in UDRsCounted ) ) { UDRsCounted[ protein1 ] = { }; }
        if( !( protein2 in UDRsCounted[ protein1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ] = { }; }
        if( !( position1 in UDRsCounted[ protein1 ][ protein2 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ] = { }; };
        if( !( position2 in UDRsCounted[ protein1 ][ protein2 ][ position1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ][ position2 ] = { }; };
    }

    static addLooplinkToCountedUDRs({UDRsCounted,link}) {
        const protein1 = link['protein1'];
        const protein2 = link['protein1'];
        const position1 = link['position1'];
        const position2 = link['position2'];

        // add this to the list of UDRs we've counted so we can calculated total unique UDRs among cross- and loop-links
        if( !( protein1 in UDRsCounted ) ) { UDRsCounted[ protein1 ] = { }; }
        if( !( protein2 in UDRsCounted[ protein1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ] = { }; }
        if( !( position1 in UDRsCounted[ protein1 ][ protein2 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ] = { }; };
        if( !( position2 in UDRsCounted[ protein1 ][ protein2 ][ position1 ] ) ) { UDRsCounted[ protein1 ][ protein2 ][ position1 ][ position2 ] = { }; };
    }

    static isUDRinRenderedUDRs({ renderedUDRs, protein1, protein2, position1, position2 } ) {

        // console.log( renderedUDRs );
        // console.log( protein1 );
        // console.log( protein2 );
        // console.log( position1 );
        // console.log( position2 );
        // console.log( "=============" );
        // console.log( renderedUDRs[ protein1 ] );
        // console.log( renderedUDRs[ protein1 ][ protein2 ] );
        // console.log( renderedUDRs[ protein1 ][ protein2 ][ position1 ] );
        // console.log( renderedUDRs[ protein1 ][ protein2 ][ position1 ][ position2 ] );
        // console.log( "=============" );

        if( protein1 in renderedUDRs ) {

            if( protein2 in renderedUDRs[ protein1 ] &&
            position1 in renderedUDRs[ protein1 ][ protein2 ] &&
            position2 in renderedUDRs[ protein1 ][ protein2 ][ position1 ] ) {
                return true;
            }

            // test swapping positions if it's within the same protein
            if( protein1 === protein2 ) {
                if( protein2 in renderedUDRs[ protein1 ] &&
                    position2 in renderedUDRs[ protein1 ][ protein2 ] &&
                    position1 in renderedUDRs[ protein1 ][ protein2 ][ position2 ] ) {
                    return true;
                }
            }

        } else if( protein1 !== protein2 && protein2 in renderedUDRs ) {

            if( protein1 in renderedUDRs[ protein2 ] &&
                position2 in renderedUDRs[ protein2 ][ protein1 ] &&
                position1 in renderedUDRs[ protein2 ][ protein1 ][ position2 ] ) {
                return true;
            }

        }

        return false;
    }

    static getDistanceArrayFromLinkablePositions( {
                                                      data,
                                                      visibleProteinsMap,
                                                      onlyShortest,
                                                      alignments,
                                                      structure,
                                                      linkExclusionHandler,
                                                      renderedLinks
                                                    }) {

        const pdbDistanceArray = [ ];

        for( let i = 0; i < data.length; i++ ) {

            // all the actually-rendered UDRs. Do not include the distance for a non-rendered UDR
            const renderedUDRs = LinkablePositionUtils.getRenderedUDRs({ renderedLinks, linkExclusionHandler } );

            const protein1 =  parseInt(data[ i ][ 'protein1' ]);
            const protein2 =  parseInt(data[ i ][ 'protein2' ]);

            const position1 = parseInt(data[ i ][ 'position1' ]);
            const position2 = parseInt(data[ i ][ 'position2' ]);

            // don't included excluded things
            if( ( linkExclusionHandler.isCrosslinkExcluded( protein1, position1, protein2, position2 ) ||
                linkExclusionHandler.isLooplinkExcluded( protein1, position1, position2 ) ) &&
                !LinkablePositionUtils.isUDRinRenderedUDRs( { renderedUDRs, protein1, protein2, position1, position2 } ) ) {
                continue;
            }

            const chains1 = visibleProteinsMap[ protein1 ];
            const chains2 = visibleProteinsMap[ protein2 ];

            let shortestDistance = -1;

            if( !chains1 || chains1 == undefined || chains1.length < 1 ) {
                console.log( "ERROR: Got no chains for protein: " + protein1 );
                return;
            }

            if( !chains2 || chains2 == undefined || chains2.length < 1 ) {
                console.log( "ERROR: Got no chains for protein: " + protein2 );
                return;
            }

            for( let j = 0; j < chains1.length; j++ ) {
                const chain1 = chains1[ j ];

                const coordsArray1 = StructureAlignmentUtils.findCACoords( protein1, position1, [ chain1 ], alignments, structure );
                if( coordsArray1 == undefined || coordsArray1.length < 1 ) { continue; }

                for( let k = 0; k < chains2.length; k++ ) {
                    const chain2 = chains2[ k ];

                    if( chain1 == chain2 && protein1 == protein2 && position1 == position2 ) { continue; }

                    const coordsArray2 = StructureAlignmentUtils.findCACoords( protein2, position2, [ chain2 ], alignments, structure );
                    if( coordsArray1 == undefined || coordsArray2.length < 1 ) { continue; }

                    const distance = StructureUtils.calculateDistance( coordsArray1[ 0 ], coordsArray2[ 0 ] );

                    if( !onlyShortest ) {

                        pdbDistanceArray.push( distance );

                    } else {

                        if( shortestDistance === -1 || shortestDistance > distance ) {
                            shortestDistance = distance;
                        }

                    }
                }
            }

            if( onlyShortest ) {
                if( shortestDistance != -1 ) {
                    pdbDistanceArray.push(shortestDistance);
                }
            }
        }

        return pdbDistanceArray;
    }

}<|endoftext|>


<commit_before>define({
    /**
     * Getter/setter for components
     *
     * @param {string} name
     * @param {BaseComponent} component Optional
     */
    pageComponent: function (name, component) {
        if (!this.pageComponents) {
            this.pageComponents = {};
        }
        if (name && component) {
            this.removePageComponent(name);
            this.pageComponents[name] = component;
            component.on('dispose', _.bind(function () {
                this.removePageComponent(name);
            }, this));
            return component;
        } else {
            return this.pageComponents[name];
        }
    },

    /**
     * @param {string} name component name to remove
     */
    removePageComponent: function (name) {
        if (!this.pageComponents) {
            this.pageComponents = {};
        }
        var toRemove = this.pageComponents[name];
        if (toRemove) {
            delete this.pageComponents[name];
            toRemove.dispose();
        }
    },

    /**
     * Destroys all linked page components
     */
    disposePageComponents: function () {
        if (!this.pageComponents) {
            return;
        }
        for (var name in this.pageComponents) {
            this.removePageComponent(name);
        }
        delete this.pageComponents;
    }
});
<commit_msg>BAP-7052 code style fixes<commit_after>define({
    /**
     * Getter/setter for components
     *
     * @param {string} name
     * @param {BaseComponent=} component to set
     */
    pageComponent: function (name, component) {
        if (!this.pageComponents) {
            this.pageComponents = {};
        }
        if (name && component) {
            this.removePageComponent(name);
            this.pageComponents[name] = component;
            component.on('dispose', _.bind(function () {
                this.removePageComponent(name);
            }, this));
            return component;
        } else {
            return this.pageComponents[name];
        }
    },

    /**
     * @param {string} name component name to remove
     */
    removePageComponent: function (name) {
        if (!this.pageComponents) {
            this.pageComponents = {};
        }
        var toRemove = this.pageComponents[name];
        if (toRemove) {
            delete this.pageComponents[name];
            toRemove.dispose();
        }
    },

    /**
     * Destroys all linked page components
     */
    disposePageComponents: function () {
        if (!this.pageComponents) {
            return;
        }
        for (var name in this.pageComponents) {
            this.removePageComponent(name);
        }
        delete this.pageComponents;
    }
});
<|endoftext|>


<commit_before>$( document ).ready(function() {

    var statsEnabled = isDataPublishingEnabled();
    var table = null;

    var selectedOptionKey = $("#alertSelected option:selected" ).val();
    var tableName = null;

    changeActiveTableName();

    if(statsEnabled){
        drawTable();
    } else {
        $('.content-data').empty();
        $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
    }

    $("#alertSelected").change( function() {
        selectedOptionKey = $("#alertSelected option:selected" ).val();
        changeActiveTableName();
        if(statsEnabled){
            table.ajax.reload(null, true);
        } else{
            $('.content-data').empty();
            $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
        }
    });

    $('#alertHistoryTable_filter input').unbind();
    $('#alertHistoryTable_filter input').bind('keyup', function(e) {
        if(e.keyCode == 13) {
            table.search( this.value ).draw();
        }
    });

    function changeActiveTableName() {
        if(selectedOptionKey == 1){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALLAPIMALERTSSTREAM"
        } else if(selectedOptionKey== 2){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_UNUSUALIPACCESS";
        } else if(selectedOptionKey== 3){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALREQUESTSPERMINALERTSTREAM";
        } else if(selectedOptionKey== 4){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALRESPONSETIMEALERTSTREAM";
        } else if(selectedOptionKey== 5){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTIERUSAGEALERT";
        } else if(selectedOptionKey== 6){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTOKENREFRESH";
        } else if(selectedOptionKey== 7){
            tableName = "ORG_WSO2_ANALYTICS_APIM_TIERLIMITHITTINGALERT";
        } else if(selectedOptionKey== 8){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALBACKENDTIMEALERTSTREAM";
        } else if(selectedOptionKey== 9){
            tableName = "ORG_WSO2_ANALYTICS_APIM_APIHEALTHMONITORALERTSTREAM";
        } else if(selectedOptionKey== 10){
            tableName = "ORG_WSO2_ANALYTICS_APIM_REQUESTPATTERNCHANGEDSTREAM";
        }

    }

    function isDataPublishingEnabled() {
        var isStatsEnabled;

        jagg.syncPost("/site/blocks/alert-table/ajax/alert-table.jag", { action: "isDataPublishingEnabled"},
            function (json) {
                if (!json.error) {
                    isStatsEnabled = json.usage;
                } else {
                    if (json.message == "AuthenticateError") {
                        jagg.showLogin();
                    } else {
                        jagg.message({content: json.message, type: "error"});
                    }
                }
            }, "json");

        return isStatsEnabled;
    }

    function changeSelectedAlertType(alertType) {
        if(alertType != null){
            if(alertType == "Unseen Source IP Address"){
                $('#alertSelected').val(2).change();
            } else if(alertType == "Abnormal Request Count"){
                $('#alertSelected').val(3).change();
            } else if(alertType == "Abnormal Response Time"){
                $('#alertSelected').val(4).change();
            } else if(alertType == "Abnormal API Usage"){
                $('#alertSelected').val(5).change();
            } else if(alertType == "Abnormal Renewal of Access Tokens"){
                $('#alertSelected').val(6).change();
            } else if(alertType == "Tier Crossing"){
                $('#alertSelected').val(7).change();
            } else if(alertType == "Abnormal Backend Time"){
                $('#alertSelected').val(8).change();
            } else if(alertType == "Availability of APIs"){
                $('#alertSelected').val(9).change();
            } else if(alertType == "Abnormal Resource Access Pattern"){
                $('#alertSelected').val(10).change();
            }
        }
    }

    function drawTable() {

        table =$('#alertHistoryTable').datatables_extended({
            "order": [[ 0, "desc" ]],
            //"processing": true,
            "serverSide": true,
            "columns" : [
                { title: i18n.t("Alert Timestamp") },
                { title: i18n.t("Type"), "orderable": false },
                { title: i18n.t("Message") , "orderable": false ,"render":function(data){
                    var userId = data['userId'];
                    var applicationName = data['applicationName'];
                    var applicationOwner = data['applicationOwner'];
                    var applicationId = data['applicationId'];
                    var api_version = data['api_version'];
                    var ip = data['ip'];
                    var api = data['api'];
                    var apiPublisher = data['apiPublisher'];
                    var resourceTemplate = data['resourceTemplate'];
                    var method = data['method'];
                    var backendTime = data['backendTime'];
                    var requestPerMin = data['requestPerMin'];
                    var reason = data['reason'];
                    var scope = data['scope'];
                    var consumerKey = data['consumerKey'];

                    var fullMessage = "";;

                    if (userId != null) {
                        fullMessage = '' + i18n.t("User ID") + ''+userId+'
';
                    }
                    if (applicationName != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Name") + ''+applicationName+'
';
                    }
                    if (applicationOwner != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Owner") + ''+applicationOwner+'
';
                    }
                    if (applicationId != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application ID") + ''+applicationId+'
';
                    }
                    if (api_version != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Version") + ''+api_version+'
';
                    }
                    if (ip != null) {
                        fullMessage = fullMessage + '' + i18n.t("IP") + ''+ip+'
';
                    }
                    if (api != null) {
                        fullMessage = fullMessage + '' + i18n.t("API") + ''+api+'
';
                    }
                    if (apiPublisher != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Publisher") + ''+apiPublisher+'
';
                    }
                    if (resourceTemplate != null) {
                        fullMessage = fullMessage + '' + i18n.t("Resource Template") + ''+resourceTemplate+'
';
                    }
                    if (method != null) {
                        fullMessage = fullMessage + '' + i18n.t("Method") + ''+method+'
';
                    }
                    if (backendTime != null) {
                        fullMessage = fullMessage + '' + i18n.t("Backend Time") + ''+backendTime+'
';
                    }
                    if (requestPerMin != null) {
                        fullMessage = fullMessage + '' + i18n.t("Requests Per-Min") + ''+requestPerMin+'
';
                    }
                    if (reason != null) {
                        fullMessage = fullMessage + '' + i18n.t("Reason") + ''+reason+'
';
                    }
                    if (scope != null) {
                        fullMessage = fullMessage + '' + i18n.t("Scope") + ''+scope+'
';
                    }
                    if (consumerKey != null) {
                        fullMessage = fullMessage + '' + i18n.t("Consumer Key") + ''+consumerKey+'
';
                    }

                    fullMessage = fullMessage + data['msg'];
                    return fullMessage;
                }
                },
                {title: i18n.t("Severity"), "render": function(data){
                    var severityLabel;
                    if(data == 1) {
                        severityLabel = '' + i18n.t("severe") + '';
                    } else if (data == 2) {
                        severityLabel = '' + i18n.t("moderate") + '';
                    } else if (data == 3){
                        severityLabel = '' + i18n.t("mild") + '';
                    } else {
                        severityLabel = '' + i18n.t("mild") + '';
                    }
                    return severityLabel;
                }
                }
            ],
            ajax: {
                "url" : "site/blocks/alert-table/ajax/alert-table.jag",
                "type": "POST",
                "data" : function (d) {
                    d.action = "getDataFromTable";
                    d.tableName = tableName;
                    d.searchQuery = null;
                    d.entriesPerPage = $("#alertHistoryTable_length option:selected" ).val();
                },
                error:function(xhr,status,error){
                    console.log('Error while trying to connect to the DAS endpoint');
                }
            },
            "drawCallback": function(){
                $('.alertTypeLink').click(function(){
                    changeSelectedAlertType(this.text);
                });

            }
        });

    }

});
     <commit_msg>adding subscriber tag in alerts table<commit_after>$( document ).ready(function() {

    var statsEnabled = isDataPublishingEnabled();
    var table = null;

    var selectedOptionKey = $("#alertSelected option:selected" ).val();
    var tableName = null;

    changeActiveTableName();

    if(statsEnabled){
        drawTable();
    } else {
        $('.content-data').empty();
        $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
    }

    $("#alertSelected").change( function() {
        selectedOptionKey = $("#alertSelected option:selected" ).val();
        changeActiveTableName();
        if(statsEnabled){
            table.ajax.reload(null, true);
        } else{
            $('.content-data').empty();
            $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
        }
    });

    $('#alertHistoryTable_filter input').unbind();
    $('#alertHistoryTable_filter input').bind('keyup', function(e) {
        if(e.keyCode == 13) {
            table.search( this.value ).draw();
        }
    });

    function changeActiveTableName() {
        if(selectedOptionKey == 1){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALLAPIMALERTSSTREAM"
        } else if(selectedOptionKey== 2){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_UNUSUALIPACCESS";
        } else if(selectedOptionKey== 3){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALREQUESTSPERMINALERTSTREAM";
        } else if(selectedOptionKey== 4){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALRESPONSETIMEALERTSTREAM";
        } else if(selectedOptionKey== 5){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTIERUSAGEALERT";
        } else if(selectedOptionKey== 6){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTOKENREFRESH";
        } else if(selectedOptionKey== 7){
            tableName = "ORG_WSO2_ANALYTICS_APIM_TIERLIMITHITTINGALERT";
        } else if(selectedOptionKey== 8){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALBACKENDTIMEALERTSTREAM";
        } else if(selectedOptionKey== 9){
            tableName = "ORG_WSO2_ANALYTICS_APIM_APIHEALTHMONITORALERTSTREAM";
        } else if(selectedOptionKey== 10){
            tableName = "ORG_WSO2_ANALYTICS_APIM_REQUESTPATTERNCHANGEDSTREAM";
        }

    }

    function isDataPublishingEnabled() {
        var isStatsEnabled;

        jagg.syncPost("/site/blocks/alert-table/ajax/alert-table.jag", { action: "isDataPublishingEnabled"},
            function (json) {
                if (!json.error) {
                    isStatsEnabled = json.usage;
                } else {
                    if (json.message == "AuthenticateError") {
                        jagg.showLogin();
                    } else {
                        jagg.message({content: json.message, type: "error"});
                    }
                }
            }, "json");

        return isStatsEnabled;
    }

    function changeSelectedAlertType(alertType) {
        if(alertType != null){
            if(alertType == "Unseen Source IP Address"){
                $('#alertSelected').val(2).change();
            } else if(alertType == "Abnormal Request Count"){
                $('#alertSelected').val(3).change();
            } else if(alertType == "Abnormal Response Time"){
                $('#alertSelected').val(4).change();
            } else if(alertType == "Abnormal API Usage"){
                $('#alertSelected').val(5).change();
            } else if(alertType == "Abnormal Renewal of Access Tokens"){
                $('#alertSelected').val(6).change();
            } else if(alertType == "Tier Crossing"){
                $('#alertSelected').val(7).change();
            } else if(alertType == "Abnormal Backend Time"){
                $('#alertSelected').val(8).change();
            } else if(alertType == "Availability of APIs"){
                $('#alertSelected').val(9).change();
            } else if(alertType == "Abnormal Resource Access Pattern"){
                $('#alertSelected').val(10).change();
            }
        }
    }

    function drawTable() {

        table =$('#alertHistoryTable').datatables_extended({
            "order": [[ 0, "desc" ]],
            //"processing": true,
            "serverSide": true,
            "columns" : [
                { title: i18n.t("Alert Timestamp") },
                { title: i18n.t("Type"), "orderable": false },
                { title: i18n.t("Message") , "orderable": false ,"render":function(data){
                    var userId = data['userId'];
                    var applicationName = data['applicationName'];
                    var applicationOwner = data['applicationOwner'];
                    var applicationId = data['applicationId'];
                    var api_version = data['api_version'];
                    var ip = data['ip'];
                    var api = data['api'];
                    var apiPublisher = data['apiPublisher'];
                    var resourceTemplate = data['resourceTemplate'];
                    var method = data['method'];
                    var backendTime = data['backendTime'];
                    var requestPerMin = data['requestPerMin'];
                    var reason = data['reason'];
                    var scope = data['scope'];
                    var consumerKey = data['consumerKey'];
                    var subscriber = data['subscriber'];

                    var fullMessage = "";;

                    if (userId != null) {
                        fullMessage = '' + i18n.t("User ID") + ''+userId+'
';
                    }
                    if (applicationName != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Name") + ''+applicationName+'
';
                    }
                    if (applicationOwner != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Owner") + ''+applicationOwner+'
';
                    }
                    if (applicationId != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Id") + ''+applicationId+'
';
                    }
                    if (api_version != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Version") + ''+api_version+'
';
                    }
                    if (ip != null) {
                        fullMessage = fullMessage + '' + i18n.t("IP") + ''+ip+'
';
                    }
                    if (api != null) {
                        fullMessage = fullMessage + '' + i18n.t("API") + ''+api+'
';
                    }
                    if (apiPublisher != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Publisher") + ''+apiPublisher+'
';
                    }
                    if (resourceTemplate != null) {
                        fullMessage = fullMessage + '' + i18n.t("Resource Template") + ''+resourceTemplate+'
';
                    }
                    if (method != null) {
                        fullMessage = fullMessage + '' + i18n.t("Method") + ''+method+'
';
                    }
                    if (backendTime != null) {
                        fullMessage = fullMessage + '' + i18n.t("Backend Time") + ''+backendTime+'
';
                    }
                    if (requestPerMin != null) {
                        fullMessage = fullMessage + '' + i18n.t("Requests Per-Min") + ''+requestPerMin+'
';
                    }
                    if (reason != null) {
                        fullMessage = fullMessage + '' + i18n.t("Reason") + ''+reason+'
';
                    }
                    if (scope != null) {
                        fullMessage = fullMessage + '' + i18n.t("Scope") + ''+scope+'
';
                    }
                    if (consumerKey != null) {
                        fullMessage = fullMessage + '' + i18n.t("Consumer Key") + ''+consumerKey+'
';
                    }
                    if (subscriber != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Subscriber") + ''+subscriber+'
';
                    }

                    fullMessage = fullMessage + data['msg'];
                    return fullMessage;
                }
                },
                {title: i18n.t("Severity"), "render": function(data){
                    var severityLabel;
                    if(data == 1) {
                        severityLabel = '' + i18n.t("severe") + '';
                    } else if (data == 2) {
                        severityLabel = '' + i18n.t("moderate") + '';
                    } else if (data == 3){
                        severityLabel = '' + i18n.t("mild") + '';
                    } else {
                        severityLabel = '' + i18n.t("mild") + '';
                    }
                    return severityLabel;
                }
                }
            ],
            ajax: {
                "url" : "site/blocks/alert-table/ajax/alert-table.jag",
                "type": "POST",
                "data" : function (d) {
                    d.action = "getDataFromTable";
                    d.tableName = tableName;
                    d.searchQuery = null;
                    d.entriesPerPage = $("#alertHistoryTable_length option:selected" ).val();
                },
                error:function(xhr,status,error){
                    console.log('Error while trying to connect to the DAS endpoint');
                }
            },
            "drawCallback": function(){
                $('.alertTypeLink').click(function(){
                    changeSelectedAlertType(this.text);
                });

            }
        });

    }

});
<|endoftext|>


<commit_before>import React from 'react';
import moment from 'moment';

import { getUpdateBufferSize } from '../utils/update-buffer-utils';
import { contrastModeUrl, isContrastMode } from '../utils/contrast-utils';
import { clickDownloadGraph, clickForceRelayout, clickPauseUpdate,
  clickResumeUpdate } from '../actions/app-actions';
import { basePathSlash } from '../utils/web-api-utils';

export default function Footer(props) {
  const { hostname, updatePaused, updatePausedAt, version } = props;
  const contrastMode = isContrastMode();

  // link url to switch contrast with current UI state
  const otherContrastModeUrl = contrastMode
    ? basePathSlash(window.location.pathname) : contrastModeUrl;
  const otherContrastModeTitle = contrastMode
    ? 'Switch to normal contrast' : 'Switch to high contrast';
  const forceRelayoutTitle = 'Force re-layout (might reduce edge crossings, '
    + 'but may shift nodes around)';

  // pause button
  const isPaused = updatePaused;
  const updateCount = getUpdateBufferSize();
  const hasUpdates = updateCount > 0;
  const pausedAgo = moment(updatePausedAt).fromNow();
  const pauseTitle = isPaused
    ? `Paused ${pausedAgo}` : 'Pause updates (freezes the nodes in their current layout)';
  const pauseAction = isPaused ? clickResumeUpdate : clickPauseUpdate;
  const pauseClassName = isPaused ? 'footer-icon footer-icon-active' : 'footer-icon';
  let pauseLabel = '';
  if (hasUpdates && isPaused) {
    pauseLabel = `Paused +${updateCount}`;
  } else if (hasUpdates && !isPaused) {
    pauseLabel = `Resuming +${updateCount}`;
  } else if (!hasUpdates && isPaused) {
    pauseLabel = 'Paused';
  }

  return (

        Version
        {version}
        on
        {hostname}

          {pauseLabel !== '' && {pauseLabel}}

  );
}
<commit_msg>Adds '?' button down to bottom to toggle shortcut overlay<commit_after>import React from 'react';
import moment from 'moment';

import { getUpdateBufferSize } from '../utils/update-buffer-utils';
import { contrastModeUrl, isContrastMode } from '../utils/contrast-utils';
import { clickDownloadGraph, clickForceRelayout, clickPauseUpdate,
  clickResumeUpdate, toggleHelp } from '../actions/app-actions';
import { basePathSlash } from '../utils/web-api-utils';

export default function Footer(props) {
  const { hostname, updatePaused, updatePausedAt, version } = props;
  const contrastMode = isContrastMode();

  // link url to switch contrast with current UI state
  const otherContrastModeUrl = contrastMode
    ? basePathSlash(window.location.pathname) : contrastModeUrl;
  const otherContrastModeTitle = contrastMode
    ? 'Switch to normal contrast' : 'Switch to high contrast';
  const forceRelayoutTitle = 'Force re-layout (might reduce edge crossings, '
    + 'but may shift nodes around)';

  // pause button
  const isPaused = updatePaused;
  const updateCount = getUpdateBufferSize();
  const hasUpdates = updateCount > 0;
  const pausedAgo = moment(updatePausedAt).fromNow();
  const pauseTitle = isPaused
    ? `Paused ${pausedAgo}` : 'Pause updates (freezes the nodes in their current layout)';
  const pauseAction = isPaused ? clickResumeUpdate : clickPauseUpdate;
  const pauseClassName = isPaused ? 'footer-icon footer-icon-active' : 'footer-icon';
  let pauseLabel = '';
  if (hasUpdates && isPaused) {
    pauseLabel = `Paused +${updateCount}`;
  } else if (hasUpdates && !isPaused) {
    pauseLabel = `Resuming +${updateCount}`;
  } else if (!hasUpdates && isPaused) {
    pauseLabel = 'Paused';
  }

  return (

        Version
        {version}
        on
        {hostname}

          {pauseLabel !== '' && {pauseLabel}}

  );
}
<|endoftext|>


<commit_before>Template.kioskEvent.helpers({
	timePeriod: function() {
		return Template.instance().parentInstance().data.timePeriod;
	},

	isOngoing: function() {
		return Template.instance().parentInstance().data.timePeriod == "ongoing";
	},

	isUpcoming: function() {
		return Template.instance().parentInstance().data.timePeriod == "upcoming";
	}
});

Template.kioskEvent.rendered = function() {
	this.$('.kiosk-event').dotdotdot();
};

Template.kioskEventLocation.helpers({
	showLocation: function() {
		// The location is shown when we have a location name and the location is not used as a filter
		return this.location.name && !Router.current().params.query.location;
	}
});
<commit_msg>don't fail hwn there's no location<commit_after>Template.kioskEvent.helpers({
	timePeriod: function() {
		return Template.instance().parentInstance().data.timePeriod;
	},

	isOngoing: function() {
		return Template.instance().parentInstance().data.timePeriod == "ongoing";
	},

	isUpcoming: function() {
		return Template.instance().parentInstance().data.timePeriod == "upcoming";
	}
});

Template.kioskEvent.rendered = function() {
	this.$('.kiosk-event').dotdotdot();
};

Template.kioskEventLocation.helpers({
	showLocation: function() {
		// The location is shown when we have a location name and the location is not used as a filter
		return this.location
		    && this.location.name
		    && !Router.current().params.query.location;
	}
});
<|endoftext|>