<commit_before>import React, { PropTypes, Component } from 'react';
import CodeEditorMulti from './CodeEditorMulti';
import CodePromptMulti from '../components/CodePromptMulti';
import TimerMulti from './TimerMulti';
import MultiplayerInfo from '../components/MultiplayerInfo';
import levenshtein from './../lib/levenshtein';
import ProgressBarMulti from './ProgressBarMulti';
import { connect } from 'react-redux';
import { startGame, endGame, stopTimer, storeGameId, syncMultiplayerStatuses, startCountdown, getUsername, leavePage } from '../actions/index';
import { bindActionCreators } from 'redux';
import underscore from 'underscore';
import AllMiniViews from './AllMiniViews';

class Multiplayer extends Component {

  static contextTypes = {
    router: PropTypes.object
  }

  constructor() {
    super();

    this.state = {
      currentPuzzle: 'N/A',
      minifiedPuzzle: 'N/A'
    };

  };

  componentWillMount() {
    this.username = this.props.getUsername().payload;
  };

  componentDidMount() {
    this.socket = io();

    if(this.props.params.gameId){
      console.log(this.props.params.gameId);
      this.props.storeGameId(this.props.params.gameId);

      this.socket.emit('create new game', {roomcode:this.props.params.gameId, username: this.username, privacySetting: this.props.location.query.status});
    }

    // listen
    this.socket.on('player joined', function(players) {
      this.props.syncMultiplayerStatuses(players);
    }.bind(this));

    // listen
    this.socket.on('here is your prompt', function(prompt) {
      var minifiedPuzzle = prompt.replace(/\s/g,'');

      this.setState({
        currentPuzzle: prompt,
        minifiedPuzzle: minifiedPuzzle
      });

    }.bind(this));

    // listening for a 'all players progress' socket event and
    // collects all players' code from socket
    this.socket.on('all players progress', function(players) {
      underscore.map(players, function(obj, key){
        var playerPercent = this.calculatePercent(players[key][2]);
        players[key][1] = playerPercent;
      }.bind(this));
      this.props.syncMultiplayerStatuses(players);

    }.bind(this));

    // listening for a 'game over' socket event to capture and stop time
    this.socket.on('game over', function(value) {
      var time = this.props.gameTime;
      underscore.once(this.saveTimeElapsed(time.tenthSeconds, time.seconds, time.minutes, value.username));

      this.props.stopTimer();
    }.bind(this));
  };

  componentWillUnmount() {
    this.socket.emit('disconnected',{roomcode:this.props.params.gameId, username: this.username})
    this.socket.disconnect();
    this.props.leavePage();
  };

  componentDidUpdate() {
    // if player finishes the puzzle, ENDED_GAME action is sent, and 'game won' socket emitted
    if (this.props.multiGameState === 'ENDED_GAME') {
      var socketInfo = {
        gameId: this.props.params.gameId,
        username: this.username,
        id: this.socket.id,
        hasWon: true
      };
      underscore.once(this.socket.emit('game won', socketInfo));
    }
  };

  sendToMultiplayerLandingPage() {
    this.context.router.push('multiplayer');
  };

  isCurrentPlayer(username) {
    if(username === this.username) {
      return 'You';
    } else {
      return username;
    }
  };

  saveTimeElapsed(tenthSeconds, seconds, minutes, winner) {
    var title, html;

    let yourTime = (minutes*60 + seconds + tenthSeconds/10).toFixed(1);

    var finalStats = this.props.multiplayerStatuses.store;

    var finalTimes = [];
    for (var key in finalStats) {
      var nameAndFinalTimeArray = [finalStats[key][1], key]
      finalTimes.push(nameAndFinalTimeArray);
    }
    // console.log(finalTimes); // [ [progress1, name1], [progress2, name2] ]

    finalTimes.sort(function(a, b) {
      return b[0] - a[0];
    });

    // if playing multiplayer alone
    if (finalTimes.length === 1) {
      title = "Nice! You've won!";
      html  = '
'
            + '
 1st Place: You (' + yourTime + ' seconds)

'
            + '
';
    } else if (finalTimes.length === 2) {
      // if there are only two players
      if (this.username === winner) {
        title = "Nice! You've won!";
        html  = '
'
              + '
 1st Place: You (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + finalTimes[1][1] + '
'
              + '
';
      } else {
        title = "Too bad!";
        html  = '
'
              + '
 1st Place: ' + finalTimes[0][1] + ' (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + this.isCurrentPlayer(finalTimes[1][1]) + '
'
              + '
';
      }
    } else {
      if (this.username === winner) {
        title = "Nice! You've won!";
        html  = '
'
              + '
 1st Place: You (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + finalTimes[1][1] + '

'
              + '
 3rd Place: ' + finalTimes[2][1] + '
'
              + '
';
      } else {
        title = "Too bad!";
        html  = '
'
              + '
 1st Place: ' + finalTimes[0][1] + ' (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + this.isCurrentPlayer(finalTimes[1][1]) + '

'
              + '
 3rd Place: ' + this.isCurrentPlayer(finalTimes[2][1]) + '
'
              + '
';
      }
    }

    swal({
      title: title,
      html: html,
      showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Take me home',
        cancelButtonText: 'Create/Join a new game',
        confirmButtonClass: 'btn  btn-raised btn-success',
        cancelButtonClass: 'btn btn-raised btn-info',
        buttonsStyling: false,
        closeOnConfirm: true,
        closeOnCancel: true
      }, function(isConfirm) {
        if (isConfirm === true) {
          console.log('user has clicked take me home');
          this.context.router.push('/');
        } else if (isConfirm === false) {
          console.log('user wants to create/join new game');
          this.context.router.push('multiplayer');
        } else {
          console.log('user has clicked outside, should send multiplayer');
          // TODO: have some message that says, sending to multiplayer
          this.context.router.push('multiplayer');
        }
      }.bind(this));
  };

  calculatePercent(playerCode) {
    // typed code is passed in, and percent completed is calculated and returned
    var miniCode = playerCode.replace(/\s/g,'');
    var totalChars = this.state.minifiedPuzzle.length;
    var distance = levenshtein(this.state.minifiedPuzzle, miniCode);

    var percentCompleted = Math.floor(((totalChars - distance) / totalChars) * 99);
    return percentCompleted;
  };

  // sends current player's code to the socket to broadcast
  sendProgressToSockets(code, roomcode) {
    var data = {
      roomcode: roomcode,
      username: this.username,
      code: code
    }

    this.socket.emit('player progress', data);
  };

  render() {
    return (

        <MultiplayerInfo gameId={ this.props.params.gameId.charAt(0) === "P" ? ( "- Private ID:" + this.props.params.gameId.slice(1) ) : ( "- Public") } />
        <TimerMulti
          saveTimeElapsed={this.saveTimeElapsed.bind(this)}
          socket={this.socket} />
           { this.props.params.gameId.charAt(0) === "P" ?
          (
Welcome to Multiplayer Mode! Your friends can enter the room ID above to join this room. When you're all ready, click the start button to begin the countdown! Let it rip!
 )
           :
          (
Welcome to Multiplayer Mode! You've just entered a random room. Wait for other players to join then click the start button to begin the countdown!
 )
          }

Copy this...

Type here...

          <CodePromptMulti puzzle={this.state.currentPuzzle} />
          <CodeEditorMulti
            puzzle={this.state.currentPuzzle}
            minifiedPuzzle={this.state.minifiedPuzzle}
            sendProgressToSockets={this.sendProgressToSockets.bind(this)} />

          <ProgressBarMulti socket={this.socket} />

          <AllMiniViews />

    )
  };
};

function mapStateToProps(state) {
  return {
    multiGameState: state.multiGameState,
    gameTime: state.gameTime,
    savedGame: state.savedGame,
    multiplayerStatuses: state.multiplayerStatuses,
    SavedUsername: state.SavedUsername
  }
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    startGame: startGame,
    storeGameId: storeGameId,
    endGame: endGame,
    stopTimer: stopTimer,
    syncMultiplayerStatuses: syncMultiplayerStatuses,
    startCountdown: startCountdown,
    getUsername: getUsername,
    leavePage: leavePage
  }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(Multiplayer);
<commit_msg>[feature] prevents swalert close onEscape or outsideClick<commit_after>import React, { PropTypes, Component } from 'react';
import CodeEditorMulti from './CodeEditorMulti';
import CodePromptMulti from '../components/CodePromptMulti';
import TimerMulti from './TimerMulti';
import MultiplayerInfo from '../components/MultiplayerInfo';
import levenshtein from './../lib/levenshtein';
import ProgressBarMulti from './ProgressBarMulti';
import { connect } from 'react-redux';
import { startGame, endGame, stopTimer, storeGameId, syncMultiplayerStatuses, startCountdown, getUsername, leavePage } from '../actions/index';
import { bindActionCreators } from 'redux';
import underscore from 'underscore';
import AllMiniViews from './AllMiniViews';

class Multiplayer extends Component {

  static contextTypes = {
    router: PropTypes.object
  }

  constructor() {
    super();

    this.state = {
      currentPuzzle: 'N/A',
      minifiedPuzzle: 'N/A'
    };

  };

  componentWillMount() {
    this.username = this.props.getUsername().payload;
  };

  componentDidMount() {
    this.socket = io();

    if(this.props.params.gameId){
      console.log(this.props.params.gameId);
      this.props.storeGameId(this.props.params.gameId);

      this.socket.emit('create new game', {roomcode:this.props.params.gameId, username: this.username, privacySetting: this.props.location.query.status});
    }

    // listen
    this.socket.on('player joined', function(players) {
      this.props.syncMultiplayerStatuses(players);
    }.bind(this));

    // listen
    this.socket.on('here is your prompt', function(prompt) {
      var minifiedPuzzle = prompt.replace(/\s/g,'');

      this.setState({
        currentPuzzle: prompt,
        minifiedPuzzle: minifiedPuzzle
      });

    }.bind(this));

    // listening for a 'all players progress' socket event and
    // collects all players' code from socket
    this.socket.on('all players progress', function(players) {
      underscore.map(players, function(obj, key){
        var playerPercent = this.calculatePercent(players[key][2]);
        players[key][1] = playerPercent;
      }.bind(this));
      this.props.syncMultiplayerStatuses(players);

    }.bind(this));

    // listening for a 'game over' socket event to capture and stop time
    this.socket.on('game over', function(value) {
      var time = this.props.gameTime;
      underscore.once(this.saveTimeElapsed(time.tenthSeconds, time.seconds, time.minutes, value.username));

      this.props.stopTimer();
    }.bind(this));
  };

  componentWillUnmount() {
    this.socket.emit('disconnected',{roomcode:this.props.params.gameId, username: this.username})
    this.socket.disconnect();
    this.props.leavePage();
  };

  componentDidUpdate() {
    // if player finishes the puzzle, ENDED_GAME action is sent, and 'game won' socket emitted
    if (this.props.multiGameState === 'ENDED_GAME') {
      var socketInfo = {
        gameId: this.props.params.gameId,
        username: this.username,
        id: this.socket.id,
        hasWon: true
      };
      underscore.once(this.socket.emit('game won', socketInfo));
    }
  };

  sendToMultiplayerLandingPage() {
    this.context.router.push('multiplayer');
  };

  isCurrentPlayer(username) {
    if(username === this.username) {
      return 'You';
    } else {
      return username;
    }
  };

  saveTimeElapsed(tenthSeconds, seconds, minutes, winner) {
    var title, html;

    let yourTime = (minutes*60 + seconds + tenthSeconds/10).toFixed(1);

    var finalStats = this.props.multiplayerStatuses.store;

    var finalTimes = [];
    for (var key in finalStats) {
      var nameAndFinalTimeArray = [finalStats[key][1], key]
      finalTimes.push(nameAndFinalTimeArray);
    }
    // console.log(finalTimes); // [ [progress1, name1], [progress2, name2] ]

    finalTimes.sort(function(a, b) {
      return b[0] - a[0];
    });

    // if playing multiplayer alone
    if (finalTimes.length === 1) {
      title = "Nice! You've won!";
      html  = '
'
            + '
 1st Place: You (' + yourTime + ' seconds)

'
            + '
';
    } else if (finalTimes.length === 2) {
      // if there are only two players
      if (this.username === winner) {
        title = "Nice! You've won!";
        html  = '
'
              + '
 1st Place: You (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + finalTimes[1][1] + '
'
              + '
';
      } else {
        title = "Too bad!";
        html  = '
'
              + '
 1st Place: ' + finalTimes[0][1] + ' (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + this.isCurrentPlayer(finalTimes[1][1]) + '
'
              + '
';
      }
    } else {
      if (this.username === winner) {
        title = "Nice! You've won!";
        html  = '
'
              + '
 1st Place: You (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + finalTimes[1][1] + '

'
              + '
 3rd Place: ' + finalTimes[2][1] + '
'
              + '
';
      } else {
        title = "Too bad!";
        html  = '
'
              + '
 1st Place: ' + finalTimes[0][1] + ' (' + yourTime + ' seconds)

'
              + '
 2nd Place: ' + this.isCurrentPlayer(finalTimes[1][1]) + '

'
              + '
 3rd Place: ' + this.isCurrentPlayer(finalTimes[2][1]) + '
'
              + '
';
      }
    }

    swal({
      title: title,
      html: html,
      showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Take me home',
        cancelButtonText: 'Create/Join a new game',
        confirmButtonClass: 'btn  btn-raised btn-success',
        cancelButtonClass: 'btn btn-raised btn-info',
        allowOutsideClick: false,
        allowEscapeKey: false,
        buttonsStyling: false,
        closeOnConfirm: true,
        closeOnCancel: true
      }, function(isConfirm) {
        if (isConfirm === true) {
          console.log('user has clicked take me home');
          this.context.router.push('/');
        } else if (isConfirm === false) {
          console.log('user wants to create/join new game');
          this.context.router.push('multiplayer');
        } else {
          console.log('user has clicked outside, should send multiplayer');
          // TODO: have some message that says, sending to multiplayer
          this.context.router.push('multiplayer');
        }
      }.bind(this));
  };

  calculatePercent(playerCode) {
    // typed code is passed in, and percent completed is calculated and returned
    var miniCode = playerCode.replace(/\s/g,'');
    var totalChars = this.state.minifiedPuzzle.length;
    var distance = levenshtein(this.state.minifiedPuzzle, miniCode);

    var percentCompleted = Math.floor(((totalChars - distance) / totalChars) * 99);
    return percentCompleted;
  };

  // sends current player's code to the socket to broadcast
  sendProgressToSockets(code, roomcode) {
    var data = {
      roomcode: roomcode,
      username: this.username,
      code: code
    }

    this.socket.emit('player progress', data);
  };

  render() {
    return (

        <MultiplayerInfo gameId={ this.props.params.gameId.charAt(0) === "P" ? ( "- Private ID:" + this.props.params.gameId.slice(1) ) : ( "- Public") } />
        <TimerMulti
          saveTimeElapsed={this.saveTimeElapsed.bind(this)}
          socket={this.socket} />
           { this.props.params.gameId.charAt(0) === "P" ?
          (
Welcome to Multiplayer Mode! Your friends can enter the room ID above to join this room. When you're all ready, click the start button to begin the countdown! Let it rip!
 )
           :
          (
Welcome to Multiplayer Mode! You've just entered a random room. Wait for other players to join then click the start button to begin the countdown!
 )
          }

Copy this...

Type here...

          <CodePromptMulti puzzle={this.state.currentPuzzle} />
          <CodeEditorMulti
            puzzle={this.state.currentPuzzle}
            minifiedPuzzle={this.state.minifiedPuzzle}
            sendProgressToSockets={this.sendProgressToSockets.bind(this)} />

          <ProgressBarMulti socket={this.socket} />

          <AllMiniViews />

    )
  };
};

function mapStateToProps(state) {
  return {
    multiGameState: state.multiGameState,
    gameTime: state.gameTime,
    savedGame: state.savedGame,
    multiplayerStatuses: state.multiplayerStatuses,
    SavedUsername: state.SavedUsername
  }
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    startGame: startGame,
    storeGameId: storeGameId,
    endGame: endGame,
    stopTimer: stopTimer,
    syncMultiplayerStatuses: syncMultiplayerStatuses,
    startCountdown: startCountdown,
    getUsername: getUsername,
    leavePage: leavePage
  }, dispatch);
};

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


<commit_before>"use strict";
keywords.cards.enchantment = function (entity, obj, value) {
    if (obj.creature) {
        throw new Error("cannot be both enchantment and creature at once");
    }
    var actions = new com.cardshifter.modapi.actions.ActionComponent();
    var enchantAction = new ECSAction(entity, ENCHANT_ACTION, function (act) { return true; }, function (act) {}).addTargetSet(1, 1);
    actions.addAction(enchantAction);
	entity.addComponent(actions);
}

keywords.cards.addAttack = function (entity, obj, value) {
    if (!obj.enchantment) {
        throw new Error("expected enchantment");
    }
    ATTACK.retriever.set(entity, value);
}

keywords.cards.addHealth = function (entity, obj, value) {
    if (!obj.enchantment) {
        throw new Error("expected enchantment");
    }
    HEALTH.retriever.set(entity, value);
    MAX_HEALTH.retriever.set(entity, value);
}

keywords.cards.set = function (entity, obj, value) {
    if (!obj.enchantment) {
        throw new Error("expected enchantment");
    }
    var eff = Java.type("net.zomis.cardshifter.ecs.effects.Effects");
    eff = new eff();

    entity.addComponent(
        eff.described("Set " + value.res + " to " + valueDescription(value.value),
            eff.giveTarget(value.res, 1, function(i) {
                var val = valueLookup(value.value);
                return val;
            })
        )
    );

}

<commit_msg>Added JSDoc to keywords-enchantments<commit_after>"use strict";

/**
 * Checks if a card is a valid Enchantment, and adds the enchantment property.
 * @param {Object} entity - The applicable card entity.
 * @param {Object} obj - The applicable card object.
 * @param {boolean} value - Whether the card is an Enchantment.
 */
keywords.cards.enchantment = function (entity, obj, value) {
    if (obj.creature) {
        throw new Error("cannot be both enchantment and creature at once");
    }
    var actions = new com.cardshifter.modapi.actions.ActionComponent();
    var enchantAction = new ECSAction(entity, ENCHANT_ACTION, function (act) { return true; }, function (act) {}).addTargetSet(1, 1);
    actions.addAction(enchantAction);
	entity.addComponent(actions);
}

/**
 * Checks for and enables addAttack property.
 * @param {Object} entity - The applicable card entity.
 * @param {Object} obj - The applicable card object.
 * @param {int} value - The attack value to be added to the target.
 */
keywords.cards.addAttack = function (entity, obj, value) {
    if (!obj.enchantment) {
        throw new Error("expected enchantment");
    }
    ATTACK.retriever.set(entity, value);
}

/**
 * Checks for and enables addHealth property.
 * @param {Object} entity - The applicable card entity.
 * @param {Object} obj - The applicable card object.
 * @param {int} value - The health value to be added to the target.
 */
keywords.cards.addHealth = function (entity, obj, value) {
    if (!obj.enchantment) {
        throw new Error("expected enchantment");
    }
    HEALTH.retriever.set(entity, value);
    MAX_HEALTH.retriever.set(entity, value);
}

/**
 * Applies Enchantment to target.
 * @param {Object} entity - The applicable card entity.
 * @param {Object} obj - The applicable card object.
 * @param {boolean} value - The value to be added to the target.
 */
keywords.cards.set = function (entity, obj, value) {
    if (!obj.enchantment) {
        throw new Error("expected enchantment");
    }
    var eff = Java.type("net.zomis.cardshifter.ecs.effects.Effects");
    eff = new eff();

    entity.addComponent(
        eff.described("Set " + value.res + " to " + valueDescription(value.value),
            eff.giveTarget(value.res, 1, function(i) {
                var val = valueLookup(value.value);
                return val;
            })
        )
    );

}

<|endoftext|>


<commit_before>'use strict';

var MSG_TYPE = {
  SAY: 0,
  SHOUT: 1,
  WHISPER: 2,
  PARTY: 3,
  TRADE: 4,
  CLAN: 5,
  ALLY: 6,
  SYSTEM: 7,
  NOTICE: 8,
  ERROR: 9,
  QUEST: 10,
  QUEST_REWARD: 11
};

var ChatManager = function() {
  EventEmitter.call(this);

  this.types = [
    new ChatManager.MessageType('say', null, this.say.bind(this)),
    new ChatManager.MessageType('shout', '!', this.shout.bind(this)),
    new ChatManager.MessageType('whisper', '"', this.whisper.bind(this)),
    new ChatManager.MessageType('party', '#', this.clan.bind(this)),
    new ChatManager.MessageType('trade', '$', this.trade.bind(this)),
    new ChatManager.MessageType('clan', '@', this.clan.bind(this)),
    new ChatManager.MessageType('ally', '~', this.clan.bind(this)),
    new ChatManager.MessageType('system', null, this.system.bind(this)),
    new ChatManager.MessageType('notice', null, this.notice.bind(this)),
    new ChatManager.MessageType('error', null, this.error.bind(this)),
    new ChatManager.MessageType('quest', null, this.quest.bind(this)),
    new ChatManager.MessageType('quest-reward', null, this.questReward.bind(this))
  ];
};

ChatManager.prototype = Object.create(EventEmitter.prototype);
ChatManager.prototype.types = [];

ChatManager.MessageType = function(name, prefix, sendFunc) {
  this.name = name;
  this.prefix = prefix;
  this.sendFunc = sendFunc;
};

ChatManager.Message = function(type, message, sender, senderObject) {
  this.type = type;
  this.message = message;

  if (sender || senderObject) {
    this.sender = {
      name: sender,
      object: senderObject
    };
  }
};

ChatManager.prototype.say = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatSay(message);
  return true;
};

ChatManager.prototype.shout = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatShout(message);
  return true;
};

ChatManager.prototype.whisper = function(message) {
  var match = message.match(/([^ ]*) (.*)/);
  if (!match) {
    return false;
  }

  netGame.chatWhisper(match[1], match[2]);
  return true;
};

ChatManager.prototype.party = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatParty(message);
  return true;
};

ChatManager.prototype.trade = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatTrade(message);
  return true;
};

ChatManager.prototype.clan = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatClan(message);
  return true;
};

ChatManager.prototype.allied = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatAllied(message);
  return true;
};

ChatManager.prototype.system = function(message) {
  this.addSystemMessage('system', message);
  return true;
};

ChatManager.prototype.notice = function(message) {
  this.addSystemMessage('notice', message);
  return true;
};

ChatManager.prototype.error = function(message) {
  this.addSystemMessage('error', message);
  return true;
};

ChatManager.prototype.quest = function(message) {
  this.addSystemMessage('quest', message);
  return true;
};

ChatManager.prototype.questReward = function(message) {
  this.addSystemMessage('quest-reward', message);
  return true;
};

ChatManager.prototype.addGameMessage = function(type, message, sender, senderObject) {
  var message = new ChatManager.Message(type, message, sender, senderObject);
  this.emit('game_message', message);
};

ChatManager.prototype.addSystemMessage = function(type, message) {
  var message = new ChatManager.Message(type, message);
  this.emit('system_message', message);
};

var GCM = new ChatManager();
<commit_msg>Fix broken system messages.<commit_after>'use strict';

var MSG_TYPE = {
  SAY: 0,
  SHOUT: 1,
  WHISPER: 2,
  PARTY: 3,
  TRADE: 4,
  CLAN: 5,
  ALLY: 6,
  SYSTEM: 7,
  NOTICE: 8,
  ERROR: 9,
  QUEST: 10,
  QUEST_REWARD: 11
};

var ChatManager = function() {
  EventEmitter.call(this);

  this.types = [
    new ChatManager.MessageType('say', null, this.say.bind(this)),
    new ChatManager.MessageType('shout', '!', this.shout.bind(this)),
    new ChatManager.MessageType('whisper', '"', this.whisper.bind(this)),
    new ChatManager.MessageType('party', '#', this.clan.bind(this)),
    new ChatManager.MessageType('trade', '$', this.trade.bind(this)),
    new ChatManager.MessageType('clan', '@', this.clan.bind(this)),
    new ChatManager.MessageType('ally', '~', this.clan.bind(this)),
    new ChatManager.MessageType('system', null, this.system.bind(this)),
    new ChatManager.MessageType('notice', null, this.notice.bind(this)),
    new ChatManager.MessageType('error', null, this.error.bind(this)),
    new ChatManager.MessageType('quest', null, this.quest.bind(this)),
    new ChatManager.MessageType('quest-reward', null, this.questReward.bind(this))
  ];
};

ChatManager.prototype = Object.create(EventEmitter.prototype);
ChatManager.prototype.types = [];

ChatManager.MessageType = function(name, prefix, sendFunc) {
  this.name = name;
  this.prefix = prefix;
  this.sendFunc = sendFunc;
};

ChatManager.Message = function(type, message, sender, senderObject) {
  this.type = type;
  this.message = message;

  if (sender || senderObject) {
    this.sender = {
      name: sender,
      object: senderObject
    };
  }
};

ChatManager.prototype.say = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatSay(message);
  return true;
};

ChatManager.prototype.shout = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatShout(message);
  return true;
};

ChatManager.prototype.whisper = function(message) {
  var match = message.match(/([^ ]*) (.*)/);
  if (!match) {
    return false;
  }

  netGame.chatWhisper(match[1], match[2]);
  return true;
};

ChatManager.prototype.party = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatParty(message);
  return true;
};

ChatManager.prototype.trade = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatTrade(message);
  return true;
};

ChatManager.prototype.clan = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatClan(message);
  return true;
};

ChatManager.prototype.allied = function(message) {
  if (!message) {
    return false;
  }

  netGame.chatAllied(message);
  return true;
};

ChatManager.prototype.system = function(message) {
  this.addSystemMessage(MSG_TYPE.SYSTEM, message);
  return true;
};

ChatManager.prototype.notice = function(message) {
  this.addSystemMessage(MSG_TYPE.NOTICE, message);
  return true;
};

ChatManager.prototype.error = function(message) {
  this.addSystemMessage(MSG_TYPE.ERROR, message);
  return true;
};

ChatManager.prototype.quest = function(message) {
  this.addSystemMessage(MSG_TYPE.QUEST, message);
  return true;
};

ChatManager.prototype.questReward = function(message) {
  this.addSystemMessage(MSG_TYPE.QUEST_REWARD, message);
  return true;
};

ChatManager.prototype.addGameMessage = function(type, message, sender, senderObject) {
  var message = new ChatManager.Message(type, message, sender, senderObject);
  this.emit('game_message', message);
};

ChatManager.prototype.addSystemMessage = function(type, message) {
  var message = new ChatManager.Message(type, message);
  this.emit('system_message', message);
};

var GCM = new ChatManager();
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const minimatch = require('minimatch');
const fs = require('fs');
const path = require('path');
const iLibInstrument = require('istanbul-lib-instrument');
const iLibCoverage = require('istanbul-lib-coverage');
const iLibSourceMaps = require('istanbul-lib-source-maps');
const iLibReport = require('istanbul-lib-report');
const iReports = require('istanbul-reports');

const REPO_PATH = toUpperDriveLetter(path.join(__dirname, '..'));

exports.initialize = function (loaderConfig) {
	const instrumenter = iLibInstrument.createInstrumenter();
	loaderConfig.nodeInstrumenter = function (contents, source) {
		if (minimatch(source, '**/test/**/*.test.js')) {
			// tests don't get instrumented
			return contents;
		}
		// Try to find a .map file
		let map = undefined;
		try {
			map = JSON.parse(fs.readFileSync(`${source}.map`).toString());
		} catch (err) {
			// missing source map...
		}
		return instrumenter.instrumentSync(contents, source, map);
	};
};

exports.createReport = function (isSingle) {
	const mapStore = iLibSourceMaps.createSourceMapStore();
	const coverageMap = iLibCoverage.createCoverageMap(global.__coverage__);
	return mapStore.transformCoverage(coverageMap).then((transformed) => {
		// Paths come out all broken
		let newData = Object.create(null);
		Object.keys(transformed.data).forEach((file) => {
			const entry = transformed.data[file];
			const fixedPath = fixPath(entry.path);
			entry.data.path = fixedPath;
			newData[fixedPath] = entry;
		});
		transformed.data = newData;

		const context = iLibReport.createContext({
			dir: path.join(__dirname, `../.build/coverage${isSingle ? '-single' : ''}`),
			coverageMap: transformed
		});
		const tree = context.getTree('flat');

		let reports = [];
		if (isSingle) {
			reports.push(iReports.create('lcovonly'));
		} else {
			reports.push(iReports.create('json'));
			reports.push(iReports.create('lcov'));
			reports.push(iReports.create('html'));
		}
		reports.forEach(report => tree.visit(report, context));
	});
};

function toUpperDriveLetter(str) {
	if (/^[a-z]:/.test(str)) {
		return str.charAt(0).toUpperCase() + str.substr(1);
	}
	return str;
}

function toLowerDriveLetter(str) {
	if (/^[A-Z]:/.test(str)) {
		return str.charAt(0).toLowerCase() + str.substr(1);
	}
	return str;
}

function fixPath(brokenPath) {
	const startIndex = brokenPath.lastIndexOf(REPO_PATH);
	if (startIndex === -1) {
		return toLowerDriveLetter(brokenPath);
	}
	return toLowerDriveLetter(brokenPath.substr(startIndex));
}
<commit_msg>Don't instrument any test code for coverage (#86608)<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const minimatch = require('minimatch');
const fs = require('fs');
const path = require('path');
const iLibInstrument = require('istanbul-lib-instrument');
const iLibCoverage = require('istanbul-lib-coverage');
const iLibSourceMaps = require('istanbul-lib-source-maps');
const iLibReport = require('istanbul-lib-report');
const iReports = require('istanbul-reports');

const REPO_PATH = toUpperDriveLetter(path.join(__dirname, '..'));

exports.initialize = function (loaderConfig) {
	const instrumenter = iLibInstrument.createInstrumenter();
	loaderConfig.nodeInstrumenter = function (contents, source) {
		if (minimatch(source, '**/test/**')) {
			// tests don't get instrumented
			return contents;
		}
		// Try to find a .map file
		let map = undefined;
		try {
			map = JSON.parse(fs.readFileSync(`${source}.map`).toString());
		} catch (err) {
			// missing source map...
		}
		return instrumenter.instrumentSync(contents, source, map);
	};
};

exports.createReport = function (isSingle) {
	const mapStore = iLibSourceMaps.createSourceMapStore();
	const coverageMap = iLibCoverage.createCoverageMap(global.__coverage__);
	return mapStore.transformCoverage(coverageMap).then((transformed) => {
		// Paths come out all broken
		let newData = Object.create(null);
		Object.keys(transformed.data).forEach((file) => {
			const entry = transformed.data[file];
			const fixedPath = fixPath(entry.path);
			entry.data.path = fixedPath;
			newData[fixedPath] = entry;
		});
		transformed.data = newData;

		const context = iLibReport.createContext({
			dir: path.join(__dirname, `../.build/coverage${isSingle ? '-single' : ''}`),
			coverageMap: transformed
		});
		const tree = context.getTree('flat');

		let reports = [];
		if (isSingle) {
			reports.push(iReports.create('lcovonly'));
		} else {
			reports.push(iReports.create('json'));
			reports.push(iReports.create('lcov'));
			reports.push(iReports.create('html'));
		}
		reports.forEach(report => tree.visit(report, context));
	});
};

function toUpperDriveLetter(str) {
	if (/^[a-z]:/.test(str)) {
		return str.charAt(0).toUpperCase() + str.substr(1);
	}
	return str;
}

function toLowerDriveLetter(str) {
	if (/^[A-Z]:/.test(str)) {
		return str.charAt(0).toLowerCase() + str.substr(1);
	}
	return str;
}

function fixPath(brokenPath) {
	const startIndex = brokenPath.lastIndexOf(REPO_PATH);
	if (startIndex === -1) {
		return toLowerDriveLetter(brokenPath);
	}
	return toLowerDriveLetter(brokenPath.substr(startIndex));
}
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/29.
 */

'use strict';

function parseDependencies(s, replace, includeAsync){
  if (replace === true) {
    includeAsync = true;
    replace = null;
  }

  if (s.indexOf('require') === -1) {
    return replace ? s : [];
  }

  var index = 0, peek = '', length = s.length, isReg = 1, modName = 0, res = [];
  var parentheseState = 0, parentheseStack = [];
  var braceState, braceStack = [], isReturn;
  var last;
  var flag;

  while (index < length) {
    readch();

    if (isBlank()) {
      if (isReturn && (peek === '\n' || peek === '\r')) {
        braceState = 0;
        isReturn = 0;
      }
    } else if (isQuote()) {
      dealQuote();

      isReg = 1;
      isReturn = 0;
      braceState = 0;
    } else if (peek === '/') {
      readch();

      if (peek === '/') {
        index = s.indexOf('\n', index);

        if (index === -1) {
          index = s.length;
        }
      } else if (peek === '*') {
        var i = s.indexOf('\n', index);
        index = s.indexOf('*/', index);

        if (index === -1) {
          index = length;
        } else {
          index += 2;
        }

        if (isReturn && i != -1 && i < index) {
          braceState = 0;
          isReturn = 0;
        }
      } else if (isReg) {
        dealReg();

        isReg = 0;
        isReturn = 0;
        braceState = 0;
      } else {
        index--;
        isReg = 1;
        isReturn = 0;
        braceState = 1;
      }
    } else if (isWord()) {
      dealWord();
    } else if (isNumber()) {
      dealNumber();

      isReturn = 0;
      braceState = 0;
    } else if (peek === '(') {
      parentheseStack.push(parentheseState);

      isReg = 1;
      isReturn = 0;
      braceState = 1;
    } else if (peek === ')') {
      isReg = parentheseStack.pop();
      isReturn = 0;
      braceState = 0;
    } else if (peek === '{') {
      if (isReturn) {
        braceState = 1
      }

      braceStack.push(braceState);

      isReturn = 0;
      isReg = 1;
    } else if (peek === '}') {
      braceState = braceStack.pop();

      isReg = !braceState;
      isReturn = 0;
    } else {
      var next = s.charAt(index);

      if (peek === ';') {
        braceState = 0
      } else if (peek === '-' && next === '-' || peek === '+' && next === '+' || peek === '=' && next === '>') {
        braceState = 0;
        index++;
      } else {
        braceState = 1;
      }

      isReg = peek != ']';
      isReturn = 0;
    }
  }

  return replace ? s : res;

  function readch(){
    peek = s.charAt(index++);
  }

  function isBlank(){
    return /\s/.test(peek);
  }

  function isQuote(){
    return peek === '"' || peek === "'";
  }

  function dealQuote(){
    var start = index;
    var c = peek;
    var end = s.indexOf(c, start);

    if (end === -1) {
      index = length;
    } else if (s.charAt(end - 1) != '\\') {
      index = end + 1;
    } else {
      while (index < length) {
        readch();

        if (peek === '\\') {
          index++;
        } else if (peek === c) {
          break;
        }
      }
    }

    if (modName) {
      var d = {
        'string': s.slice(last, s.indexOf(')', index) + 1),
        'path': s.slice(start, index - 1),
        'index': last,
        'flag': flag
      };

      res.push(d);

      if (replace) {
        var rep = replace(d);
        s = s.slice(0, last) + rep + s.slice(last + d.string.length);

        if (rep.length != d.string.length) {
          index = last + rep.length;
          length = s.length;
        }
      }

      modName = 0;
    }
  }

  function dealReg(){
    index--;

    while (index < length) {
      readch();

      if (peek === '\\') {
        index++;
      } else if (peek === '/') {
        break;
      } else if (peek === '[') {
        while (index < length) {
          readch();

          if (peek === '\\') {
            index++;
          } else if (peek === ']') {
            break;
          }
        }
      }
    }
  }

  function isWord(){
    return /[a-z_$]/i.test(peek);
  }

  function dealWord(){
    var s2 = s.slice(index - 1);
    var r = /^[\w$]+/.exec(s2)[0];

    parentheseState = {
      'if': 1,
      'for': 1,
      'while': 1,
      'with': 1
    }[r];
    isReg = {
      'break': 1,
      'case': 1,
      'continue': 1,
      'debugger': 1,
      'delete': 1,
      'do': 1,
      'else': 1,
      'false': 1,
      'if': 1,
      'in': 1,
      'instanceof': 1,
      'return': 1,
      'typeof': 1,
      'void': 1
    }[r];
    isReturn = r === 'return';
    braceState = {
      'instanceof': 1,
      'delete': 1,
      'void': 1,
      'typeof': 1,
      'return': 1
    }.hasOwnProperty(r);
    modName = includeAsync
      ? /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:(?:(['"]).+?\2)|\[.*?\])\s*[),]/.test(s2)
      : /^require\s*\(\s*(['"]).+?\1\s*[),]/.test(s2);

    if (modName) {
      last = index - 1;
      r = includeAsync ?
        /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:['"]|\[)/.exec(s2)[0]
        : /^require\s*\(\s*['"]/.exec(s2)[0];
      index += r.length - 2;
      flag = /^require\s*(?:(?:\.([a-zA-Z_$][a-zA-Z0-9_$]*))|(?:\[\s*(['"])(.*)?\2\s*\]))/.exec(s2);
      flag = flag ? flag[1] || flag[3] : null;
    } else {
      index += /^[\w$]+(?:\s*\.\s*[\w$]+)*/.exec(s2)[0].length - 1;
    }
  }

  function isNumber(){
    return /\d/.test(peek) || peek === '.' && /\d/.test(s.charAt(index));
  }

  function dealNumber(){
    var s2 = s.slice(index - 1);
    var r;

    if (peek === '.') {
      r = /^\.\d+(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    } else if (/^0x[\da-f]*/i.test(s2)) {
      r = /^0x[\da-f]*\s*/i.exec(s2)[0];
    } else {
      r = /^\d+\.?\d*(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    }

    index += r.length - 1;
    isReg = 0;
  }
}

module.exports = parseDependencies;<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/4/29.
 */

'use strict';

function parseDependencies(s, replace, includeAsync){
  if (replace === true) {
    includeAsync = true;
    replace = null;
  }

  if (s.indexOf('require') === -1) {
    return replace ? s : [];
  }

  var index = 0, peek = '', length = s.length, isReg = 1, modName = 0, res = [];
  var parentheseState = 0, parentheseStack = [];
  var braceState, braceStack = [], isReturn;
  var last;
  var flag;

  while (index < length) {
    readch();

    if (isBlank()) {
      if (isReturn && (peek === '\n' || peek === '\r')) {
        braceState = 0;
        isReturn = 0;
      }
    } else if (isQuote()) {
      dealQuote();

      isReg = 1;
      isReturn = 0;
      braceState = 0;
    } else if (peek === '/') {
      readch();

      if (peek === '/') {
        index = s.indexOf('\n', index);

        if (index === -1) {
          index = s.length;
        }
      } else if (peek === '*') {
        var i = s.indexOf('\n', index);
        index = s.indexOf('*/', index);

        if (index === -1) {
          index = length;
        } else {
          index += 2;
        }

        if (isReturn && i != -1 && i < index) {
          braceState = 0;
          isReturn = 0;
        }
      } else if (isReg) {
        dealReg();

        isReg = 0;
        isReturn = 0;
        braceState = 0;
      } else {
        index--;
        isReg = 1;
        isReturn = 0;
        braceState = 1;
      }
    } else if (isWord()) {
      dealWord();
    } else if (isNumber()) {
      dealNumber();

      isReturn = 0;
      braceState = 0;
    } else if (peek === '(') {
      parentheseStack.push(parentheseState);

      isReg = 1;
      isReturn = 0;
      braceState = 1;
    } else if (peek === ')') {
      isReg = parentheseStack.pop();
      isReturn = 0;
      braceState = 0;
    } else if (peek === '{') {
      if (isReturn) {
        braceState = 1;
      }

      braceStack.push(braceState);

      isReturn = 0;
      isReg = 1;
    } else if (peek === '}') {
      braceState = braceStack.pop();

      isReg = !braceState;
      isReturn = 0;
    } else {
      var next = s.charAt(index);

      if (peek === ';') {
        braceState = 0;
      } else if (peek === '-' && next === '-' || peek === '+' && next === '+' || peek === '=' && next === '>') {
        braceState = 0;
        index++;
      } else {
        braceState = 1;
      }

      isReg = peek != ']';
      isReturn = 0;
    }
  }

  return replace ? s : res;

  function readch(){
    peek = s.charAt(index++);
  }

  function isBlank(){
    return /\s/.test(peek);
  }

  function isQuote(){
    return peek === '"' || peek === "'";
  }

  function dealQuote(){
    var start = index;
    var c = peek;
    var end = s.indexOf(c, start);

    if (end === -1) {
      index = length;
    } else if (s.charAt(end - 1) != '\\') {
      index = end + 1;
    } else {
      while (index < length) {
        readch();

        if (peek === '\\') {
          index++;
        } else if (peek === c) {
          break;
        }
      }
    }

    if (modName) {
      var d = {
        'string': s.slice(last, s.indexOf(')', index) + 1),
        'path': s.slice(start, index - 1),
        'index': last,
        'flag': flag
      };

      res.push(d);

      if (replace) {
        var rep = replace(d);
        s = s.slice(0, last) + rep + s.slice(last + d.string.length);

        if (rep.length != d.string.length) {
          index = last + rep.length;
          length = s.length;
        }
      }

      modName = 0;
    }
  }

  function dealReg(){
    index--;

    while (index < length) {
      readch();

      if (peek === '\\') {
        index++;
      } else if (peek === '/') {
        break;
      } else if (peek === '[') {
        while (index < length) {
          readch();

          if (peek === '\\') {
            index++;
          } else if (peek === ']') {
            break;
          }
        }
      }
    }
  }

  function isWord(){
    return /[a-z_$]/i.test(peek);
  }

  function dealWord(){
    var s2 = s.slice(index - 1);
    var r = /^[\w$]+/.exec(s2)[0];

    parentheseState = {
      'if': 1,
      'for': 1,
      'while': 1,
      'with': 1
    }[r];
    isReg = {
      'break': 1,
      'case': 1,
      'continue': 1,
      'debugger': 1,
      'delete': 1,
      'do': 1,
      'else': 1,
      'false': 1,
      'if': 1,
      'in': 1,
      'instanceof': 1,
      'return': 1,
      'typeof': 1,
      'void': 1
    }[r];
    isReturn = r === 'return';
    braceState = {
      'instanceof': 1,
      'delete': 1,
      'void': 1,
      'typeof': 1,
      'return': 1
    }.hasOwnProperty(r);
    modName = includeAsync
      ? /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:(?:(['"]).+?\2)|\[.*?\])\s*[),]/.test(s2)
      : /^require\s*\(\s*(['"]).+?\1\s*[),]/.test(s2);

    if (modName) {
      last = index - 1;
      r = includeAsync ?
        /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:['"]|\[)/.exec(s2)[0]
        : /^require\s*\(\s*['"]/.exec(s2)[0];
      index += r.length - 2;
      flag = /^require\s*(?:(?:\.([a-zA-Z_$][a-zA-Z0-9_$]*))|(?:\[\s*(['"])(.*)?\2\s*\]))/.exec(s2);
      flag = flag ? flag[1] || flag[3] : null;
    } else {
      index += /^[\w$]+(?:\s*\.\s*[\w$]+)*/.exec(s2)[0].length - 1;
    }
  }

  function isNumber(){
    return /\d/.test(peek) || peek === '.' && /\d/.test(s.charAt(index));
  }

  function dealNumber(){
    var s2 = s.slice(index - 1);
    var r;

    if (peek === '.') {
      r = /^\.\d+(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    } else if (/^0x[\da-f]*/i.test(s2)) {
      r = /^0x[\da-f]*\s*/i.exec(s2)[0];
    } else {
      r = /^\d+\.?\d*(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    }

    index += r.length - 1;
    isReg = 0;
  }
}

module.exports = parseDependencies;<|endoftext|>


<commit_before>var fs       = require('fs');
var Document = require('../document.js');

var schema = JSON.parse(fs.readFileSync(__dirname+ '/../data/substance.json', 'utf-8'));
var helloWorld = JSON.parse(fs.readFileSync(__dirname+ '/../data/hello_world.json', 'utf-8'));

// console.log(helloWorld);

// Create a new document at revision 0. It's just a plain old JS object?
// var doc = Document.create(schema);

// // Add a new section
// var newSectionOp = {
//   "rev": 0,
//   "user": "michael",
//   "methods": [
//     ["node:insert", {"type": "section", "properties": {"id": "open-collab", "name": "Open Collaboration"}}]
//   ]
// };

// var addTextOp = {
//   "rev": 1,
//   "user": "michael",
//   "methods": [
//     ["node:insert", {"type": "text", "properties": {"content": "Hallo Welt"}}]
//   ]
// };

// var setTitleOp = {
//   "rev": 2,
//   "user": "michael",
//   "methods": [
//     ["document:update", {"properties": {"content": "Hallo Welt"}}]
//   ]
// };

// var operations = [newSectionOp, addTextOp];

// Document.transform(doc, newSectionOp);

console.log('Tests completed.');

var doc = new Document(helloWorld, schema);

doc.checkout('master');

// console.log(doc.content);
// Add another node to front

doc.apply({
  "op": ["node:insert", {"id": "text:intro", "type": "text", "pos": "front", "properties": {"content": "Some fresh introduction."}}],
  "user": "michael"
});

// Move [text:intro] after text:hello

doc.apply({
  "op": ["node:move", {"nodes": ["text:intro"], "target": "text:hello"}],
  "user": "michael"
});

console.log('LISTING-------------');
doc.list(function(node) {
  console.log(node.id, node);
});

// console.log('FINAL_STAAAATE');

// console.log(doc.content);

// Document session, takes a stream of operations and applies them fast forward style
// var session = new Document.Session(doc, {operations: operations});

<commit_msg>Clean up some mess.<commit_after>var fs       = require('fs');
var Document = require('../document.js');

var schema = JSON.parse(fs.readFileSync(__dirname+ '/../data/substance.json', 'utf-8'));
var helloWorld = JSON.parse(fs.readFileSync(__dirname+ '/../data/hello_world.json', 'utf-8'));

var doc = new Document(helloWorld, schema);
doc.checkout('master');

// Add another node to front

doc.apply({
  "op": ["node:insert", {"id": "text:intro", "type": "text", "target": "front", "properties": {"content": "Some fresh introduction."}}],
  "user": "michael"
});

// Move [text:intro] after text:hello

doc.apply({
  "op": ["node:move", {"nodes": ["text:intro"], "target": "text:hello"}],
  "user": "michael"
});

console.log('---------------------');
console.log('Your nodes, in order:');
console.log('---------------------');

doc.list(function(node) {
  console.log(node.id, node);
});

console.log('---------------------');
console.log('Tests completed.');
console.log('---------------------');

// TODO: merge the patch!

// doc.merge('patch-1');<|endoftext|>


<commit_before>import pathToRegExp from 'path-to-regexp';
import { _castString, $isArray, $unserialize } from 'core/types';
import { _doc } from 'core/variables';
import { $exec } from 'core/core';

const REMOVE_SLASHES_REGEXP = /^\/|\/$/g;
let _routes = [];

/**
 * Add a route to routes array
 *
 * @param routes
 * @private
 */
function _add(routes) {
	const count = routes.length;

	for (let i = 0; i < count; i++) {
		let route = _getRoute(routes[i].path);

		if (route) {
			_routes[route.index] = routes[i];
			break;
		}

		_routes.push(routes[i]);
	}
}

/**
 * Retrieve existing route with associated index
 *
 * @param {string} value
 * @param {string} key
 * @returns {Object}
 * @private
 */
function _getRoute(value) {
	const count = _routes.length;

	for (let i = 0; i < count; i++) {
		let route = _routes[i];

		if (route.path === value || route.name === value) {
			return {
				route: route,
				index: i
			};
		}
	}

	return null;
}

/**
 * Parse url and return results
 *
 * @param {string} value
 * @returns {Object}
 * @private
 */
function _parseUrl(value) {
	const a = _doc.createElement('a');
	a.href = value || window.location;

	const search = a.search,
		path = a.pathname.replace(REMOVE_SLASHES_REGEXP, '');

	return {
		full: '/' + path + search + a.hash,
		hash: a.hash.slice(1),
		path: '/' + path,
		query: search ? $unserialize(search) : {},
		segments: path.split('/'),
		url: a.href,
		port: a.port
	};
}

/**
 * Extract parameters from current URL based on matching route
 *
 * @param {string} path
 * @param {string} location
 * @returns {Object}
 * @private
 */
function _getParams(path, location) {
	let keys = [],
		params = {},
		results = pathToRegExp(path, keys).exec(location);

	if ($isArray(results)) {
		results.slice(1)
			.forEach((segment, j) => params[keys[j].name] = _castString(segment));
	}

	return Object.keys(params).length ? params : null;
}

export default {
	/**
	 * Register routes
	 *
	 * @param {Array} routes
	 * @returns {Object}
	 */
	map(routes) {
		_add(routes);

		return this;
	},

	/**
	 * Reset all routes - mainly for testing purposes
	 */
	reset() {
		_routes = [];
	},

	/**
	 * Retrieve all routes or specific route by name/path
	 *
	 * @param {string} [value]
	 * @returns {Object|Array}
	 */
	routes(value) {
		if (value) {
			let result = _getRoute(value);

			if (result) {
				return result.route;
			}
		}

		return _routes;
	},
	run() {
		const uri = this.uri();
		const length = _routes.length;

		for (let i = 0; i < length; i++) {
			let path = _routes[i].path;
			let params = _getParams(path, uri.full);

			if (params) {
				let toPath = pathToRegExp.compile(path);
				path = toPath(params);
			}

			if (uri.full === path) {
				$exec(_routes[i].handler, {
					args: [params]
				});
				break;
			}
		}
	},

	/**
	 * Retrieve information about current location
	 *
	 * @param {string} [value]
	 * @returns {Object}
	 */
	uri(value) {
		return _parseUrl(value);
	},

	/**
	 * Add a filter or array of filters to internal filter registry
	 *
	 * @param {string|Array} name
	 * @param {Function} [callback]
	 */
	addFilter(name, callback) {
		if ($isArray(name)) {
			_addFilters(name);
		} else {
			_addFilter(name, callback)
		}

		return this;
	},

	/**
	 * Return all registered filters
	 *
	 * @returns {{}}
	 */
	filters() {
		return _filters;
	}
};<commit_msg>Add filter registry and change _add function name<commit_after>import pathToRegExp from 'path-to-regexp';
import { _castString, $isArray, $unserialize } from 'core/types';
import { _doc } from 'core/variables';
import { $exec } from 'core/core';

const REMOVE_SLASHES_REGEXP = /^\/|\/$/g;
let _routes = [];
let _filters = {};

/**
 * Add a route to routes array
 *
 * @param routes
 * @private
 */
function _addRoutes(routes) {
	const count = routes.length;

	for (let i = 0; i < count; i++) {
		let route = _getRoute(routes[i].path);

		if (route) {
			_routes[route.index] = routes[i];
			break;
		}

		_routes.push(routes[i]);
	}
}

/**
 * Retrieve existing route with associated index
 *
 * @param {string} value
 * @param {string} key
 * @returns {Object}
 * @private
 */
function _getRoute(value) {
	const count = _routes.length;

	for (let i = 0; i < count; i++) {
		let route = _routes[i];

		if (route.path === value || route.name === value) {
			return {
				route: route,
				index: i
			};
		}
	}

	return null;
}

/**
 * Parse url and return results
 *
 * @param {string} value
 * @returns {Object}
 * @private
 */
function _parseUrl(value) {
	const a = _doc.createElement('a');
	a.href = value || window.location;

	const search = a.search,
		path = a.pathname.replace(REMOVE_SLASHES_REGEXP, '');

	return {
		full: '/' + path + search + a.hash,
		hash: a.hash.slice(1),
		path: '/' + path,
		query: search ? $unserialize(search) : {},
		segments: path.split('/'),
		url: a.href,
		port: a.port
	};
}

/**
 * Extract parameters from current URL based on matching route
 *
 * @param {string} path
 * @param {string} location
 * @returns {Object}
 * @private
 */
function _getParams(path, location) {
	let keys = [],
		params = {},
		results = pathToRegExp(path, keys).exec(location);

	if ($isArray(results)) {
		results.slice(1)
			.forEach((segment, j) => params[keys[j].name] = _castString(segment));
	}

	return Object.keys(params).length ? params : null;
}

export default {
	/**
	 * Register routes
	 *
	 * @param {Array} routes
	 * @returns {Object}
	 */
	map(routes) {
		_add(routes);

		return this;
	},

	/**
	 * Reset all routes - mainly for testing purposes
	 */
	reset() {
		_routes = [];
	},

	/**
	 * Retrieve all routes or specific route by name/path
	 *
	 * @param {string} [value]
	 * @returns {Object|Array}
	 */
	routes(value) {
		if (value) {
			let result = _getRoute(value);

			if (result) {
				return result.route;
			}
		}

		return _routes;
	},
	run() {
		const uri = this.uri();
		const length = _routes.length;

		for (let i = 0; i < length; i++) {
			let path = _routes[i].path;
			let params = _getParams(path, uri.full);

			if (params) {
				let toPath = pathToRegExp.compile(path);
				path = toPath(params);
			}

			if (uri.full === path) {
				$exec(_routes[i].handler, {
					args: [params]
				});
				break;
			}
		}
	},

	/**
	 * Retrieve information about current location
	 *
	 * @param {string} [value]
	 * @returns {Object}
	 */
	uri(value) {
		return _parseUrl(value);
	},

	/**
	 * Add a filter or array of filters to internal filter registry
	 *
	 * @param {string|Array} name
	 * @param {Function} [callback]
	 */
	addFilter(name, callback) {
		if ($isArray(name)) {
			_addFilters(name);
		} else {
			_addFilter(name, callback)
		}

		return this;
	},

	/**
	 * Return all registered filters
	 *
	 * @returns {{}}
	 */
	filters() {
		return _filters;
	}
};<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var ejs = require('ejs');

module.exports = {
    'test html': function(assert){
        assert.equal('
yay
', ejs.render('
yay
'));
    },

    'test buffered code': function(assert){
        var html = '
tj
',
            str = '
<%= name %>
',
            locals = { name: 'tj' };
        assert.equal(html, ejs.render(str, { locals: locals }));
    },

    'test unbuffered code': function(assert){
        var html = '
tj
',
            str = '<% if (name) { %>
<%= name %>
<% } %>',
            locals = { name: 'tj' };
        assert.equal(html, ejs.render(str, { locals: locals }));
    },

    'test `scope` option': function(assert){
        var html = '
tj
',
            str = '
<%= this %>
';
        assert.equal(html, ejs.render(str, { scope: 'tj' }));
    },

    'test `context` option': function(assert){
        var html = '
tj
',
            str = '
<%= this %>
';
        assert.equal(html, ejs.render(str, { context: 'tj' }));
    },

    'test escaping': function(assert){
        assert.equal('<script>', ejs.render('<%= "


<commit_before><commit_msg>LIB jui_filter_rules v1.00<commit_after><|endoftext|>


<commit_before>"use strict";

var _ = require('lodash');
var Schema = require('../index');

module.exports = {
	'Simple Usage: build - equal builds made by different approaches': function (test) {
		var sh1 = new Schema().object(function (required, optional) {
			this.field('first_name');
			required('last_name');
			optional('middle_name');
		});

		var sh2 = new Schema().object(function () {
			this.required('first_name');
			this.field('last_name');
			this.optional('middle_name');
		});

		var sh3 = new Schema().object(function () {
			this.field('first_name');
			this.field('last_name');
			this.field('middle_name').optional();
		});

		var sh4 = new Schema();
			sh4.required('first_name');
			sh4.field('last_name');
			sh4.optional('middle_name');

		test.deepEqual(sh1, sh2);
		test.deepEqual(sh1, sh3);
		test.deepEqual(sh1, sh4);

		test.done();
	},

	'Simple Usage: verify - no specified fields': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = {};
		sh1.verify(value, function (err, isValid, vError) {
			test.ok(!isValid);
			test.equal(vError.ruleName, 'required');
			test.strictEqual(vError.ruleParams, null);
			test.strictEqual(vError.value, undefined);
			test.deepEqual(vError.path, ['first_name']);
			test.done(err);
		});
	},

	'Simple Usage: verify - optional field isn\'t specified': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = { first_name: 'hello', last_name: 'world' };
		sh1.verify(value, function (err, isValid, vError) {
			test.ok(isValid);
			test.strictEqual(vError, null);
			test.done(err);
		});
	},

	'Simple Usage: verify - correct if all available fields not empty': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = { first_name: 'hello', last_name: 'world', middle_name: 'param-pam-pam' };
		sh1.verify(value, function (err, isValid, vError) {
			test.ok(isValid);
			test.strictEqual(vError, null);
			test.done(err);
		});
	},

	'Simple Usage: verify - excess field': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = {
			first_name: 'hello',
			last_name: 'world',
			middle_name: 'param-pam-pam'
		};
		var _keys = _.keys(value);
		value.excess_field = true;

		sh1.verify(value, function (err, isValid, vError) {
			test.ok(!isValid);
			test.equal(vError.ruleName, 'available_fields');
			test.deepEqual(vError.ruleParams, _keys);
			test.deepEqual(vError.value, value);
			test.deepEqual(vError.path, []);
			test.done(err);
		});
	},

	'Create Schema, Register - equal registering': function (test) {
		var sh1 = new Schema();
		var sh2 = Schema(); // jshint ignore: line
		var sh3 = new Schema('nameForRegister1');
		var sh4 = Schema('nameForRegister2'); // jshint ignore: line
		Schema.register('someSchema1', sh1);
		Schema.register('someSchema2', sh2);

		test.strictEqual(Schema.get('someSchema1'), sh1);
		test.strictEqual(Schema.get('someSchema2'), sh2);
		test.strictEqual(Schema.get('nameForRegister1'), sh3);
		test.strictEqual(Schema.get('nameForRegister2'), sh4);

		test.done();
	},
};<commit_msg>add example test for attachTo<commit_after>"use strict";

var _ = require('lodash');
var Schema = require('../index');

module.exports = {
	'Simple Usage: build - equal builds made by different approaches': function (test) {
		var sh1 = new Schema().object(function (required, optional) {
			this.field('first_name');
			required('last_name');
			optional('middle_name');
		});

		var sh2 = new Schema().object(function () {
			this.required('first_name');
			this.field('last_name');
			this.optional('middle_name');
		});

		var sh3 = new Schema().object(function () {
			this.field('first_name');
			this.field('last_name');
			this.field('middle_name').optional();
		});

		var sh4 = new Schema();
			sh4.required('first_name');
			sh4.field('last_name');
			sh4.optional('middle_name');

		test.deepEqual(sh1, sh2);
		test.deepEqual(sh1, sh3);
		test.deepEqual(sh1, sh4);

		test.done();
	},

	'Simple Usage: verify - no specified fields': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = {};
		sh1.verify(value, function (err, isValid, vError) {
			test.ok(!isValid);
			test.equal(vError.ruleName, 'required');
			test.strictEqual(vError.ruleParams, null);
			test.strictEqual(vError.value, undefined);
			test.deepEqual(vError.path, ['first_name']);
			test.done(err);
		});
	},

	'Simple Usage: verify - optional field isn\'t specified': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = { first_name: 'hello', last_name: 'world' };
		sh1.verify(value, function (err, isValid, vError) {
			test.ok(isValid);
			test.strictEqual(vError, null);
			test.done(err);
		});
	},

	'Simple Usage: verify - correct if all available fields not empty': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = { first_name: 'hello', last_name: 'world', middle_name: 'param-pam-pam' };
		sh1.verify(value, function (err, isValid, vError) {
			test.ok(isValid);
			test.strictEqual(vError, null);
			test.done(err);
		});
	},

	'Simple Usage: verify - excess field': function (test) {
		var sh1 = new Schema().object(function () {
			this.field('first_name');
			this.required('last_name');
			this.optional('middle_name');
		});

		var value = {
			first_name: 'hello',
			last_name: 'world',
			middle_name: 'param-pam-pam'
		};
		var _keys = _.keys(value);
		value.excess_field = true;

		sh1.verify(value, function (err, isValid, vError) {
			test.ok(!isValid);
			test.equal(vError.ruleName, 'available_fields');
			test.deepEqual(vError.ruleParams, _keys);
			test.deepEqual(vError.value, value);
			test.deepEqual(vError.path, []);
			test.done(err);
		});
	},

	'Create Schema, Register - equal registering': function (test) {
		var sh1 = new Schema();
		var sh2 = Schema(); // jshint ignore: line
		var sh3 = new Schema('nameForRegister1');
		var sh4 = Schema('nameForRegister2'); // jshint ignore: line
		Schema.register('someSchema1', sh1);
		Schema.register('someSchema2', sh2);

		test.strictEqual(Schema.get('someSchema1'), sh1);
		test.strictEqual(Schema.get('someSchema2'), sh2);
		test.strictEqual(Schema.get('nameForRegister1'), sh3);
		test.strictEqual(Schema.get('nameForRegister2'), sh4);

		test.done();
	},

	'Object Schema Building: attachTo': function (test) {
		var sh1_1 = new Schema().object(function () {
			this.field('hello');
			this.field('world');
		});

		var sh1_2 = new Schema('attachExampleSchema').object(function () {
			this.field('hello');
			this.field('world');
		});

		var sh2 = new Schema().array(function () {
			this.field('some');
		});

		// ATTACH
		sh2.clone().attachTo(sh1_1, 'myField');
		sh2.clone().attachTo('attachExampleSchema', 'myField');

		// EQUAL
		var sh3 = new Schema('Hello').object(function () {
			this.field('hello');
			this.field('world');
			this.field('myField').array(function () {
				this.field('some');
			});
		});

		test.deepEqual(sh1_1, sh3);
		test.deepEqual(sh1_2, sh3);

		test.done();
	},
};<|endoftext|>


<commit_before><commit_msg>trying to improve gs analytics<commit_after><|endoftext|>


<commit_before>// Load modules

var Lab = require('../lib');
var ChildProcess = require('child_process');

// Declare internals

var internals = {};

Lab.experiment('Examples', function () {

    Lab.test('empty.js', function (done) {

        ChildProcess.exec('./bin/lab examples/empty.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('0 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('bdd.js', function (done) {

        ChildProcess.exec('./bin/lab examples/bdd.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('tdd.js', function (done) {

        ChildProcess.exec('./bin/lab examples/tdd.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('after.js', function (done) {

        ChildProcess.exec('./bin/lab examples/after.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('before.js', function (done) {

        ChildProcess.exec('./bin/lab examples/before.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleTest.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleTest.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleExperiment.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleExperiment.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleExperimentFails.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleExperimentFails.js', function (error, stdout, stderr) {

            Lab.expect(error).to.exist;
            Lab.expect(stdout).to.contain('1 of 1 tests failed');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('nestedExperiments.js', function (done) {

        ChildProcess.exec('./bin/lab examples/nestedExperiments.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('5 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('afterError.js', function (done) {

        ChildProcess.exec('./bin/lab examples/afterError.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('beforeError.js', function (done) {

        ChildProcess.exec('./bin/lab examples/beforeError.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleExperimentErrors.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleExperimentErrors.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

});
<commit_msg>update tests for changes in #78<commit_after>// Load modules

var Lab = require('../lib');
var ChildProcess = require('child_process');

// Declare internals

var internals = {};

Lab.experiment('Examples', function () {

    Lab.test('empty.js', function (done) {

        ChildProcess.exec('./bin/lab examples/empty.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('0 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('bdd.js', function (done) {

        ChildProcess.exec('./bin/lab examples/bdd.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('tdd.js', function (done) {

        ChildProcess.exec('./bin/lab examples/tdd.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('after.js', function (done) {

        ChildProcess.exec('./bin/lab examples/after.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('before.js', function (done) {

        ChildProcess.exec('./bin/lab examples/before.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleTest.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleTest.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleExperiment.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleExperiment.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleExperimentFails.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleExperimentFails.js', function (error, stdout, stderr) {

            Lab.expect(error).to.exist;
            Lab.expect(stdout).to.contain('1 of 1 tests failed');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('nestedExperiments.js', function (done) {

        ChildProcess.exec('./bin/lab examples/nestedExperiments.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('5 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('afterError.js', function (done) {

        ChildProcess.exec('./bin/lab examples/afterError.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('beforeError.js', function (done) {

        ChildProcess.exec('./bin/lab examples/beforeError.js', function (error, stdout, stderr) {

            Lab.expect(error).to.not.exist;
            Lab.expect(stdout).to.contain('1 tests complete');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

    Lab.test('singleExperimentErrors.js', function (done) {

        ChildProcess.exec('./bin/lab examples/singleExperimentErrors.js', function (error, stdout, stderr) {

            Lab.expect(error).to.exist;
            Lab.expect(stdout).to.contain('1 of 1 tests failed');
            Lab.expect(stdout).to.contain('No global variable leaks detected');
            done();
        });
    });

});
<|endoftext|>


<commit_before><commit_msg>Change the alt message for download links<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests<commit_after><|endoftext|>


<commit_before>import { getScrollbarWidth } from './scroll.js'
import { client } from '../plugins/Platform.js'

let vpLeft, vpTop

export function validatePosition (pos) {
  let parts = pos.split(' ')
  if (parts.length !== 2) {
    return false
  }
  if (!['top', 'center', 'bottom'].includes(parts[0])) {
    console.error('Anchor/Self position must start with one of top/center/bottom')
    return false
  }
  if (!['left', 'middle', 'right'].includes(parts[1])) {
    console.error('Anchor/Self position must end with one of left/middle/right')
    return false
  }
  return true
}

export function validateOffset (val) {
  if (!val) { return true }
  if (val.length !== 2) { return false }
  if (typeof val[0] !== 'number' || typeof val[1] !== 'number') {
    return false
  }
  return true
}

export function parsePosition (pos) {
  let parts = pos.split(' ')
  return { vertical: parts[0], horizontal: parts[1] }
}

export function validateCover (val) {
  if (val === true || val === false) { return true }
  return validatePosition(val)
}

export function getAnchorProps (el, offset) {
  let { top, left, right, bottom, width, height } = el.getBoundingClientRect()

  if (offset !== void 0) {
    top -= offset[1]
    left -= offset[0]
    bottom += offset[1]
    right += offset[0]

    width += offset[0]
    height += offset[1]
  }

  return {
    top,
    left,
    right,
    bottom,
    width,
    height,
    middle: left + (right - left) / 2,
    center: top + (bottom - top) / 2
  }
}

export function getTargetProps (el) {
  return {
    top: 0,
    center: el.offsetHeight / 2,
    bottom: el.offsetHeight,
    left: 0,
    middle: el.offsetWidth / 2,
    right: el.offsetWidth
  }
}

// cfg: { el, anchorEl, anchorOrigin, selfOrigin, offset, absoluteOffset, cover, fit, maxHeight, maxWidth }
export function setPosition (cfg) {
  if (client.is.ios === true && window.visualViewport !== void 0) {
    // uses the q-position-engine CSS class

    const el = document.body.style
    const { offsetLeft: left, offsetTop: top } = window.visualViewport

    if (left !== vpLeft) {
      el.setProperty('--q-pe-left', left + 'px')
      vpLeft = left
    }
    if (top !== vpTop) {
      el.setProperty('--q-pe-top', top + 'px')
      vpTop = top
    }
  }

  let anchorProps

  // scroll position might change
  // if max-height/-width changes, so we
  // need to restore it after we calculate
  // the new positioning
  const { scrollLeft, scrollTop } = cfg.el

  if (cfg.absoluteOffset === void 0) {
    anchorProps = getAnchorProps(cfg.anchorEl, cfg.cover === true ? [0, 0] : cfg.offset)
  }
  else {
    const
      { top: anchorTop, left: anchorLeft } = cfg.anchorEl.getBoundingClientRect(),
      top = anchorTop + cfg.absoluteOffset.top,
      left = anchorLeft + cfg.absoluteOffset.left

    anchorProps = { top, left, width: 1, height: 1, right: left + 1, center: top, middle: left, bottom: top + 1 }
  }

  let elStyle = {
    maxHeight: cfg.maxHeight,
    maxWidth: cfg.maxWidth,
    visibility: 'visible'
  }

  if (cfg.fit === true || cfg.cover === true) {
    elStyle.minWidth = anchorProps.width + 'px'
    if (cfg.cover === true) {
      elStyle.minHeight = anchorProps.height + 'px'
    }
  }

  Object.assign(cfg.el.style, elStyle)

  const
    targetProps = getTargetProps(cfg.el),
    props = {
      top: anchorProps[cfg.anchorOrigin.vertical] - targetProps[cfg.selfOrigin.vertical],
      left: anchorProps[cfg.anchorOrigin.horizontal] - targetProps[cfg.selfOrigin.horizontal]
    }

  applyBoundaries(props, anchorProps, targetProps, cfg.anchorOrigin, cfg.selfOrigin)

  elStyle = {
    top: Math.floor(props.top) + 'px',
    left: Math.floor(props.left) + 'px'
  }

  if (props.maxHeight !== void 0) {
    elStyle.maxHeight = Math.floor(props.maxHeight) + 'px'

    if (anchorProps.height > props.maxHeight) {
      elStyle.minHeight = elStyle.maxHeight
    }
  }
  if (props.maxWidth !== void 0) {
    elStyle.maxWidth = Math.floor(props.maxWidth) + 'px'

    if (anchorProps.width > props.maxWidth) {
      elStyle.minWidth = elStyle.maxWidth
    }
  }

  Object.assign(cfg.el.style, elStyle)

  // restore scroll position
  if (cfg.el.scrollTop !== scrollTop) {
    cfg.el.scrollTop = scrollTop
  }
  if (cfg.el.scrollLeft !== scrollLeft) {
    cfg.el.scrollLeft = scrollLeft
  }
}

function applyBoundaries (props, anchorProps, targetProps, anchorOrigin, selfOrigin) {
  const
    currentHeight = targetProps.bottom,
    currentWidth = targetProps.right,
    margin = getScrollbarWidth(),
    innerHeight = window.innerHeight - margin,
    innerWidth = document.body.clientWidth

  if (props.top < 0 || props.top + currentHeight > innerHeight) {
    if (selfOrigin.vertical === 'center') {
      props.top = anchorProps[anchorOrigin.vertical] > innerHeight / 2
        ? Math.max(0, innerHeight - currentHeight)
        : 0
      props.maxHeight = Math.min(currentHeight, innerHeight)
    }
    else if (anchorProps[anchorOrigin.vertical] > innerHeight / 2) {
      const anchorY = Math.min(
        innerHeight,
        anchorOrigin.vertical === 'center'
          ? anchorProps.center
          : (anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.bottom : anchorProps.top)
      )
      props.maxHeight = Math.min(currentHeight, anchorY)
      props.top = Math.max(0, anchorY - currentHeight)
    }
    else {
      props.top = Math.max(0, anchorOrigin.vertical === 'center'
        ? anchorProps.center
        : (anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.top : anchorProps.bottom)
      )
      props.maxHeight = Math.min(currentHeight, innerHeight - props.top)
    }
  }

  if (props.left < 0 || props.left + currentWidth > innerWidth) {
    props.maxWidth = Math.min(currentWidth, innerWidth)
    if (selfOrigin.horizontal === 'middle') {
      props.left = anchorProps[anchorOrigin.horizontal] > innerWidth / 2
        ? Math.max(0, innerWidth - currentWidth)
        : 0
    }
    else if (anchorProps[anchorOrigin.horizontal] > innerWidth / 2) {
      const anchorX = Math.min(
        innerWidth,
        anchorOrigin.horizontal === 'middle'
          ? anchorProps.middle
          : (anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.right : anchorProps.left)
      )
      props.maxWidth = Math.min(currentWidth, anchorX)
      props.left = Math.max(0, anchorX - props.maxWidth)
    }
    else {
      props.left = Math.max(0, anchorOrigin.horizontal === 'middle'
        ? anchorProps.middle
        : (anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.left : anchorProps.right)
      )
      props.maxWidth = Math.min(currentWidth, innerWidth - props.left)
    }
  }
}
<commit_msg>fix(QMenu,QTooltip): use round instead of floor for positioning #6673 (#7238)<commit_after>import { getScrollbarWidth } from './scroll.js'
import { client } from '../plugins/Platform.js'

let vpLeft, vpTop

export function validatePosition (pos) {
  let parts = pos.split(' ')
  if (parts.length !== 2) {
    return false
  }
  if (!['top', 'center', 'bottom'].includes(parts[0])) {
    console.error('Anchor/Self position must start with one of top/center/bottom')
    return false
  }
  if (!['left', 'middle', 'right'].includes(parts[1])) {
    console.error('Anchor/Self position must end with one of left/middle/right')
    return false
  }
  return true
}

export function validateOffset (val) {
  if (!val) { return true }
  if (val.length !== 2) { return false }
  if (typeof val[0] !== 'number' || typeof val[1] !== 'number') {
    return false
  }
  return true
}

export function parsePosition (pos) {
  let parts = pos.split(' ')
  return { vertical: parts[0], horizontal: parts[1] }
}

export function validateCover (val) {
  if (val === true || val === false) { return true }
  return validatePosition(val)
}

export function getAnchorProps (el, offset) {
  let { top, left, right, bottom, width, height } = el.getBoundingClientRect()

  if (offset !== void 0) {
    top -= offset[1]
    left -= offset[0]
    bottom += offset[1]
    right += offset[0]

    width += offset[0]
    height += offset[1]
  }

  return {
    top,
    left,
    right,
    bottom,
    width,
    height,
    middle: left + (right - left) / 2,
    center: top + (bottom - top) / 2
  }
}

export function getTargetProps (el) {
  return {
    top: 0,
    center: el.offsetHeight / 2,
    bottom: el.offsetHeight,
    left: 0,
    middle: el.offsetWidth / 2,
    right: el.offsetWidth
  }
}

// cfg: { el, anchorEl, anchorOrigin, selfOrigin, offset, absoluteOffset, cover, fit, maxHeight, maxWidth }
export function setPosition (cfg) {
  if (client.is.ios === true && window.visualViewport !== void 0) {
    // uses the q-position-engine CSS class

    const el = document.body.style
    const { offsetLeft: left, offsetTop: top } = window.visualViewport

    if (left !== vpLeft) {
      el.setProperty('--q-pe-left', left + 'px')
      vpLeft = left
    }
    if (top !== vpTop) {
      el.setProperty('--q-pe-top', top + 'px')
      vpTop = top
    }
  }

  let anchorProps

  // scroll position might change
  // if max-height/-width changes, so we
  // need to restore it after we calculate
  // the new positioning
  const { scrollLeft, scrollTop } = cfg.el

  if (cfg.absoluteOffset === void 0) {
    anchorProps = getAnchorProps(cfg.anchorEl, cfg.cover === true ? [0, 0] : cfg.offset)
  }
  else {
    const
      { top: anchorTop, left: anchorLeft } = cfg.anchorEl.getBoundingClientRect(),
      top = anchorTop + cfg.absoluteOffset.top,
      left = anchorLeft + cfg.absoluteOffset.left

    anchorProps = { top, left, width: 1, height: 1, right: left + 1, center: top, middle: left, bottom: top + 1 }
  }

  let elStyle = {
    maxHeight: cfg.maxHeight,
    maxWidth: cfg.maxWidth,
    visibility: 'visible'
  }

  if (cfg.fit === true || cfg.cover === true) {
    elStyle.minWidth = anchorProps.width + 'px'
    if (cfg.cover === true) {
      elStyle.minHeight = anchorProps.height + 'px'
    }
  }

  Object.assign(cfg.el.style, elStyle)

  const
    targetProps = getTargetProps(cfg.el),
    props = {
      top: anchorProps[cfg.anchorOrigin.vertical] - targetProps[cfg.selfOrigin.vertical],
      left: anchorProps[cfg.anchorOrigin.horizontal] - targetProps[cfg.selfOrigin.horizontal]
    }

  applyBoundaries(props, anchorProps, targetProps, cfg.anchorOrigin, cfg.selfOrigin)

  elStyle = {
    top: Math.round(props.top) + 'px',
    left: Math.round(props.left) + 'px'
  }

  if (props.maxHeight !== void 0) {
    elStyle.maxHeight = Math.round(props.maxHeight) + 'px'

    if (anchorProps.height > props.maxHeight) {
      elStyle.minHeight = elStyle.maxHeight
    }
  }
  if (props.maxWidth !== void 0) {
    elStyle.maxWidth = Math.round(props.maxWidth) + 'px'

    if (anchorProps.width > props.maxWidth) {
      elStyle.minWidth = elStyle.maxWidth
    }
  }

  Object.assign(cfg.el.style, elStyle)

  // restore scroll position
  if (cfg.el.scrollTop !== scrollTop) {
    cfg.el.scrollTop = scrollTop
  }
  if (cfg.el.scrollLeft !== scrollLeft) {
    cfg.el.scrollLeft = scrollLeft
  }
}

function applyBoundaries (props, anchorProps, targetProps, anchorOrigin, selfOrigin) {
  const
    currentHeight = targetProps.bottom,
    currentWidth = targetProps.right,
    margin = getScrollbarWidth(),
    innerHeight = window.innerHeight - margin,
    innerWidth = document.body.clientWidth

  if (props.top < 0 || props.top + currentHeight > innerHeight) {
    if (selfOrigin.vertical === 'center') {
      props.top = anchorProps[anchorOrigin.vertical] > innerHeight / 2
        ? Math.max(0, innerHeight - currentHeight)
        : 0
      props.maxHeight = Math.min(currentHeight, innerHeight)
    }
    else if (anchorProps[anchorOrigin.vertical] > innerHeight / 2) {
      const anchorY = Math.min(
        innerHeight,
        anchorOrigin.vertical === 'center'
          ? anchorProps.center
          : (anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.bottom : anchorProps.top)
      )
      props.maxHeight = Math.min(currentHeight, anchorY)
      props.top = Math.max(0, anchorY - currentHeight)
    }
    else {
      props.top = Math.max(0, anchorOrigin.vertical === 'center'
        ? anchorProps.center
        : (anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.top : anchorProps.bottom)
      )
      props.maxHeight = Math.min(currentHeight, innerHeight - props.top)
    }
  }

  if (props.left < 0 || props.left + currentWidth > innerWidth) {
    props.maxWidth = Math.min(currentWidth, innerWidth)
    if (selfOrigin.horizontal === 'middle') {
      props.left = anchorProps[anchorOrigin.horizontal] > innerWidth / 2
        ? Math.max(0, innerWidth - currentWidth)
        : 0
    }
    else if (anchorProps[anchorOrigin.horizontal] > innerWidth / 2) {
      const anchorX = Math.min(
        innerWidth,
        anchorOrigin.horizontal === 'middle'
          ? anchorProps.middle
          : (anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.right : anchorProps.left)
      )
      props.maxWidth = Math.min(currentWidth, anchorX)
      props.left = Math.max(0, anchorX - props.maxWidth)
    }
    else {
      props.left = Math.max(0, anchorOrigin.horizontal === 'middle'
        ? anchorProps.middle
        : (anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.left : anchorProps.right)
      )
      props.maxWidth = Math.min(currentWidth, innerWidth - props.left)
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

(function(){

var Payloads = {
 'VLAN': 0x8100,
 'MPLS': 0x8847,
 'ARP':  0x0806,
 'IPv4': 0x0800,
 'IPv6': 0x86dd,
 'Payload': 0
};

function _VLAN() {
  this.name = 'VLAN';
  this.attrs = [{
    name: 'PCP',
    value: '0',
    test: fgConstraints.isUInt(0, 7),
    tip: 'VLAN Priority Code Point'
  }, {
    name: 'DEI',
    value: '0',
    test: fgConstraints.isUInt(0,1),
    tip: 'VLAN Drop Eligibility Indicator'
  }, {
    name: 'VLAN ID',
    value: '0',
    test: fgConstraints.isUInt(0, 0x0fff),
    tip: 'VLAN Tag Identifier'
  }, {
    name: 'TypeLen',
    value: '0x0000',
    test: fgConstraints.isUInt(0, 0xffff),
    tip: 'Ethernet type or length of payload'
  }];
}

_VLAN.prototype.bytes = function() {
  return 4;
};

_VLAN.prototype.setPayload = function(name) {
  this.attrs[3].value = '0x' + (Payloads[name] || 0).toString(16);
};

_VLAN.prototype.clearPayload = function() {
  this.attrs[3].value = '0x0000';
};

/**
 * @ngdoc service
 * @name flowsimUiApp.VLAN
 * @description
 * # VLAN
 * Service in the flowsimUiApp.
 */
angular.module('flowsimUiApp')
  .service('VLAN', function VLAN() {
    this.Payloads = Object.keys(Payloads);
    this.create = function() {
      return new _VLAN();
    };
  });

})();

<commit_msg>update<commit_after>'use strict';

(function(){

var Payloads = {
 'VLAN': 0x8100,
 'MPLS': 0x8847,
 'ARP':  0x0806,
 'IPv4': 0x0800,
 'IPv6': 0x86dd,
 'Payload': 0
};

function _VLAN() {
  this.name = 'VLAN';
  this.attrs = [{
    name: 'PCP',
    value: '0',
    test: fgConstraints.isUInt(0, 7),
    tip: 'VLAN Priority Code Point'
  }, {
    name: 'DEI',
    value: '0',
    test: fgConstraints.isUInt(0,1),
    tip: 'VLAN Drop Eligibility Indicator'
  }, {
    name: 'VLAN ID',
    value: '0',
    test: fgConstraints.isUInt(0, 0x0fff),
    tip: 'VLAN Tag Identifier'
  }, {
    name: 'TypeLen',
    value: '0x0000',
    test: fgConstraints.isUInt(0, 0xffff),
    tip: 'Ethernet type or length of payload'
  }];
}

_VLAN.prototype.bytes = function() {
  return 4;
};

_VLAN.prototype.setPayload = function(name) {
  this.attrs[3].value = '0x' + (Payloads[name] || 0).toString(16);
};

_VLAN.prototype.clearPayload = function() {
  this.attrs[3].value = '0x0000';
};

/**
 * @ngdoc service
 * @name flowsimUiApp.VLAN
 * @description
 * # VLAN
 * Service in the flowsimUiApp.
 */
angular.module('flowsimUiApp')
  .service('VLAN', function VLAN() {
    this.name = 'VLAN';
    this.Payloads = Object.keys(Payloads);
    this.create = function() {
      return new _VLAN();
    };
    this.createUI = function(){
      return new _VLAN();
    };
  });

})();
<|endoftext|>


<commit_before>// batchSize 500,
// tableName users_working

var Q = require('q');
var elasticsearch = require('elasticsearch');
var pg = require('pg').native;

var SearchIndexService = function(options){

    var esClient = elasticsearch.Client({
      hosts: [
        options.elasticsearchEndpoint
      ]
    });

    var BATCH_SIZE              = options.batchSize,
        TABLE_NAME              = options.tableName,
        DB_CONNECTION_STRING    = options.dbConnectionString;

    var iterationCount = 0;

    var createIndex = function(deferred){
        var deferred = deferred || Q.defer();

        var sql = 'SELECT * FROM ' + TABLE_NAME + ' WHERE ("user"->>\'_ninya_io_synced\')::boolean is null LIMIT ' + BATCH_SIZE;

        var rejectWithError = function(err){
            console.log('ElasticSearchSync: error ->' + err);
            deferred.reject(err);
        };

        console.log('ElasticSearchSync: connecting to postgres...');

        pg.connect(DB_CONNECTION_STRING, function(err, client, done) {
            if(err) {
                console.log('ElasticSearchSync: could not connect to postgres');
                deferred.reject(err);
                return;
            }

            console.log('ElasticSearchSync: connected to postgres');
            client.query(sql, function(err, result) {
                if(err) {
                    console.log('ElasticSearchSync: could not retrieve batch from postgres');
                    return deferred.reject(err);
                }

                console.log('ElasticSearchSync: retrieved batch from postgres');

                if (result.rows.length === 0){
                    console.log('ElasticSearchSync: sync finished');
                    deferred.resolve('finished');
                    return;
                }

                var tasks = result.rows.map(function(obj){

                    obj.user._ninya_location_lowercase = obj.user.location && obj.user.location.toLowerCase();
                    obj.user._ninya_location = obj.user.location;
                    obj.user._ninya_site = options.stackexchangeSite;

                    var esId = options.stackexchangeSite + '_' + obj.user.user_id;

                    return esClient.index({
                        index: options.elasticsearchIndex,
                        type: 'user',
                        id: esId,
                        body: obj.user
                    });
                });

                Q.all(tasks)
                 .then(function(res){
                    console.log('ElasticSearchSync: added batch');
                    //mark batch as synced
                    return Q.all(result.rows.map(function(obj){
                        var user = obj.user;
                        user._ninya_io_synced = true;
                        return client.query('UPDATE ' + TABLE_NAME + ' SET "user" = $1 WHERE "user"->>\'user_id\' = \'' + user.user_id  + '\'', [user], function(err, result) {
                            if (err){
                                console.log(err);
                            }
                        });
                    }))
                    .then(function(){
                        iterationCount++;
                        done();
                        console.log('ElasticSearchSync: flagged batch as processed');
                        console.log('ElasticSearchSync: finished ' + iterationCount + ' iteration(s)');
                        //start over
                        createIndex(deferred);
                    });
                 }, rejectWithError);
            });
        });

        return deferred.promise;
    };

    return {
        createIndex: createIndex
    }
};

module.exports = SearchIndexService;<commit_msg>fix(elasticsearch-sync): rename sync property<commit_after>// batchSize 500,
// tableName users_working

var Q = require('q');
var elasticsearch = require('elasticsearch');
var pg = require('pg').native;

var SearchIndexService = function(options){

    var esClient = elasticsearch.Client({
      hosts: [
        options.elasticsearchEndpoint
      ]
    });

    var BATCH_SIZE              = options.batchSize,
        TABLE_NAME              = options.tableName,
        DB_CONNECTION_STRING    = options.dbConnectionString;

    var iterationCount = 0;

    var createIndex = function(deferred){
        var deferred = deferred || Q.defer();

        var sql = 'SELECT * FROM ' + TABLE_NAME + ' WHERE ("user"->>\'_ninya_synced\')::boolean is null LIMIT ' + BATCH_SIZE;

        var rejectWithError = function(err){
            console.log('ElasticSearchSync: error ->' + err);
            deferred.reject(err);
        };

        console.log('ElasticSearchSync: connecting to postgres...');

        pg.connect(DB_CONNECTION_STRING, function(err, client, done) {
            if(err) {
                console.log('ElasticSearchSync: could not connect to postgres');
                deferred.reject(err);
                return;
            }

            console.log('ElasticSearchSync: connected to postgres');
            client.query(sql, function(err, result) {
                if(err) {
                    console.log('ElasticSearchSync: could not retrieve batch from postgres');
                    return deferred.reject(err);
                }

                console.log('ElasticSearchSync: retrieved batch from postgres');

                if (result.rows.length === 0){
                    console.log('ElasticSearchSync: sync finished');
                    deferred.resolve('finished');
                    return;
                }

                var tasks = result.rows.map(function(obj){

                    obj.user._ninya_location_lowercase = obj.user.location && obj.user.location.toLowerCase();
                    obj.user._ninya_location = obj.user.location;
                    obj.user._ninya_site = options.stackexchangeSite;

                    var esId = options.stackexchangeSite + '_' + obj.user.user_id;

                    return esClient.index({
                        index: options.elasticsearchIndex,
                        type: 'user',
                        id: esId,
                        body: obj.user
                    });
                });

                Q.all(tasks)
                 .then(function(res){
                    console.log('ElasticSearchSync: added batch');
                    //mark batch as synced
                    return Q.all(result.rows.map(function(obj){
                        var user = obj.user;
                        user._ninya_synced = true;
                        return client.query('UPDATE ' + TABLE_NAME + ' SET "user" = $1 WHERE "user"->>\'user_id\' = \'' + user.user_id  + '\'', [user], function(err, result) {
                            if (err){
                                console.log(err);
                            }
                        });
                    }))
                    .then(function(){
                        iterationCount++;
                        done();
                        console.log('ElasticSearchSync: flagged batch as processed');
                        console.log('ElasticSearchSync: finished ' + iterationCount + ' iteration(s)');
                        //start over
                        createIndex(deferred);
                    });
                 }, rejectWithError);
            });
        });

        return deferred.promise;
    };

    return {
        createIndex: createIndex
    }
};

module.exports = SearchIndexService;<|endoftext|>