<commit_before>/// <reference path="validation-controler.js" />
/// <reference path="Class.js" />
/// <reference path="../jquery-2.0.2.js" />
/// <reference path="persister.js" />
/// <reference path="ui.js" />

$(document).ready(function () {
    var myMainPersister = persister.mainPersister('http://localhost:47655/api');//47655

    // Check is user logged in
    if (localStorage.getItem('authCode') == '' || localStorage.getItem('authCode') == null || localStorage.getItem('authCode') == undefined) {
        $('#login-container').html(ui.drawLogIn());
    }
    else {
        $('#login-container').html(ui.drawLoggedIn());
        $('#main-game-container').html(ui.drawUserInteraction());
        $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
    }

    var int = self.setInterval(function () {
        if (localStorage.getItem('authCode') != '') {
        }
        else {
            window.clearInterval(int);
        }
    }, 5000);

    var eventControler = (function () {
        function addElementsEvents(persister) {
            // Logout
            $('#wrapper').on('click', '#user-loged-in #button-logout', function () {
                $('#login-container').empty();
                $('#left-side-bar').empty();
                $('#right-side-bar').empty();
                $('#main-game-container').empty();
                $('#main-game-container').append($('<div />').attr('id', 'error-messages'));
                $('#main-game-container').append($('<div />').attr('id', 'messages'));
                $('#login-container').html(ui.drawLogIn());

                persister.user.logout();
            });

            // Log in
            $('#wrapper').on('click', '#button-log-in', function () {
                var username = $('#login-user-nickname').val();
                var password = $('#login-user-password').val();

                ui.clearErrorMessage();
                persister.user.login(username, password, ui.showErrorMessage);
                setTimeout(function () {
                    if (localStorage.getItem('authCode') != '' && localStorage.getItem('authCode') != undefined) {
                        ui.clearErrorMessage();
                        $('#login-container').html(ui.drawLoggedIn());
                        $('#main-game-container').html(ui.drawUserInteraction());
                        $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
                    }
                }, 500);
            });

            // Register now
            $('#wrapper').on('click', '#register-now', function () {
                $('#login-container').html(ui.drawRegister());
            });

            // Register back
            $('#wrapper').on('click', '#back-to-homepage', function () {
                $('#login-container').html(ui.drawLogIn());
            });

            // Send register request
            $('#wrapper').on('click', '#button-register', function () {
                var username = $('#register-user-nickname').val();
                var nickname = $('#register-user-nickname').val();
                var password = $('#register-user-password').val();
                var passwordRe = $('#register-user-password-re').val();

                var isUsernameValid = validationControler.isUsernameCorrect(username);
                var isPasswordValid = validationControler.isPasswordCorrect(password);
                var isPasswordsEqual = password === passwordRe;

                if (isUsernameValid && isPasswordValid && isPasswordsEqual) {
                    persister.user.register(username, nickname, password, ui.showErrorMessage);
                    setTimeout(function () {
                    $('#login-container').html(ui.drawLoggedIn());
                    ui.clearErrorMessage();
                    }, 500);
                }
                else {
                    ui.showAppErrorMessage('Invalid username or password! Check your account information and try again.');
                }
            });

            // Create new game
            $('#wrapper').on('click', '#user-loged-in #button-create-new-chat', function () {
                $('#user-loged-in').html(ui.drawCreateGameMenu());
            });

            // Create new game confirm
            $('#wrapper').on('click', '#confirm-create-game', function () {
                var gameName = $('#create-game-name').val();
                var gamePassword = $('#create-game-password').val();
                $('#game-user-create').remove();
                $('#login-container').html(ui.drawLoggedIn());

                ui.clearErrorMessage();
                ui.showMessage('Game created');
                persister.game.create(gameName, gamePassword, ui.clearErrorMessage, ui.showErrorMessage);
            });

            // Show or hide list of my games
            $('#wrapper').on('click', '#games-active', function () {
                ui.showOrHideElements('#games-active');
            });

            $('#wrapper').on('click', '#games-open', function () {
                ui.showOrHideElements('#games-open');
            });

            $('#wrapper').on('click', '#games-messages', function () {
                ui.showOrHideElements('#games-messages');
            });

            // Confirm join in game
            $('#wrapper').on('click', '.button-join', function () {
                var gameID = $(this).parent('li').attr('data-game-id');
                var gamePassword;
                persister.game.join(gameID, gamePassword, function () {
                    ui.clearErrorMessage;
                    $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
                }, ui.showErrorMessage);

                ui.showMessage('You joined in game.');
            });

            // Start game new version
            $('#wrapper').on('click', '.button-start', function () {
                var gameID = $(this).parent('li').attr('data-game-id');
                //var gameNumber = $('#player-guess-text').val();
                //drawSidebars(persister);
                persister.game.start(gameID, function () {
                    ui.clearErrorMessage;
                    $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
                }, ui.showErrorMessage);
                ui.showMessage('Game is started.');
            });

            // View current game state
            $('#wrapper').on('click', '.button-view-state', function () {
                var gameID = $(this).parent('li').attr('data-game-id');
                //var gameNumber = $('#player-guess-text').val();
                persister.game.field(gameID, function (data) {
                    ui.clearErrorMessage();
                    $('#game-state-container').empty();
                    $('#game-state-container').load('game-field.html', function () {
                        ui.drawCurrentGameState(data);
                    });
                }, ui.showErrorMessage);
            });

            // Move or attack
        //    $('#wrapper').on('click', '#game-state-container table tr td', function () {
        //        var currentState = $('#game-state-container table').attr('data-is-attacing');
        //        var currentGameId = $('#game-state-container table').attr('data-game-id');
        //        var currentUnitId = $(this).attr('data-unit-id');
        //        var currentUnitPosX = $(this).attr('data-pos-x');
        //        var currentUnitPosY = $(this).attr('data-pos-y');
        //        var currentPosition = { x: currentUnitPosX, y: currentUnitPosY };

        //        if (currentState == 'true') {
        //            currentUnitId = localStorage.getItem('unit-id');

        //            var attackerRange = localStorage.getItem('attacer-range');
        //            var attackerPosX = localStorage.getItem('attacer-pos-x');
        //            var attackerPosY = localStorage.getItem('attacer-pos-y');

        //            var currentAttackRange = Math.abs(attackerPosX - currentUnitPosX) + Math.abs(attackerPosY - currentUnitPosY);
        //            var isAttackPosible = attackerRange >= currentAttackRange;
        //            var isOpponentUnit = $(this).attr('data-unit-id') != undefined;

        //            if (isAttackPosible && isOpponentUnit) {
        //                persister.battle.attack(currentGameId, currentUnitId, currentPosition, function () {
        //                    ui.showMessage('Attack is success.');

        //                    persister.game.field(currentGameId, function (data) {
        //                        ui.clearErrorMessage();
        //                        $('#game-state-container').empty();
        //                        $('#game-state-container').load('game-field.html', function () {
        //                            ui.drawCurrentGameState(data);
        //                        });
        //                    }, ui.showErrorMessage);
        //                },
        //                function (err) {
        //                    ui.showErrorMessage(err);
        //                });
        //            }
        //            else {
        //                persister.battle.move(currentGameId, currentUnitId, currentPosition, function () {
        //                    ui.showMessage('Move is success.');

        //                    persister.game.field(currentGameId, function (data) {
        //                        ui.clearErrorMessage();
        //                        $('#game-state-container').empty();
        //                        $('#game-state-container').load('game-field.html', function () {
        //                            ui.drawCurrentGameState(data);
        //                        });
        //                    }, ui.showErrorMessage);
        //                },
        //                function (err) {
        //                    ui.showErrorMessage(err);
        //                });
        //            }

        //            $('#game-state-container table').attr('data-is-attacing', 'false');
        //            localStorage.setItem('unit-id', '');
        //            localStorage.setItem('unit-id', '');
        //            localStorage.setItem('attacer-pos-x', '');
        //            localStorage.setItem('attacer-pos-y', '');
        //            localStorage.setItem('attacer-range', '');
        //        }
        //        else {
        //            $('#game-state-container table').attr('data-is-attacing', 'true');
        //            localStorage.setItem('unit-id', currentUnitId);

        //            localStorage.setItem('attacer-pos-x', currentUnitPosX);
        //            localStorage.setItem('attacer-pos-y', currentUnitPosY);

        //            if ($(this).text() == 'W') {
        //                localStorage.setItem('attacer-range', '1');
        //            }
        //            else if ($(this).text() == 'R') {
        //                localStorage.setItem('attacer-range', '3');
        //            }
        //        }
        //    });
        }

        return {
            addEvents: addElementsEvents
        }
    }());

    eventControler.addEvents(myMainPersister);
});<commit_msg>Changed app URL<commit_after>/// <reference path="validation-controler.js" />
/// <reference path="Class.js" />
/// <reference path="../jquery-2.0.2.js" />
/// <reference path="persister.js" />
/// <reference path="ui.js" />

$(document).ready(function () {
    var myMainPersister = persister.mainPersister('http://zorrochat.apphb.com/api');//47655

    // Check is user logged in
    if (localStorage.getItem('authCode') == '' || localStorage.getItem('authCode') == null || localStorage.getItem('authCode') == undefined) {
        $('#login-container').html(ui.drawLogIn());
    }
    else {
        $('#login-container').html(ui.drawLoggedIn());
        $('#main-game-container').html(ui.drawUserInteraction());
        $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
    }

    var int = self.setInterval(function () {
        if (localStorage.getItem('authCode') != '') {
        }
        else {
            window.clearInterval(int);
        }
    }, 5000);

    var eventControler = (function () {
        function addElementsEvents(persister) {
            // Logout
            $('#wrapper').on('click', '#user-loged-in #button-logout', function () {
                $('#login-container').empty();
                $('#left-side-bar').empty();
                $('#right-side-bar').empty();
                $('#main-game-container').empty();
                $('#main-game-container').append($('<div />').attr('id', 'error-messages'));
                $('#main-game-container').append($('<div />').attr('id', 'messages'));
                $('#login-container').html(ui.drawLogIn());

                persister.user.logout();
            });

            // Log in
            $('#wrapper').on('click', '#button-log-in', function () {
                var username = $('#login-user-nickname').val();
                var password = $('#login-user-password').val();

                ui.clearErrorMessage();
                persister.user.login(username, password, ui.showErrorMessage);
                setTimeout(function () {
                    if (localStorage.getItem('authCode') != '' && localStorage.getItem('authCode') != undefined) {
                        ui.clearErrorMessage();
                        $('#login-container').html(ui.drawLoggedIn());
                        $('#main-game-container').html(ui.drawUserInteraction());
                        $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
                    }
                }, 500);
            });

            // Register now
            $('#wrapper').on('click', '#register-now', function () {
                $('#login-container').html(ui.drawRegister());
            });

            // Register back
            $('#wrapper').on('click', '#back-to-homepage', function () {
                $('#login-container').html(ui.drawLogIn());
            });

            // Send register request
            $('#wrapper').on('click', '#button-register', function () {
                var username = $('#register-user-nickname').val();
                var nickname = $('#register-user-nickname').val();
                var password = $('#register-user-password').val();
                var passwordRe = $('#register-user-password-re').val();

                var isUsernameValid = validationControler.isUsernameCorrect(username);
                var isPasswordValid = validationControler.isPasswordCorrect(password);
                var isPasswordsEqual = password === passwordRe;

                if (isUsernameValid && isPasswordValid && isPasswordsEqual) {
                    persister.user.register(username, nickname, password, ui.showErrorMessage);
                    setTimeout(function () {
                    $('#login-container').html(ui.drawLoggedIn());
                    ui.clearErrorMessage();
                    }, 500);
                }
                else {
                    ui.showAppErrorMessage('Invalid username or password! Check your account information and try again.');
                }
            });

            // Create new game
            $('#wrapper').on('click', '#user-loged-in #button-create-new-chat', function () {
                $('#user-loged-in').html(ui.drawCreateGameMenu());
            });

            // Create new game confirm
            $('#wrapper').on('click', '#confirm-create-game', function () {
                var gameName = $('#create-game-name').val();
                var gamePassword = $('#create-game-password').val();
                $('#game-user-create').remove();
                $('#login-container').html(ui.drawLoggedIn());

                ui.clearErrorMessage();
                ui.showMessage('Game created');
                persister.game.create(gameName, gamePassword, ui.clearErrorMessage, ui.showErrorMessage);
            });

            // Show or hide list of my games
            $('#wrapper').on('click', '#games-active', function () {
                ui.showOrHideElements('#games-active');
            });

            $('#wrapper').on('click', '#games-open', function () {
                ui.showOrHideElements('#games-open');
            });

            $('#wrapper').on('click', '#games-messages', function () {
                ui.showOrHideElements('#games-messages');
            });

            // Confirm join in game
            $('#wrapper').on('click', '.button-join', function () {
                var gameID = $(this).parent('li').attr('data-game-id');
                var gamePassword;
                persister.game.join(gameID, gamePassword, function () {
                    ui.clearErrorMessage;
                    $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
                }, ui.showErrorMessage);

                ui.showMessage('You joined in game.');
            });

            // Start game new version
            $('#wrapper').on('click', '.button-start', function () {
                var gameID = $(this).parent('li').attr('data-game-id');
                //var gameNumber = $('#player-guess-text').val();
                //drawSidebars(persister);
                persister.game.start(gameID, function () {
                    ui.clearErrorMessage;
                    $('#left-side-bar').html(ui.drawSidebars(myMainPersister));
                }, ui.showErrorMessage);
                ui.showMessage('Game is started.');
            });

            // View current game state
            $('#wrapper').on('click', '.button-view-state', function () {
                var gameID = $(this).parent('li').attr('data-game-id');
                //var gameNumber = $('#player-guess-text').val();
                persister.game.field(gameID, function (data) {
                    ui.clearErrorMessage();
                    $('#game-state-container').empty();
                    $('#game-state-container').load('game-field.html', function () {
                        ui.drawCurrentGameState(data);
                    });
                }, ui.showErrorMessage);
            });

            // Move or attack
        //    $('#wrapper').on('click', '#game-state-container table tr td', function () {
        //        var currentState = $('#game-state-container table').attr('data-is-attacing');
        //        var currentGameId = $('#game-state-container table').attr('data-game-id');
        //        var currentUnitId = $(this).attr('data-unit-id');
        //        var currentUnitPosX = $(this).attr('data-pos-x');
        //        var currentUnitPosY = $(this).attr('data-pos-y');
        //        var currentPosition = { x: currentUnitPosX, y: currentUnitPosY };

        //        if (currentState == 'true') {
        //            currentUnitId = localStorage.getItem('unit-id');

        //            var attackerRange = localStorage.getItem('attacer-range');
        //            var attackerPosX = localStorage.getItem('attacer-pos-x');
        //            var attackerPosY = localStorage.getItem('attacer-pos-y');

        //            var currentAttackRange = Math.abs(attackerPosX - currentUnitPosX) + Math.abs(attackerPosY - currentUnitPosY);
        //            var isAttackPosible = attackerRange >= currentAttackRange;
        //            var isOpponentUnit = $(this).attr('data-unit-id') != undefined;

        //            if (isAttackPosible && isOpponentUnit) {
        //                persister.battle.attack(currentGameId, currentUnitId, currentPosition, function () {
        //                    ui.showMessage('Attack is success.');

        //                    persister.game.field(currentGameId, function (data) {
        //                        ui.clearErrorMessage();
        //                        $('#game-state-container').empty();
        //                        $('#game-state-container').load('game-field.html', function () {
        //                            ui.drawCurrentGameState(data);
        //                        });
        //                    }, ui.showErrorMessage);
        //                },
        //                function (err) {
        //                    ui.showErrorMessage(err);
        //                });
        //            }
        //            else {
        //                persister.battle.move(currentGameId, currentUnitId, currentPosition, function () {
        //                    ui.showMessage('Move is success.');

        //                    persister.game.field(currentGameId, function (data) {
        //                        ui.clearErrorMessage();
        //                        $('#game-state-container').empty();
        //                        $('#game-state-container').load('game-field.html', function () {
        //                            ui.drawCurrentGameState(data);
        //                        });
        //                    }, ui.showErrorMessage);
        //                },
        //                function (err) {
        //                    ui.showErrorMessage(err);
        //                });
        //            }

        //            $('#game-state-container table').attr('data-is-attacing', 'false');
        //            localStorage.setItem('unit-id', '');
        //            localStorage.setItem('unit-id', '');
        //            localStorage.setItem('attacer-pos-x', '');
        //            localStorage.setItem('attacer-pos-y', '');
        //            localStorage.setItem('attacer-range', '');
        //        }
        //        else {
        //            $('#game-state-container table').attr('data-is-attacing', 'true');
        //            localStorage.setItem('unit-id', currentUnitId);

        //            localStorage.setItem('attacer-pos-x', currentUnitPosX);
        //            localStorage.setItem('attacer-pos-y', currentUnitPosY);

        //            if ($(this).text() == 'W') {
        //                localStorage.setItem('attacer-range', '1');
        //            }
        //            else if ($(this).text() == 'R') {
        //                localStorage.setItem('attacer-range', '3');
        //            }
        //        }
        //    });
        }

        return {
            addEvents: addElementsEvents
        }
    }());

    eventControler.addEvents(myMainPersister);
});<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * ndf command protocol
 *
 * list systems
 * list container systemid
 *
 *
 */

'use strict';

var cmdsrv = require('cmdsrv');
var netOut = require('./networkOut');
var logger = require('winston');

module.exports = function(api) {
  var _server;

  var listSystems = function(out) {
    api.listSystems(function(err, systems) {
      logger.info('rsp: list systems');
      out.response(systems);
    });
  };

  var createSystem = function(out, name, namespace) {
    api.createSystem(name, namespace, function(err, system) {
      logger.info('rsp: create system');
      out.response(system);
    });
  };

  var getSystem = function(out, systemId) {
    api.getHeadSystem(systemId, function(err, system) {
      logger.info('rsp: get system ' + systemId);
      out.response(system);
    });
  };

  var getDeployed = function(out, systemId) {
    api.getDeployedSystem(systemId, function(err, system) {
      logger.info('rsp: get deployed ' + systemId);
      out.response(system);
    });
  };

  var putSystem = function(out, systemJson, user) {
    api.putSystem(user, systemJson, function(err) {
      logger.info('rsp: put system');
      if (err) {
        out.response({result: 'err', err: err});
      }
      else {
        out.response({result: 'ok'});
      }
    });
  };

  var deleteSystem = function(out, user, systemId) {
    api.deleteSystem(user, systemId, function(err) {
      logger.info('rsp: delete system');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var listContainers = function(out, systemId) {
    api.listContainers(systemId, function(err, containers) {
      logger.info('rsp: list containers ' + systemId);
      out.response(containers);
    });
  };

  var addContainer = function(out, containerJson, user, systemId) {
    api.addContainer(user, systemId, containerJson, function(err) {
      logger.info('rsp: add container');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var putContainer = function(out, containerJson, user, systemId) {
    api.putContainer(user, systemId, containerJson, function(err) {
      logger.info('rsp: put container');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var deleteContainer = function(out, user, systemId, containerId) {
    api.deleteContainer(user, systemId, containerId, function(err) {
      logger.info('rsp: delete container');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var buildContainer = function(out, user, systemId, containerId) {
    api.buildContainer(user, systemId, containerId, out, function(err, result) {
      logger.info('rsp: build container ' + systemId);
      out.response(result);
    });
  };

  var deploySystem = function(out, user, systemId, revisionId) {
    api.deploySystem(user, systemId, revisionId, out, function(err, result) {
      logger.info('rsp: deploy system ' + user + ' ' + systemId + ' ' + revisionId);
      out.response(result);
    });
  };

  var deployAll = function(out, systemId, revisionId) {
    api.deployAll(systemId, revisionId, out, function(err) {
      logger.info('rsp: deploy all' + systemId + ' ' + revisionId);
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var listRevisions = function(out, systemId) {
    api.listRevisions(systemId, function(err, result) {
      logger.info('rsp: list revisions ' + systemId);
      out.response(result);
    });
  };

  var getRevision = function(out, systemId, revisionId) {
    api.getRevision(systemId, revisionId, function(err, result) {
      logger.info('rsp: get revision ' + systemId);
      out.response(result);
    });
  };

  var timeline = function(out, systemId, containerId, user) {
    api.timeline(systemId, containerId, user, function(err, result) {
      logger.info('rsp: timeline');
      out.response(result);
    });
  };

  var addToTimeline = function(out, timelineJson) {
    api.addToTimeline(timelineJson, function(err) {
      logger.info('rsp: add to timeline');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var quitConnection = function(connection, out) {
    logger.info('rsp: quit');
    out.response({bye: 'bye!'}, function() {
      connection.end();
    });
  };

  var handlers = {list: { systems: listSystems,
                          containers: listContainers,
                          revisions: listRevisions,
                          timeline: timeline},
                  create: {system: createSystem},
                  get: {system: getSystem, revision: getRevision, deployed: getDeployed},
                  add: {container: addContainer, timeline: addToTimeline},
                  put: {system: putSystem, container: putContainer},
                  delete: {system: deleteSystem, container: deleteContainer},
                  build: { container: buildContainer},
                  deploy: { system: deploySystem, all: deployAll},
                  quit: quitConnection };

  /**
   * construct the server
   */
  var construct = function() {
    _server = new cmdsrv();
    var mode = 'command';
    var put = '';
    var lineTarget;
    var lineUser;
    var lineId;

    _server.on('list', function(connection, target, systemId, containerId, user){
      logger.info('rcv: list ' + target);
      handlers.list[target](netOut(connection, 'list ' + target), systemId, containerId, user);
    });

    _server.on('create', function(connection, target, name, namespace){
      logger.info('rcv: create ' + target);
      handlers.create[target](netOut(connection, 'create ' + target), name, namespace);
    });

    _server.on('get', function(connection, target, systemId, otherId){
      logger.info('rcv: get ' + target);
      handlers.get[target](netOut(connection, 'get ' + target), systemId, otherId);
    });

    _server.on('delete', function(connection, target, user, systemId, containerId){
      logger.info('rcv: delete ' + target);
      handlers.delete[target](netOut(connection, 'delete ' + target), user, systemId, containerId);
    });

    _server.on('add', function(connection, target, user, id) {
      mode = 'lineAdd';
      logger.info('rcv: add ' + target);
      put = '';
      lineTarget = target;
      lineUser = user;
      lineId = id;
    });

    _server.on('put', function(connection, target, user, id){
      mode = 'linePut';
      logger.info('rcv: put ' + target);
      put = '';
      lineTarget = target;
      lineUser = user;
      lineId = id;
    });

    _server.on('build', function(connection, target, user, systemId, containerId){
      logger.info('rcv: build ' + target);
      handlers.build[target](netOut(connection, 'build ' + target), user, systemId, containerId);
    });

    _server.on('deploy', function(connection, target, user, systemId, revisionId){
      logger.info('rcv: deploy ' + target);
      handlers.deploy[target](netOut(connection, 'deploy ' + target), user, systemId, revisionId);
    });

    _server.on('quit', function(connection){
      logger.info('rcv: quit');
      handlers.quit(connection, netOut(connection, 'quit'));
    });

    _server.on('line', function(connection, line) {
      console.log('LINE: ' + line);
      if (mode === 'linePut') {
        if (line.indexOf('END') !== -1) {
          mode = 'command';
          handlers.put[lineTarget](netOut(connection, 'put ' + lineTarget), put, lineUser, lineId);
        }
        else {
          put += line;
        }
      }
      if (mode === 'lineAdd') {
        if (line.indexOf('END') !== -1) {
          mode = 'command';
          handlers.add[lineTarget](netOut(connection, 'add ' + lineTarget), put, lineUser, lineId);
        }
        else {
          put += line;
        }
      }
    });

    logger.info('starting protocol...');
    _server.start();
  };

  construct();
  return {
  };
};

<commit_msg>Added login, token and authorized logic<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * ndf command protocol
 *
 * list systems
 * list container systemid
 *
 *
 */

'use strict';

var cmdsrv = require('cmdsrv');
var netOut = require('./networkOut');
var auth = require('../../nfd-auth')();

var logger = require('winston');

module.exports = function(api) {
  var _server;

  var login = function(connection, username, password) {
    var out = netOut(connection, 'login ' + username);
    auth.login(username, password, function(err, user) {
      if (err) {return out.stderr(err);}
      connection.user = user;
      out.response(connection.user);
    });
  }

  var token = function(connection, token) {
    var out = netOut(connection, 'token ' + token);
    auth.userInfo(token, function(err, user) {
      if (err) {return out.stderr(err);}
      logger.info('TOKEN ' + token);
      logger.info(user);
      connection.user = user;
      out.response(connection.user);
    });
  }

  var authorized = function(connection, out) {
    if (!connection.user) {
      out.response({ok:false, err:'Unauthorized'});
    }
    return !!connection.user;
  }

  var listSystems = function(out) {
    api.listSystems(function(err, systems) {
      logger.info('rsp: list systems');
      out.response(systems);
    });
  };

  var createSystem = function(out, name, namespace) {
    api.createSystem(name, namespace, function(err, system) {
      logger.info('rsp: create system');
      out.response(system);
    });
  };

  var getSystem = function(out, systemId) {
    api.getHeadSystem(systemId, function(err, system) {
      logger.info('rsp: get system ' + systemId);
      out.response(system);
    });
  };

  var getDeployed = function(out, systemId) {
    api.getDeployedSystem(systemId, function(err, system) {
      logger.info('rsp: get deployed ' + systemId);
      out.response(system);
    });
  };

  var putSystem = function(out, systemJson, user) {
    api.putSystem(user, systemJson, function(err) {
      logger.info('rsp: put system');
      if (err) {
        out.response({result: 'err', err: err});
      }
      else {
        out.response({result: 'ok'});
      }
    });
  };

  var deleteSystem = function(out, user, systemId) {
    api.deleteSystem(user, systemId, function(err) {
      logger.info('rsp: delete system');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var listContainers = function(out, systemId) {
    api.listContainers(systemId, function(err, containers) {
      logger.info('rsp: list containers ' + systemId);
      out.response(containers);
    });
  };

  var addContainer = function(out, containerJson, user, systemId) {
    api.addContainer(user, systemId, containerJson, function(err) {
      logger.info('rsp: add container');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var putContainer = function(out, containerJson, user, systemId) {
    api.putContainer(user, systemId, containerJson, function(err) {
      logger.info('rsp: put container');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var deleteContainer = function(out, user, systemId, containerId) {
    api.deleteContainer(user, systemId, containerId, function(err) {
      logger.info('rsp: delete container');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var buildContainer = function(out, user, systemId, containerId) {
    api.buildContainer(user, systemId, containerId, out, function(err, result) {
      logger.info('rsp: build container ' + systemId);
      out.response(result);
    });
  };

  var deploySystem = function(out, user, systemId, revisionId) {
    api.deploySystem(user, systemId, revisionId, out, function(err, result) {
      logger.info('rsp: deploy system ' + user + ' ' + systemId + ' ' + revisionId);
      out.response(result);
    });
  };

  var deployAll = function(out, systemId, revisionId) {
    api.deployAll(systemId, revisionId, out, function(err) {
      logger.info('rsp: deploy all' + systemId + ' ' + revisionId);
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var listRevisions = function(out, systemId) {
    api.listRevisions(systemId, function(err, result) {
      logger.info('rsp: list revisions ' + systemId);
      out.response(result);
    });
  };

  var getRevision = function(out, systemId, revisionId) {
    api.getRevision(systemId, revisionId, function(err, result) {
      logger.info('rsp: get revision ' + systemId);
      out.response(result);
    });
  };

  var timeline = function(out, systemId, containerId, user) {
    api.timeline(systemId, containerId, user, function(err, result) {
      logger.info('rsp: timeline');
      out.response(result);
    });
  };

  var addToTimeline = function(out, timelineJson) {
    api.addToTimeline(timelineJson, function(err) {
      logger.info('rsp: add to timeline');
      if (err) { out.response({result: 'err', err: err}); }
      else { out.response({result: 'ok'}); }
    });
  };

  var quitConnection = function(connection, out) {
    logger.info('rsp: quit');
    out.response({bye: 'bye!'}, function() {
      connection.end();
    });
  };

  var handlers = {
                  login: login,
                  token: token,
                  authorized: authorized,
                  list: { systems: listSystems,
                          containers: listContainers,
                          revisions: listRevisions,
                          timeline: timeline},
                  create: {system: createSystem},
                  get: {system: getSystem, revision: getRevision, deployed: getDeployed},
                  add: {container: addContainer, timeline: addToTimeline},
                  put: {system: putSystem, container: putContainer},
                  delete: {system: deleteSystem, container: deleteContainer},
                  build: { container: buildContainer},
                  deploy: { system: deploySystem, all: deployAll},
                  quit: quitConnection };

  /**
   * construct the server
   */
  var construct = function() {
    _server = new cmdsrv();

    var mode = 'command';
    var put = '';
    var lineTarget;
    var lineUser;
    var lineId;

    _server.on('login', function(connection, username, password){
      logger.info('rcv: login ' + username);
      handlers.login(connection, username, password);
    });

    _server.on('token', function(connection, token){
      logger.info('rcv: token ' + token);
      handlers.token(connection, token);
    });

    _server.on('list', function(connection, target, systemId, containerId, user){
      if (!handlers.authorized(connection, netOut(connection, 'list ' + target))) {return;}
      logger.info('rcv: list ' + target);
      handlers.list[target](netOut(connection, 'list ' + target), systemId, containerId, user);
    });

    _server.on('create', function(connection, target, name, namespace){
      logger.info('rcv: create ' + target);
      handlers.create[target](netOut(connection, 'create ' + target), name, namespace);
    });

    _server.on('get', function(connection, target, systemId, otherId){
      logger.info('rcv: get ' + target);
      handlers.get[target](netOut(connection, 'get ' + target), systemId, otherId);
    });

    _server.on('delete', function(connection, target, user, systemId, containerId){
      logger.info('rcv: delete ' + target);
      handlers.delete[target](netOut(connection, 'delete ' + target), user, systemId, containerId);
    });

    _server.on('add', function(connection, target, user, id) {
      mode = 'lineAdd';
      logger.info('rcv: add ' + target);
      put = '';
      lineTarget = target;
      lineUser = user;
      lineId = id;
    });

    _server.on('put', function(connection, target, user, id){
      mode = 'linePut';
      logger.info('rcv: put ' + target);
      put = '';
      lineTarget = target;
      lineUser = user;
      lineId = id;
    });

    _server.on('build', function(connection, target, user, systemId, containerId){
      logger.info('rcv: build ' + target);
      handlers.build[target](netOut(connection, 'build ' + target), user, systemId, containerId);
    });

    _server.on('deploy', function(connection, target, user, systemId, revisionId){
      logger.info('rcv: deploy ' + target);
      handlers.deploy[target](netOut(connection, 'deploy ' + target), user, systemId, revisionId);
    });

    _server.on('quit', function(connection){
      logger.info('rcv: quit');
      handlers.quit(connection, netOut(connection, 'quit'));
    });

    _server.on('line', function(connection, line) {
      console.log('LINE: ' + line);

      if (mode === 'linePut') {
        if (line.indexOf('END') !== -1) {
          mode = 'command';
          handlers.put[lineTarget](netOut(connection, 'put ' + lineTarget), put, lineUser, lineId);
        }
        else {
          put += line;
        }
      }
      if (mode === 'lineAdd') {
        if (line.indexOf('END') !== -1) {
          mode = 'command';
          handlers.add[lineTarget](netOut(connection, 'add ' + lineTarget), put, lineUser, lineId);
        }
        else {
          put += line;
        }
      }
    });

    logger.info('starting protocol...');
    _server.start();
  };

  construct();
  return {
  };
};

<|endoftext|>


<commit_before>var Embryo = require('./embryo')
var Extend = require('../plugins/extend')
var Attribute = require('../plugins/attribute')
var BeforeAfter = require('../plugins/before-after')

// Configure all Embryo plugins
var extendPlugin = new Extend()
extendPlugin.configure({
    nameType: '_type',
    typeDefault: 'Embryo',
    forceTyping: true,
    nameProperties: 'properties',
    deleteProperties: true
})

var attributePlugin = new Attribute()
attributePlugin.configure({
    getPrefix: 'get',
    setPrefix: 'set',
    camelize: true
})

var beforeAfterPlugin = new BeforeAfter()
beforeAfterPlugin.configure({
    plusPrefix: '+',
    moinsPrefix: '-',
    hiddenPrefix: '_bah_'
})

// Configure Embryo ;-)
Embryo.configure({
    cstrName: 'init',
    forceCstr: true,
    nameBlacklist: '_blacklist',
    deleteBlacklist: true
})
Embryo.use( extendPlugin, false )
Embryo.use( attributePlugin, true )
Embryo.use( beforeAfterPlugin, true )

module.exports = Embryo
<commit_msg>Update main.js<commit_after>var Embryo = require('./embryo')
var Extend = require('../plugins/extend')
var Attribute = require('../plugins/attribute')
var BeforeAfter = require('../plugins/before-after')

// Configure all Embryo plugins
var extendPlugin = new Extend()
extendPlugin.configure({
    nameType: '_type',
    typeDefault: 'Embryo',
    forceTyping: true,
    nameProperties: 'properties',
    deleteProperties: true
})

var attributePlugin = new Attribute()
attributePlugin.configure({
    getPrefix: 'get',
    setPrefix: 'set',
    camelize: true
})

var beforeAfterPlugin = new BeforeAfter()
beforeAfterPlugin.configure({
    plusPrefix: '+',
    moinsPrefix: '-',
    hiddenPrefix: '_bah_'
})

// Configure Embryo ;-)
Embryo.configure({
    cstrName: 'init',
    forceCstr: true,
    nameBlacklist: '_blacklist',
    deleteBlacklist: true
})
Embryo.use( extendPlugin, false )
Embryo.use( attributePlugin, false )
Embryo.use( beforeAfterPlugin, false )

module.exports = Embryo
<|endoftext|>


<commit_before>// TODO
// ??? refactor? check the outer usage of data provider.
// merge with defaultDimValueGetter?

import {__DEV__} from '../../config';
import {isTypedArray, extend, assert, each, isObject, isArray} from 'zrender/src/core/util';
import {getDataItemValue, isDataItemOption} from '../../util/model';
import {parseDate} from '../../util/number';
import Source from '../Source';
import {
    SOURCE_FORMAT_TYPED_ARRAY,
    SOURCE_FORMAT_ARRAY_ROWS,
    SOURCE_FORMAT_ORIGINAL,
    SOURCE_FORMAT_OBJECT_ROWS
} from './sourceHelper';

/**
 * If normal array used, mutable chunk size is supported.
 * If typed array used, chunk size must be fixed.
 */
export function DefaultDataProvider(source, dimSize) {
    if (!(source instanceof Source)) {
        source = Source.seriesDataToSource(source);
    }
    this._source = source;

    var data = this._data = source.data;
    var sourceFormat = source.sourceFormat;

    // Typed array. TODO IE10+?
    if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
        if (__DEV__) {
            if (dimSize == null) {
                throw new Error('Typed array data must specify dimension size');
            }
        }
        this._offset = 0;
        this._dimSize = dimSize;
        this._data = data;
    }

    var methods = providerMethods[
        sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
        ? sourceFormat + '_' + source.seriesLayoutBy
        : sourceFormat
    ];

    if (__DEV__) {
        assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
    }

    extend(this, methods);
}

var providerProto = DefaultDataProvider.prototype;
// If data is pure without style configuration
providerProto.pure = false;
// If data is persistent and will not be released after use.
providerProto.persistent = true;

// ???! FIXME legacy data provider do not has method getSource
providerProto.getSource = function () {
    return this._source;
};

var providerMethods = {

    'arrayRows_column': {
        pure: true,
        count: function () {
            return Math.max(0, this._data.length - this._source.startIndex);
        },
        getItem: function (idx) {
            return this._data[idx + this._source.startIndex];
        },
        appendData: appendDataSimply
    },

    'arrayRows_row': {
        pure: true,
        count: function () {
            var row = this._data[0];
            return row ? Math.max(0, row.length - this._source.startIndex) : 0;
        },
        getItem: function (idx) {
            idx += this._source.startIndex;
            var item = [];
            var data = this._data;
            for (var i = 0; i < data.length; i++) {
                var row = data[i];
                item.push(row ? row[idx] : null);
            }
            return item;
        },
        appendData: function () {
            throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
        }
    },

    'objectRows': {
        pure: true,
        count: countSimply,
        getItem: getItemSimply,
        appendData: appendDataSimply
    },

    'keyedColumns': {
        pure: true,
        count: function () {
            var dimName = this._source.dimensionsDefine[0];
            var col = this._data[dimName];
            return col ? col.length : 0;
        },
        getItem: function (idx) {
            var item = [];
            var dims = this._source.dimensionsDefine;
            for (var i = 0; i < dims.length; i++) {
                var col = this._data[dims[i]];
                item.push(col ? col[idx] : null);
            }
        },
        appendData: function (newData) {
            var data = this._data;
            each(newData, function (newCol, key) {
                var oldCol = data[key] || (data[key] = []);
                for (var i = 0; i < (newCol || []).length; i++) {
                    oldCol.push(newCol[i]);
                }
            });
        }
    },

    'original': {
        count: countSimply,
        getItem: getItemSimply,
        appendData: appendDataSimply
    },

    'typedArray': {
        persistent: false,
        pure: true,
        count: function () {
            return this._data ? (this._data.length / this._dimSize) : 0;
        },
        getItem: function (idx) {
            idx = idx - this._offset;
            var item = [];
            var offset = this._dimSize * idx;
            for (var i = 0; i < this._dimSize; i++) {
                item[i] = this._data[offset + i];
            }
            return item;
        },
        appendData: function (newData) {
            if (__DEV__) {
                assert(
                    isTypedArray(newData),
                    'Added data must be TypedArray if data in initialization is TypedArray'
                );
            }

            this._data = newData;
        },

        // Clean self if data is already used.
        clean: function () {
            // PENDING
            this._offset += this.count();
            this._data = null;
        }
    }
};

function countSimply() {
    return this._data.length;
}
function getItemSimply(idx) {
    return this._data[idx];
}
function appendDataSimply(newData) {
    for (var i = 0; i < newData.length; i++) {
        this._data.push(newData[i]);
    }
}

export var defaultDimValueGetters = {

    arrayRows: getDimValueSimply,

    objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
        return dataItem[dimName];
    },

    keyedColumns: getDimValueSimply,

    original: function (dataItem, dimName, dataIndex, dimIndex) {
        var value = getDataItemValue(dataItem);
        // If any dataItem is like { value: 10 }
        if (!this._rawData.pure && isDataItemOption(dataItem)) {
            this.hasItemOption = true;
        }
        return converDataValue(
            (value instanceof Array)
                ? value[dimIndex]
                // If value is a single number or something else not array.
                : value,
            this._dimensionInfos[dimName]
        );
    },

    typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
        return dataItem[dimIndex];
    }

};

function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
    return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
}

/**
 * This helper method convert value in data.
 * @param {string|number|Date} value
 * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
 *        If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
 */
function converDataValue(value, dimInfo) {
    // Performance sensitive.
    var dimType = dimInfo && dimInfo.type;
    if (dimType === 'ordinal') {
        // If given value is a category string
        var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
        return !ordinalMeta
            ? value
            : typeof value === 'string'
            ? ordinalMeta.parseAndCollect(value)
            : NaN;
    }

    if (dimType === 'time'
        // spead up when using timestamp
        && typeof value !== 'number'
        && value != null
        && value !== '-'
    ) {
        value = +parseDate(value);
    }

    // dimType defaults 'number'.
    // If dimType is not ordinal and value is null or undefined or NaN or '-',
    // parse to NaN.
    return (value == null || value === '')
        ? NaN : +value; // If string (like '-'), using '+' parse to NaN
}

// ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
// Consider persistent.
/**
 * @return {Array.<number>|number} can be null/undefined.
 */
export function getRawValueForModel(model, dataIndex, dataType) {
    var data = model.getData(dataType);
    // Consider data may be not persistent.
    var dataItem = data.getRawDataItem(dataIndex);
    var sourceFormat = data.getProvider().getSource().sourceFormat;
    if (dataItem == null) {
        return;
    }
    if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
        return (isObject(dataItem) && !isArray(dataItem))
            ? dataItem.value : dataItem;
    }
    else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
        var item = [];
        var dims = data.dimensions;
        for (var i = 0; i < dims.length; i++) {
            item.push(dataItem[dims[i]]);
        }
        return item;
    }
    else {
        return dataItem;
    }
}
<commit_msg>Fix convert value in data init.<commit_after>// TODO
// ??? refactor? check the outer usage of data provider.
// merge with defaultDimValueGetter?

import {__DEV__} from '../../config';
import {isTypedArray, extend, assert, each, isObject, isArray} from 'zrender/src/core/util';
import {getDataItemValue, isDataItemOption} from '../../util/model';
import {parseDate} from '../../util/number';
import Source from '../Source';
import {
    SOURCE_FORMAT_TYPED_ARRAY,
    SOURCE_FORMAT_ARRAY_ROWS,
    SOURCE_FORMAT_ORIGINAL,
    SOURCE_FORMAT_OBJECT_ROWS
} from './sourceHelper';

/**
 * If normal array used, mutable chunk size is supported.
 * If typed array used, chunk size must be fixed.
 */
export function DefaultDataProvider(source, dimSize) {
    if (!(source instanceof Source)) {
        source = Source.seriesDataToSource(source);
    }
    this._source = source;

    var data = this._data = source.data;
    var sourceFormat = source.sourceFormat;

    // Typed array. TODO IE10+?
    if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
        if (__DEV__) {
            if (dimSize == null) {
                throw new Error('Typed array data must specify dimension size');
            }
        }
        this._offset = 0;
        this._dimSize = dimSize;
        this._data = data;
    }

    var methods = providerMethods[
        sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
        ? sourceFormat + '_' + source.seriesLayoutBy
        : sourceFormat
    ];

    if (__DEV__) {
        assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
    }

    extend(this, methods);
}

var providerProto = DefaultDataProvider.prototype;
// If data is pure without style configuration
providerProto.pure = false;
// If data is persistent and will not be released after use.
providerProto.persistent = true;

// ???! FIXME legacy data provider do not has method getSource
providerProto.getSource = function () {
    return this._source;
};

var providerMethods = {

    'arrayRows_column': {
        pure: true,
        count: function () {
            return Math.max(0, this._data.length - this._source.startIndex);
        },
        getItem: function (idx) {
            return this._data[idx + this._source.startIndex];
        },
        appendData: appendDataSimply
    },

    'arrayRows_row': {
        pure: true,
        count: function () {
            var row = this._data[0];
            return row ? Math.max(0, row.length - this._source.startIndex) : 0;
        },
        getItem: function (idx) {
            idx += this._source.startIndex;
            var item = [];
            var data = this._data;
            for (var i = 0; i < data.length; i++) {
                var row = data[i];
                item.push(row ? row[idx] : null);
            }
            return item;
        },
        appendData: function () {
            throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
        }
    },

    'objectRows': {
        pure: true,
        count: countSimply,
        getItem: getItemSimply,
        appendData: appendDataSimply
    },

    'keyedColumns': {
        pure: true,
        count: function () {
            var dimName = this._source.dimensionsDefine[0];
            var col = this._data[dimName];
            return col ? col.length : 0;
        },
        getItem: function (idx) {
            var item = [];
            var dims = this._source.dimensionsDefine;
            for (var i = 0; i < dims.length; i++) {
                var col = this._data[dims[i]];
                item.push(col ? col[idx] : null);
            }
        },
        appendData: function (newData) {
            var data = this._data;
            each(newData, function (newCol, key) {
                var oldCol = data[key] || (data[key] = []);
                for (var i = 0; i < (newCol || []).length; i++) {
                    oldCol.push(newCol[i]);
                }
            });
        }
    },

    'original': {
        count: countSimply,
        getItem: getItemSimply,
        appendData: appendDataSimply
    },

    'typedArray': {
        persistent: false,
        pure: true,
        count: function () {
            return this._data ? (this._data.length / this._dimSize) : 0;
        },
        getItem: function (idx) {
            idx = idx - this._offset;
            var item = [];
            var offset = this._dimSize * idx;
            for (var i = 0; i < this._dimSize; i++) {
                item[i] = this._data[offset + i];
            }
            return item;
        },
        appendData: function (newData) {
            if (__DEV__) {
                assert(
                    isTypedArray(newData),
                    'Added data must be TypedArray if data in initialization is TypedArray'
                );
            }

            this._data = newData;
        },

        // Clean self if data is already used.
        clean: function () {
            // PENDING
            this._offset += this.count();
            this._data = null;
        }
    }
};

function countSimply() {
    return this._data.length;
}
function getItemSimply(idx) {
    return this._data[idx];
}
function appendDataSimply(newData) {
    for (var i = 0; i < newData.length; i++) {
        this._data.push(newData[i]);
    }
}

export var defaultDimValueGetters = {

    arrayRows: getDimValueSimply,

    objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
        return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
    },

    keyedColumns: getDimValueSimply,

    original: function (dataItem, dimName, dataIndex, dimIndex) {
        var value = getDataItemValue(dataItem);
        // If any dataItem is like { value: 10 }
        if (!this._rawData.pure && isDataItemOption(dataItem)) {
            this.hasItemOption = true;
        }
        return converDataValue(
            (value instanceof Array)
                ? value[dimIndex]
                // If value is a single number or something else not array.
                : value,
            this._dimensionInfos[dimName]
        );
    },

    typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
        return dataItem[dimIndex];
    }

};

function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
    return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
}

/**
 * This helper method convert value in data.
 * @param {string|number|Date} value
 * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
 *        If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
 */
function converDataValue(value, dimInfo) {
    // Performance sensitive.
    var dimType = dimInfo && dimInfo.type;
    if (dimType === 'ordinal') {
        // If given value is a category string
        var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
        return !ordinalMeta
            ? value
            : typeof value === 'string'
            ? ordinalMeta.parseAndCollect(value)
            : value;
    }

    if (dimType === 'time'
        // spead up when using timestamp
        && typeof value !== 'number'
        && value != null
        && value !== '-'
    ) {
        value = +parseDate(value);
    }

    // dimType defaults 'number'.
    // If dimType is not ordinal and value is null or undefined or NaN or '-',
    // parse to NaN.
    return (value == null || value === '')
        ? NaN : +value; // If string (like '-'), using '+' parse to NaN
}

// ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
// Consider persistent.
/**
 * @return {Array.<number>|number} can be null/undefined.
 */
export function getRawValueForModel(model, dataIndex, dataType) {
    var data = model.getData(dataType);
    // Consider data may be not persistent.
    var dataItem = data.getRawDataItem(dataIndex);
    var sourceFormat = data.getProvider().getSource().sourceFormat;
    if (dataItem == null) {
        return;
    }
    if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
        return (isObject(dataItem) && !isArray(dataItem))
            ? dataItem.value : dataItem;
    }
    else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
        var item = [];
        var dims = data.dimensions;
        for (var i = 0; i < dims.length; i++) {
            item.push(dataItem[dims[i]]);
        }
        return item;
    }
    else {
        return dataItem;
    }
}
<|endoftext|>


<commit_before>var structureTower {

	run: function(tower) {

		var closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
		var repairTargets = tower.pos.findInRange(FIND_STRUCTURES, 30, {
			filter: function(structure) {
				if ((structure.structureType == STRUCTURE_WALL) ||
						(structure.structureType == STRUCTURE_RAMPART)) {
					return (structure.hits < structure.hitsMax);
				}
			}
		});

		if (closestHostile) {
			tower.attack(closestHostile);
		}
		if (repairTargets.length) {
			repairTargets.sort(function(a,b) {
				return (a.hits - b.hits);
			});

			tower.repair(repairTargets[0]);
		}

	} // function

}; // structureTower

module.exports = structureTower;<commit_msg>Fix typo<commit_after>var structureTower = {

	run: function(tower) {

		var closestHostile = tower.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
		var repairTargets = tower.pos.findInRange(FIND_STRUCTURES, 30, {
			filter: function(structure) {
				if ((structure.structureType == STRUCTURE_WALL) ||
						(structure.structureType == STRUCTURE_RAMPART)) {
					return (structure.hits < structure.hitsMax);
				}
			}
		});

		if (closestHostile) {
			tower.attack(closestHostile);
		}
		if (repairTargets.length) {
			repairTargets.sort(function(a,b) {
				return (a.hits - b.hits);
			});

			tower.repair(repairTargets[0]);
		}

	} // function

}; // structureTower

module.exports = structureTower;<|endoftext|>


<commit_before>export default {
  API_ROOT: 'http://192.168.3.239:3001'
};
<commit_msg>Production: assume backend runs on same host as admin frontend<commit_after>export default {
  API_ROOT: window.location.protocol + '//' + window.location.hostname + ':3001'
};
<|endoftext|>


<commit_before>const windowUtils = require('window-utils');
const events = require("sdk/system/events");
const {Cc, Ci, Cu} = require('chrome');
const clipboard = require('sdk/clipboard');
const prefs = require('simple-prefs').prefs;
const contextMenu = require('sdk/context-menu');
const {Class} = require('sdk/core/heritage');
const {Unknown, Service} = require('sdk/platform/xpcom');
const {Request} = require('request');
const data = require('self').data;

var NetUtil = {};
Cu.import('resource://gre/modules/NetUtil.jsm', NetUtil);
NetUtil = NetUtil.NetUtil;

var recentChannels = [];

function escapeShellArg(arg) {
  let ret = '';

  if (prefs['use_double_quotes']) {
    ret = arg.replace(/["\\]/g, function (m, i, s) {
      return '\\' + m.slice(0, 1);
    });
    return '"' + ret + '"';
  }

  ret = arg.replace(/'/g, function (m, i, s) {
    return "'\\" + m.slice(0, 1) + "'";
  });
  return "'" + ret + "'";
}

function getDownloadCommands(httpChannel, filename) {
  let headerVisitor = {
    headers: [],
    visitHeader: function(aHeader, aValue) {
      this.headers.push(aHeader + ': ' + aValue);
    }
  };

  httpChannel.visitRequestHeaders(headerVisitor);

  let uri = httpChannel.URI.spec;
  let requestMethod = httpChannel.requestMethod;
  let payload = null;

  let inputStream = httpChannel.QueryInterface(Ci.nsIUploadChannel).uploadStream;
  if (inputStream) {
    let streamPos = inputStream.tell()
    inputStream.seek(0, 0);
    let body = NetUtil.readInputStreamToString(inputStream, inputStream.available(), {});
    let i = body.indexOf("\r\n\r\n");
    payload = body.substring(i+4);
    let bodyHeader = body.substring(0, i);
    if (bodyHeader.indexOf('application/x-www-form-urlencoded') == -1)
      return {}; // can't include binary data in command

    let bodyHeaders = bodyHeader.split("\r\n");

    for (h in bodyHeaders) {
      headerVisitor.headers.push(bodyHeaders[h]);
    }
    inputStream.seek(0, streamPos); // back to its original position
  }

  let ret = {};

  // Generating wget command
  if (prefs['wget'] && ((requestMethod == 'GET' && !payload) || (requestMethod == 'POST' && payload))) {
    ret.wget = 'wget';

    for (let i in headerVisitor.headers) {
      let h = headerVisitor.headers[i];
      if (h.substring(0, 15).toLowerCase() == 'accept-encoding' && prefs['remove_accept_encoding'])
        continue;
      ret.wget += ' --header=' + escapeShellArg(h);
    }

    if (payload)
      ret.wget += ' --post-data ' + escapeShellArg(payload);

    ret.wget += ' ' + escapeShellArg(uri);

    if (filename)
      ret.wget += ' -O ' + escapeShellArg(filename);

    let wgetOptions = prefs['wget.options'];
    if (wgetOptions)
      ret.wget += ' ' + wgetOptions;
  }

  // Generating curl command
  if (prefs['curl']) {
    ret.curl = 'curl';

    for (let i in headerVisitor.headers) {
      let h = headerVisitor.headers[i];
      if (h.substring(0, 15).toLowerCase() == 'accept-encoding' && prefs['remove_accept_encoding'])
        continue;
      ret.curl += ' --header ' + escapeShellArg(h);
    }

    if (requestMethod != 'GET' || payload)
      ret.curl += ' -X ' + requestMethod;

    if (payload)
      ret.curl += ' --data-binary ' + escapeShellArg(payload);

    ret.curl += ' ' + escapeShellArg(uri);

    if (filename)
      ret.curl += ' -o ' + escapeShellArg(filename);
    else
      ret.curl += ' -O -J';

    let curlOptions = prefs['curl.options'];
    if (curlOptions)
      ret.curl += ' ' + curlOptions;
  }

  // Generating aria2 command
  if (prefs['aria2'] && (requestMethod == 'GET' && !payload)) {
    ret.aria2 = 'aria2c';

    for (let i in headerVisitor.headers) {
      let h = headerVisitor.headers[i];
      if (h.substring(0, 15).toLowerCase() == 'accept-encoding' && prefs['remove_accept_encoding'])
        continue;
      ret.aria2 += ' --header ' + escapeShellArg(h);
    }

    if (filename)
      ret.aria2 += ' --out ' + escapeShellArg(filename);

    ret.aria2 += ' ' + escapeShellArg(uri);

    let aria2Options = prefs['aria2.options'];
    if (aria2Options)
      ret.aria2 += ' ' + aria2Options;
  }

  return ret;
}

function createDownloadElement(window, cmdtype, cmd) {
  let vbox = window.document.createElement('vbox');
  let label = window.document.createElement('label');
  label.setAttribute('value', 'Download with ' + cmdtype);
  vbox.appendChild(label);

  let hbox = window.document.createElement('hbox');
  vbox.appendChild(hbox);

  let textbox = window.document.createElement('textbox');
  hbox.appendChild(textbox);
  textbox.setAttribute('flex', 1);
  textbox.setAttribute('readonly', 'true');
  textbox.setAttribute('clickSelectsAll', 'true');
  textbox.setAttribute('value', cmd);

  let button = window.document.createElement('button');
  hbox.appendChild(button);
  button.setAttribute('label', 'Copy');
  button.onclick = function () {
    clipboard.set(cmd);
    window.close();
  }

  return vbox;
}

function copyCommandForUri(uri, type) {
  function listener(event) {
    if (event.subject.QueryInterface(Ci.nsIChannel).originalURI.spec == uri) {
      let cmd = getDownloadCommands(event.subject.QueryInterface(Ci.nsIHttpChannel), null);
      clipboard.set(cmd[type]);

      event.subject.QueryInterface(Ci.nsIRequest).cancel(0);
      events.off('http-on-modify-request', listener);
    }
  };

  events.on('http-on-modify-request', listener);

  Request({url: uri}).get();
}

// This is an active module of the cliget Add-on
exports.main = function() {
  contextMenu.Menu({
    label: 'cliget',
    contentScriptFile: data.url('context-menu.js'),
    items: [],
    onMessage: function (arg) {
      if (typeof arg == 'string') {
        arg = JSON.parse(arg);
        copyCommandForUri(arg.uri, arg.type);
      }
      else {
        menuItems = [];
        for (var t in arg) {
          if (prefs['curl'])
            menuItems.push(contextMenu.Item({
              label: 'Copy curl for ' + t,
              data: JSON.stringify({uri: arg[t], type: 'curl'})
            }));
          if (prefs['wget'])
            menuItems.push(contextMenu.Item({
              label: 'Copy wget for ' + t,
              data: JSON.stringify({uri: arg[t], type: 'wget'})
            }));
          if (prefs['aria2'])
            menuItems.push(contextMenu.Item({
              label: 'Copy aria2 for ' + t,
              data: JSON.stringify({uri: arg[t], type: 'aria2'})
            }));
        }
        this.items = menuItems;
      }
    }
  });

  windowUtils = new windowUtils.WindowTracker({
    onTrack: function (window) {
      if ('chrome://mozapps/content/downloads/unknownContentType.xul' != window.location)
        return;

      let parent = window.document.getElementById('unknownContentType');
      if (!parent)
        return;

      // find channel
      let channel = null;
      for (let i = 0; i < recentChannels.length; ++ i) {
        if (recentChannels[i].URI.equals(window.dialog.mLauncher.source)) {
          channel = recentChannels[i];
          recentChannels.splice(i, 1);
        }
      }
      if (!channel)
        return;

      let filename = window.dialog.mLauncher.suggestedFileName;
      let cmd = getDownloadCommands(channel, filename);

      if (cmd.curl) {
        let el = window.document.createElement('vbox');
        el.appendChild(createDownloadElement(window, 'cURL', cmd.curl));
        parent.appendChild(el);
      }

      if (cmd.wget) {
        let el = window.document.createElement('vbox');
        el.appendChild(createDownloadElement(window, 'Wget', cmd.wget));
        parent.appendChild(el);
      }

      if (cmd.aria2) {
        let el = window.document.createElement('vbox');
        el.appendChild(createDownloadElement(window, 'aria2', cmd.aria2));
        parent.appendChild(el);
      }
    }
  });
};

var contractId = '@mozilla.org/uriloader/external-helper-app-service;1';

// Implement a wrapper around external helper app service
var DownloadHelper = Class({
  extends: Unknown,
  get wrappedJSObject() this,

  originalService: Cc[contractId].getService(),

  QueryInterface: function(interface) {
    var srv = this.originalService.QueryInterface(interface);
    for (let i in srv)
      if (!(i in this))
        this[i] = function() {
          return srv[i].apply(srv, arguments);
        };
    return this;
  },

  doContent: function(aMimeContentType, aRequest, aWindowContext, aForceSave) {
    if (aRequest instanceof Ci.nsIHttpChannel)
      recentChannels.push(aRequest.QueryInterface(Ci.nsIHttpChannel));

    if (recentChannels.length >= 10)
      recentChannels.splice(0, recentChannels.length - 10);
    return this.originalService.QueryInterface(Ci.nsIExternalHelperAppService)
      .doContent(aMimeContentType, aRequest, aWindowContext, aForceSave);
  }
});

// Register the service using the contract ID
var service = Service({
  contract: contractId,
  Component: DownloadHelper
});
<commit_msg>Fixed const variable assignement error. Closes #12.<commit_after>const windowUtils = require('window-utils');
const events = require("sdk/system/events");
const {Cc, Ci, Cu} = require('chrome');
const clipboard = require('sdk/clipboard');
const prefs = require('simple-prefs').prefs;
const contextMenu = require('sdk/context-menu');
const {Class} = require('sdk/core/heritage');
const {Unknown, Service} = require('sdk/platform/xpcom');
const {Request} = require('request');
const data = require('self').data;

var NetUtil = {};
Cu.import('resource://gre/modules/NetUtil.jsm', NetUtil);
NetUtil = NetUtil.NetUtil;

var recentChannels = [];

function escapeShellArg(arg) {
  let ret = '';

  if (prefs['use_double_quotes']) {
    ret = arg.replace(/["\\]/g, function (m, i, s) {
      return '\\' + m.slice(0, 1);
    });
    return '"' + ret + '"';
  }

  ret = arg.replace(/'/g, function (m, i, s) {
    return "'\\" + m.slice(0, 1) + "'";
  });
  return "'" + ret + "'";
}

function getDownloadCommands(httpChannel, filename) {
  let headerVisitor = {
    headers: [],
    visitHeader: function(aHeader, aValue) {
      this.headers.push(aHeader + ': ' + aValue);
    }
  };

  httpChannel.visitRequestHeaders(headerVisitor);

  let uri = httpChannel.URI.spec;
  let requestMethod = httpChannel.requestMethod;
  let payload = null;

  let inputStream = httpChannel.QueryInterface(Ci.nsIUploadChannel).uploadStream;
  if (inputStream) {
    let streamPos = inputStream.tell()
    inputStream.seek(0, 0);
    let body = NetUtil.readInputStreamToString(inputStream, inputStream.available(), {});
    let i = body.indexOf("\r\n\r\n");
    payload = body.substring(i+4);
    let bodyHeader = body.substring(0, i);
    if (bodyHeader.indexOf('application/x-www-form-urlencoded') == -1)
      return {}; // can't include binary data in command

    let bodyHeaders = bodyHeader.split("\r\n");

    for (h in bodyHeaders) {
      headerVisitor.headers.push(bodyHeaders[h]);
    }
    inputStream.seek(0, streamPos); // back to its original position
  }

  let ret = {};

  // Generating wget command
  if (prefs['wget'] && ((requestMethod == 'GET' && !payload) || (requestMethod == 'POST' && payload))) {
    ret.wget = 'wget';

    for (let i in headerVisitor.headers) {
      let h = headerVisitor.headers[i];
      if (h.substring(0, 15).toLowerCase() == 'accept-encoding' && prefs['remove_accept_encoding'])
        continue;
      ret.wget += ' --header=' + escapeShellArg(h);
    }

    if (payload)
      ret.wget += ' --post-data ' + escapeShellArg(payload);

    ret.wget += ' ' + escapeShellArg(uri);

    if (filename)
      ret.wget += ' -O ' + escapeShellArg(filename);

    let wgetOptions = prefs['wget.options'];
    if (wgetOptions)
      ret.wget += ' ' + wgetOptions;
  }

  // Generating curl command
  if (prefs['curl']) {
    ret.curl = 'curl';

    for (let i in headerVisitor.headers) {
      let h = headerVisitor.headers[i];
      if (h.substring(0, 15).toLowerCase() == 'accept-encoding' && prefs['remove_accept_encoding'])
        continue;
      ret.curl += ' --header ' + escapeShellArg(h);
    }

    if (requestMethod != 'GET' || payload)
      ret.curl += ' -X ' + requestMethod;

    if (payload)
      ret.curl += ' --data-binary ' + escapeShellArg(payload);

    ret.curl += ' ' + escapeShellArg(uri);

    if (filename)
      ret.curl += ' -o ' + escapeShellArg(filename);
    else
      ret.curl += ' -O -J';

    let curlOptions = prefs['curl.options'];
    if (curlOptions)
      ret.curl += ' ' + curlOptions;
  }

  // Generating aria2 command
  if (prefs['aria2'] && (requestMethod == 'GET' && !payload)) {
    ret.aria2 = 'aria2c';

    for (let i in headerVisitor.headers) {
      let h = headerVisitor.headers[i];
      if (h.substring(0, 15).toLowerCase() == 'accept-encoding' && prefs['remove_accept_encoding'])
        continue;
      ret.aria2 += ' --header ' + escapeShellArg(h);
    }

    if (filename)
      ret.aria2 += ' --out ' + escapeShellArg(filename);

    ret.aria2 += ' ' + escapeShellArg(uri);

    let aria2Options = prefs['aria2.options'];
    if (aria2Options)
      ret.aria2 += ' ' + aria2Options;
  }

  return ret;
}

function createDownloadElement(window, cmdtype, cmd) {
  let vbox = window.document.createElement('vbox');
  let label = window.document.createElement('label');
  label.setAttribute('value', 'Download with ' + cmdtype);
  vbox.appendChild(label);

  let hbox = window.document.createElement('hbox');
  vbox.appendChild(hbox);

  let textbox = window.document.createElement('textbox');
  hbox.appendChild(textbox);
  textbox.setAttribute('flex', 1);
  textbox.setAttribute('readonly', 'true');
  textbox.setAttribute('clickSelectsAll', 'true');
  textbox.setAttribute('value', cmd);

  let button = window.document.createElement('button');
  hbox.appendChild(button);
  button.setAttribute('label', 'Copy');
  button.onclick = function () {
    clipboard.set(cmd);
    window.close();
  }

  return vbox;
}

function copyCommandForUri(uri, type) {
  function listener(event) {
    if (event.subject.QueryInterface(Ci.nsIChannel).originalURI.spec == uri) {
      let cmd = getDownloadCommands(event.subject.QueryInterface(Ci.nsIHttpChannel), null);
      clipboard.set(cmd[type]);

      event.subject.QueryInterface(Ci.nsIRequest).cancel(0);
      events.off('http-on-modify-request', listener);
    }
  };

  events.on('http-on-modify-request', listener);

  Request({url: uri}).get();
}

// This is an active module of the cliget Add-on
exports.main = function() {
  contextMenu.Menu({
    label: 'cliget',
    contentScriptFile: data.url('context-menu.js'),
    items: [],
    onMessage: function (arg) {
      if (typeof arg == 'string') {
        arg = JSON.parse(arg);
        copyCommandForUri(arg.uri, arg.type);
      }
      else {
        menuItems = [];
        for (var t in arg) {
          if (prefs['curl'])
            menuItems.push(contextMenu.Item({
              label: 'Copy curl for ' + t,
              data: JSON.stringify({uri: arg[t], type: 'curl'})
            }));
          if (prefs['wget'])
            menuItems.push(contextMenu.Item({
              label: 'Copy wget for ' + t,
              data: JSON.stringify({uri: arg[t], type: 'wget'})
            }));
          if (prefs['aria2'])
            menuItems.push(contextMenu.Item({
              label: 'Copy aria2 for ' + t,
              data: JSON.stringify({uri: arg[t], type: 'aria2'})
            }));
        }
        this.items = menuItems;
      }
    }
  });

  windowTracker = new windowUtils.WindowTracker({
    onTrack: function (window) {
      if ('chrome://mozapps/content/downloads/unknownContentType.xul' != window.location)
        return;

      let parent = window.document.getElementById('unknownContentType');
      if (!parent)
        return;

      // find channel
      let channel = null;
      for (let i = 0; i < recentChannels.length; ++ i) {
        if (recentChannels[i].URI.equals(window.dialog.mLauncher.source)) {
          channel = recentChannels[i];
          recentChannels.splice(i, 1);
        }
      }
      if (!channel)
        return;

      let filename = window.dialog.mLauncher.suggestedFileName;
      let cmd = getDownloadCommands(channel, filename);

      if (cmd.curl) {
        let el = window.document.createElement('vbox');
        el.appendChild(createDownloadElement(window, 'cURL', cmd.curl));
        parent.appendChild(el);
      }

      if (cmd.wget) {
        let el = window.document.createElement('vbox');
        el.appendChild(createDownloadElement(window, 'Wget', cmd.wget));
        parent.appendChild(el);
      }

      if (cmd.aria2) {
        let el = window.document.createElement('vbox');
        el.appendChild(createDownloadElement(window, 'aria2', cmd.aria2));
        parent.appendChild(el);
      }
    }
  });
};

var contractId = '@mozilla.org/uriloader/external-helper-app-service;1';

// Implement a wrapper around external helper app service
var DownloadHelper = Class({
  extends: Unknown,
  get wrappedJSObject() this,

  originalService: Cc[contractId].getService(),

  QueryInterface: function(interface) {
    var srv = this.originalService.QueryInterface(interface);
    for (let i in srv)
      if (!(i in this))
        this[i] = function() {
          return srv[i].apply(srv, arguments);
        };
    return this;
  },

  doContent: function(aMimeContentType, aRequest, aWindowContext, aForceSave) {
    if (aRequest instanceof Ci.nsIHttpChannel)
      recentChannels.push(aRequest.QueryInterface(Ci.nsIHttpChannel));

    if (recentChannels.length >= 10)
      recentChannels.splice(0, recentChannels.length - 10);
    return this.originalService.QueryInterface(Ci.nsIExternalHelperAppService)
      .doContent(aMimeContentType, aRequest, aWindowContext, aForceSave);
  }
});

// Register the service using the contract ID
var service = Service({
  contract: contractId,
  Component: DownloadHelper
});
<|endoftext|>


<commit_before>"use babel";

export default {
    config: {
        executable: {
            type: "string",
            default: "gfortran"
        },
        gfortran_flags: {
            type: "string",
            default: "-Wall -Wextra"
        },
    },

    activate: () => {
        require("atom-package-deps").install("linter-gfortran");
    },

    provideLinter: () => {
        const helpers = require("atom-linter");
        const path = require('path');
        const regex = ".+:(?<line>\\d+)[\.:](?<col>\\d+):((.|\\r|\\n)*?)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)";
        const tmpdir = require('tmp').dirSync().name;
        return {
            name: "gfortran",
            grammarScopes: [
                "source.fortran.free",
                "source.fortran.fixed",
                "source.fortran.modern",
                "source.fortran.punchcard"
            ],
            scope: "file",
            lintOnFly: true,
            lint: (activeEditor) => {
              const command = atom.config.get("linter-gfortran.executable");
              const fileContents = activeEditor.getText()
              const filePath = activeEditor.getPath();

              // Split the users flag string and append flags to specific syntax checking and temporary file directory.
              const args = atom.config
                .get("linter-gfortran.gfortran_flags")
                .split(" ")
                .concat(["-fsyntax-only", "-J", tmpdir]);

              // Execute gfortran on a temporary file in order for on-the-fly linter to work.
              return helpers.tempFile(path.basename(filePath), fileContents, (tmpFilename) => {
                args.push(tmpFilename);
                return helpers.exec(command, args, { stream: "stderr"}).then(output => {
                    return helpers.parse(output, regex, { filePath : filePath });
                    });
                });
          }
        };
    }
};
<commit_msg>Collumn number is optional in error message<commit_after>"use babel";

export default {
    config: {
        executable: {
            type: "string",
            default: "gfortran"
        },
        gfortran_flags: {
            type: "string",
            default: "-Wall -Wextra"
        },
    },

    activate: () => {
        require("atom-package-deps").install("linter-gfortran");
    },

    provideLinter: () => {
        const helpers = require("atom-linter");
        const path = require('path');
        const regex = ".+:(?<line>\\d+)([\.:](?<col>\\d+))?:((.|\\r|\\n)*?)(?<type>(Error|Warning|Note)):\\s*(?<message>.*)";
        const tmpdir = require('tmp').dirSync().name;
        return {
            name: "gfortran",
            grammarScopes: [
                "source.fortran.free",
                "source.fortran.fixed",
                "source.fortran.modern",
                "source.fortran.punchcard"
            ],
            scope: "file",
            lintOnFly: true,
            lint: (activeEditor) => {
              const command = atom.config.get("linter-gfortran.executable");
              const fileContents = activeEditor.getText()
              const filePath = activeEditor.getPath();

              // Split the users flag string and append flags to specific syntax checking and temporary file directory.
              const args = atom.config
                .get("linter-gfortran.gfortran_flags")
                .split(" ")
                .concat(["-fsyntax-only", "-J", tmpdir]);

              // Execute gfortran on a temporary file in order for on-the-fly linter to work.
              return helpers.tempFile(path.basename(filePath), fileContents, (tmpFilename) => {
                args.push(tmpFilename);
                return helpers.exec(command, args, { stream: "stderr"}).then(output => {
                    return helpers.parse(output, regex, { filePath : filePath });
                    });
                });
          }
        };
    }
};
<|endoftext|>


<commit_before>import nodeResolve from 'rollup-plugin-node-resolve';
import convertCJS from 'rollup-plugin-commonjs';

const packageInfo = require( '../../package.json' );

export default {
	entry: 'src/index.js',
	format: 'es',
	sourceMap: true,
	plugins: [
		nodeResolve( {
			jsnext: true,
			main: false
		} ),
		convertCJS()
	],
	banner: `/*! ${packageInfo.name} v${packageInfo.version} | (c) ${new Date().getFullYear()} ${packageInfo.author.name} | ${packageInfo.license} license (see LICENSE) */`,
	dest: `dist/${packageInfo.name}.js`
};
<commit_msg>[ci skip] Updated rollup configuration.<commit_after>import nodeResolve from 'rollup-plugin-node-resolve';
import convertCJS from 'rollup-plugin-commonjs';

const packageInfo = require( '../../package.json' );

export default {
	entry: 'src/index.js',
	format: 'es',
	external: [
		'bemquery-core'
	],
	globals: {
		'bemquery-core': 'bemquery'
	},
	sourceMap: true,
	plugins: [
		nodeResolve( {
			jsnext: true,
			main: false
		} ),
		convertCJS()
	],
	banner: `/*! ${packageInfo.name} v${packageInfo.version} | (c) ${new Date().getFullYear()} ${packageInfo.author.name} | ${packageInfo.license} license (see LICENSE) */`,
	dest: `dist/${packageInfo.name}.js`
};
<|endoftext|>


<commit_before>/*
  backgrid-text-cell
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  Licensed under the MIT @license.
*/

(function (window, $, _, Backbone, Backgrid)  {

  /**
     Renders a form with a text area and a save button in a modal dialog.

     @class Backgrid.Extension.TextareaEditor
     @extends Backgrid.CellEditor
   */
  var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({

    /** @property */
    tagName: "div",

    /** @property */
    className: "modal hide fade",

    /** @property {function(Object, ?Object=): string} template */
    template: _.template('<form>
<button type="button" class="close" data-dismiss="modal">×</button>
<%- column.get("label") %>

<textarea cols="<%= cols %>" rows="<%= rows %>"><%- content %></textarea>

<input class="btn" type="submit" value="Save"/>
</form>'),

    /** @property */
    cols: 80,

    /** @property */
    rows: 10,

    /** @property */
    events: {
      "submit": "save",
      "hide": "cancel",
      "hidden": "close"
    },

    /**
       @property {Object} modalOptions The options passed to Bootstrap's modal
       plugin.
    */
    modalOptions: {
      backdrop: false
    },

    /**
       Renders a modal form dialog with a textarea, submit button and a close button.
    */
    render: function () {
      this.$el.html($(this.template({
        column: this.column,
        cols: this.cols,
        rows: this.rows,
        content: this.formatter.fromRaw(this.model.get(this.column.get("name")))
      })));

      this.delegateEvents();

      this.$el.modal(this.modalOptions);

      return this;
    },

    /**
       Event handler. Saves the text in the text area to the model.

       Triggers a Backbone `backgrid:error` event along with the editor as the
       parameter if the value cannot be converted. Classes listening to the
       `backgrid:error` event, usually the Cell classes, should respond
       appropriately, usually by rendering some kind of error feedback.

       @param {Event} e
    */
    save: function (e) {
      if (e) e.preventDefault();

      var content = this.formatter.toRaw(this.$el.find("textarea").val());

      if (_.isUndefined(content) ||
          !this.model.set(this.column.get("name"), content, {validate: true})) {
        this.trigger("backgrid:error", this);
      }
      else {
        this.$el.modal("hide");
      }
    },

    /**
       Event handler. Revert the text in the model after asking for confirmation
       if dirty, otherwise just close the editor.

       @param {Event} e
    */
    cancel: function (e) {

      var content = this.formatter.toRaw(this.$el.find("textarea").val());

      // Dirty
      if (content !== this.model.get(this.column.get("name")).replace(/\r/g, '') &&
          window.confirm("Would you like to save your changes?")) {
        e.preventDefault();
        e.stopPropagation();
        return this.save();
      }
    },

    /**
       Triggers a `backgrid:done` event along with the cell editor as the
       parameter after the modal is hidden.
     */
    close: function () {
      this.trigger("backgrid:done", this);
    }

  });

  /**
     TextCell is a string cell type that renders a form with a text area in a
     modal dialog instead of an input box editor. It is best suited for entering
     a large body of text.

     @class Backgrid.Extension.TextCell
     @extends Backgrid.StringCell
  */
  var TextCell = Backgrid.Extension.TextCell = Backgrid.StringCell.extend({

    /** @property */
    className: "text-cell",

    /** @property  */
    editor: TextareaEditor

  });

}(window, jQuery, _, Backbone, Backgrid));
<commit_msg>Fix text cell keybaord nav bindings and focuses the text area when modal is shown<commit_after>/*
  backgrid-text-cell
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  Licensed under the MIT @license.
*/

(function (window, $, _, Backbone, Backgrid)  {

  /**
     Renders a form with a text area and a save button in a modal dialog.

     @class Backgrid.Extension.TextareaEditor
     @extends Backgrid.CellEditor
  */
  var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({

    /** @property */
    tagName: "div",

    /** @property */
    className: "modal hide fade",

    /** @property {function(Object, ?Object=): string} template */
    template: _.template('<form>
<button type="button" class="close" data-dismiss="modal">×</button>
<%- column.get("label") %>

<textarea cols="<%= cols %>" rows="<%= rows %>"><%- content %></textarea>

<input class="btn" type="submit" value="Save"/>
</form>'),

    /** @property */
    cols: 80,

    /** @property */
    rows: 10,

    /** @property */
    events: {
      "submit": "save",
      "hide": "cancel",
      "hidden": "close",
      "shown": "focus"
    },

    /**
       @property {Object} modalOptions The options passed to Bootstrap's modal
       plugin.
    */
    modalOptions: {
      backdrop: false
    },

    /**
       Renders a modal form dialog with a textarea, submit button and a close button.
    */
    render: function () {
      this.$el.html($(this.template({
        column: this.column,
        cols: this.cols,
        rows: this.rows,
        content: this.formatter.fromRaw(this.model.get(this.column.get("name")))
      })));

      this.delegateEvents();

      this.$el.modal(this.modalOptions);

      return this;
    },

    /**
       Event handler. Saves the text in the text area to the model.

       Triggers a Backbone `backgrid:error` event along with the editor as the
       parameter if the value cannot be converted. Classes listening to the
       `backgrid:error` event, usually the Cell classes, should respond
       appropriately, usually by rendering some kind of error feedback.

       @param {Event} e
    */
    save: function (e) {
      if (e) e.preventDefault();

      var content = this.formatter.toRaw(this.$el.find("textarea").val());

      if (_.isUndefined(content) ||
          !this.model.set(this.column.get("name"), content, {validate: true})) {
        this.trigger("backgrid:error", this);
      }
      else {
        this.$el.modal("hide");
      }
    },

    /**
       Event handler. Revert the text in the model after asking for confirmation
       if dirty, otherwise just close the editor.

       @param {Event} e
    */
    cancel: function (e) {

      var content = this.formatter.toRaw(this.$el.find("textarea").val());

      // Dirty
      if (content !== this.model.get(this.column.get("name")).replace(/\r/g, '') &&
          window.confirm("Would you like to save your changes?")) {
        e.preventDefault();
        e.stopPropagation();
        return this.save();
      }
    },

    /**
       Triggers a `backgrid:done` event along with the cell editor as the
       parameter after the modal is hidden.

       @param {Event} e
    */
    close: function (e) {
      this.trigger("backgrid:done", this, Backgrid.Cell.buildKeyMods(e));
    },

    /**
       Focuses the textarea when the modal is shown.
    */
    focus: function () {
      this.$el.find("textarea").focus();
    }

  });

  /**
     TextCell is a string cell type that renders a form with a text area in a
     modal dialog instead of an input box editor. It is best suited for entering
     a large body of text.

     @class Backgrid.Extension.TextCell
     @extends Backgrid.StringCell
  */
  var TextCell = Backgrid.Extension.TextCell = Backgrid.StringCell.extend({

    /** @property */
    className: "text-cell",

    /** @property  */
    editor: TextareaEditor

  });

}(window, jQuery, _, Backbone, Backgrid));
<|endoftext|>


<commit_before>import { registerMacro, removeMacro } from "htmlbars/macros";
import { compileSpec } from "htmlbars/compiler";
import { hydrate } from "htmlbars/runtime";
import { HTMLElement } from "htmlbars/ast";

function equalHTML(fragment, html) {
  var div = document.createElement("div");
  div.appendChild(fragment.cloneNode(true));

  equal(div.innerHTML, html);
}

var macros;

module("HTML Macros", {
  setup: function() {
    macros = {};
  }
});

function registerMacro(name, test, macro) {
  macros[name] = { test: test, mutate: mutate };;
}

function compile(string) {
  var spec = compileSpec(string);
  return hydrate(spec, { macros: macros });
}

test("A simple HTML macro can replace a tagName", function() {
  registerMacro('testing', function test(element) {
    return element.attributes.is && element.attributes.is[0] === 'span';
  }, function mutate(element) {
    element.tag = 'span';
    element.removeAttr('is');
  });

  var template = compile("
hi
");
  var fragment = template();

  equalHTML(fragment, "hi");
});

test("A simple HTML macro can completely remove the node", function() {
  registerMacro('testing', function test(element) {
    return element.tag === 'noop';
  }, function mutate() {
    return 'veto';
  });

  var template = compile("lorem<noop>ipsum</noop>dolor");
  var fragment = template();

  equalHTML(fragment, "loremdolor");
});

test("An HTML macro can transclude its children into a new node", function() {
  registerMacro('testing', function test(element) {
    return element.tag === 'transclude';
  }, function mutate(element) {
    var tagName = element.getAttr('tag');
    element.removeAttr('tag');
    return new HTMLElement(tagName, element.attributes, element.children, element.helpers);
  });

  var template = compile("<transclude tag='p'>lorem ipsum dolor</transclude>");
  var fragment = template();

  equalHTML(fragment, "
lorem ipsum dolor
");
});
<commit_msg>remove unused function and setup<commit_after>import { registerMacro } from "htmlbars/macros";
import { compileSpec } from "htmlbars/compiler";
import { hydrate } from "htmlbars/runtime";
import { HTMLElement } from "htmlbars/ast";

function equalHTML(fragment, html) {
  var div = document.createElement("div");
  div.appendChild(fragment.cloneNode(true));

  equal(div.innerHTML, html);
}

module("HTML Macros");

function compile(string) {
  var spec = compileSpec(string);
  return hydrate(spec, {});
}

test("A simple HTML macro can replace a tagName", function() {
  registerMacro('testing', function test(element) {
    return element.attributes.is && element.attributes.is[0] === 'span';
  }, function mutate(element) {
    element.tag = 'span';
    element.removeAttr('is');
  });

  var template = compile("
hi
");
  var fragment = template();

  equalHTML(fragment, "hi");
});

test("A simple HTML macro can completely remove the node", function() {
  registerMacro('testing', function test(element) {
    return element.tag === 'noop';
  }, function mutate() {
    return 'veto';
  });

  var template = compile("lorem<noop>ipsum</noop>dolor");
  var fragment = template();

  equalHTML(fragment, "loremdolor");
});

test("An HTML macro can transclude its children into a new node", function() {
  registerMacro('testing', function test(element) {
    return element.tag === 'transclude';
  }, function mutate(element) {
    var tagName = element.getAttr('tag');
    element.removeAttr('tag');
    return new HTMLElement(tagName, element.attributes, element.children, element.helpers);
  });

  var template = compile("<transclude tag='p'>lorem ipsum dolor</transclude>");
  var fragment = template();

  equalHTML(fragment, "
lorem ipsum dolor
");
});
<|endoftext|>


<commit_before>#! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { flagsToOptions, colorResponse } = require('./src/util')

args
  .option('header', 'HTTP request header')
  .option('baseUrl', 'Base URL for sending HTTP requests')

const flags = args.parse(process.argv)

if (!flags.help && !flags.version) {
  let config
  let schema
  try {
    config = require(path.join(process.cwd(), 'package.json')).gest
  } catch (e) {}

  const options = Object.assign({ schema: 'schema.js' }, config, flagsToOptions(flags))

  try {
    schema = require(path.join(process.cwd(), options.schema))
  } catch (e) {
    switch (e.code) {
      case 'MODULE_NOT_FOUND':
        console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
        break
      default: console.log(e)
    }
    process.exit()
  }

  if (args.sub && args.sub.length) {
    checkPath(path.join(__dirname, args.sub[0]))
    .then(readFile)
    .catch(() => args.sub[0])
    .then(sendQuery(schema, options))
    .then(colorResponse)
    .then(console.log)
    .catch(console.log)
    .then(() => process.exit())
  } else {
    // REPL
    REPL(schema, options)
  }
}
<commit_msg>Refactor error handling<commit_after>#! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { flagsToOptions, colorResponse } = require('./src/util')

args
  .option('header', 'HTTP request header')
  .option('baseUrl', 'Base URL for sending HTTP requests')

const flags = args.parse(process.argv)

try {
  if (!flags.help && !flags.version) {
    let config
    try {
      config = require(path.join(process.cwd(), 'package.json')).gest
    } catch (e) {}

    const options = Object.assign({ schema: 'schema.js' }, config, flagsToOptions(flags))

    const schema = require(path.join(process.cwd(), options.schema))

    if (args.sub && args.sub.length) {
      checkPath(path.join(__dirname, args.sub[0]))
      .then(readFile)
      .catch(() => args.sub[0])
      .then(sendQuery(schema, options))
      .then(colorResponse)
      .then(console.log)
      .catch(console.log)
      .then(() => process.exit())
    } else {
      // REPL
      REPL(schema, options)
    }
  }
} catch (e) {
  switch (e.code) {
    case 'MODULE_NOT_FOUND':
      console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
      break
    default: console.log(e)
  }
}
<|endoftext|>