<commit_before>
var Locale = require('./locale');
var KeyCombo = require('./key-combo');

function Keyboard(targetWindow, targetElement, platform, userAgent) {
  this._locale               = null;
  this._currentContext       = null;
  this._contexts             = {};
  this._listeners            = [];
  this._appliedListeners     = [];
  this._locales              = {};
  this._targetElement        = null;
  this._targetWindow         = null;
  this._targetPlatform       = '';
  this._targetUserAgent      = '';
  this._isModernBrowser      = false;
  this._targetKeyDownBinding = null;
  this._targetKeyUpBinding   = null;
  this._targetResetBinding   = null;
  this._paused               = false;

  this.setContext('global');
  this.watch(targetWindow, targetElement, platform, userAgent);
}

Keyboard.prototype.setLocale = function(localeName, localeBuilder) {
  var locale = null;
  if (typeof localeName === 'string') {

    if (localeBuilder) {
      locale = new Locale(localeName);
      localeBuilder(locale, this._targetPlatform, this._targetUserAgent);
    } else {
      locale = this._locales[localeName] || null;
    }
  } else {
    locale     = localeName;
    localeName = locale._localeName;
  }

  this._locale              = locale;
  this._locales[localeName] = locale;
  if (locale) {
    this._locale.pressedKeys = locale.pressedKeys;
  }
};

Keyboard.prototype.getLocale = function(localName) {
  localName || (localName = this._locale.localeName);
  return this._locales[localName] || null;
};

Keyboard.prototype.bind = function(keyComboStr, pressHandler, releaseHandler, preventRepeatByDefault) {
  if (keyComboStr === null || typeof keyComboStr === 'function') {
    preventRepeatByDefault = releaseHandler;
    releaseHandler         = pressHandler;
    pressHandler           = keyComboStr;
    keyComboStr            = null;
  }

  if (
    keyComboStr &&
    typeof keyComboStr === 'object' &&
    typeof keyComboStr.length === 'number'
  ) {
    for (var i = 0; i < keyComboStr.length; i += 1) {
      this.bind(keyComboStr[i], pressHandler, releaseHandler);
    }
    return;
  }

  this._listeners.push({
    keyCombo               : keyComboStr ? new KeyCombo(keyComboStr) : null,
    pressHandler           : pressHandler           || null,
    releaseHandler         : releaseHandler         || null,
    preventRepeat          : preventRepeatByDefault || false,
    preventRepeatByDefault : preventRepeatByDefault || false
  });
};
Keyboard.prototype.addListener = Keyboard.prototype.bind;
Keyboard.prototype.on          = Keyboard.prototype.bind;

Keyboard.prototype.unbind = function(keyComboStr, pressHandler, releaseHandler) {
  if (keyComboStr === null || typeof keyComboStr === 'function') {
    releaseHandler = pressHandler;
    pressHandler   = keyComboStr;
    keyComboStr = null;
  }

  if (
    keyComboStr &&
    typeof keyComboStr === 'object' &&
    typeof keyComboStr.length === 'number'
  ) {
    for (var i = 0; i < keyComboStr.length; i += 1) {
      this.unbind(keyComboStr[i], pressHandler, releaseHandler);
    }
    return;
  }

  for (var i = 0; i < this._listeners.length; i += 1) {
    var listener = this._listeners[i];

    var comboMatches          = !keyComboStr && !listener.keyCombo ||
                                listener.keyCombo.isEqual(keyComboStr);
    var pressHandlerMatches   = !pressHandler && !releaseHandler ||
                                !pressHandler && !listener.pressHandler ||
                                pressHandler === listener.pressHandler;
    var releaseHandlerMatches = !pressHandler && !releaseHandler ||
                                !releaseHandler && !listener.releaseHandler ||
                                releaseHandler === listener.releaseHandler;

    if (comboMatches && pressHandlerMatches && releaseHandlerMatches) {
      this._listeners.splice(i, 1);
      i -= 1;
    }
  }
};
Keyboard.prototype.removeListener = Keyboard.prototype.unbind;
Keyboard.prototype.off            = Keyboard.prototype.unbind;

Keyboard.prototype.setContext = function(contextName) {
  if(this._locale) { this.releaseAllKeys(); }

  if (!this._contexts[contextName]) {
    this._contexts[contextName] = [];
  }
  this._listeners      = this._contexts[contextName];
  this._currentContext = contextName;
};

Keyboard.prototype.getContext = function() {
  return this._currentContext;
};

Keyboard.prototype.withContext = function(contextName, callback) {
  var previousContextName = this.getContext();
  this.setContext(contextName);

  callback();

  this.setContext(previousContextName);
};

Keyboard.prototype.watch = function(targetWindow, targetElement, targetPlatform, targetUserAgent) {
  var _this = this;

  this.stop();

  if (!targetWindow) {
    if (!global.addEventListener && !global.attachEvent) {
      throw new Error('Cannot find global functions addEventListener or attachEvent.');
    }
    targetWindow = global;
  }

  if (typeof targetWindow.nodeType === 'number') {
    targetUserAgent = targetPlatform;
    targetPlatform  = targetElement;
    targetElement   = targetWindow;
    targetWindow    = global;
  }

  if (!targetWindow.addEventListener && !targetWindow.attachEvent) {
    throw new Error('Cannot find addEventListener or attachEvent methods on targetWindow.');
  }

  this._isModernBrowser = !!targetWindow.addEventListener;

  var userAgent = targetWindow.navigator && targetWindow.navigator.userAgent || '';
  var platform  = targetWindow.navigator && targetWindow.navigator.platform  || '';

  targetElement   && targetElement   !== null || (targetElement   = targetWindow.document);
  targetPlatform  && targetPlatform  !== null || (targetPlatform  = platform);
  targetUserAgent && targetUserAgent !== null || (targetUserAgent = userAgent);

  this._targetKeyDownBinding = function(event) {
    _this.pressKey(event.keyCode, event);
  };
  this._targetKeyUpBinding = function(event) {
    _this.releaseKey(event.keyCode, event);
  };
  this._targetResetBinding = function(event) {
    _this.releaseAllKeys(event)
  };

  this._bindEvent(targetElement, 'keydown', this._targetKeyDownBinding);
  this._bindEvent(targetElement, 'keyup',   this._targetKeyUpBinding);
  this._bindEvent(targetWindow,  'focus',   this._targetResetBinding);
  this._bindEvent(targetWindow,  'blur',    this._targetResetBinding);

  this._targetElement   = targetElement;
  this._targetWindow    = targetWindow;
  this._targetPlatform  = targetPlatform;
  this._targetUserAgent = targetUserAgent;
};

Keyboard.prototype.stop = function() {
  var _this = this;

  if (!this._targetElement || !this._targetWindow) { return; }

  this._unbindEvent(this._targetElement, 'keydown', this._targetKeyDownBinding);
  this._unbindEvent(this._targetElement, 'keyup',   this._targetKeyUpBinding);
  this._unbindEvent(this._targetWindow,  'focus',   this._targetResetBinding);
  this._unbindEvent(this._targetWindow,  'blur',    this._targetResetBinding);

  this._targetWindow  = null;
  this._targetElement = null;
};

Keyboard.prototype.pressKey = function(keyCode, event) {
  if (this._paused) { return; }
  if (!this._locale) { throw new Error('Locale not set'); }

  this._locale.pressKey(keyCode);
  this._applyBindings(event);
};

Keyboard.prototype.releaseKey = function(keyCode, event) {
  if (this._paused) { return; }
  if (!this._locale) { throw new Error('Locale not set'); }

  this._locale.releaseKey(keyCode);
  this._clearBindings(event);
};

Keyboard.prototype.releaseAllKeys = function(event) {
  if (this._paused) { return; }
  if (!this._locale) { throw new Error('Locale not set'); }

  this._locale.pressedKeys.length = 0;
  this._clearBindings(event);
};

Keyboard.prototype.pause = function() {
  if (this._paused) { return; }
  if (this._locale) { this.releaseAllKeys(); }
  this._paused = true;
};

Keyboard.prototype.resume = function() {
  this._paused = false;
};

Keyboard.prototype.reset = function() {
  this.releaseAllKeys();
  this._listeners.length = 0;
};

Keyboard.prototype._bindEvent = function(targetElement, eventName, handler) {
  return this._isModernBrowser ?
    targetElement.addEventListener(eventName, handler, false) :
    targetElement.attachEvent('on' + eventName, handler);
};

Keyboard.prototype._unbindEvent = function(targetElement, eventName, handler) {
  return this._isModernBrowser ?
    targetElement.removeEventListener(eventName, handler, false) :
    targetElement.detachEvent('on' + eventName, handler);
};

Keyboard.prototype._getGroupedListeners = function() {
  var listenerGroups   = [];
  var listenerGroupMap = [];

  var listeners = this._listeners;
  if (this._currentContext !== 'global') {
    listeners = [].concat(listeners, this._contexts.global);
  }

  listeners.sort(function(a, b) {
    return b.keyCombo.keyNames.length - a.keyCombo.keyNames.length;
  }).forEach(function(l) {
    var mapIndex = -1;
    for (var i = 0; i < listenerGroupMap.length; i += 1) {
      if (listenerGroupMap[i].isEqual(l.keyCombo)) {
        mapIndex = i;
      }
    }
    if (mapIndex === -1) {
      mapIndex = listenerGroupMap.length;
      listenerGroupMap.push(l.keyCombo);
    }
    if (!listenerGroups[mapIndex]) {
      listenerGroups[mapIndex] = [];
    }
    listenerGroups[mapIndex].push(l);
  });
  return listenerGroups;
};

Keyboard.prototype._applyBindings = function(event) {
  var preventRepeat = false;

  event || (event = {});
  event.preventRepeat = function() { preventRepeat = true; };
  event.pressedKeys   = this._locale.pressedKeys.slice(0);

  var pressedKeys    = this._locale.pressedKeys.slice(0);
  var listenerGroups = this._getGroupedListeners();

  for (var i = 0; i < listenerGroups.length; i += 1) {
    var listeners = listenerGroups[i];
    var keyCombo  = listeners[0].keyCombo;

    if (keyCombo === null || keyCombo.check(pressedKeys)) {
      for (var j = 0; j < listeners.length; j += 1) {
        var listener = listeners[j];

        if (keyCombo === null) {
          listener = {
            keyCombo               : new KeyCombo(pressedKeys.join('+')),
            pressHandler           : listener.pressHandler,
            releaseHandler         : listener.releaseHandler,
            preventRepeat          : listener.preventRepeat,
            preventRepeatByDefault : listener.preventRepeatByDefault
          };
        }

        if (listener.pressHandler && !listener.preventRepeat) {
          listener.pressHandler.call(this, event);
          if (preventRepeat) {
            listener.preventRepeat = preventRepeat;
            preventRepeat          = false;
          }
        }

        if (listener.releaseHandler && this._appliedListeners.indexOf(listener) === -1) {
          this._appliedListeners.push(listener);
        }
      }

      if (keyCombo) {
        for (var j = 0; j < keyCombo.keyNames.length; j += 1) {
          var index = pressedKeys.indexOf(keyCombo.keyNames[j]);
          if (index !== -1) {
            pressedKeys.splice(index, 1);
            j -= 1;
          }
        }
      }
    }
  }
};

Keyboard.prototype._clearBindings = function(event) {
  event || (event = {});

  for (var i = 0; i < this._appliedListeners.length; i += 1) {
    var listener = this._appliedListeners[i];
    var keyCombo = listener.keyCombo;
    if (keyCombo === null || !keyCombo.check(this._locale.pressedKeys)) {
      listener.preventRepeat = listener.preventRepeatByDefault;
      listener.releaseHandler.call(this, event);
      this._appliedListeners.splice(i, 1);
      i -= 1;
    }
  }
};

module.exports = Keyboard;
<commit_msg>fixed empty binding issue<commit_after>
var Locale = require('./locale');
var KeyCombo = require('./key-combo');

function Keyboard(targetWindow, targetElement, platform, userAgent) {
  this._locale               = null;
  this._currentContext       = null;
  this._contexts             = {};
  this._listeners            = [];
  this._appliedListeners     = [];
  this._locales              = {};
  this._targetElement        = null;
  this._targetWindow         = null;
  this._targetPlatform       = '';
  this._targetUserAgent      = '';
  this._isModernBrowser      = false;
  this._targetKeyDownBinding = null;
  this._targetKeyUpBinding   = null;
  this._targetResetBinding   = null;
  this._paused               = false;

  this.setContext('global');
  this.watch(targetWindow, targetElement, platform, userAgent);
}

Keyboard.prototype.setLocale = function(localeName, localeBuilder) {
  var locale = null;
  if (typeof localeName === 'string') {

    if (localeBuilder) {
      locale = new Locale(localeName);
      localeBuilder(locale, this._targetPlatform, this._targetUserAgent);
    } else {
      locale = this._locales[localeName] || null;
    }
  } else {
    locale     = localeName;
    localeName = locale._localeName;
  }

  this._locale              = locale;
  this._locales[localeName] = locale;
  if (locale) {
    this._locale.pressedKeys = locale.pressedKeys;
  }
};

Keyboard.prototype.getLocale = function(localName) {
  localName || (localName = this._locale.localeName);
  return this._locales[localName] || null;
};

Keyboard.prototype.bind = function(keyComboStr, pressHandler, releaseHandler, preventRepeatByDefault) {
  if (keyComboStr === null || typeof keyComboStr === 'function') {
    preventRepeatByDefault = releaseHandler;
    releaseHandler         = pressHandler;
    pressHandler           = keyComboStr;
    keyComboStr            = null;
  }

  if (
    keyComboStr &&
    typeof keyComboStr === 'object' &&
    typeof keyComboStr.length === 'number'
  ) {
    for (var i = 0; i < keyComboStr.length; i += 1) {
      this.bind(keyComboStr[i], pressHandler, releaseHandler);
    }
    return;
  }

  this._listeners.push({
    keyCombo               : keyComboStr ? new KeyCombo(keyComboStr) : null,
    pressHandler           : pressHandler           || null,
    releaseHandler         : releaseHandler         || null,
    preventRepeat          : preventRepeatByDefault || false,
    preventRepeatByDefault : preventRepeatByDefault || false
  });
};
Keyboard.prototype.addListener = Keyboard.prototype.bind;
Keyboard.prototype.on          = Keyboard.prototype.bind;

Keyboard.prototype.unbind = function(keyComboStr, pressHandler, releaseHandler) {
  if (keyComboStr === null || typeof keyComboStr === 'function') {
    releaseHandler = pressHandler;
    pressHandler   = keyComboStr;
    keyComboStr = null;
  }

  if (
    keyComboStr &&
    typeof keyComboStr === 'object' &&
    typeof keyComboStr.length === 'number'
  ) {
    for (var i = 0; i < keyComboStr.length; i += 1) {
      this.unbind(keyComboStr[i], pressHandler, releaseHandler);
    }
    return;
  }

  for (var i = 0; i < this._listeners.length; i += 1) {
    var listener = this._listeners[i];

    var comboMatches          = !keyComboStr && !listener.keyCombo ||
                                listener.keyCombo && listener.keyCombo.isEqual(keyComboStr);
    var pressHandlerMatches   = !pressHandler && !releaseHandler ||
                                !pressHandler && !listener.pressHandler ||
                                pressHandler === listener.pressHandler;
    var releaseHandlerMatches = !pressHandler && !releaseHandler ||
                                !releaseHandler && !listener.releaseHandler ||
                                releaseHandler === listener.releaseHandler;

    if (comboMatches && pressHandlerMatches && releaseHandlerMatches) {
      this._listeners.splice(i, 1);
      i -= 1;
    }
  }
};
Keyboard.prototype.removeListener = Keyboard.prototype.unbind;
Keyboard.prototype.off            = Keyboard.prototype.unbind;

Keyboard.prototype.setContext = function(contextName) {
  if(this._locale) { this.releaseAllKeys(); }

  if (!this._contexts[contextName]) {
    this._contexts[contextName] = [];
  }
  this._listeners      = this._contexts[contextName];
  this._currentContext = contextName;
};

Keyboard.prototype.getContext = function() {
  return this._currentContext;
};

Keyboard.prototype.withContext = function(contextName, callback) {
  var previousContextName = this.getContext();
  this.setContext(contextName);

  callback();

  this.setContext(previousContextName);
};

Keyboard.prototype.watch = function(targetWindow, targetElement, targetPlatform, targetUserAgent) {
  var _this = this;

  this.stop();

  if (!targetWindow) {
    if (!global.addEventListener && !global.attachEvent) {
      throw new Error('Cannot find global functions addEventListener or attachEvent.');
    }
    targetWindow = global;
  }

  if (typeof targetWindow.nodeType === 'number') {
    targetUserAgent = targetPlatform;
    targetPlatform  = targetElement;
    targetElement   = targetWindow;
    targetWindow    = global;
  }

  if (!targetWindow.addEventListener && !targetWindow.attachEvent) {
    throw new Error('Cannot find addEventListener or attachEvent methods on targetWindow.');
  }

  this._isModernBrowser = !!targetWindow.addEventListener;

  var userAgent = targetWindow.navigator && targetWindow.navigator.userAgent || '';
  var platform  = targetWindow.navigator && targetWindow.navigator.platform  || '';

  targetElement   && targetElement   !== null || (targetElement   = targetWindow.document);
  targetPlatform  && targetPlatform  !== null || (targetPlatform  = platform);
  targetUserAgent && targetUserAgent !== null || (targetUserAgent = userAgent);

  this._targetKeyDownBinding = function(event) {
    _this.pressKey(event.keyCode, event);
  };
  this._targetKeyUpBinding = function(event) {
    _this.releaseKey(event.keyCode, event);
  };
  this._targetResetBinding = function(event) {
    _this.releaseAllKeys(event)
  };

  this._bindEvent(targetElement, 'keydown', this._targetKeyDownBinding);
  this._bindEvent(targetElement, 'keyup',   this._targetKeyUpBinding);
  this._bindEvent(targetWindow,  'focus',   this._targetResetBinding);
  this._bindEvent(targetWindow,  'blur',    this._targetResetBinding);

  this._targetElement   = targetElement;
  this._targetWindow    = targetWindow;
  this._targetPlatform  = targetPlatform;
  this._targetUserAgent = targetUserAgent;
};

Keyboard.prototype.stop = function() {
  var _this = this;

  if (!this._targetElement || !this._targetWindow) { return; }

  this._unbindEvent(this._targetElement, 'keydown', this._targetKeyDownBinding);
  this._unbindEvent(this._targetElement, 'keyup',   this._targetKeyUpBinding);
  this._unbindEvent(this._targetWindow,  'focus',   this._targetResetBinding);
  this._unbindEvent(this._targetWindow,  'blur',    this._targetResetBinding);

  this._targetWindow  = null;
  this._targetElement = null;
};

Keyboard.prototype.pressKey = function(keyCode, event) {
  if (this._paused) { return; }
  if (!this._locale) { throw new Error('Locale not set'); }

  this._locale.pressKey(keyCode);
  this._applyBindings(event);
};

Keyboard.prototype.releaseKey = function(keyCode, event) {
  if (this._paused) { return; }
  if (!this._locale) { throw new Error('Locale not set'); }

  this._locale.releaseKey(keyCode);
  this._clearBindings(event);
};

Keyboard.prototype.releaseAllKeys = function(event) {
  if (this._paused) { return; }
  if (!this._locale) { throw new Error('Locale not set'); }

  this._locale.pressedKeys.length = 0;
  this._clearBindings(event);
};

Keyboard.prototype.pause = function() {
  if (this._paused) { return; }
  if (this._locale) { this.releaseAllKeys(); }
  this._paused = true;
};

Keyboard.prototype.resume = function() {
  this._paused = false;
};

Keyboard.prototype.reset = function() {
  this.releaseAllKeys();
  this._listeners.length = 0;
};

Keyboard.prototype._bindEvent = function(targetElement, eventName, handler) {
  return this._isModernBrowser ?
    targetElement.addEventListener(eventName, handler, false) :
    targetElement.attachEvent('on' + eventName, handler);
};

Keyboard.prototype._unbindEvent = function(targetElement, eventName, handler) {
  return this._isModernBrowser ?
    targetElement.removeEventListener(eventName, handler, false) :
    targetElement.detachEvent('on' + eventName, handler);
};

Keyboard.prototype._getGroupedListeners = function() {
  var listenerGroups   = [];
  var listenerGroupMap = [];

  var listeners = this._listeners;
  if (this._currentContext !== 'global') {
    listeners = [].concat(listeners, this._contexts.global);
  }

  listeners.sort(function(a, b) {
    return (b.keyCombo ? b.keyCombo.keyNames.length : 0) - (a.keyCombo ? a.keyCombo.keyNames.length : 0);
  }).forEach(function(l) {
    var mapIndex = -1;
    for (var i = 0; i < listenerGroupMap.length; i += 1) {
      if (listenerGroupMap[i] === null && l.keyCombo === null ||
          listenerGroupMap[i] !== null && listenerGroupMap[i].isEqual(l.keyCombo)) {
        mapIndex = i;
      }
    }
    if (mapIndex === -1) {
      mapIndex = listenerGroupMap.length;
      listenerGroupMap.push(l.keyCombo);
    }
    if (!listenerGroups[mapIndex]) {
      listenerGroups[mapIndex] = [];
    }
    listenerGroups[mapIndex].push(l);
  });
  return listenerGroups;
};

Keyboard.prototype._applyBindings = function(event) {
  var preventRepeat = false;

  event || (event = {});
  event.preventRepeat = function() { preventRepeat = true; };
  event.pressedKeys   = this._locale.pressedKeys.slice(0);

  var pressedKeys    = this._locale.pressedKeys.slice(0);
  var listenerGroups = this._getGroupedListeners();

  for (var i = 0; i < listenerGroups.length; i += 1) {
    var listeners = listenerGroups[i];
    var keyCombo  = listeners[0].keyCombo;

    if (keyCombo === null || keyCombo.check(pressedKeys)) {
      for (var j = 0; j < listeners.length; j += 1) {
        var listener = listeners[j];

        if (keyCombo === null) {
          listener = {
            keyCombo               : new KeyCombo(pressedKeys.join('+')),
            pressHandler           : listener.pressHandler,
            releaseHandler         : listener.releaseHandler,
            preventRepeat          : listener.preventRepeat,
            preventRepeatByDefault : listener.preventRepeatByDefault
          };
        }

        if (listener.pressHandler && !listener.preventRepeat) {
          listener.pressHandler.call(this, event);
          if (preventRepeat) {
            listener.preventRepeat = preventRepeat;
            preventRepeat          = false;
          }
        }

        if (listener.releaseHandler && this._appliedListeners.indexOf(listener) === -1) {
          this._appliedListeners.push(listener);
        }
      }

      if (keyCombo) {
        for (var j = 0; j < keyCombo.keyNames.length; j += 1) {
          var index = pressedKeys.indexOf(keyCombo.keyNames[j]);
          if (index !== -1) {
            pressedKeys.splice(index, 1);
            j -= 1;
          }
        }
      }
    }
  }
};

Keyboard.prototype._clearBindings = function(event) {
  event || (event = {});

  for (var i = 0; i < this._appliedListeners.length; i += 1) {
    var listener = this._appliedListeners[i];
    var keyCombo = listener.keyCombo;
    if (keyCombo === null || !keyCombo.check(this._locale.pressedKeys)) {
      listener.preventRepeat = listener.preventRepeatByDefault;
      listener.releaseHandler.call(this, event);
      this._appliedListeners.splice(i, 1);
      i -= 1;
    }
  }
};

module.exports = Keyboard;
<|endoftext|>


<commit_before>define(function (require) {

  var AppDispatcher = require('dispatchers/AppDispatcher'),
    ProjectConstants = require('constants/ProjectConstants'),
    ProjectImageConstants = require('constants/ProjectImageConstants'),
    ProjectImage = require('models/ProjectImage'),
    Utils = require('./Utils'),
    stores = require('stores');

  return {

    // -------------------------
    // Add/Remove Project Image
    // -------------------------

    addImageToProject: function (params, options) {
      if (!params.project) throw new Error("Missing project");
      if (!params.image && !params.image.id) throw new Error("Missing image");

      var project = params.project,
        image = params.image,
        projectImage = new ProjectImage(),
        data = {
          project: project.id,
          image: image.id
        };

      projectImage.save(null, {attrs: data}).done(function () {
        Utils.dispatch(ProjectImageConstants.ADD_PROJECT_IMAGE, {projectImage: projectImage}, options);
      })
    },

    removeImageFromProject: function (params, options) {
      if (!params.project) throw new Error("Missing project");
      if (!params.image) throw new Error("Missing image");

      var project = params.project,
        image = params.image,
        //FIXME: the line below has 0 models (When the value should be >1)
        projectImage = stores.ProjectImageStore.findOne({
          'project.id': project.id,
          'image.id': image.id
        });

      projectImage.destroy().done(function () {
        Utils.dispatch(ProjectImageConstants.REMOVE_PROJECT_IMAGE, {projectImage: projectImage}, options);
      });
    }

  };

});
<commit_msg>Missing block of code in ProjectImageStore fixes the 'Cant remove an image' Problem<commit_after>define(function (require) {

  var AppDispatcher = require('dispatchers/AppDispatcher'),
    ProjectConstants = require('constants/ProjectConstants'),
    ProjectImageConstants = require('constants/ProjectImageConstants'),
    ProjectImage = require('models/ProjectImage'),
    Utils = require('./Utils'),
    stores = require('stores');

  return {

    // -------------------------
    // Add/Remove Project Image
    // -------------------------

    addImageToProject: function (params, options) {
      if (!params.project) throw new Error("Missing project");
      if (!params.image && !params.image.id) throw new Error("Missing image");

      var project = params.project,
        image = params.image,
        projectImage = new ProjectImage(),
        data = {
          project: project.id,
          image: image.id
        };

      projectImage.save(null, {attrs: data}).done(function () {
        Utils.dispatch(ProjectImageConstants.ADD_PROJECT_IMAGE, {projectImage: projectImage}, options);
      })
    },

    removeImageFromProject: function (params, options) {
      if (!params.project) throw new Error("Missing project");
      if (!params.image) throw new Error("Missing image");

      var project = params.project,
        image = params.image,
        projectImage = stores.ProjectImageStore.findOne({
          'project.id': project.id,
          'image.id': image.id
        });

      projectImage.destroy().done(function () {
        Utils.dispatch(ProjectImageConstants.REMOVE_PROJECT_IMAGE, {projectImage: projectImage}, options);
      });
    }

  };

});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://jhipster.github.io/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const util = require('util');
const fs = require('fs');
const generator = require('yeoman-generator');
const exec = require('child_process').exec;
const chalk = require('chalk');
const _ = require('lodash');
const glob = require('glob');
const BaseGenerator = require('../generator-base');

const constants = require('../generator-constants');

const HerokuGenerator = generator.extend({});

util.inherits(HerokuGenerator, BaseGenerator);

module.exports = HerokuGenerator.extend({
    constructor: function (...args) { // eslint-disable-line object-shorthand
        generator.apply(this, args);
    },
    initializing() {
        this.log(chalk.bold('Heroku configuration is starting'));
        this.env.options.appPath = this.config.get('appPath') || constants.CLIENT_MAIN_SRC_DIR;
        this.baseName = this.config.get('baseName');
        this.packageName = this.config.get('packageName');
        this.packageFolder = this.config.get('packageFolder');
        this.hibernateCache = this.config.get('hibernateCache');
        this.databaseType = this.config.get('databaseType');
        this.prodDatabaseType = this.config.get('prodDatabaseType');
        this.angularAppName = this.getAngularAppName();
        this.buildTool = this.config.get('buildTool');
        this.applicationType = this.config.get('applicationType');
        this.herokuAppName = this.config.get('herokuAppName');
        this.dynoSize = 'Free';
    },

    prompting() {
        const done = this.async();

        if (this.herokuAppName) {
            exec('heroku apps:info --json', (err, stdout) => {
                if (err) {
                    this.config.set('herokuAppName', null);
                    this.abort = true;
                    this.log.error(`Could not find app: ${chalk.cyan(this.herokuAppName)}`);
                    this.log.error('Run the generator again to create a new app.');
                } else {
                    const json = JSON.parse(stdout);
                    this.herokuAppName = json.app.name;
                    if (json.dynos.length > 0) {
                        this.dynoSize = json.dynos[0].size;
                    }
                    this.log(`Deploying as existing app: ${chalk.bold(this.herokuAppName)}`);
                    this.herokuAppExists = true;
                    this.config.set('herokuAppName', this.herokuAppName);
                }
                done();
            });
        } else {
            const prompts = [
                {
                    type: 'input',
                    name: 'herokuAppName',
                    message: 'Name to deploy as:',
                    default: this.baseName
                },
                {
                    type: 'list',
                    name: 'herokuRegion',
                    message: 'On which region do you want to deploy ?',
                    choices: ['us', 'eu'],
                    default: 0
                }];

            this.prompt(prompts).then((props) => {
                this.herokuAppName = _.kebabCase(props.herokuAppName);
                this.herokuRegion = props.herokuRegion;
                this.herokuAppExists = false;
                done();
            });
        }
    },
    configuring: {
        checkInstallation() {
            if (this.abort) return;
            const done = this.async();

            exec('heroku --version', (err) => {
                if (err) {
                    this.log.error('You don\'t have the Heroku Toolbelt installed. ' +
                        'Download it from https://toolbelt.heroku.com/');
                    this.abort = true;
                }
                done();
            });
        }
    },

    default: {
        insight() {
            const insight = this.insight();
            insight.trackWithEvent('generator', 'heroku');
        },

        gitInit() {
            if (this.abort) return;
            const done = this.async();

            try {
                fs.lstatSync('.git');
                this.log(chalk.bold('\nUsing existing Git repository'));
                done();
            } catch (e) {
                // An exception is thrown if the folder doesn't exist
                this.log(chalk.bold('\nInitializing Git repository'));
                const child = exec('git init', {}, (err, stdout, stderr) => {
                    done();
                });
                child.stdout.on('data', (data) => {
                    this.log(data.toString());
                });
            }
        },

        installHerokuDeployPlugin() {
            if (this.abort) return;
            const done = this.async();
            this.log(chalk.bold('\nInstalling Heroku CLI deployment plugin'));
            const child = exec('heroku plugins:install heroku-cli-deploy', (err, stdout) => {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            });

            child.stdout.on('data', (data) => {
                this.log(data.toString());
            });
        },

        herokuCreate() {
            if (this.abort || this.herokuAppExists) return;
            const done = this.async();

            const regionParams = (this.herokuRegion !== 'us') ? ` --region ${this.herokuRegion}` : '';

            this.log(chalk.bold('\nCreating Heroku application and setting up node environment'));
            let herokuCreateCmd = `heroku create ${this.herokuAppName}${regionParams}`;
            this.log(herokuCreateCmd);

            const child = exec(herokuCreateCmd, {}, (err, stdout, stderr) => {
                if (err) {
                    if (stderr.indexOf('Name is already taken') > -1) {
                        const prompts = [
                            {
                                type: 'list',
                                name: 'herokuForceName',
                                message: `The Heroku app "${chalk.cyan(this.herokuAppName)}" already exists! Use it anyways?`,
                                choices: [{
                                    value: 'Yes',
                                    name: 'Yes, I have access to it'
                                }, {
                                    value: 'No',
                                    name: 'No, generate a random name'
                                }],
                                default: 0
                            }];

                        this.log('');
                        this.prompt(prompts).then((props) => {
                            let getHerokuAppName = def => def;
                            if (props.herokuForceName === 'Yes') {
                                herokuCreateCmd = `heroku git:remote --app ${this.herokuAppName}`;
                            } else {
                                herokuCreateCmd = `heroku create ${regionParams}`;

                                // Extract from "Created random-app-name-1234... done"
                                getHerokuAppName = (def, stdout) => stdout.substring(stdout.indexOf('https://') + 8, stdout.indexOf('.herokuapp'));
                            }
                            exec(herokuCreateCmd, {}, (err, stdout, stderr) => {
                                if (err) {
                                    this.abort = true;
                                    this.log.error(err);
                                } else {
                                    this.herokuAppName = getHerokuAppName(this.herokuAppName, stdout);
                                    this.log(stdout.trim());
                                }
                                this.config.set('herokuAppName', this.herokuAppName);
                                done();
                            });
                        });
                    } else {
                        this.abort = true;
                        this.log.error(err);
                        done();
                    }
                } else {
                    done();
                }
            });

            child.stdout.on('data', (data) => {
                const output = data.toString();
                if (data.search('Heroku credentials') >= 0) {
                    this.abort = true;
                    this.log.error('Error: Not authenticated. Run \'heroku login\' to login to your heroku account and try again.');
                    done();
                } else {
                    this.log(output.trim());
                }
            });
        },

        herokuAddonsCreate() {
            if (this.abort) return;
            const done = this.async();

            let dbAddOn = '';
            if (this.prodDatabaseType === 'postgresql') {
                dbAddOn = 'heroku-postgresql --as DATABASE';
            } else if (this.prodDatabaseType === 'mysql') {
                dbAddOn = 'jawsdb:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mariadb') {
                dbAddOn = 'jawsdb-maria:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mongodb') {
                dbAddOn = 'mongolab:sandbox --as MONGODB';
            } else {
                return;
            }

            this.log(chalk.bold('\nProvisioning addons'));
            exec(`heroku addons:create ${dbAddOn} --app ${this.herokuAppName}`, {}, (err, stdout, stderr) => {
                if (err) {
                    this.log('No new addons created');
                } else {
                    this.log(`Created ${dbAddOn}`);
                }
                done();
            });
        },

        configureJHipsterRegistry() {
            if (this.abort || this.herokuAppExists) return;
            const done = this.async();

            if (this.applicationType === 'microservice' || this.applicationType === 'gateway') {
                const prompts = [
                    {
                        type: 'input',
                        name: 'herokuJHipsterRegistry',
                        message: 'What is the URL of your JHipster Registry?'
                    }];

                this.log('');
                this.prompt(prompts).then((props) => {
                    const configSetCmd = `heroku config:set JHIPSTER_REGISTRY_URL=${props.herokuJHipsterRegistry} --app ${this.herokuAppName}`;
                    const child = exec(configSetCmd, {}, (err, stdout, stderr) => {
                        if (err) {
                            this.abort = true;
                            this.log.error(err);
                        }
                        done();
                    });

                    child.stdout.on('data', (data) => {
                        this.log(data.toString());
                    });
                });
            } else {
                this.conflicter.resolve((err) => {
                    done();
                });
            }
        },

        copyHerokuFiles() {
            if (this.abort) return;

            const done = this.async();
            this.log(chalk.bold('\nCreating Heroku deployment files'));

            this.template('_bootstrap-heroku.yml', `${constants.SERVER_MAIN_RES_DIR}/config/bootstrap-heroku.yml`);
            this.template('_application-heroku.yml', `${constants.SERVER_MAIN_RES_DIR}/config/application-heroku.yml`);
            this.template('_Procfile', 'Procfile');
            if (this.buildTool === 'gradle') {
                this.template('_heroku.gradle', 'gradle/heroku.gradle');
            }

            this.conflicter.resolve((err) => {
                done();
            });
        },

        addHerokuBuildPlugin() {
            if (this.buildTool !== 'gradle') return;
            this.addGradlePlugin('gradle.plugin.com.heroku.sdk', 'heroku-gradle', '0.2.0');
            this.applyFromGradleScript('gradle/heroku');
        }
    },

    end: {
        productionBuild() {
            if (this.abort) return;
            const done = this.async();
            this.log(chalk.bold('\nBuilding application'));

            const child = this.buildApplication(this.buildTool, 'prod', (err) => {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            });

            this.buildCmd = child.buildCmd;

            child.stdout.on('data', (data) => {
                const line = data.toString().trim();
                if (line.length !== 0) this.log(line);
            });
        },

        productionDeploy() {
            if (this.abort) return;
            const done = this.async();
            this.log(chalk.bold('\nDeploying application'));

            let warFileWildcard = 'target/*.war';
            if (this.buildTool === 'gradle') {
                warFileWildcard = 'build/libs/*.war';
            }

            const files = glob.sync(warFileWildcard, {});
            const warFile = files[0];
            const herokuDeployCommand = `heroku deploy:jar ${warFile} --app ${this.herokuAppName}`;

            this.log(chalk.bold(`\nUploading your application code.\nThis may take ${chalk.cyan('several minutes')} depending on your connection speed...`));
            const child = exec(herokuDeployCommand, (err, stdout) => {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                this.log(chalk.green(`\nYour app should now be live. To view it run\n\t${chalk.bold('heroku open')}`));
                this.log(chalk.yellow(`And you can view the logs with this command\n\t${chalk.bold('heroku logs --tail')}`));
                this.log(chalk.yellow(`After application modification, redeploy it with\n\t${chalk.bold('jhipster heroku')}`));
                done();
            });

            child.stdout.on('data', (data) => {
                const line = data.toString().trimRight();
                if (line.trim().length !== 0) this.log(line);
            });
        }
    }
});
<commit_msg>modify interaction with Heroku CLI for plugin install and new account<commit_after>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://jhipster.github.io/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const util = require('util');
const fs = require('fs');
const generator = require('yeoman-generator');
const exec = require('child_process').exec;
const chalk = require('chalk');
const _ = require('lodash');
const glob = require('glob');
const BaseGenerator = require('../generator-base');

const constants = require('../generator-constants');

const HerokuGenerator = generator.extend({});

util.inherits(HerokuGenerator, BaseGenerator);

module.exports = HerokuGenerator.extend({
    constructor: function (...args) { // eslint-disable-line object-shorthand
        generator.apply(this, args);
    },
    initializing() {
        this.log(chalk.bold('Heroku configuration is starting'));
        this.env.options.appPath = this.config.get('appPath') || constants.CLIENT_MAIN_SRC_DIR;
        this.baseName = this.config.get('baseName');
        this.packageName = this.config.get('packageName');
        this.packageFolder = this.config.get('packageFolder');
        this.hibernateCache = this.config.get('hibernateCache');
        this.databaseType = this.config.get('databaseType');
        this.prodDatabaseType = this.config.get('prodDatabaseType');
        this.angularAppName = this.getAngularAppName();
        this.buildTool = this.config.get('buildTool');
        this.applicationType = this.config.get('applicationType');
        this.herokuAppName = this.config.get('herokuAppName');
        this.dynoSize = 'Free';
    },

    prompting() {
        const done = this.async();

        if (this.herokuAppName) {
            exec('heroku apps:info --json', (err, stdout) => {
                if (err) {
                    this.config.set('herokuAppName', null);
                    this.abort = true;
                    this.log.error(`Could not find app: ${chalk.cyan(this.herokuAppName)}`);
                    this.log.error('Run the generator again to create a new app.');
                } else {
                    const json = JSON.parse(stdout);
                    this.herokuAppName = json.app.name;
                    if (json.dynos.length > 0) {
                        this.dynoSize = json.dynos[0].size;
                    }
                    this.log(`Deploying as existing app: ${chalk.bold(this.herokuAppName)}`);
                    this.herokuAppExists = true;
                    this.config.set('herokuAppName', this.herokuAppName);
                }
                done();
            });
        } else {
            const prompts = [
                {
                    type: 'input',
                    name: 'herokuAppName',
                    message: 'Name to deploy as:',
                    default: this.baseName
                },
                {
                    type: 'list',
                    name: 'herokuRegion',
                    message: 'On which region do you want to deploy ?',
                    choices: ['us', 'eu'],
                    default: 0
                }];

            this.prompt(prompts).then((props) => {
                this.herokuAppName = _.kebabCase(props.herokuAppName);
                this.herokuRegion = props.herokuRegion;
                this.herokuAppExists = false;
                done();
            });
        }
    },
    configuring: {
        checkInstallation() {
            if (this.abort) return;
            const done = this.async();

            exec('heroku --version', (err) => {
                if (err) {
                    this.log.error('You don\'t have the Heroku Toolbelt installed. ' +
                        'Download it from https://toolbelt.heroku.com/');
                    this.abort = true;
                }
                done();
            });
        }
    },

    default: {
        insight() {
            const insight = this.insight();
            insight.trackWithEvent('generator', 'heroku');
        },

        gitInit() {
            if (this.abort) return;
            const done = this.async();

            try {
                fs.lstatSync('.git');
                this.log(chalk.bold('\nUsing existing Git repository'));
                done();
            } catch (e) {
                // An exception is thrown if the folder doesn't exist
                this.log(chalk.bold('\nInitializing Git repository'));
                const child = exec('git init', {}, (err, stdout, stderr) => {
                    done();
                });
                child.stdout.on('data', (data) => {
                    this.log(data.toString());
                });
            }
        },

        installHerokuDeployPlugin() {
            if (this.abort) return;
            const done = this.async();
            const cliPlugin = 'heroku-cli-deploy';

            exec('heroku plugins', (err, stdout) => {
                if (stdout.indexOf(cliPlugin) > -1) {
                    this.log('\nHeroku CLI deployment plugin already installed');
                    done();
                } else {
                    this.log(chalk.bold('\nInstalling Heroku CLI deployment plugin'));
                    const child = exec(`heroku plugins:install ${cliPlugin}`, (err, stdout) => {
                        if (err) {
                            this.abort = true;
                            this.log.error(err);
                        }

                        done();
                    });

                    child.stdout.on('data', (data) => {
                        this.log(data.toString());
                    });
                }
            });
        },

        herokuCreate() {
            if (this.abort || this.herokuAppExists) return;
            const done = this.async();

            const regionParams = (this.herokuRegion !== 'us') ? ` --region ${this.herokuRegion}` : '';

            this.log(chalk.bold('\nCreating Heroku application and setting up node environment'));
            let herokuCreateCmd = `heroku create ${this.herokuAppName}${regionParams}`;
            this.log(herokuCreateCmd);

            const child = exec(herokuCreateCmd, {}, (err, stdout, stderr) => {
                if (err) {
                    if (stderr.indexOf('Name is already taken') > -1) {
                        const prompts = [
                            {
                                type: 'list',
                                name: 'herokuForceName',
                                message: `The Heroku app "${chalk.cyan(this.herokuAppName)}" already exists! Use it anyways?`,
                                choices: [{
                                    value: 'Yes',
                                    name: 'Yes, I have access to it'
                                }, {
                                    value: 'No',
                                    name: 'No, generate a random name'
                                }],
                                default: 0
                            }];

                        this.log('');
                        this.prompt(prompts).then((props) => {
                            let getHerokuAppName = def => def;
                            if (props.herokuForceName === 'Yes') {
                                herokuCreateCmd = `heroku git:remote --app ${this.herokuAppName}`;
                            } else {
                                herokuCreateCmd = `heroku create ${regionParams}`;

                                // Extract from "Created random-app-name-1234... done"
                                getHerokuAppName = (def, stdout) => stdout.substring(stdout.indexOf('https://') + 8, stdout.indexOf('.herokuapp'));
                            }
                            exec(herokuCreateCmd, {}, (err, stdout, stderr) => {
                                if (err) {
                                    this.abort = true;
                                    this.log.error(err);
                                } else {
                                    this.herokuAppName = getHerokuAppName(this.herokuAppName, stdout);
                                    this.log(stdout.trim());
                                }
                                this.config.set('herokuAppName', this.herokuAppName);
                                done();
                            });
                        });
                    } else {
                        this.abort = true;
                        this.log.error(err);
                        done();
                    }
                } else {
                    done();
                }
            });

            child.stdout.on('data', (data) => {
                const output = data.toString();
                if (data.search('Heroku credentials') >= 0) {
                    this.abort = true;
                    this.log.error('Error: Not authenticated. Run \'heroku login\' to login to your heroku account and try again.');
                    done();
                } else {
                    this.log(output.trim());
                }
            });
        },

        herokuAddonsCreate() {
            if (this.abort) return;
            const done = this.async();

            let dbAddOn = '';
            if (this.prodDatabaseType === 'postgresql') {
                dbAddOn = 'heroku-postgresql --as DATABASE';
            } else if (this.prodDatabaseType === 'mysql') {
                dbAddOn = 'jawsdb:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mariadb') {
                dbAddOn = 'jawsdb-maria:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mongodb') {
                dbAddOn = 'mongolab:sandbox --as MONGODB';
            } else {
                return;
            }

            this.log(chalk.bold('\nProvisioning addons'));
            exec(`heroku addons:create ${dbAddOn} --app ${this.herokuAppName}`, {}, (err, stdout, stderr) => {
                if (err) {
                    const verifyAccountUrl = 'https://heroku.com/verify';
                    if (err.indexOf(verifyAccountUrl) > -1) {
                        this.abort = true;
                        this.log.error(`Account must be verified to use addons. Please go to: ${verifyAccountUrl}`);
                        this.log.error(err);
                    } else {
                        this.log('No new addons created');
                    }
                } else {
                    this.log(`Created ${dbAddOn}`);
                }
                done();
            });
        },

        configureJHipsterRegistry() {
            if (this.abort || this.herokuAppExists) return;
            const done = this.async();

            if (this.applicationType === 'microservice' || this.applicationType === 'gateway') {
                const prompts = [
                    {
                        type: 'input',
                        name: 'herokuJHipsterRegistry',
                        message: 'What is the URL of your JHipster Registry?'
                    }];

                this.log('');
                this.prompt(prompts).then((props) => {
                    const configSetCmd = `heroku config:set JHIPSTER_REGISTRY_URL=${props.herokuJHipsterRegistry} --app ${this.herokuAppName}`;
                    const child = exec(configSetCmd, {}, (err, stdout, stderr) => {
                        if (err) {
                            this.abort = true;
                            this.log.error(err);
                        }
                        done();
                    });

                    child.stdout.on('data', (data) => {
                        this.log(data.toString());
                    });
                });
            } else {
                this.conflicter.resolve((err) => {
                    done();
                });
            }
        },

        copyHerokuFiles() {
            if (this.abort) return;

            const done = this.async();
            this.log(chalk.bold('\nCreating Heroku deployment files'));

            this.template('_bootstrap-heroku.yml', `${constants.SERVER_MAIN_RES_DIR}/config/bootstrap-heroku.yml`);
            this.template('_application-heroku.yml', `${constants.SERVER_MAIN_RES_DIR}/config/application-heroku.yml`);
            this.template('_Procfile', 'Procfile');
            if (this.buildTool === 'gradle') {
                this.template('_heroku.gradle', 'gradle/heroku.gradle');
            }

            this.conflicter.resolve((err) => {
                done();
            });
        },

        addHerokuBuildPlugin() {
            if (this.buildTool !== 'gradle') return;
            this.addGradlePlugin('gradle.plugin.com.heroku.sdk', 'heroku-gradle', '0.2.0');
            this.applyFromGradleScript('gradle/heroku');
        }
    },

    end: {
        productionBuild() {
            if (this.abort) return;
            const done = this.async();
            this.log(chalk.bold('\nBuilding application'));

            const child = this.buildApplication(this.buildTool, 'prod', (err) => {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            });

            this.buildCmd = child.buildCmd;

            child.stdout.on('data', (data) => {
                const line = data.toString().trim();
                if (line.length !== 0) this.log(line);
            });
        },

        productionDeploy() {
            if (this.abort) return;
            const done = this.async();
            this.log(chalk.bold('\nDeploying application'));

            let warFileWildcard = 'target/*.war';
            if (this.buildTool === 'gradle') {
                warFileWildcard = 'build/libs/*.war';
            }

            const files = glob.sync(warFileWildcard, {});
            const warFile = files[0];
            const herokuDeployCommand = `heroku deploy:jar ${warFile} --app ${this.herokuAppName}`;

            this.log(chalk.bold(`\nUploading your application code.\nThis may take ${chalk.cyan('several minutes')} depending on your connection speed...`));
            const child = exec(herokuDeployCommand, (err, stdout) => {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                this.log(chalk.green(`\nYour app should now be live. To view it run\n\t${chalk.bold('heroku open')}`));
                this.log(chalk.yellow(`And you can view the logs with this command\n\t${chalk.bold('heroku logs --tail')}`));
                this.log(chalk.yellow(`After application modification, redeploy it with\n\t${chalk.bold('jhipster heroku')}`));
                done();
            });

            child.stdout.on('data', (data) => {
                const line = data.toString().trimRight();
                if (line.trim().length !== 0) this.log(line);
            });
        }
    }
});
<|endoftext|>


<commit_before>/*global ace, define, exports*/
var language = {};
language.setlangmode = function language_setlangmode(input) {
    "use strict";
    var langmap = {
        coldfusion: "markup",
        css       : "css",
        csv       : "csv",
        dustjs    : "html",
        ejs       : "html",
        handlebars: "html",
        html      : "html",
        html_ruby : "html",
        javascript: "javascript",
        json      : "javascript",
        jsp       : "markup",
        jsx       : "javascript",
        less      : "css",
        markup    : "markup",
        php       : "html",
        qml       : "qml",
        scss      : "css",
        swig      : "html",
        text      : "text",
        titanium  : "tss",
        tss       : "tss",
        twig      : "html",
        velocity  : "velocity",
        xhtml     : "markup",
        xml       : "markup"
    };
    if (typeof input !== "string") {
        return "javascript";
    }
    if (input.indexOf("html") > -1) {
        return "html";
    }
    if (langmap[input] === undefined) {
        return "javascript";
    }
    return langmap[input];
};
language.nameproper  = function language_nameproper(input) {
    "use strict";
    var langmap = {
        coldfusion: "ColdFusion",
        dustjs    : "Dust.js",
        ejs       : "EJS Template",
        elm       : "Elm Template",
        handlebars: "Handlebars Template",
        html_ruby : "ERB (Ruby) Template",
        java      : "Java (not supported yet)",
        javascript: "JavaScript",
        jsp       : "JSTL (JSP)",
        jsx       : "React JSX",
        liquid    : "Liquid Template",
        markup    : "markup",
        scss      : "SCSS",
        text      : "Plain Text",
        titanium  : "Titanium Stylesheets",
        tss       : "Titanium Stylesheets",
        twig      : "HTML TWIG Template",
        typescript: "TypeScript (not supported yet)",
        velocity  : "Apache Velocity",
        volt      : "Volt Template"
    };
    if (typeof input !== "string" || langmap[input] === undefined) {
        return input.toUpperCase();
    }
    return langmap[input];
};
// [0] = language value for ace mode [1] = prettydiff language category from [0]
// [2] = pretty formatting for text output to user
language.auto = function language_auto(sample, defaultLang) {
    "use strict";
    var b         = [],
        c         = 0,
        output    = function language_auto_output(langname) {
            if (langname === "unknown") {
                return [
                    defaultLang, language.setlangmode(defaultLang),
                    "unknown"
                ];
            }
            if (langname === "xhtml" || langname === "markup") {
                return ["xml", "html", "XHTML"];
            }
            if (langname === "tss") {
                return ["tss", "tss", "Titanium Stylesheets"];
            }
            return [
                langname, language.setlangmode(langname),
                language.nameproper(langname)
            ];
        },
        cssA      = function language_auto_cssA() {
            if ((/\$[a-zA-Z]/).test(sample) === true || (/\{\s*(\w|\.|\$|#)+\s*\{/).test(sample) === true) {
                return output("scss");
            }
            if ((/@[a-zA-Z]/).test(sample) === true || (/\{\s*(\w|\.|@|#)+\s*\{/).test(sample) === true) {
                return output("less");
            }
            return output("css");
        },
        notmarkup = function language_auto_notmarkup() {
            var d               = 0,
                join            = "",
                flaga           = false,
                flagb           = false,
                javascriptA     = function language_auto_notmarkup_javascriptA() {
                    if (sample.indexOf("(") > -1 || sample.indexOf("=") > -1 || (sample.indexOf(";") > -1 && sample.indexOf("{") > -1)) {
                        if ((/:\s*((number)|(string))/).test(sample) === true && (/((public)|(private))\s+/).test(sample) === true) {
                            return output("typescript");
                        }
                        return output("javascript");
                    }
                    return output("unknown");
                },
                cssOrJavaScript = function language_auto_notmarkup_cssOrJavaScript() {
                    if ((/:\s*((number)|(string))/).test(sample) === true && (/((public)|(private))\s+/).test(sample) === true) {
                        return output("typescript");
                    }
                    if ((/((public)|(private))\s+(((static)?\s+(v|V)oid)|(class)|(final))/).test(sample) === true) {
                        return output("java");
                    }
                    if ((/\sclass\s+\w/).test(sample) === false && (/<[a-zA-Z]/).test(sample) === true && (/<\/[a-zA-Z]/).test(sample) === true && ((/\s?\{%/).test(sample) === true || (/\{(\{|#)(?!(\{|#|\=))/).test(sample) === true)) {
                        return output("twig");
                    }
                    if ((/^\s*(\$|@)/).test(sample) === false && (/(\};?\s*)$/).test(sample) === true) {
                        if ((/export\s+default\s+\{/).test(sample) === true || (/:\s*(\{|\(|\[)/).test(sample) === true || (/(\{|\s|;)render\s*\(\)\s*\{/).test(sample) === true || (/^(\s*return;?\s*\{)/).test(sample) === true) {
                            return output("javascript");
                        }
                    }
                    if ((/\{\{#/).test(sample) === true && (/\{\{\//).test(sample) === true && (/<\w/).test(sample) === true) {
                        return output("handlebars");
                    }
                    if ((/\{\s*(\w|\.|@|#)+\s*\{/).test(sample) === true) {
                        return output("less");
                    }
                    if ((/\$(\w|-)/).test(sample) === true) {
                        return output("scss");
                    }
                    if ((/(;|\{|:)\s*@\w/).test(sample) === true) {
                        return output("less");
                    }
                    return output("css");
                };
            for (d = 1; d < c; d += 1) {
                if (flaga === false) {
                    if (b[d] === "*" && b[d - 1] === "/") {
                        b[d - 1] = "";
                        flaga    = true;
                    } else if (flagb === false && b[d] === "f" && d < c - 6 && b[d + 1] === "i" && b[d + 2] === "l" && b[d + 3] === "t" && b[d + 4] === "e" && b[d + 5] === "r" && b[d + 6] === ":") {
                        flagb = true;
                    }
                } else if (flaga === true && b[d] === "*" && d !== c - 1 && b[d + 1] === "/") {
                    flaga    = false;
                    b[d]     = "";
                    b[d + 1] = "";
                } else if (flagb === true && b[d] === ";") {
                    flagb = false;
                    b[d]  = "";
                }
                if (flaga === true || flagb === true) {
                    b[d] = "";
                }
            }
            join = b.join("");
            if ((/^(\s*(\{|\[)(?!%))/).test(sample) === true && (/((\]|\})\s*)$/).test(sample) && sample.indexOf(",") !== -1) {
                return output("json");
            }
            if ((/((\}?(\(\))?\)*;?\s*)|([a-z0-9]("|')?\)*);?(\s*\})*)$/i).test(sample) === true && ((/(((var)|(let)|(const)|(function)|(import))\s+(\w|\$)+[a-zA-Z0-9]*)/).test(sample) === true || (/console\.log\(/).test(sample) === true || (/export\s+default\s+class\s+/).test(sample) === true || (/document\.get/).test(sample) === true || (/((\=|(\$\())\s*function)|(\s*function\s+(\w*\s+)?\()/).test(sample) === true || sample.indexOf("{") === -1 || (/^(\s*if\s+\()/).test(sample) === true)) {
                return javascriptA();
            }
            if (sample.indexOf("{") !== -1 && (/^(\s*[\{\$\.#@a-z0-9])|^(\s*\/(\*|\/))|^(\s*\*\s*\{)/i).test(sample) === true && (/^(\s*if\s*\()/).test(sample) === false && (/\=\s*(\{|\[|\()/).test(join) === false && (((/(\+|-|\=|\?)\=/).test(join) === false || (/\/\/\s*\=+/).test(join) === true) || ((/\=+('|")?\)/).test(sample) === true && (/;\s*base64/).test(sample) === true)) && (/function(\s+\w+)*\s*\(/).test(join) === false) {
                return cssOrJavaScript();
            }
            if ((/"\s*:\s*\{/).test(sample) === true) {
                return output("tss");
            }
            if (sample.indexOf("{\%") > -1) {
                return output("twig");
            }
            return output("unknown");
        },
        markup    = function language_auto_markup() {
            var html = function language_auto_markup_html() {
                if ((/<%\s*\}/).test(sample) === true) {
                    return output("ejs");
                }
                if ((/<%\s*end/).test(sample) === true) {
                    return output("html_ruby");
                }
                if ((/\{\{(#|\/|\{)/).test(sample) === true) {
                    return output("handlebars");
                }
                if ((/\{\{end\}\}/).test(sample) === true) {
                    //place holder for Go lang templates

                    return output("html");
                }
                if ((/\s?\{%/).test(sample) === true && (/\{(\{|#)(?!(\{|#|\=))/).test(sample) === true) {
                    return output("twig");
                }
                if ((/<\?/).test(sample) === true) {
                    return output("php");
                }
                if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) {
                    return output("jsp");
                }
                if ((/\{(#|\?|\^|@|<|\+|~)/).test(sample) === true && (/\{\//).test(sample) === true) {
                    return output("dustjs");
                }
                return output("html");
            };
            if ((/^(\s*<!doctype\ html>)/i).test(sample) === true || (/^(\s*<html)/i).test(sample) === true || ((/^(\s*<!DOCTYPE\s+((html)|(HTML))\s+PUBLIC\s+)/).test(sample) === true && (/XHTML\s+1\.1/).test(sample) === false && (/XHTML\s+1\.0\s+(S|s)((trict)|(TRICT))/).test(sample) === false)) {
                return html();
            }
            if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) {
                return output("jsp");
            }
            if ((/<%\s*\}/).test(sample) === true) {
                return output("ejs");
            }
            if ((/<%\s*end/).test(sample) === true) {
                return output("html_ruby");
            }
            if ((/\{\{(#|\/|\{)/).test(sample) === true) {
                return output("handlebars");
            }
            if ((/\{\{end\}\}/).test(sample) === true) {
                //place holder for Go lang templates

                return output("xml");
            }
            if ((/\s?\{%/).test(sample) === true && (/\{\{(?!(\{|#|\=))/).test(sample) === true) {
                return output("twig");
            }
            if ((/<\?(?!(xml))/).test(sample) === true) {
                return output("php");
            }
            if ((/\{(#|\?|\^|@|<|\+|~)/).test(sample) === true && (/\{\//).test(sample) === true) {
                return output("dustjs");
            }
            if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) {
                return output("jsp");
            }
            return output("xml");
        };
    if (sample === null) {
        return;
    }
    if ((/\sclass\s+\w/).test(sample) === false && (/(\s|;|\})((if)|(for)|(function\s*\w*))\s*\(/).test(sample) === false && (/((var)|(let)|(const))\s*\w/).test(sample) === false && (/return\s*\w*\s*(;|\})/).test(sample) === false && (sample === undefined || (/^(\s*#(?!(!\/)))/).test(sample) === true || (/\n\s*(\.|@)\w+(\(?|(\s*:))/).test(sample) === true)) {
        return cssA();
    }
    b = sample
        .replace(/\[[a-zA-Z][\w\-]*\=("|')?[a-zA-Z][\w\-]*("|')?\]/g, "")
        .split("");
    c = b.length;
    if ((/^(\s*\{(%|#|\{))/).test(sample) === true) {
        return markup();
    }
    if ((/^([\s\w\-]*<)/).test(sample) === false && (/(>[\s\w\-]*)$/).test(sample) === false) {
        return notmarkup();
    }
    if ((((/(>[\w\s:]*)?<(\/|!)?[\w\s:\-\[]+/).test(sample) === true || (/^(\s*<\?xml)/).test(sample) === true) && ((/^([\s\w]*<)/).test(sample) === true || (/(>[\s\w]*)$/).test(sample) === true)) || ((/^(\s*<s((cript)|(tyle)))/i).test(sample) === true && (/(<\/s((cript)|(tyle))>\s*)$/i).test(sample) === true)) {
        return markup();
    }
    return output("unknown");
};
if (typeof exports === "object" || typeof exports === "function") {
    //commonjs and nodejs support
    exports.api = language;
} else if ((typeof define === "object" || typeof define === "function") && (ace === undefined || ace.prettydiffid === undefined)) {
    //requirejs support
    define(function requirejs(require, exports) {
        "use strict";
        exports.api = language;
        //worthless if block to appease RequireJS and JSLint
        if (typeof require === "number") {
            return require;
        }
        return exports.api;
    });
}
<commit_msg>resolving a minor language identification issue<commit_after>/*global ace, define, exports*/
var language = {};
language.setlangmode = function language_setlangmode(input) {
    "use strict";
    var langmap = {
        coldfusion: "markup",
        css       : "css",
        csv       : "csv",
        dustjs    : "html",
        ejs       : "html",
        handlebars: "html",
        html      : "html",
        html_ruby : "html",
        javascript: "javascript",
        json      : "javascript",
        jsp       : "markup",
        jsx       : "javascript",
        less      : "css",
        markup    : "markup",
        php       : "html",
        qml       : "qml",
        scss      : "css",
        swig      : "html",
        text      : "text",
        titanium  : "tss",
        tss       : "tss",
        twig      : "html",
        velocity  : "velocity",
        xhtml     : "markup",
        xml       : "markup"
    };
    if (typeof input !== "string") {
        return "javascript";
    }
    if (input.indexOf("html") > -1) {
        return "html";
    }
    if (langmap[input] === undefined) {
        return "javascript";
    }
    return langmap[input];
};
language.nameproper  = function language_nameproper(input) {
    "use strict";
    var langmap = {
        coldfusion: "ColdFusion",
        dustjs    : "Dust.js",
        ejs       : "EJS Template",
        elm       : "Elm Template",
        handlebars: "Handlebars Template",
        html_ruby : "ERB (Ruby) Template",
        java      : "Java (not supported yet)",
        javascript: "JavaScript",
        jsp       : "JSTL (JSP)",
        jsx       : "React JSX",
        liquid    : "Liquid Template",
        markup    : "markup",
        scss      : "SCSS",
        text      : "Plain Text",
        titanium  : "Titanium Stylesheets",
        tss       : "Titanium Stylesheets",
        twig      : "HTML TWIG Template",
        typescript: "TypeScript (not supported yet)",
        velocity  : "Apache Velocity",
        volt      : "Volt Template"
    };
    if (typeof input !== "string" || langmap[input] === undefined) {
        return input.toUpperCase();
    }
    return langmap[input];
};
// [0] = language value for ace mode [1] = prettydiff language category from [0]
// [2] = pretty formatting for text output to user
language.auto = function language_auto(sample, defaultLang) {
    "use strict";
    var b         = [],
        c         = 0,
        output    = function language_auto_output(langname) {
            if (langname === "unknown") {
                return [
                    defaultLang, language.setlangmode(defaultLang),
                    "unknown"
                ];
            }
            if (langname === "xhtml" || langname === "markup") {
                return ["xml", "html", "XHTML"];
            }
            if (langname === "tss") {
                return ["tss", "tss", "Titanium Stylesheets"];
            }
            return [
                langname, language.setlangmode(langname),
                language.nameproper(langname)
            ];
        },
        cssA      = function language_auto_cssA() {
            if ((/\$[a-zA-Z]/).test(sample) === true || (/\{\s*(\w|\.|\$|#)+\s*\{/).test(sample) === true) {
                return output("scss");
            }
            if ((/@[a-zA-Z]/).test(sample) === true || (/\{\s*(\w|\.|@|#)+\s*\{/).test(sample) === true) {
                return output("less");
            }
            return output("css");
        },
        notmarkup = function language_auto_notmarkup() {
            var d               = 0,
                join            = "",
                flaga           = false,
                flagb           = false,
                javascriptA     = function language_auto_notmarkup_javascriptA() {
                    if (sample.indexOf("(") > -1 || sample.indexOf("=") > -1 || (sample.indexOf(";") > -1 && sample.indexOf("{") > -1)) {
                        if ((/:\s*((number)|(string))/).test(sample) === true && (/((public)|(private))\s+/).test(sample) === true) {
                            return output("typescript");
                        }
                        return output("javascript");
                    }
                    return output("unknown");
                },
                cssOrJavaScript = function language_auto_notmarkup_cssOrJavaScript() {
                    if ((/:\s*((number)|(string))/).test(sample) === true && (/((public)|(private))\s+/).test(sample) === true) {
                        return output("typescript");
                    }
                    if ((/((public)|(private))\s+(((static)?\s+(v|V)oid)|(class)|(final))/).test(sample) === true) {
                        return output("java");
                    }
                    if ((/\sclass\s+\w/).test(sample) === false && (/<[a-zA-Z]/).test(sample) === true && (/<\/[a-zA-Z]/).test(sample) === true && ((/\s?\{%/).test(sample) === true || (/\{(\{|#)(?!(\{|#|\=))/).test(sample) === true)) {
                        return output("twig");
                    }
                    if ((/^\s*(\$|@)/).test(sample) === false && (/(\};?\s*)$/).test(sample) === true) {
                        if ((/export\s+default\s+\{/).test(sample) === true || (/(:|\?)\s*(\{|\[)/).test(sample) === true || (/(\{|\s|;)render\s*\(\)\s*\{/).test(sample) === true || (/^(\s*return;?\s*\{)/).test(sample) === true) {
                            return output("javascript");
                        }
                    }
                    if ((/\{\{#/).test(sample) === true && (/\{\{\//).test(sample) === true && (/<\w/).test(sample) === true) {
                        return output("handlebars");
                    }
                    if ((/\{\s*(\w|\.|@|#)+\s*\{/).test(sample) === true) {
                        return output("less");
                    }
                    if ((/\$(\w|-)/).test(sample) === true) {
                        return output("scss");
                    }
                    if ((/(;|\{|:)\s*@\w/).test(sample) === true) {
                        return output("less");
                    }
                    return output("css");
                };
            for (d = 1; d < c; d += 1) {
                if (flaga === false) {
                    if (b[d] === "*" && b[d - 1] === "/") {
                        b[d - 1] = "";
                        flaga    = true;
                    } else if (flagb === false && b[d] === "f" && d < c - 6 && b[d + 1] === "i" && b[d + 2] === "l" && b[d + 3] === "t" && b[d + 4] === "e" && b[d + 5] === "r" && b[d + 6] === ":") {
                        flagb = true;
                    }
                } else if (flaga === true && b[d] === "*" && d !== c - 1 && b[d + 1] === "/") {
                    flaga    = false;
                    b[d]     = "";
                    b[d + 1] = "";
                } else if (flagb === true && b[d] === ";") {
                    flagb = false;
                    b[d]  = "";
                }
                if (flaga === true || flagb === true) {
                    b[d] = "";
                }
            }
            join = b.join("");
            if ((/^(\s*(\{|\[)(?!%))/).test(sample) === true && (/((\]|\})\s*)$/).test(sample) && sample.indexOf(",") !== -1) {
                return output("json");
            }
            if ((/((\}?(\(\))?\)*;?\s*)|([a-z0-9]("|')?\)*);?(\s*\})*)$/i).test(sample) === true && ((/(((var)|(let)|(const)|(function)|(import))\s+(\w|\$)+[a-zA-Z0-9]*)/).test(sample) === true || (/console\.log\(/).test(sample) === true || (/export\s+default\s+class\s+/).test(sample) === true || (/document\.get/).test(sample) === true || (/((\=|(\$\())\s*function)|(\s*function\s+(\w*\s+)?\()/).test(sample) === true || sample.indexOf("{") === -1 || (/^(\s*if\s+\()/).test(sample) === true)) {
                return javascriptA();
            }
            if (sample.indexOf("{") !== -1 && (/^(\s*[\{\$\.#@a-z0-9])|^(\s*\/(\*|\/))|^(\s*\*\s*\{)/i).test(sample) === true && (/^(\s*if\s*\()/).test(sample) === false && (/\=\s*(\{|\[|\()/).test(join) === false && (((/(\+|-|\=|\?)\=/).test(join) === false || (/\/\/\s*\=+/).test(join) === true) || ((/\=+('|")?\)/).test(sample) === true && (/;\s*base64/).test(sample) === true)) && (/function(\s+\w+)*\s*\(/).test(join) === false) {
                return cssOrJavaScript();
            }
            if ((/"\s*:\s*\{/).test(sample) === true) {
                return output("tss");
            }
            if (sample.indexOf("{\%") > -1) {
                return output("twig");
            }
            return output("unknown");
        },
        markup    = function language_auto_markup() {
            var html = function language_auto_markup_html() {
                if ((/<%\s*\}/).test(sample) === true) {
                    return output("ejs");
                }
                if ((/<%\s*end/).test(sample) === true) {
                    return output("html_ruby");
                }
                if ((/\{\{(#|\/|\{)/).test(sample) === true) {
                    return output("handlebars");
                }
                if ((/\{\{end\}\}/).test(sample) === true) {
                    //place holder for Go lang templates

                    return output("html");
                }
                if ((/\s?\{%/).test(sample) === true && (/\{(\{|#)(?!(\{|#|\=))/).test(sample) === true) {
                    return output("twig");
                }
                if ((/<\?/).test(sample) === true) {
                    return output("php");
                }
                if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) {
                    return output("jsp");
                }
                if ((/\{(#|\?|\^|@|<|\+|~)/).test(sample) === true && (/\{\//).test(sample) === true) {
                    return output("dustjs");
                }
                return output("html");
            };
            if ((/^(\s*<!doctype\ html>)/i).test(sample) === true || (/^(\s*<html)/i).test(sample) === true || ((/^(\s*<!DOCTYPE\s+((html)|(HTML))\s+PUBLIC\s+)/).test(sample) === true && (/XHTML\s+1\.1/).test(sample) === false && (/XHTML\s+1\.0\s+(S|s)((trict)|(TRICT))/).test(sample) === false)) {
                return html();
            }
            if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) {
                return output("jsp");
            }
            if ((/<%\s*\}/).test(sample) === true) {
                return output("ejs");
            }
            if ((/<%\s*end/).test(sample) === true) {
                return output("html_ruby");
            }
            if ((/\{\{(#|\/|\{)/).test(sample) === true) {
                return output("handlebars");
            }
            if ((/\{\{end\}\}/).test(sample) === true) {
                //place holder for Go lang templates

                return output("xml");
            }
            if ((/\s?\{%/).test(sample) === true && (/\{\{(?!(\{|#|\=))/).test(sample) === true) {
                return output("twig");
            }
            if ((/<\?(?!(xml))/).test(sample) === true) {
                return output("php");
            }
            if ((/\{(#|\?|\^|@|<|\+|~)/).test(sample) === true && (/\{\//).test(sample) === true) {
                return output("dustjs");
            }
            if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) {
                return output("jsp");
            }
            return output("xml");
        };
    if (sample === null) {
        return;
    }
    if ((/\sclass\s+\w/).test(sample) === false && (/(\s|;|\})((if)|(for)|(function\s*\w*))\s*\(/).test(sample) === false && (/((var)|(let)|(const))\s*\w/).test(sample) === false && (/return\s*\w*\s*(;|\})/).test(sample) === false && (sample === undefined || (/^(\s*#(?!(!\/)))/).test(sample) === true || (/\n\s*(\.|@)\w+(\(?|(\s*:))/).test(sample) === true)) {
        return cssA();
    }
    b = sample
        .replace(/\[[a-zA-Z][\w\-]*\=("|')?[a-zA-Z][\w\-]*("|')?\]/g, "")
        .split("");
    c = b.length;
    if ((/^(\s*\{(%|#|\{))/).test(sample) === true) {
        return markup();
    }
    if ((/^([\s\w\-]*<)/).test(sample) === false && (/(>[\s\w\-]*)$/).test(sample) === false) {
        return notmarkup();
    }
    if ((((/(>[\w\s:]*)?<(\/|!)?[\w\s:\-\[]+/).test(sample) === true || (/^(\s*<\?xml)/).test(sample) === true) && ((/^([\s\w]*<)/).test(sample) === true || (/(>[\s\w]*)$/).test(sample) === true)) || ((/^(\s*<s((cript)|(tyle)))/i).test(sample) === true && (/(<\/s((cript)|(tyle))>\s*)$/i).test(sample) === true)) {
        return markup();
    }
    return output("unknown");
};
if (typeof exports === "object" || typeof exports === "function") {
    //commonjs and nodejs support
    exports.api = language;
} else if ((typeof define === "object" || typeof define === "function") && (ace === undefined || ace.prettydiffid === undefined)) {
    //requirejs support
    define(function requirejs(require, exports) {
        "use strict";
        exports.api = language;
        //worthless if block to appease RequireJS and JSLint
        if (typeof require === "number") {
            return require;
        }
        return exports.api;
    });
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

/**
 * Expected Lighthouse audit values for byte efficiency tests
 */
module.exports = [
  {
    initialUrl: 'http://localhost:10200/byte-efficiency/tester.html',
    url: 'http://localhost:10200/byte-efficiency/tester.html',
    audits: {
      // TODO: re-enable once CSS protocol has stabilized
      // 'unused-css-rules': {
      //   score: false,
      //   extendedInfo: {
      //     value: {
      //       results: {
      //         length: 2
      //       }
      //     }
      //   }
      // },
      'offscreen-images': {
        score: 65,
        extendedInfo: {
          value: {
            results: {
              length: 3
            }
          }
        }
      },
      'uses-optimized-images': {
        score: 65,
        extendedInfo: {
          value: {
            results: {
              length: 4
            }
          }
        }
      },
      'uses-responsive-images': {
        score: 90,
        extendedInfo: {
          value: {
            results: {
              length: 3
            }
          }
        }
      }
    }
  },
];
<commit_msg>test: disable byte efficiency score assertions (#2198)<commit_after>/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

/**
 * Expected Lighthouse audit values for byte efficiency tests
 */
module.exports = [
  {
    initialUrl: 'http://localhost:10200/byte-efficiency/tester.html',
    url: 'http://localhost:10200/byte-efficiency/tester.html',
    audits: {
      // TODO: re-enable once CSS protocol has stabilized
      // 'unused-css-rules': {
      //   score: false,
      //   extendedInfo: {
      //     value: {
      //       results: {
      //         length: 2
      //       }
      //     }
      //   }
      // },
      'offscreen-images': {
        // TODO: re-enable score assertions when we have more flexible assertions like < 100
        // score: 65,
        extendedInfo: {
          value: {
            results: {
              length: 3
            }
          }
        }
      },
      'uses-optimized-images': {
        // score: 65,
        extendedInfo: {
          value: {
            results: {
              length: 4
            }
          }
        }
      },
      'uses-responsive-images': {
        // score: 90,
        extendedInfo: {
          value: {
            results: {
              length: 3
            }
          }
        }
      }
    }
  },
];
<|endoftext|>


<commit_before>import * as React from 'react'
import userActions from '../actions/userActions'

let Profile = React.createClass({
	componentWillReceiveProps(nextProps) {
		let email = nextProps.user ? nextProps.user.get('email') : null
		let username = nextProps.user ? nextProps.user.get('username') : null
		let name = nextProps.user ? nextProps.user.get('name') : null

		this.setState({email, username, name})
	},
	componentWillMount() {
		this.componentWillReceiveProps(this.props)
	},
	getInitialState: function() {
		return {
			email: '',
			name: '',
			username: '',
			saving: false,
		}
	},
	onNameChange(ev) {
		this.setState({name: ev.target.value})
	},
	onEmailChange(ev) {
		this.setState({email: ev.target.value})
	},
	onUsernameChange(ev) {
		this.setState({username: ev.target.value})
	},
	saveComplete() {
		this.setState({saving: 'saved'})
		console.log('saved user')
	},
	update(ev) {
		ev.preventDefault()
		this.setState({saving: 'saving'})
		this.props.user.set('username', this.state.username)
		this.props.user.set('name', this.state.name)
		this.props.user.set('password', this.refs.password.getDOMNode().value)
		this.props.user.save()
			.then(this.saveComplete)
	},
	render() {
		let title = React.createElement('h1', {className: 'view-title'}, 'User\'s Profile')

		let fields = [
			React.createElement('label', {key: 'name'}, 'Name: ', React.createElement('input',
				{type: 'text', placeholder: 'Anne Onymous', value: this.state.name, onChange: this.onNameChange})),

			React.createElement('label', {key: 'email'}, 'Email: ', React.createElement('input',
				{type: 'email', placeholder: 'anne@onymo.us', value: this.state.email, onChange: this.onEmailChange})),

			React.createElement('label', {key: 'username'}, 'Username: ', React.createElement('input',
				{type: 'username', placeholder: 'anne', value: this.state.username, onChange: this.onUsernameChange})),

			React.createElement('label', {key: 'password'}, 'Password: ', React.createElement('input',
				{type: 'password', placeholder: ':::::::', defaultValue: '', ref: 'password'})),
		]

		let profile = JSON.stringify(this.props.user, null, 2);

		return React.createElement('div',
			{id: 'profile'},
			title,
			profile,
			React.createElement('form', {className: 'edit-profile', onSubmit: this.update},
				fields,
				React.createElement('input', {type: 'submit', value: 'Save'}),
				React.createElement('button', {onClick: userActions.willSignOut}, 'Sign Out')))
	},
})

export default Profile
<commit_msg>Only change the user's password when the field is not blank<commit_after>import * as React from 'react'
import userActions from '../actions/userActions'

let Profile = React.createClass({
	componentWillReceiveProps(nextProps) {
		let email = nextProps.user ? nextProps.user.get('email') : null
		let username = nextProps.user ? nextProps.user.get('username') : null
		let name = nextProps.user ? nextProps.user.get('name') : null

		this.setState({email, username, name})
	},
	componentWillMount() {
		this.componentWillReceiveProps(this.props)
	},
	getInitialState: function() {
		return {
			email: '',
			name: '',
			username: '',
			saving: false,
		}
	},
	onNameChange(ev) {
		this.setState({name: ev.target.value})
	},
	onEmailChange(ev) {
		this.setState({email: ev.target.value})
	},
	onUsernameChange(ev) {
		this.setState({username: ev.target.value})
	},
	saveComplete() {
		this.setState({saving: 'saved'})
		console.log('saved user')
	},
	update(ev) {
		ev.preventDefault()
		this.setState({saving: 'saving'})
		this.props.user.set('username', this.state.username)
		this.props.user.set('name', this.state.name)
		if (this.refs.password.getDOMNode().value)
			this.props.user.set('password', this.refs.password.getDOMNode().value)
		this.props.user.save()
			.then(this.saveComplete)
	},
	render() {
		let title = React.createElement('h1', {className: 'view-title'}, 'User\'s Profile')

		let fields = [
			React.createElement('label', {key: 'name'}, 'Name: ', React.createElement('input',
				{type: 'text', placeholder: 'Anne Onymous', value: this.state.name, onChange: this.onNameChange})),

			React.createElement('label', {key: 'email'}, 'Email: ', React.createElement('input',
				{type: 'email', placeholder: 'anne@onymo.us', value: this.state.email, onChange: this.onEmailChange})),

			React.createElement('label', {key: 'username'}, 'Username: ', React.createElement('input',
				{type: 'username', placeholder: 'anne', value: this.state.username, onChange: this.onUsernameChange})),

			React.createElement('label', {key: 'password'}, 'Password: ', React.createElement('input',
				{type: 'password', placeholder: '·······', defaultValue: '', ref: 'password'})),
		]

		let buttons = React.createElement('div', {className: 'buttons'},
			React.createElement('input', {type: 'submit', value: 'Save'}),
			React.createElement('button', {onClick: userActions.willSignOut}, 'Sign Out'))

		let profile = JSON.stringify(this.props.user, null, 2);

		return React.createElement('div',
			{id: 'profile'},
			title,
			profile,
			React.createElement('form', {className: 'edit-profile', onSubmit: this.update},
				fields,
				buttons))
	},
})

export default Profile
<|endoftext|>