<commit_before>/*
 * Copyright 2015-2017 Jiří Janoušek <janousek.jiri@gmail.com>
 * Copyright 2017 Aleksey Zhidkov <aleksey.zhidkov@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

(function (Nuvola) {
  if (Nuvola.global === window) {
    /* Fix for broken detection of window.webkitAudioContext */
    var origHasOwnProperty = window.hasOwnProperty
    window.hasOwnProperty = function (key) {
      return origHasOwnProperty.call(window, key) && window[key] !== undefined
    }
  }

// Create media player component
  var player = Nuvola.$object(Nuvola.MediaPlayer)

// Handy aliases
  var PlaybackState = Nuvola.PlaybackState
  var PlayerAction = Nuvola.PlayerAction

// Create new WebApp prototype
  var WebApp = Nuvola.$WebApp()

// Translations
  var C_ = Nuvola.Translate.pgettext

  var ACTION_LIKE = 'like'

// Initialization routines
  WebApp._onInitWebWorker = function (emitter) {
    Nuvola.WebApp._onInitWebWorker.call(this, emitter)

    var state = document.readyState
    if (state === 'interactive' || state === 'complete') {
      this._onPageReady()
    } else {
      document.addEventListener('DOMContentLoaded', this._onPageReady.bind(this))
    }

    Nuvola.actions.addAction('like', 'win', ACTION_LIKE, C_('Action', 'Like'),
        null, null, null, true)
  }

// Page is ready for magic
  WebApp._onPageReady = function () {
    // Connect handler for signal ActionActivated
    Nuvola.actions.connect('ActionActivated', this)
    try {
      // Remove advertising sidebar
      document.querySelector('.centerblock-wrapper').setAttribute('style', 'width: 100%')
      var sidebar = document.querySelector('.sidebar__placeholder .sidebar')
      sidebar.parentNode.removeChild(sidebar)
    } catch (e) { /* ignored */ }

    player.addExtraActions([ACTION_LIKE])

    // Start update routine
    this.update()
  }

  WebApp._getShuffle = function () {
    var elm = this.getButtons().shuffle
    return elm ? elm.classList.contains('player-controls__btn_on') : null
  }

  WebApp._getRepeat = function () {
    var elm = this.getButtons().repeat
    if (!elm) {
      return null
    }

    if (elm.classList.contains('player-controls__btn_repeat_state1')) {
      return Nuvola.PlayerRepeat.PLAYLIST
    } else if (elm.classList.contains('player-controls__btn_repeat_state2')) {
      return Nuvola.PlayerRepeat.TRACK
    } else {
     return Nuvola.PlayerRepeat.NONE
    }
  }

  WebApp._setRepeat = function (repeat) {
    /*
     * There are mismatch between Nuvola's states order and Yandex.Music states order
     * and this map defines how much repeat button should be clicked, to change repeat state from current
     * to requested
     */
    var clicksMap = {
      "00": 0,
      "01": 2,
      "02": 1,
      "10": 1,
      "11": 0,
      "12": 2,
      "20": 2,
      "21": 1,
      "22": 0
    };
    var clicks = clicksMap[this._getRepeat() + "" + repeat]
    var repeat = this.getButtons().repeat
    for (var i = 0; i < clicks; i++) {
      Nuvola.clickOnElement(repeat)
    }
 }

// Extract data from the web page
  WebApp.update = function () {
    var track = {
      title: null,
      artist: null,
      album: null,
      artLocation: null
    }

    try {
      track.title = document.querySelector('.player-controls .track .track__title').innerText
      track.artist = document.querySelector('.player-controls .track .track__artists').innerText
      track.artLocation = document.querySelector('.player-controls .track .track-cover').src.replace(
            /\d+x\d+$/, '200x200')
    } catch (e) {
        // ~ console.log(e);
    }

    player.setTrack(track)

    var buttons = this.getButtons()
    var state = null
    if (buttons.pause) {
      state = PlaybackState.PLAYING
    } else if (buttons.play) {
      state = PlaybackState.PAUSED
    } else {
      state = PlaybackState.UNKNOWN
    }
    player.setPlaybackState(state)

    player.setCanGoPrev(!!buttons.prev)
    player.setCanGoNext(!!buttons.next)
    player.setCanPlay(!!buttons.play)
    player.setCanPause(!!buttons.pause)
    player.setCanShuffle(!!buttons.shuffle)
    player.setCanRepeat(!!buttons.repeat)

    player.setShuffleState(this._getShuffle())
    player.setRepeatState(this._getRepeat())

    var actionsEnabled = {}
    var actionsStates = {}
    actionsEnabled[ACTION_LIKE] = buttons.like != null && document.querySelector('.head__userpic') != null
    actionsStates[ACTION_LIKE] = buttons.like != null && document.querySelector('.d-like_on') != null
    Nuvola.actions.updateEnabledFlags(actionsEnabled)
    Nuvola.actions.updateStates(actionsStates)

    // Schedule the next update
    setTimeout(this.update.bind(this), 500)
  }

  WebApp.getButtons = function () {
    var notDisabled = function (selector) {
      var elm = document.querySelector(selector)
      return (elm && !elm.classList.contains('player-controls__btn_disabled')) ? elm : null
    }
    var playPause = notDisabled('.player-controls__btn_play')
    return {
      prev: notDisabled('.player-controls__btn_prev'),
      play: playPause && playPause.classList.contains('player-controls__btn_pause') ? null : playPause,
      pause: playPause && playPause.classList.contains('player-controls__btn_pause') ? playPause : null,
      next: notDisabled('.player-controls__btn_next'),
      like: document.querySelector('.player-controls__btn.d-like_theme-player'),
      shuffle: document.querySelector('.player-controls__btn_shuffle'),
      repeat: document.querySelector('.player-controls__btn_repeat')
    }
  }

// Handler of playback actions
  WebApp._onActionActivated = function (emitter, name, param) {
    var buttons = this.getButtons()
    switch (name) {
      case PlayerAction.TOGGLE_PLAY:
        if (buttons.play) {
          Nuvola.clickOnElement(buttons.play)
        } else if (buttons.pause) {
          Nuvola.clickOnElement(buttons.pause)
        }
        break
      case PlayerAction.PLAY:
        if (buttons.play) {
          Nuvola.clickOnElement(buttons.play)
        }
        break
      case PlayerAction.PAUSE:
      case PlayerAction.STOP:
        if (buttons.pause) {
          Nuvola.clickOnElement(buttons.pause)
        }
        break
      case PlayerAction.PREV_SONG:
        if (buttons.prev) {
          Nuvola.clickOnElement(buttons.prev)
        }
        break
      case PlayerAction.NEXT_SONG:
        if (buttons.next) {
          Nuvola.clickOnElement(buttons.next)
        }
        break
      case ACTION_LIKE:
        if (buttons.like) {
          Nuvola.clickOnElement(buttons.like)
        }
        break
      case PlayerAction.SHUFFLE:
        if (buttons.shuffle) {
          Nuvola.clickOnElement(buttons.shuffle)
        }
        break
      case PlayerAction.REPEAT:
        if (buttons.repeat) {
          this._setRepeat(param)
        }
        break
    }
  }

  WebApp.start()
})(this)  // function(Nuvola)
<commit_msg>Fix code style<commit_after>/*
 * Copyright 2015-2017 Jiří Janoušek <janousek.jiri@gmail.com>
 * Copyright 2017 Aleksey Zhidkov <aleksey.zhidkov@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

(function (Nuvola) {
  if (Nuvola.global === window) {
    /* Fix for broken detection of window.webkitAudioContext */
    var origHasOwnProperty = window.hasOwnProperty
    window.hasOwnProperty = function (key) {
      return origHasOwnProperty.call(window, key) && window[key] !== undefined
    }
  }

// Create media player component
  var player = Nuvola.$object(Nuvola.MediaPlayer)

// Handy aliases
  var PlaybackState = Nuvola.PlaybackState
  var PlayerAction = Nuvola.PlayerAction

// Create new WebApp prototype
  var WebApp = Nuvola.$WebApp()

// Translations
  var C_ = Nuvola.Translate.pgettext

  var ACTION_LIKE = 'like'

// Initialization routines
  WebApp._onInitWebWorker = function (emitter) {
    Nuvola.WebApp._onInitWebWorker.call(this, emitter)

    var state = document.readyState
    if (state === 'interactive' || state === 'complete') {
      this._onPageReady()
    } else {
      document.addEventListener('DOMContentLoaded', this._onPageReady.bind(this))
    }

    Nuvola.actions.addAction('like', 'win', ACTION_LIKE, C_('Action', 'Like'),
        null, null, null, true)
  }

// Page is ready for magic
  WebApp._onPageReady = function () {
    // Connect handler for signal ActionActivated
    Nuvola.actions.connect('ActionActivated', this)
    try {
      // Remove advertising sidebar
      document.querySelector('.centerblock-wrapper').setAttribute('style', 'width: 100%')
      var sidebar = document.querySelector('.sidebar__placeholder .sidebar')
      sidebar.parentNode.removeChild(sidebar)
    } catch (e) { /* ignored */ }

    player.addExtraActions([ACTION_LIKE])

    // Start update routine
    this.update()
  }

  WebApp._getShuffle = function () {
    var elm = this.getButtons().shuffle
    return elm ? elm.classList.contains('player-controls__btn_on') : null
  }

  WebApp._getRepeat = function () {
    var elm = this.getButtons().repeat
    if (!elm) {
      return null
    }

    if (elm.classList.contains('player-controls__btn_repeat_state1')) {
      return Nuvola.PlayerRepeat.PLAYLIST
    } else if (elm.classList.contains('player-controls__btn_repeat_state2')) {
      return Nuvola.PlayerRepeat.TRACK
    } else {
      return Nuvola.PlayerRepeat.NONE
    }
  }

  WebApp._setRepeat = function (repeat) {
    /*
     * There are mismatch between Nuvola's states order and Yandex.Music states order
     * and this map defines how much repeat button should be clicked, to change repeat state from current
     * to requested
     */
    var clicksMap = {
      '00': 0,
      '01': 2,
      '02': 1,
      '10': 1,
      '11': 0,
      '12': 2,
      '20': 2,
      '21': 1,
      '22': 0
    }
    var clicks = clicksMap[this._getRepeat() + '' + repeat]
    var repeatButton = this.getButtons().repeat
    for (var i = 0; i < clicks; i++) {
      Nuvola.clickOnElement(repeatButton)
    }
  }

// Extract data from the web page
  WebApp.update = function () {
    var track = {
      title: null,
      artist: null,
      album: null,
      artLocation: null
    }

    try {
      track.title = document.querySelector('.player-controls .track .track__title').innerText
      track.artist = document.querySelector('.player-controls .track .track__artists').innerText
      track.artLocation = document.querySelector('.player-controls .track .track-cover').src.replace(
            /\d+x\d+$/, '200x200')
    } catch (e) {
        // ~ console.log(e);
    }

    player.setTrack(track)

    var buttons = this.getButtons()
    var state = null
    if (buttons.pause) {
      state = PlaybackState.PLAYING
    } else if (buttons.play) {
      state = PlaybackState.PAUSED
    } else {
      state = PlaybackState.UNKNOWN
    }
    player.setPlaybackState(state)

    player.setCanGoPrev(!!buttons.prev)
    player.setCanGoNext(!!buttons.next)
    player.setCanPlay(!!buttons.play)
    player.setCanPause(!!buttons.pause)
    player.setCanShuffle(!!buttons.shuffle)
    player.setCanRepeat(!!buttons.repeat)

    player.setShuffleState(this._getShuffle())
    player.setRepeatState(this._getRepeat())

    var actionsEnabled = {}
    var actionsStates = {}
    actionsEnabled[ACTION_LIKE] = buttons.like != null && document.querySelector('.head__userpic') != null
    actionsStates[ACTION_LIKE] = buttons.like != null && document.querySelector('.d-like_on') != null
    Nuvola.actions.updateEnabledFlags(actionsEnabled)
    Nuvola.actions.updateStates(actionsStates)

    // Schedule the next update
    setTimeout(this.update.bind(this), 500)
  }

  WebApp.getButtons = function () {
    var notDisabled = function (selector) {
      var elm = document.querySelector(selector)
      return (elm && !elm.classList.contains('player-controls__btn_disabled')) ? elm : null
    }
    var playPause = notDisabled('.player-controls__btn_play')
    return {
      prev: notDisabled('.player-controls__btn_prev'),
      play: playPause && playPause.classList.contains('player-controls__btn_pause') ? null : playPause,
      pause: playPause && playPause.classList.contains('player-controls__btn_pause') ? playPause : null,
      next: notDisabled('.player-controls__btn_next'),
      like: document.querySelector('.player-controls__btn.d-like_theme-player'),
      shuffle: document.querySelector('.player-controls__btn_shuffle'),
      repeat: document.querySelector('.player-controls__btn_repeat')
    }
  }

// Handler of playback actions
  WebApp._onActionActivated = function (emitter, name, param) {
    var buttons = this.getButtons()
    switch (name) {
      case PlayerAction.TOGGLE_PLAY:
        if (buttons.play) {
          Nuvola.clickOnElement(buttons.play)
        } else if (buttons.pause) {
          Nuvola.clickOnElement(buttons.pause)
        }
        break
      case PlayerAction.PLAY:
        if (buttons.play) {
          Nuvola.clickOnElement(buttons.play)
        }
        break
      case PlayerAction.PAUSE:
      case PlayerAction.STOP:
        if (buttons.pause) {
          Nuvola.clickOnElement(buttons.pause)
        }
        break
      case PlayerAction.PREV_SONG:
        if (buttons.prev) {
          Nuvola.clickOnElement(buttons.prev)
        }
        break
      case PlayerAction.NEXT_SONG:
        if (buttons.next) {
          Nuvola.clickOnElement(buttons.next)
        }
        break
      case ACTION_LIKE:
        if (buttons.like) {
          Nuvola.clickOnElement(buttons.like)
        }
        break
      case PlayerAction.SHUFFLE:
        if (buttons.shuffle) {
          Nuvola.clickOnElement(buttons.shuffle)
        }
        break
      case PlayerAction.REPEAT:
        if (buttons.repeat) {
          this._setRepeat(param)
        }
        break
    }
  }

  WebApp.start()
})(this)  // function(Nuvola)
<|endoftext|>


<commit_before>// # Hello
//
// Foop
// This is a bit of documentation, try 'Read' above. Code can be written as semi-literate code, see more here <https://en.wikipedia.org/wiki/Literate_programming>

module.meta = {
  id: 'sample-app',
  name: 'Sample Application',
  version: '0.0.1'
};
var da = require('direape@0.1');
da.run(da.parent, 'appedit:html',`

Change me

Try to edit the code.

Choose Edit above, and then

     alter the code on the left side...

  (vi keybindings is enabled,

  so press <tt>i</tt> to insert)

${Object.keys(require('lodash')).join('
')}
`);<commit_msg>Commit sample-app.js via https://appedit.solsort.com/?Edit/js/gh/KodeKunstner/tutorial.<commit_after>// # Hi
//
// Fp
// This is a bit of documentation, try 'Read' above. Code can be written as semi-literate code, see more here <https://en.wikipedia.org/wiki/Literate_programming>

module.meta = {
  id: 'sample-app',
  name: 'Sample Application',
  version: '0.0.1'
};
var da = require('direape@0.1');
da.run(da.parent, 'appedit:html',`

Change me

Try to edit the code.

Choose Edit above, and then

     alter the code on the left side...

  (vi keybindings is enabled,

  so press <tt>i</tt> to insert)

${Object.keys(require('lodash')).join('
')}
`);<|endoftext|>


<commit_before>var ValidAccountOpening = (function(){
  var redirectCookie = function() {
    if (page.client.redirect_if_logout()) {
        return;
    }
    if (!page.client.is_virtual()) {
      window.location.href = page.url.url_for('user/my_accountws');
      return;
    }
    for (i = 0; i < page.user.loginid_array.length; i++){
      if (page.user.loginid_array[i].real === true){
        window.location.href = page.url.url_for('user/my_accountws');
        return;
      }
    }
  };
  var handler = function(response, message) {
    if (response.error) {
      var errorMessage = response.error.message;
      //IMPORTANT: change the code check later when shuwn yuan's changes are implemented
      if (response.error.code === 'invalid' && document.getElementById('financial-form')) {
        $('#financial-form').addClass('hidden');
        $('#financial-risk').removeClass('hidden');
        return;
      }
      if (document.getElementById('real-form')) {
        $('#real-form').remove();
      } else if (document.getElementById('japan-form')) {
        $('#japan-form').remove();
      } else if (document.getElementById('financial-form')) {
        $('#financial-form').remove();
        $('#financial-risk').remove();
      }
      var error = document.getElementsByClassName('notice-msg')[0];
      error.innerHTML = (response.msg_type === 'sanity_check') ? text.localize('There was some invalid character in an input field.') : errorMessage;
      error.parentNode.parentNode.parentNode.setAttribute('style', 'display:block');
      return;
    } else {
      var loginid = message.client_id;
      //set cookies
      var oldCookieValue = $.cookie('loginid_list');
      var cookie_domain = '.' + document.domain.split('.').slice(-2).join('.');
      $.cookie('loginid_list', loginid + ':R:E+' + oldCookieValue, {domain: cookie_domain, path:'/'});
      $.cookie('loginid', loginid, {domain: cookie_domain, path:'/'});
      // set a flag to push to gtm in my_account
      localStorage.setItem('new_account', '1');
      //generate dropdown list and switch
      page.client.clear_storage_values();
      var option = new Option('Real Account (' + loginid + ')', loginid);
      document.getElementById('client_loginid').appendChild(option);
      $('#client_loginid option[value="' + page.client.loginid + '"]').removeAttr('selected');
      option.setAttribute('selected', 'selected');
      $('#loginid-switch-form').submit();
    }
  };
  var letter, numbers, space, hyphen, period, apost;

  var initializeValues = function() {
    letters = Content.localize().textLetters;
    numbers = Content.localize().textNumbers;
    space   = Content.localize().textSpace;
    hyphen  = Content.localize().textHyphen;
    period  = Content.localize().textPeriod;
    apost   = Content.localize().textApost;
  };

  var checkFname = function(fname, errorFname) {
    if (Trim(fname.value).length < 2) {
      errorFname.innerHTML = Content.errorMessage('min', '2');
      Validate.displayErrorMessage(errorFname);
      window.accountErrorCounter++;
    } else if (!/^[a-zA-Z\s-.']+$/.test(fname.value)){
      initializeValues();
      errorFname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorFname);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkLname = function(lname, errorLname) {
    if (Trim(lname.value).length < 2) {
      errorLname.innerHTML = Content.errorMessage('min', '2');
      Validate.displayErrorMessage(errorLname);
      window.accountErrorCounter++;
    } else if (!/^[a-zA-Z\s-.']+$/.test(lname.value)){
      initializeValues();
      errorLname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorLname);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkDate = function(dobdd, dobmm, dobyy, errorDob) {
    if (!isValidDate(dobdd.value, dobmm.value, dobyy.value) || dobdd.value === '' || dobmm.value === '' || dobyy.value === '') {
      errorDob.innerHTML = Content.localize().textErrorBirthdate;
      Validate.displayErrorMessage(errorDob);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkPostcode = function(postcode, errorPostcode) {
    if (postcode.value !== '' && !/^[a-zA-Z\d-]+$/.test(postcode.value)){
      initializeValues();
      errorPostcode.innerHTML = Content.errorMessage('reg', [letters, numbers, hyphen]);
      Validate.displayErrorMessage(errorPostcode);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkTel = function(tel, errorTel) {
    if (tel.value.replace(/\+| /g,'').length < 6) {
      errorTel.innerHTML = Content.errorMessage('min', 6);
      Validate.displayErrorMessage(errorTel);
      window.accountErrorCounter++;
    } else if (!/^\+?[0-9\s]{6,35}$/.test(tel.value)){
      initializeValues();
      errorTel.innerHTML = Content.errorMessage('reg', [numbers, space]);
      Validate.displayErrorMessage(errorTel);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkAnswer = function(answer, errorAnswer) {
    if (answer.value.length < 4) {
      errorAnswer.innerHTML = Content.errorMessage('min', 4);
      Validate.displayErrorMessage(errorAnswer);
      window.accountErrorCounter++;
    }
    return;
  };
  return {
    redirectCookie: redirectCookie,
    handler: handler,
    checkFname: checkFname,
    checkLname: checkLname,
    checkDate: checkDate,
    checkPostcode: checkPostcode,
    checkTel: checkTel,
    checkAnswer: checkAnswer
  };
}());
<commit_msg>remove comment<commit_after>var ValidAccountOpening = (function(){
  var redirectCookie = function() {
    if (page.client.redirect_if_logout()) {
        return;
    }
    if (!page.client.is_virtual()) {
      window.location.href = page.url.url_for('user/my_accountws');
      return;
    }
    for (i = 0; i < page.user.loginid_array.length; i++){
      if (page.user.loginid_array[i].real === true){
        window.location.href = page.url.url_for('user/my_accountws');
        return;
      }
    }
  };
  var handler = function(response, message) {
    if (response.error) {
      var errorMessage = response.error.message;
      if (response.error.code === 'show risk disclaimer' && document.getElementById('financial-form')) {
        $('#financial-form').addClass('hidden');
        $('#financial-risk').removeClass('hidden');
        return;
      }
      if (document.getElementById('real-form')) {
        $('#real-form').remove();
      } else if (document.getElementById('japan-form')) {
        $('#japan-form').remove();
      } else if (document.getElementById('financial-form')) {
        $('#financial-form').remove();
        $('#financial-risk').remove();
      }
      var error = document.getElementsByClassName('notice-msg')[0];
      error.innerHTML = (response.msg_type === 'sanity_check') ? text.localize('There was some invalid character in an input field.') : errorMessage;
      error.parentNode.parentNode.parentNode.setAttribute('style', 'display:block');
      return;
    } else {
      var loginid = message.client_id;
      //set cookies
      var oldCookieValue = $.cookie('loginid_list');
      var cookie_domain = '.' + document.domain.split('.').slice(-2).join('.');
      $.cookie('loginid_list', loginid + ':R:E+' + oldCookieValue, {domain: cookie_domain, path:'/'});
      $.cookie('loginid', loginid, {domain: cookie_domain, path:'/'});
      // set a flag to push to gtm in my_account
      localStorage.setItem('new_account', '1');
      //generate dropdown list and switch
      page.client.clear_storage_values();
      var option = new Option('Real Account (' + loginid + ')', loginid);
      document.getElementById('client_loginid').appendChild(option);
      $('#client_loginid option[value="' + page.client.loginid + '"]').removeAttr('selected');
      option.setAttribute('selected', 'selected');
      $('#loginid-switch-form').submit();
    }
  };
  var letter, numbers, space, hyphen, period, apost;

  var initializeValues = function() {
    letters = Content.localize().textLetters;
    numbers = Content.localize().textNumbers;
    space   = Content.localize().textSpace;
    hyphen  = Content.localize().textHyphen;
    period  = Content.localize().textPeriod;
    apost   = Content.localize().textApost;
  };

  var checkFname = function(fname, errorFname) {
    if (Trim(fname.value).length < 2) {
      errorFname.innerHTML = Content.errorMessage('min', '2');
      Validate.displayErrorMessage(errorFname);
      window.accountErrorCounter++;
    } else if (!/^[a-zA-Z\s-.']+$/.test(fname.value)){
      initializeValues();
      errorFname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorFname);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkLname = function(lname, errorLname) {
    if (Trim(lname.value).length < 2) {
      errorLname.innerHTML = Content.errorMessage('min', '2');
      Validate.displayErrorMessage(errorLname);
      window.accountErrorCounter++;
    } else if (!/^[a-zA-Z\s-.']+$/.test(lname.value)){
      initializeValues();
      errorLname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorLname);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkDate = function(dobdd, dobmm, dobyy, errorDob) {
    if (!isValidDate(dobdd.value, dobmm.value, dobyy.value) || dobdd.value === '' || dobmm.value === '' || dobyy.value === '') {
      errorDob.innerHTML = Content.localize().textErrorBirthdate;
      Validate.displayErrorMessage(errorDob);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkPostcode = function(postcode, errorPostcode) {
    if (postcode.value !== '' && !/^[a-zA-Z\d-]+$/.test(postcode.value)){
      initializeValues();
      errorPostcode.innerHTML = Content.errorMessage('reg', [letters, numbers, hyphen]);
      Validate.displayErrorMessage(errorPostcode);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkTel = function(tel, errorTel) {
    if (tel.value.replace(/\+| /g,'').length < 6) {
      errorTel.innerHTML = Content.errorMessage('min', 6);
      Validate.displayErrorMessage(errorTel);
      window.accountErrorCounter++;
    } else if (!/^\+?[0-9\s]{6,35}$/.test(tel.value)){
      initializeValues();
      errorTel.innerHTML = Content.errorMessage('reg', [numbers, space]);
      Validate.displayErrorMessage(errorTel);
      window.accountErrorCounter++;
    }
    return;
  };
  var checkAnswer = function(answer, errorAnswer) {
    if (answer.value.length < 4) {
      errorAnswer.innerHTML = Content.errorMessage('min', 4);
      Validate.displayErrorMessage(errorAnswer);
      window.accountErrorCounter++;
    }
    return;
  };
  return {
    redirectCookie: redirectCookie,
    handler: handler,
    checkFname: checkFname,
    checkLname: checkLname,
    checkDate: checkDate,
    checkPostcode: checkPostcode,
    checkTel: checkTel,
    checkAnswer: checkAnswer
  };
}());
<|endoftext|>


<commit_before>CANVAS_WRAPPER = {

    drawImage: function (canvas) {

        this.canvasC = canvas

        this.draw = function (image, x, y) {

                this.canvasC.drawImage(image, x, y);

            }

        this.drawRotate = function (image, x, y, rot) {
            this.canvasC.save();
            this.canvasC.translate(x + (image.width / 2), y + (image.height / 2));
            this.canvasC.rotate(rot);
            this.canvasC.translate(-(image.width / 2) - x, -(image.height / 2) - y);
            this.canvasC.drawImage(image, x, y);
            this.canvasC.restore();
        }

        this.saveBackground = function (left, top, width, height) {

            this.backgroundPixels = this.canvasC.getImageData(left, top, width, height);
            this.bgX = left;
            this.bgY = top;
        }

        this.restoreBackground = function () {
            this.canvasC.putImageData(this.backgroundPixels, this.bgX, this.bgY);
        }
    },

    drawText: function (canvas, textParms) {

        this.canvasC = canvas;

        var HTML5TextParameters = ['fillStyle', 'font', 'textAlign', 'textBaseline'];
        var canvasPropStorage = {};

        this.font = textParms.font || "verdana";        //Default
        this.textColor = textParms.textColor || null;   // Use the canvas' value
        this.textAlignment = textParms.textAlignment || null;
        this.textBaseline = textParms.textBaseline || null;

        this.draw = function (text, x, y, width, length) {

                //Save the parameters.
                canvasPropStorage.tempBaseline = this.canvasC.textBaseline;
                canvasPropStorage.tempAlign = this.canvasC.textAlign;
                canvasPropStorage.tempFont = this.canvasC.font;
                canvasPropStorage.tempfillStyle = this.canvasC.fillStyle;

                if (this.textBaseline !== null) {
                    this.canvasC.textBaseline = this.textBaseline;
                }

                if (this.textAlignment!== null) {
                    this.canvasC.textAlign = this.textAlignment;
                }

                if (this.font !== null) {
                    this.canvasC.font = this.font;
                }

                if (this.textColor != null) {
                    this.canvasC.fillStyle = this.textColor;
                }

                //Write the label
                this.canvasC.fillText(text, x, y);

                this.canvasC.textBaseline = canvasPropStorage.tempBaseline;
                this.canvasC.textAlign = canvasPropStorage.tempAlign;
                this.canvasC.font = canvasPropStorage.tempFont;
                this.canvasC.fillStyle = canvasPropStorage.tempfillStyle;

            }

            this.saveBackground = function (left, top, width, height) {

                var xcoord,
                    ycoord,
                    wd,
                    hg;

                    xcoord = left;
                    ycoord = top;
                    wd = width;
                    hg = height;

                /* TODO check all the out of bounds
                 * and all the possibilities:
                 * https://developer.mozilla.org/en/drawing_text_using_a_canvas */
                if (this.textBaseline === 'bottom') {
                    ycoord = top - height;
                }
                if (this.textBaseline === 'middle') {
                    ycoord = top - height / 2;
                }
                if (this.textAlignment === 'end') {
                    xcoord = xcoord - wd;
                    if (xcoord < 0) {
                        xcoord = 0;
                    }
                }

                this.backgroundPixels = this.canvasC.getImageData(xcoord, ycoord, wd, hg);
                this.bgX = xcoord;
                this.bgY = ycoord;

            }

            this.restoreBackground = function () {

                this.canvasC.putImageData(this.backgroundPixels, this.bgX, this.bgY);

            }
    },

    drawRect: function (canvas) {

        function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
        function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
        function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
        function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
        function RGB2HTML(R, G, B) {
            var red = parseInt(R);
            var green = parseInt(G);
            var blue = parseInt(B);
            var hexcode = fillZero(red.toString(16)) + fillZero(green.toString(16)) + fillZero(blue.toString(16));
            return '#' + hexcode.toUpperCase();
        }

        function fillZero(myString) {
            if (myString.length == 1) return "0" + myString;
            else return myString;
        }

        this.canvasC = canvas;
        this.fillStyle = undefined;

        this.setFillStyle = function (color) {
            this.fillStyle = color;
        }

        this.setClearStyle = function (color) {
            this.clearStyle = color;
        }

        this.setStroke = function (stroke) {
            this.stroke = stroke;
        }

        /* TODO Maybe opacity? */
        this.draw = function (x, y, width, length, shade) {

            //Trasform the base color in RGB
            var R = HexToR(this.fillStyle);
            var G = HexToG(this.fillStyle);
            var B = HexToB(this.fillStyle);

            //Add "shade" to the RGB values
            R += shade;
            G += shade;
            B += shade;

            if (R < 0) {
                R = 0;
            }
            if (G < 0) {
                G = 0;
            }
            if (B < 0) {
                B = 0;
            }
            if (R > 255) {
                R = 255;
            }
            if (G > 255) {
                G = 255;
            }
            if (B > 255) {
                B = 255;
            }
            //Convert back to hex format.
            var realColor = RGB2HTML(R, G, B);

            this.reallyDraw (x,y, width, length, realColor);
        }

        this.draw = function (x, y, width, length, color) {

            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;

            // draw
            this.canvasC.fillStyle = color;
            this.canvasC.fillRect (x, y,  width, length);

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;
        }
    },

    drawPoint: function (canvas, color, dimension) {

        this.canvasC = canvas;
        this.fillStyle = color;
        this.dimension = dimension;

        this.draw = function (x, y) {
            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;
            this.canvasC.fillStyle = this.fillStyle;

            this.canvasC.fillRect(x, y, this.dimension, this.dimension);

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;

        }
    },

    drawPath: function (canvas, pathParms) {

        this.canvasC = canvas;
        this.inited = false;
        this.pathColor = pathParms.pathColor || null;
        // To be implemented
        this.pathDimension = pathParms.pathDimension;

        this.draw = function (x, y) {

            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;
            this.canvasC.fillStyle = this.pathColor;

            if (this.inited === false) {
                this.canvasC.beginPath();
                this.canvasC.moveTo(x, y);
                this.inited = true;
            }
            else {
                this.canvasC.lineTo(x, y);
            }

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;
        }

        // Redundant.
        this.beginDraw = function () {
            this.inited = false;
        }

        this.endDraw = function () {

            this.inited = false;
            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;
            this.canvasC.fillStyle = this.fillStyle;

            this.canvasC.stroke();

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;
        }

        // These should be in the wrappers interface. TODO THIS IS DUPLICATE CODE!!!
        this.saveBackground = function (left, top, width, height) {

            this.backgroundPixels = this.canvasC.getImageData(left, top, width, height);
            this.bgX = left;
            this.bgY = top;
        }

        this.restoreBackground = function () {
            this.canvasC.putImageData(this.backgroundPixels, this.bgX, this.bgY);
        }
    },

   staticMethods : {
        // General purpose 2d saver/restorer.
        save2d: function (that, left, top, width, height) {
            that.backgroundPixels = that.canvasC.getImageData(left, top, width, height);
            that.bgX = left;
            that.bgY = top;
        },

        restore2d: function (that) {
            that.canvasC.putImageData(that.backgroundPixels, that.bgX, that.bgY);
        },

        reset: function (that) {
            that.canvasC.width = that.canvasC.width;
        }
    }
}<commit_msg>Added a trivial TODO line.<commit_after>CANVAS_WRAPPER = {

    drawImage: function (canvas) {

        this.canvasC = canvas

        this.draw = function (image, x, y) {

                this.canvasC.drawImage(image, x, y);

            }

        this.drawRotate = function (image, x, y, rot, rot_type /* = center TODO */) {
            this.canvasC.save();
            this.canvasC.translate(x + (image.width / 2), y + (image.height / 2));
            this.canvasC.rotate(rot);
            this.canvasC.translate(-(image.width / 2) - x, -(image.height / 2) - y);
            this.canvasC.drawImage(image, x, y);
            this.canvasC.restore();
        }

        this.saveBackground = function (left, top, width, height) {

            this.backgroundPixels = this.canvasC.getImageData(left, top, width, height);
            this.bgX = left;
            this.bgY = top;
        }

        this.restoreBackground = function () {
            this.canvasC.putImageData(this.backgroundPixels, this.bgX, this.bgY);
        }
    },

    drawText: function (canvas, textParms) {

        this.canvasC = canvas;

        var HTML5TextParameters = ['fillStyle', 'font', 'textAlign', 'textBaseline'];
        var canvasPropStorage = {};

        this.font = textParms.font || "verdana";        //Default
        this.textColor = textParms.textColor || null;   // Use the canvas' value
        this.textAlignment = textParms.textAlignment || null;
        this.textBaseline = textParms.textBaseline || null;

        this.draw = function (text, x, y, width, length) {

                //Save the parameters.
                canvasPropStorage.tempBaseline = this.canvasC.textBaseline;
                canvasPropStorage.tempAlign = this.canvasC.textAlign;
                canvasPropStorage.tempFont = this.canvasC.font;
                canvasPropStorage.tempfillStyle = this.canvasC.fillStyle;

                if (this.textBaseline !== null) {
                    this.canvasC.textBaseline = this.textBaseline;
                }

                if (this.textAlignment!== null) {
                    this.canvasC.textAlign = this.textAlignment;
                }

                if (this.font !== null) {
                    this.canvasC.font = this.font;
                }

                if (this.textColor != null) {
                    this.canvasC.fillStyle = this.textColor;
                }

                //Write the label
                this.canvasC.fillText(text, x, y);

                this.canvasC.textBaseline = canvasPropStorage.tempBaseline;
                this.canvasC.textAlign = canvasPropStorage.tempAlign;
                this.canvasC.font = canvasPropStorage.tempFont;
                this.canvasC.fillStyle = canvasPropStorage.tempfillStyle;

            }

            this.saveBackground = function (left, top, width, height) {

                var xcoord,
                    ycoord,
                    wd,
                    hg;

                    xcoord = left;
                    ycoord = top;
                    wd = width;
                    hg = height;

                /* TODO check all the out of bounds
                 * and all the possibilities:
                 * https://developer.mozilla.org/en/drawing_text_using_a_canvas */
                if (this.textBaseline === 'bottom') {
                    ycoord = top - height;
                }
                if (this.textBaseline === 'middle') {
                    ycoord = top - height / 2;
                }
                if (this.textAlignment === 'end') {
                    xcoord = xcoord - wd;
                    if (xcoord < 0) {
                        xcoord = 0;
                    }
                }

                this.backgroundPixels = this.canvasC.getImageData(xcoord, ycoord, wd, hg);
                this.bgX = xcoord;
                this.bgY = ycoord;

            }

            this.restoreBackground = function () {

                this.canvasC.putImageData(this.backgroundPixels, this.bgX, this.bgY);

            }
    },

    drawRect: function (canvas) {

        function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
        function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
        function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
        function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
        function RGB2HTML(R, G, B) {
            var red = parseInt(R);
            var green = parseInt(G);
            var blue = parseInt(B);
            var hexcode = fillZero(red.toString(16)) + fillZero(green.toString(16)) + fillZero(blue.toString(16));
            return '#' + hexcode.toUpperCase();
        }

        function fillZero(myString) {
            if (myString.length == 1) return "0" + myString;
            else return myString;
        }

        this.canvasC = canvas;
        this.fillStyle = undefined;

        this.setFillStyle = function (color) {
            this.fillStyle = color;
        }

        this.setClearStyle = function (color) {
            this.clearStyle = color;
        }

        this.setStroke = function (stroke) {
            this.stroke = stroke;
        }

        /* TODO Maybe opacity? */
        this.draw = function (x, y, width, length, shade) {

            //Trasform the base color in RGB
            var R = HexToR(this.fillStyle);
            var G = HexToG(this.fillStyle);
            var B = HexToB(this.fillStyle);

            //Add "shade" to the RGB values
            R += shade;
            G += shade;
            B += shade;

            if (R < 0) {
                R = 0;
            }
            if (G < 0) {
                G = 0;
            }
            if (B < 0) {
                B = 0;
            }
            if (R > 255) {
                R = 255;
            }
            if (G > 255) {
                G = 255;
            }
            if (B > 255) {
                B = 255;
            }
            //Convert back to hex format.
            var realColor = RGB2HTML(R, G, B);

            this.reallyDraw (x,y, width, length, realColor);
        }

        this.draw = function (x, y, width, length, color) {

            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;

            // draw
            this.canvasC.fillStyle = color;
            this.canvasC.fillRect (x, y,  width, length);

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;
        }
    },

    drawPoint: function (canvas, color, dimension) {

        this.canvasC = canvas;
        this.fillStyle = color;
        this.dimension = dimension;

        this.draw = function (x, y) {
            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;
            this.canvasC.fillStyle = this.fillStyle;

            this.canvasC.fillRect(x, y, this.dimension, this.dimension);

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;

        }
    },

    drawPath: function (canvas, pathParms) {

        this.canvasC = canvas;
        this.inited = false;
        this.pathColor = pathParms.pathColor || null;
        // To be implemented
        this.pathDimension = pathParms.pathDimension;

        this.draw = function (x, y) {

            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;
            this.canvasC.fillStyle = this.pathColor;

            if (this.inited === false) {
                this.canvasC.beginPath();
                this.canvasC.moveTo(x, y);
                this.inited = true;
            }
            else {
                this.canvasC.lineTo(x, y);
            }

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;
        }

        // Redundant.
        this.beginDraw = function () {
            this.inited = false;
        }

        this.endDraw = function () {

            this.inited = false;
            //Save fillStyle.
            var tempfillStyle = this.canvasC.fillStyle;
            this.canvasC.fillStyle = this.fillStyle;

            this.canvasC.stroke();

            // Restore fillStyle
            this.canvasC.fillStyle = tempfillStyle;
        }

        // These should be in the wrappers interface. TODO THIS IS DUPLICATE CODE!!!
        this.saveBackground = function (left, top, width, height) {

            this.backgroundPixels = this.canvasC.getImageData(left, top, width, height);
            this.bgX = left;
            this.bgY = top;
        }

        this.restoreBackground = function () {
            this.canvasC.putImageData(this.backgroundPixels, this.bgX, this.bgY);
        }
    },

   staticMethods : {
        // General purpose 2d saver/restorer.
        save2d: function (that, left, top, width, height) {
            that.backgroundPixels = that.canvasC.getImageData(left, top, width, height);
            that.bgX = left;
            that.bgY = top;
        },

        restore2d: function (that) {
            that.canvasC.putImageData(that.backgroundPixels, that.bgX, that.bgY);
        },

        reset: function (that) {
            that.canvasC.width = that.canvasC.width;
        }
    }
}<|endoftext|>


<commit_before>module.exports = {

  /**
   * ### config.includeStack
   *
   * User configurable property, influences whether stack trace
   * is included in Assertion error message. Default of false
   * suppresses stack trace in the error message.
   *
   *     chai.config.includeStack = true;  // enable stack on error
   *
   * @param {Boolean}
   * @api public
   */

  includeStack: false,

  /**
   * ### config.showDiff
   *
   * User configurable property, influences whether or not
   * the `showDiff` flag should be included in the thrown
   * AssertionErrors. `false` will always be `false`; `true`
   * will be true when the assertion has requested a diff
   * be shown.
   *
   * @param {Boolean}
   * @api public
   */

  showDiff: true,

  /**
   * ### config.truncateThreshold
   *
   * User configurable property, sets length threshold for actual and
   * expected values in assertion errors. If this threshold is exceeded, for
   * example for large data structures, the value is replaced with something
   * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`.
   *
   * Set it to zero if you want to disable truncating altogether.
   *
   * This is especially userful when doing assertions on arrays: having this
   * set to a reasonable large value makes the failure messages readily
   * inspectable.
   *
   *     chai.config.truncateThreshold = 0;  // disable truncating
   *
   * @param {Number}
   * @api public
   */

  truncateThreshold: 40,

  /**
   * ### config.useProxy
   *
   * User configurable property, defines if chai will use a Proxy to throw
   * an error when a non-existent property is read, which protects users
   * from typos when using property-based assertions.
   *
   * Set it to false if you want to disable this feature.
   *
   *     chai.config.useProxy = false;  // disable use of Proxy
   *
   * This feature is automatically disabled regardless of this config value
   * in environments that don`t support proxies.
   *
   * @param {Boolean}
   * @api public
   */

  useProxy: true
};
<commit_msg>Fix backtick which should have been an apostrophe<commit_after>module.exports = {

  /**
   * ### config.includeStack
   *
   * User configurable property, influences whether stack trace
   * is included in Assertion error message. Default of false
   * suppresses stack trace in the error message.
   *
   *     chai.config.includeStack = true;  // enable stack on error
   *
   * @param {Boolean}
   * @api public
   */

  includeStack: false,

  /**
   * ### config.showDiff
   *
   * User configurable property, influences whether or not
   * the `showDiff` flag should be included in the thrown
   * AssertionErrors. `false` will always be `false`; `true`
   * will be true when the assertion has requested a diff
   * be shown.
   *
   * @param {Boolean}
   * @api public
   */

  showDiff: true,

  /**
   * ### config.truncateThreshold
   *
   * User configurable property, sets length threshold for actual and
   * expected values in assertion errors. If this threshold is exceeded, for
   * example for large data structures, the value is replaced with something
   * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`.
   *
   * Set it to zero if you want to disable truncating altogether.
   *
   * This is especially userful when doing assertions on arrays: having this
   * set to a reasonable large value makes the failure messages readily
   * inspectable.
   *
   *     chai.config.truncateThreshold = 0;  // disable truncating
   *
   * @param {Number}
   * @api public
   */

  truncateThreshold: 40,

  /**
   * ### config.useProxy
   *
   * User configurable property, defines if chai will use a Proxy to throw
   * an error when a non-existent property is read, which protects users
   * from typos when using property-based assertions.
   *
   * Set it to false if you want to disable this feature.
   *
   *     chai.config.useProxy = false;  // disable use of Proxy
   *
   * This feature is automatically disabled regardless of this config value
   * in environments that don't support proxies.
   *
   * @param {Boolean}
   * @api public
   */

  useProxy: true
};
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Michael Nye <thenyeguy@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

(function(Nuvola)
{

    // Create media player component
    var player = Nuvola.$object(Nuvola.MediaPlayer);

    // Handy aliases
    var PlaybackState = Nuvola.PlaybackState;
    var PlayerAction = Nuvola.PlayerAction;

    // Create new WebApp prototype
    var WebApp = Nuvola.$WebApp();

    // Create flowplayer API object
    var kexpApi = null;

    function get_api() {
        // Uses a loop because the API often doesn't connect right away
        var api = null;
        while(api == null)
            api = flowplayer();
        return api;
    }

    // Initialization routines
    WebApp._onInitWebWorker = function(emitter)
    {
        Nuvola.WebApp._onInitWebWorker.call(this, emitter);

        var state = document.readyState;
        if (state === "interactive" || state === "complete")
            this._onPageReady();
        else
            document.addEventListener("DOMContentLoaded",
                    this._onPageReady.bind(this));
    }

    // Page is ready for magic
    WebApp._onPageReady = function()
    {
        // Connect handler for signal ActionActivated
        Nuvola.actions.connect("ActionActivated", this);

        // Set default action states
        player.setCanPlay(false);
        player.setCanPause(false);
        player.setCanGoPrev(false);
        player.setCanGoNext(false);

        kexpApi = get_api();
        console.log("api: " + kexpApi);
        kexpApi.bind("pause", function(e, api) {
            // do your thing
        });

        // Start update routine
        this.update();
    }

    // Extract data from the web page
    WebApp.update = function()
    {
        // Scrape track info
        var track = document.getElementById("track").innerText
        var artist = document.getElementById("artistname").innerText
        var album = document.getElementById("album").innerText
        var track = {
            title: track,
            artist: artist,
            album: album,
            artLocation: null
        }

        // Set default state
        var state = PlaybackState.UNKNOWN;
        if(kexpApi.isPlaying())
        {
            state = PlaybackState.PLAYING;
            player.setCanPlay(false);
            player.setCanPause(true);
        }
        else
        {
            state = PlaybackState.PAUSED;
            player.setCanPlay(true);
            player.setCanPause(false);
        }

        player.setTrack(track);
        player.setPlaybackState(state);

        // Schedule the next update
        setTimeout(this.update.bind(this), 500);
    }

    // Handler of playback actions
    WebApp._onActionActivated = function(emitter, name, param)
    {
        switch(name)
        {
            case PlayerAction.TOGGLE_PLAY:
                if(kexpApi.isPlaying())
                    kexpApi.pause();
                else
                    kexpApi.play();
                break;
            case PlayerAction.PLAY:
                kexpApi.play();
                break;
            case PlayerAction.PAUSE:
                kexpApi.pause();
                break;
        }
    }

    WebApp.start();
})(this);
<commit_msg>Better uses the flowplayer api<commit_after>/*
 * Copyright 2015 Michael Nye <thenyeguy@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

(function(Nuvola)
{

    // Create media player component
    var player = Nuvola.$object(Nuvola.MediaPlayer);

    // Handy aliases
    var PlaybackState = Nuvola.PlaybackState;
    var PlayerAction = Nuvola.PlayerAction;

    // Create new WebApp prototype
    var WebApp = Nuvola.$WebApp();

    // Create flowplayer API object
    var kexpApi = null;

    function getApi() {
        // Uses a loop because the API often doesn't connect right away
        console.log("Loading flowplayer API...")
        var api = null;
        while(api == null)
            api = flowplayer();
        console.log("API loaded.")
        return api;
    }

    // Initialization routines
    WebApp._onInitWebWorker = function(emitter)
    {
        Nuvola.WebApp._onInitWebWorker.call(this, emitter);

        var state = document.readyState;
        if (state === "interactive" || state === "complete")
            this._onPageReady();
        else
            document.addEventListener("DOMContentLoaded",
                    this._onPageReady.bind(this));
    }

    // Page is ready for magic
    WebApp._onPageReady = function()
    {
        // Connect handler for signal ActionActivated
        Nuvola.actions.connect("ActionActivated", this);

        // Set default action states
        console.log("Setting action states")
        player.setCanPlay(false);
        player.setCanPause(false);
        player.setCanGoPrev(false);
        player.setCanGoNext(false);

        // Configure API hooks
        kexpApi = getApi();
        kexpApi.onStart(function(clip) {
            console.log("audio started");
            player.setCanPlay(false);
            player.setCanPause(true);
        });
        kexpApi.onStop(function(clip) {
            console.log("audio started");
            player.setCanPlay(true);
            player.setCanPause(false);
        });

        // Start update routine
        this.update();
    }

    // Extract data from the web page
    WebApp.update = function()
    {
        console.log("Updating...");
        // Scrape track info
        var track = document.getElementById("track").innerText
        var artist = document.getElementById("artistname").innerText
        var album = document.getElementById("album").innerText
        var track = {
            title: track,
            artist: artist,
            album: album,
            artLocation: null
        }
        console.log("Track: " + track);

        // Set default state
        var state = PlaybackState.UNKNOWN;
        if(kexpApi.isPlaying())
            state = PlaybackState.PLAYING;
        else
            state = PlaybackState.PAUSED;
        console.log("State: " + state);

        player.setTrack(track);
        player.setPlaybackState(state);

        // Schedule the next update
        console.log("Setting timeout");
        setTimeout(this.update.bind(this), 500);
    }

    // Handler of playback actions
    WebApp._onActionActivated = function(emitter, name, param)
    {
        console.log("_onActionActivated: " + name);
        switch(name)
        {
            case PlayerAction.TOGGLE_PLAY:
                if(kexpApi.isPlaying())
                    kexpApi.pause();
                else
                    kexpApi.play();
                break;
            case PlayerAction.PLAY:
                kexpApi.play();
                break;
            case PlayerAction.PAUSE:
                kexpApi.pause();
                break;
        }
    }

    WebApp.start();
})(this);
<|endoftext|>


<commit_before>var gearman = require('gearman-coffee');
var gearsloth = require('../gearsloth');
var logger = require('../log');
var Worker = gearman.Worker;

module.exports = function(conf) {

  // adapter backend
  function save(task, worker) {
    try {
      conf.dbconn.saveTask(task, function(err) {
        if (err) logger.err(err);
        return worker.complete();
      });
    }
    catch(err) {
      logger.err(err);
      process.exit(1);
    };
  }

  // gearman interface
  var injector = new Worker('submitJobDelayed', function(payload, worker) {
    var task = gearsloth.decodeTask(payload);
    save(task, worker);
  });
};
<commit_msg>WORK_FAIL on error in injector<commit_after>var gearman = require('gearman-coffee');
var gearsloth = require('../gearsloth');
var logger = require('../log');
var Worker = gearman.Worker;

module.exports = function(conf) {

  // adapter backend
  function save(task, worker) {
    try {
      conf.dbconn.saveTask(task, function(err) {
        if (err) {
          logger.err(err);
          worker.error();
        } else {
          worker.complete();
        }
      });
    }
    catch(err) {
      logger.err(err);
      process.exit(1);
    };
  }

  // gearman interface
  var injector = new Worker('submitJobDelayed', function(payload, worker) {
    var task = gearsloth.decodeTask(payload);
    save(task, worker);
  });
};
<|endoftext|>


<commit_before>// tap :: Function -> TransformStream
// tap function takes a function as
// argument and returns a transform stream
// that applies the function to the incoming
// values before re-emitting them.
//

import Pipe from "@pipes/core/pipe";

export default function tap(func) {

  return new Pipe( chunk => {

    // Apply
    func( chunk );
    return chunk;
  });
}

// Browserify compat
if ( typeof module !== "undefined" )
  module.exports = tap;

<commit_msg>Added flow types to tap<commit_after>// @flow

// tap :: Function -> TransformStream
// tap function takes a function as
// argument and returns a transform stream
// that applies the function to the incoming
// values before re-emitting them.
//

import type { ReadableWritable } from "@pipes/core/streams";
import type { anyFn } from "@pipes/core/utils";

import Pipe from "@pipes/core/pipe";

export default function tap(func: anyFn): ReadableWritable {

  return new Pipe( (chunk: mixed) => {

    // Apply
    func( chunk );
    return chunk;
  });
}

// Browserify compat
if ( typeof module !== "undefined" )
  // $FlowFixMe
  module.exports = tap;
<|endoftext|>


<commit_before>"use strict";

var settings = {
	logLevel: 100,
	whiteList: "",
	blackList: "",
	blockMode: "fakeReadout",
	minFakeSize: 1,
	maxFakeSize: 0,
	rng: "nonPersistent",
	useCanvasCache: true,
	ignoreFrequentColors: 0,
	fakeAlphaChannel: false,
	persistentRndStorage: "",
	storePersistentRnd: false,
	askOnlyOnce: true,
	showNotifications: true,
	storeImageForInspection: false,
	notificationDisplayTime: 30,
	ignoreList: "",
	showCallingFile: false,
	showCompleteCallingStack: false,
	enableStackList: false,
	stackList: "",
	displayAdvancedSettings: false,
	isStillDefault: true
};<commit_msg>Cleanup of the default settings.<commit_after>"use strict";

var settings = {
	logLevel: 1,
	whiteList: "",
	blackList: "",
	blockMode: "fakeReadout",
	minFakeSize: 1,
	maxFakeSize: 0,
	rng: "nonPersistent",
	useCanvasCache: true,
	ignoreFrequentColors: 0,
	fakeAlphaChannel: false,
	persistentRndStorage: "",
	storePersistentRnd: false,
	askOnlyOnce: true,
	showNotifications: true,
	storeImageForInspection: false,
	ignoreList: "",
	showCallingFile: false,
	showCompleteCallingStack: false,
	enableStackList: false,
	stackList: "",
	displayAdvancedSettings: false,

	// indicator if the real settings are loaded already
	isStillDefault: true
};<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
        'Widgets/InfoBox/InfoBox',
        'Core/defined'
    ], function(
        InfoBox,
        defined) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var testContainer;
    var infoBox;
    beforeEach(function() {
        testContainer = document.createElement('span');
        testContainer.id = 'testContainer';
        document.body.appendChild(testContainer);
    });

    afterEach(function() {
        if (defined(infoBox) && !infoBox.isDestroyed()) {
            infoBox = infoBox.destroy();
        }
        document.body.removeChild(testContainer);
    });

    it('constructor sets expected values', function() {
        infoBox = new InfoBox(testContainer);
        expect(infoBox.container).toBe(testContainer);
        expect(infoBox.viewModel).toBeDefined();
        expect(infoBox.isDestroyed()).toEqual(false);
        infoBox.destroy();
        expect(infoBox.isDestroyed()).toEqual(true);
    });

    it('can set description body', function() {
        var infoBox = new InfoBox(testContainer);
        var node;

        var infoElement = testContainer.firstChild;

        infoBox.viewModel.description = 'Please do not crash';
        waitsFor(function() {
            node = infoBox.frame.contentDocument.body.firstChild;
            return node !== null;
        });

        runs(function() {
            expect(infoElement.style['background-color']).toEqual('');
        });

        waitsFor(function() {
            return node.innerHTML === infoBox.viewModel.description;
        });

        runs(function() {
            infoBox.viewModel.description = '
Please do not crash
';
            expect(infoElement.style['background-color']).toEqual('rgb(255, 255, 255)');
        });

        waitsFor(function() {
            return node.innerHTML === infoBox.viewModel.description;
        });

        runs(function() {
            expect(infoElement['background-color']).toBeUndefined();
        });
    });

    it('constructor works with string id container', function() {
        infoBox = new InfoBox('testContainer');
        expect(infoBox.container).toBe(testContainer);
    });

    it('throws if container is undefined', function() {
        expect(function() {
            return new InfoBox(undefined);
        }).toThrowDeveloperError();
    });

    it('throws if container string is undefined', function() {
        expect(function() {
            return new InfoBox('foo');
        }).toThrowDeveloperError();
    });
});<commit_msg>Fix IE-only test failure<commit_after>/*global defineSuite*/
defineSuite([
        'Widgets/InfoBox/InfoBox',
        'Core/defined'
    ], function(
        InfoBox,
        defined) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var testContainer;
    var infoBox;
    beforeEach(function() {
        testContainer = document.createElement('span');
        testContainer.id = 'testContainer';
        document.body.appendChild(testContainer);
    });

    afterEach(function() {
        if (defined(infoBox) && !infoBox.isDestroyed()) {
            infoBox = infoBox.destroy();
        }
        document.body.removeChild(testContainer);
    });

    it('constructor sets expected values', function() {
        infoBox = new InfoBox(testContainer);
        expect(infoBox.container).toBe(testContainer);
        expect(infoBox.viewModel).toBeDefined();
        expect(infoBox.isDestroyed()).toEqual(false);
        infoBox.destroy();
        expect(infoBox.isDestroyed()).toEqual(true);
    });

    it('can set description body', function() {
        var infoBox = new InfoBox(testContainer);
        var node;

        var infoElement = testContainer.firstChild;

        infoBox.viewModel.description = 'Please do not crash';
        waitsFor(function() {
            node = infoBox.frame.contentDocument.body.firstChild;
            return node !== null;
        });

        runs(function() {
            expect(infoElement.style['background-color']).toEqual('');
        });

        waitsFor(function() {
            return node.innerHTML === infoBox.viewModel.description;
        });

        runs(function() {
            infoBox.viewModel.description = '
Please do not crash
';
            expect(infoElement.style['background-color']).toEqual('rgb(255, 255, 255)');
        });

        waitsFor(function() {
            return node.innerHTML === infoBox.viewModel.description;
        });

        runs(function() {
            expect(infoElement['background-color']).toBeUndefined();
        });
    });

    it('constructor works with string id container', function() {
        infoBox = new InfoBox('testContainer');
        expect(infoBox.container).toBe(testContainer);
    });

    it('throws if container is undefined', function() {
        expect(function() {
            return new InfoBox(undefined);
        }).toThrowDeveloperError();
    });

    it('throws if container string is undefined', function() {
        expect(function() {
            return new InfoBox('foo');
        }).toThrowDeveloperError();
    });
});<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var sumArrayOfStringsAsInts = function(n) {
    var sum = 0;
    for (var i=0;i<n.length;++i) {
      sum += n[i]|0;
    }
    return sum;
};

var tokenize = function(s, delim) {
  s = s.replace(/\n/g, delim);
  return s.split(delim);
};

var StringCalculator = function() {
  StringCalculator.prototype.add = function(s) {
    if (s.length === 0) {
      return 0;
    }

    var result = getDelimiter(s);

    var tokens = tokenize(result.line,result.delimiter);
    return sumArrayOfStringsAsInts(tokens);
  };
  return this;
};

var hasCustomDelimiter = function(s) {
  return s.indexOf('//') === 0;
};

var getDelimiter = function(s) {
  if (hasCustomDelimiter(s)) {
    return {
      delimiter: s.substr(2, s.indexOf('\n') - 2),
      line: s.substr(s.indexOf('\n') + 1)
    };
  }

  return { delimiter: ',', line: s };
};

describe('string calculator', function() {
  it('exists', function() {
    assert(new StringCalculator());
  });

  it('has an add method', function() {
    assert(new StringCalculator().add);
  });

  describe('delimiters', function() {
    it('knows about custom delimters', function() {
      assert(hasCustomDelimiter('//q\n1q2q3'));
    });

    it('ignores normal delimters', function() {
      assert(!hasCustomDelimiter('1,2,3'));
    });

    it('returns delimiter', function() {
      var s = getDelimiter('//q\n1q2q3');
      assert('q', s.delimiter);
    });

    it('returns default delimiters', function() {
      var s = getDelimiter('1,2,3');
      assert(',', s.delimiter);
    });

    it('consumes some of the string', function() {
      assert.equal('1,2,3', getDelimiter('1,2,3').line);
      assert.equal('1q2q3', getDelimiter('//q\n1q2q3').line);
    });
  });

  describe('add method', function() {
    var stringCalculator = new StringCalculator();

    it('0 args', function() {
      assert.equal(0, stringCalculator.add(''));
    });

    it('1 arg', function() {
      assert.equal(55, stringCalculator.add('55'));
    });

    it('2 args', function() {
      assert.equal(74, stringCalculator.add('69,5'));
    });

    it('n args', function() {
      assert.equal(1+2+3+4+5, stringCalculator.add('1,2,3,4,5'));
    });

    it('handles new lines as separators', function() {
      assert.equal(1+2+3, stringCalculator.add('1\n2\n3'));
    });

    it('supports delimiters', function() {
      assert.equal(1+2+3, stringCalculator.add('//q\n1q2q3'));
    });

    it('dislikes negatives', function() {
      assert.throws(function() {
        stringCalculator.add('1,-2,3');
      });
    });
  });
});<commit_msg>throw an exception with negatives not allowed<commit_after>"use strict";

var assert = require('assert');

var sumArrayOfStringsAsInts = function(n) {
    var sum = 0;
    for (var i=0;i<n.length;++i) {
      if ((n[i]|0) < 0) {
        throw Error('Negatives not allowed');
      }
      sum += n[i]|0;
    }
    return sum;
};

var tokenize = function(s, delim) {
  s = s.replace(/\n/g, delim);
  return s.split(delim);
};

var StringCalculator = function() {
  StringCalculator.prototype.add = function(s) {
    if (s.length === 0) {
      return 0;
    }

    var result = getDelimiter(s);
    var tokens = tokenize(result.line,result.delimiter);
    return sumArrayOfStringsAsInts(tokens);
  };
  return this;
};

var hasCustomDelimiter = function(s) {
  return s.indexOf('//') === 0;
};

var getDelimiter = function(s) {
  if (hasCustomDelimiter(s)) {
    return {
      delimiter: s.substr(2, s.indexOf('\n') - 2),
      line: s.substr(s.indexOf('\n') + 1)
    };
  }

  return { delimiter: ',', line: s };
};

describe('string calculator', function() {
  it('exists', function() {
    assert(new StringCalculator());
  });

  it('has an add method', function() {
    assert(new StringCalculator().add);
  });

  describe('delimiters', function() {
    it('knows about custom delimters', function() {
      assert(hasCustomDelimiter('//q\n1q2q3'));
    });

    it('ignores normal delimters', function() {
      assert(!hasCustomDelimiter('1,2,3'));
    });

    it('returns delimiter', function() {
      var s = getDelimiter('//q\n1q2q3');
      assert('q', s.delimiter);
    });

    it('returns default delimiters', function() {
      var s = getDelimiter('1,2,3');
      assert(',', s.delimiter);
    });

    it('consumes some of the string', function() {
      assert.equal('1,2,3', getDelimiter('1,2,3').line);
      assert.equal('1q2q3', getDelimiter('//q\n1q2q3').line);
    });
  });

  describe('add method', function() {
    var stringCalculator = new StringCalculator();

    it('0 args', function() {
      assert.equal(0, stringCalculator.add(''));
    });

    it('1 arg', function() {
      assert.equal(55, stringCalculator.add('55'));
    });

    it('2 args', function() {
      assert.equal(74, stringCalculator.add('69,5'));
    });

    it('n args', function() {
      assert.equal(1+2+3+4+5, stringCalculator.add('1,2,3,4,5'));
    });

    it('handles new lines as separators', function() {
      assert.equal(1+2+3, stringCalculator.add('1\n2\n3'));
    });

    it('supports delimiters', function() {
      assert.equal(1+2+3, stringCalculator.add('//q\n1q2q3'));
    });

    it('dislikes negatives', function() {
      assert.throws(function() {
        stringCalculator.add('1,-2,3');
      });
    });
  });
});<|endoftext|>


<commit_before>'use strict';
var connect = require('connect'),
    http = require('http')

var cimentarius = connect();

cimentarius.process = function(callback) {
    this.use(cimentarius.router);
    http.createServer(this).listen(8080);
};

cimentarius.router = function(req,res) {
        res.end(JSON.stringify(req.url));
};

module.exports = cimentarius;
<commit_msg>Testing editing on Chromebook... :-o (no runtime, alas)<commit_after>'use strict';
var connect = require('connect'),
    http = require('http')

var cimentarius = connect();

cimentarius.process = function(callback) {
    this.use(cimentarius.router);
    http.createServer(this).listen(8080);
};

cimentarius.router = function(req,res) {
        res.end(JSON.stringify(req.url));
};

module.exports = cimentarius;<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var path = require('path');
var chalk = require('chalk');
var env = process.env.NODE_ENV || 'development';
var Database = require('../db/database');

module.exports.migrate = function(azulfile, options) {
  var db = Database.create(azulfile[env]);
  var migrator = db.migrator(path.resolve(options.migrations));

  return migrator.migrate()
  .then(function(migrations) {
    var batches = _(migrations).pluck('batch').unique().value().join(', ');
    console.log(chalk.magenta('Applying migrations, batch %s'), batches);
    migrations.forEach(function(migration) {
      console.log(chalk.cyan('%s'), migration.name);
    });
  })
  .catch(function(e) {
    console.log(chalk.red('Migration failed. %s'), e);
    process.exit(1);
  })
  .finally(function() { db.disconnect(); });
};

module.exports.rollback = function(azulfile, options) {
  var db = Database.create(azulfile[env]);
  var migrator = db.migrator(path.resolve(options.migrations));

  return migrator.rollback()
  .then(function(migrations) {
    var batches = _(migrations).pluck('batch').unique().value().join(', ');
    console.log(chalk.magenta('Rolling back migrations, batch %s'), batches);
    migrations.forEach(function(migration) {
      console.log(chalk.cyan('%s'), migration.name);
    });
  })
  .catch(function(e) {
    console.log(chalk.red('Rollback failed. %s'), e);
    process.exit(1);
  })
  .finally(function() { db.disconnect(); });
};
<commit_msg>Added environment to migration output.<commit_after>'use strict';

var _ = require('lodash');
var path = require('path');
var chalk = require('chalk');
var env = process.env.NODE_ENV || 'development';
var Database = require('../db/database');

module.exports.migrate = function(azulfile, options) {
  var db = Database.create(azulfile[env]);
  var migrator = db.migrator(path.resolve(options.migrations));

  return migrator.migrate()
  .then(function(migrations) {
    var batches = _(migrations).pluck('batch').unique().value().join(', ');
    console.log(chalk.magenta('Applying migrations, ' +
      '%s environment, batch %s'), env, batches);
    migrations.forEach(function(migration) {
      console.log(chalk.cyan('%s'), migration.name);
    });
  })
  .catch(function(e) {
    console.log(chalk.red('Migration failed. %s'), e);
    process.exit(1);
  })
  .finally(function() { db.disconnect(); });
};

module.exports.rollback = function(azulfile, options) {
  var db = Database.create(azulfile[env]);
  var migrator = db.migrator(path.resolve(options.migrations));

  return migrator.rollback()
  .then(function(migrations) {
    var batches = _(migrations).pluck('batch').unique().value().join(', ');
    console.log(chalk.magenta('Rolling back migrations, ' +
      '%s environment, batch %s'), env, batches);
    migrations.forEach(function(migration) {
      console.log(chalk.cyan('%s'), migration.name);
    });
  })
  .catch(function(e) {
    console.log(chalk.red('Rollback failed. %s'), e);
    process.exit(1);
  })
  .finally(function() { db.disconnect(); });
};
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, CloudFunc, JsDiff, ace;
(function(CloudCmd, Util, DOM, CloudFunc){
    'use strict';

    CloudCmd.Edit = new EditProto(CloudCmd, Util, DOM, CloudFunc);

    function EditProto(CloudCmd, Util, DOM, CloudFunc){
        var Name        = 'Edit',
            Loading     = false,
            DIR         =  CloudCmd.LIBDIRCLIENT + 'edit/',
            Value,
            Edit        = this,
            Ace,
            Msg,
            Key         = CloudCmd.Key,
            Images      = DOM.Images,

            Element;

       this.init                = function(pCallBack) {
            var lFunc, lIsFunc = Util.isFunction(CloudCmd.View);

            Loading   = true;
            if (lIsFunc)
                lFunc = CloudCmd.View;
            else
                lFunc = Util.exec;

            Util.loadOnLoad([
                Edit.show,
                load,
                lFunc
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f4', Edit.show);

            delete Edit.init;
        };

        this.show                       = function(pValue) {
            var lName       = DOM.getCurrentName(),
                lExt        = Util.getExtension(lName),
                lUseWorker  = Util.strCmp(lExt, ['.js', '.json']);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.anyload({
                        name        : 'div',
                        className   : 'edit',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position: absolute;',
                        not_append : true
                    });

                  initAce();
                }

                Ace.session.setOption('useWorker', lUseWorker);

                if ( Util.isString(pValue) ) {
                    Ace.setValue(pValue);
                    CloudCmd.View.show(Element, focus);
                    Key.unsetBind();
                }
                else {
                    DOM.getCurrentData({
                        success    : function(pData){
                            var lValue = '';

                            if (pData)
                                lValue = pData.data;

                            Value = lValue;
                            Ace.setValue(lValue);
                            CloudCmd.View.show(Element, focus);
                        }
                    });
                }
            }
        };

        this.hide                       =  function(){
            CloudCmd.View.hide();
        };

        function focus() {
            Ace.focus();
            Ace.clearSelection();
            Ace.moveCursorTo(0, 0);
        }

        function initAce() {
            var lSession;

            Ace         = ace.edit(Element);
            lSession    = Ace.getSession();

            Ace.setTheme('ace/theme/tomorrow_night_blue');
            lSession.setMode('ace/mode/javascript');
            Ace.setShowPrintMargin(false);
            Ace.setShowInvisibles(true);
            lSession.setUseSoftTabs(true);

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : function (pEditor) {
                    var lPath       = DOM.getCurrentPath(),
                        lValue      = Ace.getValue();

                    DOM.RESTfull.save(lPath,  lValue, Edit.showMessage);
                }
            });
        }

        function load(pCallBack){
            Util.time(Name + ' load');

            var lFiles  = [
                    DIR + 'theme-tomorrow_night_blue.js',
                    DIR + 'ace.js',
                ];

            DOM.anyLoadOnLoad(lFiles, function(){
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(pCallBack);
            });
        }

         function listener(pEvent){
            var lF4, lKey, lIsBind = Key.isBind();

            if (lIsBind) {
                lF4     = Key.F4,
                lKey    = pEvent.keyCode;

                if(lKey === lF4)
                    Edit.show();
            }
        }

        this.showMessage    = function(text) {
            var parent,
                TWO_SECONDS = 2000;

            if (!Msg) {
                DOM.cssSet({
                    id      : 'msg-css',
                    inner   : '.msg {'              +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': white;'                +
                                'color'             + ': rgb(49, 123, 249);'    +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.anyload({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.retExec(DOM.hide, Msg), 2000);
        };
    }

})(CloudCmd, Util, DOM, CloudFunc);
<commit_msg>chore(edit) showMessage: rm z-index<commit_after>var CloudCmd, Util, DOM, CloudFunc, JsDiff, ace;
(function(CloudCmd, Util, DOM, CloudFunc){
    'use strict';

    CloudCmd.Edit = new EditProto(CloudCmd, Util, DOM, CloudFunc);

    function EditProto(CloudCmd, Util, DOM, CloudFunc){
        var Name        = 'Edit',
            Loading     = false,
            DIR         =  CloudCmd.LIBDIRCLIENT + 'edit/',
            Value,
            Edit        = this,
            Ace,
            Msg,
            Key         = CloudCmd.Key,
            Images      = DOM.Images,

            Element;

       this.init                = function(pCallBack) {
            var lFunc, lIsFunc = Util.isFunction(CloudCmd.View);

            Loading   = true;
            if (lIsFunc)
                lFunc = CloudCmd.View;
            else
                lFunc = Util.exec;

            Util.loadOnLoad([
                Edit.show,
                load,
                lFunc
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f4', Edit.show);

            delete Edit.init;
        };

        this.show                       = function(pValue) {
            var lName       = DOM.getCurrentName(),
                lExt        = Util.getExtension(lName),
                lUseWorker  = Util.strCmp(lExt, ['.js', '.json']);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.anyload({
                        name        : 'div',
                        className   : 'edit',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position: absolute;',
                        not_append : true
                    });

                  initAce();
                }

                Ace.session.setOption('useWorker', lUseWorker);

                if ( Util.isString(pValue) ) {
                    Ace.setValue(pValue);
                    CloudCmd.View.show(Element, focus);
                    Key.unsetBind();
                }
                else {
                    DOM.getCurrentData({
                        success    : function(pData){
                            var lValue = '';

                            if (pData)
                                lValue = pData.data;

                            Value = lValue;
                            Ace.setValue(lValue);
                            CloudCmd.View.show(Element, focus);
                        }
                    });
                }
            }
        };

        this.hide                       =  function(){
            CloudCmd.View.hide();
        };

        function focus() {
            Ace.focus();
            Ace.clearSelection();
            Ace.moveCursorTo(0, 0);
        }

        function initAce() {
            var lSession;

            Ace         = ace.edit(Element);
            lSession    = Ace.getSession();

            Ace.setTheme('ace/theme/tomorrow_night_blue');
            lSession.setMode('ace/mode/javascript');
            Ace.setShowPrintMargin(false);
            Ace.setShowInvisibles(true);
            lSession.setUseSoftTabs(true);

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : function (pEditor) {
                    var lPath       = DOM.getCurrentPath(),
                        lValue      = Ace.getValue();

                    DOM.RESTfull.save(lPath,  lValue, Edit.showMessage);
                }
            });
        }

        function load(pCallBack){
            Util.time(Name + ' load');

            var lFiles  = [
                    DIR + 'theme-tomorrow_night_blue.js',
                    DIR + 'ace.js',
                ];

            DOM.anyLoadOnLoad(lFiles, function(){
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(pCallBack);
            });
        }

         function listener(pEvent){
            var lF4, lKey, lIsBind = Key.isBind();

            if (lIsBind) {
                lF4     = Key.F4,
                lKey    = pEvent.keyCode;

                if(lKey === lF4)
                    Edit.show();
            }
        }

        this.showMessage    = function(text) {
            var parent,
                TWO_SECONDS = 2000;

            if (!Msg) {
                DOM.cssSet({
                    id      : 'msg-css',
                    inner   : '.msg {'              +
                                'background-color'  + ': white;'                +
                                'color'             + ': rgb(49, 123, 249);'    +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.anyload({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.retExec(DOM.hide, Msg), 2000);
        };
    }

})(CloudCmd, Util, DOM, CloudFunc);
<|endoftext|>