<commit_before>/*!
 * Copyright 2012-2014 Mattias Fliesberg
 *
 * This file is part of opmuse.
 *
 * opmuse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * opmuse is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with opmuse.  If not, see <http://www.gnu.org/licenses/>.
 */

define(['jquery', 'inheritance', 'bootstrap/popover', 'layout', 'domReady!'],
    function ($, inheritance, popover, layout) {

    "use strict";

    var Throb = Class.extend({
        init: function (brand) {
            var that = this;

            this.brand = brand;

            // animation duration as set in throbber.less
            // we want to always run one full cycle of the animation and never
            // stop in the middle of it...
            this.animationDuration = 700;

            this.active = 0;

            $(document).ajaxSend(function () {
                if (that.active == 0) {
                    that.start();
                }

                that.active++;
            });

            $(document).ajaxComplete(function () {
                that.active--;

                var sinceStart = new Date().getTime() - that.startTime;

                var timeout = null;

                if (sinceStart <= that.animationDuration) {
                    timeout = that.animationDuration - sinceStart;
                } else {
                    timeout = that.animationDuration * Math.ceil(sinceStart / that.animationDuration) - sinceStart;
                }

                setTimeout(function () {
                    if (that.active == 0) {
                        that.stop();
                    }
                }, timeout);
            });
        },
        stop: function () {
            $(this.brand).removeClass('throb');
        },
        start: function () {
            this.startTime = new Date().getTime();

            $(this.brand).addClass('throb');
        },
        setError: function (msg) {
            $(this.brand).addClass('error').popover({
                'content': $('<p>').text(msg).addClass('text-danger'),
                'html': true,
                'trigger': 'hover',
                'container': 'body',
                'placement': 'right bottom'
            });
        },
        unsetError: function () {
            $(this.brand).removeClass('error').popover('destroy');
        }
    });

    var instance = null;

    /**
     * This one listens to click events and loads the href in the content div
     * instead of reloading the full page.
     */
    var Ajaxify = Class.extend({
        init: function () {
            if (instance !== null) {
                throw Error('Only one instance of Ajaxify allowed!');
            }

            var that = this;

            this.throb = new Throb('.navbar-brand');

            this.contents = ['#main', '#navbar-sub', '#navbar-main', '#spacer'];

            if ($(this.contents[0]).length == 0) {
                return;
            }

            this.selector = '#top, #queue, #main, #spacer';

            this.initialURL = document.location.href;

            this.activeRequest = null;

            // setTimeout hack to ignore initial popstate that at least chrome fires,
            // but not firefox
            setTimeout(function () {
                $(window).on('popstate', function (event) {
                    var href = document.location.pathname + document.location.search;

                    if (that.activeRequest !== null) {
                        that.activeRequest.abort();
                    }

                    if (href !== null) {
                        that.loadPage(href);
                    }
                });
            });

            this.load(this.selector, false);

            $(document).on('click.ajaxify', 'a',
                function (event) {

                    var ajaxify = $(this).data('ajaxify');

                    if (typeof ajaxify != 'undefined' && ajaxify !== null && ajaxify === false) {
                        return;
                    }

                    var href = $(this).attr('href');

                    if (!event.ctrlKey && that.isRelative(href)) {
                        that.setPage(href);
                    } else {
                        // open external and ctrl-click in new window/tab
                        window.open(href, "_blank");
                    }

                    $(this).trigger('ajaxifyClick');

                    // continue propagation if the link has said attribute
                    return $(this).is("[data-ajaxify=continue]");
                }
            );

        },
        load: function (element, trigger) {
            var that = this;

            if (typeof trigger == 'undefined' || trigger === null) {
                trigger = true;
            }

            if (trigger) {
                $(this.selector).trigger('ajaxifyInit');
            }
        },
        loadPage: function (href) {
            var that = this;
            var contents = that.contents.join(',');

            layout.showOverlay();

            this.activeRequest = $.ajax(href, {
                success: function (data, textStatus, xhr) {
                    if (typeof data != 'undefined' && data !== null) {
                        that.setPageInDom(data);
                    }

                    layout.hideOverlay();
                    that.activeRequest = null;
                },
                error: function (xhr) {
                    if (xhr.statusText != 'abort') {
                        that.setPageInDom(xhr.responseText);
                    }

                    layout.hideOverlay();
                    that.activeRequest = null;
                },
            });
        },
        setPageInDom: function (data) {
            var html = $($.parseHTML(data));

            document.title = $.trim(html.find("#title").text());

            var notFound = 0;

            for (var index in this.contents) {
                var content = this.contents[index];
                var newContent = html.find(content);

                if (newContent.length === 0) {
                    notFound += 1;
                    continue;
                }

                this.setInDom(content, newContent);
            }

            $(window).scrollTop(0);

            // if none of the contents are found we just replace the whole
            // document, this happens when there's a standard cherrypy error
            if (notFound === this.contents.length) {
                var newDoc = document.open("text/html", "replace");
                newDoc.write(data);
                newDoc.close();
            }

            this.load(this.selector);
        },
        setInDom: function (content, newContent) {
            $(content).empty();

            if ($(newContent).length == 0) {
                return;
            }

            $(content)
                .append($(newContent).contents());

            this.fixAttributes(newContent, content);
        },
        fixAttributes: function (newContent, content) {
            // TODO adds attributes but doesn't remove no longer existing attributes
            $.each($(newContent).get(0).attributes, function (index, attribute) {
                $(content).attr(attribute.name, attribute.value);
            });
        },
        getPage: function (href) {
            if (!this.isRelative(href)) {
                href = this.getPathComponent(href);
            }

            return href;
        },
        setPage: function (href) {
            href = this.getPage(href);

            history.pushState({}, "", href);

            this.loadPage(href);
        },
        getPathComponent: function (href) {
            return href.match(/^http(s)?:\/\/[^\/]+(.*)/)[2];
        },
        isRelative: function (href) {
            return !/^http(s)?:\/\//.test(href);
        },
    });

    return (function() {
        if (instance === null) {
            instance = new Ajaxify();
        }

        return instance;
    })();
});
<commit_msg>in ajaxify, ignore empty string responses<commit_after>/*!
 * Copyright 2012-2014 Mattias Fliesberg
 *
 * This file is part of opmuse.
 *
 * opmuse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * opmuse is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with opmuse.  If not, see <http://www.gnu.org/licenses/>.
 */

define(['jquery', 'inheritance', 'bootstrap/popover', 'layout', 'domReady!'],
    function ($, inheritance, popover, layout) {

    "use strict";

    var Throb = Class.extend({
        init: function (brand) {
            var that = this;

            this.brand = brand;

            // animation duration as set in throbber.less
            // we want to always run one full cycle of the animation and never
            // stop in the middle of it...
            this.animationDuration = 700;

            this.active = 0;

            $(document).ajaxSend(function () {
                if (that.active == 0) {
                    that.start();
                }

                that.active++;
            });

            $(document).ajaxComplete(function () {
                that.active--;

                var sinceStart = new Date().getTime() - that.startTime;

                var timeout = null;

                if (sinceStart <= that.animationDuration) {
                    timeout = that.animationDuration - sinceStart;
                } else {
                    timeout = that.animationDuration * Math.ceil(sinceStart / that.animationDuration) - sinceStart;
                }

                setTimeout(function () {
                    if (that.active == 0) {
                        that.stop();
                    }
                }, timeout);
            });
        },
        stop: function () {
            $(this.brand).removeClass('throb');
        },
        start: function () {
            this.startTime = new Date().getTime();

            $(this.brand).addClass('throb');
        },
        setError: function (msg) {
            $(this.brand).addClass('error').popover({
                'content': $('<p>').text(msg).addClass('text-danger'),
                'html': true,
                'trigger': 'hover',
                'container': 'body',
                'placement': 'right bottom'
            });
        },
        unsetError: function () {
            $(this.brand).removeClass('error').popover('destroy');
        }
    });

    var instance = null;

    /**
     * This one listens to click events and loads the href in the content div
     * instead of reloading the full page.
     */
    var Ajaxify = Class.extend({
        init: function () {
            if (instance !== null) {
                throw Error('Only one instance of Ajaxify allowed!');
            }

            var that = this;

            this.throb = new Throb('.navbar-brand');

            this.contents = ['#main', '#navbar-sub', '#navbar-main', '#spacer'];

            if ($(this.contents[0]).length == 0) {
                return;
            }

            this.selector = '#top, #queue, #main, #spacer';

            this.initialURL = document.location.href;

            this.activeRequest = null;

            // setTimeout hack to ignore initial popstate that at least chrome fires,
            // but not firefox
            setTimeout(function () {
                $(window).on('popstate', function (event) {
                    var href = document.location.pathname + document.location.search;

                    if (that.activeRequest !== null) {
                        that.activeRequest.abort();
                    }

                    if (href !== null) {
                        that.loadPage(href);
                    }
                });
            });

            this.load(this.selector, false);

            $(document).on('click.ajaxify', 'a',
                function (event) {

                    var ajaxify = $(this).data('ajaxify');

                    if (typeof ajaxify != 'undefined' && ajaxify !== null && ajaxify === false) {
                        return;
                    }

                    var href = $(this).attr('href');

                    if (!event.ctrlKey && that.isRelative(href)) {
                        that.setPage(href);
                    } else {
                        // open external and ctrl-click in new window/tab
                        window.open(href, "_blank");
                    }

                    $(this).trigger('ajaxifyClick');

                    // continue propagation if the link has said attribute
                    return $(this).is("[data-ajaxify=continue]");
                }
            );

        },
        load: function (element, trigger) {
            var that = this;

            if (typeof trigger == 'undefined' || trigger === null) {
                trigger = true;
            }

            if (trigger) {
                $(this.selector).trigger('ajaxifyInit');
            }
        },
        loadPage: function (href) {
            var that = this;
            var contents = that.contents.join(',');

            layout.showOverlay();

            this.activeRequest = $.ajax(href, {
                success: function (data, textStatus, xhr) {
                    if (typeof data != 'undefined' && data !== null && data !== '') {
                        that.setPageInDom(data);
                    }

                    layout.hideOverlay();
                    that.activeRequest = null;
                },
                error: function (xhr) {
                    if (xhr.statusText != 'abort') {
                        that.setPageInDom(xhr.responseText);
                    }

                    layout.hideOverlay();
                    that.activeRequest = null;
                },
            });
        },
        setPageInDom: function (data) {
            var html = $($.parseHTML(data));

            document.title = $.trim(html.find("#title").text());

            var notFound = 0;

            for (var index in this.contents) {
                var content = this.contents[index];
                var newContent = html.find(content);

                if (newContent.length === 0) {
                    notFound += 1;
                    continue;
                }

                this.setInDom(content, newContent);
            }

            $(window).scrollTop(0);

            // if none of the contents are found we just replace the whole
            // document, this happens when there's a standard cherrypy error
            if (notFound === this.contents.length) {
                var newDoc = document.open("text/html", "replace");
                newDoc.write(data);
                newDoc.close();
            }

            this.load(this.selector);
        },
        setInDom: function (content, newContent) {
            $(content).empty();

            if ($(newContent).length == 0) {
                return;
            }

            $(content)
                .append($(newContent).contents());

            this.fixAttributes(newContent, content);
        },
        fixAttributes: function (newContent, content) {
            // TODO adds attributes but doesn't remove no longer existing attributes
            $.each($(newContent).get(0).attributes, function (index, attribute) {
                $(content).attr(attribute.name, attribute.value);
            });
        },
        getPage: function (href) {
            if (!this.isRelative(href)) {
                href = this.getPathComponent(href);
            }

            return href;
        },
        setPage: function (href) {
            href = this.getPage(href);

            history.pushState({}, "", href);

            this.loadPage(href);
        },
        getPathComponent: function (href) {
            return href.match(/^http(s)?:\/\/[^\/]+(.*)/)[2];
        },
        isRelative: function (href) {
            return !/^http(s)?:\/\//.test(href);
        },
    });

    return (function() {
        if (instance === null) {
            instance = new Ajaxify();
        }

        return instance;
    })();
});
<|endoftext|>


<commit_before>var React = require('react/addons');
var classes = require('react-classes');

var Notfication = React.createClass({

  mixins: [classes],

  /**
   * @function hide
   * @description Focus on the element.
   */
  open: function () {
    this.setState({
      active: true
    });
  },

  /**
   * @function hide
   * @description Focus on the element.
   */
  hide: function () {
    this.setState({
      active: false
    });
  },

  propTypes: {
    message: React.PropTypes.string,
    action: React.PropTypes.string,
    onClick: React.PropTypes.func
  },

  getInitialState: function () {
    return {
      active: false
    };
  },

  getDefaultProps: function () {
    return {
      message: '',
      action: 'Dismiss',
      onClick: function () {
        this.hide();
      }
    };
  },

  render: function () {\

    var classes = this.getClass('notficiation-bar', {
      'notification-active': this.state.active || false
    });

    return (

          {this.props.message}
          {this.props.action}

    )
  }

});

module.exports = Notfication;
<commit_msg>Remove syntax error<commit_after>var React = require('react/addons');
var classes = require('react-classes');

var Notfication = React.createClass({

  mixins: [classes],

  /**
   * @function hide
   * @description Focus on the element.
   */
  open: function () {
    this.setState({
      active: true
    });
  },

  /**
   * @function hide
   * @description Focus on the element.
   */
  hide: function () {
    this.setState({
      active: false
    });
  },

  propTypes: {
    message: React.PropTypes.string,
    action: React.PropTypes.string,
    onClick: React.PropTypes.func
  },

  getInitialState: function () {
    return {
      active: false
    };
  },

  getDefaultProps: function () {
    return {
      message: '',
      action: 'Dismiss',
      onClick: function () {
        this.hide();
      }
    };
  },

  render: function () {

    var classes = this.getClass('notficiation-bar', {
      'notification-active': this.state.active || false
    });

    return (

          {this.props.message}
          {this.props.action}

    )
  }

});

module.exports = Notfication;
<|endoftext|>


<commit_before>import { get } from '@ember/object';
import { dasherize } from '@ember/string';
import EmberObject from '@ember/object';
import MutableArray from '@ember/array/mutable';
import { A } from '@ember/array';
import MegamorphicModel, { EmbeddedMegamorphicModel } from './model';
import {
  resolveReferencesWithInternalModels,
  resolveReferencesWithRecords,
  isResolvedValue,
} from './utils/resolve';
import {
  deferArrayPropertyChange,
  deferPropertyChange,
  flushChanges,
} from './utils/notify-changes';
import { CUSTOM_MODEL_CLASS, PROXY_MODEL_CLASS } from 'ember-m3/-infra/features';
import { recordDataToRecordMap, recordToRecordArrayMap } from './utils/caches';
import { recordIdentifierFor } from '@ember-data/store';
import { assert } from '@ember/debug';

/**
 * BaseRecordArray
 *
 * @class BaseRecordArray
 */
let BaseRecordArray;
let baseRecordArrayProxyHandler;

if (PROXY_MODEL_CLASS) {
  const convertToInt = (prop) => {
    if (typeof prop === 'symbol') return null;

    const num = Number(prop);

    if (isNaN(num)) return null;

    return num % 1 === 0 ? num : null;
  };

  const BaseRecordArrayProxyHandler = class {
    get(target, key, receiver) {
      let index = convertToInt(key);

      if (index !== null) {
        return receiver.objectAt(key);
      }

      return Reflect.get(target, key, receiver);
    }

    set(target, key, value, receiver) {
      let index = convertToInt(key);

      if (index !== null) {
        receiver.replaceAt(index, value);
      } else {
        Reflect.set(target, key, value, receiver);
      }

      return true;
    }
  };

  baseRecordArrayProxyHandler = new BaseRecordArrayProxyHandler();
}

if (CUSTOM_MODEL_CLASS) {
  /**
   * BaseRecordArray
   *
   * @class BaseRecordArray
   */
  BaseRecordArray = class BaseRecordArray extends EmberObject.extend(MutableArray) {
    // public RecordArray API
    static create(...args) {
      let instance = super.create(...args);

      if (PROXY_MODEL_CLASS) {
        return new Proxy(instance, baseRecordArrayProxyHandler);
      }

      return instance;
    }

    init() {
      super.init(...arguments);
      this._references = [];
      if (!this._objects) {
        this._objects = A();
      }
      this._resolved = false;
      this.store = this.store || null;
    }

    replace(idx, removeAmt, newRecords) {
      let addAmt = get(newRecords, 'length');
      let newObjects = new Array(addAmt);

      if (addAmt > 0) {
        let _newRecords = A(newRecords);
        for (let i = 0; i < newObjects.length; ++i) {
          newObjects[i] = _newRecords.objectAt(i);
        }
      }

      this._objects.replace(idx, removeAmt, newObjects);
      this.arrayContentDidChange(idx, removeAmt, newObjects.length);
      this._registerWithObjects(newObjects);
      this._resolved = true;
    }

    objectAt(idx) {
      this._resolve();
      // TODO make this lazy again
      let record = this._objects[idx];
      return record;
    }

    _removeObject(object) {
      if (this._resolved) {
        this._objects.removeObject(object);
        deferArrayPropertyChange(this.store, this, 0, 1, 0);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
        // eager change events here; we're not processing payloads (that goes
        // through `_setInternalModels`); we're doing `unloadRecord`
        flushChanges(this.store);
      } else {
        for (let j = 0; j < this._references.length; ++j) {
          let { id, type } = this._references[j];
          let dtype = type && dasherize(type);
          // TODO we might not need the second condition
          let identifier = recordIdentifierFor(object);
          if ((dtype === null || dtype === identifier.type) && id === identifier.id) {
            this._references.splice(j, 1);
            break;
          }
        }
      }
    }

    // Private API
    _setObjects(objects, triggerChange = true) {
      let originalLength = this._objects.length;
      if (triggerChange) {
        this._objects.replace(0, this._objects.length, objects);
        deferArrayPropertyChange(this.store, this, 0, originalLength, this._objects.length);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
      } else {
        this._objects.splice(0, this._objects.length, ...objects);
      }

      this.setProperties({
        isLoaded: true,
        isUpdating: false,
      });

      this._registerWithObjects(objects);
      this._resolved = true;
    }

    _setReferences(references) {
      this._isAllReference = true;
      this._references = references;
      this._resolved = false;
      let originalLength = this._objects.length;
      this._objects = A();
      deferArrayPropertyChange(this.store, this, 0, originalLength, this._objects.length);
      deferPropertyChange(this.store, this, '[]');
      deferPropertyChange(this.store, this, 'length');
    }

    _removeRecordData(recordData) {
      if (this._resolved) {
        let record = recordDataToRecordMap.get(recordData);
        if (!record) {
          return;
        }
        let index = this._objects.indexOf(record);
        if (index > -1) {
          this._objects.removeObject(record);
          this.arrayContentDidChange(index, 1, 0);
        }
      }
    }

    _registerWithObjects(objects) {
      objects.forEach((object) => {
        if (!object || !isResolvedValue(object)) {
          return;
        }
        associateRecordWithRecordArray(object, this);
      });
    }

    _resolve() {
      if (this._resolved) {
        return;
      }

      if (this._references !== null) {
        let objects = resolveReferencesWithRecords(this.store, this._references);
        this._setObjects(objects, false);
      }

      this._resolved = true;
    }

    get length() {
      return this._resolved ? this._objects.length : this._references.length;
    }
  };
} else {
  BaseRecordArray = class BaseRecordArray extends EmberObject.extend(MutableArray) {
    // public RecordArray API
    static create(...args) {
      let instance = super.create(...args);

      assert('CUSTOM_MODEL_CLASS must be enabled to use PROXY_MODEL_CLASS', !PROXY_MODEL_CLASS);

      return instance;
    }

    init() {
      this._internalModels = A();
      super.init(...arguments);
      this._references = [];
      this._resolved = false;
      this.store = this.store || null;
    }

    replace(idx, removeAmt, newRecords) {
      let addAmt = get(newRecords, 'length');
      let newInternalModels = new Array(addAmt);

      if (addAmt > 0) {
        let _newRecords = A(newRecords);
        for (let i = 0; i < newInternalModels.length; ++i) {
          let newRecord = _newRecords.objectAt(i);
          newInternalModels[i] = newRecord._internalModel || newRecord;
        }
      }

      this._internalModels.replace(idx, removeAmt, newInternalModels);
      this._registerWithInternalModels(newInternalModels);
      this._resolved = true;

      this.arrayContentDidChange(idx, removeAmt, newRecords.length);
    }

    objectAt(idx) {
      this._resolve();
      let internalModel = this._internalModels[idx];
      return internalModel !== null && internalModel !== undefined
        ? internalModel.getRecord
          ? internalModel.getRecord()
          : internalModel
        : undefined;
    }

    // RecordArrayManager private api

    _pushInternalModels(internalModels) {
      this._resolve();
      this._internalModels.pushObjects(internalModels);
    }

    _removeInternalModels(internalModels) {
      if (this._resolved) {
        this._internalModels.removeObjects(internalModels);
        deferArrayPropertyChange(this.store, this, 0, internalModels.length, 0);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
        // eager change events here; we're not processing payloads (that goes
        // through `_setInternalModels`); we're doing `unloadRecord`
        flushChanges(this.store);
      } else {
        for (let i = 0; i < internalModels.length; ++i) {
          let internalModel = internalModels[i];

          for (let j = 0; j < this._references.length; ++j) {
            let { id, type } = this._references[j];
            let dtype = type && dasherize(type);

            if ((dtype === null || dtype === internalModel.modelName) && id === internalModel.id) {
              this._references.splice(j, 1);
              break;
            }
          }
        }
      }
    }

    // Private API

    _setInternalModels(internalModels, triggerChange = true) {
      let originalLength = this._internalModels.length;
      this._internalModels.replace(0, this._internalModels.length, internalModels);
      if (triggerChange) {
        deferArrayPropertyChange(this.store, this, 0, originalLength, this._internalModels.length);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
      }

      this.setProperties({
        isLoaded: true,
        isUpdating: false,
      });

      this._registerWithInternalModels(internalModels);
      this._resolved = true;
    }

    _setReferences(references) {
      this._isAllReference = true;
      this._references = references;
      this._resolved = false;
      let originalLength = this._internalModels.length;
      this._internalModels = A();
      deferArrayPropertyChange(this.store, this, 0, originalLength, this._internalModels.length);
      deferPropertyChange(this.store, this, '[]');
      deferPropertyChange(this.store, this, 'length');
    }

    _registerWithInternalModels(internalModels) {
      for (let i = 0, l = internalModels.length; i < l; i++) {
        let internalModel = internalModels[i];

        // allow refs to point to resources not in the store
        // TODO: instead add a schema missing ref hook; #254
        if (internalModel !== null && internalModel !== undefined && internalModel._recordArrays) {
          internalModel._recordArrays.add(this);
        }
      }
    }

    _resolve() {
      if (this._resolved) {
        return;
      }

      if (this._references !== null) {
        let internalModels = resolveReferencesWithInternalModels(this.store, this._references);
        this._setInternalModels(internalModels, false);
      }

      this._resolved = true;
    }

    get length() {
      return this._resolved ? this._internalModels.length : this._references.length;
    }
  };
}

if (PROXY_MODEL_CLASS) {
  // Add native array methods here
  Object.assign(BaseRecordArray.prototype, {
    push(...values) {
      return this.pushObjects(values);
    },

    pop(...values) {
      return this.popObjects(values);
    },

    shift(...values) {
      return this.shiftObjects(values);
    },

    unshift(...values) {
      return this.unshiftObjects(values);
    },

    splice(idx, amt, ...values) {
      return this.replace(idx, amt, values);
    },

    reverse() {
      return this.reverseObjects();
    },
  });
}

export function associateRecordWithRecordArray(record, recordArray) {
  if (record instanceof EmbeddedMegamorphicModel) {
    // embedded models can be added across tracked arrays (although this is
    // weird) but since they can't be unloaded there's no need to associate the
    // array with the model
    //
    // unloading the top model after adding one of its embedded models to some
    // other tracked array is undefined behaviour
    return;
  }
  if (CUSTOM_MODEL_CLASS) {
    if (record instanceof MegamorphicModel) {
      record._recordData._recordArrays.add(recordArray);
    } else {
      let recordArrays = recordToRecordArrayMap.get(record);
      if (!recordArrays) {
        recordToRecordArrayMap.set(record, [recordArray]);
      } else {
        recordArrays.push(recordArray);
      }
    }
  } else {
    record._internalModel._recordArrays.add(recordArray);
  }
}

export default BaseRecordArray;
<commit_msg>Use  operator instead of property access for existence checks<commit_after>import { get } from '@ember/object';
import { dasherize } from '@ember/string';
import EmberObject from '@ember/object';
import MutableArray from '@ember/array/mutable';
import { A } from '@ember/array';
import MegamorphicModel, { EmbeddedMegamorphicModel } from './model';
import {
  resolveReferencesWithInternalModels,
  resolveReferencesWithRecords,
  isResolvedValue,
} from './utils/resolve';
import {
  deferArrayPropertyChange,
  deferPropertyChange,
  flushChanges,
} from './utils/notify-changes';
import { CUSTOM_MODEL_CLASS, PROXY_MODEL_CLASS } from 'ember-m3/-infra/features';
import { recordDataToRecordMap, recordToRecordArrayMap } from './utils/caches';
import { recordIdentifierFor } from '@ember-data/store';
import { assert } from '@ember/debug';

/**
 * BaseRecordArray
 *
 * @class BaseRecordArray
 */
let BaseRecordArray;
let baseRecordArrayProxyHandler;

if (PROXY_MODEL_CLASS) {
  const convertToInt = (prop) => {
    if (typeof prop === 'symbol') return null;

    const num = Number(prop);

    if (isNaN(num)) return null;

    return num % 1 === 0 ? num : null;
  };

  const BaseRecordArrayProxyHandler = class {
    get(target, key, receiver) {
      let index = convertToInt(key);

      if (index !== null) {
        return receiver.objectAt(key);
      }

      return Reflect.get(target, key, receiver);
    }

    set(target, key, value, receiver) {
      let index = convertToInt(key);

      if (index !== null) {
        receiver.replaceAt(index, value);
      } else {
        Reflect.set(target, key, value, receiver);
      }

      return true;
    }
  };

  baseRecordArrayProxyHandler = new BaseRecordArrayProxyHandler();
}

if (CUSTOM_MODEL_CLASS) {
  /**
   * BaseRecordArray
   *
   * @class BaseRecordArray
   */
  BaseRecordArray = class BaseRecordArray extends EmberObject.extend(MutableArray) {
    // public RecordArray API
    static create(...args) {
      let instance = super.create(...args);

      if (PROXY_MODEL_CLASS) {
        return new Proxy(instance, baseRecordArrayProxyHandler);
      }

      return instance;
    }

    init() {
      super.init(...arguments);
      this._references = [];
      if (!this._objects) {
        this._objects = A();
      }
      this._resolved = false;
      this.store = this.store || null;
    }

    replace(idx, removeAmt, newRecords) {
      let addAmt = get(newRecords, 'length');
      let newObjects = new Array(addAmt);

      if (addAmt > 0) {
        let _newRecords = A(newRecords);
        for (let i = 0; i < newObjects.length; ++i) {
          newObjects[i] = _newRecords.objectAt(i);
        }
      }

      this._objects.replace(idx, removeAmt, newObjects);
      this.arrayContentDidChange(idx, removeAmt, newObjects.length);
      this._registerWithObjects(newObjects);
      this._resolved = true;
    }

    objectAt(idx) {
      this._resolve();
      // TODO make this lazy again
      let record = this._objects[idx];
      return record;
    }

    _removeObject(object) {
      if (this._resolved) {
        this._objects.removeObject(object);
        deferArrayPropertyChange(this.store, this, 0, 1, 0);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
        // eager change events here; we're not processing payloads (that goes
        // through `_setInternalModels`); we're doing `unloadRecord`
        flushChanges(this.store);
      } else {
        for (let j = 0; j < this._references.length; ++j) {
          let { id, type } = this._references[j];
          let dtype = type && dasherize(type);
          // TODO we might not need the second condition
          let identifier = recordIdentifierFor(object);
          if ((dtype === null || dtype === identifier.type) && id === identifier.id) {
            this._references.splice(j, 1);
            break;
          }
        }
      }
    }

    // Private API
    _setObjects(objects, triggerChange = true) {
      let originalLength = this._objects.length;
      if (triggerChange) {
        this._objects.replace(0, this._objects.length, objects);
        deferArrayPropertyChange(this.store, this, 0, originalLength, this._objects.length);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
      } else {
        this._objects.splice(0, this._objects.length, ...objects);
      }

      this.setProperties({
        isLoaded: true,
        isUpdating: false,
      });

      this._registerWithObjects(objects);
      this._resolved = true;
    }

    _setReferences(references) {
      this._isAllReference = true;
      this._references = references;
      this._resolved = false;
      let originalLength = this._objects.length;
      this._objects = A();
      deferArrayPropertyChange(this.store, this, 0, originalLength, this._objects.length);
      deferPropertyChange(this.store, this, '[]');
      deferPropertyChange(this.store, this, 'length');
    }

    _removeRecordData(recordData) {
      if (this._resolved) {
        let record = recordDataToRecordMap.get(recordData);
        if (!record) {
          return;
        }
        let index = this._objects.indexOf(record);
        if (index > -1) {
          this._objects.removeObject(record);
          this.arrayContentDidChange(index, 1, 0);
        }
      }
    }

    _registerWithObjects(objects) {
      objects.forEach((object) => {
        if (!object || !isResolvedValue(object)) {
          return;
        }
        associateRecordWithRecordArray(object, this);
      });
    }

    _resolve() {
      if (this._resolved) {
        return;
      }

      if (this._references !== null) {
        let objects = resolveReferencesWithRecords(this.store, this._references);
        this._setObjects(objects, false);
      }

      this._resolved = true;
    }

    get length() {
      return this._resolved ? this._objects.length : this._references.length;
    }
  };
} else {
  BaseRecordArray = class BaseRecordArray extends EmberObject.extend(MutableArray) {
    // public RecordArray API
    static create(...args) {
      let instance = super.create(...args);

      assert('CUSTOM_MODEL_CLASS must be enabled to use PROXY_MODEL_CLASS', !PROXY_MODEL_CLASS);

      return instance;
    }

    init() {
      this._internalModels = A();
      super.init(...arguments);
      this._references = [];
      this._resolved = false;
      this.store = this.store || null;
    }

    replace(idx, removeAmt, newRecords) {
      let addAmt = get(newRecords, 'length');
      let newInternalModels = new Array(addAmt);

      if (addAmt > 0) {
        let _newRecords = A(newRecords);
        for (let i = 0; i < newInternalModels.length; ++i) {
          let newRecord = _newRecords.objectAt(i);
          newInternalModels[i] = newRecord._internalModel || newRecord;
        }
      }

      this._internalModels.replace(idx, removeAmt, newInternalModels);
      this._registerWithInternalModels(newInternalModels);
      this._resolved = true;

      this.arrayContentDidChange(idx, removeAmt, newRecords.length);
    }

    objectAt(idx) {
      this._resolve();
      let internalModel = this._internalModels[idx];
      return internalModel !== null && internalModel !== undefined
        ? typeof internalModel === 'object' && 'getRecord' in internalModel
          ? internalModel.getRecord()
          : internalModel
        : undefined;
    }

    // RecordArrayManager private api

    _pushInternalModels(internalModels) {
      this._resolve();
      this._internalModels.pushObjects(internalModels);
    }

    _removeInternalModels(internalModels) {
      if (this._resolved) {
        this._internalModels.removeObjects(internalModels);
        deferArrayPropertyChange(this.store, this, 0, internalModels.length, 0);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
        // eager change events here; we're not processing payloads (that goes
        // through `_setInternalModels`); we're doing `unloadRecord`
        flushChanges(this.store);
      } else {
        for (let i = 0; i < internalModels.length; ++i) {
          let internalModel = internalModels[i];

          for (let j = 0; j < this._references.length; ++j) {
            let { id, type } = this._references[j];
            let dtype = type && dasherize(type);

            if ((dtype === null || dtype === internalModel.modelName) && id === internalModel.id) {
              this._references.splice(j, 1);
              break;
            }
          }
        }
      }
    }

    // Private API

    _setInternalModels(internalModels, triggerChange = true) {
      let originalLength = this._internalModels.length;
      this._internalModels.replace(0, this._internalModels.length, internalModels);
      if (triggerChange) {
        deferArrayPropertyChange(this.store, this, 0, originalLength, this._internalModels.length);
        deferPropertyChange(this.store, this, '[]');
        deferPropertyChange(this.store, this, 'length');
      }

      this.setProperties({
        isLoaded: true,
        isUpdating: false,
      });

      this._registerWithInternalModels(internalModels);
      this._resolved = true;
    }

    _setReferences(references) {
      this._isAllReference = true;
      this._references = references;
      this._resolved = false;
      let originalLength = this._internalModels.length;
      this._internalModels = A();
      deferArrayPropertyChange(this.store, this, 0, originalLength, this._internalModels.length);
      deferPropertyChange(this.store, this, '[]');
      deferPropertyChange(this.store, this, 'length');
    }

    _registerWithInternalModels(internalModels) {
      for (let i = 0, l = internalModels.length; i < l; i++) {
        let internalModel = internalModels[i];

        // allow refs to point to resources not in the store
        // TODO: instead add a schema missing ref hook; #254
        if (
          internalModel !== null &&
          internalModel !== undefined &&
          typeof internalModel === 'object' &&
          '_recordArrays' in internalModel
        ) {
          internalModel._recordArrays.add(this);
        }
      }
    }

    _resolve() {
      if (this._resolved) {
        return;
      }

      if (this._references !== null) {
        let internalModels = resolveReferencesWithInternalModels(this.store, this._references);
        this._setInternalModels(internalModels, false);
      }

      this._resolved = true;
    }

    get length() {
      return this._resolved ? this._internalModels.length : this._references.length;
    }
  };
}

if (PROXY_MODEL_CLASS) {
  // Add native array methods here
  Object.assign(BaseRecordArray.prototype, {
    push(...values) {
      return this.pushObjects(values);
    },

    pop(...values) {
      return this.popObjects(values);
    },

    shift(...values) {
      return this.shiftObjects(values);
    },

    unshift(...values) {
      return this.unshiftObjects(values);
    },

    splice(idx, amt, ...values) {
      return this.replace(idx, amt, values);
    },

    reverse() {
      return this.reverseObjects();
    },
  });
}

export function associateRecordWithRecordArray(record, recordArray) {
  if (record instanceof EmbeddedMegamorphicModel) {
    // embedded models can be added across tracked arrays (although this is
    // weird) but since they can't be unloaded there's no need to associate the
    // array with the model
    //
    // unloading the top model after adding one of its embedded models to some
    // other tracked array is undefined behaviour
    return;
  }
  if (CUSTOM_MODEL_CLASS) {
    if (record instanceof MegamorphicModel) {
      record._recordData._recordArrays.add(recordArray);
    } else {
      let recordArrays = recordToRecordArrayMap.get(record);
      if (!recordArrays) {
        recordToRecordArrayMap.set(record, [recordArray]);
      } else {
        recordArrays.push(recordArray);
      }
    }
  } else {
    record._internalModel._recordArrays.add(recordArray);
  }
}

export default BaseRecordArray;
<|endoftext|>


<commit_before>$(function () {
  $(".proposal-votes").on('click', '.voting-link', function(e) {
    e.preventDefault();
    var self = $(this);
    if (!self.attr('href')) {
      return;
    }

    $.ajax({
      url: self.attr('href'),
      method: 'POST'
    }).success(function(data, status, xhr) {
      // Make previous vote link clickable and current vote not clickable!
      unvote = self.parent('.proposal-votes').find('.no-hover');
      self.add(unvote).toggleClass('no-hover voting-link');
      unvote.attr('href', unvote.attr('data-href'))
            .removeAttr('data-href');
      self.attr('data-href', self.attr('href'))
          .removeAttr('href');
      // Display success message
      var successAlert = '
' +
                           '' +
                             data.message +
                           '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                         '
';
      self.parent('.proposal-votes').parent('.panel-body').append(successAlert);
      window.setTimeout(function() {
        $("#succes-vote-alert").alert('close');
      }, 3000);
    }).error(function(xhr, status, error) {
      if (xhr.responseJSON) {
        if (xhr.responseJSON.redirectUrl) {
          window.location.href = xhr.responseJSON.redirectUrl;
        } else if (xhr.responseJSON.message) {
          var errorAlert = '
' +
                             '' +
                               xhr.responseJSON.message +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                           '
';
          self.parent('.proposal-votes').parent('.panel-body').append(errorAlert);
        }
      }
    });
  });

  $(".proposal-actions").on('click', '.approve-link', function(e) {
    e.preventDefault();
    var self = $(this);
    if (!self.attr('href')) {
      return;
    }

    $.ajax({
      url: self.attr('href'),
      method: 'POST'
    }).success(function(data, status, xhr) {
      var old_href = self.attr('href');
      var new_href = old_href.replace('/approve_proposal', '/disapprove_proposal');
      self.attr('href', new_href);
      var old_title = self.attr('data-original-title');
      var new_title = old_title.replace(
        gettext('Approve the proposal.'), gettext('Disapprove the proposal.'));
      self.attr('data-original-title', new_title);
      self.removeClass('approve-link');
      self.addClass('disapprove-link');
      self.find('i').attr('class', 'icon-check-empty');
      self.find('span').html(gettext('Disapprove'));
      self.blur();

      var successAlert = '
' +
                           '' +
                             data.message +
                           '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                         '
';
      self.parents('.proposal-item').find('.proposal-votes').append(successAlert);
      window.setTimeout(function() {
        $("#succes-approved-alert").alert('close');
      }, 3000);
    }).error(function(xhr, status, error) {
      if (xhr.responseJSON) {
        if (xhr.responseJSON.redirectUrl) {
          window.location.href = xhr.responseJSON.redirectUrl;
        } else if (xhr.responseJSON.message) {
          var errorAlert = '
' +
                             '' +
                               xhr.responseJSON.message +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                           '
';
          self.parents('.proposal-item').find('.proposal-votes').append(errorAlert);
        }
      }
    });
  });

  $(".proposal-actions").on('click', '.disapprove-link', function(e) {
    e.preventDefault();
    var self = $(this);
    if (!self.attr('href')) {
      return;
    }

    $.ajax({
      url: self.attr('href'),
      method: 'POST'
    }).success(function(data, status, xhr) {
      var old_href = self.attr('href');
      var new_href = old_href.replace('/disapprove_proposal', '/approve_proposal');
      self.attr('href', new_href);
      var old_title = self.attr('data-original-title');
      var new_title = old_title.replace(
        gettext('Disapprove the proposal.'), gettext('Approve the proposal.'));
      self.attr('data-original-title', new_title);
      self.removeClass('disapprove-link');
      self.addClass('approve-link');
      self.find('i').attr('class', 'icon-check');
      self.find('span').html(gettext('Approve'));
      self.blur();

      var successAlert = '
' +
                           '' +
                             data.message +
                           '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                         '
';
      self.parents('.proposal-item').find('.proposal-votes').append(successAlert);
      window.setTimeout(function() {
        $("#succes-disapproved-alert").alert('close');
      }, 3000);
    }).error(function(xhr, status, error) {
      if (xhr.responseJSON) {
        if (xhr.responseJSON.redirectUrl) {
          window.location.href = xhr.responseJSON.redirectUrl;
        } else if (xhr.responseJSON.message) {
          var errorAlert = '
' +
                             '' +
                               xhr.responseJSON.message +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                           '
';
          self.parents('.proposal-item').find('.proposal-votes').append(errorAlert);
        }
      }
    });
  });
});
<commit_msg>Close #235 - Add csrf token to the $.ajax calls.<commit_after>$(function () {
    function getCookie(name) {
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
          var cookie = jQuery.trim(cookies[i]);
          // Does this cookie string begin with the name we want?
          if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
          }
        }
      }
      return cookieValue;
  }

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
      }
    }
  });

  $(".proposal-votes").on('click', '.voting-link', function(e) {
    e.preventDefault();
    var self = $(this);
    if (!self.attr('href')) {
      return;
    }

    $.ajax({
      url: self.attr('href'),
      method: 'POST'
    }).success(function(data, status, xhr) {
      // Make previous vote link clickable and current vote not clickable!
      unvote = self.parent('.proposal-votes').find('.no-hover');
      self.add(unvote).toggleClass('no-hover voting-link');
      unvote.attr('href', unvote.attr('data-href'))
            .removeAttr('data-href');
      self.attr('data-href', self.attr('href'))
          .removeAttr('href');
      // Display success message
      var successAlert = '
' +
                           '' +
                             data.message +
                           '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                         '
';
      self.parent('.proposal-votes').parent('.panel-body').append(successAlert);
      window.setTimeout(function() {
        $("#succes-vote-alert").alert('close');
      }, 3000);
    }).error(function(xhr, status, error) {
      if (xhr.responseJSON) {
        if (xhr.responseJSON.redirectUrl) {
          window.location.href = xhr.responseJSON.redirectUrl;
        } else if (xhr.responseJSON.message) {
          var errorAlert = '
' +
                             '' +
                               xhr.responseJSON.message +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                           '
';
          self.parent('.proposal-votes').parent('.panel-body').append(errorAlert);
        }
      }
    });
  });

  $(".proposal-actions").on('click', '.approve-link', function(e) {
    e.preventDefault();
    var self = $(this);
    if (!self.attr('href')) {
      return;
    }

    $.ajax({
      url: self.attr('href'),
      method: 'POST'
    }).success(function(data, status, xhr) {
      var old_href = self.attr('href');
      var new_href = old_href.replace('/approve_proposal', '/disapprove_proposal');
      self.attr('href', new_href);
      var old_title = self.attr('data-original-title');
      var new_title = old_title.replace(
        gettext('Approve the proposal.'), gettext('Disapprove the proposal.'));
      self.attr('data-original-title', new_title);
      self.removeClass('approve-link');
      self.addClass('disapprove-link');
      self.find('i').attr('class', 'icon-check-empty');
      self.find('span').html(gettext('Disapprove'));
      self.blur();

      var successAlert = '
' +
                           '' +
                             data.message +
                           '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                         '
';
      self.parents('.proposal-item').find('.proposal-votes').append(successAlert);
      window.setTimeout(function() {
        $("#succes-approved-alert").alert('close');
      }, 3000);
    }).error(function(xhr, status, error) {
      if (xhr.responseJSON) {
        if (xhr.responseJSON.redirectUrl) {
          window.location.href = xhr.responseJSON.redirectUrl;
        } else if (xhr.responseJSON.message) {
          var errorAlert = '
' +
                             '' +
                               xhr.responseJSON.message +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                           '
';
          self.parents('.proposal-item').find('.proposal-votes').append(errorAlert);
        }
      }
    });
  });

  $(".proposal-actions").on('click', '.disapprove-link', function(e) {
    e.preventDefault();
    var self = $(this);
    if (!self.attr('href')) {
      return;
    }

    $.ajax({
      url: self.attr('href'),
      method: 'POST'
    }).success(function(data, status, xhr) {
      var old_href = self.attr('href');
      var new_href = old_href.replace('/disapprove_proposal', '/approve_proposal');
      self.attr('href', new_href);
      var old_title = self.attr('data-original-title');
      var new_title = old_title.replace(
        gettext('Disapprove the proposal.'), gettext('Approve the proposal.'));
      self.attr('data-original-title', new_title);
      self.removeClass('disapprove-link');
      self.addClass('approve-link');
      self.find('i').attr('class', 'icon-check');
      self.find('span').html(gettext('Approve'));
      self.blur();

      var successAlert = '
' +
                           '' +
                             data.message +
                           '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                         '
';
      self.parents('.proposal-item').find('.proposal-votes').append(successAlert);
      window.setTimeout(function() {
        $("#succes-disapproved-alert").alert('close');
      }, 3000);
    }).error(function(xhr, status, error) {
      if (xhr.responseJSON) {
        if (xhr.responseJSON.redirectUrl) {
          window.location.href = xhr.responseJSON.redirectUrl;
        } else if (xhr.responseJSON.message) {
          var errorAlert = '
' +
                             '' +
                               xhr.responseJSON.message +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                           '
';
          self.parents('.proposal-item').find('.proposal-votes').append(errorAlert);
        }
      }
    });
  });
});
<|endoftext|>


<commit_before>/*jslint browser: true, devel: true */
/**

=head1 Accessions.js

Dialogs for managing accessions

=head1 AUTHOR

Jeremy D. Edwards <jde22@cornell.edu>

=cut

*/

var $j = jQuery.noConflict();

jQuery(document).ready(function ($) {

    var list = new CXGN.List();

    $( "#add_accessions_dialog" ).dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		verify_accession_list();
		//$(this).dialog( "close" );
		//location.reload();
	    }
	}
    });

    $('#add_accessions_link').click(function () {
        $('#add_accessions_dialog').dialog("open");
	$("#list_div").append(list.listSelect("accessions"));
    });

    function verify_accession_list () {
	var accession_list_id = $('#accessions_list_select').val();
	var accession_list = JSON.stringify(list.getList(accession_list_id));
	alert(accession_list);

	$.ajax({
	    type: 'POST',
	    url: '/ajax/accession_list/verify',
	    dataType: "json",
	    data: {
                'accession_list': accession_list,
	    },
	    success: function (response) {
                if (response.error) {
		    alert(response.error);
                } else {
		    alert('success');
                }
	    },
	    error: function () {
                alert('An error occurred in processing. sorry');
	    }
        });
    }
    $( "${0:my_dialog_div_id}" ).dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
	width: 500,
	position: ['top', 150],
	buttons: {
	    Ok: function() {

	    },
	}
    });

});
<commit_msg>arrange js functions in better order<commit_after>/*jslint browser: true, devel: true */
/**

=head1 Accessions.js

Dialogs for managing accessions

=head1 AUTHOR

Jeremy D. Edwards <jde22@cornell.edu>

=cut

*/

var $j = jQuery.noConflict();

jQuery(document).ready(function ($) {

    var list = new CXGN.List();

    function verify_accession_list () {
	var accession_list_id = $('#accessions_list_select').val();
	var accession_list = JSON.stringify(list.getList(accession_list_id));
	alert(accession_list);

	$.ajax({
	    type: 'POST',
	    url: '/ajax/accession_list/verify',
	    dataType: "json",
	    data: {
                'accession_list': accession_list,
	    },
	    success: function (response) {
                if (response.error) {
		    alert(response.error);
                } else {
		    alert('success');
                }
	    },
	    error: function () {
                alert('An error occurred in processing. sorry');
	    }
        });
    }

    $( "#add_accessions_dialog" ).dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		verify_accession_list();
		//$(this).dialog( "close" );
		//location.reload();
	    }
	}
    });

    $('#add_accessions_link').click(function () {
        $('#add_accessions_dialog').dialog("open");
	$("#list_div").append(list.listSelect("accessions"));
    });

    $( "${0:my_dialog_div_id}" ).dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
	width: 500,
	position: ['top', 150],
	buttons: {
	    Ok: function() {

	    },
	}
    });

});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

MODEL({
  package: 'foam.core.bootstrap',
  name: 'ChromeAppFileDAO',

  imports: [
    'document',
    'window'
  ],

  properties: [
    {
      name: 'pending',
      factory: function() { return {}; }
    },
    {
      name: 'preload',
      factory: function() { return {}; }
    },
    {
      name: 'rootPath',
      factory: function() {
        return this.window.FOAM_BOOT_DIR + '../js/';
      }
    },
    'looking_'
  ],

  methods: {
    toURL_: function(key) {
      return this.rootPath + key.replace(/\./g, '/') + '.js';
    },
    find: function(key, sink) {
      if ( this.preload[key] ) {
        sink && sink.put && sink.put(this.preload[key]);
        delete this.preload[key];
        return;
      }

      if ( this.pending[key] ) {
        this.pending[key].push(sink);
        return;
      }

      this.pending[key] = [sink];

      var tag;
      var onerror = function() {
        var pending = this.pending[key];
        delete this.pending[key];
        for ( var i = 0 ; i < pending.length ; i++ ) {
          pending[i] && pending[i].error && pending[i].error.apply(null, arguments);
        }
        if ( tag ) tag.remove();
      }.bind(this);

      aseq(
        function(ret) {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", this.toURL_(key));
          xhr.responseType = "blob";
          xhr.onreadystatechange = function() {
            if ( xhr.readyState != xhr.DONE ) return;

            if ( xhr.status >= 200 && xhr.status < 300 ) {
              ret(xhr.response);
              return;
            }
            ret(null);
          };
          xhr.send();
        }.bind(this),
        function(ret, blob) {
          if (!blob) {
            onerror();
            return;
          }

          tag = this.document.createElement('script');
          var looking = key;

          tag.callback = function(data, latch) {
            var work = [anop];
	    data.sourcePath = this.toURL_(key);

            var obj = JSONUtil.mapToObj(this.X, data, undefined, work);

            if ( ! obj ) throw new Error('Failed to decode data: ' + data);

            if ( looking === obj.id ) looking = null;

            if ( ! this.pending[obj.id] ) {
              if ( latch ) {
                latch(data);
              } else {
                // Workaround for legacy apps that include extra models via
                // additional script tags.
                this.preload[obj.id] = obj;
              }
              return;
            }

            aseq.apply(null, work)(
              function(ret) {
                var sinks = this.pending[obj.id];
                delete this.pending[obj.id];
                if ( sinks ) {
                  for ( var i = 0; i < sinks.length ; i++ ) {
                    var sink = sinks[i];
                    sink && sink.put && sink.put(obj);
                  }
                }
              }.bind(this));
          }.bind(this);

          tag.onload = function() {
            if ( looking != null ) {
              onerror();
            }
            tag.remove();
          };
          tag.onerror = onerror;

          tag.src = this.window.URL.createObjectURL(blob);

          this.document.head.appendChild(tag);
        }.bind(this))(function(){});
    }
  }
});
<commit_msg>Switch ChromeAppFileDAO to use aMapToObj.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

MODEL({
  package: 'foam.core.bootstrap',
  name: 'ChromeAppFileDAO',

  imports: [
    'document',
    'window'
  ],

  properties: [
    {
      name: 'pending',
      factory: function() { return {}; }
    },
    {
      name: 'preload',
      factory: function() { return {}; }
    },
    {
      name: 'rootPath',
      factory: function() {
        return this.window.FOAM_BOOT_DIR + '../js/';
      }
    },
    'looking_'
  ],

  methods: {
    toURL_: function(key) {
      return this.rootPath + key.replace(/\./g, '/') + '.js';
    },
    find: function(key, sink) {
      if ( this.preload[key] ) {
        sink && sink.put && sink.put(this.preload[key]);
        delete this.preload[key];
        return;
      }

      if ( this.pending[key] ) {
        this.pending[key].push(sink);
        return;
      }

      this.pending[key] = [sink];

      var tag;
      var onerror = function() {
        var pending = this.pending[key];
        delete this.pending[key];
        for ( var i = 0 ; i < pending.length ; i++ ) {
          pending[i] && pending[i].error && pending[i].error.apply(null, arguments);
        }
        if ( tag ) tag.remove();
      }.bind(this);

      aseq(
        function(ret) {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", this.toURL_(key));
          xhr.responseType = "blob";
          xhr.onreadystatechange = function() {
            if ( xhr.readyState != xhr.DONE ) return;

            if ( xhr.status >= 200 && xhr.status < 300 ) {
              ret(xhr.response);
              return;
            }
            ret(null);
          };
          xhr.send();
        }.bind(this),
        function(ret, blob) {
          if (!blob) {
            onerror();
            return;
          }

          tag = this.document.createElement('script');
          var looking = key;

          tag.callback = function(data, latch) {
	    data.sourcePath = this.toURL_(key);

	    if ( looking === data.package + '.' + data.name ) looking = null;

	    aseq(
	      JSONUtil.aMapToObj(this.X, data),
	      function(ret, obj) {
		if ( ! obj ) throw new Error('Failed to decode data: ' + data);

		if ( ! this.pending[obj.id] ) {
		  if ( latch ) {
                    latch(data);
		  } else {
                    // Workaround for legacy apps that include extra models via
                    // additional script tags.
                    this.preload[obj.id] = obj;
		  }
		  return;
		}

                var sinks = this.pending[obj.id];
                delete this.pending[obj.id];
                if ( sinks ) {
                  for ( var i = 0; i < sinks.length ; i++ ) {
                    var sink = sinks[i];
                    sink && sink.put && sink.put(obj);
                  }
                }
              }.bind(this))();
          }.bind(this);

          tag.onload = function() {
            if ( looking != null ) {
              onerror();
            }
            tag.remove();
          };
          tag.onerror = onerror;

          tag.src = this.window.URL.createObjectURL(blob);

          this.document.head.appendChild(tag);
        }.bind(this))(function(){});
    }
  }
});
<|endoftext|>


<commit_before>import { List, Record } from 'immutable';
import yaml from 'components/helpers/parseYaml';
import Team from './team';
import Tournament from './tournament';
import User from './user';

const defaultVideo = {
  id: null,
  createdAt: null,
  debateType: null,
  debateLevel: null,
  thumbnail: null,
  key: null,
  provider: null,
  liveNow: false,
  isFeatured: false,
  tournamentId: null,
  tournament: new Tournament(),
  favoritesCount: 0,
  affTeamId: null,
  affTeam: new Team(),
  negTeamId: null,
  negTeam: new Team(),
  tags: List(),
  tagsVideos: null,
  views: 0,
  user: new User(),
};

export default class Video extends Record(defaultVideo) {
  getTitle() {
    return `${this.tournament.getYearAndName()}: ${this.affTeam.getTeamCode()} vs. ${this.negTeam.getTeamCode()}`;
  }

  getThumbnail() {
    if(this.provider === 0) {
      return `https://img.youtube.com/vi/${this.key.first}/hqdefault.jpg`;
    } else if(this.thumbnail) {
      return this.thumbnail.replace('200x150', '600x450');
    }
  }

  getFrameProps() {
    const keyArray = yaml(this.key);
    const firstKey = keyArray.shift();

    let src;
    let providerProps;

    if(this.provider === 0) {
      src = `https://www.youtube.com/embed/${firstKey}?origin=https://debatevid.io`;
      if(keyArray.length > 0) {
        src = `${src}&playlist=${keyArray.join(',')}`;
      }
      providerProps = {
        type: 'text/html',
      };
    } else if(this.provider === 1) {
      src = `https://player.vimeo.com/video/${firstKey}`;
      providerProps = {
        webkitallowfullscreen: true,
        mozallowfullscreen: true,
        allowfullscreen: true,
      };
    }

    return Object.assign({
      id: 'vidframe',
      frameBorder: 0,
      src,
    }, providerProps);
  }

  matchingTag(term) {
    return this.tags.find((tag) => tag.matches(term)) !== undefined;
  }

  matchingTagId(id) {
    return this.tags.find((tag) => tag.id === id) !== undefined;
  }

  matches(term) {
    if(term === '') {
      return true;
    } else {
      return this.getTitle().toLowerCase().includes(term.toLowerCase()) || this.matchingTag(term);
    }
  }
}
<commit_msg>dammit<commit_after>import { List, Record } from 'immutable';
import yaml from 'components/helpers/parseYaml';
import Team from './team';
import Tournament from './tournament';
import User from './user';

const defaultVideo = {
  id: null,
  createdAt: null,
  debateType: null,
  debateLevel: null,
  thumbnail: null,
  key: null,
  provider: null,
  liveNow: false,
  isFeatured: false,
  tournamentId: null,
  tournament: new Tournament(),
  favoritesCount: 0,
  affTeamId: null,
  affTeam: new Team(),
  negTeamId: null,
  negTeam: new Team(),
  tags: List(),
  tagsVideos: null,
  views: 0,
  user: new User(),
};

export default class Video extends Record(defaultVideo) {
  getTitle() {
    return `${this.tournament.getYearAndName()}: ${this.affTeam.getTeamCode()} vs. ${this.negTeam.getTeamCode()}`;
  }

  getThumbnail() {
    if(this.provider === 0) {
      return `https://img.youtube.com/vi/${yaml(this.key).shift()}/hqdefault.jpg`;
    } else if(this.thumbnail) {
      return this.thumbnail.replace('200x150', '600x450');
    }
  }

  getFrameProps() {
    const keyArray = yaml(this.key);
    const firstKey = keyArray.shift();

    let src;
    let providerProps;

    if(this.provider === 0) {
      src = `https://www.youtube.com/embed/${firstKey}?origin=https://debatevid.io`;
      if(keyArray.length > 0) {
        src = `${src}&playlist=${keyArray.join(',')}`;
      }
      providerProps = {
        type: 'text/html',
      };
    } else if(this.provider === 1) {
      src = `https://player.vimeo.com/video/${firstKey}`;
      providerProps = {
        webkitallowfullscreen: true,
        mozallowfullscreen: true,
        allowfullscreen: true,
      };
    }

    return Object.assign({
      id: 'vidframe',
      frameBorder: 0,
      src,
    }, providerProps);
  }

  matchingTag(term) {
    return this.tags.find((tag) => tag.matches(term)) !== undefined;
  }

  matchingTagId(id) {
    return this.tags.find((tag) => tag.id === id) !== undefined;
  }

  matches(term) {
    if(term === '') {
      return true;
    } else {
      return this.getTitle().toLowerCase().includes(term.toLowerCase()) || this.matchingTag(term);
    }
  }
}
<|endoftext|>


<commit_before>/**
 *
 * Copyright (c) Chong-U Lim
 * http://github.com/chongdashu
 */
this.chongdashu = this.chongdashu||{};

(function() {
    "use strict";

/**
 * Entity
 * @class Entity
 * @constructor
 **/
var Entity = function(state) {
    this.init(state);
};
var p = Entity.prototype;
Entity.prototype.constructor = Entity;

    p.komponents = {};

    p.init = function(state)
    {
        console.log("[Entity], init()");
        this.state = state;
        this.game = state.game;
        this.komponents = {};
    };

    p.add = function(component) {
        if (typeof this.komponents == "undefined" || this.komponents === null) {
            // initialize an empty dictionary
            this.komponents = {};
        }
        // add this component to the entity's map of components
        this.komponents[component.getType()] = component;
        return this;
    };

    p.remove = function(componentOrType) {
        var type = "";
        if (typeof componentOrType == "string") {
            type = componentOrType;
        }
        else if (typeof componentOrType == "object") {
            type = componentOrType.getType();
        }
        else {
            console.warn("[Entity], remove(), unknown component or type param=%s", componentOrType);
        }

        if (type) {
            if (type in this.komponents) {
                var component = this.komponents[type];
                delete this.komponents[type];
            }
            else {
                console.warn("[Entity], remove(), component type=%s doesn't exist in entity.", type);
            }
        }

    };

    p.get = function(componentType) {
        return this.komponents[componentType];
    };

    p.getAll = function() {
        var components = [];
        $.each(this.komponents, function(index, component) {
            components.push(component);
        });

        return component;
    };

    p.isComponent = function(componentType) {
        return componentType in this.komponents && this.komponents[componentType] !== null;
    };

    p.update = function() {

    };

    p.render = function() {

    };

// Link
// ----
chongdashu.Entity = Entity;

}());

<commit_msg>Add stuff to entity<commit_after>/**
 *
 * Copyright (c) Chong-U Lim
 * http://github.com/chongdashu
 */
this.chongdashu = this.chongdashu||{};

(function() {
    "use strict";

/**
 * Entity
 * @class Entity
 * @constructor
 **/
var Entity = function(state) {
    this.init(state);
};
var p = Entity.prototype;
Entity.prototype.constructor = Entity;

    p._components = {};
    p.onComponentAddCallbacks = [];
    p.onComponentRemoveCallbacks = [];

    p.init = function(state)
    {
        console.log("[Entity], init()");
        this.state = state;
        this.game = state.game;
        this._components = {};
        this.onComponentAddCallbacks = [];
        this.onComponentRemoveCallbacks = [];
    };

    p.add = function(component) {
        if (typeof this._components == "undefined" || this._components === null) {
            // initialize an empty dictionary
            this._components = {};
        }
        // add this component to the entity's map of components
        this._components[component.getType()] = component;

        // dispatch callbacks
        for (var i=0; i < this.onComponentAddCallbacks; i++) {
            this.onComponentAddCallbacks[i](this, component.getType());
        }

        return this;
    };

    p.remove = function(componentOrType) {
        var type = "";
        if (typeof componentOrType == "string") {
            type = componentOrType;
        }
        else if (typeof componentOrType == "object") {
            type = componentOrType.getType();
        }
        else {
            console.warn("[Entity], remove(), unknown component or type param=%s", componentOrType);
        }

        var component = null;

        if (type) {
            if (type in this._components) {
                // get the component
                component = this._components[type];

                // remove the key entry
                delete this._components[type];

                // dispatch callbacks
                for (var i=0; i < this.onComponentRemoveCallbacks; i++) {
                    this.onComponentRemoveCallbacks[i](this, component.getType());
                }
            }
            else {
                console.warn("[Entity], remove(), component type=%s doesn't exist in entity.", type);
            }
        }

        return component;

    };

    p.get = function(componentType) {
        return this._components[componentType];
    };

    p.getAll = function() {
        var components = [];
        for (var i=0; i < this._components.length; i++) {
            components.push(this._components[i]);
        }

        return component;
    };

    p.isComponent = function(componentType) {
        return componentType in this._components && this._components[componentType] !== null;
    };

    p.addOnComponentAddCallback = function(callback) {
        this.onComponentAddCallbacks.push(callback);
    };

    p.removeOnComponentRemoveCallback = function(callback) {
        this.onComponentRemoveCallbacks.push(callback);
    };

// Link
// ----
chongdashu.Entity = Entity;

}());

<|endoftext|>


<commit_before>'use strict';

const favicon = require('serve-favicon');
const debug = require('debug')('express-test:server');

const config = require('./config/config'),
	BASE_URL = `http://127.0.0.1:${config.port}`;

var electron 		= require('electron'),
	electronApp 	= electron.app,
	BrowserWindow 	= electron.BrowserWindow,
	async 	 		= require('async'),
	mongoose 		= require('mongoose'),
	express  		= require('express'),
	electronConfig  = require('./config/electronConfig'),
	http 	 		= require('http');

electronApp.on('window-all-closed', function() {
	if (process.platform !== 'darwin') {
		electronApp.quit();
	}
});

electronApp.on('ready', function() {
	async.series({
		mongodb: (done) => {
			var db = mongoose.connection;

			db.once('open', () => {
				console.log('Connected to MongoDB Server.');

				require('./app/models/gps.model.js');
				done(null, db);
			});

			db.once('close', () => {
				mongoose.disconnect(() => {
					console.log('MongoDB Connection Closed.');
				});
			});

			console.log('Connecting to MongoDB Server...');

			let connectWithRetry = () => {
				mongoose.connect(config.mongo.url, {}, (error) => {
					if (error) {
						console.error('Failed to connect to mongo on startup - retrying in 5 sec', error);
						setTimeout(connectWithRetry, 5000);
					}
				});
			};

			connectWithRetry();
		},
		mainWindow: (done) => {
			let mainWindow = new BrowserWindow({
				title: config.app.title,
				autoHideMenuBar: true,
				webPreferences: {
					nodeIntegration: false
				},
				width: 640,
				height: 400
			});

			electronConfig.setAppMenu();

			done(null, mainWindow);
		},
		expressApp: (done) => {
			let expressApp = express(),
			bodyParser = require('body-parser'),
			consolidate = require('consolidate');

			expressApp.disable('x-powered-by');
			// expressApp.set('showStackError', false);
			expressApp.use(bodyParser.json());
			expressApp.use(bodyParser.urlencoded({
				extended: true
			}));

			expressApp.engine('view.html', consolidate.swig);
			expressApp.set('view engine', 'view.html');
			expressApp.set('views', `${__dirname}/app/views`);
			expressApp.set('view cache', false);

			// Setting the app router and static folder
			expressApp.use(express.static(`${__dirname}/public`));

			expressApp.use(function (req, res, next) {
				res.locals.base_url = BASE_URL;
				res.locals.gateway = config.gateway;
				next();
			});

			expressApp.use('/', require('./app/routes/index'));

			// Error handler
			expressApp.use(function (error, req, res, next) {
				if (error.status) {
					res.status(error.status).json({
						message: error.message
					});
				}
				else {
					console.log(error.stack);
					res.status(500).json({
						message: 'An unexpected error has occurred. Please contact support.'
					});
				}
			});

			// Assume 404 since no middleware responded
			expressApp.use((req, res) => {
				res.status(404).json({
					message: `${req.originalUrl} Not Found`
				});
			});
			done(null, expressApp);
		}
	}, (err, result) => {

		var httpServer = http.createServer(result.expressApp);
		httpServer.listen(config.port);
		httpServer.on('error', (error) => {
			console.log(error);
			process.exit();
		});
		httpServer.on('listening', () => {
			console.log(`Server listening on port ${config.port}`);
			result.mainWindow.loadURL(`${BASE_URL}/index`);
			// result.mainWindow.toggleDevTools();
		});
		httpServer.once('close', () => {
			console.log('Web Server closed.');
		});

		result.mainWindow.on('closed', function() {
			result.mainWindow = null;
			httpServer.close();
		});
	});
});
<commit_msg>set app window size<commit_after>'use strict';

const favicon = require('serve-favicon');
const debug = require('debug')('express-test:server');

const config = require('./config/config'),
	BASE_URL = `http://127.0.0.1:${config.port}`;

var electron 		= require('electron'),
	electronApp 	= electron.app,
	BrowserWindow 	= electron.BrowserWindow,
	async 	 		= require('async'),
	mongoose 		= require('mongoose'),
	express  		= require('express'),
	electronConfig  = require('./config/electronConfig'),
	http 	 		= require('http');

electronApp.on('window-all-closed', function() {
	if (process.platform !== 'darwin') {
		electronApp.quit();
	}
});

electronApp.on('ready', function() {
	async.series({
		mongodb: (done) => {
			var db = mongoose.connection;

			db.once('open', () => {
				console.log('Connected to MongoDB Server.');

				require('./app/models/gps.model.js');
				done(null, db);
			});

			db.once('close', () => {
				mongoose.disconnect(() => {
					console.log('MongoDB Connection Closed.');
				});
			});

			console.log('Connecting to MongoDB Server...');

			let connectWithRetry = () => {
				mongoose.connect(config.mongo.url, {}, (error) => {
					if (error) {
						console.error('Failed to connect to mongo on startup - retrying in 5 sec', error);
						setTimeout(connectWithRetry, 5000);
					}
				});
			};

			connectWithRetry();
		},
		mainWindow: (done) => {
			let mainWindow = new BrowserWindow({
				title: config.app.title,
				autoHideMenuBar: true,
				webPreferences: {
					nodeIntegration: false
				},
				width: 1024,
				height: 768
			});

			electronConfig.setAppMenu();

			done(null, mainWindow);
		},
		expressApp: (done) => {
			let expressApp = express(),
			bodyParser = require('body-parser'),
			consolidate = require('consolidate');

			expressApp.disable('x-powered-by');
			// expressApp.set('showStackError', false);
			expressApp.use(bodyParser.json());
			expressApp.use(bodyParser.urlencoded({
				extended: true
			}));

			expressApp.engine('view.html', consolidate.swig);
			expressApp.set('view engine', 'view.html');
			expressApp.set('views', `${__dirname}/app/views`);
			expressApp.set('view cache', false);

			// Setting the app router and static folder
			expressApp.use(express.static(`${__dirname}/public`));

			expressApp.use(function (req, res, next) {
				res.locals.base_url = BASE_URL;
				res.locals.gateway = config.gateway;
				next();
			});

			expressApp.use('/', require('./app/routes/index'));

			// Error handler
			expressApp.use(function (error, req, res, next) {
				if (error.status) {
					res.status(error.status).json({
						message: error.message
					});
				}
				else {
					console.log(error.stack);
					res.status(500).json({
						message: 'An unexpected error has occurred. Please contact support.'
					});
				}
			});

			// Assume 404 since no middleware responded
			expressApp.use((req, res) => {
				res.status(404).json({
					message: `${req.originalUrl} Not Found`
				});
			});
			done(null, expressApp);
		}
	}, (err, result) => {

		var httpServer = http.createServer(result.expressApp);
		httpServer.listen(config.port);
		httpServer.on('error', (error) => {
			console.log(error);
			process.exit();
		});
		httpServer.on('listening', () => {
			console.log(`Server listening on port ${config.port}`);
			result.mainWindow.loadURL(`${BASE_URL}/index`);
			// result.mainWindow.toggleDevTools();
		});
		httpServer.once('close', () => {
			console.log('Web Server closed.');
		});

		result.mainWindow.on('closed', function() {
			result.mainWindow = null;
			httpServer.close();
		});
	});
});
<|endoftext|>


<commit_before>
// Overrides console to show on the onscren-console but keeping reference to original console.log function.
let _console = console.log;
console.log = function(somethingToLog){
    let resultTextArea = document.getElementById("executionresult");
    resultTextArea.value = resultTextArea.value + somethingToLog + "\n";
    _console(somethingToLog);
}

function clearConsole() {
    let resultTextArea = document.getElementById("executionresult");
    resultTextArea.value = "";
}

function executeCode() {

    clearConsole();
    printExecutionHeaderOnConsole();
    let codeToEval = editor.getValue();

    let selectedLanguage = getSelectedLanguage();

    try {
        result = null;
        switch(selectedLanguage) {
            case "javascript":
                result = executeJavaScriptCode(codeToEval);
                break;
            case "python":
                result = executePythonCode(codeToEval);
                break;
            case "ruby":
                result = executeRubyCode(codeToEval);
                break;
            default:
                console.log("\nERROR:\n Language not supported: " + selectedLanguage);
        }

        if (result != null) {
            console.log(result);
        }

        console.log("Execution finished successfully.");

    } catch (e) {
        console.log("\nERROR:\n" + e.message + "\n");
    }
}

function executeRubyCode(codeToEval) {

    // Testing if Opan is loaded. If not, just shows a warning message and do not try to run the code.
    if (Opal == null || Opan.compile == null) {
        console.log("The Ruby library (Opan) is not loaded yet. Please try again in a few seconds.")
        return;
    }

    let transpiledCodeFromRubyToJS = Opal.compile(codeToEval)

    let result = eval(transpiledCodeFromRubyToJS);

    // TODO: For some reason it is adding a blank link (or in some cases object) in the end of the result.

    return result;
}

function executePythonCode(codeToEval) {

    // Testing if Brython is loaded. If not, just shows a warning message and do not try to run the code.
    if (brython == null || brython.$eval == null) {
        console.log("The Python library (Brython) is not loaded yet. Please try again in a few seconds.")
        return;
    }

    let result = brython.$eval(codeToEval);

    // TODO: For some reason it is adding a blank link (or in some cases object) in the end of the result.

    return result;
}

function printExecutionHeaderOnConsole() {
    let time = new Date().toLocaleTimeString('en-US', { hour12: false,
                                                        hour: "numeric",
                                                        minute: "numeric", second: "numeric"});

    console.log("Starting execution (" + time + ")...");
}

function executeJavaScriptCode(codeToEval) {
    let result = eval(codeToEval);

    return result;
}

function loadSample() {
    alert("Load sample option is not implemented yet :(")
}

function helpMe() {
    alert("Help option is not implemented yet :(")
}

function autoCompleteChanged(el) {
    if (el.checked) {
        editor.setOptions({
            enableBasicAutocompletion: true
        });
    } else {
        editor.setOptions({
            enableBasicAutocompletion: false
        });
    }

}

function autoPairingChanged(el) {
    if (el.checked) {
        editor.setBehavioursEnabled(true);
    } else {
        editor.setBehavioursEnabled(false);
    }
}

function languageSelectChanged(el) {

    let selectedLanguage = el.value;

    switch(selectedLanguage) {
        case "javascript":
            editor.getSession().setMode("ace/mode/javascript");
            disableAceEditorMissingSemiColonWarningMessage();
            break;
        case "ruby":
            editor.getSession().setMode("ace/mode/ruby");
            break;
        case "python":
            editor.getSession().setMode("ace/mode/python");
            break;
        default:
            console.log("\nERROR:\n Language not supported: " + selectedLanguage);
    }
}

function getSelectedLanguage() {
    return document.getElementById("selectLanguage").value;
}

function disableAceEditorMissingSemiColonWarningMessage() {
    editor.session.$worker.call("changeOptions", [{asi: true}]);
}

window.onload = function() {
    disableAceEditorMissingSemiColonWarningMessage();

    // By default, do not auto-close parenthesis, brackets, etc.
    editor.setBehavioursEnabled(false);
}

// Adding keyboard shortcut for "Run" button.
document.onkeydown = function(e) {

    // For IEs window event-object.
    var e = e || window.event;

    // The "R" key is the 82 code, so let's Run the code when the user presses CTR + R.
    if (e.altKey && e.which == 82) {
        executeCode();
     }

}<commit_msg>Removing unused functions<commit_after>
// Overrides console to show on the onscren-console but keeping reference to original console.log function.
let _console = console.log;
console.log = function(somethingToLog){
    let resultTextArea = document.getElementById("executionresult");
    resultTextArea.value = resultTextArea.value + somethingToLog + "\n";
    _console(somethingToLog);
}

function clearConsole() {
    let resultTextArea = document.getElementById("executionresult");
    resultTextArea.value = "";
}

function executeCode() {

    clearConsole();
    printExecutionHeaderOnConsole();
    let codeToEval = editor.getValue();

    let selectedLanguage = getSelectedLanguage();

    try {
        result = null;
        switch(selectedLanguage) {
            case "javascript":
                result = executeJavaScriptCode(codeToEval);
                break;
            case "python":
                result = executePythonCode(codeToEval);
                break;
            case "ruby":
                result = executeRubyCode(codeToEval);
                break;
            default:
                console.log("\nERROR:\n Language not supported: " + selectedLanguage);
        }

        if (result != null) {
            console.log(result);
        }

        console.log("Execution finished successfully.");

    } catch (e) {
        console.log("\nERROR:\n" + e.message + "\n");
    }
}

function executeRubyCode(codeToEval) {

    // Testing if Opan is loaded. If not, just shows a warning message and do not try to run the code.
    if (Opal == null || Opan.compile == null) {
        console.log("The Ruby library (Opan) is not loaded yet. Please try again in a few seconds.")
        return;
    }

    let transpiledCodeFromRubyToJS = Opal.compile(codeToEval)

    let result = eval(transpiledCodeFromRubyToJS);

    // TODO: For some reason it is adding a blank link (or in some cases object) in the end of the result.

    return result;
}

function executePythonCode(codeToEval) {

    // Testing if Brython is loaded. If not, just shows a warning message and do not try to run the code.
    if (brython == null || brython.$eval == null) {
        console.log("The Python library (Brython) is not loaded yet. Please try again in a few seconds.")
        return;
    }

    let result = brython.$eval(codeToEval);

    // TODO: For some reason it is adding a blank link (or in some cases object) in the end of the result.

    return result;
}

function printExecutionHeaderOnConsole() {
    let time = new Date().toLocaleTimeString('en-US', { hour12: false,
                                                        hour: "numeric",
                                                        minute: "numeric", second: "numeric"});

    console.log("Starting execution (" + time + ")...");
}

function executeJavaScriptCode(codeToEval) {
    let result = eval(codeToEval);

    return result;
}

function autoCompleteChanged(el) {

    if (el.checked) {
        editor.setOptions({
            enableBasicAutocompletion: true
        });
    } else {
        editor.setOptions({
            enableBasicAutocompletion: false
        });
    }

}

function autoPairingChanged(el) {

    if (el.checked) {
        editor.setBehavioursEnabled(true);
    } else {
        editor.setBehavioursEnabled(false);
    }

}

function languageSelectChanged(el) {

    let selectedLanguage = el.value;

    switch(selectedLanguage) {
        case "javascript":
            editor.getSession().setMode("ace/mode/javascript");
            disableAceEditorMissingSemiColonWarningMessage();
            break;
        case "ruby":
            editor.getSession().setMode("ace/mode/ruby");
            break;
        case "python":
            editor.getSession().setMode("ace/mode/python");
            break;
        default:
            console.log("\nERROR:\n Language not supported: " + selectedLanguage);
    }
}

function getSelectedLanguage() {
    return document.getElementById("selectLanguage").value;
}

function disableAceEditorMissingSemiColonWarningMessage() {
    editor.session.$worker.call("changeOptions", [{asi: true}]);
}

window.onload = function() {
    disableAceEditorMissingSemiColonWarningMessage();

    // By default, do not auto-close parenthesis, brackets, etc.
    editor.setBehavioursEnabled(false);
}

// Adding keyboard shortcut for "Run" button.
document.onkeydown = function(e) {

    // For IEs window event-object.
    var e = e || window.event;

    // The "R" key is the 82 code, so let's Run the code when the user presses ALT + R.
    if (e.altKey && e.which == 82) {
        executeCode();
     }

}<|endoftext|>


<commit_before>const EventEmitter = require('events').EventEmitter;
const prism = require('prism-media');
const StreamDispatcher = require('../dispatcher/StreamDispatcher');

const FFMPEG_ARGUMENTS = [
  '-analyzeduration', '0',
  '-loglevel', '0',
  '-f', 's16le',
  '-ar', '48000',
  '-ac', '2',
];

/**
 * An Audio Player for a Voice Connection.
 * @private
 * @extends {EventEmitter}
 */
class AudioPlayer extends EventEmitter {
  constructor(voiceConnection) {
    super();
    /**
     * The voice connection that the player serves
     * @type {VoiceConnection}
     */
    this.voiceConnection = voiceConnection;

    this.streams = {};
    this.dispatcher = null;

    this.streamingData = {
      channels: 2,
      count: 0,
      sequence: 0,
      timestamp: 0,
      pausedTime: 0,
    };

    this.voiceConnection.once('closing', () => this.destroyCurrentStream());
  }

  destroy() {
    this.destroyDispatcher();
  }

  destroyDispatcher() {
    if (this.dispatcher) {
      this.dispatcher.destroy();
      this.dispatcher = null;
    }
  }

  /**
   * Set the bitrate of the current Opus encoder.
   * @param {number} value New bitrate, in kbps
   * If set to 'auto', the voice channel's bitrate will be used
   */
  setBitrate(value) {
    if (!value) return;
    if (!this.opusEncoder) return;
    const bitrate = value === 'auto' ? this.voiceConnection.channel.bitrate : value;
    this.opusEncoder.setBitrate(bitrate);
  }

  playUnknownStream(stream, options = {}) {
    this.destroyDispatcher();
    const ffmpeg = this.streams.ffmpeg = new prism.FFmpeg({ args: FFMPEG_ARGUMENTS });
    stream.pipe(ffmpeg);
    return this.playPCMStream(ffmpeg, options);
  }

  playPCMStream(stream, options = {}) {
    this.destroyDispatcher();
    const opus = this.streams.opus = new prism.opus.Encoder({ channels: 2, rate: 48000, frameSize: 960 });
    stream.pipe(opus);
    return this.playOpusStream(opus, options);
  }

  playOpusStream(stream, options = {}) {
    this.destroyDispatcher();
    const dispatcher = this.dispatcher = this.createDispatcher(options);
    stream.pipe(dispatcher);
    return dispatcher;
  }

  playBroadcast(broadcast, options) {

  }

  createDispatcher({ seek = 0, volume = 1, passes = 1 } = {}) {
    this.destroyDispatcher();
    const options = { seek, volume, passes };
    const dispatcher = new StreamDispatcher(this, options);
    this.streamingData.count = 0;
    dispatcher.on('speaking', value => this.voiceConnection.setSpeaking(value));
    return dispatcher;
  }
}

module.exports = AudioPlayer;
<commit_msg>Don't need to continue count and pausedTime amongst dispatchers<commit_after>const EventEmitter = require('events').EventEmitter;
const prism = require('prism-media');
const StreamDispatcher = require('../dispatcher/StreamDispatcher');

const FFMPEG_ARGUMENTS = [
  '-analyzeduration', '0',
  '-loglevel', '0',
  '-f', 's16le',
  '-ar', '48000',
  '-ac', '2',
];

/**
 * An Audio Player for a Voice Connection.
 * @private
 * @extends {EventEmitter}
 */
class AudioPlayer extends EventEmitter {
  constructor(voiceConnection) {
    super();
    /**
     * The voice connection that the player serves
     * @type {VoiceConnection}
     */
    this.voiceConnection = voiceConnection;

    this.streams = {};
    this.dispatcher = null;

    this.streamingData = {
      channels: 2,
      sequence: 0,
      timestamp: 0,
    };

    this.voiceConnection.once('closing', () => this.destroyCurrentStream());
  }

  destroy() {
    this.destroyDispatcher();
  }

  destroyDispatcher() {
    if (this.dispatcher) {
      this.dispatcher.destroy();
      this.dispatcher = null;
    }
  }

  /**
   * Set the bitrate of the current Opus encoder.
   * @param {number} value New bitrate, in kbps
   * If set to 'auto', the voice channel's bitrate will be used
   */
  setBitrate(value) {
    if (!value) return;
    if (!this.opusEncoder) return;
    const bitrate = value === 'auto' ? this.voiceConnection.channel.bitrate : value;
    this.opusEncoder.setBitrate(bitrate);
  }

  playUnknownStream(stream, options = {}) {
    this.destroyDispatcher();
    const ffmpeg = this.streams.ffmpeg = new prism.FFmpeg({ args: FFMPEG_ARGUMENTS });
    stream.pipe(ffmpeg);
    return this.playPCMStream(ffmpeg, options);
  }

  playPCMStream(stream, options = {}) {
    this.destroyDispatcher();
    const opus = this.streams.opus = new prism.opus.Encoder({ channels: 2, rate: 48000, frameSize: 960 });
    stream.pipe(opus);
    return this.playOpusStream(opus, options);
  }

  playOpusStream(stream, options = {}) {
    this.destroyDispatcher();
    const dispatcher = this.dispatcher = this.createDispatcher(options);
    stream.pipe(dispatcher);
    return dispatcher;
  }

  playBroadcast(broadcast, options) {

  }

  createDispatcher({ seek = 0, volume = 1, passes = 1 } = {}) {
    this.destroyDispatcher();
    const options = { seek, volume, passes };
    const dispatcher = new StreamDispatcher(this, options);
    this.streamingData.count = 0;
    dispatcher.on('speaking', value => this.voiceConnection.setSpeaking(value));
    return dispatcher;
  }
}

module.exports = AudioPlayer;
<|endoftext|>


<commit_before>$(document).ready(function() {
  $('#playPause').easyAudio({
    mpeg: 'http://meaganproctorkavouras.com/audio/song.mp3',
    wav:  'http://meaganproctorkavouras.com/audio/song.wav',
    ogg:  'http://meaganproctorkavouras.com/audio/song.ogg'
  });
});
<commit_msg>correct selector<commit_after>$(document).ready(function() {
  $('#trigger').easyAudio({
    mpeg: 'http://meaganproctorkavouras.com/audio/pewpew.mp3',
    wav:  'http://meaganproctorkavouras.com/audio/pewpew.wav',
    ogg:  'http://meaganproctorkavouras.com/audio/pewpew.ogg'
  });
});
<|endoftext|>