<commit_before>/*
 * ! ${copyright}
 */

sap.ui.define([
], function(
) {
	"use strict";

	/**
	 * Base class for connectors.
	 *
	 * @namespace sap.ui.fl.write.connectors.BaseConnector
	 * @experimental Since 1.67
	 * @since 1.67
	 * @public
	 */
	var BaseConnector = /** @lends sap.ui.fl.write.connectors.BaseConnector */{

		/**
		 * Interface called to write flex data; This method is called with a list of entities like changes, variants,
		 * control variants, variant changes and variant management changes.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {sap.ui.fl.Change[]} mPropertyBag.payload Data to be stored
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer in which the data should be stored
		 * @param {string} [mPropertyBag.url] Configured url for the connector
		 * @returns {Promise} Promise resolves as soon as the writing was completed
		 */
		write: function (/* mPropertyBag */) {
			return Promise.reject("writeFlexData is not implemented");
		},

		/**
		 * Interface called to delete flex data.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {string} mPropertyBag.name Name of the file to be deleted
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer in which the data should be deleted
		 * @param {string} mParameters.namespace The namespace of the change file
		 * @param {string} [mParameters.changeList] The transport ID
		 * @param {string} [mPropertyBag.url] Configured url for the connector
		 * @returns {Promise} Promise resolves when the writing was completed
		 */
		deleteFlexData: function (/* mPropertyBag */) {
			return Promise.reject("deleteFlexData is not implemented");
		},

		/**
		 * Resets flexibility files for a given application and layer.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {string} mPropertyBag.reference Flex reference of the application
		 * @param {string} mPropertyBag.url Configured url for the connector
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer
		 * @param {string} [mPropertyBag.changelist] Transport Id
		 * @param {string} [mPropertyBag.appVersion] Version of the application for which the reset takes place
		 * @param {string} [mPropertyBag.generator] Generator with which the changes were created
		 * @param {string} [mPropertyBag.selectorIds] Selector IDs of controls for which the reset should filter (comma-separated list)
		 * @param {string} [mPropertyBag.changeTypes] Change types of the changes which should be reset (comma-separated list)
		 * @returns {Promise} Promise resolves as soon as the reset has completed
		 */
		reset: function (/* mPropertyBag */) {
			return Promise.reject("reset is not implemented");
		},

		/**
		 * Publish flexibility files for a given application and layer.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer
		 * @param {string} mPropertyBag.reference Flex reference of the application
		 * @param {string} mPropertyBag.url Configured url for the connector
		 * @param {string} mPropertyBag.changelist Transport Id
		 * @param {string} [mPropertyBag.package] ABAP package (mandatory when layer is 'VENDOR')
		 * @param {string} [mPropertyBag.appVersion] Version of the application
		 * @returns {Promise} Promise resolves as soon as the publish has completed
		 */
		publish: function (/* mPropertyBag */) {
			return Promise.reject("publish is not implemented");
		},

		/**
		 * Gets the flexibility info for a given application and layer.
		 * The flexibility info is a JSON string that has boolean properties 'isPublishEnabled' and 'isResetEnabled'
		 * that indicate if for the given application and layer a publish and reset shall be enabled, respectively
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer
		 * @param {string} mPropertyBag.reference Flex reference
		 * @param {string} [mPropertyBag.url] Configured url for the connector
		 * @param {string} [mPropertyBag.appVersion] Version of the application
		 * @returns {Promise} Promise resolves as soon as the writing was completed
		 */
		getFlexInfo: function (/* mPropertyBag */) {
			return Promise.reject("getFlexInfo is not implemented");
		},

		/**
		 * Interface called to get the flex feature.
		 *
		 * @returns {Promise<Object>} Promise resolves with an object containing a flex features response
		 */
		loadFeatures: function () {
			return Promise.reject("loadFeatures is not implemented");
		}
	};

	return BaseConnector;
}, true);
<commit_msg>[INTERNAL] sap.ui.fl.apply.connectors.BaseConnector docu update & rename<commit_after>/*
 * ! ${copyright}
 */

sap.ui.define([
], function(
) {
	"use strict";

	/**
	 * Base class for connectors.
	 *
	 * @namespace sap.ui.fl.write.connectors.BaseConnector
	 * @experimental Since 1.67
	 * @since 1.67
	 * @public
	 */
	var BaseConnector = /** @lends sap.ui.fl.write.connectors.BaseConnector */{

		/**
		 * Interface called to write flex data; This method is called with a list of entities like changes, variants,
		 * control variants, variant changes and variant management changes.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {object[]} mPropertyBag.flexObjects Objects to be written (i.e. change definitions, variant definitions etc.)
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer in which the data should be stored
		 * @param {string} [mPropertyBag.url] Configured url for the connector
		 * @returns {Promise} Resolves as soon as the writing is completed without data
		 */
		write: function (/* mPropertyBag */) {
			return Promise.reject("write is not implemented");
		},

		/**
		 * Interface called to delete flex data.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {string} mPropertyBag.name Name of the file to be deleted
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer in which the data should be deleted
		 * @param {string} [mParameters.namespace] The namespace of the file
		 * @param {string} [mPropertyBag.url] Configured url for the connector
		 * @returns {Promise} Resolves as soon as the deletion is completed without data
		 */
		remove: function (/* mPropertyBag */) {
			return Promise.reject("remove is not implemented");
		},

		/**
		 * Resets flexibility files for a given application and layer.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {string} mPropertyBag.reference Flex reference of the application
		 * @param {string} mPropertyBag.url Configured url for the connector
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer
		 * @param {string} [mPropertyBag.appVersion] Version of the application for which the reset takes place
		 * @param {string} [mPropertyBag.generator] Generator with which the changes were created
		 * @param {string} [mPropertyBag.selectorIds] Selector IDs of controls for which the reset should filter (comma-separated list)
		 * @param {string} [mPropertyBag.changeTypes] Change types of the changes which should be reset (comma-separated list)
		 * @returns {Promise} Resolves as soon as the reset is completed without data
		 */
		reset: function (/* mPropertyBag */) {
			return Promise.reject("reset is not implemented");
		},

		/**
		 * Publish flexibility files for a given application and layer.
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer
		 * @param {string} mPropertyBag.reference Flex reference of the application
		 * @param {string} mPropertyBag.url Configured url for the connector
		 * @param {string} mPropertyBag.changelist Transport Id
		 * @param {string} [mPropertyBag.appVersion] Version of the application
		 * @returns {Promise} Resolves as soon as the publish is completed without data
		 */
		publish: function (/* mPropertyBag */) {
			return Promise.reject("publish is not implemented");
		},

		/**
		 * Gets the flexibility info for a given application and layer.
		 * The flexibility info is a JSON string that has boolean properties 'isPublishEnabled' and 'isResetEnabled'
		 * that indicate if for the given application and layer a publish and reset shall be enabled, respectively
		 *
		 * @param {object} mPropertyBag Property bag
		 * @param {sap.ui.fl.Layer} mPropertyBag.layer Layer
		 * @param {string} mPropertyBag.reference Flex reference
		 * @param {string} [mPropertyBag.url] Configured url for the connector
		 * @param {string} [mPropertyBag.appVersion] Versio1n of the application
		 * @returns {Promise<object>} Promise resolves as soon as the writing was completed
		 */
		getFlexInfo: function (/* mPropertyBag */) {
			return Promise.reject("getFlexInfo is not implemented");
		},

		/**
		 * Interface called to get the flex feature.
		 *
		 * @returns {Promise<object>} Resolves with an object containing the data for the flex features
		 */
		loadFeatures: function () {
			return Promise.reject("loadFeatures is not implemented");
		}
	};

	return BaseConnector;
}, true);
<|endoftext|>


<commit_before>import Ember from 'ember';

const Wrapper = Ember.Object.extend({
  content: null,
  list:    null,

  isSelected: Ember.computed("list.selected.[]", function() {
    const selected = this.get("list.selected");
    const by       = this.get("list.by");
    const content  = by ? this.get("content").get(by) : this.get("content");

    if (Ember.isArray(selected)) {
      if (by) {
        return Ember.A(selected).mapBy(by).contains(content);
      } else {
        return Ember.A(selected).contains(content);
      }
    } else {
      return selected === content;
    }
  })
});

export default Ember.Component.extend({
  tagName:   "ul",
  items:     null,
  selected:  null,

  'item-class':      null,
  'selected-class': 'selected',

  // if you want to compare against a property instead of the whole object
  // useful if the object identities are different, so test against ID or something
  by: null,

  // optional object to send up in-case there are multiple of these on a page
  // TODO - deprecate this when new actions land as you can curry options
  object: null,

  // whether to bubble click events
  // TODO - deprecate this when new actions land as it will no longer be needed
  bubbles: true,

  wrapped: Ember.computed("items.[]", function() {
    return Ember.A(this.get("items").map(item => {
      return Wrapper.create({
        content: item,
        list:    this
      });
    }));
  }),

  clicked: Ember.on("click", function(e) {
    // false can come in as a string from the component
    if (!this.get("bubbles") || this.get("bubbles") === "false") {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
  }),

  actions: {
    select: function(wrapped) {
      const item   = wrapped.get("content");
      const object = this.get("object");

      if (wrapped.get("isSelected")) {
        this.sendAction("on-deselect", item, object);
      } else {
        this.sendAction("on-select", item, object);
      }
      this.sendAction("on-toggle", item, object);
    }
  }
});<commit_msg>handle being give null items<commit_after>import Ember from 'ember';

const Wrapper = Ember.Object.extend({
  content: null,
  list:    null,

  isSelected: Ember.computed("list.selected.[]", function() {
    const selected = this.get("list.selected");
    const by       = this.get("list.by");
    const content  = by ? this.get("content").get(by) : this.get("content");

    if (Ember.isArray(selected)) {
      if (by) {
        return Ember.A(selected).mapBy(by).contains(content);
      } else {
        return Ember.A(selected).contains(content);
      }
    } else {
      return selected === content;
    }
  })
});

export default Ember.Component.extend({
  tagName:   "ul",
  items:     null,
  selected:  null,

  'item-class':      null,
  'selected-class': 'selected',

  // if you want to compare against a property instead of the whole object
  // useful if the object identities are different, so test against ID or something
  by: null,

  // optional object to send up in-case there are multiple of these on a page
  // TODO - deprecate this when new actions land as you can curry options
  object: null,

  // whether to bubble click events
  // TODO - deprecate this when new actions land as it will no longer be needed
  bubbles: true,

  wrapped: Ember.computed("items.[]", function() {
    return Ember.A((this.get("items") || []).map(item => {
      return Wrapper.create({
        content: item,
        list:    this
      });
    }));
  }),

  clicked: Ember.on("click", function(e) {
    // false can come in as a string from the component
    if (!this.get("bubbles") || this.get("bubbles") === "false") {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
  }),

  actions: {
    select: function(wrapped) {
      const item   = wrapped.get("content");
      const object = this.get("object");

      if (wrapped.get("isSelected")) {
        this.sendAction("on-deselect", item, object);
      } else {
        this.sendAction("on-select", item, object);
      }
      this.sendAction("on-toggle", item, object);
    }
  }
});<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import counterpart from 'counterpart'
import * as LocaleActions from 'shared/actions/LocaleActions'
import { connect } from 'react-redux'

class LocaleSwitcher extends React.Component {

  static propTypes = {
    locale: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  constructor (props) {
    super(props)

    this.handleChange = ::this.handleChange
  }

  handleChange (e) {
    const lang = e.target.getAttribute('value')
    counterpart.setLocale(lang)
    this.props.dispatch(
      LocaleActions.sync(lang)
    )
    const title = counterpart(this.props.locale.title)
    const defaultTitle = counterpart('title.site')
    if (defaultTitle) {
      document.title = `${title} | ${defaultTitle}`
    } else {
      document.title = `${title}`
    }
  }

  render () {
    return (

            正體中文

            简体中文

            English

    )
  }
}

export default connect(state => ({
  locale: state.locale
}))(LocaleSwitcher)
<commit_msg>fix title issue when change locale<commit_after>import React, { PropTypes } from 'react'
import counterpart from 'counterpart'
import * as LocaleActions from 'shared/actions/LocaleActions'
import { connect } from 'react-redux'

class LocaleSwitcher extends React.Component {

  static propTypes = {
    locale: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  constructor (props) {
    super(props)

    this.handleChange = ::this.handleChange
  }

  handleChange (e) {
    const lang = e.target.getAttribute('value')
    counterpart.setLocale(lang)
    this.props.dispatch(
      LocaleActions.sync(lang)
    )
    let title = counterpart(this.props.locale.title)
    if (title.startsWith('missing')) {
      title = this.props.locale.title
    }
    const defaultTitle = counterpart('title.site')
    if (defaultTitle) {
      document.title = `${title} | ${defaultTitle}`
    } else {
      document.title = `${title}`
    }
  }

  render () {
    return (

            正體中文

            简体中文

            English

    )
  }
}

export default connect(state => ({
  locale: state.locale
}))(LocaleSwitcher)
<|endoftext|>


<commit_before>pleaseDontLeave = function (msg) {
    var message = msg || "Please come back!!1";
    window.onunload=function() {
      function pleaseDontLeave() {
        alert(message);
      }
      pleaseDontLeave();
    };
  };

anything.prototype.pleaseDontLeave = pleaseDontLeave;
<commit_msg>Fixed declaration bug<commit_after>var pleaseDontLeave = function (msg) {
    var message = msg || "Please come back!!1";
    window.onunload=function() {
      function pleaseDontLeave() {
        alert(message);
      }
      pleaseDontLeave();
    };
  };

anything.prototype.pleaseDontLeave = pleaseDontLeave;
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  var defaults = {
    pairs: "()[]{}''\"\"",
    triples: "",
    explode: "[]{}"
  };

  var Pos = CodeMirror.Pos;

  CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.removeKeyMap(keyMap);
      cm.state.closeBrackets = null;
    }
    if (val) {
      cm.state.closeBrackets = val;
      cm.addKeyMap(keyMap);
    }
  });

  function getOption(conf, name) {
    if (name == "pairs" && typeof conf == "string") return conf;
    if (typeof conf == "object" && conf[name] != null) return conf[name];
    return defaults[name];
  }

  var bind = defaults.pairs + "`";
  var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
  for (var i = 0; i < bind.length; i++)
    keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i));

  function handler(ch) {
    return function(cm) { return handleChar(cm, ch); };
  }

  function getConfig(cm) {
    var deflt = cm.state.closeBrackets;
    if (!deflt) return null;
    var mode = cm.getModeAt(cm.getCursor());
    return mode.closeBrackets || deflt;
  }

  function handleBackspace(cm) {
    var conf = getConfig(cm);
    if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;

    var pairs = getOption(conf, "pairs");
    var ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) return CodeMirror.Pass;
      var around = charsAround(cm, ranges[i].head);
      if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
    }
    for (var i = ranges.length - 1; i >= 0; i--) {
      var cur = ranges[i].head;
      cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
    }
  }

  function handleEnter(cm) {
    var conf = getConfig(cm);
    var explode = conf && getOption(conf, "explode");
    if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;

    var ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) return CodeMirror.Pass;
      var around = charsAround(cm, ranges[i].head);
      if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
    }
    cm.operation(function() {
      cm.replaceSelection("\n\n", null);
      cm.execCommand("goCharLeft");
      ranges = cm.listSelections();
      for (var i = 0; i < ranges.length; i++) {
        var line = ranges[i].head.line;
        cm.indentLine(line, null, true);
        cm.indentLine(line + 1, null, true);
      }
    });
  }

  function contractSelection(sel){
    if (sel.anchor.line<sel.head.line || (sel.anchor.line===sel.head.line&&sel.anchor.ch<sel.head.ch)){
      sel.anchor.ch++;
      sel.head.ch--;
    }
    if (sel.anchor.line>sel.head.line || (sel.anchor.line===sel.head.line&&sel.anchor.ch>sel.head.ch)){
      sel.head.ch++;
      sel.anchor.ch--;
    }
  }
  function handleChar(cm, ch) {
    var conf = getConfig(cm);
    if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;

    var pairs = getOption(conf, "pairs");
    var pos = pairs.indexOf(ch);
    if (pos == -1) return CodeMirror.Pass;
    var triples = getOption(conf, "triples");

    var identical = pairs.charAt(pos + 1) == ch;
    var ranges = cm.listSelections();
    var opening = pos % 2 == 0;

    var type, next;
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i], cur = range.head, curType;
      var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
      if (opening && !range.empty()) {
        curType = "surround";
      } else if ((identical || !opening) && next == ch) {
        if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
          curType = "skipThree";
        else
          curType = "skip";
      } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
                 cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch &&
                 (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) {
        curType = "addFour";
      } else if (identical) {
        if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both";
        else return CodeMirror.Pass;
      } else if (opening && (cm.getLine(cur.line).length == cur.ch ||
                             isClosingBracket(next, pairs) ||
                             /\s/.test(next))) {
        curType = "both";
      } else {
        return CodeMirror.Pass;
      }
      if (!type) type = curType;
      else if (type != curType) return CodeMirror.Pass;
    }

    var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
    var right = pos % 2 ? ch : pairs.charAt(pos + 1);
    cm.operation(function() {
      if (type == "skip") {
        cm.execCommand("goCharRight");
      } else if (type == "skipThree") {
        for (var i = 0; i < 3; i++)
          cm.execCommand("goCharRight");
      } else if (type == "surround") {
        var sels = cm.getSelections();
        for (var i = 0; i < sels.length; i++)
          sels[i] = left + sels[i] + right;
        cm.replaceSelections(sels, "around");
        var selections = cm.listSelections();
        for (var i=0;i<selections.length;i++){
          contractSelection(selections[i]);
        }
        cm.setSelections(selections);
      } else if (type == "both") {
        cm.replaceSelection(left + right, null);
        cm.triggerElectric(left + right);
        cm.execCommand("goCharLeft");
      } else if (type == "addFour") {
        cm.replaceSelection(left + left + left + left, "before");
        cm.execCommand("goCharRight");
      }
    });
  }

  function isClosingBracket(ch, pairs) {
    var pos = pairs.lastIndexOf(ch);
    return pos > -1 && pos % 2 == 1;
  }

  function charsAround(cm, pos) {
    var str = cm.getRange(Pos(pos.line, pos.ch - 1),
                          Pos(pos.line, pos.ch + 1));
    return str.length == 2 ? str : null;
  }

  // Project the token type that will exists after the given char is
  // typed, and use it to determine whether it would cause the start
  // of a string token.
  function enteringString(cm, pos, ch) {
    var line = cm.getLine(pos.line);
    var token = cm.getTokenAt(pos);
    if (/\bstring2?\b/.test(token.type)) return false;
    var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
    stream.pos = stream.start = token.start;
    for (;;) {
      var type1 = cm.getMode().token(stream, token.state);
      if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
      stream.start = stream.pos;
    }
  }
});
<commit_msg>[closebrackets addon] Fix mutation of shared data<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  var defaults = {
    pairs: "()[]{}''\"\"",
    triples: "",
    explode: "[]{}"
  };

  var Pos = CodeMirror.Pos;

  CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.removeKeyMap(keyMap);
      cm.state.closeBrackets = null;
    }
    if (val) {
      cm.state.closeBrackets = val;
      cm.addKeyMap(keyMap);
    }
  });

  function getOption(conf, name) {
    if (name == "pairs" && typeof conf == "string") return conf;
    if (typeof conf == "object" && conf[name] != null) return conf[name];
    return defaults[name];
  }

  var bind = defaults.pairs + "`";
  var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
  for (var i = 0; i < bind.length; i++)
    keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i));

  function handler(ch) {
    return function(cm) { return handleChar(cm, ch); };
  }

  function getConfig(cm) {
    var deflt = cm.state.closeBrackets;
    if (!deflt) return null;
    var mode = cm.getModeAt(cm.getCursor());
    return mode.closeBrackets || deflt;
  }

  function handleBackspace(cm) {
    var conf = getConfig(cm);
    if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;

    var pairs = getOption(conf, "pairs");
    var ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) return CodeMirror.Pass;
      var around = charsAround(cm, ranges[i].head);
      if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
    }
    for (var i = ranges.length - 1; i >= 0; i--) {
      var cur = ranges[i].head;
      cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
    }
  }

  function handleEnter(cm) {
    var conf = getConfig(cm);
    var explode = conf && getOption(conf, "explode");
    if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;

    var ranges = cm.listSelections();
    for (var i = 0; i < ranges.length; i++) {
      if (!ranges[i].empty()) return CodeMirror.Pass;
      var around = charsAround(cm, ranges[i].head);
      if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
    }
    cm.operation(function() {
      cm.replaceSelection("\n\n", null);
      cm.execCommand("goCharLeft");
      ranges = cm.listSelections();
      for (var i = 0; i < ranges.length; i++) {
        var line = ranges[i].head.line;
        cm.indentLine(line, null, true);
        cm.indentLine(line + 1, null, true);
      }
    });
  }

  function contractSelection(sel) {
    var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
    return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
            head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
  }

  function handleChar(cm, ch) {
    var conf = getConfig(cm);
    if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;

    var pairs = getOption(conf, "pairs");
    var pos = pairs.indexOf(ch);
    if (pos == -1) return CodeMirror.Pass;
    var triples = getOption(conf, "triples");

    var identical = pairs.charAt(pos + 1) == ch;
    var ranges = cm.listSelections();
    var opening = pos % 2 == 0;

    var type, next;
    for (var i = 0; i < ranges.length; i++) {
      var range = ranges[i], cur = range.head, curType;
      var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
      if (opening && !range.empty()) {
        curType = "surround";
      } else if ((identical || !opening) && next == ch) {
        if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
          curType = "skipThree";
        else
          curType = "skip";
      } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
                 cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch &&
                 (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) {
        curType = "addFour";
      } else if (identical) {
        if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both";
        else return CodeMirror.Pass;
      } else if (opening && (cm.getLine(cur.line).length == cur.ch ||
                             isClosingBracket(next, pairs) ||
                             /\s/.test(next))) {
        curType = "both";
      } else {
        return CodeMirror.Pass;
      }
      if (!type) type = curType;
      else if (type != curType) return CodeMirror.Pass;
    }

    var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
    var right = pos % 2 ? ch : pairs.charAt(pos + 1);
    cm.operation(function() {
      if (type == "skip") {
        cm.execCommand("goCharRight");
      } else if (type == "skipThree") {
        for (var i = 0; i < 3; i++)
          cm.execCommand("goCharRight");
      } else if (type == "surround") {
        var sels = cm.getSelections();
        for (var i = 0; i < sels.length; i++)
          sels[i] = left + sels[i] + right;
        cm.replaceSelections(sels, "around");
        sels = cm.listSelections().slice();
        for (var i = 0; i < sels.length; i++)
          sels[i] = contractSelection(sels[i]);
        cm.setSelections(sels);
      } else if (type == "both") {
        cm.replaceSelection(left + right, null);
        cm.triggerElectric(left + right);
        cm.execCommand("goCharLeft");
      } else if (type == "addFour") {
        cm.replaceSelection(left + left + left + left, "before");
        cm.execCommand("goCharRight");
      }
    });
  }

  function isClosingBracket(ch, pairs) {
    var pos = pairs.lastIndexOf(ch);
    return pos > -1 && pos % 2 == 1;
  }

  function charsAround(cm, pos) {
    var str = cm.getRange(Pos(pos.line, pos.ch - 1),
                          Pos(pos.line, pos.ch + 1));
    return str.length == 2 ? str : null;
  }

  // Project the token type that will exists after the given char is
  // typed, and use it to determine whether it would cause the start
  // of a string token.
  function enteringString(cm, pos, ch) {
    var line = cm.getLine(pos.line);
    var token = cm.getTokenAt(pos);
    if (/\bstring2?\b/.test(token.type)) return false;
    var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
    stream.pos = stream.start = token.start;
    for (;;) {
      var type1 = cm.getMode().token(stream, token.state);
      if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
      stream.start = stream.pos;
    }
  }
});
<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var Kibo = require('../../base/kibo')

var BOLD = 'font-weight: bold; font-size: 13px;';
var INFO = 'color: #006600;' + BOLD;
var DEBUG = 'color: #0000ff;' + BOLD;
var WARN = 'color: #ff8000;' + BOLD;
var ERROR = 'color: #ff0000;' + BOLD;

var LEVEL_DEBUG = 0
var LEVEL_INFO = 1
var LEVEL_WARN = 2
var LEVEL_ERROR = 3
var LEVEL_DISABLED = 4

var COLORS = [DEBUG, INFO, WARN, ERROR, ERROR]
var DESCRIPTIONS = ['debug', 'info', 'warn', 'error', 'disabled']

class Log {
  constructor(level = LEVEL_WARN) {
    this.kibo = new Kibo()
    this.kibo.down(['ctrl shift d'], () => this.onOff())
    this.BLACKLIST = ['timeupdate', 'playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
    this.level = level
  }

  debug(klass) {this.log(klass, LEVEL_DEBUG, Array.prototype.slice.call(arguments, 1))}
  info(klass) {this.log(klass, LEVEL_INFO, Array.prototype.slice.call(arguments, 1))}
  warn(klass) {this.log(klass, LEVEL_WARN, Array.prototype.slice.call(arguments, 1))}
  error(klass) {this.log(klass, LEVEL_ERROR, Array.prototype.slice.call(arguments, 1))}

  onOff() {
    if (this.level === LEVEL_DISABLED) {
      this.level = this.previousLevel
    } else {
      this.previousLevel = this.level
      this.level = LEVEL_DISABLED
    }
    console.log.apply(console, ["%c[Clappr.Log] set log level to " + DESCRIPTIONS[this.level], ERROR]);
  }

  level(newLevel) {
    this.level = newLevel
  }

  log(klass, level, message) {
    if (this.BLACKLIST.indexOf(message[0]) >= 0) return
    if (level < this.level) return

    if (!message) {
      message = klass
      klass = null
    }
    var klassDescription = ""
    var color = COLORS[level]
    if (klass) {
      klassDescription = "[" + klass + "]"
    }
    console.log.apply(console, ["%c[" + DESCRIPTIONS[level] + "]" + klassDescription, color].concat(message));
  }
}

Log.LEVEL_DEBUG = LEVEL_DEBUG
Log.LEVEL_INFO = LEVEL_INFO
Log.LEVEL_WARN = LEVEL_WARN
Log.LEVEL_ERROR = LEVEL_ERROR

Log.getInstance = function() {
  if (this._instance === undefined) {
    this._instance = new this()
  }
  return this._instance
}

module.exports = Log
<commit_msg>remove unused variable<commit_after>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var Kibo = require('../../base/kibo')

var BOLD = 'font-weight: bold; font-size: 13px;';
var INFO = 'color: #006600;' + BOLD;
var DEBUG = 'color: #0000ff;' + BOLD;
var WARN = 'color: #ff8000;' + BOLD;
var ERROR = 'color: #ff0000;' + BOLD;

var LEVEL_DEBUG = 0
var LEVEL_INFO = 1
var LEVEL_WARN = 2
var LEVEL_ERROR = 3
var LEVEL_DISABLED = 4

var COLORS = [DEBUG, INFO, WARN, ERROR, ERROR]
var DESCRIPTIONS = ['debug', 'info', 'warn', 'error', 'disabled']

class Log {
  constructor(level = LEVEL_WARN) {
    this.kibo = new Kibo()
    this.kibo.down(['ctrl shift d'], () => this.onOff())
    this.BLACKLIST = ['timeupdate', 'playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
    this.level = level
  }

  debug(klass) {this.log(klass, LEVEL_DEBUG, Array.prototype.slice.call(arguments, 1))}
  info(klass) {this.log(klass, LEVEL_INFO, Array.prototype.slice.call(arguments, 1))}
  warn(klass) {this.log(klass, LEVEL_WARN, Array.prototype.slice.call(arguments, 1))}
  error(klass) {this.log(klass, LEVEL_ERROR, Array.prototype.slice.call(arguments, 1))}

  onOff() {
    if (this.level === LEVEL_DISABLED) {
      this.level = this.previousLevel
    } else {
      this.previousLevel = this.level
      this.level = LEVEL_DISABLED
    }
    console.log.apply(console, ["%c[Clappr.Log] set log level to " + DESCRIPTIONS[this.level], ERROR]);
  }

  level(newLevel) {
    this.level = newLevel
  }

  log(klass, level, message) {
    if (this.BLACKLIST.indexOf(message[0]) >= 0) return
    if (level < this.level) return

    if (!message) {
      message = klass
      klass = null
    }
    var klassDescription = ""
    var color = COLORS[level]
    if (klass) {
      klassDescription = "[" + klass + "]"
    }
    console.log.apply(console, ["%c[" + DESCRIPTIONS[level] + "]" + klassDescription, color].concat(message));
  }
}

Log.LEVEL_DEBUG = LEVEL_DEBUG
Log.LEVEL_INFO = LEVEL_INFO
Log.LEVEL_WARN = LEVEL_WARN
Log.LEVEL_ERROR = LEVEL_ERROR

Log.getInstance = function() {
  if (this._instance === undefined) {
    this._instance = new this()
  }
  return this._instance
}

module.exports = Log
<|endoftext|>


<commit_before>for( i = 1;i<document.getElementsByClassName("textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder").length;i++) {
document.getElementsByClassName("textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder")[i].click();
var input = $( "textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder" );
input.val( input.val() + "testing" );

}
void(0);

for( i = 1;i<document.getElementsByClassName("UFIAddComment").length;i++) {
document.getElementsByClassName("UFIAddComment")[i].click();
var input = $( "UFIAddComment" );
input.val( input.val() + "testing" );

}
void(0);
<commit_msg>Simple formatting<commit_after>for( i = 1;i<document.getElementsByClassName("textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder").length;i++) {
    document.getElementsByClassName("textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder")[i].click();
    var input = $( "textInput mentionsTextarea uiTextareaAutogrow uiTextareaNoResize UFIAddCommentInput DOMControl_placeholder" );
    input.val( input.val() + "testing" );
}
void(0);

for( i = 1;i<document.getElementsByClassName("UFIAddComment").length;i++) {
    document.getElementsByClassName("UFIAddComment")[i].click();
    var input = $( "UFIAddComment" );
    input.val( input.val() + "testing" );
}
void(0);
<|endoftext|>


<commit_before>(function(){

	var app = angular.module('app.projectFactory', []);

	app.factory('app.projectFactory', ['$http', '$q', function($http, $q) {

		// `projects` object caches all our Projects
		var projects;

		// Data refresh intervals
		var projects_last_fetched;
		var projects_max_life = 30; 	// seconds
		var project_max_life = 10;		// seconds
		var projects_force_refetch = true;

		// `timeRecords` object stores promises keyed to Project IDs
		var timeRecords = {};
		var time_records_last_fetched = {};	// Keyed to a Project ID

		var refreshIntervalPassed = function() {

			var now = new Date().getTime() / 1000;
			if (projects_last_fetched) {
				var last_fetch = projects_last_fetched.getTime() / 1000;
			}

			if (!last_fetch) {
				console.log('[app.projectFactory] refreshIntervalPassed(): No last fetch value.');
				return true;
			}

			var seconds = now - last_fetch;
			console.log('[app.projectFactory] refreshIntervalPassed(): Seconds since last fetch: '+seconds);

			return seconds > projects_max_life;
		};

		// Service object
		var service =  {
			projects: function() {
				console.log('[app.projectFactory] service.projects(): call')
				if (!projects || projects_force_refetch || refreshIntervalPassed()) {
					return service.fetchProjects();
				}
				return projects;
			}, fetchProjects: function() {
				console.log('[app.projectFactory] service.fetchProjects(): call')
				projects_force_refetch = false;
				projects = $http({
					method: 'GET',
					url: '/api/projects/list.json',
					params: {
						't': new Date().getTime()
					}
				}).then(function(response) {
					// HTTP 200-299 Status
					if (angular.isObject(response.data)) {
						if (response.data.hasOwnProperty('projects')) {
							// Iterate through these projects, chang anything that must be changed...
							console.log('[app.projectFactory] service.fetchProjects(): data.response has projects, is valid');

							var keyedById = {};
							projects_last_fetched = new Date();

							for (var i = response.data.projects.length - 1; i >= 0; i--) {
								keyedById[response.data.projects[i].id] = response.data.projects[i];
								keyedById[response.data.projects[i].id]._lastFetch = projects_last_fetched;
							};
							return keyedById;
						}
					}
					console.log('[app.projectFactory] service.fetchProjects(): Error reading response.');
					return {
						'error': true
					};
				}, function(response) {
					// Error
					console.log('[app.projectFactory] service.fetchProjects(): Request error: '+response.status);
					return {
						'error': true,
						'status': response.status
					};
				});
				return projects;
			}, create: function(options) {

				var data = {
					'name': options.name,
					'description': options.description
				};

				return $http({
					method: 'POST',
					url: '/api/projects/create.json',
					params: {
						't': new Date().getTime()
					}, data: data
				}).then(function(response) {
					// HTTP 200-299 Status
					if (angular.isObject(response.data)) {
						if (response.data.hasOwnProperty('project')) {
							// Success!!!

							var _projects = $q.defer();
							var allProjects = {};

							if (!projects) {
								projects = _projects.promise;
								projects_force_refetch = true; 	// Force refetch of all projects
							} else {
								projects.then(function(currentProjects) {
									allProjects = currentProjects;
								});
							}

							allProjects[response.data.project.id] = response.data.project;
							allProjects[response.data.project.id]._lastFetch = new Date();

							_projects.resolve(allProjects);	// Resolve projects
							return allProjects[response.data.project.id];
						}
					}
					console.log('[app.projectFactory] service.create(): Error reading response.');
					return {
						'error': true
					};
				}, function(response) {
					// Error
					console.log('[app.projectFactory] service.create(): Request error: '+response.status);
					return {
						'error': true,
						'status': response.status
					};
				});
			}, project: function(projectId) {
				console.log('[app.projectFactory] service.project(): call, projectId: '+projectId);

				// Check to see if we have this Project in `projects` with the correct data, and it's not too old...

				var _project = $q.defer();

				service.projects().then(function(response) {
					if (response.hasOwnProperty(projectId)) {

						// Check age...
						_project.resolve(response[projectId]);
					}
				});

				return _project.promise;
			}, timeRecords: function(projectId) {
				console.log('[app.projectFactory] service.timeRecords(): call, projectId: '+projectId);
				if (!timeRecords[projectId] || projects_force_refetch[projectId] /*|| refreshIntervalPassed()*/) {
					return service.fetchTimeRecords(projectId);
				}
				return timeRecords[projectId];
			}, fetchTimeRecords: function(projectId) {
				console.log('[app.projectFactory] service.fetchTimeRecords(): call, projectId: '+projectId)
				timeRecords[projectId] = $http({
					method: 'GET',
					url: '/api/projects/time-records/list.json',
					params: {
						't': new Date().getTime(),
						'project_id': projectId
					}
				}).then(function(response) {
					// HTTP 200-299 Status
					if (angular.isObject(response.data)) {
						if (response.data.hasOwnProperty('project') && response.data.hasOwnProperty('time_records')) {
							// Iterate through these projects, chang anything that must be changed...
							console.log('[app.projectFactory] service.fetchTimeRecords(): data.response has projects and time_records, is valid');

							var keyedById = {};
							time_records_last_fetched[response.data.project.id] = new Date();

							for (var i = response.data.time_records.length - 1; i >= 0; i--) {
								keyedById[response.data.time_records[i].id] = response.data.time_records[i];
								keyedById[response.data.time_records[i].id]._lastFetch = time_records_last_fetched[response.data.project.id];
							};
							return keyedById;
						}
					}
					console.log('[app.projectFactory] service.fetchTimeRecords(): Error reading response.');
					return {
						'error': true
					};
				}, function(response) {
					// Error
					console.log('[app.projectFactory] service.fetchTimeRecords(): Request error: '+response.status);
					return {
						'error': true,
						'status': response.status
					};
				});
				return timeRecords[projectId];
			}
		};

		// Return the service object
		return service;
	}]);

})();<commit_msg>Moved where  is set, correctly forces a reload upon new Project creation<commit_after>(function(){

	var app = angular.module('app.projectFactory', []);

	app.factory('app.projectFactory', ['$http', '$q', function($http, $q) {

		// `projects` object caches all our Projects
		var projects;

		// Data refresh intervals
		var projects_last_fetched;
		var projects_max_life = 30; 	// seconds
		var project_max_life = 10;		// seconds
		var projects_force_refetch = true;

		// `timeRecords` object stores promises keyed to Project IDs
		var timeRecords = {};
		var time_records_last_fetched = {};	// Keyed to a Project ID

		var refreshIntervalPassed = function() {

			var now = new Date().getTime() / 1000;
			if (projects_last_fetched) {
				var last_fetch = projects_last_fetched.getTime() / 1000;
			}

			if (!last_fetch) {
				console.log('[app.projectFactory] refreshIntervalPassed(): No last fetch value.');
				return true;
			}

			var seconds = now - last_fetch;
			console.log('[app.projectFactory] refreshIntervalPassed(): Seconds since last fetch: '+seconds);

			return seconds > projects_max_life;
		};

		// Service object
		var service =  {
			projects: function() {
				console.log('[app.projectFactory] service.projects(): call')
				if (!projects || projects_force_refetch || refreshIntervalPassed()) {
					return service.fetchProjects();
				}
				return projects;
			}, fetchProjects: function() {
				console.log('[app.projectFactory] service.fetchProjects(): call')
				projects_force_refetch = false;
				projects = $http({
					method: 'GET',
					url: '/api/projects/list.json',
					params: {
						't': new Date().getTime()
					}
				}).then(function(response) {
					// HTTP 200-299 Status
					if (angular.isObject(response.data)) {
						if (response.data.hasOwnProperty('projects')) {
							// Iterate through these projects, chang anything that must be changed...
							console.log('[app.projectFactory] service.fetchProjects(): data.response has projects, is valid');

							var keyedById = {};
							projects_last_fetched = new Date();

							for (var i = response.data.projects.length - 1; i >= 0; i--) {
								keyedById[response.data.projects[i].id] = response.data.projects[i];
								keyedById[response.data.projects[i].id]._lastFetch = projects_last_fetched;
							};
							return keyedById;
						}
					}
					console.log('[app.projectFactory] service.fetchProjects(): Error reading response.');
					return {
						'error': true
					};
				}, function(response) {
					// Error
					console.log('[app.projectFactory] service.fetchProjects(): Request error: '+response.status);
					return {
						'error': true,
						'status': response.status
					};
				});
				return projects;
			}, create: function(options) {

				var data = {
					'name': options.name,
					'description': options.description
				};

				return $http({
					method: 'POST',
					url: '/api/projects/create.json',
					params: {
						't': new Date().getTime()
					}, data: data
				}).then(function(response) {
					// HTTP 200-299 Status
					if (angular.isObject(response.data)) {
						if (response.data.hasOwnProperty('project')) {
							// Success!!!

							var _projects = $q.defer();
							var allProjects = {};

							if (!projects) {
								projects = _projects.promise;
							} else {
								projects_force_refetch = true; 	// Force refetch of all projects
								projects.then(function(currentProjects) {
									allProjects = currentProjects;
								});
							}

							allProjects[response.data.project.id] = response.data.project;
							allProjects[response.data.project.id]._lastFetch = new Date();

							_projects.resolve(allProjects);	// Resolve projects
							return allProjects[response.data.project.id];
						}
					}
					console.log('[app.projectFactory] service.create(): Error reading response.');
					return {
						'error': true
					};
				}, function(response) {
					// Error
					console.log('[app.projectFactory] service.create(): Request error: '+response.status);
					return {
						'error': true,
						'status': response.status
					};
				});
			}, project: function(projectId) {
				console.log('[app.projectFactory] service.project(): call, projectId: '+projectId);

				// Check to see if we have this Project in `projects` with the correct data, and it's not too old...

				var _project = $q.defer();

				service.projects().then(function(response) {
					if (response.hasOwnProperty(projectId)) {

						// Check age...
						_project.resolve(response[projectId]);
					}
				});

				return _project.promise;
			}, timeRecords: function(projectId) {
				console.log('[app.projectFactory] service.timeRecords(): call, projectId: '+projectId);
				if (!timeRecords[projectId] || projects_force_refetch[projectId] /*|| refreshIntervalPassed()*/) {
					return service.fetchTimeRecords(projectId);
				}
				return timeRecords[projectId];
			}, fetchTimeRecords: function(projectId) {
				console.log('[app.projectFactory] service.fetchTimeRecords(): call, projectId: '+projectId)
				timeRecords[projectId] = $http({
					method: 'GET',
					url: '/api/projects/time-records/list.json',
					params: {
						't': new Date().getTime(),
						'project_id': projectId
					}
				}).then(function(response) {
					// HTTP 200-299 Status
					if (angular.isObject(response.data)) {
						if (response.data.hasOwnProperty('project') && response.data.hasOwnProperty('time_records')) {
							// Iterate through these projects, chang anything that must be changed...
							console.log('[app.projectFactory] service.fetchTimeRecords(): data.response has projects and time_records, is valid');

							var keyedById = {};
							time_records_last_fetched[response.data.project.id] = new Date();

							for (var i = response.data.time_records.length - 1; i >= 0; i--) {
								keyedById[response.data.time_records[i].id] = response.data.time_records[i];
								keyedById[response.data.time_records[i].id]._lastFetch = time_records_last_fetched[response.data.project.id];
							};
							return keyedById;
						}
					}
					console.log('[app.projectFactory] service.fetchTimeRecords(): Error reading response.');
					return {
						'error': true
					};
				}, function(response) {
					// Error
					console.log('[app.projectFactory] service.fetchTimeRecords(): Request error: '+response.status);
					return {
						'error': true,
						'status': response.status
					};
				});
				return timeRecords[projectId];
			}
		};

		// Return the service object
		return service;
	}]);

})();<|endoftext|>


<commit_before>'use strict';

import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import {ExtendModel} from '../../lib/Vogels/ExtendModel';
import {Exception} from '../../lib/Vogels/Exceptions/Exception';
import {UndefinedMethodException} from '../../lib/Vogels/Exceptions/UndefinedMethodException';
import {ModelMock} from '../../test/Mock/ModelMock';
import {ExtendModelMock} from '../../test/Mock/ExtendModelMock';
import resultSegments from './scan.segments';

chai.use(sinonChai);

suite('Vogels/ExtendModel', () => {
  let model = {
    Name: {
      Name: 'string',
      Id: 'timeUUID',
    },
  };
  let extendModel = new ExtendModel(model);

  let modelMock = new ModelMock();
  modelMock.setMode(ModelMock.NO_RESULT_MODE);
  let mockedExtendModel = new ExtendModel(modelMock);

  test('Class ExtendModel exists in Vogels/ExtendModel', () => {
    chai.expect(ExtendModel).to.be.an('function');
  });

  test('Check constructor sets _model', () => {
    chai.expect(extendModel.model).to.be.equal(model);
  });

  test('Check DEFAULT_LIMIT static getter returns value more than 0', () => {
    chai.expect(ExtendModel.DEFAULT_LIMIT).to.be.above(0);
  });

  test('Check DEFAULT_SEGMENTS_NUMBER static getter returns value more than 0', () => {
    chai.expect(ExtendModel.DEFAULT_SEGMENTS_NUMBER).to.be.above(0);
  });

  test('Check buildScanParameters static getter returns value more than 0', () => {
    let expectedResult = {
      filterExpression: '#firstKey = :firstKey AND #secondKey = :secondKey',
      filterExpressionNames: {
        '#firstKey': 'firstKey',
        '#secondKey': 'secondKey',
      },
      filterExpressionValues: {
        ':firstKey': 'Value0',
        ':secondKey': 'Value0',
      },
    };
    let acttualResult = ExtendModel.buildScanParameters({firstKey: 'Value0', secondKey: 'Value0',})
    chai.expect(acttualResult).to.be.eql(expectedResult);
  });

  test('Check inject() method with methods=null', () => {
    chai.expect(extendModel.inject()).to.be.eql(model);
  });

  test('Check methods() getter', () => {
    let actualResult = extendModel.methods;
    let methods = Object.keys(actualResult);

    let expectedMethodNames = ['findAll', 'findAllPaginated', 'findOneById', 'findOneBy',
      'findBy', 'findAllBy', 'findAllByPaginated', 'findMatching', 'findOneMatching',
      'findAllMatching', 'findAllMatchingPaginated', 'deleteById',
      'deleteByIdConditional', 'createItem', 'createUniqueOnFields',
      'updateItem', 'updateItemConditional', 'findItems'];

    //check all items is fucntions
    for (let methodName of expectedMethodNames) {
      chai.expect(methods).to.be.contains(methodName);
      chai.expect(typeof actualResult[methodName]).to.be.equal('function');
    }
  });

  // @todo move to a separate file
  const queryMock = (function() {
    let segmentKeys = Object.keys(resultSegments);
    let startKey = segmentKeys[0];

    return {
      segmentKeys() {
        return segmentKeys;
      },
      limit() {
        return this;
      },
      startKey(key) {
        startKey = key || startKey;
        return this;
      },
      exec(cb) {
        const result = resultSegments[startKey];

        cb(null, result);
      },
    };
  });

  test('Check method._findUntilLimit[Cb]() passes findOne* call', (done) => {
    mockedExtendModel.methods._findUntilLimitCb((error, result) => {
      chai.expect(error).to.be.null;
      chai.expect(result).to.deep.equal({
        ScannedCount: 3,
        Count: 1,
        Items: [ 'a1' ],
      });

      done();
    }, new queryMock, 1);
  });

  test('Check method._findUntilLimit[Cb]() passes findBy* call', (done) => {
    mockedExtendModel.methods._findUntilLimitCb((error, result) => {
      chai.expect(error).to.be.null;
      chai.expect(result).to.deep.equal({
        ScannedCount: 9,
        Count: 7,
        Items: [ 'a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1' ],
      });

      done();
    }, new queryMock, 7);
  });

  test('Check method._findUntilLimit[Cb]() passes findBy*Paginated call', (done) => {
    let query = new queryMock;
    let segmentKeys = query.segmentKeys();

    mockedExtendModel.methods._findUntilLimitCb(
      (error, result) => {
        chai.expect(error).to.be.null;
        chai.expect(result).to.deep.equal({
          ScannedCount: 6,
          Count: 6,
          Items: [ 'c1', 'c2', 'c3', 'd1', 'd2', 'd3' ],
        });

        done();
      }, query, 999, 0, [], segmentKeys[segmentKeys.length - 3]
    );
  });

  test('Check method.findAll() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAll(spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  // test('Check method.findAllPaginated() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findAllPaginated('startKey', 'limit', spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  test('Check method.findOneById() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findOneById('id', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  // test('Check method.findOneBy() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findOneBy('fieldName', 'value', spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  // test('Check method.findBy() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findBy('fieldName', 'value', spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  test('Check method.findAllBy() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllBy('fieldName', 'value', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.findAllByPaginated() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllByPaginated('fieldName', 'value', 'startKey', 'limit', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  // test('Check method.findMatching() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findMatching({}, spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  // test('Check method.findOneMatching() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findOneMatching({}, spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  test('Check method.findAllMatching() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllMatching({}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.findAllMatchingPaginated() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllMatchingPaginated({}, 'startKey', 'limit', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.deleteById() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.deleteById('id', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.deleteByIdConditional() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.deleteByIdConditional('id', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.createItem() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.createItem('data', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.updateItem() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.updateItem('id', {key: 'test value'}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.updateItemConditional() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.updateItemConditional('id', {key: 'test value'}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.createUniqueOnFields() for already existed item', () => {
    let spyCallback = sinon.spy();

    modelMock.setMode(ModelMock.DATA_WITH_COUNT_MODE, ['exec']);

    mockedExtendModel.methods.createUniqueOnFields('fields', {Count: false}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWith();

    chai.expect(spyCallback.args[0][0]).to.contains('already exists');
  });

  test('Check method.createUniqueOnFields() for new fields', () => {
    let spyCallback = sinon.spy();

    modelMock.setMode(ModelMock.DATA_MODE, ['exec']);

    mockedExtendModel.methods.createUniqueOnFields('fields', {Count: false}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  //@todo - to be updated
  //test('Check "Exception" exception can be called', () => {
  //  let extendModelMock = new ExtendModelMock();
  //  let error = null;
  //  let msg = 'Test message';
  //
  //  try {
  //    extendModelMock.throwException(msg);
  //  } catch (e) {
  //    error = e;
  //  }
  //
  //  chai.assert.instanceOf(error, Exception, 'error is an instance of Exception');
  //});
  //
  //test('Check "UndefinedMethodException" exception can be called', () => {
  //  let error = null;
  //  let method = 'test';
  //  let predefinedMethods = ['firstMethod', 'secondMethod'];
  //  let extendModelMock = new ExtendModelMock();
  //
  //  try {
  //    extendModelMock.throwUndefinedMethodException(method, predefinedMethods);
  //  } catch (e) {
  //    error = e;
  //  }
  //
  //  chai.assert.instanceOf(
  //    error, UndefinedMethodException, 'error is an instance of UndefinedMethodException'
  //  );
  //});
});
<commit_msg>Fix packages tests<commit_after>'use strict';

import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import {ExtendModel} from '../../lib/Vogels/ExtendModel';
import {Exception} from '../../lib/Vogels/Exceptions/Exception';
import {UndefinedMethodException} from '../../lib/Vogels/Exceptions/UndefinedMethodException';
import {ModelMock} from '../../test/Mock/ModelMock';
import {ExtendModelMock} from '../../test/Mock/ExtendModelMock';
import resultSegments from './scan.segments';

chai.use(sinonChai);

suite('Vogels/ExtendModel', () => {
  let model = {
    Name: {
      Name: 'string',
      Id: 'timeUUID',
    },
  };
  let extendModel = new ExtendModel(model);

  let modelMock = new ModelMock();
  modelMock.setMode(ModelMock.NO_RESULT_MODE);
  let mockedExtendModel = new ExtendModel(modelMock);

  test('Class ExtendModel exists in Vogels/ExtendModel', () => {
    chai.expect(ExtendModel).to.be.an('function');
  });

  test('Check constructor sets _model', () => {
    chai.expect(extendModel.model).to.be.equal(model);
  });

  test('Check DEFAULT_LIMIT static getter returns value more than 0', () => {
    chai.expect(ExtendModel.DEFAULT_LIMIT).to.be.above(0);
  });

  test('Check DEFAULT_SEGMENTS_NUMBER static getter returns value more than 0', () => {
    chai.expect(ExtendModel.DEFAULT_SEGMENTS_NUMBER).to.be.above(0);
  });

  test('Check buildScanParameters static getter returns value more than 0', () => {
    let expectedResult = {
      filterExpression: '#firstKey = :firstKey AND #secondKey = :secondKey',
      filterExpressionNames: {
        '#firstKey': 'firstKey',
        '#secondKey': 'secondKey',
      },
      filterExpressionValues: {
        ':firstKey': 'Value0',
        ':secondKey': 'Value0',
      },
    };
    let acttualResult = ExtendModel.buildScanParameters({firstKey: 'Value0', secondKey: 'Value0',})
    chai.expect(acttualResult).to.be.eql(expectedResult);
  });

  test('Check inject() method with methods=null', () => {
    chai.expect(extendModel.inject()).to.be.eql(model);
  });

  test('Check methods() getter', () => {
    let actualResult = extendModel.methods;
    let methods = Object.keys(actualResult);

    let expectedMethodNames = ['findAll', 'findAllPaginated', 'findOneById', 'findOneBy',
      'findBy', 'findAllBy', 'findAllByPaginated', 'findMatching', 'findOneMatching',
      'findAllMatching', 'findAllMatchingPaginated', 'deleteById',
      'deleteByIdConditional', 'createItem', 'createUniqueOnFields',
      'updateItem', 'updateItemConditional', 'findItems'];

    //check all items is fucntions
    for (let methodName of expectedMethodNames) {
      chai.expect(methods).to.be.contains(methodName);
      chai.expect(typeof actualResult[methodName]).to.be.equal('function');
    }
  });

  // @todo move to a separate file
  const queryMock = (function() {
    let segmentKeys = Object.keys(resultSegments);
    let startKey = segmentKeys[0];

    return {
      segmentKeys() {
        return segmentKeys;
      },
      limit() {
        return this;
      },
      startKey(key) {
        startKey = key || startKey;
        return this;
      },
      exec(cb) {
        const result = resultSegments[startKey];

        cb(null, result);
      },
    };
  });

  test('Check method._findUntilLimit[Cb]() passes findOne* call', (done) => {
    mockedExtendModel.methods._findUntilLimitCb((error, result) => {
      chai.expect(error).to.be.null;
      chai.expect(result).to.deep.equal({
        ScannedCount: 3,
        Count: 1,
        Items: [ 'a1' ],
      });

      done();
    }, new queryMock, 1);
  });

  test('Check method._findUntilLimit[Cb]() passes findBy* call', (done) => {
    mockedExtendModel.methods._findUntilLimitCb((error, result) => {
      chai.expect(error).to.be.null;
      chai.expect(result).to.deep.equal({
        ScannedCount: 9,
        Count: 7,
        Items: [ 'a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1' ],
      });

      done();
    }, new queryMock, 7);
  });

  test('Check method._findUntilLimit[Cb]() passes findBy*Paginated call', (done) => {
    let query = new queryMock;
    let segmentKeys = query.segmentKeys();

    mockedExtendModel.methods._findUntilLimitCb(
      (error, result) => {
        console.log('result', JSON.stringify(result));//@todo remove

        chai.expect(error).to.be.null;
        chai.expect(result).to.deep.equal({
          ScannedCount: 6,
          Count: 6,
          Items: [ 'c1', 'c2', 'c3', 'd1', 'd2', 'd3' ],
        });

        done();
      }, query, 999, 0, [], segmentKeys[segmentKeys.length - 3]
    );
  });

  test('Check method.findAll() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAll(spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  // test('Check method.findAllPaginated() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findAllPaginated('startKey', 'limit', spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  test('Check method.findOneById() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findOneById('id', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  // test('Check method.findOneBy() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findOneBy('fieldName', 'value', spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  // test('Check method.findBy() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findBy('fieldName', 'value', spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  test('Check method.findAllBy() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllBy('fieldName', 'value', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.findAllByPaginated() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllByPaginated('fieldName', 'value', 'startKey', 'limit', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  // test('Check method.findMatching() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findMatching({}, spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  // test('Check method.findOneMatching() exist and can be called', () => {
  //   let spyCallback = sinon.spy();
  //
  //   mockedExtendModel.methods.findOneMatching({}, spyCallback);
  //
  //   chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  // });

  test('Check method.findAllMatching() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllMatching({}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.findAllMatchingPaginated() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.findAllMatchingPaginated({}, 'startKey', 'limit', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.deleteById() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.deleteById('id', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.deleteByIdConditional() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.deleteByIdConditional('id', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.createItem() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.createItem('data', spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.updateItem() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.updateItem('id', {key: 'test value'}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.updateItemConditional() exist and can be called', () => {
    let spyCallback = sinon.spy();

    mockedExtendModel.methods.updateItemConditional('id', {key: 'test value'}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  test('Check method.createUniqueOnFields() for already existed item', () => {
    let spyCallback = sinon.spy();

    modelMock.setMode(ModelMock.DATA_WITH_COUNT_MODE, ['exec']);

    mockedExtendModel.methods.createUniqueOnFields('fields', {Count: false}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWith();

    chai.expect(spyCallback.args[0][0]).to.contains('already exists');
  });

  test('Check method.createUniqueOnFields() for new fields', () => {
    let spyCallback = sinon.spy();

    modelMock.setMode(ModelMock.DATA_MODE, ['exec']);

    mockedExtendModel.methods.createUniqueOnFields('fields', {Count: false}, spyCallback);

    chai.expect(spyCallback).to.have.been.calledWithExactly(null, null);
  });

  //@todo - to be updated
  //test('Check "Exception" exception can be called', () => {
  //  let extendModelMock = new ExtendModelMock();
  //  let error = null;
  //  let msg = 'Test message';
  //
  //  try {
  //    extendModelMock.throwException(msg);
  //  } catch (e) {
  //    error = e;
  //  }
  //
  //  chai.assert.instanceOf(error, Exception, 'error is an instance of Exception');
  //});
  //
  //test('Check "UndefinedMethodException" exception can be called', () => {
  //  let error = null;
  //  let method = 'test';
  //  let predefinedMethods = ['firstMethod', 'secondMethod'];
  //  let extendModelMock = new ExtendModelMock();
  //
  //  try {
  //    extendModelMock.throwUndefinedMethodException(method, predefinedMethods);
  //  } catch (e) {
  //    error = e;
  //  }
  //
  //  chai.assert.instanceOf(
  //    error, UndefinedMethodException, 'error is an instance of UndefinedMethodException'
  //  );
  //});
});
<|endoftext|>


<commit_before>
// install   :      cordova plugin add phonegap-plugin-push
// link      :      https://github.com/phonegap/phonegap-plugin-push

angular.module('ngCordova.plugins.push_v5', [])
  .factory('$cordovaPushV5',['$q', '$rootScope', '$timeout', function ($q, $rootScope, $timeout) {
   /*global PushNotification*/

    var push;
    return {
      initialize : function (options) {
        var q = $q.defer();
        push = PushNotification.init(options);
        q.resolve(push);
        return q.promise;
      },
      onNotification : function () {
        $timeout(function () {
          push.on('notification', function (notification) {
            $rootScope.$emit('$cordovaPushV5:notificationReceived', notification);
          });
        });
      },
      onError : function () {
        $timeout(function () {
          push.on('error', function (error) { $rootScope.$emit('$cordovaPushV5:errorOccurred', error);});
        });
      },
      register : function () {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.on('registration', function (data) {
            q.resolve(data.registrationId);
          });
        }
        return q.promise;
      },
      unregister : function () {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.unregister(function (success) {
            q.resolve(success);
          },function (error) {
            q.reject(error);
          });
        }
        return q.promise;
      },
      setBadgeNumber : function (number) {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.setApplicationIconBadgeNumber(function (success) {
            q.resolve(success);
          }, function (error) {
            q.reject(error);
          }, number);
        }
        return q.promise;
      },
      finish: function (){
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.finish(function (success) {
            q.resolve(success);
          }, function (error) {
            q.reject(error);
          });
        }
        return q.promise;
      }
    };
  }]);
<commit_msg>Add new method getBadgeNumber() to push_v5 (#1216)<commit_after>
// install   :      cordova plugin add phonegap-plugin-push
// link      :      https://github.com/phonegap/phonegap-plugin-push

angular.module('ngCordova.plugins.push_v5', [])
  .factory('$cordovaPushV5',['$q', '$rootScope', '$timeout', function ($q, $rootScope, $timeout) {
   /*global PushNotification*/

    var push;
    return {
      initialize : function (options) {
        var q = $q.defer();
        push = PushNotification.init(options);
        q.resolve(push);
        return q.promise;
      },
      onNotification : function () {
        $timeout(function () {
          push.on('notification', function (notification) {
            $rootScope.$emit('$cordovaPushV5:notificationReceived', notification);
          });
        });
      },
      onError : function () {
        $timeout(function () {
          push.on('error', function (error) { $rootScope.$emit('$cordovaPushV5:errorOccurred', error);});
        });
      },
      register : function () {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.on('registration', function (data) {
            q.resolve(data.registrationId);
          });
        }
        return q.promise;
      },
      unregister : function () {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.unregister(function (success) {
            q.resolve(success);
          },function (error) {
            q.reject(error);
          });
        }
        return q.promise;
      },
      getBadgeNumber : function () {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.getApplicationIconBadgeNumber(function (success) {
            q.resolve(success);
          }, function (error) {
            q.reject(error);
          });
        }
        return q.promise;
      },
      setBadgeNumber : function (number) {
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.setApplicationIconBadgeNumber(function (success) {
            q.resolve(success);
          }, function (error) {
            q.reject(error);
          }, number);
        }
        return q.promise;
      },
      finish: function (){
        var q = $q.defer();
        if (push === undefined) {
          q.reject(new Error('init must be called before any other operation'));
        } else {
          push.finish(function (success) {
            q.resolve(success);
          }, function (error) {
            q.reject(error);
          });
        }
        return q.promise;
      }
    };
  }]);
<|endoftext|>


<commit_before>import Ember from "ember";

const {
  computed,
  ArrayProxy,
  ObjectProxy
  } = Ember;

function computeProxiedArray() {

  var proxied = this.get('content');
  var key = this.get('keyForId');
  var content = this.get('__proxyContent');
  var newLength;
  var newObjects = Ember.A();
  var diff;

  // play nice with arrays that are already proxied
  if (proxied && proxied.get && proxied.get('content')) {
    proxied = proxied.get('content');
  }

  this.beginPropertyChanges();

  // create a new array object if we don't have one yet
  if (proxied) {

    // handle additions to the beginning of the array
    if (this._changeIsPrepend(proxied, content, key)) {

      newLength = Ember.get(proxied, 'length');
      diff = newLength - content.get('length');
      for (var i = 0; i < diff; i++) {
        newObjects.push(ObjectProxy.create({content: proxied[i]}));
      }
      if (newObjects.length) {
        content.replace(0, 0, newObjects);
      }

      // handle additions and inline changes
    } else {

      proxied.forEach(function(item, index) {
        var proxiedObject = content.objectAt(index);
        if (proxiedObject) {
          proxiedObject.set('content', item);
        } else {
          newObjects.push(ObjectProxy.create({content: item}));
        }
      });

      if (newObjects.length) {
        content.pushObjects(newObjects);
      }

    }

  }

  newLength = proxied ? Ember.get(proxied, 'length') : 0;

  if (newLength < content.get('length')) {
    diff = content.get('length') - newLength;
    content.removeAt(newLength, diff);
  }

  this.endPropertyChanges();

  return content;

}

var Mixin = Ember.Mixin.create({

  keyForId: null,

  content: null,

  _proxyContentTo: '__content',

  __proxyContent: null,

  _changeIsPrepend: function(newArray, proxiedArray, key) {

    var lengthDifference = proxiedArray.get('length') - Ember.get(newArray, 'length');

    // if either array is empty or the new array is not longer, do not treat as prepend
    if (!proxiedArray.get('length') || !Ember.get(newArray, 'length') || lengthDifference >= 0) {
      return false;
    }

    // if the object at the right key is the same, this is a prepend
    var oldInitialItem = proxiedArray.objectAt(0).get('__key');

    var newInitialItem = Ember.get(newArray[-lengthDifference], key);
    return oldInitialItem === newInitialItem;

  },

  _initializeMagicArray: function() {
    var dest = this.get('_proxyContentTo');
    this.set('__proxyContent', ArrayProxy.create({ content: Ember.A() }));
    this.set(dest, computed('content', 'content.@each', computeProxiedArray));
  },

  init: function() {
    this._super.apply(this, arguments);
    this._initializeMagicArray();
  }

});

export default Mixin;
<commit_msg>adds experimental diffing flag to the magic array<commit_after>import Ember from "ember";

const {
  computed,
  ArrayProxy,
  ObjectProxy,
  get: get
  } = Ember;

function mergeDiffedArrays() {
  var inbound = this.get('content');
  var outbound = this.get('__proxyContent');
  var keyForId = this.get('keyForId');
  var cache = this.get('__cache');
  var newList = {};
  var newOutbound = [];

  inbound.forEach((item) => {
    let key = get(item, keyForId);
    let obj = cache[key] || ObjectProxy.create({content: item});
    newList[key] = obj;
    newOutbound.push(obj);
  });

  outbound.set('content', newOutbound);
  this.set('__cache', newList);

  return outbound;
}

function computeProxiedArray() {

  if (this.get('useDiffing')) {
    return mergeDiffedArrays.call(this);
  }

  var inbound = this.get('content');
  var key = this.get('keyForId');
  var outbound = this.get('__proxyContent');
  var newLength;
  var newObjects = Ember.A();
  var diff;

  // play nice with arrays that are already proxied
  if (inbound && inbound.get && inbound.get('content')) {
    inbound = inbound.get('content');
  }

  this.beginPropertyChanges();

  // create a new array object if we don't have one yet
  if (inbound) {

    // handle additions to the beginning of the array
    if (this._changeIsPrepend(inbound, outbound, key)) {

      newLength = Ember.get(inbound, 'length');
      diff = newLength - outbound.get('length');
      for (var i = 0; i < diff; i++) {
        newObjects.push(ObjectProxy.create({content: inbound[i]}));
      }
      if (newObjects.length) {
        outbound.replace(0, 0, newObjects);
      }

      // handle additions and inline changes
    } else {

      inbound.forEach(function(item, index) {
        var proxiedObject = outbound.objectAt(index);
        if (proxiedObject) {
          proxiedObject.set('content', item);
        } else {
          newObjects.push(ObjectProxy.create({content: item}));
        }
      });

      if (newObjects.length) {
        outbound.pushObjects(newObjects);
      }

    }

  }

  newLength = inbound ? Ember.get(inbound, 'length') : 0;

  if (newLength < outbound.get('length')) {
    diff = outbound.get('length') - newLength;
    outbound.removeAt(newLength, diff);
  }

  this.endPropertyChanges();

  return outbound;

}

var Mixin = Ember.Mixin.create({

  keyForId: null,

  content: null,

  useDiffing: false,

  _proxyContentTo: '__content',

  __proxyContent: null,

  __cache: null,

  _changeIsPrepend: function(newArray, proxiedArray, key) {

    var lengthDifference = proxiedArray.get('length') - Ember.get(newArray, 'length');

    // if either array is empty or the new array is not longer, do not treat as prepend
    if (!proxiedArray.get('length') || !Ember.get(newArray, 'length') || lengthDifference >= 0) {
      return false;
    }

    // if the object at the right key is the same, this is a prepend
    var oldInitialItem = proxiedArray.objectAt(0).get('__key');

    var newInitialItem = Ember.get(newArray[-lengthDifference], key);
    return oldInitialItem === newInitialItem;

  },

  _initializeMagicArray: function() {
    var dest = this.get('_proxyContentTo');
    this.set('__proxyContent', ArrayProxy.create({ content: [] }));
    this.set(dest, computed('content', 'content.@each', computeProxiedArray));
  },

  init: function() {
    this._super.apply(this, arguments);
    this.set('__cache', {});
    this._initializeMagicArray();
  }

});

export default Mixin;
<|endoftext|>


<commit_before>import path from "path";
import { fileURLToPath } from "url";
import TestStream from "test262-stream";
import TestRunner from "../utils/parser-test-runner.js";

const dirname = path.dirname(fileURLToPath(import.meta.url));

const ignoredFeatures = [
  "__getter__",
  "__setter__",
  "AggregateError",
  "Array.prototype.at",
  "Array.prototype.flat",
  "Array.prototype.flatMap",
  "Array.prototype.item",
  "Array.prototype.values",
  "ArrayBuffer",
  "align-detached-buffer-semantics-with-web-reality",
  "async-functions",
  "async-iteration",
  "arrow-function",
  "Atomics",
  "Atomics.waitAsync",
  "BigInt",
  "caller",
  "class",
  "cleanupSome",
  "coalesce-expression",
  "computed-property-names",
  "const",
  "cross-realm",
  "DataView",
  "DataView.prototype.getFloat32",
  "DataView.prototype.getFloat64",
  "DataView.prototype.getInt8",
  "DataView.prototype.getInt16",
  "DataView.prototype.getInt32",
  "DataView.prototype.getUint16",
  "DataView.prototype.getUint32",
  "DataView.prototype.setUint8",
  "default-parameters",
  "destructuring-assignment",
  "destructuring-binding",
  "dynamic-import",
  "export-star-as-namespace-from-module",
  "FinalizationGroup",
  "FinalizationRegistry",
  "FinalizationRegistry.prototype.cleanupSome",
  "Float32Array",
  "Float64Array",
  "for-in-order",
  "for-of",
  "generators",
  "globalThis",
  "hashbang",
  "host-gc-required",
  "Int8Array",
  "Int16Array",
  "Int32Array",
  "Intl.DateTimeFormat-datetimestyle",
  "Intl.DateTimeFormat-dayPeriod",
  "Intl.DateTimeFormat-fractionalSecondDigits",
  "Intl.DateTimeFormat-formatRange",
  "Intl.DisplayNames",
  "Intl.ListFormat",
  "Intl.Locale",
  "Intl.NumberFormat-unified",
  "Intl.RelativeTimeFormat",
  "Intl.Segmenter",
  "IsHTMLDDA",
  "import.meta",
  "intl-normative-optional",
  "json-superset",
  "legacy-regexp",
  "let",
  "logical-assignment-operators",
  "Map",
  "new.target",
  "numeric-separator-literal",
  "Object.fromEntries",
  "Object.is",
  "object-rest",
  "object-spread",
  "optional-catch-binding",
  "optional-chaining",
  "Promise",
  "Promise.allSettled",
  "Promise.any",
  "Promise.prototype.finally",
  "Proxy",
  "proxy-missing-checks",
  "Reflect",
  "Reflect.construct",
  "Reflect.set",
  "Reflect.setPrototypeOf",
  "regexp-dotall",
  "regexp-lookbehind",
  "regexp-named-groups",
  "regexp-unicode-property-escapes",
  "rest-parameters",
  "SharedArrayBuffer",
  "Set",
  "String.fromCodePoint",
  "String.prototype.at",
  "String.prototype.endsWith",
  "String.prototype.includes",
  "String.prototype.item",
  "String.prototype.matchAll",
  "String.prototype.replaceAll",
  "String.prototype.trimEnd",
  "String.prototype.trimStart",
  "string-trimming",
  "super",
  "Symbol",
  "Symbol.asyncIterator",
  "Symbol.hasInstance",
  "Symbol.isConcatSpreadable",
  "Symbol.iterator",
  "Symbol.match",
  "Symbol.matchAll",
  "Symbol.prototype.description",
  "Symbol.replace",
  "Symbol.search",
  "Symbol.split",
  "Symbol.species",
  "Symbol.toPrimitive",
  "Symbol.toStringTag",
  "Symbol.unscopables",
  "tail-call-optimization",
  "template",
  "TypedArray",
  "TypedArray.prototype.at",
  "TypedArray.prototype.item",
  "u180e",
  "Uint8Array",
  "Uint8ClampedArray",
  "Uint16Array",
  "Uint32Array",
  "WeakMap",
  "WeakSet",
  "WeakRef",
  "well-formed-json-stringify",
];

const ignoredTests = ["built-ins/RegExp/", "language/literals/regexp/"];

const featuresToPlugins = {
  "arbitrary-module-namespace-names": "moduleStringNames",
  "class-fields-private": "classPrivateProperties",
  "class-fields-private-in": "privateIn",
  "class-fields-public": "classProperties",
  "class-methods-private": "classPrivateMethods",
  "class-static-fields-public": "classProperties",
  "class-static-fields-private": "classPrivateProperties",
  "class-static-methods-private": "classPrivateMethods",
  "top-level-await": "topLevelAwait",
};

const unmappedFeatures = new Set();

function* getPlugins(features) {
  if (!features) return;

  for (const f of features) {
    if (featuresToPlugins[f]) {
      yield featuresToPlugins[f];
    } else if (!ignoredFeatures.includes(f)) {
      unmappedFeatures.add(f);
    }
  }
}

const runner = new TestRunner({
  testDir: path.join(dirname, "../../../build/test262"),
  allowlist: path.join(dirname, "allowlist.txt"),
  logInterval: 500,
  shouldUpdate: process.argv.includes("--update-allowlist"),

  async *getTests() {
    const stream = new TestStream(this.testDir, {
      omitRuntime: true,
    });

    for await (const test of stream) {
      // strip test/
      const fileName = test.file.substr(5);

      if (ignoredTests.some(start => fileName.startsWith(start))) continue;

      yield {
        contents: test.contents,
        fileName,
        id: `${fileName}(${test.scenario})`,
        sourceType: test.attrs.flags.module ? "module" : "script",
        plugins: Array.from(getPlugins(test.attrs.features)),
        expectedError:
          !!test.attrs.negative &&
          (test.attrs.negative.phase === "parse" ||
            test.attrs.negative.phase === "early"),
      };
    }
  },
});

runner
  .run()
  .then(() => {
    if (unmappedFeatures.size) {
      console.log("");
      console.log(
        "The following Features are not currently mapped or ignored:"
      );
      console.log(
        Array.from(unmappedFeatures).join("\n").replace(/^/gm, "   ")
      );
    }
  })
  .catch(err => {
    console.error(err);
    process.exitCode = 1;
  });
<commit_msg>chore: add class-static-block test262 mapping (#13313)<commit_after>import path from "path";
import { fileURLToPath } from "url";
import TestStream from "test262-stream";
import TestRunner from "../utils/parser-test-runner.js";

const dirname = path.dirname(fileURLToPath(import.meta.url));

const ignoredFeatures = [
  "__getter__",
  "__setter__",
  "AggregateError",
  "Array.prototype.at",
  "Array.prototype.flat",
  "Array.prototype.flatMap",
  "Array.prototype.item",
  "Array.prototype.values",
  "ArrayBuffer",
  "align-detached-buffer-semantics-with-web-reality",
  "arbitrary-module-namespace-names",
  "async-functions",
  "async-iteration",
  "arrow-function",
  "Atomics",
  "Atomics.waitAsync",
  "BigInt",
  "caller",
  "class",
  "class-fields-private",
  "class-fields-public",
  "class-methods-private",
  "class-static-fields-private",
  "class-static-fields-public",
  "class-static-methods-private",
  "cleanupSome",
  "coalesce-expression",
  "computed-property-names",
  "const",
  "cross-realm",
  "DataView",
  "DataView.prototype.getFloat32",
  "DataView.prototype.getFloat64",
  "DataView.prototype.getInt8",
  "DataView.prototype.getInt16",
  "DataView.prototype.getInt32",
  "DataView.prototype.getUint16",
  "DataView.prototype.getUint32",
  "DataView.prototype.setUint8",
  "default-parameters",
  "destructuring-assignment",
  "destructuring-binding",
  "dynamic-import",
  "export-star-as-namespace-from-module",
  "FinalizationGroup",
  "FinalizationRegistry",
  "FinalizationRegistry.prototype.cleanupSome",
  "Float32Array",
  "Float64Array",
  "for-in-order",
  "for-of",
  "generators",
  "globalThis",
  "hashbang",
  "host-gc-required",
  "Int8Array",
  "Int16Array",
  "Int32Array",
  "Intl.DateTimeFormat-datetimestyle",
  "Intl.DateTimeFormat-dayPeriod",
  "Intl.DateTimeFormat-fractionalSecondDigits",
  "Intl.DateTimeFormat-formatRange",
  "Intl.DisplayNames",
  "Intl.ListFormat",
  "Intl.Locale",
  "Intl.NumberFormat-unified",
  "Intl.RelativeTimeFormat",
  "Intl.Segmenter",
  "IsHTMLDDA",
  "import.meta",
  "intl-normative-optional",
  "json-superset",
  "legacy-regexp",
  "let",
  "logical-assignment-operators",
  "Map",
  "new.target",
  "numeric-separator-literal",
  "Object.fromEntries",
  "Object.is",
  "object-rest",
  "object-spread",
  "optional-catch-binding",
  "optional-chaining",
  "Promise",
  "Promise.allSettled",
  "Promise.any",
  "Promise.prototype.finally",
  "Proxy",
  "proxy-missing-checks",
  "Reflect",
  "Reflect.construct",
  "Reflect.set",
  "Reflect.setPrototypeOf",
  "regexp-dotall",
  "regexp-lookbehind",
  "regexp-named-groups",
  "regexp-unicode-property-escapes",
  "rest-parameters",
  "SharedArrayBuffer",
  "Set",
  "String.fromCodePoint",
  "String.prototype.at",
  "String.prototype.endsWith",
  "String.prototype.includes",
  "String.prototype.item",
  "String.prototype.matchAll",
  "String.prototype.replaceAll",
  "String.prototype.trimEnd",
  "String.prototype.trimStart",
  "string-trimming",
  "super",
  "Symbol",
  "Symbol.asyncIterator",
  "Symbol.hasInstance",
  "Symbol.isConcatSpreadable",
  "Symbol.iterator",
  "Symbol.match",
  "Symbol.matchAll",
  "Symbol.prototype.description",
  "Symbol.replace",
  "Symbol.search",
  "Symbol.split",
  "Symbol.species",
  "Symbol.toPrimitive",
  "Symbol.toStringTag",
  "Symbol.unscopables",
  "tail-call-optimization",
  "template",
  "TypedArray",
  "TypedArray.prototype.at",
  "TypedArray.prototype.item",
  "u180e",
  "Uint8Array",
  "Uint8ClampedArray",
  "Uint16Array",
  "Uint32Array",
  "WeakMap",
  "WeakSet",
  "WeakRef",
  "well-formed-json-stringify",
];

const ignoredTests = ["built-ins/RegExp/", "language/literals/regexp/"];

const featuresToPlugins = {
  "class-fields-private-in": "privateIn",
  "class-static-block": "classStaticBlock",
  "top-level-await": "topLevelAwait",
};

const unmappedFeatures = new Set();

function* getPlugins(features) {
  if (!features) return;

  for (const f of features) {
    if (featuresToPlugins[f]) {
      yield featuresToPlugins[f];
    } else if (!ignoredFeatures.includes(f)) {
      unmappedFeatures.add(f);
    }
  }
}

const runner = new TestRunner({
  testDir: path.join(dirname, "../../../build/test262"),
  allowlist: path.join(dirname, "allowlist.txt"),
  logInterval: 500,
  shouldUpdate: process.argv.includes("--update-allowlist"),

  async *getTests() {
    const stream = new TestStream(this.testDir, {
      omitRuntime: true,
    });

    for await (const test of stream) {
      // strip test/
      const fileName = test.file.substr(5);

      if (ignoredTests.some(start => fileName.startsWith(start))) continue;

      yield {
        contents: test.contents,
        fileName,
        id: `${fileName}(${test.scenario})`,
        sourceType: test.attrs.flags.module ? "module" : "script",
        plugins: Array.from(getPlugins(test.attrs.features)),
        expectedError:
          !!test.attrs.negative &&
          (test.attrs.negative.phase === "parse" ||
            test.attrs.negative.phase === "early"),
      };
    }
  },
});

runner
  .run()
  .then(() => {
    if (unmappedFeatures.size) {
      console.log("");
      console.log(
        "The following Features are not currently mapped or ignored:"
      );
      console.log(
        Array.from(unmappedFeatures).join("\n").replace(/^/gm, "   ")
      );
    }
  })
  .catch(err => {
    console.error(err);
    process.exitCode = 1;
  });
<|endoftext|>


<commit_before>/**
 * Handling of tags input fields.
 *
 * @mixin
 * @namespace Bolt.fields.tags
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 */
(function (bolt, $) {

    /**
     * Bolt.fields.tags mixin container.
     *
     * @private
     * @type {Object}
     */
    var tags = {};

    /**
     * Bind tags field.
     *
     * @static
     * @function init
     * @memberof Bolt.fields.tags
     *
     * @param {Object} fieldset
     * @param {FieldConf} fconf
     */
    tags.init = function (fieldset, fconf) {
        var slug = fconf.slug,
            taxonomy = $(fieldset).find('select'),
            tagcloud = $(fieldset).find('div.tagcloud');

        // Load all tags.
        $.ajax({
            url: bolt.conf('paths.root') + 'async/tags/' + slug,
            dataType: 'json',
            success: function (data) {
                var results = [];

                $.each(data, function (index, item) {
                    results.push( item.slug );
                });

                taxonomy.select2({
                    width: '100%',
                    tags: results,
                    minimumInputLength: 1,
                    tokenSeparators: [',', ' ']
                });
            },
            error: function () {
                taxonomy.select2({
                    width: '100%',
                    tags: [],
                    minimumInputLength: 1,
                    tokenSeparators: [',', ' ']
                });
            }
        });

        // Popular tags.
        if (tagcloud) {
            $.ajax({
                url: bolt.conf('paths.root') + 'async/populartags/' + slug,
                dataType: 'json',
                data : {
                    limit: 40
                },
                success: function(data) {
                    if (data.length > 0) {
                        $.each(data, function(index, item){
                            tagcloud.append('' + item.slug + '');
                        });

                        tagcloud.find('a').on('click', function (e) {
                            var data;

                            e.preventDefault();
                            data = taxonomy.select2('data');
                            data.push({
                                id: $(this).text(),
                                text: $(this).text()
                            });
                            taxonomy.select2('data', data);
                        });

                        $.fn.tagcloud.defaults = {
                            size: {
                                start: 12,
                                end: 22,
                                unit: 'px'
                            },
                            color: {
                                start: '#888',
                                end: '#194770'
                            }
                        };
                        tagcloud.find('a').tagcloud();
                    }
                }
            });
        }
    };

    // Apply mixin container
    bolt.fields.tags = tags;

})(Bolt || {}, jQuery);
<commit_msg>Refactor using one function to initialize the tag selector<commit_after>/**
 * Handling of tags input fields.
 *
 * @mixin
 * @namespace Bolt.fields.tags
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 */
(function (bolt, $) {

    /**
     * Bolt.fields.tags mixin container.
     *
     * @private
     * @type {Object}
     */
    var tags = {};

    /**
     * Bind tags field.
     *
     * @static
     * @function init
     * @memberof Bolt.fields.tags
     *
     * @param {Object} fieldset
     * @param {FieldConf} fconf
     */
    tags.init = function (fieldset, fconf) {
        var slug = fconf.slug,
            taxonomy = $(fieldset).find('select'),
            tagcloud = $(fieldset).find('div.tagcloud'),
            initSelect = function (tags) {
                taxonomy.select2({
                    width: '100%',
                    tags: tags,
                    minimumInputLength: 1,
                    tokenSeparators: [',', ' ']
                });
            };

        // Load all tags.
        $.ajax({
            url: bolt.conf('paths.root') + 'async/tags/' + slug,
            dataType: 'json',
            success: function (data) {
                var results = [];

                $.each(data, function (index, item) {
                    results.push( item.slug );
                });

                initSelect(results);
            },
            error: function () {
                initSelect([]);
            }
        });

        // Popular tags.
        if (tagcloud) {
            $.ajax({
                url: bolt.conf('paths.root') + 'async/populartags/' + slug,
                dataType: 'json',
                data : {
                    limit: 40
                },
                success: function(data) {
                    if (data.length > 0) {
                        $.each(data, function(index, item){
                            tagcloud.append('' + item.slug + '');
                        });

                        tagcloud.find('a').on('click', function (e) {
                            var data;

                            e.preventDefault();
                            data = taxonomy.select2('data');
                            data.push({
                                id: $(this).text(),
                                text: $(this).text()
                            });
                            taxonomy.select2('data', data);
                        });

                        $.fn.tagcloud.defaults = {
                            size: {
                                start: 12,
                                end: 22,
                                unit: 'px'
                            },
                            color: {
                                start: '#888',
                                end: '#194770'
                            }
                        };
                        tagcloud.find('a').tagcloud();
                    }
                }
            });
        }
    };

    // Apply mixin container
    bolt.fields.tags = tags;

})(Bolt || {}, jQuery);
<|endoftext|>