<commit_before>/**
 * The EvalSystem set of functions (keeps the namespace clean and tidy) -AZ
 * DEPENDS on jQuery 1.2 to operate
 * @author Antranig Basman
 * @author Aaron Zeckoski (aaronz@vt.edu)
 */
var EvalSystem = function() {
  function $it(elementID) {
    return document.getElementById(elementID);
  }

  /**
   * Because JQuery uses this sort of CSS based selector system, if you have
   * wacky characters in your tag ID (such as RSF Colons) you have to escape
   * them. At the moment this just escapes the colons, should probably have a
   * fuller (or automatic) jquery escaping mechanism.
   */
  function escIdForJquery(value) {
    return value != null ? "#" + value.replace(/:/g, "\\:") : null;
  }

  return {

    /**
     *  A little bit of javascript to validate the Eval Assign Page. At the
     *  moment this is only for making sure users have selected at least one
     *  group or hierarchy node or something.
     *
     * @errorDivId A Div with an already translated message we can light up.
     * @submitButtonId The button that is doing the submitting.
     */
    initEvalAssignValidation: function(formId, errorDivId, submitButtonId) {
        var form = $(escIdForJquery(formId));
        var errorDiv = $(escIdForJquery(errorDivId));
        var submitButton = $(escIdForJquery(submitButtonId));

        // Boolean to store whether the form should submit based on validation.
        var passes = false;

        form.submit(function() {
            if (!passes) {
                errorDiv.show();
                RSF.getDOMModifyFirer().fireEvent();
            }
            return passes;
        });

        var onAssignClick = function(event) {
            passes = false;
            var n = $(".evalgroupselect:checked").length;
            if (n > 0) {
                passes=true;
            }
        }

        submitButton.click( function(event) { onAssignClick(event) } );
    },

    initEvalReportView: function (allCommentsId, allTextResponsesId) {
        // for now this is just enabling toggling of comments and responses
        // see the makeToggle method for description of arguments
        if (allCommentsId.length > 0) {
            $(escIdForJquery(allCommentsId)).show();
            EvalSystem.makeToggle(allCommentsId + "Show", allCommentsId + "Hide", null, "showcomments", false);
        }
        if (allTextResponsesId.length > 0) {
            $(escIdForJquery(allTextResponsesId)).show();
            EvalSystem.makeToggle(allTextResponsesId + "Show", allTextResponsesId + "Hide", null, "showtextresponses", false);
        }
    },

    /**
     * This will hide an area (or a set areas that match the toggleClass)
     * when the element with hideId is clicked (it will also be hidden),
     * it will show the area(s) and the hideId element when the element with showId is clicked,
     * and also hide the showId element
     * showId: the id of the element that triggers the show when clicked
     * hideId: the id of the element that triggers the hide when clicked
     * areaId: the id of area (div probably) to show/hide, set null if not used
     * toggleClass: a classname such that all elements with this class will be shown/hidden, set null if not used
     * initialHide: if true then start things hidden, else start things shown (default if unspecified)
     */
    makeToggle: function (showId, hideId, areaId, toggleClass, initialHide) {
        var showButton = $(escIdForJquery(showId));
        var hideButton = $(escIdForJquery(hideId));
        var area = $(escIdForJquery(areaId));
        var toggles = $(toggleClass == null ? null : "." + toggleClass);

        showButton.show();
        hideButton.show();

        var showAction = function(event) {
            showButton.hide();
            hideButton.show();
            area.show("normal");
            toggles.show("normal");
            RSF.getDOMModifyFirer().fireEvent();
        }

        var hideAction = function(event) {
            showButton.show();
            hideButton.hide();
            area.hide("normal");
            toggles.hide("normal");
            RSF.getDOMModifyFirer().fireEvent();
        }

        if (initialHide) {
            hideAction();
        } else {
            showAction();
        }

        showButton.click( function (event) { showAction(event) });
        hideButton.click( function (event) { hideAction(event) });
    },

    // this just makes it easier to add in more stuff later -AZ
    initEvalSettings: function (areaId, selectId, selectValue, reminderId) {
        // see the toggleAndDisableSetReminder method for description of arguments
        EvalSystem.toggleAndDisableSetReminder(areaId, selectId, selectValue, reminderId);
    },

    /**
     * This will hide and disable the setReminder option area
     * and force the setting to 0 reminders on the evaluation settings page
     * when the anonymous auth option is selected OR reveal the option area
     * areaId: the id of area (div probably) to show/hide
     * selectId: the id of the select that triggers the show/hide
     * selectValue: the value of the select that causes the hide action (other cause show)
     * reminderId: the id of the form control to set when hide action happens
     */
    toggleAndDisableSetReminder: function (areaId, selectId, selectValue, reminderId) {
        var area = $("#"+areaId); //document.getElementById(areaId);
        var select = $("#"+selectId); //document.getElementById(selectId);
        var reminder = $("#"+reminderId); //document.getElementById(reminderId);

        var changeAction = function(event) {
            var selectedValue = event.target.value;
            if (selectedValue == selectValue) {
                // values are the same so we need to hide things
                // only take action if needed so we are not resetting the field constantly
                if ( area.is(':visible') ) {
                    // area is currently visible so hide it
                    area.hide("normal");
                    // force reminder to the no reminders setting of 0
                    reminder.val('0');
                }
            } else {
                // set to one of the non-hiding options
                if ( area.is(':hidden') ) {
                    // area is currently hidden so reveal it
                    area.show("slow");
                }
            }
        }
        // add the event for onchange to trigger the changeAction method and cause it to fire immediately
        select.change( function(event) { changeAction(event) }).change();
    },

    getRelativeID: function (baseid, targetid) {
      colpos = baseid.lastIndexOf(':');
      return baseid.substring(0, colpos + 1) + targetid;
    },

   // See http://www.pageresource.com/jscript/jdropbox.htm for general approach
    operateSelectLink: function(linkid, localselectid) {
      var selectid = EvalSystem.getRelativeID(linkid, localselectid);
      var selection = $it(selectid);
      var url = selection.options[selection.selectedIndex].value;
      // See http://www.quirksmode.org/js/iframe.html for discussion
      document.location.href = url;
    },

    decorateReorderSelects: function(namebase, count) {
      var buttonid = namebase + "hiddenBtn";
      var button = $it(buttonid);
      for (var i = 0; i < count; ++ i) {
        var selectid = namebase + "item-row:"+i+":item-select-selection";
        var selection = $it(selectid);
        selection.onchange = function() {
        	button.click();
        };
      }
    }

  }
}();<commit_msg>CTL-1242: make toggle work on the whole of the text<commit_after>/**
 * The EvalSystem set of functions (keeps the namespace clean and tidy) -AZ
 * DEPENDS on jQuery 1.2 to operate
 * @author Antranig Basman
 * @author Aaron Zeckoski (aaronz@vt.edu)
 */
var EvalSystem = function() {
  function $it(elementID) {
    return document.getElementById(elementID);
  }

  /**
   * Because JQuery uses this sort of CSS based selector system, if you have
   * wacky characters in your tag ID (such as RSF Colons) you have to escape
   * them. At the moment this just escapes the colons, should probably have a
   * fuller (or automatic) jquery escaping mechanism.
   */
  function escIdForJquery(value) {
    return value != null ? "#" + value.replace(/:/g, "\\:") : null;
  }

  return {

    /**
     *  A little bit of javascript to validate the Eval Assign Page. At the
     *  moment this is only for making sure users have selected at least one
     *  group or hierarchy node or something.
     *
     * @errorDivId A Div with an already translated message we can light up.
     * @submitButtonId The button that is doing the submitting.
     */
    initEvalAssignValidation: function(formId, errorDivId, submitButtonId) {
        var form = $(escIdForJquery(formId));
        var errorDiv = $(escIdForJquery(errorDivId));
        var submitButton = $(escIdForJquery(submitButtonId));

        // Boolean to store whether the form should submit based on validation.
        var passes = false;

        form.submit(function() {
            if (!passes) {
                errorDiv.show();
                RSF.getDOMModifyFirer().fireEvent();
            }
            return passes;
        });

        var onAssignClick = function(event) {
            passes = false;
            var n = $(".evalgroupselect:checked").length;
            if (n > 0) {
                passes=true;
            }
        }

        submitButton.click( function(event) { onAssignClick(event) } );
    },

    initEvalReportView: function (allCommentsId, allTextResponsesId) {
        // for now this is just enabling toggling of comments and responses
        // see the makeToggle method for description of arguments
        if (allCommentsId.length > 0) {
            $(escIdForJquery(allCommentsId)).show();
            EvalSystem.makeToggle(allCommentsId + "Show", allCommentsId + "Hide", null, "showcomments", false);
        }
        if (allTextResponsesId.length > 0) {
            $(escIdForJquery(allTextResponsesId)).show();
            EvalSystem.makeToggle(allTextResponsesId + "Show", allTextResponsesId + "Hide", null, "showtextresponses", false);
        }
    },

    /**
     * This will hide an area (or a set areas that match the toggleClass)
     * when the element with hideId is clicked (it will also be hidden),
     * it will show the area(s) and the hideId element when the element with showId is clicked,
     * and also hide the showId element
     * showId: the id of the element that triggers the show when clicked
     * hideId: the id of the element that triggers the hide when clicked
     * areaId: the id of area (div probably) to show/hide, set null if not used
     * toggleClass: a classname such that all elements with this class will be shown/hidden, set null if not used
     * initialHide: if true then start things hidden, else start things shown (default if unspecified)
     */
    makeToggle: function (showId, hideId, areaId, toggleClass, initialHide) {
        var showButton = $(escIdForJquery(showId));
        var hideButton = $(escIdForJquery(hideId));
        var area = $(escIdForJquery(areaId));
        var toggles = $(toggleClass == null ? null : "." + toggleClass);

        var togglearea = showButton.parent().parent();
        showButton.show();
        hideButton.show();

        var showAction = function(event) {
            showButton.hide();
            hideButton.show();
            area.show("normal");
            toggles.show("normal");
            RSF.getDOMModifyFirer().fireEvent();
        }

        var hideAction = function(event) {
            showButton.show();
            hideButton.hide();
            area.hide("normal");
            toggles.hide("normal");
            RSF.getDOMModifyFirer().fireEvent();
        }

        if (initialHide) {
            hideAction();
        } else {
            showAction();
        }

        var toggle = function(event) {
        	showButton.toggle();
        	hideButton.toggle();
        	area.toggle("normal");
        	toggles.toggle("normal");
        	RSF.getDOMModifyFirer().fireEvent();
        }

        togglearea.click( function (event) { toggle(event) } );

        /*showButton.click( function (event) { showAction(event) });
        hideButton.click( function (event) { hideAction(event) });*/
    },

    // this just makes it easier to add in more stuff later -AZ
    initEvalSettings: function (areaId, selectId, selectValue, reminderId) {
        // see the toggleAndDisableSetReminder method for description of arguments
        EvalSystem.toggleAndDisableSetReminder(areaId, selectId, selectValue, reminderId);
    },

    /**
     * This will hide and disable the setReminder option area
     * and force the setting to 0 reminders on the evaluation settings page
     * when the anonymous auth option is selected OR reveal the option area
     * areaId: the id of area (div probably) to show/hide
     * selectId: the id of the select that triggers the show/hide
     * selectValue: the value of the select that causes the hide action (other cause show)
     * reminderId: the id of the form control to set when hide action happens
     */
    toggleAndDisableSetReminder: function (areaId, selectId, selectValue, reminderId) {
        var area = $("#"+areaId); //document.getElementById(areaId);
        var select = $("#"+selectId); //document.getElementById(selectId);
        var reminder = $("#"+reminderId); //document.getElementById(reminderId);

        var changeAction = function(event) {
            var selectedValue = event.target.value;
            if (selectedValue == selectValue) {
                // values are the same so we need to hide things
                // only take action if needed so we are not resetting the field constantly
                if ( area.is(':visible') ) {
                    // area is currently visible so hide it
                    area.hide("normal");
                    // force reminder to the no reminders setting of 0
                    reminder.val('0');
                }
            } else {
                // set to one of the non-hiding options
                if ( area.is(':hidden') ) {
                    // area is currently hidden so reveal it
                    area.show("slow");
                }
            }
        }
        // add the event for onchange to trigger the changeAction method and cause it to fire immediately
        select.change( function(event) { changeAction(event) }).change();
    },

    getRelativeID: function (baseid, targetid) {
      colpos = baseid.lastIndexOf(':');
      return baseid.substring(0, colpos + 1) + targetid;
    },

   // See http://www.pageresource.com/jscript/jdropbox.htm for general approach
    operateSelectLink: function(linkid, localselectid) {
      var selectid = EvalSystem.getRelativeID(linkid, localselectid);
      var selection = $it(selectid);
      var url = selection.options[selection.selectedIndex].value;
      // See http://www.quirksmode.org/js/iframe.html for discussion
      document.location.href = url;
    },

    decorateReorderSelects: function(namebase, count) {
      var buttonid = namebase + "hiddenBtn";
      var button = $it(buttonid);
      for (var i = 0; i < count; ++ i) {
        var selectid = namebase + "item-row:"+i+":item-select-selection";
        var selection = $it(selectid);
        selection.onchange = function() {
        	button.click();
        };
      }
    }

  }
}();<|endoftext|>


<commit_before>//=============================================================================
// SkipPartyCommand.js
// ----------------------------------------------------------------------------
// Copyright (c) 2017-2018 Tsumio
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// ----------------------------------------------------------------------------
// Version
// 1.0.4 2018/01/04 アクターコマンドに逃げるコマンドを追加。
// 1.0.3 2018/01/02 パーティー先頭に行動不能アクターが存在した場合の不具合を修正。
// 1.0.2 2017/08/16 さらに微調整。
// 1.0.1 2017/08/16 スキップの判定を微調整。
// 1.0.0 2017/08/16 公開。
// ----------------------------------------------------------------------------
// [GitHub] : https://github.com/Tsumio/rmmv-plugins
// [Blog]   : http://ntgame.wpblog.jp/
// [Twitter]: https://twitter.com/TsumioNtGame
//=============================================================================

/*:
 * @plugindesc This plugin skip party command in battle.
 * @author Tsumio
 *
 * @param SwitchNumberForSkipping
 * @type switch
 * @desc If this switch is on, party command is skipped.
 * @default 1
 *
 * @param SwitchNumberForEscapeCommand
 * @type switch
 * @desc If this switch is on, show escape command to actor command window.
 * @default 2
 *
 * @help This plugin skip party command in battle.
 *
 * ----how to use----
 * You can use this plugin after setting SwitchNumberForSkipping and SwitchNumberForEscapeCommand parameters.
 *
 * ----plugin command----
 * There is no plugin command.
 *
 *
 * ----change log---
 * 1.0.4 2018/01/04 Add escape command to acttor command window.
 * 1.0.3 2018/01/02 Fixed a bug when a inactivity actor is at the beginning of the party.
 * 1.0.2 2017/08/16 More Adjustment.
 * 1.0.1 2017/08/16 Adjustment of skip judgment.
 * 1.0.0 2017/08/16 Release
 *
 * ----remarks----
 * I shall not be responsible for any loss, damages and troubles from using this plugin.
 *
 * --Terms of Use--
 * This plugin is free for both commercial and non-commercial use.
 * You may edit the source code to suit your needs,
 * so long as you don't claim the source code belongs to you.
 *
 */
/*:ja
 * @plugindesc 戦闘時のパーティーコマンドをスキップします。
 * @author ツミオ
 *
 * @param スキップ用のスイッチ番号
 * @type switch
 * @desc このスイッチ番号がONのとき、パーティーコマンドはスキップされます。
 * @default 1
 *
 * @param 逃げるコマンド表示用のスイッチ番号
 * @type switch
 * @desc このスイッチ番号がONのとき、アクターコマンドに逃げるコマンドが追加されます。
 * @default 2
 *
 * @help 戦闘時のパーティーコマンドをスキップします。
 *
 *
 *
 * 【使用方法】
 * プラグインの導入後、スキップ用のスイッチ番号および逃げるコマンド表示用のスイッチ番号を設定することによって使用できます。
 *
 *
 * 【プラグインコマンド】
 * このプラグインにプラグインコマンドはありません。
 *
 * 【更新履歴】
 * 1.0.4 2018/01/04 アクターコマンドに逃げるコマンドを追加。
 * 1.0.3 2018/01/02 パーティー先頭に行動不能アクターが存在した場合の不具合を修正。
 * 1.0.2 2017/08/16 さらに微調整。
 * 1.0.1 2017/08/16 スキップの判定を微調整。
 * 1.0.0 2017/08/16 公開。
 *
 * 【備考】
 * 当プラグインを利用したことによるいかなる損害に対しても、制作者は一切の責任を負わないこととします。
 *
 * 【利用規約】
 * ソースコードの著作権者が自分であると主張しない限り、
 * 作者に無断で改変、再配布が可能です。
 * 利用形態（商用、18禁利用等）についても制限はありません。
 * 自由に使用してください。
 *
 */

(function() {
    'use strict';
    var pluginName = 'SkipPartyCommand';

////=============================================================================
//// NTMO
////  Declare NTMO namespace.
////=============================================================================
    var NTMO = NTMO || {};
    NTMO.SPC = function(){
    };

////=============================================================================
//// Local function
////  These functions checks & formats pluguin's command parameters.
////  I borrowed these functions from Triacontane.Thanks!
////=============================================================================
    var getParamString = function(paramNames) {
        if (!Array.isArray(paramNames)) paramNames = [paramNames];
        for (var i = 0; i < paramNames.length; i++) {
            var name = PluginManager.parameters(pluginName)[paramNames[i]];
            if (name) return name;
        }
        return '';
    };

    var getParamNumber = function(paramNames, min, max) {
        var value = getParamString(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(value) || 0).clamp(min, max);
    };

    //This function is not written by Triacontane.Tsumio wrote this function !
    var getParamDouble = function(paramNames, min, max) {
        var value = getParamString(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return Number(value);
    };

    //This function is not written by Triacontane.Tsumio wrote this function !
    var convertParam = function(param) {
        if(param !== undefined){
            try {
                return JSON.parse(param);
            }catch(e){
                console.group();
                console.error('%cParameter is invalid ! You should check the following parameter !','background-color: #5174FF');
                console.error('Parameter:' + eval(param));
                console.error('Error message :' + e);
                console.groupEnd();
            }
        }
    };

////=============================================================================
//// Get and set pluguin parameters.
////=============================================================================
    var param                          = {};
    param.switchNum_skipping           = getParamNumber(['SwitchNumberForSkipping', 'スキップ用のスイッチ番号']);
    param.switchNum_escapeCommand      = getParamNumber(['SwitchNumberForEscapeCommand', '逃げるコマンド表示用のスイッチ番号']);

////==============================
//// Convert parameters.
////==============================

    //There is none.

//////=============================================================================
///// Scene_Battle
/////  Add skipping system to battle scene.
////   Override some methods for skipping always.
/////=============================================================================

    const _Scene_Battle_changeInputWindow = Scene_Battle.prototype.changeInputWindow;
    Scene_Battle.prototype.changeInputWindow = function() {
        if(this.skipPartyCommand_SPC()){//If return true, it means be skipped.
            return;
        }

        _Scene_Battle_changeInputWindow.call(this);
    };

    //This is additional method.
    Scene_Battle.prototype.skipPartyCommand_SPC = function() {
        if (this.canSkipPartyCommand_SPC()) {
            BattleManager.selectNextCommand();//Instead of commandFight().
            this.startActorCommandSelection();
            return true;//Be skipped.
        }
        return false;
    };

    //This is additional method.
    Scene_Battle.prototype.isSkippableSwitchOn_SPC = function() {
        return $gameSwitches.value(param.switchNum_skipping);
    };

    //This is additional method.
    Scene_Battle.prototype.canSkipPartyCommand_SPC = function() {
        return this.isSkippableSwitchOn_SPC() && BattleManager.isInputting() && !BattleManager.actor();
    };

    const _Scene_Battle_createActorCommandWindow = Scene_Battle.prototype.createActorCommandWindow;
    Scene_Battle.prototype.createActorCommandWindow = function() {
        _Scene_Battle_createActorCommandWindow.call(this);
        this._actorCommandWindow.setHandler('escape', this.commandEscape.bind(this));
    };

//////=============================================================================
///// Window_ActorCommand
/////  Add escapeCommand.
/////=============================================================================
    const _Window_ActorCommand_changeInputWindow = Window_ActorCommand.prototype.makeCommandList;
    Window_ActorCommand.prototype.makeCommandList = function() {
        _Window_ActorCommand_changeInputWindow.call(this);
        if(this._actor) {
            this.addEscapeCommand();
        }
    };

    Window_ActorCommand.prototype.addEscapeCommand = function() {
        if(this.isEscapeCommandSwitchOn_SPC()) {
            this.addCommand(TextManager.escape, 'escape', BattleManager.canEscape());
        }
    };

    Window_ActorCommand.prototype.isEscapeCommandSwitchOn_SPC = function() {
        return $gameSwitches.value(param.switchNum_escapeCommand);
    };

})();
<commit_msg>Update:Fixed to refresh the status window also on turn 0.<commit_after>//=============================================================================
// SkipPartyCommand.js
// ----------------------------------------------------------------------------
// Copyright (c) 2017-2018 Tsumio
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// ----------------------------------------------------------------------------
// Version
// 1.0.5 2018/07/25 0ターン目もステータスウィンドウをリフレッシュするよう修正。
// 1.0.4 2018/01/04 アクターコマンドに逃げるコマンドを追加。
// 1.0.3 2018/01/02 パーティー先頭に行動不能アクターが存在した場合の不具合を修正。
// 1.0.2 2017/08/16 さらに微調整。
// 1.0.1 2017/08/16 スキップの判定を微調整。
// 1.0.0 2017/08/16 公開。
// ----------------------------------------------------------------------------
// [GitHub] : https://github.com/Tsumio/rmmv-plugins
// [Blog]   : http://ntgame.wpblog.jp/
// [Twitter]: https://twitter.com/TsumioNtGame
//=============================================================================

/*:
 * @plugindesc This plugin skip party command in battle.
 * @author Tsumio
 *
 * @param SwitchNumberForSkipping
 * @type switch
 * @desc If this switch is on, party command is skipped.
 * @default 1
 *
 * @param SwitchNumberForEscapeCommand
 * @type switch
 * @desc If this switch is on, show escape command to actor command window.
 * @default 2
 *
 * @help This plugin skip party command in battle.
 *
 * ----how to use----
 * You can use this plugin after setting SwitchNumberForSkipping and SwitchNumberForEscapeCommand parameters.
 *
 * ----plugin command----
 * There is no plugin command.
 *
 *
 * ----change log---
 * 1.0.5 2018/07/25 Fixed to refresh the status window also on turn 0.
 * 1.0.4 2018/01/04 Add escape command to acttor command window.
 * 1.0.3 2018/01/02 Fixed a bug when a inactivity actor is at the beginning of the party.
 * 1.0.2 2017/08/16 More Adjustment.
 * 1.0.1 2017/08/16 Adjustment of skip judgment.
 * 1.0.0 2017/08/16 Release
 *
 * ----remarks----
 * I shall not be responsible for any loss, damages and troubles from using this plugin.
 *
 * --Terms of Use--
 * This plugin is free for both commercial and non-commercial use.
 * You may edit the source code to suit your needs,
 * so long as you don't claim the source code belongs to you.
 *
 */
/*:ja
 * @plugindesc 戦闘時のパーティーコマンドをスキップします。
 * @author ツミオ
 *
 * @param スキップ用のスイッチ番号
 * @type switch
 * @desc このスイッチ番号がONのとき、パーティーコマンドはスキップされます。
 * @default 1
 *
 * @param 逃げるコマンド表示用のスイッチ番号
 * @type switch
 * @desc このスイッチ番号がONのとき、アクターコマンドに逃げるコマンドが追加されます。
 * @default 2
 *
 * @help 戦闘時のパーティーコマンドをスキップします。
 *
 *
 *
 * 【使用方法】
 * プラグインの導入後、スキップ用のスイッチ番号および逃げるコマンド表示用のスイッチ番号を設定することによって使用できます。
 *
 *
 * 【プラグインコマンド】
 * このプラグインにプラグインコマンドはありません。
 *
 * 【更新履歴】
 * 1.0.5 2018/07/25 0ターン目もステータスウィンドウをリフレッシュするよう修正。
 * 1.0.4 2018/01/04 アクターコマンドに逃げるコマンドを追加。
 * 1.0.3 2018/01/02 パーティー先頭に行動不能アクターが存在した場合の不具合を修正。
 * 1.0.2 2017/08/16 さらに微調整。
 * 1.0.1 2017/08/16 スキップの判定を微調整。
 * 1.0.0 2017/08/16 公開。
 *
 * 【備考】
 * 当プラグインを利用したことによるいかなる損害に対しても、制作者は一切の責任を負わないこととします。
 *
 * 【利用規約】
 * ソースコードの著作権者が自分であると主張しない限り、
 * 作者に無断で改変、再配布が可能です。
 * 利用形態（商用、18禁利用等）についても制限はありません。
 * 自由に使用してください。
 *
 */

(function() {
    'use strict';
    var pluginName = 'SkipPartyCommand';

////=============================================================================
//// NTMO
////  Declare NTMO namespace.
////=============================================================================
    var NTMO = NTMO || {};
    NTMO.SPC = function(){
    };

////=============================================================================
//// Local function
////  These functions checks & formats pluguin's command parameters.
////  I borrowed these functions from Triacontane.Thanks!
////=============================================================================
    var getParamString = function(paramNames) {
        if (!Array.isArray(paramNames)) paramNames = [paramNames];
        for (var i = 0; i < paramNames.length; i++) {
            var name = PluginManager.parameters(pluginName)[paramNames[i]];
            if (name) return name;
        }
        return '';
    };

    var getParamNumber = function(paramNames, min, max) {
        var value = getParamString(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(value) || 0).clamp(min, max);
    };

    //This function is not written by Triacontane.Tsumio wrote this function !
    var getParamDouble = function(paramNames, min, max) {
        var value = getParamString(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return Number(value);
    };

    //This function is not written by Triacontane.Tsumio wrote this function !
    var convertParam = function(param) {
        if(param !== undefined){
            try {
                return JSON.parse(param);
            }catch(e){
                console.group();
                console.error('%cParameter is invalid ! You should check the following parameter !','background-color: #5174FF');
                console.error('Parameter:' + eval(param));
                console.error('Error message :' + e);
                console.groupEnd();
            }
        }
    };

////=============================================================================
//// Get and set pluguin parameters.
////=============================================================================
    var param                          = {};
    param.switchNum_skipping           = getParamNumber(['SwitchNumberForSkipping', 'スキップ用のスイッチ番号']);
    param.switchNum_escapeCommand      = getParamNumber(['SwitchNumberForEscapeCommand', '逃げるコマンド表示用のスイッチ番号']);

////==============================
//// Convert parameters.
////==============================

    //There is none.

//////=============================================================================
///// Scene_Battle
/////  Add skipping system to battle scene.
////   Override some methods for skipping always.
/////=============================================================================

    const _Scene_Battle_changeInputWindow = Scene_Battle.prototype.changeInputWindow;
    Scene_Battle.prototype.changeInputWindow = function() {
        if(this.skipPartyCommand_SPC()){//If return true, it means be skipped.
            return;
        }

        _Scene_Battle_changeInputWindow.call(this);
    };

    //This is additional method.
    Scene_Battle.prototype.skipPartyCommand_SPC = function() {
        if (this.canSkipPartyCommand_SPC()) {
            BattleManager.selectNextCommand();//Instead of commandFight().
            this.refreshStatus();
            this.startActorCommandSelection();
            return true;//Be skipped.
        }
        return false;
    };

    //This is additional method.
    Scene_Battle.prototype.isSkippableSwitchOn_SPC = function() {
        return $gameSwitches.value(param.switchNum_skipping);
    };

    //This is additional method.
    Scene_Battle.prototype.canSkipPartyCommand_SPC = function() {
        return this.isSkippableSwitchOn_SPC() && BattleManager.isInputting() && !BattleManager.actor();
    };

    const _Scene_Battle_createActorCommandWindow = Scene_Battle.prototype.createActorCommandWindow;
    Scene_Battle.prototype.createActorCommandWindow = function() {
        _Scene_Battle_createActorCommandWindow.call(this);
        this._actorCommandWindow.setHandler('escape', this.commandEscape.bind(this));
    };

//////=============================================================================
///// Window_ActorCommand
/////  Add escapeCommand.
/////=============================================================================
    const _Window_ActorCommand_changeInputWindow = Window_ActorCommand.prototype.makeCommandList;
    Window_ActorCommand.prototype.makeCommandList = function() {
        _Window_ActorCommand_changeInputWindow.call(this);
        if(this._actor) {
            this.addEscapeCommand();
        }
    };

    Window_ActorCommand.prototype.addEscapeCommand = function() {
        if(this.isEscapeCommandSwitchOn_SPC()) {
            this.addCommand(TextManager.escape, 'escape', BattleManager.canEscape());
        }
    };

    Window_ActorCommand.prototype.isEscapeCommandSwitchOn_SPC = function() {
        return $gameSwitches.value(param.switchNum_escapeCommand);
    };

})();
<|endoftext|>


<commit_before>define(["underscore", "jquery"], function(_, $) {
    $.fn.transition = function(klFrom, klActive, klFinal) {
        var self = this;
        this.addClass(klFrom);
        this.one("animationend", function(e) {
            self.removeClass(klFrom).removeClass(klActive);
            if (klFinal)
                self.addClass(klFinal);
        });
        this.addClass(klActive);
    };

    $.fn.animateAddClass = function(klBase) {
        this.classTransition(klBase + "-enter",
                             klBase + "-active");
    };

    function commas(s) {
        if (!s) return "";

        s = s.toString();
        var split = s.split("."),
            after = split[1];

        s = split[0];

        var l = s.length;
        if (l <= 3)
            return s;

        var istart = 0,
            iend = (l % 3) || 3,
            pieces = [],
            p;

        while ((p = s.slice(istart, iend))) {
            pieces.push(p);
            istart = iend;
            iend += 3;
        }

        return pieces.join(",") + (after ? ("." + after) : "");
    }

    function prettyAmount(amount, currency) {
        currency = currency || "$";

        var mag = "";

        if (amount >= 10000) {
            if (amount < 1000000) {
                mag = "k";
                amount /= 1000;
            } else if (amount < 1000000000) {
                mag = "m";
                amount /= 1000000;
            } else {
                mag = "b";
                amount /= 1000000000;
            }

            var amountStr = amount.toFixed(1).replace(/\.0$/, "");

            return currency + amountStr + mag;
        }

        return currency + commas(amount);
    }

    function prettyDistance(ft) {
        var miles = ft/5280;

        if (miles >= 1) {
            var m = miles.toFixed(1).replace(/\.0$/, "");
            return m + " mile" + (miles - 1 < 0.1 ? "" : "s");
        }

        return commas(ft) + " feet";
    }

    function capitalize(s) {
        return s[0].toUpperCase() + s.slice(1);
    }

    function isDigit(s) {
        return /^[0-9]+$/.test(s);
    }

    function diff(o1, o2) {
        var result = {};

        _.each(o1, function(v, k) {

        });

        _.each(o2, function(v, k) {

        });
    }

    function setIn(obj, ks, v) {
        if (ks.length == 0)
            return v;

        var k = ks[0];

        if (isDigit(k))
            k = parseInt(k);

        if (ks.length === 1 && k === undefined) {
            delete obj[k];
        } else {
            obj[k] = setIn(obj[k] || {},
                           ks.slice(1),
                           v);
        }
        return obj;
    }

    function getIn(obj, ks) {
        if (ks.length === 0)
            return obj;

        if (!obj)
            return undefined;

        return getIn(obj[ks[0]], ks.slice(1));
    }

    function flattenMap(obj, pref) {
        pref = pref || "";
        return _.reduce(obj, function(m, val, key) {
            if (!(!key || val === undefined)) {
                if (_.isObject(val) && !_.isFunction(val)) {
                    return _.extend(m, flattenMap(val, key + "."));
                }

                m[pref + key] = val;
            }

            return m;
        }, {});
    }

    var defaultHelpers = {
        formatDate: function(d) {
            return (d.toLocaleDateString) ?
                d.toLocaleDateString() :
                d.toString().slice(0, 15);
        },

        capitalize: capitalize,

        commas: commas,

        pluralize: function(n, sing, plur) {
            return n == 1 ? sing : (plur || sing + "s");
        },

        prettyAmount: prettyAmount,

        prettyDistance: prettyDistance
    };

    var $u = {
        keepArgs: function(fn, n) {
            return function() {
                return fn.apply(this, _.take(arguments, n));
            };
        },

        parseInt10: function(n) {
            return parseInt(n, 10);
        },

        capitalize: capitalize,

        diff: diff,

        escapeRegex: function(s) {
            return s.replace(/[.*+?\^$[\]\\(){}|\-]/g, "\\$&");
        },

        /**
         * Generate an equivalent regular expression for the given glob
         * string.
         *
         * @param {String} patt A glob pattern
         *
         * @returns {RegExp}
         */
        glob: function(patt) {
            var re = patt
                    .replace(/[.+\^$[\]\\(){}|\-]/g, "\\$&")
                    .replace("*", ".*")
                    .replace("?", ".");

            return new RegExp(re, "i");
        },

        everyPred: function(fs, arg) {
            return _.every(fs, function(f) {
                return f(arg);
            });
        },

        findIndex: function(coll, f) {
            for (var i = 0, l = coll.length; i < l; i++) {
                if (f(coll[i]))
                    return i;
            }

            return -1;
        },

        /**
         * Call function fn on an array of the 1st argument of each
         * array in colls, then on an array of the 2nd arguments,
         * etc. Stops when any of the arrays is exhausted.
         *
         * @param {Function} fn
         * @param {Array} colls
         *
         * @returns {Array} Results of calling fn on the elements of
         * colls.
         */
        zipmap: function(fn, colls) {
            var out = [],
                idx = 0;

            outer:
            while (true) {
                var args = [], i = 0, coll;

                while ((coll = colls[i++]) !== undefined) {
                    if (coll[idx] === undefined)
                        break outer;

                    args.push(coll[idx]);
                }

                out.push(fn(args));

                idx++;
            }

            return out;
        },

        /**
         * @returns {jquery.Deferred} A promise that, when resolved,
         * returns the coordinates from the user's browser.
         */
        promiseLocation: function() {
            var promise = $.Deferred();

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(pos) {
                        var coords = pos.coords;
                        promise.resolve([coords.latitude,
                                         coords.longitude,
                                         coords.altitude]);
                    },
                    function() {
                        promise.reject({reason: "Permission denied"});
                    });
            } else {
                promise.reject({reason: "Geolocation unavailable in this browser."});
            }

            return promise;
        },

        mToFeet: function(m) {
            return m*3.281;
        },

        feetToM: function(ft) {
            return ft/3.281;
        },

        mToMiles: function(m) {
            return m*3.281/5280;
        },

        commas: commas,

        currentYear: function() {
            return (new Date()).getFullYear();
        },

        /**
         * @param {number} amount
         * @param {string} currency
         *
         * @returns {string}
         */
        prettyAmount: prettyAmount,

        /**
         * Present a distance in feet in a human-readable way.
         *
         * @param {number} feet Distance in feet
         */
        prettyDistance: prettyDistance,

        /**
         * Register a default template helper, which will be available
         * to templates created with $u.template().
         *
         * @param {string} name
         * @param {Function}
         */
        registerHelper: function(name, fn) {
            defaultHelpers[name] = fn;
            return this;
        },

        setCookie: function(name, value, options) {
            document.cookie = [
                encodeURIComponent(name), "=",
                encodeURIComponent(value), ";"
            ].join("");
        },

        getCookie: function(name) {
            var cookie = document.cookie,
                patt = new RegExp("(^|;\\s*)" +
                                  $u.escapeRegex(encodeURIComponent(name)) +
                                 "=([^;]+)"),
                m = cookie.match(patt);

            return m && decodeURIComponents(m[2]);
        },

        getIn: getIn,
        setIn: setIn,

        flattenMap: flattenMap,

        /**
         * @param {Object} o A map of strings to
         *
         * @returns A string encoding the contents of the map
         */
        encodeQuery: function(o) {
            return _.map(flattenMap(o), function(val, k) {
                return encodeURIComponent(k) + "=" + encodeURIComponent(val);
            }).sort().join("&");
        },

        decodeQuery: function(s) {
            var idxRe = /\[(\d+)\]$/;
            return _.reduce(s.split("&"), function(m, piece) {
                var ss = piece.split("="),
                    k = decodeURIComponent(ss[0]),
                    val = decodeURIComponent(ss[1]);

                if (k.indexOf(".") > -1) {
                    var ks = k.split(".");
                    setIn(m, ks, val);
                } else {
                    m[k] = val;
                }

                return m;
            }, {});
        },

        /**
         * Like _.template, except that it adds helper functions to the
         * data passed to the resulting template function.
         *
         * @param {string} templateString
         * @param {object} helpers Mapping names to functions
         * @param {object} settings Passed as second argument to _.template
         */
        template: function(templateString, settings, helpers) {
            helpers = helpers || defaultHelpers;

            if (settings) {
                var varName = settings.variable;
                delete settings.variable;
            }

            var temp = _.template(templateString, settings);

            return function(data) {
                if (varName) {
                    var d = {};
                    d[varName] = data;
                    data = d;
                }

                return temp(_.extend(data, helpers));
            };
        },

        /**
         * @param {string} id Element ID of the template element in the
         * DOM.
         * @param {object} options
         */
        templateWithId: function(id, options) {
            var templateString = $("#" + id).text();

            if (!templateString) {
                throw new Error("Unknown template: " + id);
            }
            options = options || {};
            return $u.template(templateString, options, options.helpers);
        }
    };

    return $u;
});
<commit_msg>Added deepMerge utility<commit_after>define(["underscore", "jquery"], function(_, $) {
    $.fn.transition = function(klFrom, klActive, klFinal) {
        var self = this;
        this.addClass(klFrom);
        this.one("animationend", function(e) {
            self.removeClass(klFrom).removeClass(klActive);
            if (klFinal)
                self.addClass(klFinal);
        });
        this.addClass(klActive);
    };

    $.fn.animateAddClass = function(klBase) {
        this.classTransition(klBase + "-enter",
                             klBase + "-active");
    };

    function commas(s) {
        if (!s) return "";

        s = s.toString();
        var split = s.split("."),
            after = split[1];

        s = split[0];

        var l = s.length;
        if (l <= 3)
            return s;

        var istart = 0,
            iend = (l % 3) || 3,
            pieces = [],
            p;

        while ((p = s.slice(istart, iend))) {
            pieces.push(p);
            istart = iend;
            iend += 3;
        }

        return pieces.join(",") + (after ? ("." + after) : "");
    }

    function prettyAmount(amount, currency) {
        currency = currency || "$";

        var mag = "";

        if (amount >= 10000) {
            if (amount < 1000000) {
                mag = "k";
                amount /= 1000;
            } else if (amount < 1000000000) {
                mag = "m";
                amount /= 1000000;
            } else {
                mag = "b";
                amount /= 1000000000;
            }

            var amountStr = amount.toFixed(1).replace(/\.0$/, "");

            return currency + amountStr + mag;
        }

        return currency + commas(amount);
    }

    function prettyDistance(ft) {
        var miles = ft/5280;

        if (miles >= 1) {
            var m = miles.toFixed(1).replace(/\.0$/, "");
            return m + " mile" + (miles - 1 < 0.1 ? "" : "s");
        }

        return commas(ft) + " feet";
    }

    function capitalize(s) {
        return s[0].toUpperCase() + s.slice(1);
    }

    function isDigit(s) {
        return /^[0-9]+$/.test(s);
    }

    function isSimpleObject(o) {
        return o.constructor && o.constructor === Object;
    }

    function diff(o1, o2) {
        var result = {};

        _.each(o1, function(v, k) {

        });

        _.each(o2, function(v, k) {

        });
    }

    function setIn(obj, ks, v) {
        if (ks.length == 0)
            return v;

        var k = ks[0];

        if (isDigit(k))
            k = parseInt(k);

        if (ks.length === 1 && k === undefined) {
            delete obj[k];
        } else {
            obj[k] = setIn(obj[k] || {},
                           ks.slice(1),
                           v);
        }
        return obj;
    }

    function getIn(obj, ks) {
        if (ks.length === 0)
            return obj;

        if (!obj)
            return undefined;

        return getIn(obj[ks[0]], ks.slice(1));
    }

    function deepMerge(obj1, obj2) {
        _.each(obj2, function(v, k) {
            var orig = obj2[k];
            if (orig && isSimpleObject(v) && isSimpleObject(orig)) {
                deepMerge(v, orig);
            } else {
                obj1[k] = v;
            }
        });
    }

    function flattenMap(obj, pref) {
        pref = pref || "";
        return _.reduce(obj, function(m, val, key) {
            if (!(!key || val === undefined)) {
                if (isSimpleObject(val)) {
                    return _.extend(m, flattenMap(val, key + "."));
                }

                m[pref + key] = val;
            }

            return m;
        }, {});
    }

    var defaultHelpers = {
        formatDate: function(d) {
            return (d.toLocaleDateString) ?
                d.toLocaleDateString() :
                d.toString().slice(0, 15);
        },

        capitalize: capitalize,

        commas: commas,

        pluralize: function(n, sing, plur) {
            return n == 1 ? sing : (plur || sing + "s");
        },

        prettyAmount: prettyAmount,

        prettyDistance: prettyDistance
    };

    var $u = {
        keepArgs: function(fn, n) {
            return function() {
                return fn.apply(this, _.take(arguments, n));
            };
        },

        parseInt10: function(n) {
            return parseInt(n, 10);
        },

        capitalize: capitalize,

        diff: diff,

        escapeRegex: function(s) {
            return s.replace(/[.*+?\^$[\]\\(){}|\-]/g, "\\$&");
        },

        /**
         * Generate an equivalent regular expression for the given glob
         * string.
         *
         * @param {String} patt A glob pattern
         *
         * @returns {RegExp}
         */
        glob: function(patt) {
            var re = patt
                    .replace(/[.+\^$[\]\\(){}|\-]/g, "\\$&")
                    .replace("*", ".*")
                    .replace("?", ".");

            return new RegExp(re, "i");
        },

        everyPred: function(fs, arg) {
            return _.every(fs, function(f) {
                return f(arg);
            });
        },

        findIndex: function(coll, f) {
            for (var i = 0, l = coll.length; i < l; i++) {
                if (f(coll[i]))
                    return i;
            }

            return -1;
        },

        /**
         * Call function fn on an array of the 1st argument of each
         * array in colls, then on an array of the 2nd arguments,
         * etc. Stops when any of the arrays is exhausted.
         *
         * @param {Function} fn
         * @param {Array} colls
         *
         * @returns {Array} Results of calling fn on the elements of
         * colls.
         */
        zipmap: function(fn, colls) {
            var out = [],
                idx = 0;

            outer:
            while (true) {
                var args = [], i = 0, coll;

                while ((coll = colls[i++]) !== undefined) {
                    if (coll[idx] === undefined)
                        break outer;

                    args.push(coll[idx]);
                }

                out.push(fn(args));

                idx++;
            }

            return out;
        },

        /**
         * @returns {jquery.Deferred} A promise that, when resolved,
         * returns the coordinates from the user's browser.
         */
        promiseLocation: function() {
            var promise = $.Deferred();

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(pos) {
                        var coords = pos.coords;
                        promise.resolve([coords.latitude,
                                         coords.longitude,
                                         coords.altitude]);
                    },
                    function() {
                        promise.reject({reason: "Permission denied"});
                    });
            } else {
                promise.reject({reason: "Geolocation unavailable in this browser."});
            }

            return promise;
        },

        mToFeet: function(m) {
            return m*3.281;
        },

        feetToM: function(ft) {
            return ft/3.281;
        },

        mToMiles: function(m) {
            return m*3.281/5280;
        },

        commas: commas,

        currentYear: function() {
            return (new Date()).getFullYear();
        },

        /**
         * @param {number} amount
         * @param {string} currency
         *
         * @returns {string}
         */
        prettyAmount: prettyAmount,

        /**
         * Present a distance in feet in a human-readable way.
         *
         * @param {number} feet Distance in feet
         */
        prettyDistance: prettyDistance,

        /**
         * Register a default template helper, which will be available
         * to templates created with $u.template().
         *
         * @param {string} name
         * @param {Function}
         */
        registerHelper: function(name, fn) {
            defaultHelpers[name] = fn;
            return this;
        },

        setCookie: function(name, value, options) {
            document.cookie = [
                encodeURIComponent(name), "=",
                encodeURIComponent(value), ";"
            ].join("");
        },

        getCookie: function(name) {
            var cookie = document.cookie,
                patt = new RegExp("(^|;\\s*)" +
                                  $u.escapeRegex(encodeURIComponent(name)) +
                                 "=([^;]+)"),
                m = cookie.match(patt);

            return m && decodeURIComponents(m[2]);
        },

        getIn: getIn,
        setIn: setIn,

        deepMerge: deepMerge,
        flattenMap: flattenMap,

        /**
         * @param {Object} o A map of strings to
         *
         * @returns A string encoding the contents of the map
         */
        encodeQuery: function(o) {
            return _.map(flattenMap(o), function(val, k) {
                return encodeURIComponent(k) + "=" + encodeURIComponent(val);
            }).sort().join("&");
        },

        decodeQuery: function(s) {
            var idxRe = /\[(\d+)\]$/;
            return _.reduce(s.split("&"), function(m, piece) {
                var ss = piece.split("="),
                    k = decodeURIComponent(ss[0]),
                    val = decodeURIComponent(ss[1]);

                if (k.indexOf(".") > -1) {
                    var ks = k.split(".");
                    setIn(m, ks, val);
                } else {
                    m[k] = val;
                }

                return m;
            }, {});
        },

        /**
         * Like _.template, except that it adds helper functions to the
         * data passed to the resulting template function.
         *
         * @param {string} templateString
         * @param {object} helpers Mapping names to functions
         * @param {object} settings Passed as second argument to _.template
         */
        template: function(templateString, settings, helpers) {
            helpers = helpers || defaultHelpers;

            if (settings) {
                var varName = settings.variable;
                delete settings.variable;
            }

            var temp = _.template(templateString, settings);

            return function(data) {
                if (varName) {
                    var d = {};
                    d[varName] = data;
                    data = d;
                }

                return temp(_.extend(data, helpers));
            };
        },

        /**
         * @param {string} id Element ID of the template element in the
         * DOM.
         * @param {object} options
         */
        templateWithId: function(id, options) {
            var templateString = $("#" + id).text();

            if (!templateString) {
                throw new Error("Unknown template: " + id);
            }
            options = options || {};
            return $u.template(templateString, options, options.helpers);
        }
    };

    return $u;
});
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import StepContent from '../../components/Stepper/StepContent';
import StepWrapper from '../../components/Stepper/StepWrapper';
import AmountSelection from '../../components/AmountSelection/AmountSelection';
import MemberDetailsForm from '../../components/MemberDetailsForm/MemberDetailsForm';
import Payment from '../../components/Payment/Payment';
import {
  changeAmount,
  changeCurrency,
  changeStep,
} from '../../state/fundraiser/actions';

import type { Dispatch } from 'redux';
import type { AppState } from '../../state';

type OwnProps = {
  currentStep: number;
  formValues: any;
  member: any;
  currency: string;
  donationBands: {[id:string]: number[]};
  donationFeaturedAmount: ?number;
  donationAmount: ?number;
  changeStep: (step: number) => void;
  selectAmount: (amount: ?number) => void;
  selectCurrency: (currency: string) => void;
  fields: any[];
  outstandingFields: string[];
  formId: number;
};

export class FundraiserView extends Component {
  props: OwnProps & mapStateToProps;

  static defaultProps = {
    currentStep: 0,
    member: null,
    currency: 'USD',
    donationBands: { 'USD': [2, 5, 10, 25, 50],
                     'GBP': [1, 2, 3, 4, 5]
    }
  }

  selectAmount(amount: ?number) {
    this.props.selectAmount(amount);
  }

  proceed() {
    this.props.changeStep(this.props.fundraiser.currentStep + 1);
  }

  render() {
    const {
      member,
      fundraiser: {
        formId,
        fields,
        formValues,
        donationBands,
        donationAmount,
        donationFeaturedAmount,
        currency,
        currencies,
        currentStep,
        outstandingFields,
      }
    }  = this.props;

    return (

        <StepWrapper title={this.props.fundraiser.title} currentStep={currentStep} changeStep={this.props.changeStep}>
          <StepContent title={AmountSelection.title(donationAmount, currency)}>
            <AmountSelection
              donationAmount={donationAmount}
              currency={currency}
              donationBands={donationBands}
              donationFeaturedAmount={donationFeaturedAmount}
              currencies={currencies}
              nextStepTitle={ formValues ? 'payment' : MemberDetailsForm.title }
              changeCurrency={this.props.selectCurrency.bind(this)}
              selectAmount={amount => this.selectAmount(amount)}
              proceed={this.proceed.bind(this)}
            />
          </StepContent>

          { outstandingFields.length !== 0 &&
            <StepContent title="details">
              <MemberDetailsForm
                buttonText={<FormattedMessage id="fundraiser.proceed_to_payment" defaultMessage="Proceed to payment" />}
                fields={fields}
                outstandingFields={outstandingFields}
                prefillValues={formValues}
                formId={formId}
                proceed={this.proceed.bind(this)}
              />
            </StepContent> }

          <StepContent title="payment">
            <Payment />
          </StepContent>
        </StepWrapper>

    );
  }
}

export const mapStateToProps = (state: AppState) => ({
  fundraiser: state.fundraiser,
  member: state.member,
});

export const mapDispatchToProps = (dispatch: Dispatch<*>) => ({
  changeStep: (step: number) => dispatch(changeStep(step)),
  selectAmount: (amount: ?number) => dispatch(changeAmount(amount)),
  selectCurrency: (currency: string) => dispatch(changeCurrency(currency)),
});

export default connect(mapStateToProps, mapDispatchToProps)(FundraiserView);
<commit_msg>Removed unused defaultProps from FundraiserView<commit_after>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import StepContent from '../../components/Stepper/StepContent';
import StepWrapper from '../../components/Stepper/StepWrapper';
import AmountSelection from '../../components/AmountSelection/AmountSelection';
import MemberDetailsForm from '../../components/MemberDetailsForm/MemberDetailsForm';
import Payment from '../../components/Payment/Payment';
import {
  changeAmount,
  changeCurrency,
  changeStep,
} from '../../state/fundraiser/actions';

import type { Dispatch } from 'redux';
import type { AppState } from '../../state';

type OwnProps = {
  currentStep: number;
  formValues: any;
  member: any;
  currency: string;
  donationBands: {[id:string]: number[]};
  donationFeaturedAmount: ?number;
  donationAmount: ?number;
  changeStep: (step: number) => void;
  selectAmount: (amount: ?number) => void;
  selectCurrency: (currency: string) => void;
  fields: any[];
  outstandingFields: string[];
  formId: number;
};

export class FundraiserView extends Component {
  props: OwnProps & mapStateToProps;

  selectAmount(amount: ?number) {
    this.props.selectAmount(amount);
  }

  proceed() {
    this.props.changeStep(this.props.fundraiser.currentStep + 1);
  }

  render() {
    const {
      member,
      fundraiser: {
        formId,
        fields,
        formValues,
        donationBands,
        donationAmount,
        donationFeaturedAmount,
        currency,
        currencies,
        currentStep,
        outstandingFields,
      }
    }  = this.props;

    return (

        <StepWrapper title={this.props.fundraiser.title} currentStep={currentStep} changeStep={this.props.changeStep}>
          <StepContent title={AmountSelection.title(donationAmount, currency)}>
            <AmountSelection
              donationAmount={donationAmount}
              currency={currency}
              donationBands={donationBands}
              donationFeaturedAmount={donationFeaturedAmount}
              currencies={currencies}
              nextStepTitle={ formValues ? 'payment' : MemberDetailsForm.title }
              changeCurrency={this.props.selectCurrency.bind(this)}
              selectAmount={amount => this.selectAmount(amount)}
              proceed={this.proceed.bind(this)}
            />
          </StepContent>

          { outstandingFields.length !== 0 &&
            <StepContent title="details">
              <MemberDetailsForm
                buttonText={<FormattedMessage id="fundraiser.proceed_to_payment" defaultMessage="Proceed to payment" />}
                fields={fields}
                outstandingFields={outstandingFields}
                prefillValues={formValues}
                formId={formId}
                proceed={this.proceed.bind(this)}
              />
            </StepContent> }

          <StepContent title="payment">
            <Payment />
          </StepContent>
        </StepWrapper>

    );
  }
}

export const mapStateToProps = (state: AppState) => ({
  fundraiser: state.fundraiser,
  member: state.member,
});

export const mapDispatchToProps = (dispatch: Dispatch<*>) => ({
  changeStep: (step: number) => dispatch(changeStep(step)),
  selectAmount: (amount: ?number) => dispatch(changeAmount(amount)),
  selectCurrency: (currency: string) => dispatch(changeCurrency(currency)),
});

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


<commit_before>'use strict';

// MODULES //

var debug = require( 'debug' )( 'for-each-async:limit' );

// MAIN //

/**
* Invokes a function once for each element in a collection, limiting the number of concurrently pending functions.
*
* @private
* @param {Collection} collection - input collection
* @param {Options} opts - function options
* @param {*} [opts.thisArg] - execution context
* @param {PositiveInteger} [opts.limit] - maximum number of pending function invocations
* @param {Function} fcn - function to invoke
* @param {Callback} done - function to invoke upon completion or upon encountering an error
* @returns {void}
*/
function limit( collection, opts, fcn, done ) {
	var maxIndex;
	var errFLG;
	var count;
	var nargs;
	var lim;
	var len;
	var idx;
	var i;

	len = collection.length;
	debug( 'Collection length: %d', len );

	if ( len === 0 ) {
		debug( 'Finished processing a collection.' );
		return done();
	}
	if ( len < opts.limit ) {
		lim = len;
	} else {
		lim = opts.limit;
	}
	debug( 'Concurrency limit: %d', lim );

	if ( fcn.length === 2 || fcn.length === 3 ) {
		nargs = fcn.length;
	} else {
		nargs = 4;
	}
	debug( 'Number of arguments: %d', nargs );

	maxIndex = len - 1;
	count = 0;
	idx = -1;
	for ( i = 0; i < lim; i++ ) {
		// This guard is necessary to protect against synchronous functions which exhaust all collection elements...
		if ( idx <= maxIndex ) {
			next(); // eslint-disable-line callback-return
		}
	}

	/**
	* Callback to invoke a provided function for the next element in a collection.
	*
	* @private
	*/
	function next() {
		idx += 1;
		debug( 'Collection element %d: %s.', idx, JSON.stringify( collection[ idx ] ) );
		if ( nargs < 3 ) {
			fcn.call( opts.thisArg, collection[ idx ], clbk );
		} else if ( nargs === 3 ) {
			fcn.call( opts.thisArg, collection[ idx ], idx, clbk );
		} else {
			fcn.call( opts.thisArg, collection[ idx ], idx, collection, clbk );
		}
	} // end FUNCTION next()

	/**
	* Callback invoked once a provided function finishes processing a collection element.
	*
	* @private
	* @param {*} [error] - error
	* @returns {void}
	*/
	function clbk( error ) {
		if ( error ) {
			errFLG = true;
			debug( 'Encountered an error: %s', error.message );
			return done( error );
		}
		if ( errFLG ) {
			// Prevent further processing of collection elements:
			return;
		}
		count += 1;
		debug( 'Processed %d of %d collection elements.', count, len );
		if ( idx < maxIndex ) {
			return next();
		} else if ( count === len ) {
			debug( 'Finished processing a collection.' );
			return done();
		}
	} // end FUNCTION clbk()
} // end FUNCTION limit()

// EXPORTS //

module.exports = limit;
<commit_msg>Remove variable<commit_after>'use strict';

// MODULES //

var debug = require( 'debug' )( 'for-each-async:limit' );

// MAIN //

/**
* Invokes a function once for each element in a collection, limiting the number of concurrently pending functions.
*
* @private
* @param {Collection} collection - input collection
* @param {Options} opts - function options
* @param {*} [opts.thisArg] - execution context
* @param {PositiveInteger} [opts.limit] - maximum number of pending function invocations
* @param {Function} fcn - function to invoke
* @param {Callback} done - function to invoke upon completion or upon encountering an error
* @returns {void}
*/
function limit( collection, opts, fcn, done ) {
	var maxIndex;
	var errFLG;
	var count;
	var lim;
	var len;
	var idx;
	var i;

	len = collection.length;
	debug( 'Collection length: %d', len );

	if ( len === 0 ) {
		debug( 'Finished processing a collection.' );
		return done();
	}
	if ( len < opts.limit ) {
		lim = len;
	} else {
		lim = opts.limit;
	}
	debug( 'Concurrency limit: %d', lim );
	debug( 'Number of arguments: %d', fcn.length );

	maxIndex = len - 1;
	count = 0;
	idx = -1;
	for ( i = 0; i < lim; i++ ) {
		// This guard is necessary to protect against synchronous functions which exhaust all collection elements...
		if ( idx <= maxIndex ) {
			next(); // eslint-disable-line callback-return
		}
	}

	/**
	* Callback to invoke a provided function for the next element in a collection.
	*
	* @private
	*/
	function next() {
		idx += 1;
		debug( 'Collection element %d: %s.', idx, JSON.stringify( collection[ idx ] ) );
		if ( fcn.length === 2 ) {
			fcn.call( opts.thisArg, collection[ idx ], clbk );
		} else if ( fcn.length === 3 ) {
			fcn.call( opts.thisArg, collection[ idx ], idx, clbk );
		} else {
			fcn.call( opts.thisArg, collection[ idx ], idx, collection, clbk );
		}
	} // end FUNCTION next()

	/**
	* Callback invoked once a provided function finishes processing a collection element.
	*
	* @private
	* @param {*} [error] - error
	* @returns {void}
	*/
	function clbk( error ) {
		if ( error ) {
			errFLG = true;
			debug( 'Encountered an error: %s', error.message );
			return done( error );
		}
		if ( errFLG ) {
			// Prevent further processing of collection elements:
			return;
		}
		count += 1;
		debug( 'Processed %d of %d collection elements.', count, len );
		if ( idx < maxIndex ) {
			return next();
		} else if ( count === len ) {
			debug( 'Finished processing a collection.' );
			return done();
		}
	} // end FUNCTION clbk()
} // end FUNCTION limit()

// EXPORTS //

module.exports = limit;
<|endoftext|>


<commit_before>//= require voluntary/application
//= require handlebars
//= require ember
//= require ember-data
//= require_self
//= require ./app

Volontariat = Ember.Application.create({ LOG_TRANSITIONS: true, rootElement: '#outlet' });
<commit_msg>refs #4 Include active model adapter plugin for Ember.JS upgrade .<commit_after>//= require voluntary/application
//= require handlebars
//= require ember
//= require ember-data
//= require active-model-adapter
//= require_self
//= require ./app

Volontariat = Ember.Application.create({ LOG_TRANSITIONS: true, rootElement: '#outlet' });
<|endoftext|>


<commit_before>/* global Auth0Lock */
(function () {
  function appendScript(src, callback) {
    var new_script = document.createElement('script');
    new_script.setAttribute('src',src);
    new_script.onload = callback;
    document.head.appendChild(new_script);
  }

  var lock;

  var script_url = '//cdn.auth0.com/js/lock-7.8.js';

  appendScript(script_url, function () {
    var checkInterval = setInterval(function () {
      if (!Discourse.SiteSettings) {
        return;
      }

      clearInterval(checkInterval);

      if (!Discourse.SiteSettings.auth0_client_id) {
        return;
      }

      var client_id = Discourse.SiteSettings.auth0_client_id;
      var domain = Discourse.SiteSettings.auth0_domain;

      lock = new Auth0Lock(client_id, domain);

    }, 300);
  });

  Discourse.ApplicationRoute.reopen({
    actions: {
      showLogin: function() {
        if (!Discourse.SiteSettings.auth0_client_id || Discourse.SiteSettings.auth0_connection !== '') {
          return this._super();
        }

        lock.show({
          popup:        true,
          responseType: 'code',
          callbackURL:  Discourse.SiteSettings.auth0_callback_url
        });

        this.controllerFor('login').resetForm();
      },
      showCreateAccount: function () {
        if (!Discourse.SiteSettings.auth0_client_id || Discourse.SiteSettings.auth0_connection !== '') {
          return this._super();
        }

        var createAccountController = Discourse.__container__.lookup('controller:createAccount');

        if (createAccountController && createAccountController.accountEmail) {
          if (lock) {
            lock.hide();
            Discourse.Route.showModal(this, 'createAccount');
          } else {
            this._super();
          }
        } else {
          lock.show({
            mode:         'signup',
            popup:        true,
            responseType: 'code',
            callbackURL:  Discourse.SiteSettings.auth0_callback_url
          });
        }
      }
    }
  });

})();
<commit_msg>close Lock on signup - fix #12<commit_after>/* global Auth0Lock */
(function () {
  function appendScript(src, callback) {
    var new_script = document.createElement('script');
    new_script.setAttribute('src',src);
    new_script.onload = callback;
    document.head.appendChild(new_script);
  }

  var lock;

  var script_url = '//cdn.auth0.com/js/lock-7.8.js';

  appendScript(script_url, function () {
    var checkInterval = setInterval(function () {
      if (!Discourse.SiteSettings) {
        return;
      }

      clearInterval(checkInterval);

      if (!Discourse.SiteSettings.auth0_client_id) {
        return;
      }

      var client_id = Discourse.SiteSettings.auth0_client_id;
      var domain = Discourse.SiteSettings.auth0_domain;

      lock = new Auth0Lock(client_id, domain);

    }, 300);
  });

  Discourse.LoginController.reopen({
    authenticationComplete: function () {
      if (lock) {
        lock.hide();
      }
      return this._super.apply(this, arguments);
    }
  });

  Discourse.ApplicationRoute.reopen({
    actions: {
      showLogin: function() {
        if (!Discourse.SiteSettings.auth0_client_id || Discourse.SiteSettings.auth0_connection !== '') {
          return this._super();
        }

        lock.show({
          popup:        true,
          responseType: 'code',
          callbackURL:  Discourse.SiteSettings.auth0_callback_url
        });

        this.controllerFor('login').resetForm();
      },
      showCreateAccount: function () {
        if (!Discourse.SiteSettings.auth0_client_id || Discourse.SiteSettings.auth0_connection !== '') {
          return this._super();
        }

        var createAccountController = Discourse.__container__.lookup('controller:createAccount');

        if (createAccountController && createAccountController.accountEmail) {
          if (lock) {
            lock.hide();
            Discourse.Route.showModal(this, 'createAccount');
          } else {
            this._super();
          }
        } else {
          lock.show({
            mode:         'signup',
            popup:        true,
            responseType: 'code',
            callbackURL:  Discourse.SiteSettings.auth0_callback_url
          });
        }
      }
    }
  });

})();
<|endoftext|>


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

var Controller = require('./RC');
var expect = require('chai').expect;
var HazelcastClient = require('../.').Client;
var Config = require('../.').Config;
var Util = require('./Util');
var Promise = require('bluebird');

describe('Listeners on reconnect', function () {

    this.timeout(120000);
    var client;
    var members = [];
    var cluster;
    var map;

    beforeEach(function () {
        return Controller.createCluster(null, null).then(function (cl) {
            cluster = cl;
        });
    });

    afterEach(function () {
        return map.destroy().then(function () {
            client.shutdown();
            return Controller.shutdownCluster(cluster.id);
        });
    });

    function closeTwoMembersOfThreeAndTestListener(done, isSmart, membersToClose, turnoffMember) {
        Controller.startMember(cluster.id).then(function (m) {
            members[0] = m;
            return Controller.startMember(cluster.id);
        }).then(function (m) {
            members[1] = m;
            return Controller.startMember(cluster.id);
        }).then(function (m) {
            members[2] = m;
            var cfg = new Config.ClientConfig();
            cfg.properties['hazelcast.client.heartbeat.interval'] = 1000;
            cfg.properties['hazelcast.client.heartbeat.timeout'] = 3000;
            cfg.networkConfig.smartRouting = isSmart;
            return HazelcastClient.newHazelcastClient(cfg);
        }).then(function (cl) {
            client = cl;
            map = client.getMap('testmap');
            var listenerObject = {
                added: function (key, oldValue, value, mergingValue) {
                    try {
                        expect(key).to.equal('keyx');
                        expect(oldValue).to.be.undefined;
                        expect(value).to.equal('valx');
                        expect(mergingValue).to.be.undefined;
                        done();
                    } catch (err) {
                        done(err);
                    }
                }
            };
            return map.addEntryListener(listenerObject, 'keyx', true);
        }).then(function () {
            return Promise.all([
                turnoffMember(cluster.id, members[membersToClose[0]].uuid),
                turnoffMember(cluster.id, members[membersToClose[1]].uuid)
            ]);
        }).then(function () {
            return map.put('keyx', 'valx');
        });
    }

    [true, false].forEach(function (isSmart) {

        /**
         * We use three members to simulate all configurations where connection is closed to;
         *  - ownerconnection
         *  - connection that has the local listener that will react to map.put event
         *  - the other unrelated connection
         */

        it('kill two members [1,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [1, 2], Controller.terminateMember);
        });

        it('kill two members [0,1], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 1], Controller.terminateMember);
        });

        it('kill two members [0,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 2], Controller.terminateMember);
        });

        it('shutdown two members [1,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [1, 2], Controller.shutdownMember);
        });

        it('shutdown two members [0,1], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 1], Controller.shutdownMember);
        });

        it('shutdown two members [0,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 2], Controller.shutdownMember);
        });

        it('restart member, listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            var member;
            Controller.startMember(cluster.id).then(function (m) {
                member = m;
                var cfg = new Config.ClientConfig();
                cfg.networkConfig.smartRouting = isSmart;
                cfg.properties['hazelcast.client.heartbeat.interval'] = 1000;
                return HazelcastClient.newHazelcastClient(cfg);
            }).then(function (cl) {
                client = cl;
                map = client.getMap('testmap');
                var listenerObject = {
                    added: function (key, oldValue, value, mergingValue) {
                        try {
                            expect(key).to.equal('keyx');
                            expect(oldValue).to.be.undefined;
                            expect(value).to.equal('valx');
                            expect(mergingValue).to.be.undefined;
                            done();
                        } catch (err) {
                            done(err);
                        }
                    }
                };
                return map.addEntryListener(listenerObject, 'keyx', true);
            }).then(function () {
                return Controller.terminateMember(cluster.id, member.uuid);
            }).then(function () {
                return Controller.startMember(cluster.id);
            }).then(function () {
                return Util.promiseWaitMilliseconds(5000);
            }).then(function () {
                return map.put('keyx', 'valx');
            });
        });
    });
});
<commit_msg>fix Listeners on reconnect kill two members test<commit_after>/*
 * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Controller = require('./RC');
var expect = require('chai').expect;
var HazelcastClient = require('../.').Client;
var Config = require('../.').Config;
var Util = require('./Util');
var Promise = require('bluebird');

describe('Listeners on reconnect', function () {

    this.timeout(30000);
    var client;
    var members = [];
    var cluster;
    var map;

    beforeEach(function () {
        return Controller.createCluster(null, null).then(function (cl) {
            cluster = cl;
        });
    });

    afterEach(function () {
        return map.destroy().then(function () {
            client.shutdown();
            return Controller.terminateCluster(cluster.id);
        });
    });

    function closeTwoMembersOfThreeAndTestListener(done, isSmart, membersToClose, turnoffMember) {
        Controller.startMember(cluster.id).then(function (m) {
            members[0] = m;
            return Controller.startMember(cluster.id);
        }).then(function (m) {
            members[1] = m;
            return Controller.startMember(cluster.id);
        }).then(function (m) {
            members[2] = m;
            var cfg = new Config.ClientConfig();
            cfg.properties['hazelcast.client.heartbeat.interval'] = 1000;
            cfg.properties['hazelcast.client.heartbeat.timeout'] = 3000;
            cfg.networkConfig.smartRouting = isSmart;
            return HazelcastClient.newHazelcastClient(cfg);
        }).then(function (cl) {
            client = cl;
            map = client.getMap('testmap');
            var listenerObject = {
                added: function (key, oldValue, value, mergingValue) {
                    try {
                        expect(key).to.equal('keyx');
                        expect(oldValue).to.be.undefined;
                        expect(value).to.equal('valx');
                        expect(mergingValue).to.be.undefined;
                        done();
                    } catch (err) {
                        done(err);
                    }
                }
            };
            return map.addEntryListener(listenerObject, 'keyx', true);
        }).then(function () {
            return Promise.all([
                turnoffMember(cluster.id, members[membersToClose[0]].uuid),
                turnoffMember(cluster.id, members[membersToClose[1]].uuid)
            ]);
        }).then(function () {
            return Util.promiseWaitMilliseconds(5000);
        }).then(function () {
            return map.put('keyx', 'valx');
        });
    }

    [true, false].forEach(function (isSmart) {

        /**
         * We use three members to simulate all configurations where connection is closed to;
         *  - ownerconnection
         *  - connection that has the local listener that will react to map.put event
         *  - the other unrelated connection
         */

        it('kill two members [1,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [1, 2], Controller.terminateMember);
        });

        it('kill two members [0,1], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 1], Controller.terminateMember);
        });

        it('kill two members [0,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 2], Controller.terminateMember);
        });

        it('shutdown two members [1,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [1, 2], Controller.shutdownMember);
        });

        it('shutdown two members [0,1], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 1], Controller.shutdownMember);
        });

        it('shutdown two members [0,2], listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            closeTwoMembersOfThreeAndTestListener(done, isSmart, [0, 2], Controller.shutdownMember);
        });

        it('restart member, listener still receives map.put event [smart=' + isSmart + ']', function (done) {
            var member;
            Controller.startMember(cluster.id).then(function (m) {
                member = m;
                var cfg = new Config.ClientConfig();
                cfg.networkConfig.smartRouting = isSmart;
                cfg.properties['hazelcast.client.heartbeat.interval'] = 1000;
                return HazelcastClient.newHazelcastClient(cfg);
            }).then(function (cl) {
                client = cl;
                map = client.getMap('testmap');
                var listenerObject = {
                    added: function (key, oldValue, value, mergingValue) {
                        try {
                            expect(key).to.equal('keyx');
                            expect(oldValue).to.be.undefined;
                            expect(value).to.equal('valx');
                            expect(mergingValue).to.be.undefined;
                            done();
                        } catch (err) {
                            done(err);
                        }
                    }
                };
                return map.addEntryListener(listenerObject, 'keyx', true);
            }).then(function () {
                return Controller.terminateMember(cluster.id, member.uuid);
            }).then(function () {
                return Controller.startMember(cluster.id);
            }).then(function () {
                return Util.promiseWaitMilliseconds(5000);
            }).then(function () {
                return map.put('keyx', 'valx');
            });
        });
    });
});
<|endoftext|>


<commit_before>var gulp = require('gulp');

var libs = [
    'node_modules/crypto-js/crypto-js.js',
    'node_modules/jquery/dist/jquery.js',
    'node_modules/moment/moment.js'
];

gulp.task('default', () => {
    console.log('run `gulp --tasks`');
});

gulp.task('clean', () => {
    var del = require('del');
    return del(['tmp/', 'KinnosukeTimeRecorder/']);
});

gulp.task('prepare', () => {
    return (
        gulp.src('manifest.json').pipe(gulp.dest('tmp/')),
        gulp.src('html/*').pipe(gulp.dest('tmp/html/')),
        gulp.src('images/*').pipe(gulp.dest('tmp/images/')),
        gulp.src('js/*').pipe(gulp.dest('tmp/js/')),
        gulp.src(libs).pipe(gulp.dest('tmp/vendor/'))
    );
});

gulp.task('zip', gulp.series('prepare', () => {
    var zip = require('gulp-zip');
    return gulp.src('tmp/**')
        .pipe(zip('KinnosukeTimeRecorder.zip'))
        .pipe(gulp.dest('./'));
}));

gulp.task('build', gulp.series('clean', 'zip'));

gulp.task('vendor', () => {
    return gulp.src(libs).pipe(gulp.dest('vendor/'));
});

<commit_msg>clean時はzipファイルを消すようにしました<commit_after>var gulp = require('gulp');

var libs = [
    'node_modules/crypto-js/crypto-js.js',
    'node_modules/jquery/dist/jquery.js',
    'node_modules/moment/moment.js'
];

gulp.task('default', () => {
    console.log('run `gulp --tasks`');
});

gulp.task('clean', () => {
    var del = require('del');
    return del(['tmp/', 'KinnosukeTimeRecorder.zip']);
});

gulp.task('prepare', () => {
    return (
        gulp.src('manifest.json').pipe(gulp.dest('tmp/')),
        gulp.src('html/*').pipe(gulp.dest('tmp/html/')),
        gulp.src('images/*').pipe(gulp.dest('tmp/images/')),
        gulp.src('js/*').pipe(gulp.dest('tmp/js/')),
        gulp.src(libs).pipe(gulp.dest('tmp/vendor/'))
    );
});

gulp.task('zip', gulp.series('prepare', () => {
    var zip = require('gulp-zip');
    return gulp.src('tmp/**')
        .pipe(zip('KinnosukeTimeRecorder.zip'))
        .pipe(gulp.dest('./'));
}));

gulp.task('build', gulp.series('clean', 'zip'));

gulp.task('vendor', () => {
    return gulp.src(libs).pipe(gulp.dest('vendor/'));
});

<|endoftext|>


<commit_before>function Cube (element_id) {
	var DOM = document.getElementById(element_id);
	this.DOM = DOM;

	var sides = ['front','top','bottom','back','left','right'];

	for (i in sides) {this[sides[i]]=['z','-y','y','-z','-x','x'][i]}

	function fill () { // fill DOM cube sides with appropriate values
		for (i in sides) {
			var element = document.getElementById(sides[i]);
			var value = this[sides[i]];
			element.innerHTML=value;
			element.style.backgroundColor = get_random_color(value);
		}
	}
	this.fill = fill;

	function make (direction) {
	    rotate(direction)
	}
	this.make = make;

	function rotate (direction) {
		var t_angles = [0,0,0];
		console.group(direction);
		switch (direction) {
	        case "top" : {
	            t_angles = convert_angles(1,0);
	        }; break;
	        case "bottom" : {
	            t_angles = convert_angles(-1,0);
	        }; break;
	        case "left" : {
	            t_angles = convert_angles(0,-1);
	        }; break;
	        case "right" : {
	            t_angles = convert_angles(0,1);
	        }; break;
	        default: throw new TypeError('direction must be "top", "bottom", "left" or "right", but not: "'+direction+'"');
	    };
		rotate3d(t_angles[0],t_angles[1],t_angles[2],90);
	}

	var coords = ['x','y','z']; // initial coord system
	var Ox = 'x',Oy='y'; // initial default ords

	function convert_angles (x,y) {
		var new_angles = [x,y,0];

		console.log(x,y);
			console.log('coords before',coords);

			switch (coords.join(',')) {
				case "x,y,z" : { //defalut
					new_angles = [x,y,0];
				}; break;
				case "x,-z,y" : { //up
					new_angles = [x,0,-y];
					/*switch ([x,y].join(',')) {
						case "1,0": coords = ['x','-y','z']; break; //up
						case "-1,0": coords = ['x','y','z']; break; //down
						case "0,1": coords = ['y','-z','-x']; break; //right
						case "0,-1": coords = ['-y','-z','x']; break; //left
					}*/
				}; break;
				case "-y,-z,x" : { // up-left
					new_angles = [0,-x,-y];
					/*switch ([x,y].join(',')) {
						case "1,0": coords = ['-y','-x','-z']; break; //up
						case "-1,0": coords = ['-y','x','z']; break; //down
						case "0,1": coords = ['x','-z','y']; break; //right
						case "0,-1": coords = ['-x','-z','-y']; break; //left
					}*/
				}; break;
				default : throw new RangeError('coordinate system "'+coords+'" is unknown');
			}

			switch ([x,y].join(',')) {
				case "1,0": { //up
					// coords = ['x','-z','y']
					var temp = coords[2];
					coords[2] = coords[1];
					coords[1] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "-1,0": { //down
					// coords = ['x','z','-y']
					var temp = coords[1];
					coords[1] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,1": { //right
					// coords = ['z','y','-x']
					var temp = coords[0];
					coords[0] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,-1": { //left
					// coords = ['-z','y','x']
					var temp = coords[2];
					coords[2] = coords[0];
					coords[0] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
			};

			console.log('coords after',coords);
		console.groupEnd();

		var tX = 0,tY=0,tZ=0;

		return new_angles;
	}

	function rotate3d(x,y,z,degree) {
		var matrix = new WebKitCSSMatrix(DOM.style.webkitTransform);
		matrix = matrix.rotateAxisAngle(x,y,z,degree);
		DOM.style.webkitTransform = matrix.toString();
	}
	rotate3d(-1,-1,0,30); // initial rotation

	return this;
}

var cube = new Cube('cube3d') // main cube object
cube.fill();

shortcut.add('up',function () {cube.make('top')});
shortcut.add('down',function () {cube.make('bottom')});
shortcut.add('left',function () {cube.make('left')});
shortcut.add('Right',function () {cube.make('right')});

function get_random_color (value) {
	Math.seedrandom(value);
    var color = 'rgba('+(Math.round(Math.random()*150)+55)+','+(Math.round(Math.random()*250)+5)+','+(Math.round(Math.random()*250)+5)+','+'.5)';
    Math.seedrandom();
    return color;
}<commit_msg>add some more coord system states<commit_after>function Cube (element_id) {
	var DOM = document.getElementById(element_id);
	this.DOM = DOM;

	var sides = ['front','top','bottom','back','left','right'];

	for (i in sides) {this[sides[i]]=['z','-y','y','-z','-x','x'][i]}

	function fill () { // fill DOM cube sides with appropriate values
		for (i in sides) {
			var element = document.getElementById(sides[i]);
			var value = this[sides[i]];
			element.innerHTML=value;
			element.style.backgroundColor = get_random_color(value);
		}
	}
	this.fill = fill;

	function make (direction) {
	    rotate(direction)
	}
	this.make = make;

	function rotate (direction) {
		var t_angles = [0,0,0];
		console.group(direction);
		switch (direction) {
	        case "top" : {
	            t_angles = convert_angles(1,0);
	        }; break;
	        case "bottom" : {
	            t_angles = convert_angles(-1,0);
	        }; break;
	        case "left" : {
	            t_angles = convert_angles(0,-1);
	        }; break;
	        case "right" : {
	            t_angles = convert_angles(0,1);
	        }; break;
	        default: throw new TypeError('direction must be "top", "bottom", "left" or "right", but not: "'+direction+'"');
	    };
		rotate3d(t_angles[0],t_angles[1],t_angles[2],90);
	}

	var coords = ['x','y','z']; // initial coord system
	var Ox = 'x',Oy='y'; // initial default ords

	function convert_angles (x,y) {
		var new_angles = [x,y,0];

		console.log(x,y);
			console.log('coords before',coords);

			switch (coords.join(',')) {
				case "x,y,z" : { //defalut
					new_angles = [x,y,0];
				}; break;
				case "x,-z,y" : { //up
					new_angles = [x,0,-y];
				}; break;
				case "x,z,-y" : { //down
					new_angles = [x,0,y];
				}; break;
				case "z,y,-x" : { //right
					new_angles = [0,y,x];
				}; break;
				case "-z,y,x" : { //left
					new_angles = [0,y,-x];
				}; break;
				case "-y,-z,x" : { // up-left
					new_angles = [0,-x,-y];
				}; break;
				default : throw new RangeError('coordinate system "'+coords+'" is unknown');
			}

			switch ([x,y].join(',')) {
				case "1,0": { //up
					// coords = ['x','-z','y']
					var temp = coords[2];
					coords[2] = coords[1];
					coords[1] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "-1,0": { //down
					// coords = ['x','z','-y']
					var temp = coords[1];
					coords[1] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,1": { //right
					// coords = ['z','y','-x']
					var temp = coords[0];
					coords[0] = coords[2];
					coords[2] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
				case "0,-1": { //left
					// coords = ['-z','y','x']
					var temp = coords[2];
					coords[2] = coords[0];
					coords[0] = (temp.length==1)?'-'+temp:temp[1];
				}; break;
			};

			console.log('coords after',coords);
		console.groupEnd();

		var tX = 0,tY=0,tZ=0;

		return new_angles;
	}

	function rotate3d(x,y,z,degree) {
		var matrix = new WebKitCSSMatrix(DOM.style.webkitTransform);
		matrix = matrix.rotateAxisAngle(x,y,z,degree);
		DOM.style.webkitTransform = matrix.toString();
	}
	rotate3d(-1,-1,0,30); // initial rotation

	return this;
}

var cube = new Cube('cube3d') // main cube object
cube.fill();

shortcut.add('up',function () {cube.make('top')});
shortcut.add('down',function () {cube.make('bottom')});
shortcut.add('left',function () {cube.make('left')});
shortcut.add('Right',function () {cube.make('right')});

function get_random_color (value) {
	Math.seedrandom(value);
    var color = 'rgba('+(Math.round(Math.random()*150)+55)+','+(Math.round(Math.random()*250)+5)+','+(Math.round(Math.random()*250)+5)+','+'.5)';
    Math.seedrandom();
    return color;
}<|endoftext|>