<commit_before>'use strict';

angular.module('Pear2Pear')
  .factory('ProjectsSvc', ['swellRT', '$q', '$timeout', 'base64', 'SwellRTSession', 'SwellRTCommon', 'ProfilesSvc', function(swellRT, $q, $timeout, base64, SwellRTSession, SwellRTCommon, ProfilesSvc){

    var Project = function(){};

    Project.prototype.addContributor = function(user) {
      if (!user){
        user = SwellRTSession.users.current();
      }
      if (user && this.contributors.indexOf(user) < 0){
        this.contributors.push(user);
      }
    };

    Project.prototype.setShareMode = function(shareMode){
      this.shareMode = shareMode;
    };

    //TODO profiles Service and bring this method there
    Project.prototype.timestampProjectAccess = function(){
      var proj = this;
      ProfilesSvc.current().then(function(profile) {
        profile.lastProjectVisit[proj.id] = (new Date()).toJSON();
      });
    };

    Project.prototype.toogleSupport = function(){
      var index = this.supporters.indexOf(SwellRTSession.users.current());

      if (index > -1) {
        this.supporters.splice(index, 1);
      } else {
        this.supporters.push(SwellRTSession.users.current());
      }
    };

    Project.prototype.addChatMessage = function(message){
      this.chat.push({
          text: message,
          who: SwellRTSession.users.current(),
          time: (new Date()).toJSON()
        });
      this.addContributor();
    };

    Project.prototype.addChatNotification = function(message, translateValues){
      this.chat.push({
        text: message,
        time: (new Date()).toJSON(),
        standpoint: 'notification',
        translateValues: translateValues
      });
    };

    Project.prototype.addNeedComment = function(need, comment){
      if (!need.comments){
        need.comments = [];
      }
      need.comments.push({
        text: comment,
        time: (new Date()).toJSON(),
        author: SwellRTSession.users.current()
      });
    };

    Project.prototype.isSupporter = function(user){
      if (!user){
        user = SwellRTSession.users.current();
      }
      return this.supporters.indexOf(user) > -1;
    };

    // Service functions //

    var openedProjects = {};

    var find = function(urlId) {

      var id = base64.urldecode(urlId);
      var def = $q.defer();
      if (!openedProjects[id]) {
        openedProjects[id] = def.promise;
        SwellRT.openModel(id, function(model){
          $timeout(function(){
            var pr = swellRT.proxy(model, Project);
            def.resolve(pr);
          });
        }, function(error){
          console.log(error);
          def.reject(error);
        });
      }
      return openedProjects[id];
    };

    var create = function(callback, communityId) {
      var d = $q.defer();
      var id = SwellRT.createModel(function(model){
        openedProjects[id] = d.promise;

        SwellRTCommon.makeModelPublic(model);

        var proxyProj;

        $timeout(function(){
          proxyProj = swellRT.proxy(model, Project);
        });

        $timeout(function(){
          proxyProj.type = 'project';
          proxyProj.communities = (communityId) ? [communityId] : [];
          proxyProj.id = id;
          proxyProj.title = '';
          proxyProj.chat = [];
          proxyProj.pad = new swellRT.TextObject();
          proxyProj.needs = [];
          proxyProj.promoter = SwellRTSession.users.current();
          proxyProj.supporters = [];
          proxyProj.contributors = [SwellRTSession.users.current()];
          proxyProj.shareMode = 'link';
          d.resolve(proxyProj);
        });
      });

      d.promise.then(callback);

      return d.promise;
    };

    return {
      find: find,
      create: create
    };
  }]);
<commit_msg>create public projects by default<commit_after>'use strict';

angular.module('Pear2Pear')
  .factory('ProjectsSvc', ['swellRT', '$q', '$timeout', 'base64', 'SwellRTSession', 'SwellRTCommon', 'ProfilesSvc', function(swellRT, $q, $timeout, base64, SwellRTSession, SwellRTCommon, ProfilesSvc){

    var Project = function(){};

    Project.prototype.addContributor = function(user) {
      if (!user){
        user = SwellRTSession.users.current();
      }
      if (user && this.contributors.indexOf(user) < 0){
        this.contributors.push(user);
      }
    };

    Project.prototype.setShareMode = function(shareMode){
      this.shareMode = shareMode;
    };

    //TODO profiles Service and bring this method there
    Project.prototype.timestampProjectAccess = function(){
      var proj = this;
      ProfilesSvc.current().then(function(profile) {
        profile.lastProjectVisit[proj.id] = (new Date()).toJSON();
      });
    };

    Project.prototype.toogleSupport = function(){
      var index = this.supporters.indexOf(SwellRTSession.users.current());

      if (index > -1) {
        this.supporters.splice(index, 1);
      } else {
        this.supporters.push(SwellRTSession.users.current());
      }
    };

    Project.prototype.addChatMessage = function(message){
      this.chat.push({
          text: message,
          who: SwellRTSession.users.current(),
          time: (new Date()).toJSON()
        });
      this.addContributor();
    };

    Project.prototype.addChatNotification = function(message, translateValues){
      this.chat.push({
        text: message,
        time: (new Date()).toJSON(),
        standpoint: 'notification',
        translateValues: translateValues
      });
    };

    Project.prototype.addNeedComment = function(need, comment){
      if (!need.comments){
        need.comments = [];
      }
      need.comments.push({
        text: comment,
        time: (new Date()).toJSON(),
        author: SwellRTSession.users.current()
      });
    };

    Project.prototype.isSupporter = function(user){
      if (!user){
        user = SwellRTSession.users.current();
      }
      return this.supporters.indexOf(user) > -1;
    };

    // Service functions //

    var openedProjects = {};

    var find = function(urlId) {

      var id = base64.urldecode(urlId);
      var def = $q.defer();
      if (!openedProjects[id]) {
        openedProjects[id] = def.promise;
        SwellRT.openModel(id, function(model){
          $timeout(function(){
            var pr = swellRT.proxy(model, Project);
            def.resolve(pr);
          });
        }, function(error){
          console.log(error);
          def.reject(error);
        });
      }
      return openedProjects[id];
    };

    var create = function(callback, communityId) {
      var d = $q.defer();
      var id = SwellRT.createModel(function(model){
        openedProjects[id] = d.promise;

        SwellRTCommon.makeModelPublic(model);

        var proxyProj;

        $timeout(function(){
          proxyProj = swellRT.proxy(model, Project);
        });

        $timeout(function(){
          proxyProj.type = 'project';
          proxyProj.communities = (communityId) ? [communityId] : [];
          proxyProj.id = id;
          proxyProj.title = '';
          proxyProj.chat = [];
          proxyProj.pad = new swellRT.TextObject();
          proxyProj.needs = [];
          proxyProj.promoter = SwellRTSession.users.current();
          proxyProj.supporters = [];
          proxyProj.contributors = [SwellRTSession.users.current()];
          proxyProj.shareMode = 'public';
          d.resolve(proxyProj);
        });
      });

      d.promise.then(callback);

      return d.promise;
    };

    return {
      find: find,
      create: create
    };
  }]);
<|endoftext|>


<commit_before>var irc = require('irc'),
    config = require('./lib/config'),
    strftime = require('strftime'),
    format = require('irc-colors'),
    rawjs = require('raw.js'),
    reddit = new rawjs(config.user_agent),
    latest = 0;

reddit.setupOAuth2(config.app.id, config.app.secret);

var client = new irc.Client(config.irc.host, config.irc.nick, {
  channels: [config.irc.channel],
  messageSplit: 2048
});

client.addListener('registered', function(msg) {
  client.say('NickServ', 'identify ' + config.irc.pass);
});

client.addListener('error', function(err) {
  // if (err.rawCommand != '421') console.log(err);
  log('ERROR in irc client');
  console.log(err);
});

client.addListener('nick', function(oldnick, newnick) {
  log('-- ' + oldnick + ' is now known as ' + newnick);
});

client.addListener('join', function(channel, nick) {
  log('>> ' + nick + ' joined');
});

client.addListener('part', function(channel, nick, reason) {
  log('<< ' + nick + ' left (' + reason + ')');
});

client.addListener('quit', function(nick, reason) {
  log('<< ' + nick + ' quit (' + reason + ')');
});

client.addListener('topic', function(channel, topic, nick) {
  log('!! ' + nick + ' changed the topic to "' + topic + '"');
});

client.addListener('kick', function(channel, nick, by, reason) {
  log('<< ' + nick + ' was kicked by ' + by + '(' + reason + ')');
});

client.addListener('message', function(from, to, msg) {
  log(from + ' ' + to + ' ' + msg);
});

var say = function(msg) {
  client.say(config.irc.channel, msg)
  log(config.irc.nick + ' ' + config.irc.channel + ' ' + msg);
}

var log = function(msg) {
  console.log(strftime('%F %T ') + msg)
}

var debug = function(msg) {
  process.stderr.write(strftime('%T ') + msg + '\n');
}

// check for new r/philippines posts and if any
// are found, post them to the channel
//
var report_new_posts = function() {

  var options = {
    r: 'Philippines',
    limit: 5,
    all: true
  };

  reddit.new(options, function(err, response) {
    if (err) {
      log('ERROR fetching new posts');
      console.log(err);
    } else {
      if (response.children.length) {

        var init = (latest === 0);

        for (var i = response.children.length-1; i >= 0; i--) {
          var post = response.children[i].data;

          if (post.created_utc > latest) {

            latest = post.created_utc;

            if (!init) {

              var msg = 'http://redd.it/' + post.id
                      + ' ' + format.green.bold(post.title)
                      + ' by ' + format.brown.italic(post.author)

              if (post.selftext) {
                msg += ': ' + post.selftext.replace(/\n/g, ' ');;
              }

              say(msg);
            }
          }
        }
      }
    }
  });

  setTimeout(report_new_posts, 30000);
};

setTimeout(report_new_posts, 5000);
<commit_msg>report new posts from /user/the_yaya/m/all_pinoy/ to promote content of the other subreddits<commit_after>var irc = require('irc'),
    config = require('./lib/config'),
    strftime = require('strftime'),
    format = require('irc-colors'),
    request  = require('request-json'),
    reddit = request.newClient('http://www.reddit.com/'),
    latest = 0;

var client = new irc.Client(config.irc.host, config.irc.nick, {
  channels: [config.irc.channel],
  messageSplit: 2048
});

client.addListener('registered', function(msg) {
  client.say('NickServ', 'identify ' + config.irc.pass);
});

client.addListener('error', function(err) {
  // if (err.rawCommand != '421') console.log(err);
  log('ERROR in irc client');
  console.log(err);
});

client.addListener('nick', function(oldnick, newnick) {
  log('-- ' + oldnick + ' is now known as ' + newnick);
});

client.addListener('join', function(channel, nick) {
  log('>> ' + nick + ' joined');
});

client.addListener('part', function(channel, nick, reason) {
  log('<< ' + nick + ' left (' + reason + ')');
});

client.addListener('quit', function(nick, reason) {
  log('<< ' + nick + ' quit (' + reason + ')');
});

client.addListener('topic', function(channel, topic, nick) {
  log('!! ' + nick + ' changed the topic to "' + topic + '"');
});

client.addListener('kick', function(channel, nick, by, reason) {
  log('<< ' + nick + ' was kicked by ' + by + '(' + reason + ')');
});

client.addListener('message', function(from, to, msg) {
  log(from + ' ' + to + ' ' + msg);
});

var say = function(msg) {
  client.say(config.irc.channel, msg)
  log(config.irc.nick + ' ' + config.irc.channel + ' ' + msg);
}

var log = function(msg) {
  console.log(strftime('%F %T ') + msg)
}

var debug = function(msg) {
  process.stderr.write(strftime('%T ') + msg + '\n');
}

// check for new r/philippines posts and if any
// are found, post them to the channel
//
var report_new_posts = function() {

  var url = '/user/the_yaya/m/all_pinoy/new/.json';

  reddit.get(url, function(err, res, body) {
    if (err) {
      log('ERROR fetching new posts');
      console.log(err);
    } else {

      if (body.data.children.length) {

        var init = (latest === 0);

        var children = body.data.children;

        for (var i = children.length-1; i >= 0; i--) {
          var post = children[i].data;

          if (post.created_utc > latest) {

            latest = post.created_utc;

            if (!init) {

              var msg = 'http://redd.it/' + post.id
                      + ' in r/' + post.subreddit + ':'
                      + ' ' + format.green.bold(post.title)
                      + ' by ' + format.brown.italic(post.author)

              if (post.selftext) {
                msg += ': ' + post.selftext.replace(/\n/g, ' ');;
              }

              say(msg);
            }
          }
        }
      }
    }
  });

  setTimeout(report_new_posts, 30000);
};

setTimeout(report_new_posts, 5000);
<|endoftext|>


<commit_before>describe("Key State Test", function() {
	var displayflag = false;
	beforeEach(function() {
		/* ... Set up your object ... */
		displayflag = false;
	});

	afterEach(function() {
		/* ... Tear it down ... */
	});

	it("VT281-0850 | Keystate showStates without any property |", function() {
		runs(function()
		{
			Rho.Keystate.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0851 | Keystate showStates with right to 50 |", function() {
		runs(function()
		{

			Rho.Keystate.showStates([{"right":50}]);
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator at right 50 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0854 | Keystate showStates with left to 70 |", function() {
		runs(function()
		{

			Rho.Keystate.showStates({"left":70})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator at left 70 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0857 | Keystate showStates with width to 100 |", function() {
		runs(function()
		{

			Rho.Keystate.showStates({"width":100})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator width 100 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0860 | Keystate showStates with height to 100 |", function() {
		runs(function()
		{

			Rho.Keystate.showStates({"height":150})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator width 100 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0863 | Keystate showStates with all properties |", function() {
		runs(function()
		{

			Rho.Keystate.showStates({'right':100,'left':150,'height':200,'width':250})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("right:100,left:150,Height:200,width:250
 Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator at
 right:100,left:150 with Height:200,width:250 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0864 | KeyState hideStates |", function() {
		runs(function()
		{

			Rho.Keystate.showStates({'right':100,'left':150,'height':200,'width':250});
			Rho.Keystate.hideStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("right:100,left:150,Height:200,width:250
 Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("KeyState indicator should be hidden and should not be shown on page.
 Have you seen this behavior ?");
			expect(testPassed).toEqual(true);
		});
	});

	var m = 0;
	var test_key = [{'testCaseId':'VT281-0866','keyName':'SHIFT'},
					{'testCaseId':'VT281-0867','keyName':'CTRL'},
					{'testCaseId':'VT281-0868','keyName':'Function'},
					{'testCaseId':'VT281-0869','keyName':'Caps'},
					{'testCaseId':'VT281-0870','keyName':'Num lock'},
					{'testCaseId':'VT281-0871','keyName':'ALT'}]
	for (var i=0;i<test_key.length;i++){

		it(test_key[i]['testCaseId']+" | KeyState functionality Test with "+test_key[i]['keyName']+"Key | ", function() {

		runs(function()
		{

			Rho.Keystate.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press "+test_key['keyName']+ " key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator for
"+test_key['keyName']+" Key ?");
			expect(testPassed).toEqual(true);
		});

		});

	}

	it("VT281-0872 | KeyState functionality Test with Orange key once |", function() {
		runs(function()
		{

			Rho.Keystate.showStates();
			add('text');
			text.focus();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Orange Key once.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0873 | KeyState functionality Test with Orange key Twice |", function() {
		runs(function()
		{

			Rho.Keystate.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Orange Key Twice.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0874 | KeyState functionality Test with Blue key once |", function() {
		runs(function()
		{

			Rho.Keystate.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Blue Key once.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0875 | KeyState functionality Test with Blue key Twice |", function() {
		runs(function()
		{

			Rho.Keystate.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Blue Key Twice.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

});
<commit_msg>Changed Keystate to KeyState.<commit_after>describe("Key State Test", function() {
	var displayflag = false;
	beforeEach(function() {
		/* ... Set up your object ... */
		displayflag = false;
	});

	afterEach(function() {
		/* ... Tear it down ... */
	});

	it("VT281-0850 | KeyState showStates without any property |", function() {
		runs(function()
		{
			Rho.KeyState.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0851 | KeyState showStates with right to 50 |", function() {
		runs(function()
		{

			Rho.KeyState.showStates([{"right":50}]);
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator at right 50 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0854 | KeyState showStates with left to 70 |", function() {
		runs(function()
		{

			Rho.KeyState.showStates({"left":70})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator at left 70 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0857 | KeyState showStates with width to 100 |", function() {
		runs(function()
		{

			Rho.KeyState.showStates({"width":100})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator width 100 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0860 | KeyState showStates with height to 100 |", function() {
		runs(function()
		{

			Rho.KeyState.showStates({"height":150})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator width 100 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0863 | KeyState showStates with all properties |", function() {
		runs(function()
		{

			Rho.KeyState.showStates({'right':100,'left':150,'height':200,'width':250})
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("right:100,left:150,Height:200,width:250
 Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator at
 right:100,left:150 with Height:200,width:250 ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0864 | KeyState hideStates |", function() {
		runs(function()
		{

			Rho.KeyState.showStates({'right':100,'left':150,'height':200,'width':250});
			Rho.KeyState.hideStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("right:100,left:150,Height:200,width:250
 Press Shift, Alt, Control, Function, Caps, Num lock and Orange key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("KeyState indicator should be hidden and should not be shown on page.
 Have you seen this behavior ?");
			expect(testPassed).toEqual(true);
		});
	});

	var m = 0;
	var test_key = [{'testCaseId':'VT281-0866','keyName':'SHIFT'},
					{'testCaseId':'VT281-0867','keyName':'CTRL'},
					{'testCaseId':'VT281-0868','keyName':'Function'},
					{'testCaseId':'VT281-0869','keyName':'Caps'},
					{'testCaseId':'VT281-0870','keyName':'Num lock'},
					{'testCaseId':'VT281-0871','keyName':'ALT'}]
	for (var i=0;i<test_key.length;i++){

		it(test_key[i]['testCaseId']+" | KeyState functionality Test with "+test_key[i]['keyName']+"Key | ", function() {

		runs(function()
		{

			Rho.KeyState.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press "+test_key['keyName']+ " key");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("Do you see KeyState indicator for
"+test_key['keyName']+" Key ?");
			expect(testPassed).toEqual(true);
		});

		});

	}

	it("VT281-0872 | KeyState functionality Test with Orange key once |", function() {
		runs(function()
		{

			Rho.KeyState.showStates();
			add('text');
			text.focus();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Orange Key once.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0873 | KeyState functionality Test with Orange key Twice |", function() {
		runs(function()
		{

			Rho.KeyState.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Orange Key Twice.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0874 | KeyState functionality Test with Blue key once |", function() {
		runs(function()
		{

			Rho.KeyState.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Blue Key once.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

	it("VT281-0875 | KeyState functionality Test with Blue key Twice |", function() {
		runs(function()
		{

			Rho.KeyState.showStates();
			setTimeout(function() {
				displayflag = true;
			}, 10000);
		});

		waitsFor(function()
		{
			dispCurrentProcess("Press Blue Key Twice.
 Press another key from the keyboard");
			return displayflag;
		}, 'The KeyState indicator should display', 11000);

		runs(function()
		{
			var testPassed = confirm("The data should be seen in the input box.
 Are you able to see ?");
			expect(testPassed).toEqual(true);
		});
	});

});
<|endoftext|>


<commit_before>/* @flow */

import React, { Component, PropTypes } from 'react';
import ReactNative from 'react-native';
import shallowCompare from 'react-addons-shallow-compare';
import template from 'lodash/template';
import Card from './Card';
import Share from '../../modules/Share';
import type { Room, User } from '../../../lib/schemaTypes';

const {
	Image,
	Linking,
	StyleSheet,
	TouchableOpacity,
} = ReactNative;

const styles = StyleSheet.create({
	container: {
		flex: 1,
	},
	cover: {
		height: 180,
		resizeMode: 'cover',
	},
});

type State = {
	image: ?string;
}

type Props = {
	user: User;
	room: ?Room;
	data: ?{
		id: string;
		image?: string;
		images?: Array<string>;
		title: string;
		content: ?string;
		url: ?string;
		type: 'share' | 'view';
	}
}

export default class CTACard extends Component<void, Props, State> {
	static propTypes = {
		room: PropTypes.object,
		user: PropTypes.object.isRequired,
		data: PropTypes.shape({
			id: PropTypes.string.isRequired,
			image: PropTypes.string,
			images: PropTypes.arrayOf(PropTypes.string),
			title: PropTypes.string.isRequired,
			content: PropTypes.string,
			url: PropTypes.string,
			type: PropTypes.oneOf([ 'share', 'view' ]),
		}),
	};

	state: State = {
		image: null,
	};

	componentWillMount() {
		this._setImage(this.props);
	}

	componentWillReceiveProps(nextProps: Props) {
		this._setImage(nextProps);
	}

	shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
		return shallowCompare(this, nextProps, nextState);
	}

	_checkImageExists: Function = (url: string): Promise<boolean> => {
		return new Promise(resolve => {
			const req = new XMLHttpRequest();

			req.open('HEAD', url, true); // Avoid doing a GET request to prevent OOM
			req.onreadystatechange = () => {
				if (req.readyState === req.DONE) {
					resolve(req.status === 200);
				}
			};
			req.send();
		});
	};

	_checkImageList: Function = function(urls: Array<string>): Observable {
		return new Observable(observer => {
			const promises = urls.map(async url => {
				const exists = await this._checkImageExists(url);
				return {
					url,
					exists,
				};
			});

			Promise
				.all(promises)
				.then(
					results => {
						results.forEach(result => {
							if (result.exists) {
								observer.next(result.url);
							}
						});
						observer.complete();
					},
					e => observer.error(e)
				);
		});
	}

	_setImage: Function = (props: Props) => {
		const {
			room,
			user,
			data,
		} = props;

		if (data) {
			let images;

			if (data.images) {
				images = data.images;
			} else if (data.image) {
				images = [ data.image ];
			} else {
				images = [];
			}

			images = images.map(url => template(url)({ room, user }));

			let done;

			this._checkImageList(images).forEach(image => {
				if (done) {
					return;
				}
				done = true;
				this.setState({
					image,
				});
			});
		}
	};

	_handleShare: Function = () => {
		const {
			data,
			room,
			user,
		} = this.props;

		if (data && data.content) {
			try {
				Share.shareItem(data.title ? template(data.title)({ room, user }) : 'Share…', template(data.content)({ room, user }));
			} catch (e) {
				// ignore
			}
		}
	};

	_handleView: Function = async () => {
		const {
			room,
			user,
			data,
		} = this.props;

		if (data && data.url) {
			const link = template(data.url)({ room, user });

			try {
				const canOpen = await Linking.canOpenURL(link);

				if (canOpen) {
					await Linking.openURL(link);
				}
			} catch (e) {
				// ignore
			}
		}
	};

	_handlePress: Function = () => {
		const {
			data,
		} = this.props;

		if (data) {
			switch (data.type) {
			case 'share':
				this._handleShare();
				break;
			case 'view':
				this._handleView();
				break;
			}
		}
	};

	render() {
		if (!this.state.image) {
			return null;
		}

		return (
			<Card {...this.props}>
				<TouchableOpacity style={styles.container} onPress={this._handlePress}>
					<Image
						style={styles.cover}
						source={{ uri: this.state.image }}
					/>
				</TouchableOpacity>
			</Card>
		);
	}
}
<commit_msg>fix(cta): properly cleanup CTACard on unmount (#338)<commit_after>/* @flow */

import React, { Component, PropTypes } from 'react';
import ReactNative from 'react-native';
import shallowCompare from 'react-addons-shallow-compare';
import template from 'lodash/template';
import Card from './Card';
import Share from '../../modules/Share';
import type { Room, User } from '../../../lib/schemaTypes';

const {
	Image,
	Linking,
	StyleSheet,
	TouchableOpacity,
} = ReactNative;

const styles = StyleSheet.create({
	container: {
		flex: 1,
	},
	cover: {
		height: 180,
		resizeMode: 'cover',
	},
});

type State = {
	image: ?string;
}

type Props = {
	user: User;
	room: ?Room;
	data: ?{
		id: string;
		image?: string;
		images?: Array<string>;
		title: string;
		content: ?string;
		url: ?string;
		type: 'share' | 'view';
	}
}

export default class CTACard extends Component<void, Props, State> {
	static propTypes = {
		room: PropTypes.object,
		user: PropTypes.object.isRequired,
		data: PropTypes.shape({
			id: PropTypes.string.isRequired,
			image: PropTypes.string,
			images: PropTypes.arrayOf(PropTypes.string),
			title: PropTypes.string.isRequired,
			content: PropTypes.string,
			url: PropTypes.string,
			type: PropTypes.oneOf([ 'share', 'view' ]),
		}),
	};

	state: State = {
		image: null,
	};

	componentWillMount() {
		this._setImage(this.props);
	}

	componentWillReceiveProps(nextProps: Props) {
		this._setImage(nextProps);
	}

	shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
		return shallowCompare(this, nextProps, nextState);
	}

	componentWillUnmount() {
		if (this._subscription) {
			this._subscription.unsubscribe();
			this._subscription = null;
		}
	}

	_subscription: ?Subscription;

	_checkImageExists: Function = (url: string): Promise<boolean> => {
		return new Promise(resolve => {
			const req = new XMLHttpRequest();

			req.open('HEAD', url, true); // Avoid doing a GET request to prevent OOM
			req.onreadystatechange = () => {
				if (req.readyState === req.DONE) {
					resolve(req.status === 200);
				}
			};
			req.send();
		});
	};

	_checkImageList: Function = function(urls: Array<string>): Observable {
		return new Observable(observer => {
			const promises = urls.map(async url => {
				const exists = await this._checkImageExists(url);
				return {
					url,
					exists,
				};
			});

			Promise
				.all(promises)
				.then(
					results => {
						results.forEach(result => {
							if (result.exists) {
								observer.next(result.url);
							}
						});
						observer.complete();
					},
					e => observer.error(e)
				);
		});
	}

	_setImage: Function = (props: Props) => {
		const {
			room,
			user,
			data,
		} = props;

		if (data) {
			let images;

			if (data.images) {
				images = data.images;
			} else if (data.image) {
				images = [ data.image ];
			} else {
				images = [];
			}

			images = images.map(url => template(url)({ room, user }));

			let done;

			this._subscription = this._checkImageList(images).subscribe({
				next: image => {
					if (done) {
						return;
					}
					done = true;
					this.setState({
						image,
					});
				},
			});
		}
	};

	_handleShare: Function = () => {
		const {
			data,
			room,
			user,
		} = this.props;

		if (data && data.content) {
			try {
				Share.shareItem(data.title ? template(data.title)({ room, user }) : 'Share…', template(data.content)({ room, user }));
			} catch (e) {
				// ignore
			}
		}
	};

	_handleView: Function = async () => {
		const {
			room,
			user,
			data,
		} = this.props;

		if (data && data.url) {
			const link = template(data.url)({ room, user });

			try {
				const canOpen = await Linking.canOpenURL(link);

				if (canOpen) {
					await Linking.openURL(link);
				}
			} catch (e) {
				// ignore
			}
		}
	};

	_handlePress: Function = () => {
		const {
			data,
		} = this.props;

		if (data) {
			switch (data.type) {
			case 'share':
				this._handleShare();
				break;
			case 'view':
				this._handleView();
				break;
			}
		}
	};

	render() {
		if (!this.state.image) {
			return null;
		}

		return (
			<Card {...this.props}>
				<TouchableOpacity style={styles.container} onPress={this._handlePress}>
					<Image
						style={styles.cover}
						source={{ uri: this.state.image }}
					/>
				</TouchableOpacity>
			</Card>
		);
	}
}
<|endoftext|>


<commit_before>import enhanceViews from '../enhancers/enhanceViews'

// Turns the views of multiple widgets into one array of views
export default (widgets) => {

	// Enhance views for all widgets
	const enhancedViews = widgets.map((widget) => {

		console.log(widget)
		return enhanceViews(widget.value, 14)

	})

	// Merge all views to one array of views
	return enhancedViews.reduce((acc, views) => {

		// Views is an array. Each item represents the visit count of one day, month or year.
		views.forEach((view, index) => {

			// The current day, month or year might be new and should be initialised first
			const initial = acc[index] == null ? 0 : acc[index]

			// Add the current day, month or year to the global array of days, months or years
			acc[index] = initial + view

		})

		return acc

	}, [])

}<commit_msg>Remove console.log<commit_after>import enhanceViews from '../enhancers/enhanceViews'

// Turns the views of multiple widgets into one array of views
export default (widgets) => {

	// Enhance views for all widgets
	const enhancedViews = widgets.map((widget) => {

		return enhanceViews(widget.value, 14)

	})

	// Merge all views to one array of views
	return enhancedViews.reduce((acc, views) => {

		// Views is an array. Each item represents the visit count of one day, month or year.
		views.forEach((view, index) => {

			// The current day, month or year might be new and should be initialised first
			const initial = acc[index] == null ? 0 : acc[index]

			// Add the current day, month or year to the global array of days, months or years
			acc[index] = initial + view

		})

		return acc

	}, [])

}<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash'),
	path = require('path'),
	chalk = require('chalk'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Role = mongoose.model('_Role');
	//Invitation = mongoose.model('Invitation');
	// Role = mongoose.model('Role'),
	// Roles = require(path.resolve('./modules/roles/server/controllers/role.controller'));

var Invitation = require(path.resolve('./modules/invitations/server/controllers/invitation.controller'));

// ensure that we have come through Siteminder...
var parseSm = function (req) {
	return new Promise(function (fulfill, reject) {
		var userGuid = req.headers.smgov_userguid;
		var userType = req.headers.smgov_usertype;
		var universalId = req.headers.sm_universalid; // if we need to add in IDIR or BCEID, get from sm_authdirname

		if (!_.isEmpty(process.env.ALLOW_SITEMINDER_OVERRIDE) && process.env.ALLOW_SITEMINDER_OVERRIDE === 'true') {
			userGuid = userGuid || req.params.userguid || req.query.smgov_userguid;
			userType = userType || req.params.usertype || req.query.smgov_usertype;
			universalId = universalId || req.params.sm_universalid || req.query.sm_universalid;
		}

		if (userGuid) {
			fulfill({userGuid: userGuid, userType: userType, universalId: universalId});
		} else {
			reject(new Error('parseSm: Could not find user information from Siteminder'));
		}
	});
};

var findUserByGuid = function (userGuid) {
	return new Promise(function (fulfill, reject) {
		User.findOne({
			userGuid: userGuid.toLowerCase()
		}).populate('org').exec(function (error, user) {
			if (error) {
				reject(new Error(error));
			} else if (!user) {
				reject(new Error('findUserByGuid: User not found for Siteminder headers.'));
			} else {
				fulfill(user);
			}
		});
	});
};

var checkUsers = function (sm, user, inviteUser) {
	return new Promise(function (fulfill, reject) {
		if (!user && !inviteUser) {
			reject(new Error('No users found to sign in'));
		}
		else if (!user && inviteUser) {
			if (!_.isEmpty(inviteUser.userGuid) && (sm.userGuid !== inviteUser.userGuid)) {
				//console.log(chalk.green("checkUsers()... inviteUser.userGuid: '" + inviteUser.userGuid + "' sm.userGuid: '" + sm.userGuid + "'"));
				// auto-assigned guid - we can carry on in this case...
				if (inviteUser.userGuid.lastIndexOf("esm-", 0) === 0) {
					//console.log(chalk.green("checkUsers()...detected auto-assigned userGuid...proceeding with SiteMinder account linking..."));
					fulfill(inviteUser);
				} else {
					reject(new Error('Invitation user does not match Signed in user.'));
				}
			} else {
				// carry on with the invitation's user, will need to set siteminder fields...
				fulfill(inviteUser);
			}
		} else if (user && inviteUser) {
			if (!_.isEmpty(user.userGuid) && user.userGuid === inviteUser.userGuid) {
				// all good, invited user matches and has been signed in before...
				fulfill(user);
			} else {
				// we've got a problem here...
				// siteminder headers loaded a user that doesn't match up with our invite user
				reject(new Error('Signed in user does not match Invitation user.'));
			}
		}
	});
};

var updateRolesUsername = function(sm, user) {
	// a user is invited and possibly assigned roles to their generated username.
	// so let's update the generated username to the Siteminder username...
	if (sm.universalId.toLowerCase() === user.username.toLowerCase()) {
		return Promise.resolve(user);
	} else {
		var update  = { user: sm.universalId.toLowerCase() }; // role schema doesn't convert to lowercase...
		var query   = { user: user.username };
		return new Promise(function(fulfill, reject) {
			Role.update(query, update, {multi: true}).exec()
			.then (function () { return user; })
			.then (fulfill, reject);
		});
	}
};

var updateUserFromSiteminder = function (sm, user) {
	return new Promise(function (fulfill, reject) {
		if (_.isEmpty(user.userGuid) || _.startsWith(user.userGuid, 'esm-')) {
			// set the siteminder fields
			user.userGuid = sm.userGuid;
			user.userType = sm.userType;
			user.username = sm.universalId.toLowerCase(); // would happen automatically due to schema
			if (!_.includes(user.roles, 'user')) {
				user.roles.push('user');
			}

			user.save(function (err, u) {
				if (err) {
					reject(new Error(err));
				} else {
					fulfill(u);
				}
			});
		} else {
			fulfill(user);
		}
	});
};

var loginUser = function (req, user) {
	return new Promise(function (fulfill, reject) {
		req.logout();
		req.login(user, function (err) {
			if (err) {
				reject(new Error(err));
			} else {
				fulfill(user);
			}
		});
	});
};

exports.signIn = function (req, res) {
	var redirectPath = '/';
	var siteMinder;
	parseSm(req)
		.then(function (sm) {
			siteMinder = sm;
			//console.log(chalk.green('parseSm(): ' + sm.userGuid));
			return findUserByGuid(sm.userGuid);
		})
		.then(function (user) {
			//console.log(chalk.green('findUserByGuid(): ' + user.displayName));
			return loginUser(req, user);
		})
		.then(function () {
			//console.log(chalk.green('loginUser(): ' + req.isAuthenticated()));
			res.redirect(redirectPath);
		})
		.catch(function (err) {
			//console.error(chalk.red('Error: signIn(): ' + err.message));
			// should we do something differently here?
			redirectPath = '/smerr';
			if (siteMinder !== undefined && siteMinder.userType !== undefined ) {
				redirectPath += '?t=' + siteMinder.userType.toLowerCase();
			}
			res.redirect(redirectPath);
		});
};

exports.acceptInvitation = function (req, res) {
	//console.log('acceptInvitation > token = ', req.params.token);
	//console.log('acceptInvitation > user = ', JSON.stringify(req.user));
	var redirectPath = '/';
	var invite, siteMinder, user;

	(new Invitation({user: req.user, context: 'application'})).acceptInvitation(req)
		.then(function (data) {
			//console.log('acceptInvitation > invite = ', JSON.stringify(data));
			invite = data;
			return parseSm(req);
		})
		.then(function (sm) {
			//console.log('acceptInvitation > siteMinder = ', JSON.stringify(sm));
			siteMinder = sm;
			return findUserByGuid(siteMinder.userGuid).catch(function () {
				// user may not have guid populated yet...
				return null;
			});
		})
		.then(function (u) {
			if (u) {
				//console.log('acceptInvitation > found guid = ', JSON.stringify(u));
				user = u;
			}
			//console.log('acceptInvitation > call checkUsers = ', JSON.stringify(u));
			return checkUsers(siteMinder, user, invite.user);
		})
		.then(function (u) {
			//console.log('acceptInvitation > checkUsers = ', JSON.stringify(u));
			user = u; // may come from the invite user, or the sm user...
			//console.log('acceptInvitation > call updateRolesUsername = ', JSON.stringify(u));
			return updateRolesUsername(siteMinder, user);
		})
		.then(function () {
			//console.log('acceptInvitation > call updateUserFromSiteminder = ', JSON.stringify(user));
			return updateUserFromSiteminder(siteMinder, user);
		})
		.then(function () {
			//console.log('acceptInvitation > call loginUser = ', JSON.stringify(user));
			return loginUser(req, user);
		})
		.then(function () {
			//console.log(chalk.green('loginUser(): ' + req.isAuthenticated()));
			res.redirect(redirectPath);
		})
		.catch(function (err) {
			//console.error(chalk.red('Error: acceptInvitation(): ' + err.message));
			// should we do something differently here?
			// can we examine an error type and send off a different message?
			res.redirect(redirectPath);
		});

};

exports.logHeaders = function(req, res) {
	//console.log(JSON.stringify(req.headers));

	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end(JSON.stringify(req.headers));
};
<commit_msg>EPIC-1004 - User redirect to dashboard<commit_after>'use strict';

var _ = require('lodash'),
	path = require('path'),
	chalk = require('chalk'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Role = mongoose.model('_Role');
	//Invitation = mongoose.model('Invitation');
	// Role = mongoose.model('Role'),
	// Roles = require(path.resolve('./modules/roles/server/controllers/role.controller'));

var Invitation = require(path.resolve('./modules/invitations/server/controllers/invitation.controller'));

// ensure that we have come through Siteminder...
var parseSm = function (req) {
	return new Promise(function (fulfill, reject) {
		var userGuid = req.headers.smgov_userguid;
		var userType = req.headers.smgov_usertype;
		var universalId = req.headers.sm_universalid; // if we need to add in IDIR or BCEID, get from sm_authdirname

		if (!_.isEmpty(process.env.ALLOW_SITEMINDER_OVERRIDE) && process.env.ALLOW_SITEMINDER_OVERRIDE === 'true') {
			userGuid = userGuid || req.params.userguid || req.query.smgov_userguid;
			userType = userType || req.params.usertype || req.query.smgov_usertype;
			universalId = universalId || req.params.sm_universalid || req.query.sm_universalid;
		}

		if (userGuid) {
			fulfill({userGuid: userGuid, userType: userType, universalId: universalId});
		} else {
			reject(new Error('parseSm: Could not find user information from Siteminder'));
		}
	});
};

var findUserByGuid = function (userGuid) {
	return new Promise(function (fulfill, reject) {
		User.findOne({
			userGuid: userGuid.toLowerCase()
		}).populate('org').exec(function (error, user) {
			if (error) {
				reject(new Error(error));
			} else if (!user) {
				reject(new Error('findUserByGuid: User not found for Siteminder headers.'));
			} else {
				fulfill(user);
			}
		});
	});
};

var checkUsers = function (sm, user, inviteUser) {
	return new Promise(function (fulfill, reject) {
		if (!user && !inviteUser) {
			reject(new Error('No users found to sign in'));
		}
		else if (!user && inviteUser) {
			if (!_.isEmpty(inviteUser.userGuid) && (sm.userGuid !== inviteUser.userGuid)) {
				//console.log(chalk.green("checkUsers()... inviteUser.userGuid: '" + inviteUser.userGuid + "' sm.userGuid: '" + sm.userGuid + "'"));
				// auto-assigned guid - we can carry on in this case...
				if (inviteUser.userGuid.lastIndexOf("esm-", 0) === 0) {
					//console.log(chalk.green("checkUsers()...detected auto-assigned userGuid...proceeding with SiteMinder account linking..."));
					fulfill(inviteUser);
				} else {
					reject(new Error('Invitation user does not match Signed in user.'));
				}
			} else {
				// carry on with the invitation's user, will need to set siteminder fields...
				fulfill(inviteUser);
			}
		} else if (user && inviteUser) {
			if (!_.isEmpty(user.userGuid) && user.userGuid === inviteUser.userGuid) {
				// all good, invited user matches and has been signed in before...
				fulfill(user);
			} else {
				// we've got a problem here...
				// siteminder headers loaded a user that doesn't match up with our invite user
				reject(new Error('Signed in user does not match Invitation user.'));
			}
		}
	});
};

var updateRolesUsername = function(sm, user) {
	// a user is invited and possibly assigned roles to their generated username.
	// so let's update the generated username to the Siteminder username...
	if (sm.universalId.toLowerCase() === user.username.toLowerCase()) {
		return Promise.resolve(user);
	} else {
		var update  = { user: sm.universalId.toLowerCase() }; // role schema doesn't convert to lowercase...
		var query   = { user: user.username };
		return new Promise(function(fulfill, reject) {
			Role.update(query, update, {multi: true}).exec()
			.then (function () { return user; })
			.then (fulfill, reject);
		});
	}
};

var updateUserFromSiteminder = function (sm, user) {
	return new Promise(function (fulfill, reject) {
		if (_.isEmpty(user.userGuid) || _.startsWith(user.userGuid, 'esm-')) {
			// set the siteminder fields
			user.userGuid = sm.userGuid;
			user.userType = sm.userType;
			user.username = sm.universalId.toLowerCase(); // would happen automatically due to schema
			if (!_.includes(user.roles, 'user')) {
				user.roles.push('user');
			}

			user.save(function (err, u) {
				if (err) {
					reject(new Error(err));
				} else {
					fulfill(u);
				}
			});
		} else {
			fulfill(user);
		}
	});
};

var loginUser = function (req, user) {
	return new Promise(function (fulfill, reject) {
		req.logout();
		req.login(user, function (err) {
			if (err) {
				reject(new Error(err));
			} else {
				fulfill(user);
			}
		});
	});
};

exports.signIn = function (req, res) {
	var redirectPath = '/dashboard';
	var siteMinder;
	parseSm(req)
		.then(function (sm) {
			siteMinder = sm;
			//console.log(chalk.green('parseSm(): ' + sm.userGuid));
			return findUserByGuid(sm.userGuid);
		})
		.then(function (user) {
			//console.log(chalk.green('findUserByGuid(): ' + user.displayName));
			return loginUser(req, user);
		})
		.then(function () {
			//console.log(chalk.green('loginUser(): ' + req.isAuthenticated()));
			res.redirect(redirectPath);
		})
		.catch(function (err) {
			//console.error(chalk.red('Error: signIn(): ' + err.message));
			// should we do something differently here?
			redirectPath = '/smerr';
			if (siteMinder !== undefined && siteMinder.userType !== undefined ) {
				redirectPath += '?t=' + siteMinder.userType.toLowerCase();
			}
			res.redirect(redirectPath);
		});
};

exports.acceptInvitation = function (req, res) {
	//console.log('acceptInvitation > token = ', req.params.token);
	//console.log('acceptInvitation > user = ', JSON.stringify(req.user));
	var redirectPath = '/dashboard';
	var invite, siteMinder, user;

	(new Invitation({user: req.user, context: 'application'})).acceptInvitation(req)
		.then(function (data) {
			//console.log('acceptInvitation > invite = ', JSON.stringify(data));
			invite = data;
			return parseSm(req);
		})
		.then(function (sm) {
			//console.log('acceptInvitation > siteMinder = ', JSON.stringify(sm));
			siteMinder = sm;
			return findUserByGuid(siteMinder.userGuid).catch(function () {
				// user may not have guid populated yet...
				return null;
			});
		})
		.then(function (u) {
			if (u) {
				//console.log('acceptInvitation > found guid = ', JSON.stringify(u));
				user = u;
			}
			//console.log('acceptInvitation > call checkUsers = ', JSON.stringify(u));
			return checkUsers(siteMinder, user, invite.user);
		})
		.then(function (u) {
			//console.log('acceptInvitation > checkUsers = ', JSON.stringify(u));
			user = u; // may come from the invite user, or the sm user...
			//console.log('acceptInvitation > call updateRolesUsername = ', JSON.stringify(u));
			return updateRolesUsername(siteMinder, user);
		})
		.then(function () {
			//console.log('acceptInvitation > call updateUserFromSiteminder = ', JSON.stringify(user));
			return updateUserFromSiteminder(siteMinder, user);
		})
		.then(function () {
			//console.log('acceptInvitation > call loginUser = ', JSON.stringify(user));
			return loginUser(req, user);
		})
		.then(function () {
			//console.log(chalk.green('loginUser(): ' + req.isAuthenticated()));
			res.redirect(redirectPath);
		})
		.catch(function (err) {
			//console.error(chalk.red('Error: acceptInvitation(): ' + err.message));
			// should we do something differently here?
			// can we examine an error type and send off a different message?
			res.redirect(redirectPath);
		});

};

exports.logHeaders = function(req, res) {
	//console.log(JSON.stringify(req.headers));

	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end(JSON.stringify(req.headers));
};
<|endoftext|>


<commit_before>const GESTURES = {
  'click': 'tap',
  'dblclick': 'double_tap'
}

var Explore = {

  currentElement: null,

  /**
  * add event listener to DER elements
  * @param {HTMLElement} element
  * @param {Object} actions
  * @param {readAudioFile} tts
  * @param {Function} tts
  */
  setExploreEvents: function(params) {
    this.readFunction = params.readFunction;
    this.tts = params.tts;
    this.filter = params.filter;
    this.pois = [];
    this.actions = {};

    params.pois.map(function(poi) {
      var id = poi.id.split('-').pop();
      var elements = document.querySelectorAll('[data-link="' + id + '"]');

      Object.keys(elements).forEach((index) => {
        if (elements[index] !== undefined) {
          Explore.pois.push(elements[index]);
          Explore.actions[id] = poi.actions.action;
          Object.keys(GESTURES).map(function(gesture) {
            elements[index].addEventListener(gesture, Explore.initAction);
          });
        }
      });
    });
  },

  removeExploreEvents: function() {
    Explore.pois.map(function(poiEl) {
      Object.keys(GESTURES).map(function(gesture) {
        poiEl.removeEventListener(gesture, Explore.initAction);
      });
    });
  },

  initAction: function(event) {
    let element = event.target;
    let actions = Explore.actions[element.getAttribute('data-link')];
    let action = Explore._getAction(actions, event.type);
    if (action !== undefined && GESTURES[event.type] === action.gesture) {
      Explore._onEventStarted(element);
      if (action.protocol === 'mp3') {
        if (Explore.currentElement) {
          Explore._onEventEnded(Explore.currentElement);
        }

        Explore.currentElement = element;
        Explore.readFunction(action.value).then(() => {
          Explore._onEventEnded(element);
        });
      }

      if (action.protocol === 'tts') {
        Explore.tts.speak(action.value).then(function() {
          Explore._onEventEnded(element);
        });
      }
    }
  },

  _getAction: function(actions, type) {
    if (actions.length === undefined) {
      return actions;
    } else {
      for (var i = 0; i < actions.length; i++) {
        let a = actions[i];
        if (this.filter) {
          if (a.filter === this.filter.id) {
            return a;
          }
        }
        // if (GESTURES[type] === a.gesture && a.protocol !== undefined) {
        //   return a;
        // }
      }
    }
    return;
  },

  _onEventStarted: function(element) {
    this.initialColor = element.style.fill;
    element.style.fill = 'red';
  },

  _onEventEnded: function(element) {
    element.style.fill = this.initialColor;
  }

};

module.exports = Explore;
<commit_msg>Correct filter interaction #23<commit_after>const GESTURES = {
  'click': 'tap',
  'dblclick': 'double_tap'
}

var Explore = {

  currentElement: null,

  /**
  * add event listener to DER elements
  * @param {HTMLElement} element
  * @param {Object} actions
  * @param {readAudioFile} tts
  * @param {Function} tts
  */
  setExploreEvents: function(params) {
    this.readFunction = params.readFunction;
    this.tts = params.tts;
    this.filter = params.filter;
    this.pois = [];
    this.actions = {};

    params.pois.map(function(poi) {
      var id = poi.id.split('-').pop();
      var elements = document.querySelectorAll('[data-link="' + id + '"]');

      Object.keys(elements).forEach((index) => {
        if (elements[index] !== undefined) {
          Explore.pois.push(elements[index]);
          Explore.actions[id] = poi.actions.action;
          Object.keys(GESTURES).map(function(gesture) {
            elements[index].addEventListener(gesture, Explore.initAction);
          });
        }
      });
    });
  },

  removeExploreEvents: function() {
    Explore.pois.map(function(poiEl) {
      Object.keys(GESTURES).map(function(gesture) {
        poiEl.removeEventListener(gesture, Explore.initAction);
      });
    });
  },

  initAction: function(event) {
    let element = event.target;
    let actions = Explore.actions[element.getAttribute('data-link')];
    let action = Explore._getAction(actions, event.type);
    if (action !== undefined && GESTURES[event.type] === action.gesture) {
      Explore._onEventStarted(element);
      if (action.protocol === 'mp3') {
        if (Explore.currentElement) {
          Explore._onEventEnded(Explore.currentElement);
        }

        Explore.currentElement = element;
        Explore.readFunction(action.value).then(() => {
          Explore._onEventEnded(element);
        });
      }

      if (action.protocol === 'tts') {
        Explore.tts.speak(action.value).then(function() {
          Explore._onEventEnded(element);
        });
      }
    }
  },

  _getAction: function(actions, type) {
    if (!Array.isArray(actions)) {
      return actions;
    } else {
      for (var i = 0; i < actions.length; i++) {
        let a = actions[i];
        if (this.filter) {
          if (a.filter === this.filter.id) {
            return a;
          }
        }
        // if (GESTURES[type] === a.gesture && a.protocol !== undefined) {
        //   return a;
        // }
      }
    }
    return;
  },

  _onEventStarted: function(element) {
    this.initialColor = element.style.fill;
    element.style.fill = 'red';
  },

  _onEventEnded: function(element) {
    element.style.fill = this.initialColor;
  }

};

module.exports = Explore;
<|endoftext|>


<commit_before>var things = null;

function Movable(id, x, y) {
  this.currentX = x;
  this.currentY = y;
  this.id = id;

  this.htmlObj = document.getElementById(id);
  this.htmlObj.style.left = (this.currentX + "px");
  this.htmlObj.style.top = (this.currentY + "px");
//  console.log('Movable() id=' + id + '  currentX = ' + this.currentX + "px    currentX =" + this.currentY + "px");
}

Movable.prototype.move = function(x, y)
{
  destX = destX + x;
  destY = destY + y;
}

Movable.prototype.MoveUp = function(x, y)
{
  move(this.destX, this.destY - 10);
}

Movable.prototype.MoveDown = function(x, y)
{
  move(this.destX, this.destY + 10);
}

Movable.prototype.MoveLeft = function(x, y)
{
  move(this.destX - 10, this.destY);
}

Movable.prototype.MoveRight = function(x, y)
{
  move(this.destX + 10, this.destY);
}

Movable.prototype.InitialScale = function()
{
  console.log('in InitialScale()');
  console.log('In InitialScale().   this.htmlObj.style.width=' + this.htmlObj.style.width + '   id=' + this.id);
//  console.log('In InitialScale().   this.htmlObj.width=' + this.htmlObj.width );

  console.log('In InitialScale().   jQuery Width=' + $("#" + this.id).width());
  console.log('In InitialScale().   this.clientWidth=' + this.htmlObj.naturalWidth);
  console.log('In InitialScale().   this.htmlObj.style id=' + this.htmlObj.htmlObj.id);

  var nNewWidth = (this.htmlObj.naturalWidth * parseFloat(this.htmlObj.scale));
  console.log('In InitialScale().   nNewWidth=' + nNewWidth);
  var nNewHeight = (this.htmlObj.naturalHeight * parseFloat(this.htmlObj.scale));
  console.log('In InitialScale().   nNewHeight=' + nNewHeight);
  this.htmlObj.width = nNewWidth;
  this.htmlObj.height = nNewHeight;

//  this.htmlObj = document.getElementById(id);
//  this.htmlObj.style.width = (this.currentX + "px");
}

function ScaleObjects()
{
  console.log('In ScaleObjects().   things.length=' + things.length);
//  console.log('In ScaleObjects().   things.[length].id=' + things[0].id);
//  console.log('in ScaleObjects()');
  for (var nIndex = 0; nIndex < things.length; nIndex++)
  {
      console.log('In ScaleObjects().   thisThing.id=' + things[nIndex].id);
      var thisItem = things[nIndex];
      thisItem.InitialScale();
  }
  console.log('Done ScaleObjects()');
}

function GameInitilize2(e)
{
  console.log('in GameInitialize2()');
  dad = new Movable("Dad", 3, 5);
  mom = new Movable("Mom", 5, 59);
  jordan = new Movable("Jordan", 40, 20);
  house = new Movable("House", 60, 5);
  candyhouse = new Movable("CandyHouse", 60, 75);
//  console.log('Finished GameInitialize2()');

  things = new Array(dad, mom, jordan, house, candyhouse);
  //  console.log('GameInitilize2: id=' + things[0].id);
  ScaleObjects();
}

function GameInitilize(e)
{
//  console.log('In GameInitialize()');
//  window.document.onload = GameInitilize2;
  $(document).ready(GameInitilize2);
}

// console.log('Running Game.js global code.');
GameInitilize();

<commit_msg>Update Game.js<commit_after>var things = null;

function Movable(id, x, y) {
  this.currentX = x;
  this.currentY = y;
  this.id = id;

  this.htmlObj = document.getElementById(id);
  this.htmlObj.style.left = (this.currentX + "px");
  this.htmlObj.style.top = (this.currentY + "px");
//  console.log('Movable() id=' + id + '  currentX = ' + this.currentX + "px    currentX =" + this.currentY + "px");
}

Movable.prototype.move = function(x, y)
{
  destX = destX + x;
  destY = destY + y;
}

Movable.prototype.MoveUp = function(x, y)
{
  move(this.destX, this.destY - 10);
}

Movable.prototype.MoveDown = function(x, y)
{
  move(this.destX, this.destY + 10);
}

Movable.prototype.MoveLeft = function(x, y)
{
  move(this.destX - 10, this.destY);
}

Movable.prototype.MoveRight = function(x, y)
{
  move(this.destX + 10, this.destY);
}

Movable.prototype.InitialScale = function()
{
  console.log('in InitialScale()');
  console.log('In InitialScale().   this.htmlObj.style.width=' + this.htmlObj.style.width + '   id=' + this.id);
//  console.log('In InitialScale().   this.htmlObj.width=' + this.htmlObj.width );

  console.log('In InitialScale().   jQuery Width=' + $("#" + this.id).width());
  console.log('In InitialScale().   this.naturalWidth=' + this.htmlObj.naturalWidth);
  console.log('In InitialScale().   this.clientWidth=' + this.htmlObj.clientWidth);
  console.log('In InitialScale().   this.htmlObj.style id=' + this.htmlObj.id);

  var nNewWidth = (this.htmlObj.naturalWidth * parseFloat(this.htmlObj.scale));
  console.log('In InitialScale().   nNewWidth=' + nNewWidth);
  var nNewHeight = (this.htmlObj.naturalHeight * parseFloat(this.htmlObj.scale));
  console.log('In InitialScale().   nNewHeight=' + nNewHeight);
  this.htmlObj.width = nNewWidth;
  this.htmlObj.height = nNewHeight;

//  this.htmlObj = document.getElementById(id);
//  this.htmlObj.style.width = (this.currentX + "px");
}

function ScaleObjects()
{
//  console.log('In ScaleObjects().   things.length=' + things.length);
//  console.log('In ScaleObjects().   things.[length].id=' + things[0].id);
//  console.log('in ScaleObjects()');
  for (var nIndex = 0; nIndex < things.length; nIndex++)
  {
//      console.log('In ScaleObjects().   thisThing.id=' + things[nIndex].id);
      var thisItem = things[nIndex];
      thisItem.InitialScale();
  }
  console.log('Done ScaleObjects()');
}

function GameInitilize2(e)
{
  console.log('in GameInitialize2()');
  dad = new Movable("Dad", 3, 5);
  mom = new Movable("Mom", 5, 59);
  jordan = new Movable("Jordan", 40, 20);
  house = new Movable("House", 60, 5);
  candyhouse = new Movable("CandyHouse", 60, 75);
//  console.log('Finished GameInitialize2()');

  things = new Array(dad, mom, jordan, house, candyhouse);
  //  console.log('GameInitilize2: id=' + things[0].id);
  ScaleObjects();
}

function GameInitilize(e)
{
//  console.log('In GameInitialize()');
//  window.document.onload = GameInitilize2;
  $(document).ready(GameInitilize2);
}

// console.log('Running Game.js global code.');
GameInitilize();

<|endoftext|>


<commit_before>var ESC_KEY = 27;

/**
 * An activity scores table builder.
 *
 * @class
 */
function ActivityTable(activityScores) {
  this._activityScores = activityScores;
}

function openModal() {
  // Bind Esc press to close window
  $(document).on("keyup.modal", function(e) {
    if (e.keyCode == ESC_KEY) {
        closeModal();
    }
  });
  $("#question-window").show();
}

function closeModal() {
  $("#question-window, #question-container > div").hide();
  //Remove Esc binding
  $(document).off("keyup.modal");
}

/**
 * Sets up handlers for modal window.
 */
function setUpModalWindow() {
  // Bind click on background and on close button to close window
  $("#question-background, #question-window .question-close-button").on("click", function(e) {
    closeModal();
  });
  $("#question-container > div").hide();
}

ActivityTable.prototype = {
  _buildRow: function(sequence, question) {

    var tr = $('

');

    // add question number
    var td = $(
        '' +
        '  Question ' + ++sequence +
        '

' +
        '	'
    );
    td.find('.md-visibility').data('quid', question[0]['quid']);

    tr.append(td);

    td.find('.md-visibility').click(function () {
      openModal();
      var params = {
          action: 'question_preview',
          quid: $(this).data('quid')
      };
      $('#question-preview').html($('').attr(
        {id: 'question-preview', src: 'dashboard?' + $.param(params)})).show();
    });

    // add choices
    var numOfColumns = this._columnCount();
    var numCorrect = 0;
    var numIncorrect = 0;

    for (var i = 1; i <= numOfColumns; i++) {
      var td;

      if (i <= question.length) {
        var td = $(
          '' +
            question[i-1].count +
          '	'
        );

        if (question[i-1].score > 0) {
          $(td).addClass('correct-choice');
          numCorrect += question[i-1].count;
        }
        else {
          numIncorrect += question[i-1].count;
        }
      }
      else {
        var td = $(
          '--	'
        );
      }

      tr.append(td);
    }

    var totalQuestions = numCorrect + numIncorrect;
    var percentCorrect = 0;
    if (totalQuestions > 0) {
        percentCorrect = numCorrect / totalQuestions;
    }

    if (percentCorrect < .75 && percentCorrect > .5) {
      $($(tr).find('.question-info')).addClass('uncertain-question');
    }
    else if (percentCorrect <= .5) {
      $($(tr).find('.question-info')).addClass('problem-question');
    }

    return tr;
  },

  _buildHeader: function() {
    var numOfColumns = this._columnCount();

    var thead = $(
      '
' +
      '
' +
      '    	' +
      '
' +
      '
'
    );

    for (var i = 1; i <= numOfColumns; i++) {
      $(thead).find('tr').append(' Choice ' + i + '	');
    }

    return thead;
  },

  _buildBody: function() {
    var that = this;
    var tbody = $('

');

    var i = 0;
    $.each(that._activityScores, function (key, question) {
      var row = that._buildRow(key, question);
      row.addClass( i++ % 2 == 0 ? 'even' : 'odd');
      tbody.append(row);
    });

    return tbody;
  },

  _refresh: function() {
    this._table.find('tbody').remove();
    this._table.append(this._buildBody());
  },

  _columnCount: function() {
    var numOfColumns = 0;
    $.each(this._activityScores, function (key, question) {
      if (numOfColumns === 0 || question.length > numOfColumns) {
        numOfColumns = question.length;
      }
    });

    return numOfColumns;
  },

  buildTable: function(unitId, lessonId, unitTitle, lessonTitle) {
    var that = this;

    this._content = $(
      '
' +
      '
Question Scores for Unit: ' + unitTitle + ', Lesson: ' + lessonTitle + '
' +
      '

');

    this._table = this._content.find('.questions-table');
    this._table.append(that._buildHeader());

    this._refresh();

    return this._content;
  }
};

function retrieveLessonScores(scores, unitId, lessonId) {
  var lessonScores = {};

  $.each(scores, function (studentId, units) {
    var questions = units[unitId][lessonId];
//     if (!questions) {
//       return;
//     }
    $.each(questions, function (sequence, question) {
      if (!lessonScores[sequence]) {
        $.each(question['choices'], function (key, value) {
          value.count = 0;
          value.quid = question['question_id']
        });
        lessonScores[sequence] = question['choices'];
      }
      $.each(question['answers'], function (key, value) {
        if (question['question_type'] === 'SaQuestion') {
          var weighted_score = question['weighted_score'];
          if (weighted_score > 0) {
            lessonScores[sequence][0].count += 1;
          }
          else {
            if (lessonScores[sequence][1] === undefined) {
              lessonScores[sequence][1] = lessonScores[sequence][0];
              lessonScores[sequence][1].count = 0;
            }
            lessonScores[sequence][1].count += 1;
          }
          return;
        }
        else {
          lessonScores[sequence][value].count += 1;
        }
      });
    });
  });

  return lessonScores;
}

window.retrieveLessonScores = retrieveLessonScores;
window.ActivityTable = ActivityTable;

setUpModalWindow();<commit_msg>Avoids bug caused by wrong params in retrieveLessonScores.<commit_after>var ESC_KEY = 27;

/**
 * An activity scores table builder.
 *
 * @class
 */
function ActivityTable(activityScores) {
  this._activityScores = activityScores;
}

function openModal() {
  // Bind Esc press to close window
  $(document).on("keyup.modal", function(e) {
    if (e.keyCode == ESC_KEY) {
        closeModal();
    }
  });
  $("#question-window").show();
}

function closeModal() {
  $("#question-window, #question-container > div").hide();
  //Remove Esc binding
  $(document).off("keyup.modal");
}

/**
 * Sets up handlers for modal window.
 */
function setUpModalWindow() {
  // Bind click on background and on close button to close window
  $("#question-background, #question-window .question-close-button").on("click", function(e) {
    closeModal();
  });
  $("#question-container > div").hide();
}

ActivityTable.prototype = {
  _buildRow: function(sequence, question) {

    var tr = $('

');

    // add question number
    var td = $(
        '' +
        '  Question ' + ++sequence +
        '

' +
        '	'
    );
    td.find('.md-visibility').data('quid', question[0]['quid']);

    tr.append(td);

    td.find('.md-visibility').click(function () {
      openModal();
      var params = {
          action: 'question_preview',
          quid: $(this).data('quid')
      };
      $('#question-preview').html($('').attr(
        {id: 'question-preview', src: 'dashboard?' + $.param(params)})).show();
    });

    // add choices
    var numOfColumns = this._columnCount();
    var numCorrect = 0;
    var numIncorrect = 0;

    for (var i = 1; i <= numOfColumns; i++) {
      var td;

      if (i <= question.length) {
        var td = $(
          '' +
            question[i-1].count +
          '	'
        );

        if (question[i-1].score > 0) {
          $(td).addClass('correct-choice');
          numCorrect += question[i-1].count;
        }
        else {
          numIncorrect += question[i-1].count;
        }
      }
      else {
        var td = $(
          '--	'
        );
      }

      tr.append(td);
    }

    var totalQuestions = numCorrect + numIncorrect;
    var percentCorrect = 0;
    if (totalQuestions > 0) {
        percentCorrect = numCorrect / totalQuestions;
    }

    if (percentCorrect < .75 && percentCorrect > .5) {
      $($(tr).find('.question-info')).addClass('uncertain-question');
    }
    else if (percentCorrect <= .5) {
      $($(tr).find('.question-info')).addClass('problem-question');
    }

    return tr;
  },

  _buildHeader: function() {
    var numOfColumns = this._columnCount();

    var thead = $(
      '
' +
      '
' +
      '    	' +
      '
' +
      '
'
    );

    for (var i = 1; i <= numOfColumns; i++) {
      $(thead).find('tr').append(' Choice ' + i + '	');
    }

    return thead;
  },

  _buildBody: function() {
    var that = this;
    var tbody = $('

');

    var i = 0;
    $.each(that._activityScores, function (key, question) {
      var row = that._buildRow(key, question);
      row.addClass( i++ % 2 == 0 ? 'even' : 'odd');
      tbody.append(row);
    });

    return tbody;
  },

  _refresh: function() {
    this._table.find('tbody').remove();
    this._table.append(this._buildBody());
  },

  _columnCount: function() {
    var numOfColumns = 0;
    $.each(this._activityScores, function (key, question) {
      if (numOfColumns === 0 || question.length > numOfColumns) {
        numOfColumns = question.length;
      }
    });

    return numOfColumns;
  },

  buildTable: function(unitId, lessonId, unitTitle, lessonTitle) {
    var that = this;

    this._content = $(
      '
' +
      '' +
      '

');

    this._table = this._content.find('.questions-table');
    this._table.append(that._buildHeader());

    this._refresh();

    return this._content;
  }
};

function retrieveLessonScores(scores, unitId, lessonId) {
  var lessonScores = {};

  // Something must have changed in v1.10.  questions is frequently null.
  // The problem is units[unitId][lessonId] throws an error.
  $.each(scores, function (studentId, units) {
      var questions = {};
      var unit = units[unitId];
      if (unit) {
        questions = unit[lessonId];
        if (!questions) {
	  return lessonScores;
	}
      }
      $.each(questions, function (sequence, question) {
        console.log('for each question ' + question);
        if (!lessonScores[sequence]) {
          $.each(question['choices'], function (key, value) {
            value.count = 0;
            value.quid = question['question_id']
          });
          lessonScores[sequence] = question['choices'];
        }
        $.each(question['answers'], function (key, value) {
          if (question['question_type'] === 'SaQuestion') {
            var weighted_score = question['weighted_score'];
            if (weighted_score > 0) {
              lessonScores[sequence][0].count += 1;
            }
            else {
              if (lessonScores[sequence][1] === undefined) {
                lessonScores[sequence][1] = lessonScores[sequence][0];
                lessonScores[sequence][1].count = 0;
              }
              lessonScores[sequence][1].count += 1;
            }
            return;
          }
          else {
            lessonScores[sequence][value].count += 1;
          }
        });
      });
    });
  return lessonScores;
}

window.retrieveLessonScores = retrieveLessonScores;
window.ActivityTable = ActivityTable;

setUpModalWindow();<|endoftext|>


<commit_before>/*
 * jQuery File Upload Plugin JS Example
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 */

/* global $, window */

$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: 'view/jquery-file-upload/server/php/',
        maxChunkSize: 10000000, // 10 MB
        add: function (e, data) {
            var that = this;
            $.getJSON('view/jquery-file-upload/server/php/', {file: data.files[0].name}, function (result) {
                var file = result.file;
                data.uploadedBytes = file && file.size;
                $.blueimp.fileupload.prototype
                        .options.add.call(that, e, data);
            });
        },
        maxRetries: 100,
        retryTimeout: 500,
        fail: function (e, data) {
            // jQuery Widget Factory uses "namespace-widgetname" since version 1.10.0:
            var fu = $(this).data('blueimp-fileupload') || $(this).data('fileupload'),
                    retries = data.context.data('retries') || 0,
                    retry = function () {
                        $.getJSON('view/jquery-file-upload/server/php/', {file: data.files[0].name})
                                .done(function (result) {
                                    var file = result.file;
                                    data.uploadedBytes = file && file.size;
                                    // clear the previous data:
                                    data.data = null;
                                    data.submit();
                                })
                                .fail(function () {
                                    fu._trigger('fail', e, data);
                                });
                    };
            if (data.errorThrown !== 'abort' &&
                    data.uploadedBytes < data.files[0].size &&
                    retries < fu.options.maxRetries) {
                retries += 1;
                data.context.data('retries', retries);
                window.setTimeout(retry, retries * fu.options.retryTimeout);
                return;
            }
            data.context.removeData('retries');
            $.blueimp.fileupload.prototype
                    .options.fail.call(this, e, data);
        }
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
            'option',
            'redirect',
            window.location.href.replace(
                    /\/[^\/]*$/,
                    '/cors/result.html?%s'
                    )
            );

    if (window.location.hostname === 'blueimp.github.io') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com/',
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                    .test(window.navigator.userAgent),
            maxFileSize: 999000,
            acceptFileTypes: /(\.|\/)(mp4|avi|mov|flv|mp3|wav|m4v|webm|wmv|mpg|mpeg|f4v|m4v|m4a|m2p|rm|vob|mkv|3gp)$/i
        });
        // Upload server status check for browsers with CORS support:
        if ($.support.cors) {
            $.ajax({
                url: '//jquery-file-upload.appspot.com/',
                type: 'HEAD'
            }).fail(function () {
                $('
')
                        .text('Upload server currently unavailable - ' +
                                new Date())
                        .appendTo('#fileupload');
            });
        }
    } else {
        // Load existing files:
        $('#fileupload').addClass('fileupload-processing');
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function () {
            $(this).removeClass('fileupload-processing');
        }).done(function (result) {
            $(this).fileupload('option', 'done')
                    .call(this, $.Event('done'), {result: result});
        });
    }
    $('#fileupload').bind('fileuploadsubmit', function (e, data) {
        data.formData = {
            "audioOnly": $('#inputAudioOnly').is(":checked"),
            "spectrum": $('#inputAudioSpectrum').is(":checked"),
            "webm": $('#inputWebM').is(":checked"),
            "inputHLS": $('#inputHLS').is(":checked"),
            "inputLow": $('#inputLow').is(":checked"),
            "inputSD": $('#inputSD').is(":checked"),
            "inputHD": $('#inputHD').is(":checked"),
            "title": $('#title').val(),
            "description": $('#description').val(),
            "categories_id": $('#categories_id').val()
        };
    }).bind('fileuploaddone', function (e, data) {
        console.log(e);
        console.log(data);
        $.ajax({
            url: 'view/jquery-file-upload/server/php/fileuploadchunkdone.php',
            data: {
                "file": data.files[0].name,
                "audioOnly": $('#inputAudioOnly').is(":checked"),
                "spectrum": $('#inputAudioSpectrum').is(":checked"),
                "webm": $('#inputWebM').is(":checked"),
                "inputHLS": $('#inputHLS').is(":checked"),
                "inputLow": $('#inputLow').is(":checked"),
                "inputSD": $('#inputSD').is(":checked"),
                "inputHD": $('#inputHD').is(":checked"),
                "title": $('#title').val(),
                "description": $('#description').val(),
                "categories_id": $('#categories_id').val()
            },
            type: 'post',
            success: function (response) {
                console.log(response);
            }
        });
    });
});
<commit_msg>Version 2.6 adding chunked and resumable file uploads<commit_after>/*
 * jQuery File Upload Plugin JS Example
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * https://opensource.org/licenses/MIT
 */

/* global $, window */

$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: 'view/jquery-file-upload/server/php/',
        maxChunkSize: 5000000, // 5 MB
        add: function (e, data) {
            var that = this;
            $.getJSON('view/jquery-file-upload/server/php/', {file: data.files[0].name}, function (result) {
                var file = result.file;
                data.uploadedBytes = file && file.size;
                $.blueimp.fileupload.prototype
                        .options.add.call(that, e, data);
            });
        },
        maxRetries: 100,
        retryTimeout: 500,
        fail: function (e, data) {
            // jQuery Widget Factory uses "namespace-widgetname" since version 1.10.0:
            var fu = $(this).data('blueimp-fileupload') || $(this).data('fileupload'),
                    retries = data.context.data('retries') || 0,
                    retry = function () {
                        $.getJSON('view/jquery-file-upload/server/php/', {file: data.files[0].name})
                                .done(function (result) {
                                    var file = result.file;
                                    data.uploadedBytes = file && file.size;
                                    // clear the previous data:
                                    data.data = null;
                                    data.submit();
                                })
                                .fail(function () {
                                    fu._trigger('fail', e, data);
                                });
                    };
            if (data.errorThrown !== 'abort' &&
                    data.uploadedBytes < data.files[0].size &&
                    retries < fu.options.maxRetries) {
                retries += 1;
                data.context.data('retries', retries);
                window.setTimeout(retry, retries * fu.options.retryTimeout);
                return;
            }
            data.context.removeData('retries');
            $.blueimp.fileupload.prototype
                    .options.fail.call(this, e, data);
        }
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
            'option',
            'redirect',
            window.location.href.replace(
                    /\/[^\/]*$/,
                    '/cors/result.html?%s'
                    )
            );

    if (window.location.hostname === 'blueimp.github.io') {
        // Demo settings:
        $('#fileupload').fileupload('option', {
            url: '//jquery-file-upload.appspot.com/',
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                    .test(window.navigator.userAgent),
            maxFileSize: 999000,
            acceptFileTypes: /(\.|\/)(mp4|avi|mov|flv|mp3|wav|m4v|webm|wmv|mpg|mpeg|f4v|m4v|m4a|m2p|rm|vob|mkv|3gp)$/i
        });
        // Upload server status check for browsers with CORS support:
        if ($.support.cors) {
            $.ajax({
                url: '//jquery-file-upload.appspot.com/',
                type: 'HEAD'
            }).fail(function () {
                $('
')
                        .text('Upload server currently unavailable - ' +
                                new Date())
                        .appendTo('#fileupload');
            });
        }
    } else {
        // Load existing files:
        $('#fileupload').addClass('fileupload-processing');
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: $('#fileupload').fileupload('option', 'url'),
            dataType: 'json',
            context: $('#fileupload')[0]
        }).always(function () {
            $(this).removeClass('fileupload-processing');
        }).done(function (result) {
            $(this).fileupload('option', 'done')
                    .call(this, $.Event('done'), {result: result});
        });
    }
    $('#fileupload').bind('fileuploadsubmit', function (e, data) {
        data.formData = {
            "audioOnly": $('#inputAudioOnly').is(":checked"),
            "spectrum": $('#inputAudioSpectrum').is(":checked"),
            "webm": $('#inputWebM').is(":checked"),
            "inputHLS": $('#inputHLS').is(":checked"),
            "inputLow": $('#inputLow').is(":checked"),
            "inputSD": $('#inputSD').is(":checked"),
            "inputHD": $('#inputHD').is(":checked"),
            "title": $('#title').val(),
            "description": $('#description').val(),
            "categories_id": $('#categories_id').val()
        };
    }).bind('fileuploaddone', function (e, data) {
        console.log(e);
        console.log(data);
        $.ajax({
            url: 'view/jquery-file-upload/server/php/fileuploadchunkdone.php',
            data: {
                "file": data.files[0].name,
                "audioOnly": $('#inputAudioOnly').is(":checked"),
                "spectrum": $('#inputAudioSpectrum').is(":checked"),
                "webm": $('#inputWebM').is(":checked"),
                "inputHLS": $('#inputHLS').is(":checked"),
                "inputLow": $('#inputLow').is(":checked"),
                "inputSD": $('#inputSD').is(":checked"),
                "inputHD": $('#inputHD').is(":checked"),
                "title": $('#title').val(),
                "description": $('#description').val(),
                "categories_id": $('#categories_id').val()
            },
            type: 'post',
            success: function (response) {
                console.log(response);
            }
        });
    });
});
<|endoftext|>