<commit_before>var KonvaView = require('../konva');
var Bus = require('bus');
var defaults = require('defaults');
var config = require('config');

module.exports = KonvaView.extend({
    currentTweens: null,

    events: {
    },

    initialize: function(options) {
        options = options || {};
        this.baseLayer = options.baseLayer;
        this.mouseoverLayer = options.mouseoverLayer;
        this.stage = options.stage;
        this.options = options;

        this.currentTweens = [];

        this.render();

        Bus.Event.on('note:highlighted', function(note) {
            var notes = this.noteGroup.find('.' + note);

            _.each(this.currentTweens, function(tween) {
                tween.destroy();
            });
            var mouseoverLayer = this.mouseoverLayer;
            notes.each(function(noteNode) {
                noteNode.moveTo(mouseoverLayer);
                var color = noteNode.getAttr('color');
                noteNode.setAttrs({
                    shadowBlur: 10,
                    shadowEnabled: true,
                    shadowColor: color,
                    opacity: 1
                });
            });
            this.stage.draw();
        }, this);

        Bus.Event.on('note:unhighlighted', function(note) {
            var notes = this.mouseoverLayer.find('.' + note);

            _.each(this.currentTweens, function(tween) {
                tween.destroy();
            });
            var noteGroup = this.noteGroup;
            notes.each(function(noteNode) {
                noteNode.moveTo(noteGroup);
                var initialOpacity = noteNode.getAttr('initialOpacity');
                noteNode.setAttrs({
                    opacity: initialOpacity,
                    shadowEnabled: false
                });
            });
            this.stage.draw();
        }, this);

        Bus.Event.on('change:mode', function(newMode) {
            this.noteGroup.children.each(function(noteNode) {
                noteNode.setAttrs({
                    opacity: 0.1,
                    initialOpacity: 0.1
                });
            });
            var positions = config.modes[newMode];
            var currentTonic = Bus.Reqres.request('current:tonic');
            var scale = config.chromaticScales[currentTonic];
            var nodes = [];
            var nodesToFind = _.map(positions, function(position) {
                return '.note-' + scale.at(position).get('name');
            }).join(',');
            var notes = this.noteGroup.find(nodesToFind);
            notes.each(function(noteNode) {
                noteNode.setAttrs({
                    opacity: 1,
                    initialOpacity: 1
                });
            });
            this.stage.draw();
        }, this);
    },

    _addNut: function(string, index, settings) {
        var rootNote = _.first(string.get('notes'));
        var rootNoteName = 'note-' + rootNote.get('name');
        var nutNoteColor = new Konva.Rect({
            x: 0,
            y: settings.stringHeight * index + settings.padding,
            width: settings.padding - settings.nutWidth,
            height: settings.stringHeight,
            fill: rootNote.get('color'),
            name: rootNoteName,
            opacity: 0.1
        });
        this.noteGroup.add(nutNoteColor);
        var nut = new Konva.Rect({
            x: settings.padding - settings.nutWidth,
            y: settings.stringHeight * index + settings.padding,
            width: settings.nutWidth,
            height: settings.stringHeight,
            fill: 'black'
        });
        this.fretGroup.add(nut);
    },

    _addNotes: function(string, index, settings) {
        for (var i = 1; i <= string.get('frets'); i++) {
            var distanceFromNut = this.collection.settings.fretDistanceMap[i];
            var fret = new Konva.Rect({
                x: (settings.padding + distanceFromNut.distance) - settings.fretWidth,
                y: settings.stringHeight * index + settings.padding,
                width: settings.fretWidth,
                height: settings.stringHeight,
                fill: 'silver'
            });
            this.fretGroup.add(fret);
            var color = new Konva.Rect({
                x: (settings.padding + distanceFromNut.distance) - distanceFromNut.width,
                y: settings.stringHeight * index + settings.padding,
                width: distanceFromNut.width - settings.fretWidth,
                height: settings.stringHeight,
                fill: string.get('notes')[i].get('color'),
                name: 'note-' + string.get('notes')[i].get('name'),
                opacity: 0.1
            });
            this.noteGroup.add(color);
        }
    },

    _addStrings: function(string, index, settings) {
        var stringOverNut = new Konva.Rect({
            x: 0,
            y: (settings.stringHeight / 2) - (settings.fretWidth / 2) + (settings.stringHeight * index) + settings.padding,
            width: settings.padding,
            height: settings.fretWidth,
            fill: string.get('notes')[0].get('color'),
            name: 'note-' + string.get('notes')[0].get('name')
        });
        this.stringGroup.add(stringOverNut);
        var string = new Konva.Rect({
            x: settings.padding,
            y: (settings.stringHeight / 2) - (settings.fretWidth / 2) + (settings.stringHeight * index) + settings.padding,
            width: this.collection.settings.displayWidth,
            height: settings.fretWidth,
            fill: 'black'
        });
        this.stringGroup.add(string);
    },

    _addToGroup: function() {
        this.fretGroup = new Konva.Group();
        this.noteGroup = new Konva.Group();
        this.stringGroup = new Konva.Group();
        var settings = this.collection.settings;

        this.collection.each(function(string, index) {
            this._addNut(string, index, settings);
            this._addNotes(string, index, settings);
            this._addStrings(string, index, settings);
        }, this);
        this.group.add(this.fretGroup);
        this.group.add(this.noteGroup);
        this.group.add(this.stringGroup);
    },

    onDestroy: function() {
        this.fretGroup.destroyChildren();
        this.noteGroup.destroyChildren();
        this.stringGroup.destroyChildren();
    }
}); <commit_msg>Fixed instrument view sticking around after being destroyed<commit_after>var KonvaView = require('../konva');
var Bus = require('bus');
var defaults = require('defaults');
var config = require('config');

module.exports = KonvaView.extend({
    currentTweens: null,

    events: {
    },

    initialize: function(options) {
        options = options || {};
        this.baseLayer = options.baseLayer;
        this.mouseoverLayer = options.mouseoverLayer;
        this.stage = options.stage;
        this.options = options;

        this.currentTweens = [];

        this.render();

        Bus.Event.on('note:highlighted', this._highlightSelectedNotes, this);

        Bus.Event.on('note:unhighlighted', this._unhighlightNotes, this);

        Bus.Event.on('change:mode', this._changeMode, this);
    },

    _changeMode: function(newMode) {
        this.noteGroup.children.each(function(noteNode) {
            noteNode.setAttrs({
                opacity: 0.1,
                initialOpacity: 0.1
            });
        });
        var positions = config.modes[newMode];
        var currentTonic = Bus.Reqres.request('current:tonic');
        var scale = config.chromaticScales[currentTonic];
        var nodes = [];
        var nodesToFind = _.map(positions, function(position) {
            return '.note-' + scale.at(position).get('name');
        }).join(',');
        var notes = this.noteGroup.find(nodesToFind);
        notes.each(function(noteNode) {
            noteNode.setAttrs({
                opacity: 1,
                initialOpacity: 1
            });
        });
        this.stage.draw();
    },

    _unhighlightNotes: function(note) {
        var notes = this.mouseoverLayer.find('.' + note);

        _.each(this.currentTweens, function(tween) {
            tween.destroy();
        });
        var noteGroup = this.noteGroup;
        notes.each(function(noteNode) {
            noteNode.moveTo(noteGroup);
            var initialOpacity = noteNode.getAttr('initialOpacity');
            noteNode.setAttrs({
                opacity: initialOpacity,
                shadowEnabled: false
            });
        });
        this.stage.draw();
    },

    _highlightSelectedNotes: function(note) {
        var notes = this.noteGroup.find('.' + note);

        _.each(this.currentTweens, function(tween) {
            tween.destroy();
        });
        var mouseoverLayer = this.mouseoverLayer;
        notes.each(function(noteNode) {
            noteNode.moveTo(mouseoverLayer);
            var color = noteNode.getAttr('color');
            noteNode.setAttrs({
                shadowBlur: 10,
                shadowEnabled: true,
                shadowColor: color,
                opacity: 1
            });
        });
        this.stage.draw();
    },

    _addNut: function(string, index, settings) {
        var rootNote = _.first(string.get('notes'));
        var rootNoteName = 'note-' + rootNote.get('name');
        var nutNoteColor = new Konva.Rect({
            x: 0,
            y: settings.stringHeight * index + settings.padding,
            width: settings.padding - settings.nutWidth,
            height: settings.stringHeight,
            fill: rootNote.get('color'),
            name: rootNoteName,
            opacity: 0.1
        });
        this.noteGroup.add(nutNoteColor);
        var nut = new Konva.Rect({
            x: settings.padding - settings.nutWidth,
            y: settings.stringHeight * index + settings.padding,
            width: settings.nutWidth,
            height: settings.stringHeight,
            fill: 'black'
        });
        this.fretGroup.add(nut);
    },

    _addNotes: function(string, index, settings) {
        for (var i = 1; i <= string.get('frets'); i++) {
            var distanceFromNut = this.collection.settings.fretDistanceMap[i];
            var fret = new Konva.Rect({
                x: (settings.padding + distanceFromNut.distance) - settings.fretWidth,
                y: settings.stringHeight * index + settings.padding,
                width: settings.fretWidth,
                height: settings.stringHeight,
                fill: 'silver'
            });
            this.fretGroup.add(fret);
            var color = new Konva.Rect({
                x: (settings.padding + distanceFromNut.distance) - distanceFromNut.width,
                y: settings.stringHeight * index + settings.padding,
                width: distanceFromNut.width - settings.fretWidth,
                height: settings.stringHeight,
                fill: string.get('notes')[i].get('color'),
                name: 'note-' + string.get('notes')[i].get('name'),
                opacity: 0.1
            });
            this.noteGroup.add(color);
        }
    },

    _addStrings: function(string, index, settings) {
        var stringOverNut = new Konva.Rect({
            x: 0,
            y: (settings.stringHeight / 2) - (settings.fretWidth / 2) + (settings.stringHeight * index) + settings.padding,
            width: settings.padding,
            height: settings.fretWidth,
            fill: string.get('notes')[0].get('color'),
            name: 'note-' + string.get('notes')[0].get('name')
        });
        this.stringGroup.add(stringOverNut);
        var string = new Konva.Rect({
            x: settings.padding,
            y: (settings.stringHeight / 2) - (settings.fretWidth / 2) + (settings.stringHeight * index) + settings.padding,
            width: this.collection.settings.displayWidth,
            height: settings.fretWidth,
            fill: 'black'
        });
        this.stringGroup.add(string);
    },

    _addToGroup: function() {
        this.fretGroup = new Konva.Group();
        this.noteGroup = new Konva.Group();
        this.stringGroup = new Konva.Group();
        var settings = this.collection.settings;

        this.collection.each(function(string, index) {
            this._addNut(string, index, settings);
            this._addNotes(string, index, settings);
            this._addStrings(string, index, settings);
        }, this);
        this.group.add(this.fretGroup);
        this.group.add(this.noteGroup);
        this.group.add(this.stringGroup);
    },

    onDestroy: function() {
        this.fretGroup.destroyChildren();
        this.noteGroup.destroyChildren();
        this.stringGroup.destroyChildren();

        Bus.Event.off('note:highlighted', this._highlightSelectedNotes, this);
        Bus.Event.off('note:unhighlighted', this._unhighlightNotes, this);
        Bus.Event.off('change:mode', this._changeMode, this);

    }
}); <|endoftext|>


<commit_before>/* Copyright 2011 the Melange authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/" + melange.config.app_version + "/js/";

  // Melange CSS URL prefix
  var mcss = "/" + melange.config.css_path + "/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "https://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "https://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.2.js"
    ];
  }
  else {
    s.jquery = [
      "https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    "/tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.counter = [
    tpjs + "jquery/jquery-counter.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.raty = [
    tpjs + "jquery/jquery.raty.js"
  ];

  s.cluetip = [
    tpjs + "jquery/jquery.cluetip.js"
   ];

  s.dimensions = [
    tpjs + "jquery/jquery.dimensions.js"
  ];

  s.scrollTo = [
    tpjs + "jquery/jquery.scrollTo.js"
  ];

  s.formbuilder = [
    s.scrollTo,
    null,
    tpjs + "jquery/jquery.formbuilder.js"
  ];

  s.colorbox = [
    tpjs + "jquery/jquery.colorbox.js"
  ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.datepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.datepicker.js"
  ];

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.mouse = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.mouse.js"
  ];

  s.jqueryui.button = [
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.button.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    new $m.cssFile(mcss + "jquery-ui/jquery.ui.autocomplete.css"),
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqueryui.dialog = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.dialog.js"
  ];

  s.jqueryui.checkboxes = [
    s.jqueryui.core,
    tpjs + "jquery/jquery.ui-checkboxes.js"
  ];

  s.jqueryui.sortable = [
    s.jqueryui.widget,
    s.jqueryui.mouse,
    null,
    tpjs + "jquery/jquery-ui.sortable.js"
  ];

  s.jqueryui.effects = [
    tpjs + "jquery/jquery-ui.effects.core.js"
  ];

  s.jqueryui.effects.blind = [
    s.jqueryui.effects,
    null,
    tpjs + "jquery/jquery-ui.effects.blind.js"
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile(mcss + "ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.fmatter.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    s.cookie,
    null,
    mpjs + "melange.js"
  ];

  s.melange.gdata = {};

  s.melange.gdata.core = [
    mpjs + "melange.gdata.core.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.datepicker,
    null,
    mpjs + "melange.datetimepicker.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    new $m.cssFile(mcss + "others.css"),
    null,
    s.jqueryui.dialog,
    s.jqueryui.button,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js",
    null,
    function () {
      if (window.melange_list_queue !== undefined && window.melange_list_queue instanceof Array) {
        jQuery.each(window.melange_list_queue, function (index, function_to_call) {
          function_to_call();
        });
      }
    }
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  s.melange.action = [
    s.dimensions,
    s.cluetip,
    s.jqueryui.checkboxes,
    null,
    mpjs + "melange.action.js"
  ];

  s.melange.map = [
    mpjs + "melange.map.js"
  ];

  s.melange.program_select = [
    mpjs + "melange.program_select.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];
    // Temporary queue with CSS paths strings.
    var _cssqueue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      }
      else if (temp_val instanceof $m.cssFile) {
        if (jQuery.inArray(temp_val.css, _cssqueue) === -1) {
          _queue.push(temp_val);
          _cssqueue.push(temp_val.css);
        }
      }
      else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).script(_queue[i].script_template).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<commit_msg>Added hashchange script to dependecy<commit_after>/* Copyright 2011 the Melange authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/" + melange.config.app_version + "/js/";

  // Melange CSS URL prefix
  var mcss = "/" + melange.config.css_path + "/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "https://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "https://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.2.js"
    ];
  }
  else {
    s.jquery = [
      "https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    "/tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.counter = [
    tpjs + "jquery/jquery-counter.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.raty = [
    tpjs + "jquery/jquery.raty.js"
  ];

  s.cluetip = [
    tpjs + "jquery/jquery.cluetip.js"
   ];

  s.dimensions = [
    tpjs + "jquery/jquery.dimensions.js"
  ];

  s.scrollTo = [
    tpjs + "jquery/jquery.scrollTo.js"
  ];

  s.formbuilder = [
    s.scrollTo,
    null,
    tpjs + "jquery/jquery.formbuilder.js"
  ];

  s.colorbox = [
    tpjs + "jquery/jquery.colorbox.js"
  ];

  s.hashchange = [
    tpjs + "jquery/jquery.ba-hashchange.js"
  ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.datepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.datepicker.js"
  ];

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.mouse = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.mouse.js"
  ];

  s.jqueryui.button = [
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.button.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    new $m.cssFile(mcss + "jquery-ui/jquery.ui.autocomplete.css"),
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqueryui.dialog = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.dialog.js"
  ];

  s.jqueryui.checkboxes = [
    s.jqueryui.core,
    tpjs + "jquery/jquery.ui-checkboxes.js"
  ];

  s.jqueryui.sortable = [
    s.jqueryui.widget,
    s.jqueryui.mouse,
    null,
    tpjs + "jquery/jquery-ui.sortable.js"
  ];

  s.jqueryui.effects = [
    tpjs + "jquery/jquery-ui.effects.core.js"
  ];

  s.jqueryui.effects.blind = [
    s.jqueryui.effects,
    null,
    tpjs + "jquery/jquery-ui.effects.blind.js"
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile(mcss + "ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.fmatter.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    s.cookie,
    null,
    mpjs + "melange.js"
  ];

  s.melange.gdata = {};

  s.melange.gdata.core = [
    mpjs + "melange.gdata.core.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.datepicker,
    null,
    mpjs + "melange.datetimepicker.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    new $m.cssFile(mcss + "others.css"),
    null,
    s.jqueryui.dialog,
    s.jqueryui.button,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js",
    null,
    function () {
      if (window.melange_list_queue !== undefined && window.melange_list_queue instanceof Array) {
        jQuery.each(window.melange_list_queue, function (index, function_to_call) {
          function_to_call();
        });
      }
    }
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  s.melange.action = [
    s.dimensions,
    s.cluetip,
    s.jqueryui.checkboxes,
    null,
    mpjs + "melange.action.js"
  ];

  s.melange.map = [
    mpjs + "melange.map.js"
  ];

  s.melange.program_select = [
    mpjs + "melange.program_select.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];
    // Temporary queue with CSS paths strings.
    var _cssqueue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      }
      else if (temp_val instanceof $m.cssFile) {
        if (jQuery.inArray(temp_val.css, _cssqueue) === -1) {
          _queue.push(temp_val);
          _cssqueue.push(temp_val.css);
        }
      }
      else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).script(_queue[i].script_template).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<|endoftext|>


<commit_before>const fs = require('fs-extra');
const path = require('path');
const winston = require('winston');

const run = () => {
    fs.copy(path.normalize('./initial-data'), path.normalize('./data'), function(error) {
        if (error) {
            winston.error(error);
        }
    });
};

if(module.parent) {
    module.exports = {run};
    process.exit(0);
}

run();<commit_msg>Fixed initializer<commit_after>const fs = require('fs-extra');
const path = require('path');
const winston = require('winston');

const run = () => {
    fs.copy(path.normalize('./initial-data'), path.normalize('./data'), function(error) {
        if (error) {
            winston.error(error);
        }
    });
};

module.exports = {
    run
};

if (!module.parent) {
    run();
}
<|endoftext|>


<commit_before>import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, useAuthentication, useInstance } from 'react-components';
import createSecureSessionStorage from 'proton-shared/lib/createSecureSessionStorage';
import { MAILBOX_PASSWORD_KEY, UID_KEY } from 'proton-shared/lib/constants';
import sentry from 'proton-shared/lib/helpers/sentry';

import * as config from './config';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';

import './app.scss';

sentry(config);

const Setup = () => {
    const { UID, login, logout } = useAuthentication();
    if (UID) {
        return <PrivateApp onLogout={logout} />;
    }
    return <PublicApp onLogin={login} />;
};

const App = () => {
    const storage = useInstance(() => createSecureSessionStorage([MAILBOX_PASSWORD_KEY, UID_KEY]));
    return (
        <div className="App body mod--hidden content">
            <ProtonApp config={config} storage={storage}>
                <Setup />
            </ProtonApp>
        </div>
    );
};

export default hot(App);
<commit_msg>Remove unnecessary wrapper<commit_after>import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, useAuthentication, useInstance } from 'react-components';
import createSecureSessionStorage from 'proton-shared/lib/createSecureSessionStorage';
import { MAILBOX_PASSWORD_KEY, UID_KEY } from 'proton-shared/lib/constants';
import sentry from 'proton-shared/lib/helpers/sentry';

import * as config from './config';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';

import './app.scss';

sentry(config);

const Setup = () => {
    const { UID, login, logout } = useAuthentication();
    if (UID) {
        return <PrivateApp onLogout={logout} />;
    }
    return <PublicApp onLogin={login} />;
};

const App = () => {
    const storage = useInstance(() => createSecureSessionStorage([MAILBOX_PASSWORD_KEY, UID_KEY]));
    return (
        <ProtonApp config={config} storage={storage}>
            <Setup />
        </ProtonApp>
    );
};

export default hot(App);
<|endoftext|>


<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global require, yo, define, brackets: true, $, jQuery, window, document, navigator*/

/**************
 *   @author : Ajain Vivek
 *   @desc : Yo.js - Templating Utility Library
 *   @license : MIT Licensed
 ***************/

(function (w, doc, un) {
    "use strict";

	window.yo = window.yo || {};
    window.yo.utils = window.yo.utils || {};

    yo.utils.template = yo.utils.template || {};

    var baseURL = "";

    //Set the base URL for template class
    var setBaseURL = function (url) {
        baseURL = url;
    };

    //Get the base URL
    var getBaseURL = function () {
        return baseURL;
    };

    //Cache the dom reference
    var cachedDOM = function (uid, root, ele, template) {

        var cacheObj = {
            uid: uid,
            ele: ele,
            template: template
        };

        var cacheId = cacheObj.uid;
        var setCache = true;
        var i;

        cachedDOM.cache = cachedDOM.cache || {};

        if (cachedDOM.cache[root] === null || cachedDOM.cache[root] === undefined) {
            cachedDOM.cache[root] = [];
        } else {
            for (i = 0; i < cachedDOM.cache[root].length; i++) {
                if (cachedDOM.cache[root][i].ele === ele) {
                    cacheId = cachedDOM.cache[root][i].uid;
                    setCache = false;
                }
            }
        }

        if (setCache) {
            cachedDOM.cache[root].push(cacheObj);
        }

        return {
            uid : cacheId
        };
    };

    //Fetch the HTML Template
    var fetchHTML = function (fileRef) {
        var ele = "";
        var url = baseURL + fileRef;
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'html',
            async: false,
            cache: false,
            success: function (html) {
                ele = html;
            },
            fail: function () {
                console.error("Error: source not found");
            }
        });

        return ele;
    };

    //Map the string with curly braces
    var getValues = function (str) {
        var vals = [], // an array to collect the strings that are found
            rxp = new RegExp("{([^}]+)}", "g"),
            curMatch;

        while ((curMatch = rxp.exec(str)) !== null) {
            vals.push(curMatch[1]);
        }

        return vals;
    };

    //Add the element on to the dom
    var add = function (options, callback) {

        var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            template: options.template || "",
            animate: options.animate || "slide",
            mode: options.mode || "append",
            data: options.data || {}
        };

        var uid = (new Date()).getTime();

        var keys = Object.keys(defaults.data);
        var html = fetchHTML(defaults.template);
        var template = html;
        var arrValues = getValues(html);
        var i, j;

        var cacheDOM = cachedDOM(uid, defaults.root, defaults.ele, defaults.template);

        //Set the data value for dom element
        for (i = 0; i < arrValues.length; i++) {
            for (j = 0; j < keys.length; j++) {
                if (arrValues[i] === keys[j]) {
                    html = html.replace("{" + keys[j] + "}", defaults.data[keys[j]]);
                }
            }
        }

        //Remove Hidden Element if it exists in the DOM
        $("#templateBuilder").remove();

        var hiddenEle = $("body").append("

");
        var ele = [];
        var arrEl = [];

        if (defaults.ele instanceof Array) {
            for (i = 0; i < defaults.ele.length; i++) {
                if (defaults.ele[i].charAt(0) === "#" || defaults.ele[i].charAt(0) === ".") {
                    arrEl = $("#templateBuilder").html(html).find(defaults.ele[i]); //Insert into the dom
                    arrEl.first().attr("uid", cacheDOM.uid);
                    ele.push(arrEl[0]);
                } else {
                    console.error("Error: Incorrect reference - pass class or id only.");
                }
            }
        } else {
            if (defaults.ele.charAt(0) === "#" || defaults.ele.charAt(0) === ".") {
                ele = $("#templateBuilder").html(html).find(defaults.ele); //Insert into the dom
                ele.first().attr("uid", cacheDOM.uid);
            } else {
                console.error("Error: Incorrect reference - pass class or id only.");
            }
        }

        if (defaults.mode === "insert") {
            $(defaults.root).html(ele);
        } else {
            $(defaults.root).append(ele);
        }

        var oRef = {
            uid: ("[uid='" + cacheDOM.uid + "']"),
            template: defaults.template,
            ele: defaults.ele
        };

        if (typeof callback === "function") {
            callback(oRef); // Execute callback function
        }

        return {
            uid: cacheDOM.uid,
            template: defaults.template,
            ele: defaults.ele
        };

    };

    //Get cached data
    var cache = function () {
        return cachedDOM.cache;
    };

    //Remove from the dom but will not be removed from cache
    var remove = function (options, callback) {

        var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            uid: options.uid || "",
            animate: options.animate || "slide"
        };
        var i, j;
        var cachedDom = cache();
        var keys = Object.keys(cachedDom);

        if (defaults.uid !== "") {
            for (i = 0; i < keys.length; i++) {
                for (j = 0; j < cachedDom[keys[i]].length; j++) {
                    if (defaults.uid === cachedDom[keys[i]][j].uid) {
                        $(keys[i]).find("[uid='" + defaults.uid + "']").remove();
                        break;
                    }
                }
            }

        } else {
            if (defaults.ele.charAt(0) === "#" || defaults.ele.charAt(0) === ".") {
                $(defaults.ele).remove();
            }
        }

    };

    //Destroy the element from dom
    var destroy = function (options, callback) {

        var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            uid: options.uid || "",
            animate: options.animate || "slide"
        };

        var i, j;
        var cachedDom = cache();
        var keys = Object.keys(cachedDom);

        if (defaults.uid !== "") {
            for (i = 0; i < keys.length; i++) {
                for (j = 0; j < cachedDom[keys[i]].length; j++) {
                    if (defaults.uid === cachedDom[keys[i]][j].uid) {
                        $(keys[i]).find("[uid='" + defaults.uid + "']").remove();
                        cachedDom[keys[i]].splice(j, 1); //Remove from cache
                        break;
                    }
                }
            }

        } else {
            if (defaults.ele.charAt(0) === "#" || defaults.ele.charAt(0) === ".") {

                for (i = 0; i < keys.length; i++) {
                    for (j = 0; j < cachedDom[keys[i]].length; j++) {
                        if (defaults.ele === cachedDom[keys[i]][j].ele) {
                            cachedDom[keys[i]].splice(j, 1); //Remove from cache
                        }
                    }
                }

                $(defaults.ele).remove();

            } else {
                console.error("Error: Incorrect reference - pass class or id only.");
            }
        }

    };

    yo.utils.template = {
        add: add,
        remove: remove,
        destroy: destroy,
        cache: cache,
        setBaseURL: setBaseURL,
        getBaseURL: getBaseURL
    };

    return yo.utils.template;

}(window, document, undefined));<commit_msg>Global Define + Array Templates<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global require, yo, define, brackets: true, $, jQuery, window, document, navigator*/

/**************
 *   @author : Ajain Vivek
 *   @desc : Yo.js - Templating Utility Library
 *   @license : MIT Licensed
 ***************/

(function (w, doc, un) {
    "use strict";

	window.yo = window.yo || {};
    window.yo.utils = window.yo.utils || {};

    yo.utils.template = yo.utils.template || {};

    var baseURL = "";
	var setBaseURL, getBaseURL, cachedDOM, fetchHTML, addElements, add, remove, destroy, cache;

    //Set the base URL for template class
    setBaseURL = function (url) {
        baseURL = url;
    };

    //Get the base URL
    getBaseURL = function () {
        return baseURL;
    };

    //Cache the dom reference
    cachedDOM = function (uid, root, ele, template) {

        var cacheObj = {
            uid: uid,
            ele: ele,
            template: template
        };

        var cacheId = cacheObj.uid;
        var setCache = true;
        var i;

        cachedDOM.cache = cachedDOM.cache || {};

        if (cachedDOM.cache[root] === null || cachedDOM.cache[root] === undefined) {
            cachedDOM.cache[root] = [];
        } else {
            for (i = 0; i < cachedDOM.cache[root].length; i++) {
                if (cachedDOM.cache[root][i].ele === ele) {
                    cacheId = cachedDOM.cache[root][i].uid;
                    setCache = false;
                }
            }
        }

        if (setCache) {
            cachedDOM.cache[root].push(cacheObj);
        }

        return {
            uid : cacheId
        };
    };

    //Fetch the HTML Template
    fetchHTML = function (fileRef) {
        var ele = "";
        var url = baseURL + fileRef;
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'html',
            async: false,
            cache: false,
            success: function (html) {
                ele = html;
            },
            fail: function () {
                console.error("Error: source not found");
            }
        });

        return ele;
    };

    //Map the string with curly braces
    var getValues = function (str) {
        var vals = [], // an array to collect the strings that are found
            rxp = new RegExp("{([^}]+)}", "g"),
            curMatch;

        while ((curMatch = rxp.exec(str)) !== null) {
            vals.push(curMatch[1]);
        }

        return vals;
    };

    //Add the element on to the dom
    add = function (options, callback) {

        var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            template: options.template || "",
            animate: options.animate || "slide",
            mode: options.mode || "append",
            data: options.data || {}
        };

		if (defaults.data instanceof Array) {
			addElements(options, callback);
		} else {
			var uid = (new Date()).getTime();

			var keys = Object.keys(defaults.data);
			var html = fetchHTML(defaults.template);
			var template = html;
			var arrValues = getValues(html);
			var i, j;

			var cacheDOM = cachedDOM(uid, defaults.root, defaults.ele, defaults.template);

			//Set the data value for dom element
			for (i = 0; i < arrValues.length; i++) {
				for (j = 0; j < keys.length; j++) {
					if (arrValues[i] === keys[j]) {
						html = html.replace("{" + keys[j] + "}", defaults.data[keys[j]]);
					}
				}
			}

			//Remove Hidden Element if it exists in the DOM
			$("#templateBuilder").remove();

			var hiddenEle = $("body").append("

");
			var ele = [];
			var arrEl = [];

			if (defaults.ele instanceof Array) {
				for (i = 0; i < defaults.ele.length; i++) {
					if (defaults.ele[i].charAt(0) === "#" || defaults.ele[i].charAt(0) === ".") {
						arrEl = $("#templateBuilder").html(html).find(defaults.ele[i]); //Insert into the dom
						arrEl.first().attr("uid", cacheDOM.uid);
						ele.push(arrEl[0]);
					} else {
						console.error("Error: Incorrect reference - pass class or id only.");
					}
				}
			} else {
				if (defaults.ele.charAt(0) === "#" || defaults.ele.charAt(0) === ".") {
					ele = $("#templateBuilder").html(html).find(defaults.ele); //Insert into the dom
					ele.first().attr("uid", cacheDOM.uid);
				} else {
					console.error("Error: Incorrect reference - pass class or id only.");
				}
			}

			if (defaults.mode === "insert") {
				$(defaults.root).html(ele);
			} else {
				$(defaults.root).append(ele);
			}

			var oRef = {
				uid: ("[uid='" + cacheDOM.uid + "']"),
				template: defaults.template,
				ele: defaults.ele
			};

			if (typeof callback === "function") {
				callback(oRef); // Execute callback function
			}

			return {
				uid: cacheDOM.uid,
				template: defaults.template,
				ele: defaults.ele
			};
		}

    };

	//Add Multiple Elements
	addElements = function (options, callback) {
		var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            template: options.template || "",
            animate: options.animate || "slide",
            mode: options.mode || "append"
        };
		var i;

		for (i = 0; i < options.data.length; i++) {
			defaults.data = options.data[i];
			if (i === options.data.length - 1) {
				add(defaults, callback);
			} else {
				add(defaults);
			}
		}
	};

    //Get cached data
    cache = function () {
        return cachedDOM.cache;
    };

    //Remove from the dom but will not be removed from cache
    remove = function (options, callback) {

        var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            uid: options.uid || "",
            animate: options.animate || "slide"
        };
        var i, j;
        var cachedDom = cache();
        var keys = Object.keys(cachedDom);

        if (defaults.uid !== "") {
            for (i = 0; i < keys.length; i++) {
                for (j = 0; j < cachedDom[keys[i]].length; j++) {
                    if (defaults.uid === cachedDom[keys[i]][j].uid) {
                        $(keys[i]).find("[uid='" + defaults.uid + "']").remove();
                        break;
                    }
                }
            }

        } else {
            if (defaults.ele.charAt(0) === "#" || defaults.ele.charAt(0) === ".") {
                $(defaults.ele).remove();
            }
        }

    };

    //Destroy the element from dom
    destroy = function (options, callback) {

        var defaults = {
            root: options.root || "body",
            ele: options.ele || "",
            uid: options.uid || "",
            animate: options.animate || "slide"
        };

        var i, j;
        var cachedDom = cache();
        var keys = Object.keys(cachedDom);

        if (defaults.uid !== "") {
            for (i = 0; i < keys.length; i++) {
                for (j = 0; j < cachedDom[keys[i]].length; j++) {
                    if (defaults.uid === cachedDom[keys[i]][j].uid) {
                        $(keys[i]).find("[uid='" + defaults.uid + "']").remove();
                        cachedDom[keys[i]].splice(j, 1); //Remove from cache
                        break;
                    }
                }
            }

        } else {
            if (defaults.ele.charAt(0) === "#" || defaults.ele.charAt(0) === ".") {

                for (i = 0; i < keys.length; i++) {
                    for (j = 0; j < cachedDom[keys[i]].length; j++) {
                        if (defaults.ele === cachedDom[keys[i]][j].ele) {
                            cachedDom[keys[i]].splice(j, 1); //Remove from cache
                        }
                    }
                }

                $(defaults.ele).remove();

            } else {
                console.error("Error: Incorrect reference - pass class or id only.");
            }
        }

    };

    yo.utils.template = {
        add: add,
        remove: remove,
        destroy: destroy,
        cache: cache,
        setBaseURL: setBaseURL,
        getBaseURL: getBaseURL
    };

    return yo.utils.template;

}(window, document, undefined));

<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: express_http_module.js
 */

var util = require("./util_module.js");
var queue = require("./queue_module.js");
var ring = require("./ring_module.js");
var account_mgr = require("./session_mgr_module.js");
var link_mgr = require("./link_mgr_module.js");
var link_entry = require("./link_entry_module.js");
var express = require('express');
var bodyParser = require('body-parser');
var state;

module.exports = {
    post: function (req, res) {
        processPost(req, res);
    },

    get: function (req, res) {
        processGet(req, res);
    },

    not_found: function (req, res) {
        processNotFound(req, res);
    },

    failure: function (req, res) {
        processFailure(err, req, res, next);
    },
};

function processPost(req, res) {
    var my_link_id, my_session, his_session;

    debug(false, "processPost", "start");
    debug(false, "processPost", "my_name=" + req.body.my_name + " link_id=" + req.body.link_id);
    state = "processPost start";

    my_link_id = Number(req.body.link_id);
    my_link = link_mgr.search(req.body.my_name, my_link_id);
    if (!my_link) {
        abend("processPost", "null my_link");
        return;
    }
    if (my_link.link_id === 0) {
        abend("processPost", "null my_link = 0");
        return;
    }

    var my_session_id = Number(req.body.session_id);
    my_session = account_mgr.search(req.body.my_name, req.body.his_name, my_session_id);
    if (!my_session) {
        abend("processPost", "null my_session");
        return;
    }
    if (my_session.session_id === 0) {
        abend("processPost", "null my_session = 0");
        return;
    }

    logit("processPost", "(" + req.body.link_id + "," + req.body.session_id + ") "  + req.body.my_name + "=>" + req.body.his_name + " {" + req.body.data + "} " + req.body.xmt_seq + "=>" + my_session.up_seq);

    if (req.body.my_name === req.body.his_name) {
        his_session = my_session;
    }
    else {
        his_session = account_mgr.search(req.body.my_name, req.body.his_name, -1);
        if (!his_session) {
            abend("processPost", "null his_session");
            return;
        }
        if (his_session.session_id === 0) {
            abend("processPost", "null his_session = 0");
            return;
        }
    }

    if (req.body.xmt_seq === my_session.up_seq) {
        queue.enqueue(his_session.queue, req.body.data);
        ring.enqueue(his_session.ring, req.body.data);
        my_session.up_seq += 1;
    } else if (req.body.xmt_seq < my_session.up_seq) {
         if (req.body.xmt_seq === 0) {
            queue.enqueue(his_session.queue, req.body.data);
            ring.enqueue(his_session.ring, req.body.data);
            my_session.up_seq = 1;
            logit("processPost", req.body.data + " post " + req.body.xmt_seq + " reset");
        } else {
            logit("processPost", "(" + req.body.link_id + "," + req.body.session_id + ") "  + req.body.my_name + "=>" + req.body.his_name + " {" + req.body.data + "} " + req.body.xmt_seq + " dropped");
        }
    } else {
        logit("***abend: processPost", req.body.data + " post seq=" + req.body.xmt_seq + " dropped");
    }
    state = "processPost end";
    debug(false, "processPost", "end");
}

function processGet (req, res) {
    debug(false, "processGet", "command=" + req.headers.command);

    if (req.headers.command === "keep_alive") {
        keepAlive(req, res);
        return;
    }

    if (req.headers.command === "get_pending_data") {
        getPendingData(req, res);
        return;
    }

    if (req.headers.command === "setup_link") {
        initLink(req, res);
        return;
    }

    if (req.headers.command === "setup_session") {
        initSession(req, res);
        return;
    }

    if (req.headers.command === "get_name_list") {
        getNameList(req, res);
        return;
    }

    debug(false, "processGet ", "start");
    debug(false, "processGet ", "link=" + req.headers.session_id + " "  + req.headers.his_name + "=>" + req.headers.my_name);
    state = "processGet start";

    var my_link_id, session_id;

    my_link_id = Number(req.headers.link_id);
    my_link = link_mgr.search(req.headers.my_name, my_link_id);
    if (!my_link) {
        abend("processGet", "null my_link");
        return;
    }
    if (my_link.link_id === 0) {
        abend("processGet", "null my_link = 0");
        return;
    }

    session_id = Number(req.headers.session_id);
    var my_session = account_mgr.search(req.headers.my_name, req.headers.his_name, session_id);
    if (!my_session) {
        abend("processGet", "null my_session");
        return;
    }
    if (my_session.session_id === 0) {
        abend("processGet", "null my_session = 0");
        return;
    }
    if (!my_session.queue) {
        abend("processGet", "null queue");
        return;
    }
    res.type('application/json');
    state = "get 2000";
    var data = queue.dequeue(my_session.queue);
    state = "get 3000";
    var data1 = ring.dequeue(my_session.ring);
    state = "get 4000";
    if (data !== data1) {
        logit("*****Abend: processGet", "queue and ring not match");
    }
    if (!data) {
        //logit("processGet", "null data");
        return;
    }
    if (!data1) {
        //logti("processGet", "null data1");
        return;
    }

    logit("processGet ", "(" + req.headers.link_id + "," + req.headers.session_id + ") "  + req.headers.his_name + "=>" + req.headers.my_name + " {" + data + "}");
    res.send(data);
    state = "processGet end";
    debug(false, "processGet ", "end");
}

function getPendingData (req, res) {
    //logit("getPendingData", "");
    res.send("response from server for getPendingData");
}

function keepAlive (req, res) {
    state = "keepAlive start";
    var my_link_id = Number(req.headers.link_id);
    //logit("keepAlive", "link_id=" + my_link_id + " my_name=" + req.headers.my_name);
    var link = link_mgr.search(req.headers.my_name, my_link_id);
    if (!link) {
        abend("keepAlive", "***null link***" + "link_id=" + my_link_id + " my_name=" + req.headers.my_name);
        return;
    }
    link_entry.keep_alive(link);
    //res.send(null);
    state = "keepAlive end";
}

function initLink (req, res) {
    state = "initLink start";
    var link = link_mgr.search_and_create(req.headers.my_name, 0);
    if (!link) {
        abend("initLink", "null link");
        return;
    }
    var link_id_str = "" + link.link_id;
    //var name_array = link_mgr.get_name_list();
    //var data = {link_id: link.link_id, name_list: name_array};
    //var data_str = JSON.stringify(data);
    res.send(link_id_str);
    logit("initLink   ", "(" + link.link_id + ",0) " + req.headers.my_name + "=>server " + link_id_str);
    state = "initLink end";
}

function getNameList (req, res) {
    debug(false, "getNameList", "(" + link.link_id + ",0) " + req.headers.my_name + "=>server");
    state = "getNameList start";
    var my_link_id;

    my_link_id = Number(req.headers.link_id);
    my_link = link_mgr.search(req.headers.my_name, my_link_id);
    if (!my_link) {
        abend("getNameList", "null my_link" + "link_id=" + my_link_id + " my_name=" + req.headers.my_name);
        return;
    }
    if (my_link.link_id === 0) {
        abend("getNameList", "null my_link = 0");
        return;
    }

    var name_array = link_mgr.get_name_list();
    name_array_str = JSON.stringify(name_array);
    res.send(name_array_str);
    debug(false, "getNameList", "(" + link.link_id + ",0) " + req.headers.my_name + "=>server " + name_array_str);
    state = "getNameList end";
}

function initSession (req, res) {
    state = "initSession start";
    var session, session_id_str;
    session = account_mgr.search_and_create(req.headers.my_name, req.headers.his_name, 0);
    if (!session) {
        abend("initSession", "null session");
        return;
    }
    session_id_str = "" + session.session_id;
    res.send(session_id_str);
    logit("initSession", "(" + req.headers.link_id + "," + session.session_id + ") " + req.headers.my_name + "=>" + req.headers.his_name);
    state = "initSession end";
}

function processNotFound (req, res) {
    console.log(req.headers);
    logit("processNotFound", "*****");
    res.type('text/plain');
    res.status(404);
    res.send('Not Found');
}

function processFailure (err, req, res, next) {
    logit("processFailure", state);
}

function debug(debug_val, str1_val, str2_val) {
    if (debug_val) {
        logit(str1_val, "==" + str2_val);
    }
}

function logit (str1_val, str2_val) {
    return util.utilLogit("NodeMain." + str1_val, str2_val);
}

function abend (str1_val, str2_val) {
    return util.utilAbend("NodeMain." + str1_val, str2_val);
}
<commit_msg>get session data<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: express_http_module.js
 */

var util = require("./util_module.js");
var queue = require("./queue_module.js");
var ring = require("./ring_module.js");
var account_mgr = require("./session_mgr_module.js");
var link_mgr = require("./link_mgr_module.js");
var link_entry = require("./link_entry_module.js");
var express = require('express');
var bodyParser = require('body-parser');
var state;

module.exports = {
    post: function (req, res) {
        processPost(req, res);
    },

    get: function (req, res) {
        processGet(req, res);
    },

    not_found: function (req, res) {
        processNotFound(req, res);
    },

    failure: function (req, res) {
        processFailure(err, req, res, next);
    },
};

function processPost(req, res) {
    var my_link_id, my_session, his_session;

    debug(false, "processPost", "start");
    debug(false, "processPost", "my_name=" + req.body.my_name + " link_id=" + req.body.link_id);
    state = "processPost start";

    my_link_id = Number(req.body.link_id);
    my_link = link_mgr.search(req.body.my_name, my_link_id);
    if (!my_link) {
        abend("processPost", "null my_link");
        return;
    }
    if (my_link.link_id === 0) {
        abend("processPost", "null my_link = 0");
        return;
    }

    var my_session_id = Number(req.body.session_id);
    my_session = account_mgr.search(req.body.my_name, req.body.his_name, my_session_id);
    if (!my_session) {
        abend("processPost", "null my_session");
        return;
    }
    if (my_session.session_id === 0) {
        abend("processPost", "null my_session = 0");
        return;
    }

    logit("processPost", "(" + req.body.link_id + "," + req.body.session_id + ") "  + req.body.my_name + "=>" + req.body.his_name + " {" + req.body.data + "} " + req.body.xmt_seq + "=>" + my_session.up_seq);

    if (req.body.my_name === req.body.his_name) {
        his_session = my_session;
    }
    else {
        his_session = account_mgr.search(req.body.my_name, req.body.his_name, -1);
        if (!his_session) {
            abend("processPost", "null his_session");
            return;
        }
        if (his_session.session_id === 0) {
            abend("processPost", "null his_session = 0");
            return;
        }
    }

    if (req.body.xmt_seq === my_session.up_seq) {
        queue.enqueue(his_session.queue, req.body.data);
        ring.enqueue(his_session.ring, req.body.data);
        my_session.up_seq += 1;
    } else if (req.body.xmt_seq < my_session.up_seq) {
         if (req.body.xmt_seq === 0) {
            queue.enqueue(his_session.queue, req.body.data);
            ring.enqueue(his_session.ring, req.body.data);
            my_session.up_seq = 1;
            logit("processPost", req.body.data + " post " + req.body.xmt_seq + " reset");
        } else {
            logit("processPost", "(" + req.body.link_id + "," + req.body.session_id + ") "  + req.body.my_name + "=>" + req.body.his_name + " {" + req.body.data + "} " + req.body.xmt_seq + " dropped");
        }
    } else {
        logit("***abend: processPost", req.body.data + " post seq=" + req.body.xmt_seq + " dropped");
    }
    state = "processPost end";
    debug(false, "processPost", "end");
}

function processGet (req, res) {
    debug(false, "processGet", "command=" + req.headers.command);

    if (req.headers.command === "keep_alive") {
        keepAlive(req, res);
        return;
    }

    if (req.headers.command === "get_pending_data") {
        getPendingData(req, res);
        return;
    }

    if (req.headers.command === "setup_link") {
        initLink(req, res);
        return;
    }

    if (req.headers.command === "setup_session") {
        initSession(req, res);
        return;
    }

    if (req.headers.command === "get_name_list") {
        getNameList(req, res);
        return;
    }

    if (req.headers.command === "get_session_data") {
        getSessionData(req, res);
        return;
    }

    debug(false, "processGet ", "start");
    debug(false, "processGet ", "link=" + req.headers.session_id + " "  + req.headers.his_name + "=>" + req.headers.my_name);
    state = "processGet start";

    var my_link_id, session_id;

    my_link_id = Number(req.headers.link_id);
    my_link = link_mgr.search(req.headers.my_name, my_link_id);
    if (!my_link) {
        abend("processGet", "null my_link");
        return;
    }
    if (my_link.link_id === 0) {
        abend("processGet", "null my_link = 0");
        return;
    }

    session_id = Number(req.headers.session_id);
    var my_session = account_mgr.search(req.headers.my_name, req.headers.his_name, session_id);
    if (!my_session) {
        abend("processGet", "null my_session");
        return;
    }
    if (my_session.session_id === 0) {
        abend("processGet", "null my_session = 0");
        return;
    }
    if (!my_session.queue) {
        abend("processGet", "null queue");
        return;
    }
    res.type('application/json');
    state = "get 2000";
    var data = queue.dequeue(my_session.queue);
    state = "get 3000";
    var data1 = ring.dequeue(my_session.ring);
    state = "get 4000";
    if (data !== data1) {
        logit("*****Abend: processGet", "queue and ring not match");
    }
    if (!data) {
        //logit("processGet", "null data");
        return;
    }
    if (!data1) {
        //logti("processGet", "null data1");
        return;
    }

    logit("processGet ", "(" + req.headers.link_id + "," + req.headers.session_id + ") "  + req.headers.his_name + "=>" + req.headers.my_name + " {" + data + "}");
    res.send(data);
    state = "processGet end";
    debug(false, "processGet ", "end");
}

function getSessionData (req, res) {
    logit("getSessionData", "session_id=" + req.headers.session_id + " "  + req.headers.his_name + "=>" + req.headers.my_name);
    var link_id, session_id;

    link_id = Number(req.headers.link_id);
    link = link_mgr.search(req.headers.my_name, link_id);
    if (!link) {
        abend("processGet", "null link");
        return;
    }

    session_id = Number(req.headers.session_id);
    var my_session = account_mgr.search(req.headers.my_name, req.headers.his_name, session_id);
    if (!my_session) {
        abend("processGet", "null my_session");
        return;
    }
    if (my_session.session_id === 0) {
        abend("processGet", "null my_session = 0");
        return;
    }
    if (!my_session.queue) {
        abend("processGet", "null queue");
        return;
    }
}

function getPendingData (req, res) {
    //logit("getPendingData", "");
    res.send("response from server for getPendingData");
}

function keepAlive (req, res) {
    state = "keepAlive start";
    var my_link_id = Number(req.headers.link_id);
    debug(false, "keepAlive", "link_id=" + my_link_id + " my_name=" + req.headers.my_name);
    var link = link_mgr.search(req.headers.my_name, my_link_id);
    if (!link) {
        abend("keepAlive", "***null link***" + "link_id=" + my_link_id + " my_name=" + req.headers.my_name);
        return;
    }
    link_entry.keep_alive(link);
    res.send(null);
    state = "keepAlive end";
}

function initLink (req, res) {
    state = "initLink start";
    var link = link_mgr.search_and_create(req.headers.my_name, 0);
    if (!link) {
        abend("initLink", "null link");
        return;
    }
    var link_id_str = "" + link.link_id;
    //var name_array = link_mgr.get_name_list();
    //var data = {link_id: link.link_id, name_list: name_array};
    //var data_str = JSON.stringify(data);
    res.send(link_id_str);
    logit("initLink   ", "(" + link.link_id + ",0) " + req.headers.my_name + "=>server " + link_id_str);
    state = "initLink end";
}

function getNameList (req, res) {
    debug(false, "getNameList", "(" + link.link_id + ",0) " + req.headers.my_name + "=>server");
    state = "getNameList start";
    var my_link_id;

    my_link_id = Number(req.headers.link_id);
    my_link = link_mgr.search(req.headers.my_name, my_link_id);
    if (!my_link) {
        abend("getNameList", "null my_link" + "link_id=" + my_link_id + " my_name=" + req.headers.my_name);
        return;
    }
    if (my_link.link_id === 0) {
        abend("getNameList", "null my_link = 0");
        return;
    }

    var name_array = link_mgr.get_name_list();
    name_array_str = JSON.stringify(name_array);
    res.send(name_array_str);
    debug(false, "getNameList", "(" + link.link_id + ",0) " + req.headers.my_name + "=>server " + name_array_str);
    state = "getNameList end";
}

function initSession (req, res) {
    state = "initSession start";
    var session, session_id_str;
    session = account_mgr.search_and_create(req.headers.my_name, req.headers.his_name, 0);
    if (!session) {
        abend("initSession", "null session");
        return;
    }
    session_id_str = "" + session.session_id;
    res.send(session_id_str);
    logit("initSession", "(" + req.headers.link_id + "," + session.session_id + ") " + req.headers.my_name + "=>" + req.headers.his_name);
    state = "initSession end";
}

function processNotFound (req, res) {
    console.log(req.headers);
    logit("processNotFound", "*****");
    res.type('text/plain');
    res.status(404);
    res.send('Not Found');
}

function processFailure (err, req, res, next) {
    logit("processFailure", state);
}

function debug(debug_val, str1_val, str2_val) {
    if (debug_val) {
        logit(str1_val, "==" + str2_val);
    }
}

function logit (str1_val, str2_val) {
    return util.utilLogit("NodeMain." + str1_val, str2_val);
}

function abend (str1_val, str2_val) {
    return util.utilAbend("NodeMain." + str1_val, str2_val);
}
<|endoftext|>


<commit_before>function changeMenuStyle(obj, new_style) {
  obj.className = new_style;
}

function showCursor(){
	document.body.style.cursor='hand';
}

function hideCursor(){
	document.body.style.cursor='default';
}

function confirmDelete(){
  if (confirm('Are you sure you want to delete?')){
    return true;
    }else{
    return false;
  }
}
function get_tree()
{

		d = new dTree('d');

		d.config.target="";

		d.add(0,-1,'Workflow');
		d.add(1,0,'Pre-screening Assays','javascript:void(0)', '', '', '');
		d.add(2,1,'STE-1','javascript:gotoPage(\'assayActionMenu.jsp\')', '', '', '');
		d.add(3,2,'run 1','javascript:void(0)');
		d.add(4,3,'In','javascript:gotoPage(\'inputActionMenu.jsp\')');
		d.add(5,4,'NCL6-7105-1','javascript:gotoPage(\'viewAliquot.jsp\')', '', '', '');
		d.add(6,4,'NCL6-7105-2','javascript:void(0)','','','');
		d.add(7,3,'Out','javascript:gotoPage(\'outputActionMenu.jsp\')');
		d.add(8,7,'NCL6.vaf','doc/astra_5.doc');
		d.add(9,2,'run 2','javascript:void(0)');
		d.add(10,9,'In','javascript:gotoPage(\'inputActionMenu.jsp\')');
		d.add(11,9,'Out','javascript:gotoPage(\'outputActionMenu.jsp\')');
		d.add(12,1,'STE-2','javascript:gotoPage(\'assayActionMenu.jsp\')');
		d.add(13,1,'STE-3','javascript:gotoPage(\'assayActionMenu.jsp\')', '', '', '');
		d.add(14,1,'PCC-1','javascript:gotoPage(\'assayActionMenu.jsp\')', '', '', '');
		d.add(15,0,'In Vitro Assays','javascript:void(0)', '', '', '');
		d.add(16,0,'In Vivo Assays','javascript:void(0)', '', '', '');

		document.write(d);
}

function add_hist()	{
	document.getElementById('hists').options[document.getElementById('hists').options.length] = new Option("new text", "new value");
}

function gotoPage(pageURL)	{
	window.location.href=pageURL;
}

function openWindow(pageURL, name, width, height) {
    window.open (pageURL, name, "alwaysRaised,dependent,status,scrollbars,resizable,width="+width+",height="+height);

}

<commit_msg>updated reference to viewAliquot<commit_after>function changeMenuStyle(obj, new_style) {
  obj.className = new_style;
}

function showCursor(){
	document.body.style.cursor='hand';
}

function hideCursor(){
	document.body.style.cursor='default';
}

function confirmDelete(){
  if (confirm('Are you sure you want to delete?')){
    return true;
    }else{
    return false;
  }
}
function get_tree()
{

		d = new dTree('d');

		d.config.target="";

		d.add(0,-1,'Workflow');
		d.add(1,0,'Pre-screening Assays','javascript:void(0)', '', '', '');
		d.add(2,1,'STE-1','javascript:gotoPage(\'assayActionMenu.jsp\')', '', '', '');
		d.add(3,2,'run 1','javascript:void(0)');
		d.add(4,3,'In','javascript:gotoPage(\'inputActionMenu.jsp\')');
		d.add(5,4,'NCL6-7105-1','javascript:gotoPage(\'viewAliquot.do?aliquotId=NCL6-7105-1\')', '', '', '');
		d.add(6,4,'NCL6-7105-2','javascript:void(0)','','','');
		d.add(7,3,'Out','javascript:gotoPage(\'outputActionMenu.jsp\')');
		d.add(8,7,'NCL6.vaf','doc/astra_5.doc');
		d.add(9,2,'run 2','javascript:void(0)');
		d.add(10,9,'In','javascript:gotoPage(\'inputActionMenu.jsp\')');
		d.add(11,9,'Out','javascript:gotoPage(\'outputActionMenu.jsp\')');
		d.add(12,1,'STE-2','javascript:gotoPage(\'assayActionMenu.jsp\')');
		d.add(13,1,'STE-3','javascript:gotoPage(\'assayActionMenu.jsp\')', '', '', '');
		d.add(14,1,'PCC-1','javascript:gotoPage(\'assayActionMenu.jsp\')', '', '', '');
		d.add(15,0,'In Vitro Assays','javascript:void(0)', '', '', '');
		d.add(16,0,'In Vivo Assays','javascript:void(0)', '', '', '');

		document.write(d);
}

function add_hist()	{
	document.getElementById('hists').options[document.getElementById('hists').options.length] = new Option("new text", "new value");
}

function gotoPage(pageURL)	{
	window.location.href=pageURL;
}

function openWindow(pageURL, name, width, height) {
    window.open (pageURL, name, "alwaysRaised,dependent,status,scrollbars,resizable,width="+width+",height="+height);

}

<|endoftext|>


<commit_before>const express = require('express')
const guilds = express.Router()
const axios = require('axios')
const statusCodes = require('../../constants/codes.js')
const discordAPIConstants = require('../../constants/discordAPI.js')
const MANAGE_CHANNEL_PERMISSION = 16
const ADMINISTRATOR_PERMISSION = 8
const dbOps = require('../../../util/dbOps.js')
const VALID_GUILD_PATCH_TYPES = {
  sendAlertsTo: [String],
  dateFormat: String,
  dateLanguage: String,
  timezone: String,
  prefix: String
}
const BOT_HEADERS = require('../../constants/discordAPIHeaders.js').bot

async function checkUserGuildPermission (req, res, next) {
  try {
    const guildId = req.params.guildId
    const user = req.session.identity.id
    // Check if the user is the owner of the guild or if the user has a role with the correct permission to view the guild profile
    const [ guildJsonRes, rolesArrayRes, memberJsonRes ] = await Promise.all([
      axios.get(`${discordAPIConstants.apiHost}/guilds/${guildId}`, BOT_HEADERS),
      axios.get(`${discordAPIConstants.apiHost}/guilds/${guildId}/roles`, BOT_HEADERS),
      axios.get(`${discordAPIConstants.apiHost}/guilds/${guildId}/members/${user}`, BOT_HEADERS)
    ])
    const guildJson = guildJsonRes.data
    const rolesArray = rolesArrayRes.data
    const memberJson = memberJsonRes.data

    // Now check if they have the permissions
    let memberHasPerm = false || guildJson.owner_id === user
    if (!memberHasPerm) {
      for (const roleObject of rolesArray) {
        const roleId = roleObject.id
        if (!memberJson.roles.includes(roleId)) continue
        memberHasPerm = memberHasPerm || ((roleObject.permissions & MANAGE_CHANNEL_PERMISSION) === MANAGE_CHANNEL_PERMISSION) || ((roleObject.permissions & ADMINISTRATOR_PERMISSION) === MANAGE_CHANNEL_PERMISSION)
      }
    }
    if (!memberHasPerm) return res.status(401).json({ code: 401, message: statusCodes['401'].message })
    req.guild = guildJson
    req.guildRoles = rolesArray
    req.guildName = guildJson.name
    next()
  } catch (err) {
    next(err)
  }
}

async function createUserGuiildProfile (req, res, next) {
  try {
    const guildId = req.params.guildId
    const guildRss = await dbOps.guildRss.get(guildId)
    if (guildRss) {
      req.guildRss = guildRss
      return next()
    }
    const result = await dbOps.guildRss.update({ id: guildId, name: req.guild.name }, true) // req.guild.name is provided through the middleware function checkUserGuildPermission
    if (result.ok !== 1) return res.status(500).json({ code: 500, message: statusCodes['500'].message })
    if (result.n === 0) return res.status(404).json({ code: 404, message: statusCodes['404'].message })
    if (result.nModified !== 1) return res.status(304).json({ code: 304, message: statusCodes['304'].message })
    next()
  } catch (err) {
    next(err)
  }
}

guilds.use('/:guildId', checkUserGuildPermission)

guilds.get('/:guildId', async (req, res, next) => {
  try {
    const guildRss = await dbOps.guildRss.get(req.params.guildId)
    if (!guildRss) return res.status(404).json({ code: 404, message: statusCodes['404'].message })
    res.json(guildRss)
  } catch (err) {
    console.log(err)
    next(err)
  }
})

// Modify a guild profile, and create it if it doesn't exist before the PATCH
guilds.patch(`/:guildId`, (req, res, next) => {
  const errors = {}
  const body = req.body
  for (const key in body) {
    const wantedType = VALID_GUILD_PATCH_TYPES[key]
    if (!wantedType) continue
    if (body[key].constructor !== wantedType || (Array.isArray(wantedType) && body[key].constructor !== wantedType[0])) {
      errors[key] = `Must be a ${Array.isArray(wantedType) ? wantedType[0].name : wantedType.name}`
    }
  }
  if (Object.keys(errors).length > 0) return res.status(403).json({ code: 403, message: errors })
  next()
}, createUserGuiildProfile, async (req, res, next) => {
  try {
    const result = await dbOps.guildRss.update({ ...req.body, id: req.params.guildId }, true)
    if (result.ok !== 1) return res.status(500).json({ code: 500, message: statusCodes['500'].message })
    if (result.n === 0) return res.status(404).json({ code: 404, message: statusCodes['404'].message })
    if (result.nModified !== 1) return res.status(304).json({ code: 304, message: statusCodes['304'].message })
    return res.json({ code: 200, message: 'ok' })
  } catch (err) {
    next(err)
  }

  res.json(req.body)
})

guilds.delete('/:guildId', async (req, res, next) => {
  try {
    const result = await dbOps.guildRss.remove({ id: req.params.guildId })
    if (result.ok !== 1) return res.status(500).json({ code: 500, message: statusCodes['500'].message })
    if (result.n === 0) return res.status(304).json({ code: 304, message: statusCodes['304'].message })
    return res.json({ code: 200, message: 'ok' })
  } catch (err) {
    next(err)
  }
})

module.exports = guilds
<commit_msg>Fix typo<commit_after>const express = require('express')
const guilds = express.Router()
const axios = require('axios')
const statusCodes = require('../../constants/codes.js')
const discordAPIConstants = require('../../constants/discordAPI.js')
const MANAGE_CHANNEL_PERMISSION = 16
const ADMINISTRATOR_PERMISSION = 8
const dbOps = require('../../../util/dbOps.js')
const VALID_GUILD_PATCH_TYPES = {
  sendAlertsTo: [String],
  dateFormat: String,
  dateLanguage: String,
  timezone: String,
  prefix: String
}
const BOT_HEADERS = require('../../constants/discordAPIHeaders.js').bot

async function checkUserGuildPermission (req, res, next) {
  try {
    const guildId = req.params.guildId
    const user = req.session.identity.id
    // Check if the user is the owner of the guild or if the user has a role with the correct permission to view the guild profile
    const [ guildJsonRes, rolesArrayRes, memberJsonRes ] = await Promise.all([
      axios.get(`${discordAPIConstants.apiHost}/guilds/${guildId}`, BOT_HEADERS),
      axios.get(`${discordAPIConstants.apiHost}/guilds/${guildId}/roles`, BOT_HEADERS),
      axios.get(`${discordAPIConstants.apiHost}/guilds/${guildId}/members/${user}`, BOT_HEADERS)
    ])
    const guildJson = guildJsonRes.data
    const rolesArray = rolesArrayRes.data
    const memberJson = memberJsonRes.data

    // Now check if they have the permissions
    let memberHasPerm = false || guildJson.owner_id === user
    if (!memberHasPerm) {
      for (const roleObject of rolesArray) {
        const roleId = roleObject.id
        if (!memberJson.roles.includes(roleId)) continue
        memberHasPerm = memberHasPerm || ((roleObject.permissions & MANAGE_CHANNEL_PERMISSION) === MANAGE_CHANNEL_PERMISSION) || ((roleObject.permissions & ADMINISTRATOR_PERMISSION) === ADMINISTRATOR_PERMISSION)
      }
    }
    if (!memberHasPerm) return res.status(401).json({ code: 401, message: statusCodes['401'].message })
    req.guild = guildJson
    req.guildRoles = rolesArray
    req.guildName = guildJson.name
    next()
  } catch (err) {
    next(err)
  }
}

async function createUserGuiildProfile (req, res, next) {
  try {
    const guildId = req.params.guildId
    const guildRss = await dbOps.guildRss.get(guildId)
    if (guildRss) {
      req.guildRss = guildRss
      return next()
    }
    const result = await dbOps.guildRss.update({ id: guildId, name: req.guild.name }, true) // req.guild.name is provided through the middleware function checkUserGuildPermission
    if (result.ok !== 1) return res.status(500).json({ code: 500, message: statusCodes['500'].message })
    if (result.n === 0) return res.status(404).json({ code: 404, message: statusCodes['404'].message })
    if (result.nModified !== 1) return res.status(304).json({ code: 304, message: statusCodes['304'].message })
    next()
  } catch (err) {
    next(err)
  }
}

guilds.use('/:guildId', checkUserGuildPermission)

guilds.get('/:guildId', async (req, res, next) => {
  try {
    const guildRss = await dbOps.guildRss.get(req.params.guildId)
    if (!guildRss) return res.status(404).json({ code: 404, message: statusCodes['404'].message })
    res.json(guildRss)
  } catch (err) {
    console.log(err)
    next(err)
  }
})

// Modify a guild profile, and create it if it doesn't exist before the PATCH
guilds.patch(`/:guildId`, (req, res, next) => {
  const errors = {}
  const body = req.body
  for (const key in body) {
    const wantedType = VALID_GUILD_PATCH_TYPES[key]
    if (!wantedType) continue
    if (body[key].constructor !== wantedType || (Array.isArray(wantedType) && body[key].constructor !== wantedType[0])) {
      errors[key] = `Must be a ${Array.isArray(wantedType) ? wantedType[0].name : wantedType.name}`
    }
  }
  if (Object.keys(errors).length > 0) return res.status(403).json({ code: 403, message: errors })
  next()
}, createUserGuiildProfile, async (req, res, next) => {
  try {
    const result = await dbOps.guildRss.update({ ...req.body, id: req.params.guildId }, true)
    if (result.ok !== 1) return res.status(500).json({ code: 500, message: statusCodes['500'].message })
    if (result.n === 0) return res.status(404).json({ code: 404, message: statusCodes['404'].message })
    if (result.nModified !== 1) return res.status(304).json({ code: 304, message: statusCodes['304'].message })
    return res.json({ code: 200, message: 'ok' })
  } catch (err) {
    next(err)
  }

  res.json(req.body)
})

guilds.delete('/:guildId', async (req, res, next) => {
  try {
    const result = await dbOps.guildRss.remove({ id: req.params.guildId })
    if (result.ok !== 1) return res.status(500).json({ code: 500, message: statusCodes['500'].message })
    if (result.n === 0) return res.status(304).json({ code: 304, message: statusCodes['304'].message })
    return res.json({ code: 200, message: 'ok' })
  } catch (err) {
    next(err)
  }
})

module.exports = guilds
<|endoftext|>


<commit_before>const _ = require('lodash');
const promisify = require('tiny-promisify');
const moment = require('moment');

const pipelineRunner = promisify(require('../../core/workers/pipeline/parent'));
const cache = require('../state/cache');
const Logger = require('../state/logger');
const broadcast = cache.get('broadcast');
const apiKeyManager= cache.get('apiKeyManager');
const gekkoManager = cache.get('gekkos');

const base = require('./baseConfig');

// starts an import
// requires a post body with a config object
module.exports = function *() {
  const mode = this.request.body.mode;

  let config = {};

  _.merge(config, base, this.request.body);

  // Attach API keys
  if(config.trader && config.trader.enabled) {

    const keys = apiKeyManager._getApiKeyPair(config.watch.exchange);

    if(!keys) {
      this.body = 'No API keys found for this exchange.';
      return;
    }

    _.merge(
      config.trader,
      keys
    );
  }

  // set type
  if(mode === 'realtime') {
    if(config.market && config.market.type)
      var type = config.market.type;
    else
      var type = 'watcher';
  } else {
    var type = '';
  }

  const id = (Math.random() + '').slice(3);

  let errored = false;

  var logType = type;
  if(logType === 'leech') {
    if(config.trader && config.trader.enabled)
      logType = 'tradebot';
    else
      logType = 'papertrader';
  }
  const logger = new Logger(logType);

  console.log('Gekko', id, 'started');

  const child = pipelineRunner(mode, config, (err, event) => {

    if(err) {
      if(errored)
        return;

      let deleted = gekkoManager.delete(id);

      if(!deleted)
        // it was already deleted
        return;

      errored = true;
      console.error('RECEIVED ERROR IN GEKKO', id);
      console.error(err);
      return broadcast({
        type: 'gekko_error',
        gekko_id: id,
        error: err
      });
    }

    if(!event)
      return;

    if(event.type === 'trade') {
      let trade = event.trade;
      gekkoManager.push(id, 'trades', trade);
      let wsEvent = {
        type: 'trade',
        gekko_id: id,
        gekko_mode: mode,
        gekko_type: type,
        emitter: 'gekko',
        trade
      }
      broadcast(wsEvent);
      return;
    } else if(event.type === 'roundtrip') {
      let roundtrip = event.roundtrip;
      gekkoManager.push(id, 'roundtrips', roundtrip);
      let wsEvent = {
        type: 'roundtrip',
        gekko_id: id,
        gekko_mode: mode,
        gekko_type: type,
        emitter: 'gekko',
        roundtrip
      }
      broadcast(wsEvent);
      return;
    } else if(event.log) {
      logger.write(event.log);
    }

    let updates = {};

    if(event.type === 'update') {
      updates.latest = event.latest;
    }  else {
      // all possible events can be found in
      // @file gekko/core/cp.js
      updates[event.type] = event[event.type];
    }

    gekkoManager.update(id, updates);
    // emit update over ws
    let wsEvent = {
      type: event.type,
      gekko_id: id,
      gekko_mode: mode,
      gekko_type: type,
      emitter: 'gekko',
      updates
    }
    broadcast(wsEvent);
  });

  const now = moment.utc().format();

  var gekko = {
    watch: config.watch,
    id,
    startAt: '',
    latest: '',
    mode,
    type
  }

  if(config.tradingAdvisor && config.tradingAdvisor.enabled) {
    gekko.strat = {
      name: config.tradingAdvisor.method,
      tradingAdvisor: config.tradingAdvisor,
      params: config[ config.tradingAdvisor.method ]
    };

    gekko.trades = [];
    gekko.roundtrips = [];

    if(config.trader && config.trader.enabled)
      gekko.trader = 'tradebot';
    else
      gekko.trader = 'paper trader';
  }

  gekkoManager.add(gekko);

  broadcast({
    type: 'new_gekko',
    gekko
  });

  this.body = gekko;
}<commit_msg>be sure to drop events without types (like log events)<commit_after>const _ = require('lodash');
const promisify = require('tiny-promisify');
const moment = require('moment');

const pipelineRunner = promisify(require('../../core/workers/pipeline/parent'));
const cache = require('../state/cache');
const Logger = require('../state/logger');
const broadcast = cache.get('broadcast');
const apiKeyManager= cache.get('apiKeyManager');
const gekkoManager = cache.get('gekkos');

const base = require('./baseConfig');

// starts an import
// requires a post body with a config object
module.exports = function *() {
  const mode = this.request.body.mode;

  let config = {};

  _.merge(config, base, this.request.body);

  // Attach API keys
  if(config.trader && config.trader.enabled) {

    const keys = apiKeyManager._getApiKeyPair(config.watch.exchange);

    if(!keys) {
      this.body = 'No API keys found for this exchange.';
      return;
    }

    _.merge(
      config.trader,
      keys
    );
  }

  // set type
  if(mode === 'realtime') {
    if(config.market && config.market.type)
      var type = config.market.type;
    else
      var type = 'watcher';
  } else {
    var type = '';
  }

  const id = (Math.random() + '').slice(3);

  let errored = false;

  var logType = type;
  if(logType === 'leech') {
    if(config.trader && config.trader.enabled)
      logType = 'tradebot';
    else
      logType = 'papertrader';
  }
  const logger = new Logger(logType);

  console.log('Gekko', id, 'started');

  const child = pipelineRunner(mode, config, (err, event) => {

    if(err) {
      if(errored)
        return;

      let deleted = gekkoManager.delete(id);

      if(!deleted)
        // it was already deleted
        return;

      errored = true;
      console.error('RECEIVED ERROR IN GEKKO', id);
      console.error(err);
      return broadcast({
        type: 'gekko_error',
        gekko_id: id,
        error: err
      });
    }

    if(!event || !event.type)
      return;

    if(event.type === 'trade') {
      let trade = event.trade;
      gekkoManager.push(id, 'trades', trade);
      let wsEvent = {
        type: 'trade',
        gekko_id: id,
        gekko_mode: mode,
        gekko_type: type,
        emitter: 'gekko',
        trade
      }
      broadcast(wsEvent);
      return;
    } else if(event.type === 'roundtrip') {
      let roundtrip = event.roundtrip;
      gekkoManager.push(id, 'roundtrips', roundtrip);
      let wsEvent = {
        type: 'roundtrip',
        gekko_id: id,
        gekko_mode: mode,
        gekko_type: type,
        emitter: 'gekko',
        roundtrip
      }
      broadcast(wsEvent);
      return;
    } else if(event.log) {
      logger.write(event.log);
    }

    let updates = {};

    if(event.type === 'update') {
      updates.latest = event.latest;
    }  else {
      // all possible events can be found in
      // @file gekko/core/cp.js
      updates[event.type] = event[event.type];
    }

    gekkoManager.update(id, updates);
    // emit update over ws
    let wsEvent = {
      type: event.type,
      gekko_id: id,
      gekko_mode: mode,
      gekko_type: type,
      emitter: 'gekko',
      updates
    }
    broadcast(wsEvent);
  });

  const now = moment.utc().format();

  var gekko = {
    watch: config.watch,
    id,
    startAt: '',
    latest: '',
    mode,
    type
  }

  if(config.tradingAdvisor && config.tradingAdvisor.enabled) {
    gekko.strat = {
      name: config.tradingAdvisor.method,
      tradingAdvisor: config.tradingAdvisor,
      params: config[ config.tradingAdvisor.method ]
    };

    gekko.trades = [];
    gekko.roundtrips = [];

    if(config.trader && config.trader.enabled)
      gekko.trader = 'tradebot';
    else
      gekko.trader = 'paper trader';
  }

  gekkoManager.add(gekko);

  broadcast({
    type: 'new_gekko',
    gekko
  });

  this.body = gekko;
}<|endoftext|>


<commit_before><script id="mathjaxscript_config_pelican_#%@#$@#" type="text/javascript">
//see https://docs.mathjax.org/en/v2.5-latest/configuration.html#using-plain-javascript
    var align = "{{align}}",
        indent = "{{indent}}",
        linebreak = {{ 'true' if process_escapes else 'false'}};

    if ({{responsive}}) {
        align = (screen.width < {{responsive_break}}) ? "left" : align;
        indent = (screen.width < {{responsive_break}}) ? "0em" : indent;
        linebreak = (screen.width < {{responsive_break}}) ? true : linebreak;
    }
    window.MathJax = {
        config: ["MMLorHTML.js"],
        TeX: {
            extensions: [
{% for ext in tex_extensions %}
    "{{ext}}"{% if not loop.last %},{% endif %}
{% endfor %}
            ],
            equationNumbers: { autoNumber: 'AMS' } },
        jax: ['input/TeX','input/MathML','output/HTML-CSS'],
        extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],
        displayAlign: align,
        displayIndent: indent,
        showMathMenu: {{'true' if show_menu else 'false'}},
        messageStyle: '{{message_style}}',
        tex2jax: {
            inlineMath: [ ['\\(','\\)'] ],
            displayMath: [ ['$$','$$'] ],
            processEscapes: {{'true' if process_escapes else 'false'}},
            preview: '{{latex_preview}}',
        },
        "HTML-CSS": {
            styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: '{{color}} !important'} },
            linebreaks: {
                automatic: linebreak,
                width: '90% container' },
        },
    };
    {% if mathjax_font != 'default' %}
    window.MathJax.AuthorInit = function() {
        MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {
            var VARIANT = MathJax.OutputJax['HTML-C}'].FONTDATA.VARIANT;
            VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
            VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
            VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
        });
        MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {
            var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;
            VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
            VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
            VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
        });
    }
    {% endif %}
</script>
<script id="mathjaxscript_pelican_#%@#$@#"
        type="text/javascript"
        src="{{source}}" >
</script><commit_msg>was ignoring linebreak_automatic setting<commit_after><script id="mathjaxscript_config_pelican_#%@#$@#" type="text/javascript">
//see https://docs.mathjax.org/en/v2.5-latest/configuration.html#using-plain-javascript
    var align = "{{align}}",
        indent = "{{indent}}",
        linebreak = {{ 'true' if linebreak_automatic else 'false'}};

    if ({{responsive}}) {
        align = (screen.width < {{responsive_break}}) ? "left" : align;
        indent = (screen.width < {{responsive_break}}) ? "0em" : indent;
        linebreak = (screen.width < {{responsive_break}}) ? true : linebreak;
    }
    window.MathJax = {
        config: ["MMLorHTML.js"],
        TeX: {
            extensions: [
{% for ext in tex_extensions %}
    "{{ext}}"{% if not loop.last %},{% endif %}
{% endfor %}
            ],
            equationNumbers: { autoNumber: 'AMS' } },
        jax: ['input/TeX','input/MathML','output/HTML-CSS'],
        extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js'],
        displayAlign: align,
        displayIndent: indent,
        showMathMenu: {{'true' if show_menu else 'false'}},
        messageStyle: '{{message_style}}',
        tex2jax: {
            inlineMath: [ ['\\(','\\)'] ],
            displayMath: [ ['$$','$$'] ],
            processEscapes: {{'true' if process_escapes else 'false'}},
            preview: '{{latex_preview}}',
        },
        "HTML-CSS": {
            styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: '{{color}} !important'} },
            linebreaks: {
                automatic: linebreak,
                width: '90% container' },
        },
    };
    {% if mathjax_font != 'default' %}
    window.MathJax.AuthorInit = function() {
        MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {
            var VARIANT = MathJax.OutputJax['HTML-C}'].FONTDATA.VARIANT;
            VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
            VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
            VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
        });
        MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {
            var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;
            VARIANT['normal'].fonts.unshift('MathJax_{{mathjax_font}}');
            VARIANT['bold'].fonts.unshift('MathJax_{{mathjax_font}}-bold');
            VARIANT['italic'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
            VARIANT['-tex-mathit'].fonts.unshift('MathJax_{{mathjax_font}}-italic');
        });
    }
    {% endif %}
</script>
<script id="mathjaxscript_pelican_#%@#$@#"
        type="text/javascript"
        src="{{source}}" >
</script><|endoftext|>