<commit_before>CKEDITOR.editorConfig = function(config) {
  config.keystrokes =
  [
    [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
    [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],

    [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],

    [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
    [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],

    [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],

    [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
    [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
    [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],

    [ CKEDITOR.CTRL + 86 /*V*/, 'pastetext' ],
    [ CKEDITOR.SHIFT + 45 /*INS*/, 'pastetext' ],

    [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]
  ];

  config.toolbar = [
    { name: 'basicstyles', items: [ 'Bold', 'Italic' ] },
    { name: 'insert', items: [ 'Image' ] },
    { name: 'clipboard', items: [ 'Cut', 'Copy', 'PasteText', '-', 'Undo', 'Redo' ] },
    { name: 'colors', items: [ 'BGColor' ] },
    { name: 'document', items: [ 'Source' ] }
  ];

  config.language = 'pt-BR';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }

    //customize class field for childrens approuch [VIZIR]
    if (dialogName == 'image')
    {
      for (var i in dialogDefinition.contents)
      {
        var contents = dialogDefinition.contents[i];
        var classField = dialogDefinition.contents[3].elements[2];
        dialogDefinition.contents[3].elements[2] = null;

        if (contents.id == "info")
        {
          classField.widths[0] = '100%';
          classField.widths[1] = '0%';
          classField.children[0].label = 'Intenção de tamanho para a imagem publicada';
          classField.children[0].type = 'select';
          classField.children[0].default = 'medium-intention';
          classField.children[0].items = [];
          classField.children[0].items.push(['Imagem com Tamanho Pequeno','small-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Médio','medium-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Grande','big-intention']);
          delete classField.children[1];
          contents.elements.splice(1, 0, classField);
          contents.elements[2].label = 'Legenda da Imagem';
        }
      }
    }
  });

  CKEDITOR.on('instanceReady', function(ck) {
    ck.editor.removeMenuItem('paste');
  });

};

// Blocking the paste keystroke
CKEDITOR.config.blockedKeystrokes.push(CKEDITOR.CTRL + 86 /*V*/);

//showing message to alert user about using the paste button
$(document).keydown(function(e){
      if(e.ctrlKey && e.keyCode == 86){
            if ($("#paste-message").length == 0){
              $("
").appendTo($("body"));
            }
            $("#paste-message").addClass('alert');
            $("#paste-message").addClass('alert-box');
            $("#paste-message").html('Para colar textos, utilize o botão na barra de ferramentas<button type="button" class="close" data-dismiss="alert">×</button>');
            $("#paste-message").alert();
      }
});<commit_msg>Removendo campos da tela de upload de imagem<commit_after>CKEDITOR.editorConfig = function(config) {
  config.keystrokes =
  [
    [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],
    [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],

    [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],

    [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],
    [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],

    [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],

    [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
    [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
    [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],

    [ CKEDITOR.CTRL + 86 /*V*/, 'pastetext' ],
    [ CKEDITOR.SHIFT + 45 /*INS*/, 'pastetext' ],

    [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]
  ];

  config.toolbar = [
    { name: 'basicstyles', items: [ 'Bold', 'Italic' ] },
    { name: 'insert', items: [ 'Image' ] },
    { name: 'clipboard', items: [ 'Cut', 'Copy', 'PasteText', '-', 'Undo', 'Redo' ] },
    { name: 'colors', items: [ 'BGColor' ] },
    { name: 'document', items: [ 'Source' ] }
  ];

  config.language = 'pt-BR';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Because of
  config.hideDialogFields = "image:info:htmlPreview";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }

    //customize class field for childrens approuch [VIZIR]
    if (dialogName == 'image')
    {
      for (var i in dialogDefinition.contents)
      {
        var contents = dialogDefinition.contents[i];

        if (contents.id == "info")
        {
          var classField = dialogDefinition.contents[3].elements[2];
          dialogDefinition.contents[3].elements[2] = null;

          classField.widths[0] = '100%';
          classField.widths[1] = '0%';
          classField.children[0].label = 'Intenção de tamanho para a imagem publicada';
          classField.children[0].type = 'select';
          classField.children[0].default = 'medium-intention';
          classField.children[0].items = [];
          classField.children[0].items.push(['Imagem com Tamanho Pequeno','small-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Médio','medium-intention']);
          classField.children[0].items.push(['Imagem com Tamanho Grande','big-intention']);
          delete classField.children[1];
          contents.elements.splice(1, 0, classField);
          contents.elements[2].label = 'Legenda da Imagem';
          delete contents.elements[3].children[0].children[0]; //remove the width, heigth, border, etc fields
        }
      }

      dialogDefinition.onLoad = function () {
        var dialog = CKEDITOR.dialog.getCurrent();

        var elem = dialog.getContentElement('info','htmlPreview');
        elem.getElement().hide();

        dialog.hidePage('advanced');
      };
    }
  });

  CKEDITOR.on('instanceReady', function(ck) {
    ck.editor.removeMenuItem('paste');
  });

};

// Blocking the paste keystroke
CKEDITOR.config.blockedKeystrokes.push(CKEDITOR.CTRL + 86 /*V*/);

//showing message to alert user about using the paste button
$(document).keydown(function(e){
      if(e.ctrlKey && e.keyCode == 86){
            if ($("#paste-message").length == 0){
              $("
").appendTo($("body"));
            }
            $("#paste-message").addClass('alert');
            $("#paste-message").addClass('alert-box');
            $("#paste-message").html('Para colar textos, utilize o botão na barra de ferramentas<button type="button" class="close" data-dismiss="alert">×</button>');
            $("#paste-message").alert();
      }
});<|endoftext|>


<commit_before>/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
  // Define changes to default configuration here. For example:
  // config.language = 'fr';
  // config.uiColor = '#AADC6E';

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });
};
<commit_msg>add gothic replacement<commit_after>/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
  // Define changes to default configuration here. For example:
  // config.language = 'fr';
  // config.uiColor = '#AADC6E';
  myFonts = ['Muli'];

  config.font_names = 'sans serif';

  for(var i = 0; i<myFonts.length; i++){
     config.font_names = config.font_names+';'+myFonts[i];
     myFonts[i] = 'http://fonts.googleapis.com/css?family='+myFonts[i].replace(' ','+');

     //assuming you use jquery
     $("head").append("<link rel='stylesheet' href='"+ myFonts[i] +"'>");
  }

  /* Filebrowser routes */
  // The location of an external file browser, that should be launched when "Browse Server" button is pressed.
  config.filebrowserBrowseUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
  config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";

  // The location of a script that handles file uploads in the Flash dialog.
  config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
  config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";

  // The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
  config.filebrowserImageBrowseUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads in the Image dialog.
  config.filebrowserImageUploadUrl = "/ckeditor/pictures";

  // The location of a script that handles file uploads.
  config.filebrowserUploadUrl = "/ckeditor/attachment_files";

  // Rails CSRF token
  config.filebrowserParams = function(){
    var csrf_token, csrf_param, meta,
        metas = document.getElementsByTagName('meta'),
        params = new Object();

    for ( var i = 0 ; i < metas.length ; i++ ){
      meta = metas[i];

      switch(meta.name) {
        case "csrf-token":
          csrf_token = meta.content;
          break;
        case "csrf-param":
          csrf_param = meta.content;
          break;
        default:
          continue;
      }
    }

    if (csrf_param !== undefined && csrf_token !== undefined) {
      params[csrf_param] = csrf_token;
    }

    return params;
  };

  config.addQueryString = function( url, params ){
    var queryString = [];

    if ( !params ) {
      return url;
    } else {
      for ( var i in params )
        queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
    }

    return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
  };

  // Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;
    var content, upload;

    if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
      content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
      upload = (content == null ? null : content.get('upload'));

      if (upload && upload.filebrowser && upload.filebrowser['params'] === undefined) {
        upload.filebrowser['params'] = config.filebrowserParams();
        upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
      }
    }
  });
};
<|endoftext|>


<commit_before>idleOut = {}

idleOut.pageTimeOut = function(timeout) {
  this.timeout = timeout
}

idleOut.pageTimeOut.prototype.start = function() {
  var idleTime = 0;
  var increment = this.timeout
  var alerted = true;

  if(alerted === true) {
    var idleInterval = setInterval(timerIncrement, increment); // 1 minute
  }

  function timerIncrement() {
    idleTime++;
    if (idleTime > 1 && alerted === true) { // 50 minutes
      alerted = false
      alert("Your page has timed out.  Please save/copy your information elsewhere before you are redirected to our login server.")
    }
  }

}
<commit_msg>changed input to respond to minutes instead of timer increment<commit_after>idleOut = {}

idleOut.pageTimeOut = function(timeout) {
  this.timeout = timeout
}

idleOut.pageTimeOut.prototype.start = function() {
  var idleTime = 0;
  var minutes = this.timeout
  var alerted = true;

  if(alerted === true) {
    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
  }

  function timerIncrement() {
    idleTime++;
    if (idleTime > minutes && alerted === true) { // 50 minutes
      alerted = false
      alert("Your page has timed out.  Please save/copy your information elsewhere before you are redirected to our login server.")
    }
  }

}
<|endoftext|>


<commit_before>import React from "react";

export default (
  <g>
    <path d="M16.19,10.56L7,19.76a0.78,0.78,0,0,1-1.12,0L3.81,17.7a0.78,0.78,0,0,1,0-1.12L10.4,10,3.81,3.41a0.78,0.78,0,0,1,0-1.12L5.87,0.24A0.78,0.78,0,0,1,7,.24l9.21,9.21A0.78,0.78,0,0,1,16.19,10.56Z" />
  </g>
)
<commit_msg>New right chevron<commit_after>import React from "react";

export default (
  <g>
    <polyline fill="none" stroke="#000000" stroke-width="3" stroke-linecap="round" stroke-miterlimit="10" points="6,2 14,10 6,18 "/>
  </g>
)
<|endoftext|>


<commit_before>(function(app, kea, ko) {
  "use strict";

  var Base,
      Serializable,
      Validatable;

  Base = function Base() {

    this.id            = null;
    this.resource_path = null;

    this.persisted = ko.observable(false);

    this._attributeNames                    = [];
    this._deserializableAttributes          = [];
    this._serializableAttributes            = [];
    this._deserializableAssociations        = {};
    this._serializableAssociations          = {};
    this._deserializableHasManyAssociations = {};
    this._serializableHasManyAssociations   = {};

    this.deserializationOptions = { attributes: {} };
    this.serializationOptions   = { attributes: {} };
  };

  Base.prototype._modelName = function _modelName() {
    console.error("Model does not implement _modelName");
  };

  Base.prototype.addAttribute = function addAttribute(name, options) {
    options             = options || {};
    options.array       = typeof options.array !== 'undefined' ? options.array : false;
    options.deserialize = typeof options.deserialize !== 'undefined' ? options.deserialize : true;
    options.serialize   = typeof options.serialize !== 'undefined' ? options.serialize : true;

    if (options.array) {
      this[name] = ko.observableArray([]);
    } else {
      this[name] = ko.observable(options.value);
    }

    if (options.deserialize) {
      this._deserializableAttributes.push(name);

      if (typeof options !== 'boolean') {
        this.deserializationOptions.attributes[name] = options.deserialize;
      }
    }

    if (options.serialize) {
      this._serializableAttributes.push(name);

      if (typeof options !== 'boolean') {
        this.serializationOptions.attributes[name] = options.serialize;
      }
    }
  };

  Base.prototype.unserializableAttributes = function unserializableAttributes(attributeNames) {
    attributeNames.forEach(function(name) {
      this.addAttribute(name, {serialize: false});
    }, this);
  };

  Base.prototype.serializableAttributes = function unserializableAttributes(attributeNames) {
    attributeNames.forEach(function(name) {
      this.addAttribute(name);
    }, this);
  };

  Base.prototype.addAssociation = function addAssociation(modelName, attributeName, type, options) {
    var deserializationKey,
        serializationKey;

    options             = options || {};
    options.deserialize = typeof options.deserialize !== 'undefined' ? options.deserialize : true;
    options.serialize   = typeof options.serialize !== 'undefined' ? options.serialize : true;

    if (type === 'hasOne') {
      this[attributeName] = ko.observable();
      deserializationKey  = '_deserializableAssociations';
      serializationKey    = '_serializableAssociations';

    } else if (type === 'hasMany') {
      this[attributeName] = ko.observableArray([]);
      deserializationKey  = '_deserializableHasManyAssociations';
      serializationKey    = '_serializableHasManyAssociations';

    } else {
      console.error('unsupported association type %s', type);
      return;
    }

    if (options.deserialize) {
      this[deserializationKey][attributeName] = modelName;

      if (typeof options !== 'boolean') {
        this.deserializationOptions.attributes[name] = options.deserialize;
      }
    }

    if (options.serialize) {
      this[serializationKey][attributeName] = modelName;

      if (typeof options !== 'boolean') {
        this.serializationOptions.attributes[name] = options.serialize;
      }
    }
  };

  Base.prototype.hasOne = function hasOne(modelName, attributeName, options) {
    if (typeof attributeName === 'undefined') {
      attributeName = modelName.toLowerCase();
    }

    this.addAssociation(modelName, attributeName, 'hasOne', options);
  };

  Base.prototype.hasMany = function hasMany(modelName, attributeName, options) {
    this.addAssociation(modelName, attributeName, 'hasMany', options);
  };

  Base.prototype.forEachAssocation = function forEachAssocation(type, callback) {
    var key = '_' + type + 'Associations';

    for (var attributeName in this[key]) {
      if ( this[key].hasOwnProperty(attributeName) ) {
        callback.call(this, attributeName, this[key][attributeName]);
      }
    }
  };

  Base.prototype.service = function service() {
    if (DEBUG) {
      console.assert(app.services[ this._modelName() ], this._modelName() + " service does not exist");
    }

    return app.services[ this._modelName() ];
  };

  Base.prototype.update = function update(params) {
    var that = this,
        deferred;

    deferred = this.service()
      .update(that, params)
      .done(function(data) {
        that.deserialize(data);
      });

    return deferred;
  };

  Base.prototype.destroy = function destroy() {
    return $.ajax({
      type:     'DELETE',
      url:      this.resource_path,
      dataType: 'JSON'

    }).fail(function(jqXHR, textStatus) {
      window.kea.notify(textStatus, 'error');

    });
  };

  Base.prototype.deserialize = function deserialize(data) {
    this.persisted(true);

    this.id            = data.id;
    this.resource_path = data.resource_path;

    this._deserializableAttributes.forEach(function(name) {
      var newValue = data[name];

      if (this.deserializationOptions.attributes[name] &&
          this.deserializationOptions.attributes[name].map === true) {

        var currentValue = this[name]();

        if (typeof currentValue === 'object') {
          ko.mapping.fromJS(newValue, {}, currentValue);
        } else {
          this[name]( ko.mapping.fromJS(newValue) );
        }

      } else {
        this[name](newValue);
      }
    }, this);

    this.forEachAssocation('deserializable', function(attributeName, modelName) {
      if ( data[attributeName] ) {
        this[attributeName]( new app.models[modelName](data[attributeName]) );
      }
    });

    this.forEachAssocation('deserializableHasMany', function(attributeName, modelName) {
      if ( data[attributeName] ) {
        this[attributeName].removeAll();

        data[attributeName].forEach(function(associationData) {
          this[attributeName].push( new app.models[modelName](associationData) );
        }, this);
      }
    });

    if (typeof this.fromJS === 'function') {
      this.fromJS(data);
    }
  };

  Base.prototype.serialize = function serialize(options) {
    var that = this,
        result = {},
        defaultOptions,
        attributeList,
        attributeOptions,
        isBlank,
        shouldIncludeAttribute;

    defaultOptions = {
      includeId: false,
      attributes: {}
    };

    options = $.extend({}, defaultOptions, this.serializationOptions, options);

    attributeOptions = function attributeOptions(attributeName) {
      return options.attributes[attributeName] || {};
    };

    isBlank = function isBlank(value) {
      return typeof value === 'undefined' || value === null || value === '' || (Array.isArray(value) && value.length === 0 );
    };

    shouldIncludeAttribute = function shouldIncludeAttribute(name, value) {
      var skipBlank = typeof attributeOptions(name).skipBlank !== 'undefined' ? attributeOptions(name).skipBlank : options.skipBlank;

      if ( that._serializableAttributes.indexOf(name) === -1) {
        return false;
      } else if (skipBlank && isBlank(value)) {
        return false;
      } else {
        return true;
      }
    };

    if (options.includeId) {
      result.id = this.id;
    }

    if (this._destroy) {
      result._destroy = true;
    }

    this._serializableAttributes.forEach(function(name) {
      var value = this[name]();

      if (shouldIncludeAttribute(name, value)) {

        if (attributeOptions(name).map === true) {
          result[name] = ko.mapping.toJS(value);
        } else {
          result[name] = value;
        }

      }
    }, this);

    this.forEachAssocation('serializable', function(attributeName, modelName) {
      var value,
          key;

      if (attributeOptions(attributeName).idOnly) {
        value = this[attributeName]() ? this[attributeName]().id : null;
        key   = attributeName + '_id';
      } else {
        value = this[attributeName]() ? this[attributeName]().serialize() : null;
        key   = attributeName;
      }

      if (shouldIncludeAttribute(attributeName, value)) {
        result[key] = value;
      }
    });

    this.forEachAssocation('serializableHasMany', function(attributeName, modelName) {
      var value = this[attributeName]().map(function(association) { return association.serialize(); } );

      if (shouldIncludeAttribute(attributeName, value)) {
        result[attributeName + '_attributes'] = value;
      }
    });

    if (typeof this.toJS === 'function') {
      result = this.toJS(result);
    }

    return result;
  };

  kea.models.Base = Base;

  Validatable = function Validatable() {
    var that = this;

    this.isValidatable = ko.observable(false);

    this.makeValidatable = function makeValidatable(options) {
      if (DEBUG) {
        console.assert(this.attachValidators, "object does not implement attachValidators");
      }

      this.attachValidators(options);
      this.isValidatable(true);
    };

    this.validatableFields = function validatableFields() {
      return [];
    };

    this.validatableAssociations = function validatableAssociations() {
      return [];
    };

    this.validatableAssociationLists = function validatableAssociationLists() {
      return [];
    };

    this.forEachValidatableField = function forEachValidatableField(callback) {
      ko.utils.arrayForEach(this.validatableFields(), function(field) {
        if (that[field].isValidatable) {
          callback.call(that, that[field], field);
        }
      });
    };

    this.forEachValidatableAssociation = function forEachValidatableAssociation(callback) {
      var association_list;

      ko.utils.arrayForEach(this.validatableAssociations(), function(association_name) {
        var association = that[association_name]();

        if (association.isValidatable && association.isValidatable()) {
          callback.call(that, association, association_name);
        }
      });

      ko.utils.arrayForEach(this.validatableAssociationLists(), function(association_list_name) {
        association_list = that[association_list_name];

        ko.utils.arrayForEach(association_list(), function(association) {
          if (association.isValidatable && association.isValidatable()) {
            callback.call(that, association);
          }
        });
      });
    };

    this.hasErrors = ko.computed(function hasErrors() {
      var result = false;

      that.forEachValidatableField(function(observable) {
        if (observable.hasError()) {
          result = true;
        }
      }, this);

      if (result) {
        return true;
      }

      that.forEachValidatableAssociation(function(association) {
        if (association.hasErrors()) {
          result = true;
        }
      });

      return result;
    }, this, {deferEvaluation: true});

    this.validationMessages = ko.computed(function validationMessages() {
      var messages = [];

      that.forEachValidatableField(function(observable, fieldName) {
        if (observable.hasError()) {
          messages.push(fieldName + ': ' + observable.validationMessage());
        }
      }, this);

      that.forEachValidatableAssociation(function(association, name) {
        if (association.hasErrors()) {
          messages = name + ': ' + messages.concat(association.validationMessages());
        }
      });

      return messages;
    }, this, {deferEvaluation: true});

    this.isFullyValidated = ko.computed(function isFullyValidated() {
      var result = true;

      that.forEachValidatableField(function(observable) {
        if (observable.isUnvalidated() || observable.validationInProgress()) {
          result = false;
        }
      });

      if (!result) {
        return false;
      }

      that.forEachValidatableAssociation(function(association) {
        if (!association.isFullyValidated() || association.hasValidationsInProgress()) {
          result = false;
        }
      });

      return result;
    }, this, {deferEvaluation: true});

    this.hasValidationsInProgress = ko.computed(function hasValidationsInProgress() {
      var result = false;

      that.forEachValidatableField(function(observable) {
        if (observable.validationInProgress()) {
          result = true;
        }
      });

      if (result) {
        return true;
      }

      that.forEachValidatableAssociation(function(association) {
        if (association.hasValidationsInProgress()) {
          result = true;
        }
      });

      return result;
    }, this, {deferEvaluation: true});

    this.isValid = ko.computed(function isValid() {
      return !this.hasErrors() && this.isFullyValidated();
    }, this, {deferEvaluation: true});

    this.validate = function validate() {
      that.forEachValidatableField(function(observable) {
        observable.validate();
      });

      that.forEachValidatableAssociation(function(association) {
        association.validate();
      });
    };
  };

  kea.models.Validatable = Validatable;

})(window.app, window.kea, ko);<commit_msg>Fix typo<commit_after>(function(app, kea, ko) {
  "use strict";

  var Base,
      Serializable,
      Validatable;

  Base = function Base() {

    this.id            = null;
    this.resource_path = null;

    this.persisted = ko.observable(false);

    this._attributeNames                    = [];
    this._deserializableAttributes          = [];
    this._serializableAttributes            = [];
    this._deserializableAssociations        = {};
    this._serializableAssociations          = {};
    this._deserializableHasManyAssociations = {};
    this._serializableHasManyAssociations   = {};

    this.deserializationOptions = { attributes: {} };
    this.serializationOptions   = { attributes: {} };
  };

  Base.prototype._modelName = function _modelName() {
    console.error("Model does not implement _modelName");
  };

  Base.prototype.addAttribute = function addAttribute(name, options) {
    options             = options || {};
    options.array       = typeof options.array !== 'undefined' ? options.array : false;
    options.deserialize = typeof options.deserialize !== 'undefined' ? options.deserialize : true;
    options.serialize   = typeof options.serialize !== 'undefined' ? options.serialize : true;

    if (options.array) {
      this[name] = ko.observableArray([]);
    } else {
      this[name] = ko.observable(options.value);
    }

    if (options.deserialize) {
      this._deserializableAttributes.push(name);

      if (typeof options !== 'boolean') {
        this.deserializationOptions.attributes[name] = options.deserialize;
      }
    }

    if (options.serialize) {
      this._serializableAttributes.push(name);

      if (typeof options !== 'boolean') {
        this.serializationOptions.attributes[name] = options.serialize;
      }
    }
  };

  Base.prototype.unserializableAttributes = function unserializableAttributes(attributeNames) {
    attributeNames.forEach(function(name) {
      this.addAttribute(name, {serialize: false});
    }, this);
  };

  Base.prototype.serializableAttributes = function unserializableAttributes(attributeNames) {
    attributeNames.forEach(function(name) {
      this.addAttribute(name);
    }, this);
  };

  Base.prototype.addAssociation = function addAssociation(modelName, attributeName, type, options) {
    var deserializationKey,
        serializationKey;

    options             = options || {};
    options.deserialize = typeof options.deserialize !== 'undefined' ? options.deserialize : true;
    options.serialize   = typeof options.serialize !== 'undefined' ? options.serialize : true;

    if (type === 'hasOne') {
      this[attributeName] = ko.observable();
      deserializationKey  = '_deserializableAssociations';
      serializationKey    = '_serializableAssociations';

    } else if (type === 'hasMany') {
      this[attributeName] = ko.observableArray([]);
      deserializationKey  = '_deserializableHasManyAssociations';
      serializationKey    = '_serializableHasManyAssociations';

    } else {
      console.error('unsupported association type %s', type);
      return;
    }

    if (options.deserialize) {
      this[deserializationKey][attributeName] = modelName;

      if (typeof options !== 'boolean') {
        this.deserializationOptions.attributes[attributeName] = options.deserialize;
      }
    }

    if (options.serialize) {
      this[serializationKey][attributeName] = modelName;

      if (typeof options !== 'boolean') {
        this.serializationOptions.attributes[attributeName] = options.serialize;
      }
    }
  };

  Base.prototype.hasOne = function hasOne(modelName, attributeName, options) {
    if (typeof attributeName === 'undefined') {
      attributeName = modelName.toLowerCase();
    }

    this.addAssociation(modelName, attributeName, 'hasOne', options);
  };

  Base.prototype.hasMany = function hasMany(modelName, attributeName, options) {
    this.addAssociation(modelName, attributeName, 'hasMany', options);
  };

  Base.prototype.forEachAssocation = function forEachAssocation(type, callback) {
    var key = '_' + type + 'Associations';

    for (var attributeName in this[key]) {
      if ( this[key].hasOwnProperty(attributeName) ) {
        callback.call(this, attributeName, this[key][attributeName]);
      }
    }
  };

  Base.prototype.service = function service() {
    if (DEBUG) {
      console.assert(app.services[ this._modelName() ], this._modelName() + " service does not exist");
    }

    return app.services[ this._modelName() ];
  };

  Base.prototype.update = function update(params) {
    var that = this,
        deferred;

    deferred = this.service()
      .update(that, params)
      .done(function(data) {
        that.deserialize(data);
      });

    return deferred;
  };

  Base.prototype.destroy = function destroy() {
    return $.ajax({
      type:     'DELETE',
      url:      this.resource_path,
      dataType: 'JSON'

    }).fail(function(jqXHR, textStatus) {
      window.kea.notify(textStatus, 'error');

    });
  };

  Base.prototype.deserialize = function deserialize(data) {
    this.persisted(true);

    this.id            = data.id;
    this.resource_path = data.resource_path;

    this._deserializableAttributes.forEach(function(name) {
      var newValue = data[name];

      if (this.deserializationOptions.attributes[name] &&
          this.deserializationOptions.attributes[name].map === true) {

        var currentValue = this[name]();

        if (typeof currentValue === 'object') {
          ko.mapping.fromJS(newValue, {}, currentValue);
        } else {
          this[name]( ko.mapping.fromJS(newValue) );
        }

      } else {
        this[name](newValue);
      }
    }, this);

    this.forEachAssocation('deserializable', function(attributeName, modelName) {
      if ( data[attributeName] ) {
        this[attributeName]( new app.models[modelName](data[attributeName]) );
      }
    });

    this.forEachAssocation('deserializableHasMany', function(attributeName, modelName) {
      if ( data[attributeName] ) {
        this[attributeName].removeAll();

        data[attributeName].forEach(function(associationData) {
          this[attributeName].push( new app.models[modelName](associationData) );
        }, this);
      }
    });

    if (typeof this.fromJS === 'function') {
      this.fromJS(data);
    }
  };

  Base.prototype.serialize = function serialize(options) {
    var that = this,
        result = {},
        defaultOptions,
        attributeList,
        attributeOptions,
        isBlank,
        shouldIncludeAttribute;

    defaultOptions = {
      includeId: false,
      attributes: {}
    };

    options = $.extend({}, defaultOptions, this.serializationOptions, options);

    attributeOptions = function attributeOptions(attributeName) {
      return options.attributes[attributeName] || {};
    };

    isBlank = function isBlank(value) {
      return typeof value === 'undefined' || value === null || value === '' || (Array.isArray(value) && value.length === 0 );
    };

    shouldIncludeAttribute = function shouldIncludeAttribute(name, value) {
      var skipBlank = typeof attributeOptions(name).skipBlank !== 'undefined' ? attributeOptions(name).skipBlank : options.skipBlank;

      if ( that._serializableAttributes.indexOf(name) === -1) {
        return false;
      } else if (skipBlank && isBlank(value)) {
        return false;
      } else {
        return true;
      }
    };

    if (options.includeId) {
      result.id = this.id;
    }

    if (this._destroy) {
      result._destroy = true;
    }

    this._serializableAttributes.forEach(function(name) {
      var value = this[name]();

      if (shouldIncludeAttribute(name, value)) {

        if (attributeOptions(name).map === true) {
          result[name] = ko.mapping.toJS(value);
        } else {
          result[name] = value;
        }

      }
    }, this);

    this.forEachAssocation('serializable', function(attributeName, modelName) {
      var value,
          key;

      if (attributeOptions(attributeName).idOnly) {
        value = this[attributeName]() ? this[attributeName]().id : null;
        key   = attributeName + '_id';
      } else {
        value = this[attributeName]() ? this[attributeName]().serialize() : null;
        key   = attributeName;
      }

      if (shouldIncludeAttribute(attributeName, value)) {
        result[key] = value;
      }
    });

    this.forEachAssocation('serializableHasMany', function(attributeName, modelName) {
      var value = this[attributeName]().map(function(association) { return association.serialize(); } );

      if (shouldIncludeAttribute(attributeName, value)) {
        result[attributeName + '_attributes'] = value;
      }
    });

    if (typeof this.toJS === 'function') {
      result = this.toJS(result);
    }

    return result;
  };

  kea.models.Base = Base;

  Validatable = function Validatable() {
    var that = this;

    this.isValidatable = ko.observable(false);

    this.makeValidatable = function makeValidatable(options) {
      if (DEBUG) {
        console.assert(this.attachValidators, "object does not implement attachValidators");
      }

      this.attachValidators(options);
      this.isValidatable(true);
    };

    this.validatableFields = function validatableFields() {
      return [];
    };

    this.validatableAssociations = function validatableAssociations() {
      return [];
    };

    this.validatableAssociationLists = function validatableAssociationLists() {
      return [];
    };

    this.forEachValidatableField = function forEachValidatableField(callback) {
      ko.utils.arrayForEach(this.validatableFields(), function(field) {
        if (that[field].isValidatable) {
          callback.call(that, that[field], field);
        }
      });
    };

    this.forEachValidatableAssociation = function forEachValidatableAssociation(callback) {
      var association_list;

      ko.utils.arrayForEach(this.validatableAssociations(), function(association_name) {
        var association = that[association_name]();

        if (association.isValidatable && association.isValidatable()) {
          callback.call(that, association, association_name);
        }
      });

      ko.utils.arrayForEach(this.validatableAssociationLists(), function(association_list_name) {
        association_list = that[association_list_name];

        ko.utils.arrayForEach(association_list(), function(association) {
          if (association.isValidatable && association.isValidatable()) {
            callback.call(that, association);
          }
        });
      });
    };

    this.hasErrors = ko.computed(function hasErrors() {
      var result = false;

      that.forEachValidatableField(function(observable) {
        if (observable.hasError()) {
          result = true;
        }
      }, this);

      if (result) {
        return true;
      }

      that.forEachValidatableAssociation(function(association) {
        if (association.hasErrors()) {
          result = true;
        }
      });

      return result;
    }, this, {deferEvaluation: true});

    this.validationMessages = ko.computed(function validationMessages() {
      var messages = [];

      that.forEachValidatableField(function(observable, fieldName) {
        if (observable.hasError()) {
          messages.push(fieldName + ': ' + observable.validationMessage());
        }
      }, this);

      that.forEachValidatableAssociation(function(association, name) {
        if (association.hasErrors()) {
          messages = name + ': ' + messages.concat(association.validationMessages());
        }
      });

      return messages;
    }, this, {deferEvaluation: true});

    this.isFullyValidated = ko.computed(function isFullyValidated() {
      var result = true;

      that.forEachValidatableField(function(observable) {
        if (observable.isUnvalidated() || observable.validationInProgress()) {
          result = false;
        }
      });

      if (!result) {
        return false;
      }

      that.forEachValidatableAssociation(function(association) {
        if (!association.isFullyValidated() || association.hasValidationsInProgress()) {
          result = false;
        }
      });

      return result;
    }, this, {deferEvaluation: true});

    this.hasValidationsInProgress = ko.computed(function hasValidationsInProgress() {
      var result = false;

      that.forEachValidatableField(function(observable) {
        if (observable.validationInProgress()) {
          result = true;
        }
      });

      if (result) {
        return true;
      }

      that.forEachValidatableAssociation(function(association) {
        if (association.hasValidationsInProgress()) {
          result = true;
        }
      });

      return result;
    }, this, {deferEvaluation: true});

    this.isValid = ko.computed(function isValid() {
      return !this.hasErrors() && this.isFullyValidated();
    }, this, {deferEvaluation: true});

    this.validate = function validate() {
      that.forEachValidatableField(function(observable) {
        observable.validate();
      });

      that.forEachValidatableAssociation(function(association) {
        association.validate();
      });
    };
  };

  kea.models.Validatable = Validatable;

})(window.app, window.kea, ko);<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// ======================================================
// Containers
// ======================================================
import Layout from '../../Layout';
import { FooterAction } from '../../Utils';

// ======================================================
// Components
// ======================================================
import { MobileTopupTitle, ProductTitle, PromotionSetTitle, PaymentConfirmation, Loading, Thankyou } from '../../../components';

// ======================================================
// Actions
// ======================================================
import * as ApplicationActions from '../../../actions/applicationActions';
import * as Actions from './actions';

// ======================================================
// Selectors
// ======================================================
import RootSelector from '../../../selectors/root';
import MasterappSelector from '../../../selectors/masterapp';
import OrderSelector from '../../../selectors/order';

const mapStateToProps = state => {
  return {
    ...state.payment,
    moneyBoxActive: MasterappSelector.verifyIsMoneyBoxActive(state.masterapp),
    canChangeCash: state.masterapp.canChangeCash,
    baseURL: MasterappSelector.getBaseURL(state.masterapp),
    summaryList: RootSelector.getPaymentSummaryList(state),
    paymentBgImage: OrderSelector.getPaymentBgImage(state.order),
    orderType: OrderSelector.getOrderType(state.order)
  };
};

const actions = {
  ...ApplicationActions,
  ...Actions,
};

const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);

class PaymentPage extends PureComponent {
  static propTypes = {
    baseURL: PropTypes.string.isRequired,
    summaryList: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    isFinish: PropTypes.bool.isRequired,
    isLoading: PropTypes.bool.isRequired,
    returnAllInsertCash: PropTypes.func.isRequired,
    initPaymentPage: PropTypes.func.isRequired,
    canChangeCash: PropTypes.bool.isRequired,
    orderType: PropTypes.string,
    paymentBgImage: PropTypes.string,
  };

  componentDidMount = () => {
    const { initPaymentPage } = this.props;
    initPaymentPage();
  }

  componentWillUnmount = () => {
    const { returnAllInsertCash } = this.props;
    console.log('outPaymentPage !!!!');
    // if unmount return
    returnAllInsertCash();
  }

  renderContent = () => {
    const { moneyBoxActive, baseURL, isLoading, isFinish, summaryList, canChangeCash } = this.props;
    // const isFinish = true;
    if (moneyBoxActive) {
      if (isFinish) return <Thankyou baseURL={baseURL} />;
      if (isLoading) return <Loading baseURL={baseURL} />;
      return (
        <PaymentConfirmation
          baseURL={baseURL}
          summaryList={summaryList}
          canChangeCash={canChangeCash}
        />
      );
    }
    if (isFinish) {
      return <Thankyou baseURL={baseURL} />;
    }
    return <Loading text={'ระบบกำลังเปิดรับเงิน รอสักครู่'} baseURL={baseURL} />
  }

  renderTitle = () => {
    const { baseURL, orderType, paymentBgImage } = this.props;
    if (orderType === 'promotionSet') {
      return <PromotionSetTitle baseURL={baseURL} bgImage={paymentBgImage} />;
    }
    if (orderType === 'mobileTopup') {
      return <MobileTopupTitle baseURL={baseURL} bgImage={paymentBgImage} />;
    }
    return <ProductTitle baseURL={baseURL} bgImage={paymentBgImage} />;
  }

  render() {
    const { moneyBoxActive, baseURL, isLoading, isFinish } = this.props;
    const canBack = !isLoading && !isFinish;
    return (

        <Layout.Title>
          {
            this.renderTitle()
          }
        </Layout.Title>
        <Layout.Content>
          {
            !moneyBoxActive && <Loading text={'ระบบกำลังเปิดรับเงิน รอสักครู่'} baseURL={baseURL} />
          }
          {
            moneyBoxActive && this.renderContent()
          }
          {
            moneyBoxActive && canBack &&
            <FooterAction />
          }
        </Layout.Content>

    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PaymentPage);
<commit_msg>Add audio for paymentPage<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// ======================================================
// Hoc
// ======================================================
import { withAudio } from '../../../hoc/withAudio';
// ======================================================
// Containers
// ======================================================
import Layout from '../../Layout';
import ThankyouPage from '../../ThankyouPage';
import { FooterAction } from '../../Utils';

// ======================================================
// Components
// ======================================================
import {
  MobileTopupTitle,
  ProductTitle,
  PromotionSetTitle,
  PaymentConfirmation,
  Loading
} from '../../../components';

// ======================================================
// Actions
// ======================================================
import * as ApplicationActions from '../../../actions/applicationActions';
import * as Actions from './actions';

// ======================================================
// Selectors
// ======================================================
import RootSelector from '../../../selectors/root';
import MasterappSelector from '../../../selectors/masterapp';
import OrderSelector from '../../../selectors/order';

const mapStateToProps = state => ({
  ...state.payment,
  moneyBoxActive: MasterappSelector.verifyIsMoneyBoxActive(state.masterapp),
  canChangeCash: state.masterapp.canChangeCash,
  baseURL: MasterappSelector.getBaseURL(state.masterapp),
  summaryList: RootSelector.getPaymentSummaryList(state),
  paymentBgImage: OrderSelector.getPaymentBgImage(state.order),
  orderType: OrderSelector.getOrderType(state.order)
});

const actions = {
  ...ApplicationActions,
  ...Actions
};

const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);

class PaymentPage extends PureComponent {
  static propTypes = {
    baseURL: PropTypes.string.isRequired,
    summaryList: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
    isFinish: PropTypes.bool.isRequired,
    isLoading: PropTypes.bool.isRequired,
    returnAllInsertCash: PropTypes.func.isRequired,
    initPaymentPage: PropTypes.func.isRequired,
    canChangeCash: PropTypes.bool.isRequired,
    orderType: PropTypes.string,
    paymentBgImage: PropTypes.string
  };

  componentDidMount = () => {
    const { initPaymentPage } = this.props;
    initPaymentPage();
  };

  componentWillUnmount = () => {
    const { returnAllInsertCash } = this.props;
    console.log('outPaymentPage !!!!');
    // if unmount return
    returnAllInsertCash();
  };

  renderContent = () => {
    const { moneyBoxActive, baseURL, isLoading, isFinish, summaryList, canChangeCash } = this.props;
    // const isFinish = true;
    if (moneyBoxActive) {
      if (isFinish) return <ThankyouPage baseURL={baseURL} />;
      if (isLoading) return <Loading baseURL={baseURL} />;
      return (
        <PaymentConfirmation
          baseURL={baseURL}
          summaryList={summaryList}
          canChangeCash={canChangeCash}
        />
      );
    }
    if (isFinish) {
      return <ThankyouPage baseURL={baseURL} />;
    }
    return <Loading text={'ระบบกำลังเปิดรับเงิน รอสักครู่'} baseURL={baseURL} />;
  };

  renderTitle = () => {
    const { baseURL, orderType, paymentBgImage } = this.props;
    if (orderType === 'promotionSet') {
      return <PromotionSetTitle baseURL={baseURL} bgImage={paymentBgImage} />;
    }
    if (orderType === 'mobileTopup') {
      return <MobileTopupTitle baseURL={baseURL} bgImage={paymentBgImage} />;
    }
    return <ProductTitle baseURL={baseURL} bgImage={paymentBgImage} />;
  };

  render() {
    const { moneyBoxActive, baseURL, isLoading, isFinish } = this.props;
    const canBack = !isLoading && !isFinish;
    return (

        <Layout.Title>{this.renderTitle()}</Layout.Title>
        <Layout.Content>
          {!moneyBoxActive && <Loading text={'ระบบกำลังเปิดรับเงิน รอสักครู่'} baseURL={baseURL} />}
          {moneyBoxActive && this.renderContent()}
          {moneyBoxActive && canBack && <FooterAction />}
        </Layout.Content>

    );
  }
}

export default withAudio({ src: 'http://localhost:8888/vms/html-v2/voice/4.m4a' })(
  connect(mapStateToProps, mapDispatchToProps)(PaymentPage)
);
<|endoftext|>


<commit_before>import Sortable from 'sortablejs';
import { s__ } from '~/locale';
import createFlash from '~/flash';
import {
  getBoardSortableDefaultOptions,
  sortableStart,
} from '~/boards/mixins/sortable_default_options';
import axios from '~/lib/utils/axios_utils';

const updateIssue = (url, issueList, { move_before_id, move_after_id }) =>
  axios
    .put(`${url}/reorder`, {
      move_before_id,
      move_after_id,
      group_full_path: issueList.dataset.groupFullPath,
    })
    .catch(() => {
      createFlash(s__("ManualOrdering|Couldn't save the order of the issues"));
    });

const initManualOrdering = () => {
  const issueList = document.querySelector('.manual-ordering');

  if (!issueList || !(gon.features && gon.features.manualSorting) || !(gon.current_user_id > 0)) {
    return;
  }

  Sortable.create(
    issueList,
    getBoardSortableDefaultOptions({
      scroll: true,
      dataIdAttr: 'data-id',
      fallbackOnBody: false,
      group: {
        name: 'issues',
      },
      draggable: 'li.issue',
      onStart: () => {
        sortableStart();
      },
      onUpdate: event => {
        const el = event.item;

        const url = el.getAttribute('url');

        const prev = el.previousElementSibling;
        const next = el.nextElementSibling;

        const beforeId = prev && parseInt(prev.dataset.id, 10);
        const afterId = next && parseInt(next.dataset.id, 10);

        updateIssue(url, issueList, { move_after_id: afterId, move_before_id: beforeId });
      },
    }),
  );
};

export default initManualOrdering;
<commit_msg>Remove manual_sorting flag from FE<commit_after>import Sortable from 'sortablejs';
import { s__ } from '~/locale';
import createFlash from '~/flash';
import {
  getBoardSortableDefaultOptions,
  sortableStart,
} from '~/boards/mixins/sortable_default_options';
import axios from '~/lib/utils/axios_utils';

const updateIssue = (url, issueList, { move_before_id, move_after_id }) =>
  axios
    .put(`${url}/reorder`, {
      move_before_id,
      move_after_id,
      group_full_path: issueList.dataset.groupFullPath,
    })
    .catch(() => {
      createFlash(s__("ManualOrdering|Couldn't save the order of the issues"));
    });

const initManualOrdering = () => {
  const issueList = document.querySelector('.manual-ordering');

  if (!issueList || !(gon.current_user_id > 0)) {
    return;
  }

  Sortable.create(
    issueList,
    getBoardSortableDefaultOptions({
      scroll: true,
      dataIdAttr: 'data-id',
      fallbackOnBody: false,
      group: {
        name: 'issues',
      },
      draggable: 'li.issue',
      onStart: () => {
        sortableStart();
      },
      onUpdate: event => {
        const el = event.item;

        const url = el.getAttribute('url');

        const prev = el.previousElementSibling;
        const next = el.nextElementSibling;

        const beforeId = prev && parseInt(prev.dataset.id, 10);
        const afterId = next && parseInt(next.dataset.id, 10);

        updateIssue(url, issueList, { move_after_id: afterId, move_before_id: beforeId });
      },
    }),
  );
};

export default initManualOrdering;
<|endoftext|>


<commit_before>import React from 'react';

function Hero() {
  return (

            Cum fac o sesizare?

            Vrei să trimiți o sesizare, dar nu ești sigur dacă s-a încălcat o regulă? Verifică mai jos, în ghidul alegătorului, care sunt regulile de vot, pentru a transmite informații corecte și utile.
Pentru a ne asigura ca sesizările privesc exact subiectul alegerilor, acestea vor fi postate pe site după o verificare făcută de echipa proiectului.

  );
}

export default Hero;
<commit_msg>Content replacement 3<commit_after>import React from 'react';

function Hero() {
  return (

            Cum fac o sesizare?

            Vrei să trimiți o sesizare, dar nu ești sigur dacă s-a încălcat o
            regulă? Verifică mai jos, în ghidul alegătorului, care sunt regulile
            de vot la referendum, pentru a transmite informații corecte și
            utile.

            Pentru a ne asigura ca sesizările privesc exact subiectul
            referendumului pentru familie din 2018, acestea vor fi postate pe
            site după o verificare făcută de echipa proiectului.

  );
}

export default Hero;
<|endoftext|>


<commit_before>/* jshint globalstrict: true */
"use strict";

var EventEmitter = require('./EventEmitter');
var typpo_module = require('./factory');
var Int64 = require('./Int64');
var buffer = require('buffer');
var typpo = require('./typpo');

var MAX_XBEE_PACKET_SIZE = 256;

// TODO(kzentner): Don't hard code this.
var LENGTH_OFFSET = 2;

// TODO(kzentner): Don't hard code this.
var EXTRA_XBEE_BYTES = 4;

var Accumulator = function(serportObj) {
  EventEmitter.apply(this);
  this.buf = buffer.Buffer(MAX_XBEE_PACKET_SIZE);
  this.offset = 0;
  this.target_length = null;
  this._on_recv = on_recv.bind(this);
  this.serportObj = serportObj;
  serportObj.on('data', this._on_recv);
};

exports.Accumulator = Accumulator;

Accumulator.prototype = Object.create(EventEmitter.prototype);

Accumulator.prototype.destroy = function () {
  this.serportObj.off('data', this._on_recv);
};

var on_recv = function (data) {
  data.copy(this.buf, this.offset, 0, data.length);
  this.offset += data.length;
  if (this.offset > LENGTH_OFFSET && this.target_length === null) {
    this.target_length = this.buf[LENGTH_OFFSET] + EXTRA_XBEE_BYTES;
  }

  if (this.target_length !== null && this.offset >= this.target_length) {
    var buf = this.buf.slice(0, this.target_length);
    var new_buf = buffer.Buffer(MAX_XBEE_PACKET_SIZE);
    this.buf.copy(new_buf, 0, this.target_length, this.offset);
    this.buf = new_buf;
    this.offset = 0;
    this.target_length = null;
    console.log('length', buf.length);
    this.emit('data', buf);
  }
};

// This module contains utilities for using an XBee radio.
// TODO(kzentner): Move other, duplicated xbee functionality here.

exports.computeChecksum = function (buf, start, len) {
    if (start === undefined) {
      start = typpo.get_size('xbee_api_packet', true) -
              typpo.get_size('xbee_tx64_header', true);
    }
    if (len === undefined) {
      // -1 for checksum byte at the end.
      len = buf.length - start - 1;
    }
    var sum = 0;

    for (var i = start; i < start + len; i++) {
        sum += buf[i];
    }

    sum = sum & 0xFF;

    return 0xFF - sum;
};

// Creates a full XBee packet.
// payload should be an object returned from factory.js, or a buffer.
// Address should be a hexadecimal string.

exports.createPacket = function (payload, address) {
  var payload_length = 0;
  if (payload instanceof buffer.Buffer) {
    payload_length = payload.length;
  } else if (payload.type) {
    payload_length = payload.get_size();
    // We're going to store payload into a uint8_t[] below, so cast it.
    payload = payload.cast();
  } else {
    throw "Could not determine type of XBee payload.";
  }
  var xbee_tx_frame = typpo.wrap(typpo.get_type('xbee_tx64_header'), {
    xbee_api_type: typpo.get_const('XBEE_API_TYPE_TX64'),
    frameId: 0,
    xbee_dest_addr: new Int64("0x" + address),
    options: 0,
    data: payload
  });

  var xbee_payload = typpo.wrap(typpo.get_type('xbee_payload'), {
    tx64: xbee_tx_frame
  });

  var xbee_packet = typpo.wrap(typpo.get_type('xbee_api_packet'), {
    xbee_api_magic: typpo.get_const('XBEE_MAGIC'),
    length: typpo.get_size('xbee_tx64_header', true) + payload_length,
    payload: xbee_payload
  });

  // The +1 allows the checksum to be crammed in the end

  var buf = buffer.Buffer(typpo.get_size('xbee_api_packet', true) + payload_length + 1);

  xbee_packet.write(buf);

  // Note, this is kinda jank.
  buf[buf.length - 1] = exports.computeChecksum(buf);

  return buf;
};

// Returns true if buf contains *exactly* a single valid XBee packet.
// Extra space at the end of the buffer is not allowed.
exports.isFullPacket = function (buf) {
  var header_size = typpo.get_size('xbee_api_packet', true);
  if (buf.length < header_size) {
    return false;
  }
  try {
    var xbee_packet = typpo.read('xbee_api_packet', buf);
    var payload_header_size = typpo.get_size('xbee_tx64_header', true);
    var length = xbee_packet.get_slot('length').val;
    var checksum_size = 1;
    if (buf.length === length + header_size + checksum_size - payload_header_size) {
      var checksum = exports.computeChecksum(buf);
      if (checksum === buf[buf.length - 1]) {
        return true;
      }
    }
  } catch (_) {
    // The packet caused an error, so it was almost certainly corrupt (and thus
    // not a full packet).
  }
  return false;
};

exports.extractPayload = function (rxPacket) {
  console.log('payload', rxPacket);
  var api_packet = typpo.read('xbee_api_packet', rxPacket);
  var payload = api_packet.get_slot('payload');
  var api_type = payload.get_slot('xbee_api_type').unwrap();
  if (api_type !== typpo.get_const('XBEE_API_TYPE_RX64')) {
    throw "Attempt to extract the payload from a non-rx64 packet.";
  }
  var rx = api_packet.get_slot('payload').get_slot('rx64');
  var data = rx.get_slot('data').unwrap();

  // Don't ouput checksum.
  return data.slice(0, -1);
};
<commit_msg>A few more debug statements.<commit_after>/* jshint globalstrict: true */
"use strict";

var EventEmitter = require('./EventEmitter');
var typpo_module = require('./factory');
var Int64 = require('./Int64');
var buffer = require('buffer');
var typpo = require('./typpo');

var MAX_XBEE_PACKET_SIZE = 256;

// TODO(kzentner): Don't hard code this.
var LENGTH_OFFSET = 2;

// TODO(kzentner): Don't hard code this.
var EXTRA_XBEE_BYTES = 4;

var Accumulator = function(serportObj) {
  EventEmitter.apply(this);
  this.buf = buffer.Buffer(MAX_XBEE_PACKET_SIZE);
  this.buf.fill(0xff);
  this.offset = 0;
  this.target_length = null;
  this._on_recv = on_recv.bind(this);
  this.serportObj = serportObj;
  serportObj.on('data', this._on_recv);
};

exports.Accumulator = Accumulator;

Accumulator.prototype = Object.create(EventEmitter.prototype);

Accumulator.prototype.destroy = function () {
  this.serportObj.off('data', this._on_recv);
};

var on_recv = function (data) {
  console.log('data.length =', data.length);
  data.copy(this.buf, this.offset, 0, data.length);
  this.offset += data.length;
  if (this.offset > LENGTH_OFFSET && this.target_length === null) {
    this.target_length = this.buf[LENGTH_OFFSET] + EXTRA_XBEE_BYTES;
  }

  if (this.target_length !== null && this.offset >= this.target_length) {
    var buf = this.buf.slice(0, this.target_length);
    var new_buf = buffer.Buffer(MAX_XBEE_PACKET_SIZE);
    new_buf.fill(0xff);
    console.log('this.buf.length =', this.buf.length);
    this.buf.copy(new_buf, 0, this.target_length, this.offset);
    this.buf = new_buf;
    this.offset = 0;
    this.target_length = null;
    console.log('length', buf.length);
    this.emit('data', buf);
  }
};

// This module contains utilities for using an XBee radio.
// TODO(kzentner): Move other, duplicated xbee functionality here.

exports.computeChecksum = function (buf, start, len) {
    if (start === undefined) {
      start = typpo.get_size('xbee_api_packet', true) -
              typpo.get_size('xbee_tx64_header', true);
    }
    if (len === undefined) {
      // -1 for checksum byte at the end.
      len = buf.length - start - 1;
    }
    var sum = 0;

    for (var i = start; i < start + len; i++) {
        sum += buf[i];
    }

    sum = sum & 0xFF;

    return 0xFF - sum;
};

// Creates a full XBee packet.
// payload should be an object returned from factory.js, or a buffer.
// Address should be a hexadecimal string.

exports.createPacket = function (payload, address) {
  var payload_length = 0;
  if (payload instanceof buffer.Buffer) {
    payload_length = payload.length;
  } else if (payload.type) {
    payload_length = payload.get_size();
    // We're going to store payload into a uint8_t[] below, so cast it.
    payload = payload.cast();
  } else {
    throw "Could not determine type of XBee payload.";
  }
  var xbee_tx_frame = typpo.wrap(typpo.get_type('xbee_tx64_header'), {
    xbee_api_type: typpo.get_const('XBEE_API_TYPE_TX64'),
    frameId: 0,
    xbee_dest_addr: new Int64("0x" + address),
    options: 0,
    data: payload
  });

  var xbee_payload = typpo.wrap(typpo.get_type('xbee_payload'), {
    tx64: xbee_tx_frame
  });

  var xbee_packet = typpo.wrap(typpo.get_type('xbee_api_packet'), {
    xbee_api_magic: typpo.get_const('XBEE_MAGIC'),
    length: typpo.get_size('xbee_tx64_header', true) + payload_length,
    payload: xbee_payload
  });

  // The +1 allows the checksum to be crammed in the end

  var buf = buffer.Buffer(typpo.get_size('xbee_api_packet', true) + payload_length + 1);

  xbee_packet.write(buf);

  // Note, this is kinda jank.
  buf[buf.length - 1] = exports.computeChecksum(buf);

  return buf;
};

// Returns true if buf contains *exactly* a single valid XBee packet.
// Extra space at the end of the buffer is not allowed.
exports.isFullPacket = function (buf) {
  var header_size = typpo.get_size('xbee_api_packet', true);
  if (buf.length < header_size) {
    return false;
  }
  try {
    var xbee_packet = typpo.read('xbee_api_packet', buf);
    var payload_header_size = typpo.get_size('xbee_tx64_header', true);
    var length = xbee_packet.get_slot('length').val;
    var checksum_size = 1;
    if (buf.length === length + header_size + checksum_size - payload_header_size) {
      var checksum = exports.computeChecksum(buf);
      if (checksum === buf[buf.length - 1]) {
        return true;
      }
    }
  } catch (_) {
    // The packet caused an error, so it was almost certainly corrupt (and thus
    // not a full packet).
  }
  return false;
};

exports.extractPayload = function (rxPacket) {
  console.log('payload', rxPacket);
  var api_packet = typpo.read('xbee_api_packet', rxPacket);
  var payload = api_packet.get_slot('payload');
  var api_type = payload.get_slot('xbee_api_type').unwrap();
  if (api_type !== typpo.get_const('XBEE_API_TYPE_RX64')) {
    throw "Attempt to extract the payload from a non-rx64 packet.";
  }
  var rx = api_packet.get_slot('payload').get_slot('rx64');
  var data = rx.get_slot('data').unwrap();

  // Don't ouput checksum.
  return data.slice(0, -1);
};
<|endoftext|>


<commit_before>'use strict';
const yeoman = require('yeoman-generator'),
  chalk = require('chalk'),
  yosay = require('yosay'),
  bakery = require('../../lib/bakery'),
  feedback = require('../../lib/feedback'),
  debug = require('debug')('bakery:generators:bake:index'),
  _ = require('lodash');

const AWS_REGIONS = [{
  name: 'us-east-1'
}, {
  name: 'us-east-2'
}, {
  name: 'us-west-1'
}, {
  name: 'us-west-2'
}, {
  name: 'ap-south-1'
}, {
  name: 'ap-northeast-1'
}, {
  name: 'ap-southeast-1'
}, {
  name: 'ap-southeast-2'
}, {
  name: 'ap-northeast-1'
}, {
  name: 'eu-central-1'
}, {
  name: 'eu-west-1'
}, {
  name: 'sa-east-1'
}];
const AWS_INSTANCE_TYPES = ['t2.nano', 't2.micro', 't2.small', 't2.medium', 't2.large', 'm4.large', 'm4.xlarge', 'm4.2xlarge', 'm4.4xlarge', 'm4.8xlarge', 'm4.16xlarge', 'c4.large', 'c4.xlarge', 'c4.2xlarge', 'c4.4xlarge', 'c4.8xlarge'];

var BakeryBake = yeoman.Base.extend({

  constructor: function() {
    yeoman.Base.apply(this, arguments);

    this._options.help.desc = 'Show this help';

    /** @property {object} answers - prompt answers */
    this.answers = {};

    this.option('projectname', {
      desc: 'Name of the project being created',
      type: String,
      alias: 'n'
    });

    this.option('awsprofile', {
      type: String,
      alias: 'p',
      desc: 'Name of the AWS profile to use when calling the AWS api for value validation'
    });
  },

  prompting: function() {
    this.log(bakery.banner('Bakery Setup!'));

    var prompts = [{
      type: "confirm",
      name: "createami",
      message: "Create Amazon Machine Image?",
      default: true
    }, {
      type: 'input',
      name: 'aminame',
      message: 'Name for this AMI:',
      default: function() {
        return process.env.PROJECTNAME + ' {{timestamp}}'
      },
      when: function(response) {
        return response.createami && process.env.PROJECTNAME;
      }
    }, {
      type: 'input',
      name: 'amidescription',
      message: 'Enter a description for this AMI:',
      when: function(response) {
        return response.createami;
      }
    }, {
      type: "checkbox",
      name: "awsregions",
      message: "Choose AWS Region(s) for creation",
      choices: AWS_REGIONS,
      when: function(response) {
        return response.createami;
      },
      default: process.env.AWS_REGION || 'us-west-2',
      validate: function(response) {
        feedback.info(response);
        if (response.length < 0) {
          return 'You must choose at least one AWS Region.';
        }
        return true;
      }
    }, {
      type: 'list',
      name: 'primaryregion',
      message: 'Choose a primary region for building in AWS:',
      when: function(response) {
        if (response.awsregions.length == 1) {
          response.primaryregion = response.awsregions[0]
        }
        return (response.awsregions.length > 1);
      },
      choices: function(response) {
        return response.awsregions;
      },
      default: function(response) {
        if (response.awsregions.indexOf('us-west-2') > -1) {
          return 'us-west-2';
        } else {
          return response.awsregions[0];
        }
      }
    }, {
      type: 'list',
      name: 'buildimagetype',
      message: 'Instance Type for build:',
      default: 't2.large',
      choices: AWS_INSTANCE_TYPES,
      when: function(response) {
        return response.createami;
      }
    }, {
      type: 'input',
      name: 'regionspecificami',
      message: function(response) {
        return 'AMI ID in ' + response.primaryregion + ' region:';
      },
      when: function(response) {
        return response.createami;
      },
      validate: function(response) {
        return bakery.validateAMIId(response, {
          awsregion: response.primaryregion || 'us-west-2',
          awsprofile: process.env.AWS_PROFILE || 'default'
        }).then(function(successful) {
          return successful;
        });
      }
    }, {
      type: 'confirm',
      name: 'iswindows',
      message: 'Is this a Windows-based image:',
      default: false,
      when: function(response) {
        return response.createami && !process.env.WINDOWSIMAGE;
      }
    }, {
      type: 'input',
      name: 'amigroups',
      message: 'Enter a list (comma separated) of groups to share this AMI with:',
      when: function(response) {
        return response.createami;
      }
    }, {
      type: 'input',
      name: 'amiusers',
      message: 'Enter a list of (comma separated) account id\'s to share this AMI with:',
      when: function(response) {
        return response.createami;
      }
    }, {
      type: 'input',
      name: 'iaminstanceprofile',
      message: 'Enter the IAM instance profile id you want to apply to instances while they are being built:',
      when: function(response) {
        return response.createami;
      }
    }, {
      type: 'input',
      name: 'vpcid',
      message: 'Enter VPC ID, leave blank for default VPC:',
      when: function(response) {
        return response.createami;
      }
    }, {
      type: 'input',
      name: 'subnetid',
      message: 'Enter subnet id - Required for non-default VPC ID:',
      when: function(response) {
        return response.createami && response.vpcid.length > 0;
      }
    }, {
      type: 'input',
      name: 'securitygroupids',
      message: 'Enter security group ids (comma separated) - required for non-default VPC ID:',
      when: function(response) {
        return response.createami && response.vpcid.length > 0;
      }
    }];

    return this.prompt(prompts).then(function(props) {
      this.props = props;
      switch (process.env.CI_TYPE) {
        case 'drone':
          //do something
          break;
        case 'jenkins':
          //do something
          break;
        default:
          this.error('CI toolset ' + process.env.CI_TYPE + ' is not currently available. Skipping CI script setup');
          break;
      }
    }.bind(this));
  },

  writing: function() {
    var packerDictionary = {
      variables: {
        aws_access_key: "{{ env 'AWS_ACCESS_KEY_ID' }}",
        aws_secret_key: "{{ env 'AWS_SECRET_ACCESS_KEY' }}",
        instance_type: this.props.buildimagetype
      },
      builders: [],
      provisioners: []
    };

    packerDictionary.builders[0] = {};

    packerDictionary.builders[0].type = "amazon-ebs";
    packerDictionary.builders[0].access_key = "{{ user `aws_access_key` }}";
    packerDictionary.builders[0].secret_key = "{{ user `aws_secret_key` }}";
    packerDictionary.builders[0].ami_name = this.props.aminame || process.env.PROJECTNAME + ' {{timestamp}}';
    packerDictionary.builders[0].instance_type = "{{ user `instance_type` }}";
    packerDictionary.builders[0].region = this.props.primaryregion;
    packerDictionary.builders[0].source_ami = this.props.regionspecificami;

    if (this.props.awsregions.length > 1) {
      packerDictionary.builders[0]['ami_regions'] = [];
      this.props.awsregions.forEach(function(element) {
        if (element != this.props.primaryregion) {
          packerDictionary.builders[0]['ami_regions'].push(element);
        }
      }.bind(this));
    };
    if (typeof this.props.amidescription !== 'undefined' && this.props.amidescription.length > 0) {
      packerDictionary.builders[0]['ami_description'] = this.props.amidescription;
    };
    if (typeof this.props.amigroups !== 'undefined' && this.props.amigroups.length > 0) {
      packerDictionary.builders[0]['ami_groups'] = this.props.amigroups.split(',');
    };
    if (typeof this.props.amiusers !== 'undefined' && this.props.amiusers.length > 0) {
      packerDictionary.builders[0]['ami_users'] = this.props.amiusers.split(',');
    }
    if (typeof this.props.vpcid !== 'undefined' && this.props.vpcid.length > 0) {
      packerDictionary.builders[0]['vpc_id'] = this.props.vpcid;
    };
    if (typeof this.props.subnetid !== 'undefined' && this.props.subnetid.length > 0) {
      packerDictionary.builders[0]['subnet_id'] = this.props.subnetid;
    };
    if (typeof this.props.securitygroupids !== 'undefined' && this.props.securitygroupids.length > 0) {
      buildpackerDictionary.builders[0]['security_group_ids'] = this.props.securitygroupids.split(',');
    };
    if (typeof this.props.iaminstanceprofile !== 'undefined' && this.props.iaminstanceprofile.length > 0) {
      packerDictionary.builders[0]['iam_instance_profile'] = this.props.iaminstanceprofile;
    };

    packerDictionary.provisioners[0] = {}

    var osType = 'unix';
    if (process.env.WINDOWSIMAGE || this.props.iswindows) {
      osType = 'windows';
    };

    switch (process.env.CM_TYPE) {
      case 'chef':
        packerDictionary.provisioners[0]['type'] = 'chef-solo';
        packerDictionary.provisioners[0]['cookbook_paths'] = ['../'];
        packerDictionary.provisioners[0]['guest_os_type'] = osType;
        break;
      case 'puppet':
        packerDictionary.provisioners[0]['type'] = 'puppet-masterless';
        packerDictionary.provisioners[0]['manifest_file'] = 'manifests/';
        primarpackerDictionary.provisioners[0]['hiera_config_path'] = 'hiera.yaml';
        packerDictionary.provisioners[0]['module_paths'] = 'modules/';
        break;
      default:
        feedback.warn('CM Toolset ' + process.env.CM_TYPE + ' is not currently supported or available.');
        break;
    }

    this.fs.writeJSON('packer.json', packerDictionary);
  },

  default: {
    saveConfig: function() {
      _.forOwn(this.answers, function(value, key) {
        this.config.set(key, value);
      })
    }
  },

  install: function() {
    this.installDependencies();
  }
});

module.exports = BakeryBake;
<commit_msg>refactor bake generator to be able to use prompt responses in later validation steps<commit_after>'use strict';
const yeoman = require('yeoman-generator'),
  chalk = require('chalk'),
  yosay = require('yosay'),
  bakery = require('../../lib/bakery'),
  feedback = require('../../lib/feedback'),
  debug = require('debug')('bakery:generators:bake:index'),
  _ = require('lodash');

const AWS_REGIONS = [{
  name: 'us-east-1'
}, {
  name: 'us-east-2'
}, {
  name: 'us-west-1'
}, {
  name: 'us-west-2'
}, {
  name: 'ap-south-1'
}, {
  name: 'ap-northeast-1'
}, {
  name: 'ap-southeast-1'
}, {
  name: 'ap-southeast-2'
}, {
  name: 'ap-northeast-1'
}, {
  name: 'eu-central-1'
}, {
  name: 'eu-west-1'
}, {
  name: 'sa-east-1'
}];
const AWS_INSTANCE_TYPES = ['t2.nano', 't2.micro', 't2.small', 't2.medium', 't2.large', 'm4.large', 'm4.xlarge', 'm4.2xlarge', 'm4.4xlarge', 'm4.8xlarge', 'm4.16xlarge', 'c4.large', 'c4.xlarge', 'c4.2xlarge', 'c4.4xlarge', 'c4.8xlarge'];

var BakeryBake = yeoman.Base.extend({

  constructor: function() {
    yeoman.Base.apply(this, arguments);

    this._options.help.desc = 'Show this help';

    /** @property {object} answers - prompt answers */
    this.answers = {};

    this.option('projectname', {
      desc: 'Name of the project being created',
      type: String,
      alias: 'n'
    });

    this.option('awsprofile', {
      type: String,
      alias: 'p',
      desc: 'Name of the AWS profile to use when calling the AWS api for value validation'
    });
  },

  prompting: function() {
    // preserve 'this' reference across scopes
    var _this = this
    this.log(bakery.banner('Bakery Setup!'));

    // The primary region is needed in order to validate AMI ID. In order to access primary region the prompts
    // must be run and their results processed. For this reason the prompts are split into two groups:
    //    initialPrompts - these run to gather everything up to primary region
    //    prompts - all remaining prompts
    //
    // This required a few accomodations:
    //   1) numerous anonymous handler functions are supplied in the prompts below. 'this' is captured as '_this'
    //      to ensure the proper identity object is available across function scopes.
    //
    //   2) all prompt values must be stored somewhere on the generator object. The handler function for prompt
    //      results therefore simply adds prompt values to _this.options
    //
    //   3) this.prompt is async and returns a Promise. To ensure initialPrompts have been processed before the
    //      remaining prompts, the call to this.prompt for the remainder is nested in a call to .then() on the
    //      Promise returned from the first this.prompt call.

    // define initial prompts
    var initialPrompts = [{
      type: "confirm",
      name: "createami",
      message: "Create Amazon Machine Image?",
      default: true
    }, {
      type: 'input',
      name: 'aminame',
      message: 'Name for this AMI:',
      default: function() {
        return process.env.PROJECTNAME + ' {{timestamp}}'
      },
      when: function(response) {
        return response.createami && process.env.PROJECTNAME;
      }
    }, {
      type: 'input',
      name: 'amidescription',
      message: 'Enter a description for this AMI:',
      when: function(response) {
        return response.createami;
      }
    }, {
      type: "checkbox",
      name: "awsregions",
      message: "Choose AWS Region(s) for creation",
      choices: AWS_REGIONS,
      when: function(response) {
        return response.createami;
      },
      default: process.env.AWS_REGION || 'us-west-2',
      validate: function(response) {
        if (response.length < 0) {
          return 'You must choose at least one AWS Region.';
        }
        return true;
      }
    }, {
      type: 'list',
      name: 'primaryregion',
      message: 'Choose a primary region for building in AWS:',
      when: function(response) {
        if (response.awsregions.length == 1) {
          _this.options['primaryregion'] = response.awsregions[0]
        }
        return (response.awsregions.length > 1);
      },
      choices: function(response) {
        return response.awsregions;
      },
      default: function(response) {
        if (response.awsregions.indexOf('us-west-2') > -1) {
          return 'us-west-2';
        } else {
          return response.awsregions[0];
        }
      }
    }];

    // this runs the first set of prompts and returns the resulting Promise to cause the Yeoman
    //  run loop to pause until prompts are complete
    return this.prompt(initialPrompts).then(function(responses) {

      // copy responses into this.options
      for(var response in responses) {
        if (responses.hasOwnProperty(response)) {
          _this.options[response] = responses[response];
        }
      }

      // define the remaining prompts
      var prompts = [{
        type: 'list',
        name: 'buildimagetype',
        message: 'Instance Type for build:',
        default: 't2.large',
        choices: AWS_INSTANCE_TYPES,
        when: function(response) {
          return _this.options.createami;
        }
      }, {
        type: 'input',
        name: 'regionspecificami',
        message: function(response) {
          return 'AMI ID in ' + _this.options.primaryregion + ' region:';
        },
        when: function(response) {
          return _this.options.createami;
        },
        validate: function(response) {
          // validate that the AMI exists - send primary region; for profile defualt to:
          //    1) --awsprofile/-p argument
          //    2) Environment variable AWS_POFILE
          //    3) default
          return bakery.validateAMIId(response, {
            awsregion: _this.options.primaryregion,
            awsprofile: _this.options.awsprofile || process.env.AWS_PROFILE || 'default'
          }).then(function(successful) {
            return successful;
          });
        }
      }, {
        type: 'confirm',
        name: 'iswindows',
        message: 'Is this a Windows-based image:',
        default: false,
        when: function(response) {
          return _this.options.createami && !process.env.WINDOWSIMAGE;
        }
      }, {
        type: 'input',
        name: 'amigroups',
        message: 'Enter a list (comma separated) of groups to share this AMI with:',
        when: function(response) {
          return _this.options.createami;
        }
      }, {
        type: 'input',
        name: 'amiusers',
        message: 'Enter a list of (comma separated) account id\'s to share this AMI with:',
        when: function(response) {
          return _this.options.createami;
        }
      }, {
        type: 'input',
        name: 'iaminstanceprofile',
        message: 'Enter the IAM instance profile id you want to apply to instances while they are being built:',
        when: function(response) {
          return _this.options.createami;
        }
      }, {
        type: 'input',
        name: 'vpcid',
        message: 'Enter VPC ID, leave blank for default VPC:',
        when: function(response) {
          return _this.options.createami;
        }
      }, {
        type: 'input',
        name: 'subnetid',
        message: 'Enter subnet id - Required for non-default VPC ID:',
        when: function(response) {
          return _this.options.createami && response.vpcid.length > 0;
        }
      }, {
        type: 'input',
        name: 'securitygroupids',
        message: 'Enter security group ids (comma separated) - required for non-default VPC ID:',
        when: function(response) {
          return _this.options.createami && response.vpcid.length > 0;
        }
      }];
      return _this.prompt(prompts).then(function(props) {
        for(var prop in props) {
          if (props.hasOwnProperty(prop)) {
            _this.options[prop] = props[prop];
          }
        }
        switch (process.env.CI_TYPE) {
          case 'drone':
            //do something
            break;
          case 'jenkins':
            //do something
            break;
          default:
            _this.log('CI toolset ' + process.env.CI_TYPE + ' is not currently available. Skipping CI script setup');
            break;
        }
      }.bind(_this));
    });
  },
  writing: function() {
    var packerDictionary = {
      variables: {
        aws_access_key: "{{ env 'AWS_ACCESS_KEY_ID' }}",
        aws_secret_key: "{{ env 'AWS_SECRET_ACCESS_KEY' }}",
        instance_type: this.options.buildimagetype
      },
      builders: [],
      provisioners: []
    };

    packerDictionary.builders[0] = {};

    packerDictionary.builders[0].type = "amazon-ebs";
    packerDictionary.builders[0].access_key = "{{ user `aws_access_key` }}";
    packerDictionary.builders[0].secret_key = "{{ user `aws_secret_key` }}";
    packerDictionary.builders[0].ami_name = this.options.aminame || process.env.PROJECTNAME + ' {{timestamp}}';
    packerDictionary.builders[0].instance_type = "{{ user `instance_type` }}";
    packerDictionary.builders[0].region = this.option.primaryregion;
    packerDictionary.builders[0].source_ami = this.options.regionspecificami;

    if (this.options.awsregions.length > 1) {
      packerDictionary.builders[0]['ami_regions'] = [];
      this.options.awsregions.forEach(function(element) {
        if (element != this.options.primaryregion) {
          packerDictionary.builders[0]['ami_regions'].push(element);
        }
      }.bind(this));
    };
    if (typeof this.options.amidescription !== 'undefined' && this.options.amidescription.length > 0) {
      packerDictionary.builders[0]['ami_description'] = this.options.amidescription;
    };
    if (typeof this.options.amigroups !== 'undefined' && this.options.amigroups.length > 0) {
      packerDictionary.builders[0]['ami_groups'] = this.options.amigroups.split(',');
    };
    if (typeof this.options.amiusers !== 'undefined' && this.options.amiusers.length > 0) {
      packerDictionary.builders[0]['ami_users'] = this.options.amiusers.split(',');
    }
    if (typeof this.options.vpcid !== 'undefined' && this.options.vpcid.length > 0) {
      packerDictionary.builders[0]['vpc_id'] = this.options.vpcid;
    };
    if (typeof this.options.subnetid !== 'undefined' && this.options.subnetid.length > 0) {
      packerDictionary.builders[0]['subnet_id'] = this.options.subnetid;
    };
    if (typeof this.options.securitygroupids !== 'undefined' && this.options.securitygroupids.length > 0) {
      buildpackerDictionary.builders[0]['security_group_ids'] = this.options.securitygroupids.split(',');
    };
    if (typeof this.options.iaminstanceprofile !== 'undefined' && this.options.iaminstanceprofile.length > 0) {
      packerDictionary.builders[0]['iam_instance_profile'] = this.options.iaminstanceprofile;
    };

    packerDictionary.provisioners[0] = {}

    var osType = 'unix';
    if (process.env.WINDOWSIMAGE || this.options.iswindows) {
      osType = 'windows';
    };

    switch (process.env.CM_TYPE) {
      case 'chef':
        packerDictionary.provisioners[0]['type'] = 'chef-solo';
        packerDictionary.provisioners[0]['cookbook_paths'] = ['../'];
        packerDictionary.provisioners[0]['guest_os_type'] = osType;
        break;
      case 'puppet':
        packerDictionary.provisioners[0]['type'] = 'puppet-masterless';
        packerDictionary.provisioners[0]['manifest_file'] = 'manifests/';
        primarpackerDictionary.provisioners[0]['hiera_config_path'] = 'hiera.yaml';
        packerDictionary.provisioners[0]['module_paths'] = 'modules/';
        break;
      default:
        feedback.warn('CM Toolset ' + process.env.CM_TYPE + ' is not currently supported or available.');
        break;
    }

    this.fs.writeJSON('packer.json', packerDictionary);
  },

  default: {
    saveConfig: function() {
      _.forOwn(this.answers, function(value, key) {
        this.config.set(key, value);
      })
    }
  },

  install: function() {
    this.installDependencies();
  }
});

module.exports = BakeryBake;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { EntitySetList } from '../../components/entityset/EntitySetList';
import { createEntitySetListRequest } from './CatalogActionFactories';
import AsyncContent from '../../components/asynccontent/AsyncContent';

class CatalogComponent extends React.Component {
  static propTypes = {
    asyncState: PropTypes.object.isRequired,
    entitySets: PropTypes.array.isRequired,
    requestEntitySets: PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);
  }

  render() {
    return (

Catalog

        <AsyncContent {...this.props.asyncState}>
          <EntitySetList entitySets={this.props.entitySets}/>
        </AsyncContent>

    );
  }

  componentDidMount() {
    this.props.requestEntitySets();
  }
}

function mapStateToProps(state) {
  return state.get('catalog');
}

function mapDispatchToProps(dispatch) {
  return {
    requestEntitySets: () => { dispatch(createEntitySetListRequest()) }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CatalogComponent);<commit_msg>fixed catalogComponent propTypes<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { EntitySetList } from '../../components/entityset/EntitySetList';
import { EntitySetPropType } from '../../components/entityset/EntitySet';
import { createEntitySetListRequest } from './CatalogActionFactories';
import AsyncContent from '../../components/asynccontent/AsyncContent';

class CatalogComponent extends React.Component {
  static propTypes = {
    asyncState: PropTypes.shape({
      isLoading: PropTypes.bool.isRequired,
      errorMessage: PropTypes.string
    }).isRequired,
    entitySets: PropTypes.arrayOf(EntitySetPropType).isRequired,
    requestEntitySets: PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);
  }

  render() {
    return (

Catalog

        <AsyncContent {...this.props.asyncState}>
          <EntitySetList entitySets={this.props.entitySets}/>
        </AsyncContent>

    );
  }

  componentDidMount() {
    this.props.requestEntitySets();
  }
}

function mapStateToProps(state) {
  return state.get('catalog');
}

function mapDispatchToProps(dispatch) {
  return {
    requestEntitySets: () => { dispatch(createEntitySetListRequest()) }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CatalogComponent);<|endoftext|>