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

describe('no protractor at all', function() {
  it('should still do normal tests', function() {
    expect(true).toBe(true);
  });
});

describe('protractor library', function() {
  it('should expose the correct global variables', function() {
    expect(protractor).toBeDefined();
    expect(browser).toBeDefined();
    expect(by).toBeDefined();
    expect(By).toBeDefined();
    expect(element).toBeDefined();
    expect($).toBeDefined();
    expect(DartObject).toBeDefined();
    var obj = {};
    var dartProxy = new DartObject(obj);
    expect(dartProxy.o === obj).toBe(true);
  });

  it('should export other webdriver classes onto the global protractor',
      function() {
        expect(protractor.ActionSequence).toBeDefined();
        expect(protractor.Key.RETURN).toEqual('\uE006');
      });

  it('should export custom parameters to the protractor instance', function() {
    expect(browser.params.login).toBeDefined();
    expect(browser.params.login.user).toEqual('Jane');
    expect(browser.params.login.password).toEqual('1234');
  });

  it('should allow a mix of using protractor and using the driver directly',
      function() {
        browser.get('index.html');
        expect(browser.getCurrentUrl()).toMatch('#/form');

        browser.driver.findElement(protractor.By.linkText('repeater')).click();
        expect(browser.driver.getCurrentUrl()).toMatch('#/repeater');

        browser.navigate().back();
        expect(browser.driver.getCurrentUrl()).toMatch('#/form');
      });

  it('should have access to the processed config block', function() {
    function containsMatching(arr, string) {
      var contains = false;
      for (var i = 0; i < arr.length; ++i) {
        if (arr[i].indexOf(string) !== -1) {
          contains = true;
        }
      }
      return contains;
    }

    browser.getProcessedConfig().then(function(config) {
      expect(config.params.login).toBeDefined();
      expect(config.params.login.user).toEqual('Jane');
      expect(config.params.login.password).toEqual('1234');
      expect(containsMatching(config.specs, 'lib_spec.js')).toBe(true);
      expect(config.capabilities).toBeDefined();
    });
  });

  it('should allow adding custom locators', function() {
    var findMenuItem = function() {
      var itemName = arguments[0];
      var using = arguments[1]; // unused
      var menu = document.querySelectorAll('.menu li');
      for (var i = 0; i < menu.length; ++i) {
        if (menu[i].textContent == itemName) {
          return [menu[i]];
        }
      }
    };

    by.addLocator('menuItem', findMenuItem);

    expect(by.menuItem).toBeDefined();

    browser.get('index.html');
    expect(element(by.menuItem('repeater')).isPresent());
    expect(element(by.menuItem('repeater')).getText()).toEqual('repeater');
  });

  it('should allow adding custom varargs locators', function() {
    var findMenuItemWithName = function() {
      var css = arguments[0];
      var itemName = arguments[1];
      var using = arguments[2]; // unused
      var menu = document.querySelectorAll(css);
      for (var i = 0; i < menu.length; ++i) {
        if (menu[i].textContent == itemName) {
          return [menu[i]];
        }
      }
    };

    by.addLocator('menuItemWithName', findMenuItemWithName);

    expect(by.menuItemWithName).toBeDefined();

    browser.get('index.html');
    expect(element(by.menuItemWithName('.menu li', 'repeater')).isPresent());
    expect(element(by.menuItemWithName('.menu li', 'repeater')).getText()).
        toEqual('repeater');
  });

  it('should allow self-wrapped webdriver instances', function() {
    var driver = protractor.wrapDriver(browser.driver);
    driver.get('index.html');
  });

  describe('helper functions', function() {
    it('should get the absolute URL', function() {
      browser.get('index.html');
      expect(browser.getLocationAbsUrl()).
          toMatch('/form');

      element(by.linkText('repeater')).click();
      expect(browser.getLocationAbsUrl()).
          toMatch('/repeater');
    });

    it('should navigate to another url with setLocation', function() {
      browser.get('index.html');

      browser.setLocation('/repeater');

      expect(browser.getLocationAbsUrl()).
          toMatch('/repeater');
    });
  });
});
<commit_msg>Update lib_spec.js<commit_after>var util = require('util');

describe('no protractor at all', function() {
  it('should still do normal tests', function() {
    expect(true).toBe(true);
  });
});

describe('protractor library', function() {
  it('should expose the correct global variables', function() {
    expect(protractor).toBeDefined();
    expect(browser).toBeDefined();
    expect(by).toBeDefined();
    expect(By).toBeDefined();
    expect(element).toBeDefined();
    expect($).toBeDefined();
    expect(DartObject).toBeDefined();
    var obj = {};
    var dartProxy = new DartObject(obj);
    expect(dartProxy.o === obj).toBe(true);
  });

  it('should export other webdriver classes onto the global protractor',
      function() {
        expect(protractor.ActionSequence).toBeDefined();
        expect(protractor.Key.RETURN).toEqual('\uE006');
      });

  it('should export custom parameters to the protractor instance', function() {
    expect(browser.params.login).toBeDefined();
    expect(browser.params.login.user).toEqual('Jane');
    expect(browser.params.login.password).toEqual('1234');
  });

  it('should allow a mix of using protractor and using the driver directly',
      function() {
        browser.get('index.html');
        expect(browser.getCurrentUrl()).toMatch('#/form');

        browser.driver.findElement(protractor.By.linkText('repeater')).click();
        expect(browser.driver.getCurrentUrl()).toMatch('#/repeater');

        browser.navigate().back();
        expect(browser.driver.getCurrentUrl()).toMatch('#/form');
      });

  it('should have access to the processed config block', function() {
    function containsMatching(arr, string) {
      var contains = false;
      for (var i = 0; i < arr.length; ++i) {
        if (arr[i].indexOf(string) !== -1) {
          contains = true;
        }
      }
      return contains;
    }

    browser.getProcessedConfig().then(function(config) {
      expect(config.params.login).toBeDefined();
      expect(config.params.login.user).toEqual('Jane');
      expect(config.params.login.password).toEqual('1234');
      expect(containsMatching(config.specs, 'lib_spec.js')).toBe(true);
      expect(config.capabilities).toBeDefined();
    });
  });

  it('should allow adding custom locators', function() {
    var findMenuItem = function() {
      var itemName = arguments[0];
      var using = arguments[1]; // unused
      var menu = document.querySelectorAll('.menu li');
      for (var i = 0; i < menu.length; ++i) {
        if (menu[i].textContent == itemName) {
          return [menu[i]];
        }
      }
    };

    by.addLocator('menuItem', findMenuItem);

    expect(by.menuItem).toBeDefined();

    browser.get('index.html');
    expect(element(by.menuItem('repeater')).isPresent());
    expect(element(by.menuItem('repeater')).getText()).toEqual('repeater');
  });

  it('should allow adding custom varargs locators', function() {
    var findMenuItemWithName = function() {
      var css = arguments[0];
      var itemName = arguments[1];
      var using = arguments[2]; // unused
      var menu = document.querySelectorAll(css);
      for (var i = 0; i < menu.length; ++i) {
        if (menu[i].textContent == itemName) {
          return [menu[i]];
        }
      }
    };

    by.addLocator('menuItemWithName', findMenuItemWithName);

    expect(by.menuItemWithName).toBeDefined();

    browser.get('index.html');
    expect(element(by.menuItemWithName('.menu li', 'repeater')).isPresent());
    expect(element(by.menuItemWithName('.menu li', 'repeater')).getText()).
        toEqual('repeater');
  });

  it('should allow self-wrapped webdriver instances', function() {
    var driver = protractor.wrapDriver(browser.driver);
    var url = browser.baseUrl + 'index.html';
    driver.get(url);
  });

  describe('helper functions', function() {
    it('should get the absolute URL', function() {
      browser.get('index.html');
      expect(browser.getLocationAbsUrl()).
          toMatch('/form');

      element(by.linkText('repeater')).click();
      expect(browser.getLocationAbsUrl()).
          toMatch('/repeater');
    });

    it('should navigate to another url with setLocation', function() {
      browser.get('index.html');

      browser.setLocation('/repeater');

      expect(browser.getLocationAbsUrl()).
          toMatch('/repeater');
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Expression organization is undefined on line 4, column 61 in Templates/Licenses/license-gpl30.txt.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Popup component
 * Creates a button which activates the generic popup.
 * @author Meine Toonen
 */
Ext.define ("viewer.components.tools.PopupButton",{
    extend: "viewer.components.tools.JSButton",
    popup:null,

    config:{
        name: "zoomIn"
    },
    constructor: function (conf){
        conf.toggle = true;
        conf.enabled = false;
        conf. selected =false;
        viewer.components.tools.PopupButton.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.popup = this.viewerController.layoutManager.popupWin;
        var me =this;
        this.popup.popupWin.addListener("show",function(){me.setSelectedState(true);},this);
        this.popup.popupWin.addListener("hide",function(){me.setSelectedState(false);},this);

        this.addListener(viewer.viewercontroller.controller.Event.ON_EVENT_DOWN,this.down, this);
        this.addListener(viewer.viewercontroller.controller.Event.ON_EVENT_UP,this.up, this);
        return this;
    },
    /**
     *  Handler for the down event on this button. Shows the popup window.
     **/
    down : function (button,comp){
        this.popup.show()
    },
    up : function (button,comp){
        this.popup.hide();
    }
});

<commit_msg>PopupButton initializes the correct state of the button<commit_after>/*
 * Copyright (C) 2012 Expression organization is undefined on line 4, column 61 in Templates/Licenses/license-gpl30.txt.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Popup component
 * Creates a button which activates the generic popup.
 * @author Meine Toonen
 */
Ext.define ("viewer.components.tools.PopupButton",{
    extend: "viewer.components.tools.JSButton",
    popup:null,

    config:{
        name: "zoomIn"
    },
    constructor: function (conf){
        this.popup = conf.viewerController.layoutManager.popupWin;
        conf.toggle = true;
        conf.enabled = false;
        conf.selected = !this.popup.popupWin.isHidden() ||false ;
        viewer.components.tools.PopupButton.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        var me =this;
        this.popup.popupWin.addListener("show",function(){me.setSelectedState(true);},this);
        this.popup.popupWin.addListener("hide",function(){me.setSelectedState(false);},this);
        this.addListener(viewer.viewercontroller.controller.Event.ON_EVENT_DOWN,this.down, this);
        this.addListener(viewer.viewercontroller.controller.Event.ON_EVENT_UP,this.up, this);
        return this;
    },
    /**
     *  Handler for the down event on this button. Shows the popup window.
     **/
    down : function (button,comp){
        this.popup.show()
    },
    up : function (button,comp){
        this.popup.hide();
    }
});

<|endoftext|>


<commit_before>'use strict';

var util = require('util'),
    ltx = require('ltx'),
    winston = require('winston'),
    logger = winston.loggers.get('xep-0045'),
    XepComponent = require('../../XepComponent'),
    Message = require('node-xmpp-core').Stanza.Message,
    Presence = require('node-xmpp-core').Stanza.Presence,
    JID = require('node-xmpp-core').JID,
    NS = require('../namespace');

function PresenceHandler() {}

util.inherits(PresenceHandler, XepComponent);

PresenceHandler.prototype.generatePresence = function (affiliation, role) {
    var presence = new Presence({
        from: '',
        to: ''
    });
    presence.c('x', {
        'xmlns': NS.MUC_USER
    }).c('item', {
        'affiliation': affiliation,
        'role': role
    });

    return presence;
};

PresenceHandler.prototype.sendPresenceConfirmation = function (room, member, roomjid) {
    logger.debug('send presence confirmation to ' + member.jid);

    // send client the confirmation
    var confirmMsg = new Presence({
        from: roomjid.toString(),
        to: member.jid.toString()
    });
    var x = confirmMsg.c('x', {
        'xmlns': NS.MUC_USER
    });
    x.c('item', {
        'affiliation': member.RoomMembers.affiliation,
        'role': member.RoomMembers.role
    });
    x.c('status', {
        'code': '110'
    });
    this.send(confirmMsg);
};

PresenceHandler.prototype.sendPresenceJoin = function (room, newMember, roomjid, nickname) {
    logger.debug('send join of ' + newMember.jid + ' to all participants');
    var self = this;

    // iterate over existing members
    room.getMembers().success(
        function (members) {
            try {
                // send presence to each member
                var newPresence = self.generatePresence(NS.MUC_AFFILIATION_ADMIN, NS.MUC_ROLE_ADMIN);
                for (var i = 0, l = members.length; i < l; i++) {
                    var member = members[i];

                    // send existing room members the info about new user
                    if (member.jid.toString() !== newMember.jid.toString()) {
                        var memberMessage = newPresence.clone();
                        var newuser = roomjid.bare();
                        newuser.setResource(nickname);
                        memberMessage.attrs.from = newuser.toString(); // must be with nickname of user
                        memberMessage.attrs.to = member.jid;
                        self.send(memberMessage);
                    }

                    // send presence of existing room members to new user
                    if (member.jid.toString() !== newMember.jid.toString()) {
                        // read member details
                        var nick = member.RoomMembers.nickname;
                        var affiliation = member.RoomMembers.affiliation;
                        var role = member.RoomMembers.role;

                        var joinermsg = self.generatePresence(affiliation, role);

                        var memberroomjid = roomjid.bare();
                        memberroomjid.setResource(nick);

                        joinermsg.attrs.from = memberroomjid.toString();
                        joinermsg.attrs.to = member.jid.toString();
                        self.send(joinermsg, null);
                    }
                }
            } catch (err) {
                logger.error(err.toString());
            }
        }
    );
};

PresenceHandler.prototype.sendRoomHistory = function (room, member, roomjid ) {
    logger.debug('send room ' + roomjid + ' history to ' + member.jid);
    var self = this;
    room.getMessages().success(
        function (messages) {
            // send room history
            for (var i = 0, l = messages.length; i < l; i += 1) {
                // extract message
                var el = ltx.parse(messages[i].content);
                // el.attrs.from = roomjid;
                el.attrs.to = member.jid;
                self.send(el);
            }
        }
    ).error(function(err){
        console.error(err);
    });
};

PresenceHandler.prototype.joinRoom = function (room, user, roomjid) {
    var nickname = roomjid.resource.toString();
    var self = this;

    logger.debug('user ' + user.jid + ' joins the room');

    // join room
    room.join(user, {
        role: 'visitor',
        affiliation:'member',
        nickname: nickname
    }).then(function (member) {
        // send presence confirmation to new member
        self.sendPresenceConfirmation(room, member, roomjid);

        // send presence of existing users to new member and
        // inform the existing members about the new member
        self.sendPresenceJoin(room, member, roomjid, nickname);

        // send the new member the message history
        self.sendRoomHistory(room, member, roomjid);
    });

};

PresenceHandler.prototype.sendPresenceLeave = function (room, user, roomjid) {
    var self = this;

    // send client the confirmation
    var confirmMsg = new Presence({
        from: roomjid,
        to: user.jid,
        type: 'unavailable'
    });
    var x = confirmMsg.c('x', {
        'xmlns': NS.MUC_USER
    });
    x.c('item', {
        'affiliation': NS.MUC_AFFILIATION_ADMIN,
        'role': NS.MUC_ROLE_ADMIN
    });
    x.c('status', {
        'code': '110'
    });
    self.send(confirmMsg);

    // send new presense to exsting members
    var newPresence = new Presence({
        from: '',
        to: '',
        type: 'unavailable'
    });
    newPresence.c('x', {
        'xmlns': NS.MUC_USER
    }).c('item', {
        'affiliation': NS.MUC_AFFILIATION_ADMIN,
        'role': NS.MUC_ROLE_ADMIN
    });

    room.listMembers().then(
        function (members) {
            for (var i = 0, l = members.length; i < l; i += 1) {
                var member = members[i];

                // send existing room members the info
                var memberMessage = newPresence.clone();
                memberMessage.attrs.from = roomjid;
                memberMessage.attrs.to = member.jid;
                self.send(memberMessage);
            }
        }
    );
};

PresenceHandler.prototype.leaveRoom = function (room, user) {
    var self = this;
    logger.debug('user' + user.jid + ' leaves the room');
    // leave room
    room.leave(user).then(
        function () {
            logger.debug('send unavailibility to all users');
            self.sendPresenceLeave(room, user);
        }).catch(function (err) {
            console.error(err);
            logger.error(err);
        });
};

PresenceHandler.prototype.handlePresence = function (room, user, stanza) {
    logger.debug('handle presence');
    var self = this;

    var roomjid = new JID(stanza.attrs.to);

    // user leaves the room
    // @see http://xmpp.org/extensions/xep-0045.html#exit
    if (room && stanza.attrs.type === 'unavailable') {
        self.leaveRoom(room, user, roomjid);
    }
    // user joins the room
    else {
        self.joinRoom(room, user, roomjid);
    }
};

module.exports = PresenceHandler;<commit_msg>fix method name<commit_after>'use strict';

var util = require('util'),
    ltx = require('ltx'),
    winston = require('winston'),
    logger = winston.loggers.get('xep-0045'),
    XepComponent = require('../../XepComponent'),
    Message = require('node-xmpp-core').Stanza.Message,
    Presence = require('node-xmpp-core').Stanza.Presence,
    JID = require('node-xmpp-core').JID,
    NS = require('../namespace');

function PresenceHandler() {}

util.inherits(PresenceHandler, XepComponent);

PresenceHandler.prototype.generatePresence = function (affiliation, role) {
    var presence = new Presence({
        from: '',
        to: ''
    });
    presence.c('x', {
        'xmlns': NS.MUC_USER
    }).c('item', {
        'affiliation': affiliation,
        'role': role
    });

    return presence;
};

PresenceHandler.prototype.sendPresenceConfirmation = function (room, member, roomjid) {
    logger.debug('send presence confirmation to ' + member.jid);

    // send client the confirmation
    var confirmMsg = new Presence({
        from: roomjid.toString(),
        to: member.jid.toString()
    });
    var x = confirmMsg.c('x', {
        'xmlns': NS.MUC_USER
    });
    x.c('item', {
        'affiliation': member.RoomMembers.affiliation,
        'role': member.RoomMembers.role
    });
    x.c('status', {
        'code': '110'
    });
    this.send(confirmMsg);
};

PresenceHandler.prototype.sendPresenceJoin = function (room, newMember, roomjid, nickname) {
    logger.debug('send join of ' + newMember.jid + ' to all participants');
    var self = this;

    // iterate over existing members
    room.getMembers().success(
        function (members) {
            try {
                // send presence to each member
                var newPresence = self.generatePresence(NS.MUC_AFFILIATION_ADMIN, NS.MUC_ROLE_ADMIN);
                for (var i = 0, l = members.length; i < l; i++) {
                    var member = members[i];

                    // send existing room members the info about new user
                    if (member.jid.toString() !== newMember.jid.toString()) {
                        var memberMessage = newPresence.clone();
                        var newuser = roomjid.bare();
                        newuser.setResource(nickname);
                        memberMessage.attrs.from = newuser.toString(); // must be with nickname of user
                        memberMessage.attrs.to = member.jid;
                        self.send(memberMessage);
                    }

                    // send presence of existing room members to new user
                    if (member.jid.toString() !== newMember.jid.toString()) {
                        // read member details
                        var nick = member.RoomMembers.nickname;
                        var affiliation = member.RoomMembers.affiliation;
                        var role = member.RoomMembers.role;

                        var joinermsg = self.generatePresence(affiliation, role);

                        var memberroomjid = roomjid.bare();
                        memberroomjid.setResource(nick);

                        joinermsg.attrs.from = memberroomjid.toString();
                        joinermsg.attrs.to = member.jid.toString();
                        self.send(joinermsg, null);
                    }
                }
            } catch (err) {
                logger.error(err.toString());
            }
        }
    );
};

PresenceHandler.prototype.sendRoomHistory = function (room, member, roomjid ) {
    logger.debug('send room ' + roomjid + ' history to ' + member.jid);
    var self = this;
    room.getMessages().success(
        function (messages) {
            // send room history
            for (var i = 0, l = messages.length; i < l; i += 1) {
                // extract message
                var el = ltx.parse(messages[i].content);
                // el.attrs.from = roomjid;
                el.attrs.to = member.jid;
                self.send(el);
            }
        }
    ).error(function(err){
        console.error(err);
    });
};

PresenceHandler.prototype.joinRoom = function (room, user, roomjid) {
    var nickname = roomjid.resource.toString();
    var self = this;

    logger.debug('user ' + user.jid + ' joins the room');

    // join room
    room.join(user, {
        role: 'visitor',
        affiliation:'member',
        nickname: nickname
    }).then(function (member) {
        // send presence confirmation to new member
        self.sendPresenceConfirmation(room, member, roomjid);

        // send presence of existing users to new member and
        // inform the existing members about the new member
        self.sendPresenceJoin(room, member, roomjid, nickname);

        // send the new member the message history
        self.sendRoomHistory(room, member, roomjid);
    });

};

PresenceHandler.prototype.sendPresenceLeave = function (room, user, roomjid) {
    var self = this;

    // send client the confirmation
    var confirmMsg = new Presence({
        from: roomjid,
        to: user.jid,
        type: 'unavailable'
    });
    var x = confirmMsg.c('x', {
        'xmlns': NS.MUC_USER
    });
    x.c('item', {
        'affiliation': NS.MUC_AFFILIATION_ADMIN,
        'role': NS.MUC_ROLE_ADMIN
    });
    x.c('status', {
        'code': '110'
    });
    self.send(confirmMsg);

    // send new presense to exsting members
    var newPresence = new Presence({
        from: '',
        to: '',
        type: 'unavailable'
    });
    newPresence.c('x', {
        'xmlns': NS.MUC_USER
    }).c('item', {
        'affiliation': NS.MUC_AFFILIATION_ADMIN,
        'role': NS.MUC_ROLE_ADMIN
    });

    room.getMembers().then(
        function (members) {
            for (var i = 0, l = members.length; i < l; i += 1) {
                var member = members[i];

                // send existing room members the info
                var memberMessage = newPresence.clone();
                memberMessage.attrs.from = roomjid;
                memberMessage.attrs.to = member.jid;
                self.send(memberMessage);
            }
        }
    );
};

PresenceHandler.prototype.leaveRoom = function (room, user) {
    var self = this;
    logger.debug('user' + user.jid + ' leaves the room');
    // leave room
    room.leave(user).then(
        function () {
            logger.debug('send unavailibility to all users');
            self.sendPresenceLeave(room, user);
        }).catch(function (err) {
            console.error(err);
            logger.error(err);
        });
};

PresenceHandler.prototype.handlePresence = function (room, user, stanza) {
    logger.debug('handle presence');
    var self = this;

    var roomjid = new JID(stanza.attrs.to);

    // user leaves the room
    // @see http://xmpp.org/extensions/xep-0045.html#exit
    if (room && stanza.attrs.type === 'unavailable') {
        self.leaveRoom(room, user, roomjid);
    }
    // user joins the room
    else {
        self.joinRoom(room, user, roomjid);
    }
};

module.exports = PresenceHandler;<|endoftext|>


<commit_before>var MetaTable = require('./MetaTable')

exports.validate = function(supplier, tabIndex, headers, content) {
// supplier; (string) 'Migdal' לדגמ
// tabIndex; (integer) the tab number in the suppliers xls sheet
// headers; (array of objects) [{columnName: 'instrument_id'}]
//
// content; (array of arrays - each of which has the same length as headers) [
// 				["instrument 1"],
// 				["instrument 2"]
// 			]

	// validate all content arrays have same length as headers
	removeBadLengthLines(content, headers.length);

	removeEmptyLines(content)
	removeSumLines(content)
	validateTypes();

	var db = require('./db').open();
	var tableWriter = db.openTable(headers)
	tableWriter(content);

	console.log("<><><<>< headers", headers)
	console.log("<><><<>< Sheet Data",content);
}

function removeBadLengthLines(content, numColumns)
{
	for (var i = content.length - 1 ; i > -1; i--){
		if (content[i].length !== numColumns){
			content.splice(i, 1);
			console.log ('line ' + i + ' has ' + content[i].length + ' columns. expected ' + numColumns + '.');
		}
	}
}

function removeEmptyLines(content){
	for (var i = content.length - 1 ; i > -1; i--){
		if (lineIsEmpty(content[i])){
			content.splice(i, 1);
		}
	}
}

function lineIsEmpty(line)
{
	for (var i = 0; i < line.length; i++)
	{
		if (line[i] != '')
		{
			return false;
		}
	}
	return true;
}

function removeSumLines(content){

}

function validateTypes(){

}
<commit_msg>+patching validator to do CSV<commit_after>var MetaTable = require('./MetaTable')

exports.validate = function(supplier, tabIndex, headers, content,tabIndex) {
// supplier; (string) 'Migdal' לדגמ
// tabIndex; (integer) the tab number in the suppliers xls sheet
// headers; (array of objects) [{columnName: 'instrument_id'}]
//
// content; (array of arrays - each of which has the same length as headers) [
// 				["instrument 1"],
// 				["instrument 2"]
// 			]

	// validate all content arrays have same length as headers
	removeBadLengthLines(content, headers.length);

	removeEmptyLines(content)
	removeSumLines(content)
	validateTypes();

	var DB =  require('./db');
	var db = new DB.csv(supplier + "_tab_" + tabIndex + ".csv");
	var tableWriter = db.openTable(headers)
	tableWriter(content);

	// console.log("<><><<>< headers", headers)
	// console.log("<><><<>< Sheet Data",content);
}

function removeBadLengthLines(content, numColumns)
{
	for (var i = content.length - 1 ; i > -1; i--){
		if (content[i].length !== numColumns){
			content.splice(i, 1);
			// console.log ('line ' + i + ' has ' + content[i].length + ' columns. expected ' + numColumns + '.');
		}
	}
}

function removeEmptyLines(content){
	for (var i = content.length - 1 ; i > -1; i--){
		if (lineIsEmpty(content[i])){
			content.splice(i, 1);
		}
	}
}

function lineIsEmpty(line)
{
	for (var i = 0; i < line.length; i++)
	{
		if (line[i] != '')
		{
			return false;
		}
	}
	return true;
}

function removeSumLines(content){

}

function validateTypes(){

}
<|endoftext|>


<commit_before>/* @flow */

import express from 'express'
import expressWinston from 'express-winston'
import logger from 'winston'
import cors from 'cors'

import { ProofChecker } from './ProofChecker'
import type { ProofCheckerConfig } from './ProofChecker'
import { getChallengeText, LATEST_AUTH_VERSION } from './authentication'
import { HubServer } from './server'
import type { HubServerConfig } from './server'
import { getDriverClass } from './utils'
import { DriverModel } from './driverModel'
import * as errors from './errors'

function writeResponse(res: express.response, data: Object, statusCode: number) {
  res.writeHead(statusCode, {'Content-Type' : 'application/json'})
  res.write(JSON.stringify(data))
  res.end()
}

export interface MakeHttpServerConfig {
  proofsConfig?: ProofCheckerConfig,
  driverInstance?: DriverModel, driverClass?: Class<DriverModel>, driver?: string
}

export function makeHttpServer(config: MakeHttpServerConfig & HubServerConfig) : express.Application {

  const app : express.Application = express()

  // Handle driver configuration
  let driver : DriverModel

  if (config.driverInstance) {
    driver = config.driverInstance
  } else if (config.driverClass) {
    driver = new config.driverClass(config)
  } else if (config.driver) {
    const driverClass = getDriverClass(config.driver)
    driver = new driverClass(config)
  } else {
    throw new Error('Driver option not configured')
  }

  const proofChecker = new ProofChecker(config.proofsConfig)
  const server = new HubServer(driver, proofChecker, config)

  // Instantiate server logging with Winston
  app.use(expressWinston.logger({
    winstonInstance: logger }))

  app.use(cors())

  // sadly, express doesn't like to capture slashes.
  //  but that's okay! regexes solve that problem
  app.post(/^\/store\/([a-zA-Z0-9]+)\/(.+)/, (req: express.request,
                                           res: express.response) => {
    let filename = req.params[1]
    if (filename.endsWith('/')){
      filename = filename.substring(0, filename.length - 1)
    }
    const address = req.params[0]

    server.handleRequest(address, filename, req.headers, req)
      .then((publicURL) => {
        writeResponse(res, { publicURL }, 202)
      })
      .catch((err) => {
        logger.error(err)
        if (err instanceof errors.ValidationError) {
          writeResponse(res, { message: err.message, error: err.name }, 401)
        } else if (err instanceof errors.AuthTokenTimestampValidationError) {
          writeResponse(res, { message: err.message, error: err.name  }, 401)
        } else if (err instanceof errors.BadPathError) {
          writeResponse(res, { message: err.message, error: err.name  }, 403)
        } else if (err instanceof errors.NotEnoughProofError) {
          writeResponse(res, { message: err.message, error: err.name  }, 402)
        } else {
          writeResponse(res, { message: 'Server Error' }, 500)
        }
      })
  })

  app.post(
      /^\/list-files\/([a-zA-Z0-9]+)\/?/, express.json(),
    (req: express.request, res: express.response) => {
      // sanity check...
      if (req.headers['content-length'] > 4096) {
        writeResponse(res, { mesasge: 'Invalid JSON: too long'}, 400)
        return
      }

      const address = req.params[0]
      const requestBody = req.body
      const page = requestBody.page ? requestBody.page : null

      server.handleListFiles(address, page, req.headers)
        .then((files) => {
          writeResponse(res, { entries: files.entries, page: files.page }, 202)
        })
        .catch((err) => {
          logger.error(err)
          if (err.name === 'ValidationError') {
            writeResponse(res, { message: err.message }, 401)
          } else {
            writeResponse(res, { message: 'Server Error' }, 500)
          }
        })
  })

  app.post(
    /^\/revoke-all\/([a-zA-Z0-9]+)\/?/,
    express.json(),
    (req: express.request, res: express.response) => {
      // sanity check...
      if (req.headers['content-length'] > 4096) {
        writeResponse(res, { mesasge: 'Invalid JSON: too long'}, 400)
        return
      }

      if (!req.body || !req.body.oldestValidTimestamp) {
        writeResponse(res, { mesasge: 'Invalid JSON: missing oldestValidTimestamp'}, 400)
        return
      }

      const address = req.params[0]
      const oldestValidTimestamp: number = parseInt(req.body.oldestValidTimestamp)

      if (!Number.isFinite(oldestValidTimestamp)) {
        writeResponse(res, { mesasge: 'Invalid JSON: oldestValidTimestamp is not a valid integer'}, 400)
        return
      }

      server.handleAuthBump(address, oldestValidTimestamp, req.headers)
      .then(() => {
        writeResponse(res, { status: 'success' }, 202)
      })
      .catch((err) => {
        logger.error(err)
        if (err instanceof errors.ValidationError) {
          writeResponse(res, { message: err.message, error: err.name  }, 401)
        } else if (err instanceof errors.BadPathError) {
          writeResponse(res, { message: err.message, error: err.name  }, 403)
        } else {
          writeResponse(res, { message: 'Server Error' }, 500)
        }
      })
  })

  app.get('/hub_info/', (req: express.request,
                         res: express.response) => {
    const challengeText = getChallengeText(server.serverName)
    if (challengeText.length < 10) {
      return writeResponse(res, { message: 'Server challenge text misconfigured' }, 500)
    }
    const readURLPrefix = server.getReadURLPrefix()
    writeResponse(res, { 'challenge_text': challengeText,
                         'latest_auth_version': LATEST_AUTH_VERSION,
                         'read_url_prefix': readURLPrefix }, 200)
  })

  // Instantiate express application
  return app
}
<commit_msg>Fix error message key typo<commit_after>/* @flow */

import express from 'express'
import expressWinston from 'express-winston'
import logger from 'winston'
import cors from 'cors'

import { ProofChecker } from './ProofChecker'
import type { ProofCheckerConfig } from './ProofChecker'
import { getChallengeText, LATEST_AUTH_VERSION } from './authentication'
import { HubServer } from './server'
import type { HubServerConfig } from './server'
import { getDriverClass } from './utils'
import { DriverModel } from './driverModel'
import * as errors from './errors'

function writeResponse(res: express.response, data: Object, statusCode: number) {
  res.writeHead(statusCode, {'Content-Type' : 'application/json'})
  res.write(JSON.stringify(data))
  res.end()
}

export interface MakeHttpServerConfig {
  proofsConfig?: ProofCheckerConfig,
  driverInstance?: DriverModel, driverClass?: Class<DriverModel>, driver?: string
}

export function makeHttpServer(config: MakeHttpServerConfig & HubServerConfig) : express.Application {

  const app : express.Application = express()

  // Handle driver configuration
  let driver : DriverModel

  if (config.driverInstance) {
    driver = config.driverInstance
  } else if (config.driverClass) {
    driver = new config.driverClass(config)
  } else if (config.driver) {
    const driverClass = getDriverClass(config.driver)
    driver = new driverClass(config)
  } else {
    throw new Error('Driver option not configured')
  }

  const proofChecker = new ProofChecker(config.proofsConfig)
  const server = new HubServer(driver, proofChecker, config)

  // Instantiate server logging with Winston
  app.use(expressWinston.logger({
    winstonInstance: logger }))

  app.use(cors())

  // sadly, express doesn't like to capture slashes.
  //  but that's okay! regexes solve that problem
  app.post(/^\/store\/([a-zA-Z0-9]+)\/(.+)/, (req: express.request,
                                           res: express.response) => {
    let filename = req.params[1]
    if (filename.endsWith('/')){
      filename = filename.substring(0, filename.length - 1)
    }
    const address = req.params[0]

    server.handleRequest(address, filename, req.headers, req)
      .then((publicURL) => {
        writeResponse(res, { publicURL }, 202)
      })
      .catch((err) => {
        logger.error(err)
        if (err instanceof errors.ValidationError) {
          writeResponse(res, { message: err.message, error: err.name }, 401)
        } else if (err instanceof errors.AuthTokenTimestampValidationError) {
          writeResponse(res, { message: err.message, error: err.name  }, 401)
        } else if (err instanceof errors.BadPathError) {
          writeResponse(res, { message: err.message, error: err.name  }, 403)
        } else if (err instanceof errors.NotEnoughProofError) {
          writeResponse(res, { message: err.message, error: err.name  }, 402)
        } else {
          writeResponse(res, { message: 'Server Error' }, 500)
        }
      })
  })

  app.post(
      /^\/list-files\/([a-zA-Z0-9]+)\/?/, express.json(),
    (req: express.request, res: express.response) => {
      // sanity check...
      if (req.headers['content-length'] > 4096) {
        writeResponse(res, { message: 'Invalid JSON: too long'}, 400)
        return
      }

      const address = req.params[0]
      const requestBody = req.body
      const page = requestBody.page ? requestBody.page : null

      server.handleListFiles(address, page, req.headers)
        .then((files) => {
          writeResponse(res, { entries: files.entries, page: files.page }, 202)
        })
        .catch((err) => {
          logger.error(err)
          if (err.name === 'ValidationError') {
            writeResponse(res, { message: err.message }, 401)
          } else {
            writeResponse(res, { message: 'Server Error' }, 500)
          }
        })
  })

  app.post(
    /^\/revoke-all\/([a-zA-Z0-9]+)\/?/,
    express.json(),
    (req: express.request, res: express.response) => {
      // sanity check...
      if (req.headers['content-length'] > 4096) {
        writeResponse(res, { message: 'Invalid JSON: too long'}, 400)
        return
      }

      if (!req.body || !req.body.oldestValidTimestamp) {
        writeResponse(res, { message: 'Invalid JSON: missing oldestValidTimestamp'}, 400)
        return
      }

      const address = req.params[0]
      const oldestValidTimestamp: number = parseInt(req.body.oldestValidTimestamp)

      if (!Number.isFinite(oldestValidTimestamp)) {
        writeResponse(res, { message: 'Invalid JSON: oldestValidTimestamp is not a valid integer'}, 400)
        return
      }

      server.handleAuthBump(address, oldestValidTimestamp, req.headers)
      .then(() => {
        writeResponse(res, { status: 'success' }, 202)
      })
      .catch((err) => {
        logger.error(err)
        if (err instanceof errors.ValidationError) {
          writeResponse(res, { message: err.message, error: err.name  }, 401)
        } else if (err instanceof errors.BadPathError) {
          writeResponse(res, { message: err.message, error: err.name  }, 403)
        } else {
          writeResponse(res, { message: 'Server Error' }, 500)
        }
      })
  })

  app.get('/hub_info/', (req: express.request,
                         res: express.response) => {
    const challengeText = getChallengeText(server.serverName)
    if (challengeText.length < 10) {
      return writeResponse(res, { message: 'Server challenge text misconfigured' }, 500)
    }
    const readURLPrefix = server.getReadURLPrefix()
    writeResponse(res, { 'challenge_text': challengeText,
                         'latest_auth_version': LATEST_AUTH_VERSION,
                         'read_url_prefix': readURLPrefix }, 200)
  })

  // Instantiate express application
  return app
}
<|endoftext|>


<commit_before>foam.CLASS({
  package: 'foam.doc',
  name: 'DocBorder',
  extends: 'foam.u2.Element',

  axioms: [
    foam.u2.CSS.create({
      code: function() {/*
        ^ { background: gray; padding: 10px; display: inline-block; }
        ^title { padding: 6px; align-content: center; background: aliceblue; }
        ^content { padding: 6px; min-width: 220px; height: 100%; background: white; }
      */}
    })
  ],

  properties: [
    'title'
  ],

  methods: [
    function init() {
      this.
        cssClass(this.myCls()).
        start('div').cssClass(this.myCls('title')).add(this.title$).end().
        start('div', null, this.content$).
          cssClass(this.myCls('content')).
        end();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'AxiomInfo',
  ids: ['name'],

  properties: [
    {
      name: 'axiom',
      hidden: true
    },
    {
      name: 'cls',
      label: 'Source Class',
      tableCellView: function(o, e) {
        return foam.doc.LinkView.create({data: o.cls}, e.__subSubContext__);
      },
      tableCellFormatter: function(value, obj, axiom) {
        this.tag(foam.doc.LinkView, { data: value });
      }
    },
    {
      name: 'type',
      tableCellView: function(o, e) {
        return o.type ?
          foam.doc.LinkView.create({data: foam.doc.Link.create({path: o.type.id, label: o.type.name})}, e.__subSubContext__) :
          'anonymous';
      },
      tableCellFormatter: function(value, obj, axiom) {
        if ( value ) {
          this.tag(foam.doc.LinkView, { data: foam.doc.Link.create({ path: value.id, label: value.name }) });
          return;
        }
        this.add('anonymous');
      }
    },
    {
      name: 'name'
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'ClassList',
  extends: 'foam.u2.View',

  requires: [
    'foam.doc.ClassLink'
  ],

  methods: [
    function initE() {
      this.SUPER();

      var self = this;

      this.add('(', this.data.length, ')').br();

      this.data.forEach(function(cls) {
        self.start(self.ClassLink, {data: cls, showPackage: true}).end().br();
      });
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'ClassDocView',
  extends: 'foam.u2.View',

  requires: [
    'foam.doc.Link',
    'foam.doc.ClassLink',
    'foam.doc.AxiomInfo',
    'foam.u2.view.TableView',
    'foam.dao.ArrayDAO'
  ],

  imports: [
    'selectedAxiom'
  ],

  properties: [
    {
      class: 'Boolean',
      name: 'showInherited',
      value: true
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      var data = this.data;

      this.add('CLASS: ', data.name, ' (', data.count_, ')').br();
      this.add('extends: ');
      var cls = data;
      for ( var i = 0 ; cls ; i++ ) {
        cls = this.lookup(cls.model_.extends, true);
        if ( i ) this.add(' : ');
        this.start(this.ClassLink, {data: cls}).end();
        if ( cls === foam.core.FObject ) break;
      }
      this.br();
      this.add(data.documentation);

      this.add('Show Inherited: ').start(this.SHOW_INHERITED, {data$: this.showInherited$}).end();

      this.add(this.slot(function (showInherited) {
        // TODO: hide 'Source Class' column if showInherited is false
        var axs = [];
        for ( var key in data.axiomMap_ ) {
          if ( showInherited || Object.hasOwnProperty.call(data.axiomMap_, key) ) {
            var a  = data.axiomMap_[key];
            var ai = foam.doc.AxiomInfo.create({
              axiom: a,
              type: a.cls_,
              cls: this.Link.create({
                path: a.sourceCls_.id,
                label: a.sourceCls_.name
              }),
              name: a.name
            });
            axs.push(ai);
          }
        }

        return this.TableView.create({
          of: this.AxiomInfo,
          data: this.ArrayDAO.create({array: axs}),
          hoverSelection$: this.selectedAxiom$
        });
      }));
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'Link',

  properties: [
    'path',
    'label'
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'LinkView',
  extends: 'foam.u2.View',

  imports: [ 'browserPath' ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('a').
        on('click', this.click).
        attrs({href: this.data.path}).
        add(this.data.label);
    }
  ],

  listeners: [
    function click(e) {
      this.browserPath$.set(this.data.path);
      e.preventDefault();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'ClassLink',
  extends: 'foam.u2.View',

  imports: [ 'browserPath' ],

  properties: [
    {
      class: 'Class',
      name: 'data'
    },
    {
      class: 'Boolean',
      name: 'showPackage'
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('a').
        on('click', this.click).
        attrs({href: this.data.id}).
        add(this.showPackage ? this.data.id : this.data.name);
    }
  ],

  listeners: [
    function click(e) {
      this.browserPath$.set(this.data.id);
      e.preventDefault();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'DocBrowser',
  extends: 'foam.u2.Element',

  requires: [
    'foam.doc.DocBorder',
    'foam.doc.ClassList',
    'foam.doc.ClassDocView'
  ],

  exports: [
    'as data',
    'path as browserPath',
    'axiom as selectedAxiom'
  ],

  properties: [
    'path',
    {
      class: 'FObjectProperty',
      name: 'axiom',
      view: { class: 'foam.u2.DetailView' }
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.tag(this.PATH, {displayWidth: 80}).br().br();

      this.
        start('table').
          start('tr').
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Class List'}).
                start(this.ClassList, {data: Object.values(foam.USED).sort(foam.core.Model.ID.compare)}).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Sub-Classes'}).
                add(this.slot(function(path) {
                  var o = foam.lookup(path, true);
                  if ( ! o ) return '';
                  return this.ClassDocView.create({data: o});
                })).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Sub-Classes'}).
                add(this.slot(function(path) {
                  var o = foam.lookup(path, true);
                  if ( ! o ) return '';
                  return this.ClassList.create({data: Object.values(foam.USED).filter(function(cls) { return cls.model_.extends == path || 'foam.core.' + cls.model_.extends == path; }).sort(foam.core.Model.ID.compare)});
                })).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Required-By'}).
                add(this.slot(function(path) {
                  var o = foam.lookup(path, true);
                  if ( ! o ) return '';
                  // TODO: this could be done more efficiently, and memoized
                  return this.ClassList.create({data: Object.values(foam.USED).filter(function(cls) {
                    return cls.model_.requires && cls.model_.requires.map(function(r) { return r.path; }).includes(path); }).sort(foam.core.Model.ID.compare)});
                })).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Axiom Definition'}).
                add(this.slot(function (axiom) { return axiom && foam.u2.DetailView.create({data: axiom.axiom}); })).
              end().
            end().
          end().
        end();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'DocBrowserWindow',

  requires: [
    'foam.doc.DocBrowser',
    'foam.core.Window'
  ],

  imports: [ 'window' ],

  properties: [
    'initialClass'
  ],

  methods: [
    function init() {
      // TODO: There should be some helper support to make this easier
      var w = this.window.open('', '', 'width=700, heigh=1000');
      var window = foam.core.Window.create({window: w});
      var browser = this.DocBrowser.create({path: this.initialClass}, window.__subContext__);
      w.document.body.insertAdjacentHTML('beforeend', browser.outerHTML);
      browser.load();
    }
  ]
});

foam.debug.doc = function(opt_obj, showUnused) {
  if ( showUnused ) {
    for ( var key in foam.UNUSED ) foam.lookup(key);
  }

  foam.doc.DocBrowserWindow.create({
    initialClass: foam.core.FObject.isSubClass(opt_obj) ?
      opt_obj.id :
      ( opt_obj && opt_obj.cls_ ) ? opt_obj.cls_.id :
      'foam.core.FObject' });
};<commit_msg>Fixed typo.<commit_after>foam.CLASS({
  package: 'foam.doc',
  name: 'DocBorder',
  extends: 'foam.u2.Element',

  axioms: [
    foam.u2.CSS.create({
      code: function() {/*
        ^ { background: gray; padding: 10px; display: inline-block; }
        ^title { padding: 6px; align-content: center; background: aliceblue; }
        ^content { padding: 6px; min-width: 220px; height: 100%; background: white; }
      */}
    })
  ],

  properties: [
    'title'
  ],

  methods: [
    function init() {
      this.
        cssClass(this.myCls()).
        start('div').cssClass(this.myCls('title')).add(this.title$).end().
        start('div', null, this.content$).
          cssClass(this.myCls('content')).
        end();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'AxiomInfo',
  ids: ['name'],

  properties: [
    {
      name: 'axiom',
      hidden: true
    },
    {
      name: 'cls',
      label: 'Source Class',
      tableCellView: function(o, e) {
        return foam.doc.LinkView.create({data: o.cls}, e.__subSubContext__);
      },
      tableCellFormatter: function(value, obj, axiom) {
        this.tag(foam.doc.LinkView, { data: value });
      }
    },
    {
      name: 'type',
      tableCellView: function(o, e) {
        return o.type ?
          foam.doc.LinkView.create({data: foam.doc.Link.create({path: o.type.id, label: o.type.name})}, e.__subSubContext__) :
          'anonymous';
      },
      tableCellFormatter: function(value, obj, axiom) {
        if ( value ) {
          this.tag(foam.doc.LinkView, { data: foam.doc.Link.create({ path: value.id, label: value.name }) });
          return;
        }
        this.add('anonymous');
      }
    },
    {
      name: 'name'
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'ClassList',
  extends: 'foam.u2.View',

  requires: [
    'foam.doc.ClassLink'
  ],

  methods: [
    function initE() {
      this.SUPER();

      var self = this;

      this.add('(', this.data.length, ')').br();

      this.data.forEach(function(cls) {
        self.start(self.ClassLink, {data: cls, showPackage: true}).end().br();
      });
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'ClassDocView',
  extends: 'foam.u2.View',

  requires: [
    'foam.doc.Link',
    'foam.doc.ClassLink',
    'foam.doc.AxiomInfo',
    'foam.u2.view.TableView',
    'foam.dao.ArrayDAO'
  ],

  imports: [
    'selectedAxiom'
  ],

  properties: [
    {
      class: 'Boolean',
      name: 'showInherited',
      value: true
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      var data = this.data;

      this.add('CLASS: ', data.name, ' (', data.count_, ')').br();
      this.add('extends: ');
      var cls = data;
      for ( var i = 0 ; cls ; i++ ) {
        cls = this.lookup(cls.model_.extends, true);
        if ( i ) this.add(' : ');
        this.start(this.ClassLink, {data: cls}).end();
        if ( cls === foam.core.FObject ) break;
      }
      this.br();
      this.add(data.documentation);

      this.add('Show Inherited: ').start(this.SHOW_INHERITED, {data$: this.showInherited$}).end();

      this.add(this.slot(function (showInherited) {
        // TODO: hide 'Source Class' column if showInherited is false
        var axs = [];
        for ( var key in data.axiomMap_ ) {
          if ( showInherited || Object.hasOwnProperty.call(data.axiomMap_, key) ) {
            var a  = data.axiomMap_[key];
            var ai = foam.doc.AxiomInfo.create({
              axiom: a,
              type: a.cls_,
              cls: this.Link.create({
                path: a.sourceCls_.id,
                label: a.sourceCls_.name
              }),
              name: a.name
            });
            axs.push(ai);
          }
        }

        return this.TableView.create({
          of: this.AxiomInfo,
          data: this.ArrayDAO.create({array: axs}),
          hoverSelection$: this.selectedAxiom$
        });
      }));
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'Link',

  properties: [
    'path',
    'label'
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'LinkView',
  extends: 'foam.u2.View',

  imports: [ 'browserPath' ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('a').
        on('click', this.click).
        attrs({href: this.data.path}).
        add(this.data.label);
    }
  ],

  listeners: [
    function click(e) {
      this.browserPath$.set(this.data.path);
      e.preventDefault();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'ClassLink',
  extends: 'foam.u2.View',

  imports: [ 'browserPath' ],

  properties: [
    {
      class: 'Class',
      name: 'data'
    },
    {
      class: 'Boolean',
      name: 'showPackage'
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('a').
        on('click', this.click).
        attrs({href: this.data.id}).
        add(this.showPackage ? this.data.id : this.data.name);
    }
  ],

  listeners: [
    function click(e) {
      this.browserPath$.set(this.data.id);
      e.preventDefault();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'DocBrowser',
  extends: 'foam.u2.Element',

  requires: [
    'foam.doc.DocBorder',
    'foam.doc.ClassList',
    'foam.doc.ClassDocView'
  ],

  exports: [
    'as data',
    'path as browserPath',
    'axiom as selectedAxiom'
  ],

  properties: [
    'path',
    {
      class: 'FObjectProperty',
      name: 'axiom',
      view: { class: 'foam.u2.DetailView' }
    }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.tag(this.PATH, {displayWidth: 80}).br().br();

      this.
        start('table').
          start('tr').
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Class List'}).
                start(this.ClassList, {data: Object.values(foam.USED).sort(foam.core.Model.ID.compare)}).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Class Definition'}).
                add(this.slot(function(path) {
                  var o = foam.lookup(path, true);
                  if ( ! o ) return '';
                  return this.ClassDocView.create({data: o});
                })).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Sub-Classes'}).
                add(this.slot(function(path) {
                  var o = foam.lookup(path, true);
                  if ( ! o ) return '';
                  return this.ClassList.create({data: Object.values(foam.USED).filter(function(cls) { return cls.model_.extends == path || 'foam.core.' + cls.model_.extends == path; }).sort(foam.core.Model.ID.compare)});
                })).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Required-By'}).
                add(this.slot(function(path) {
                  var o = foam.lookup(path, true);
                  if ( ! o ) return '';
                  // TODO: this could be done more efficiently, and memoized
                  return this.ClassList.create({data: Object.values(foam.USED).filter(function(cls) {
                    return cls.model_.requires && cls.model_.requires.map(function(r) { return r.path; }).includes(path); }).sort(foam.core.Model.ID.compare)});
                })).
              end().
            end().
            start('td').
              style({'vertical-align': 'top'}).
              start(this.DocBorder, {title: 'Axiom Definition'}).
                add(this.slot(function (axiom) { return axiom && foam.u2.DetailView.create({data: axiom.axiom}); })).
              end().
            end().
          end().
        end();
    }
  ]
});

foam.CLASS({
  package: 'foam.doc',
  name: 'DocBrowserWindow',

  requires: [
    'foam.doc.DocBrowser',
    'foam.core.Window'
  ],

  imports: [ 'window' ],

  properties: [
    'initialClass'
  ],

  methods: [
    function init() {
      // TODO: There should be some helper support to make this easier
      var w = this.window.open('', '', 'width=700, heigh=1000');
      var window = foam.core.Window.create({window: w});
      var browser = this.DocBrowser.create({path: this.initialClass}, window.__subContext__);
      w.document.body.insertAdjacentHTML('beforeend', browser.outerHTML);
      browser.load();
    }
  ]
});

foam.debug.doc = function(opt_obj, showUnused) {
  if ( showUnused ) {
    for ( var key in foam.UNUSED ) foam.lookup(key);
  }

  foam.doc.DocBrowserWindow.create({
    initialClass: foam.core.FObject.isSubClass(opt_obj) ?
      opt_obj.id :
      ( opt_obj && opt_obj.cls_ ) ? opt_obj.cls_.id :
      'foam.core.FObject' });
};<|endoftext|>


<commit_before>// Fake AJAX with DOM, single AJAX call. Response test data is loaded using .loadTestData.

describe("showing questions", function() {
  beforeEach(function() {
    setFixtures('<button class="showQuestions"/>

');
    sut.setupQuestionsBehavior();
  });

  describe("succeeds", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/questions/list": {successData: loadTestData(".questions", "fake-ajax-fixture.html")}}});
      $(".showQuestions").click();
    });

    it("shows the list of questions fetched from server", function() {
      expect($(".question").length).toEqual(3);
      expect($(".question").last()).toHaveText("Question 3");
    });
  });

  describe("fails", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/questions/list": {errorMessage: "Failed loading questions."}}});
      $(".showQuestions").click();
    });

    it("shows error message from server", function() {
      expect($(".questions")).toHaveText("Failed loading questions.");
    });
  });
});

// Fake AJAX without DOM.

describe(".countResponseLength", function() {
  describe("succeeds", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/succeeds": {successData: "Jasmine FTW!"}}});
    });

    it("counts response length", function() {
      expect(sut.countResponseLength({url: "/succeeds"})).toEqual(12);
    });
  });

  describe("fails", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/fails": {errorMessage: "argh"}}});
    });

    it("yields given default value", function() {
      expect(sut.countResponseLength({url: "/fails", defaultOnError: 666})).toEqual(666);
    });

    it("executes given error handler", function() {
      var errorMessage;
      function errorHandler(xhr) {
        errorMessage = xhr.responseText;
      }
      sut.countResponseLength({url: "/fails", errorHandler: errorHandler})
      expect(errorMessage).toEqual("argh");
    });
  });
});

// Multiple related AJAX calls, some succeed, some fail.

describe("clicking question", function() {
  describe("author is not available", function() {
    beforeEach(function() {
      setFixtures('

q1

q2

');
      sut.setupAnswersBehavior();
      fakeAjax({
        urls: {
          "/answers/get?questionId=question2": {successData: loadTestData(".answer2", "fake-ajax-fixture.html")},
          "/authors/get?answerId=answer2": {errorMessage: "author data not available"},
          "/onError": {successData: "Please try again later."}
        }
      });
      $(".questions li").last().click();
    });

    it("shows answer", function() {
      expect($(".answer")).toHaveText("Answer 2");
    });

    it("shows error message instead of author details", function() {
      expect($(".author")).toHaveText("Please try again later.");
    });
  });
});

// When we only need to check the request URL.

describe(".latestAjaxUrlMatching", function() {
  beforeEach(function() {
    sut.setupMultipleAjaxCalls();
  });

  it("sends expected params", function() {
    expect(latestAjaxUrlMatching("second")).toContain("foo=bar");
    expect(latestAjaxUrlMatching("fir")).toContain("p1=v1");
  });
});

// When response is expected to be in JSON format ($.getJSON is called in SUT).

describe("showing user info", function() {
  beforeEach(function() {
    setFixtures('<button class="showUser"/>

');
    sut.setupUserBehavior();
    fakeAjax({urls: {"/user": {successData: {name: "John", age: 30}}}});
    $('.showUser').click();
  });

  it("shows name", function() {
    expect($('.user .name')).toHaveText('John');
  });

  it("shows age", function() {
    expect($('.user .age')).toHaveText('30');
  });
});

describe("after each spec", function() {
  it("context is cleared", function() {
    expect(jasmine.FakeAjax.urls).toBeFalsy();
  });
});
<commit_msg>Add first logging test.<commit_after>// Fake AJAX with DOM, single AJAX call. Response test data is loaded using .loadTestData.

describe("showing questions", function() {
  beforeEach(function() {
    setFixtures('<button class="showQuestions"/>

');
    sut.setupQuestionsBehavior();
  });

  describe("succeeds", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/questions/list": {successData: loadTestData(".questions", "fake-ajax-fixture.html")}}});
      $(".showQuestions").click();
    });

    it("shows the list of questions fetched from server", function() {
      expect($(".question").length).toEqual(3);
      expect($(".question").last()).toHaveText("Question 3");
    });
  });

  describe("fails", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/questions/list": {errorMessage: "Failed loading questions."}}});
      $(".showQuestions").click();
    });

    it("shows error message from server", function() {
      expect($(".questions")).toHaveText("Failed loading questions.");
    });
  });
});

// Fake AJAX without DOM.

describe(".countResponseLength", function() {
  describe("succeeds", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/succeeds": {successData: "Jasmine FTW!"}}});
    });

    it("counts response length", function() {
      expect(sut.countResponseLength({url: "/succeeds"})).toEqual(12);
    });
  });

  describe("fails", function() {
    beforeEach(function() {
      fakeAjax({urls: {"/fails": {errorMessage: "argh"}}});
    });

    it("yields given default value", function() {
      expect(sut.countResponseLength({url: "/fails", defaultOnError: 666})).toEqual(666);
    });

    it("executes given error handler", function() {
      var errorMessage;
      function errorHandler(xhr) {
        errorMessage = xhr.responseText;
      }
      sut.countResponseLength({url: "/fails", errorHandler: errorHandler})
      expect(errorMessage).toEqual("argh");
    });
  });
});

// Multiple related AJAX calls, some succeed, some fail.

describe("clicking question", function() {
  describe("author is not available", function() {
    beforeEach(function() {
      setFixtures('

q1

q2

');
      sut.setupAnswersBehavior();
      fakeAjax({
        urls: {
          "/answers/get?questionId=question2": {successData: loadTestData(".answer2", "fake-ajax-fixture.html")},
          "/authors/get?answerId=answer2": {errorMessage: "author data not available"},
          "/onError": {successData: "Please try again later."}
        }
      });
      $(".questions li").last().click();
    });

    it("shows answer", function() {
      expect($(".answer")).toHaveText("Answer 2");
    });

    it("shows error message instead of author details", function() {
      expect($(".author")).toHaveText("Please try again later.");
    });
  });
});

// When we only need to check the request URL.

describe(".latestAjaxUrlMatching", function() {
  beforeEach(function() {
    sut.setupMultipleAjaxCalls();
  });

  it("sends expected params", function() {
    expect(latestAjaxUrlMatching("second")).toContain("foo=bar");
    expect(latestAjaxUrlMatching("fir")).toContain("p1=v1");
  });
});

// When response is expected to be in JSON format ($.getJSON is called in SUT).

describe("showing user info", function() {
  beforeEach(function() {
    setFixtures('<button class="showUser"/>

');
    sut.setupUserBehavior();
    fakeAjax({urls: {"/user": {successData: {name: "John", age: 30}}}});
    $('.showUser').click();
  });

  it("shows name", function() {
    expect($('.user .name')).toHaveText('John');
  });

  it("shows age", function() {
    expect($('.user .age')).toHaveText('30');
  });
});

describe("after each spec", function() {
  it("context is cleared", function() {
    expect(jasmine.FakeAjax.urls).toBeFalsy();
  });
});

describe("logging", function() {
  var latestWarning;
  jasmine.FakeAjax.log.warn = function(message) {
    latestWarning = message;
  };

  describe("without url mappings", function() {
    beforeEach(function() {
      $.get('/example');
    });

    it("logs warning", function() {
      expect(latestWarning).toEqual('There are no ajax url mappings defined.');
    });
  });
});
<|endoftext|>


<commit_before>import fs from "fs";
import path from "path";
import chalk from "chalk";
import sha1 from "sha1";
import updatePackage from "./update-package";

/**
 * Let the user know that we are updating the file and copy the contents over.
 *
 * @param {String} name the name of the file
 * @param {String} data the data for the new file
 */
function replaceFile (name, data) {
  const filePath = getCurrentFilePath(name);
  console.log(chalk.yellow(`${name} file out of date.`));
  console.log(chalk.green(`Updating ${filePath}`));

  fs.writeFileSync(filePath, data);
}

/**
 * Get the path to the file in the current project's config folder.
 *
 * @param {String} name the file name we are looking for
 */
function getCurrentFilePath (name) {
  return path.join(process.cwd(), "src", "config", name);
}

module.exports = async function () {
  await updatePackage();

  // Make sure we are in a gluestick project
  try {
    fs.statSync(path.join(process.cwd(), ".gluestick"))
  }
  catch (e) {
    console.log(chalk.red("This does not appear to be a valid GlueStick project. Please run this command inside of a gluestick project"));
    process.exit();
  }

  // Compare contents of our hidden files, if they do not match up then auto
  // update
  [".entry.js", ".store.js"].forEach((fileName) => {
    const currentFile = fs.readFileSync(getCurrentFilePath(fileName));
    const currentSha = sha1(currentFile);

    const newFile = fs.readFileSync(path.join(__dirname, "..", "new", "src", "config", fileName), "utf8");
    const newSha = sha1(newFile);

    if (currentSha !== newSha) {
      replaceFile(fileName, newFile);
    }
  });

  // If there is no src/config/application.js file make one now (This is to upgrade apps created prior to 0.1.6)
  try {
    fs.statSync(path.join(process.cwd(), "src/config/application.js"))
  }
  catch (e) {
    const newApplicationConfigFile = fs.readFileSync(path.join(__dirname, "..", "new", "src", "config", "application.js"), "utf8");
    replaceFile("application.js", newApplicationConfigFile);
  }
};

<commit_msg>Autoupgrade can easily support adding mulitple files as Gluestick progresses<commit_after>import fs from "fs";
import path from "path";
import chalk from "chalk";
import sha1 from "sha1";
import updatePackage from "./update-package";

/**
 * Let the user know that we are updating the file and copy the contents over.
 *
 * @param {String} name the name of the file
 * @param {String} data the data for the new file
 */
function replaceFile (name, data) {
  const filePath = getCurrentFilePath(name);
  console.log(chalk.yellow(`${name} file out of date.`));
  console.log(chalk.green(`Updating ${filePath}`));

  fs.writeFileSync(filePath, data);
}

/**
 * Get the path to the file in the current project's config folder.
 *
 * @param {String} name the file name we are looking for
 */
function getCurrentFilePath (name) {
  return path.join(process.cwd(), "src", "config", name);
}

module.exports = async function () {
  await updatePackage();

  // Make sure we are in a gluestick project
  try {
    fs.statSync(path.join(process.cwd(), ".gluestick"))
  }
  catch (e) {
    console.log(chalk.red("This does not appear to be a valid GlueStick project. Please run this command inside of a gluestick project"));
    process.exit();
  }

  // Compare contents of our hidden files, if they do not match up then auto
  // update
  [".entry.js", ".store.js"].forEach((fileName) => {
    const currentFile = fs.readFileSync(getCurrentFilePath(fileName));
    const currentSha = sha1(currentFile);

    const newFile = fs.readFileSync(path.join(__dirname, "..", "new", "src", "config", fileName), "utf8");
    const newSha = sha1(newFile);

    if (currentSha !== newSha) {
      replaceFile(fileName, newFile);
    }
  });

  // Check for certain files that we've added to new Gluestick applications. If those files don't exist, add them
  // for the user.
  const newFiles = [
    "src/config/application.js",      //-> prior to 0.1.6
    "src/config/redux-middleware.js"  //-> prior to 0.1.12
  ];
  newFiles.forEach((filePath) => {
    try {
      fs.statSync(path.join(process.cwd(), filePath));
    }
    catch (e) {
      const fileName = path.parse(filePath).base;
      const newFile = fs.readFileSync(path.join(__dirname, "..", "new", filePath), "utf8");
      replaceFile(fileName, newFile);
    }
  });
};
<|endoftext|>


<commit_before>var utils = require('../utils')
var Issue = utils.issues.Issue

// Match sub-.../... files, except sub-emptyroom
const matchSubjectPath = file =>
  file.relativePath.match(/sub-((?!emptyroom).)*(?=\/)/)

// Helper for filtering unique values in an array
const uniqueArray = (value, index, self) => self.indexOf(value) === index

/**
 * Find unique subjects from FileList
 * @param {FileList} fileList Browser FileList or Node equivalent
 */
const getFolderSubjects = fileList =>
  Array.from(fileList)
    .filter(matchSubjectPath)
    .map(f => matchSubjectPath(f)[1])
    .filter(uniqueArray)

/**
 * checkAnyDataPresent
 *
 * Takes a list of files and participants with valid data. Checks if they match.
 */
function checkAnyDataPresent(fileList, summarySubjects) {
  var issues = []
  var folderSubjects = getFolderSubjects(fileList)
  var subjectsWithoutAnyValidData = folderSubjects.filter(function(i) {
    return summarySubjects.indexOf(i) < 0
  })

  for (var i = 0; i < subjectsWithoutAnyValidData.length; i++) {
    var missingSubject = subjectsWithoutAnyValidData[i]
    var subFolder = '/sub-' + missingSubject
    issues.push(
      new Issue({
        file: {
          relativePath: subFolder,
          webkitRelativePath: subFolder,
          name: subFolder,
          path: subFolder,
        },
        reason: 'No BIDS compatible data found for subject ' + missingSubject,
        code: 67,
      }),
    )
  }
  return issues
}

module.exports = checkAnyDataPresent
module.exports.getFolderSubjects = getFolderSubjects
<commit_msg>Fix regexp for nested subject folders in getFolderSubjects<commit_after>var utils = require('../utils')
var Issue = utils.issues.Issue

// Match sub-.../... files, except sub-emptyroom
const matchSubjectPath = file =>
  file.relativePath.match(/sub-((?!emptyroom).)*?(?=\/)/)

// Helper for filtering unique values in an array
const uniqueArray = (value, index, self) => self.indexOf(value) === index

/**
 * Find unique subjects from FileList
 * @param {FileList} fileList Browser FileList or Node equivalent
 */
const getFolderSubjects = fileList =>
  Array.from(fileList)
    .filter(matchSubjectPath)
    .map(f => matchSubjectPath(f)[1])
    .filter(uniqueArray)

/**
 * checkAnyDataPresent
 *
 * Takes a list of files and participants with valid data. Checks if they match.
 */
function checkAnyDataPresent(fileList, summarySubjects) {
  var issues = []
  var folderSubjects = getFolderSubjects(fileList)
  var subjectsWithoutAnyValidData = folderSubjects.filter(function(i) {
    return summarySubjects.indexOf(i) < 0
  })

  for (var i = 0; i < subjectsWithoutAnyValidData.length; i++) {
    var missingSubject = subjectsWithoutAnyValidData[i]
    var subFolder = '/sub-' + missingSubject
    issues.push(
      new Issue({
        file: {
          relativePath: subFolder,
          webkitRelativePath: subFolder,
          name: subFolder,
          path: subFolder,
        },
        reason: 'No BIDS compatible data found for subject ' + missingSubject,
        code: 67,
      }),
    )
  }
  return issues
}

module.exports = checkAnyDataPresent
module.exports.getFolderSubjects = getFolderSubjects
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

YUI.add('PagerMojitModel-tests', function(Y) {

    var suite = new YUITest.TestSuite('PagerMojitModel-tests'),
        model = null,
        A = YUITest.Assert;

    suite.add(new YUITest.TestCase({

        name: 'PagerMojit model user tests',

        setUp: function() {
            model = Y.mojito.models.PagerMojit;
        },
        tearDown: function() {
            model = null;
        },

        'test mojit model': function() {
            A.isNotNull(model);
            A.isFunction(model.getData);
        }

    }));

    YUITest.TestRunner.add(suite);

}, '0.0.1', {requires: ['mojito-test', 'PagerMojitModel']});
<commit_msg>Fixed a model test. Made sure all tests run.<commit_after>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

YUI.add('PagerMojitModel-tests', function(Y, NAME) {

    var suite = new YUITest.TestSuite('PagerMojitModel-tests'),
        model = null,
        A = YUITest.Assert;

    suite.add(new YUITest.TestCase({

        name: 'PagerMojit model user tests',

        setUp: function() {
            Y.log(Y.mojito.models);
            model = Y.mojito.models.PagerMojitModel;
        },
        tearDown: function() {
            model = null;
        },

        'test mojit model': function() {
            A.isNotNull(model);
            A.isFunction(model.getData);
        }

    }));

    YUITest.TestRunner.add(suite);

}, '0.0.1', {requires: ['mojito-test', 'PagerMojitModel']});
<|endoftext|>


<commit_before>// @flow

import React from 'react'
import PropTypes from 'prop-types'
import serializeError from 'serialize-error'
import Button from '../../components/button'
import {
	convertStudent,
	semesterName,
	type PartialStudent,
} from '@gob/school-st-olaf-college'
import {getCourse} from '../../helpers/get-courses'
import {StudentSummary} from '../../modules/student/student-summary'
import map from 'lodash/map'
import groupBy from 'lodash/groupBy'
import sortBy from 'lodash/sortBy'
import {initStudent} from '../../redux/students/actions/init-student'
import {connect} from 'react-redux'
import withRouter from 'react-router/lib/withRouter'
import debug from 'debug'
const log = debug('web:react')
import './method-import.scss'

import type {
	HydratedStudentType,
	HydratedScheduleType,
} from '@gob/object-student'

type Props = {
	+dispatch: Function,
	+router: Object,
}

type State = {
	status: 'pending' | 'processing' | 'ready',
	error: ?Error,
	ids: Array<mixed>,
	selectedId: ?number,
	student: ?HydratedStudentType,
	rawStudentText: string,
	parsedStudentText: ?PartialStudent,
}

class SISImportScreen extends React.Component<Props, State> {
	static propTypes = {
		dispatch: PropTypes.func.isRequired, // redux
		router: PropTypes.object.isRequired,
	}

	state = {
		status: 'pending',
		error: null,
		ids: [],
		selectedId: null,
		student: null,
		rawStudentText: '',
		parsedStudentText: null,
	}

	handleImportData = async () => {
		let {parsedStudentText} = this.state
		if (!parsedStudentText) {
			this.setState(() => ({error: new Error('no data to import!')}))
			return
		}

		this.setState(() => ({status: 'processing'}))

		try {
			let student = await convertStudent(parsedStudentText, getCourse)
			this.setState(() => ({student}))
		} catch (error) {
			console.warn(error)
			this.setState(() => ({error: serializeError(error)}))
		}
	}

	handleCreateStudent = () => {
		let action = initStudent(this.state.student)
		this.props.dispatch(action)
		this.props.router.push(`/s/${action.payload.id}`)
	}

	handleRawStudent = (ev: SyntheticInputEvent<HTMLTextAreaElement>) => {
		ev.preventDefault()

		let data = ev.currentTarget.value

		this.setState(() => ({rawStudentText: data}))

		this.setState(
			() => {
				try {
					return {parsedStudentText: JSON.parse(data)}
				} catch (error) {
					console.warn(error)
					return {error}
				}
			},
			() => {
				this.handleImportData()
			},
		)
	}

	render() {
		let {student, error, parsedStudentText} = this.state

		return (

Import from the SIS

					This is a Work-In-Progress. It may not work
					at all!

					To import your student data from St. Olaf's SIS, follow the
					following steps:

						Open{' '}

							stolaf.edu/sis/st-courses-json.cfm
						{' '}
						in a new tab

Copy the text from the text box (all of it)

Paste the text into the text box below

				<textarea
					style={{width: '100%', height: '100px'}}
					value={this.state.rawStudentText}
					onChange={this.handleRawStudent}
					placeholder="Paste the gibberish here"
				/>

				{parsedStudentText && (

						Parsed student data

{JSON.stringify(parsedStudentText, null, 2)}

				)}

				{error ? (

							{error.name}: {error.message}

{error.stack}

				) : null}

				{student ? <StudentInfo student={student} /> : null}

					{student && (
						<Button onClick={this.handleCreateStudent}>
							Import Student
						</Button>
					)}

		)
	}
}

const StudentInfo = ({student}: {student: HydratedStudentType}) => (

		<StudentSummary student={student} showMessage={false} />

			{map(
				groupBy(student.schedules, s => s.year),
				(schedules: Array<HydratedScheduleType>, year) => (

						{year}:

							{sortBy(schedules, s => s.semester).map(
								(schedule: HydratedScheduleType) => (

										{semesterName(schedule.semester)}:

											{(schedule.courses || []).map(
												course => (

														{course.department}{' '}
														{course.number}
														{course.section} –{' '}
														{course.name}

												),
											)}

								),
							)}

				),
			)}

)

let mapDispatch = dispatch => ({dispatch})

export default connect(
	undefined,
	mapDispatch,
)(withRouter(SISImportScreen))
<commit_msg>remove unused import<commit_after>// @flow

import React from 'react'
import PropTypes from 'prop-types'
import serializeError from 'serialize-error'
import Button from '../../components/button'
import {
	convertStudent,
	semesterName,
	type PartialStudent,
} from '@gob/school-st-olaf-college'
import {getCourse} from '../../helpers/get-courses'
import {StudentSummary} from '../../modules/student/student-summary'
import map from 'lodash/map'
import groupBy from 'lodash/groupBy'
import sortBy from 'lodash/sortBy'
import {initStudent} from '../../redux/students/actions/init-student'
import {connect} from 'react-redux'
import withRouter from 'react-router/lib/withRouter'
import './method-import.scss'

import type {
	HydratedStudentType,
	HydratedScheduleType,
} from '@gob/object-student'

type Props = {
	+dispatch: Function,
	+router: Object,
}

type State = {
	status: 'pending' | 'processing' | 'ready',
	error: ?Error,
	ids: Array<mixed>,
	selectedId: ?number,
	student: ?HydratedStudentType,
	rawStudentText: string,
	parsedStudentText: ?PartialStudent,
}

class SISImportScreen extends React.Component<Props, State> {
	static propTypes = {
		dispatch: PropTypes.func.isRequired, // redux
		router: PropTypes.object.isRequired,
	}

	state = {
		status: 'pending',
		error: null,
		ids: [],
		selectedId: null,
		student: null,
		rawStudentText: '',
		parsedStudentText: null,
	}

	handleImportData = async () => {
		let {parsedStudentText} = this.state
		if (!parsedStudentText) {
			this.setState(() => ({error: new Error('no data to import!')}))
			return
		}

		this.setState(() => ({status: 'processing'}))

		try {
			let student = await convertStudent(parsedStudentText, getCourse)
			this.setState(() => ({student}))
		} catch (error) {
			console.warn(error)
			this.setState(() => ({error: serializeError(error)}))
		}
	}

	handleCreateStudent = () => {
		let action = initStudent(this.state.student)
		this.props.dispatch(action)
		this.props.router.push(`/s/${action.payload.id}`)
	}

	handleRawStudent = (ev: SyntheticInputEvent<HTMLTextAreaElement>) => {
		ev.preventDefault()

		let data = ev.currentTarget.value

		this.setState(() => ({rawStudentText: data}))

		this.setState(
			() => {
				try {
					return {parsedStudentText: JSON.parse(data)}
				} catch (error) {
					console.warn(error)
					return {error}
				}
			},
			() => {
				this.handleImportData()
			},
		)
	}

	render() {
		let {student, error, parsedStudentText} = this.state

		return (

Import from the SIS

					This is a Work-In-Progress. It may not work
					at all!

					To import your student data from St. Olaf's SIS, follow the
					following steps:

						Open{' '}

							stolaf.edu/sis/st-courses-json.cfm
						{' '}
						in a new tab

Copy the text from the text box (all of it)

Paste the text into the text box below

				<textarea
					style={{width: '100%', height: '100px'}}
					value={this.state.rawStudentText}
					onChange={this.handleRawStudent}
					placeholder="Paste the gibberish here"
				/>

				{parsedStudentText && (

						Parsed student data

{JSON.stringify(parsedStudentText, null, 2)}

				)}

				{error ? (

							{error.name}: {error.message}

{error.stack}

				) : null}

				{student ? <StudentInfo student={student} /> : null}

					{student && (
						<Button onClick={this.handleCreateStudent}>
							Import Student
						</Button>
					)}

		)
	}
}

const StudentInfo = ({student}: {student: HydratedStudentType}) => (

		<StudentSummary student={student} showMessage={false} />

			{map(
				groupBy(student.schedules, s => s.year),
				(schedules: Array<HydratedScheduleType>, year) => (

						{year}:

							{sortBy(schedules, s => s.semester).map(
								(schedule: HydratedScheduleType) => (

										{semesterName(schedule.semester)}:

											{(schedule.courses || []).map(
												course => (

														{course.department}{' '}
														{course.number}
														{course.section} –{' '}
														{course.name}

												),
											)}

								),
							)}

				),
			)}

)

let mapDispatch = dispatch => ({dispatch})

export default connect(
	undefined,
	mapDispatch,
)(withRouter(SISImportScreen))
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('<%=angularAppName%>')
        .factory('ProfileService', ProfileService);

    ProfileService.$inject = ['$q', '$resource'];

    function ProfileService($q, $resource) {

        var dataPromise;

        var service = {
            profileInfo : profileInfo
        };

        return service;

        function rest() {

            return $resource('api/activeProfiles', {}, {
                'get' : {
                    method : 'GET',
                    params : {},
                    isArray : false,
                    interceptor : {
                        response : function(response) {
                            // expose response
                            return response;
                        }
                    }
                }
            });
        }

        function profileInfo() {
            if (dataPromise===null) {
                dataPromise = rest().get().$promise.then(function(result) {
                    if (result.data.activeProfiles) {
                        var response = {};
                        response.activeProfiles = result.data.activeProfiles;
                        response.ribbonEnv = result.data.ribbonEnv;
                        response.inProduction = result.data.activeProfiles.indexOf("prod") !== -1;
                        return response;
                    }
                });
            }
            return dataPromise;
        }
    }
})();
<commit_msg>fixed undefined check<commit_after>(function() {
    'use strict';

    angular
        .module('<%=angularAppName%>')
        .factory('ProfileService', ProfileService);

    ProfileService.$inject = ['$q', '$resource'];

    function ProfileService($q, $resource) {

        var dataPromise;

        var service = {
            profileInfo : profileInfo
        };

        return service;

        function rest() {

            return $resource('api/activeProfiles', {}, {
                'get' : {
                    method : 'GET',
                    params : {},
                    isArray : false,
                    interceptor : {
                        response : function(response) {
                            // expose response
                            return response;
                        }
                    }
                }
            });
        }

        function profileInfo() {
            if (!angular.isDefined(dataPromise)) {
                dataPromise = rest().get().$promise.then(function(result) {
                    if (result.data.activeProfiles) {
                        var response = {};
                        response.activeProfiles = result.data.activeProfiles;
                        response.ribbonEnv = result.data.ribbonEnv;
                        response.inProduction = result.data.activeProfiles.indexOf("prod") !== -1;
                        return response;
                    }
                });
            }
            return dataPromise;
        }
    }
})();
<|endoftext|>


<commit_before>/**
 * When used inside `Array.prototype.sort()`, sorts
 * the array in ascending alphabetical order.
 *
 * @category Sort
 *
 * @return {Array} The array in ascending alphabetical order.
 *
 * @example
 * let names = ["Athos", "Porthos", "Aramis"];
 * names.sort(byAlphabeticalOrder());
 * // => ["Aramis", "Athos", "Porthos"]
 */
const byAlphabeticalOrder = () => (strA, strB) => (strA > strB) ? +1 : (strA < strB) ? -1 : 0;

export default byAlphabeticalOrder;
<commit_msg>minor adjustments to docs<commit_after>/**
 * When used inside `Array.prototype.sort()`, sorts
 * the array in ascending alphabetical order.
 *
 * @category Sort
 *
 * @return {Array} The array in ascending alphabetical order.
 *
 * @example
 * let musqueteers = ["Athos", "Porthos", "Aramis"];
 * musqueteers.sort(byAlphabeticalOrder());
 * // => ["Aramis", "Athos", "Porthos"]
 */
const byAlphabeticalOrder = () => (strA, strB) => (strA > strB) ? +1 : (strA < strB) ? -1 : 0;

export default byAlphabeticalOrder;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2.layout',
  name: 'Grid',
  extends: 'foam.u2.Element',
  documentation: `
    A grid of responsive elements
  `,

  imports: [
    'displayWidth?'
  ],

  requires: [
    'foam.u2.layout.GUnit'
  ],

  css: `
    ^ {
      display: grid;
      grid-template-columns: repeat(12, 1fr);
    }
  `,

  properties: [
    {
      class: 'Int',
      name: 'currentWidth',
      value: 0
    }
  ],

  methods: [
    function initE() {
      this.SUPER();
      this.addClass(this.myClass());
      this.style({ 'grid-template-columns': this.displayWidth$.map(dw => {
        dw = dw || foam.u2.layout.DisplayWidth.XL;
        return `repeat(${dw.cols}, 1fr)`;
      }) })
    },

    function createChild_(spec, args){
      var ret = this.SUPER(spec, args);

      var width = this.GUnit.isInstance(ret)
        ? ret.columns
        : this.displayWidth.cols;

      var startCol = this.currentWidth + 1;
      this.currentWidth += width;

      if ( this.currentWidth > this.displayWidth.cols ) {
        startCol = 1;
        this.currentWidth = width;
      }

      var endCol = startCol + width;

      ret.style({
        'grid-column-start': startCol,
        'grid-column-end': endCol,
      });

      return ret;
    }
  ]
});
<commit_msg>Removed unused grid-template-columns<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2.layout',
  name: 'Grid',
  extends: 'foam.u2.Element',
  documentation: `
    A grid of responsive elements
  `,

  imports: [
    'displayWidth?'
  ],

  requires: [
    'foam.u2.layout.GUnit'
  ],

  css: `
    ^ {
      display: grid;
    }
  `,

  properties: [
    {
      class: 'Int',
      name: 'currentWidth',
      value: 0
    }
  ],

  methods: [
    function initE() {
      this.SUPER();
      this.addClass(this.myClass());
      this.style({ 'grid-template-columns': this.displayWidth$.map(dw => {
        dw = dw || foam.u2.layout.DisplayWidth.XL;
        return `repeat(${dw.cols}, 1fr)`;
      }) })
    },

    function createChild_(spec, args){
      var ret = this.SUPER(spec, args);

      var width = this.GUnit.isInstance(ret)
        ? ret[`${this.displayWidth.name.toLowerCase()}Columns`]
        : this.displayWidth.cols;

      var startCol = this.currentWidth + 1;
      this.currentWidth += width;

      if ( this.currentWidth > this.displayWidth.cols ) {
        startCol = 1;
        this.currentWidth = width;
      }

      var endCol = startCol + width;

      ret.style({
        'grid-column-start': startCol,
        'grid-column-end': endCol,
      });

      return ret;
    }
  ]
});
<|endoftext|>