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

/*
 * AJAX get event given event ID
 */

exports.getEvent = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');
  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      res.render("event", {
        theme: req.session.theme,
        eventId: eventId,
        eventType: record.getType(),
        allVoted: record.allVoted(),
        notVoted: record.notVoted(id),
        notDecided: record.notDecided(id),
        startDate: record.startDate,
        endDate: record.endDate,
        firstUse: req.session.first_use,
        firstDecide: req.session.first_decide
      });
    } else {
      res.send(404);
    }
  });
};

exports.getHeatmap = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');
  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      var self = req.query.self || false;
      res.json(record.genHeatmap(id, self));
    } else {
      res.send(404);
    }
  });
};

exports.getSlot = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');

  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      for (var i = 0; i < record.participants.length; ++i) {
        if (record.participants[i].personId === id) {
          return res.json(record.participants[i].slot);
        }
      }
    } else {
      res.send(404);
    }
  });
};

/*
 * AJAX get event list given user's ID
 */

exports.listEvent = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var Event = req.app.get('models')('event');
  Event.find({ 'participants.personId': id },
    function(error, record) {
      record.sort(function(a, b) {
        var acode = 2, bcode = 2;
        if (a.notDecided(id) && a.isPending()) acode = 0;
        if (a.notVoted(id) && a.isOngoing()) acode = 1;
        if (b.notDecided(id) && b.isPending()) bcode = 0;
        if (b.notVoted(id) && b.isOngoing()) bcode = 1;
        return (acode + a.deadline) > (bcode + b.deadline);
      });
      res.render('list', {
        theme: req.session.theme,
        fb_id: req.session.fb_id,
        fb_name: req.session.fb_name,
        events: record
      });
    }
  );
};

/*
 * AJAX new event
 */

exports.createEventPage = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  res.render("new", {theme: req.session.theme});
}

exports.createEvent = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var data = req.body;
  data.eventId = crypto.randomBytes(20).toString('hex');
  //data.participants = data.participants || [];
  data.participants = [
    {
      "name" : "Andrew Liu",
      "personId" : "766485187",
    },
    {
      "name" : "Jocelin Ho",
      "personId" : "100000010285733",
    }
  ];
  // add myself as participant
  data.participants.push({
    name: req.session.fb_name,
    personId: req.session.fb_id
  });

  // merge hour and min to duration
  data.duration = data["duration-hr"] + data["duration-min"];
  data.host = {
    name: req.session.fb_name,
    personId: req.session.fb_id
  };

  var Event = req.app.get('models')('event');
  var newEvent = new Event(data);
  newEvent.save(function(error) {
    if (error) {
      console.log(error);
    }
    res.redirect("/events");
  });
};

exports.updateEvent = function(req, res) {
  // TODO
};

/*
 * AJAX update slot
 */

exports.updateSlot = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var slot = req.body.slot;

  var Event = req.app.get('models')('event');
  Event.update(
    { eventId: eventId, "participants.personId": id },
    { $set: { "participants.$.slot": slot } },
    function(error) {
      if (error) console.log(error);

      var User = req.app.get('models')('user');
      console
      User.update( {fb_id: id}, {$set: {firstUse: false}}, function(error) {
        console.log("Updated: not first time");
        req.session.first_use = false;
        if (error) console.log(error);
        res.json("");
      })
    }
  );
};

exports.decideSlot = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var decision = req.body.slot[0];

  var Event = req.app.get('models')('event');
  Event.update(
    { eventId: eventId },
    { $set: { "decision": decision } },
    function(error) {
      if (error) {
        console.log(error);
      }
      res.json("");
    }
  );
}

exports.getDecision = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');

  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      res.json([record.decision]);
    } else {
      res.send(404);
    }
  });
};
<commit_msg>Change the order of Go vote and Go decide<commit_after>var crypto = require('crypto');

/*
 * AJAX get event given event ID
 */

exports.getEvent = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');
  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      res.render("event", {
        theme: req.session.theme,
        eventId: eventId,
        eventType: record.getType(),
        allVoted: record.allVoted(),
        notVoted: record.notVoted(id),
        notDecided: record.notDecided(id),
        startDate: record.startDate,
        endDate: record.endDate,
        firstUse: req.session.first_use,
        firstDecide: req.session.first_decide
      });
    } else {
      res.send(404);
    }
  });
};

exports.getHeatmap = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');
  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      var self = req.query.self || false;
      res.json(record.genHeatmap(id, self));
    } else {
      res.send(404);
    }
  });
};

exports.getSlot = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');

  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      for (var i = 0; i < record.participants.length; ++i) {
        if (record.participants[i].personId === id) {
          return res.json(record.participants[i].slot);
        }
      }
    } else {
      res.send(404);
    }
  });
};

/*
 * AJAX get event list given user's ID
 */

exports.listEvent = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var Event = req.app.get('models')('event');
  Event.find({ 'participants.personId': id },
    function(error, record) {
      record.sort(function(a, b) {
        var acode = 2, bcode = 2;
        if (a.notDecided(id) && a.isPending()) acode = 1;
        if (a.notVoted(id) && a.isOngoing()) acode = 0;
        if (b.notDecided(id) && b.isPending()) bcode = 1;
        if (b.notVoted(id) && b.isOngoing()) bcode = 0;
        return (acode + a.deadline) > (bcode + b.deadline);
      });
      res.render('list', {
        theme: req.session.theme,
        fb_id: req.session.fb_id,
        fb_name: req.session.fb_name,
        events: record
      });
    }
  );
};

/*
 * AJAX new event
 */

exports.createEventPage = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  res.render("new", {theme: req.session.theme});
}

exports.createEvent = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var data = req.body;
  data.eventId = crypto.randomBytes(20).toString('hex');
  //data.participants = data.participants || [];
  data.participants = [
    {
      "name" : "Andrew Liu",
      "personId" : "766485187",
    },
    {
      "name" : "Jocelin Ho",
      "personId" : "100000010285733",
    }
  ];
  // add myself as participant
  data.participants.push({
    name: req.session.fb_name,
    personId: req.session.fb_id
  });

  // merge hour and min to duration
  data.duration = data["duration-hr"] + data["duration-min"];
  data.host = {
    name: req.session.fb_name,
    personId: req.session.fb_id
  };

  var Event = req.app.get('models')('event');
  var newEvent = new Event(data);
  newEvent.save(function(error) {
    if (error) {
      console.log(error);
    }
    res.redirect("/events");
  });
};

exports.updateEvent = function(req, res) {
  // TODO
};

/*
 * AJAX update slot
 */

exports.updateSlot = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var slot = req.body.slot;

  var Event = req.app.get('models')('event');
  Event.update(
    { eventId: eventId, "participants.personId": id },
    { $set: { "participants.$.slot": slot } },
    function(error) {
      if (error) console.log(error);

      var User = req.app.get('models')('user');
      console
      User.update( {fb_id: id}, {$set: {firstUse: false}}, function(error) {
        console.log("Updated: not first time");
        req.session.first_use = false;
        if (error) console.log(error);
        res.json("");
      })
    }
  );
};

exports.decideSlot = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var decision = req.body.slot[0];

  var Event = req.app.get('models')('event');
  Event.update(
    { eventId: eventId },
    { $set: { "decision": decision } },
    function(error) {
      if (error) {
        console.log(error);
      }
      res.json("");
    }
  );
}

exports.getDecision = function(req, res) {
  var id = req.session.fb_id;
  if (!id) return res.redirect('/login');

  var eventId = req.params.id;
  var Event = req.app.get('models')('event');

  Event.findOne({ eventId: eventId }, function(error, record) {
    if (record) {
      res.json([record.decision]);
    } else {
      res.send(404);
    }
  });
};
<|endoftext|>


<commit_before>exports.get = function(req, res) {
	res.send("You're a mentorafa")
}<commit_msg>Test gitpull<commit_after>exports.get = function(req, res) {
	res.send("You're a ")
}<|endoftext|>


<commit_before>/*
* Copyright 2015 CareerBuilder, LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
var express = require('express');
var db = require('../tools/db_tool.js');
var aws = require('aws-sdk');
var exec = require('child_process').execFile;
var fs = require('fs');
var aws_obj = {region:global.config.Region};
if('Amazon' in global.config){
  if (global.config.AccessKey && global.config.SecretKey){
    aws_obj.accessKeyId = global.config.AccessKey;
    aws_obj.secretAccessKey = global.config.SecretKey;
  }else{
    console.log('Cant find keys in config');
  }

}
var ec2 = new aws.EC2(aws_obj);
var router = express.Router();

var stacksrepo = global.config.STACKREPO;
if(!stacksrepo){
  console.log("Stacks_Repo not configured");
}

router.get('/regions', function(req, res){
  ec2.describeRegions({}, function(err, data){
    if(err){
      console.log('Error describing regions: ', err);
      return res.send({Success:false, Error: err});
    }
    var regions = [];
    for(var i=0; i<data.Regions.length; i++){
      regions.push(data.Regions[i].RegionName);
    }
    return res.send({Success: true, Regions: regions});
  });
});

router.get('/', function(req, res){
  db.get_stacks({},function(err, results){
    if(err){
      console.log(err);
      return res.send({Success: false, Error: err});
    }
    return res.send({Success:true, Data:results});
  });
});

router.get('/:name', function(req, res){
  db.get_stack({"Name":req.params.name}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success: false, Error:err});
    }
    return res.send({Success:true, Data: result});
  });
});

router.post('/', function(req, res){
  var build = req.body.build;
  var email = req.body.user;
  var name = build.Name.trim();
  var template = build.Template;
  db.put_stack({Name:build.Name}, build, function(err, result){
    if(err){
      console.log(err);
      return res.send({Code: -1, Error:err});
    }
    else{
      if(stacksrepo){
        var stackspath = stacksrepo + "/" + name +".stack";
        fs.writeFile(stackspath, JSON.stringify(template), function(err){
          if(err){
            console.log(err);
            return res.send({Code: 399, Message: "Stack not saved!", Error:err});
          }
          else{
            try{
              var userstring = '"'+email.split('@')[0].replace('\.', ' ') +' <'+email+'>'+'"';
              exec('./VersionControl.sh', [userstring, stacksrepo], function(err, stdout, stderr){
                if(err){
                  console.log(err);
                  return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
                }
                console.log(stdout, '\n', stderr);
                return res.send({Code: 400, Message: "Stack Saved!"});
              });
            } catch(e){
              return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
            }
          }
        });
      }
      else{
        console.log("Added stack without git hook");
        return res.send({Code: 388, Message: "No Stack Repo configured"});
      }
    }
  });
});

router.post('/build/:name', function(req, res){
  var auth = req.body.userid;
  db.get_user({"confirm":auth}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success:false, Error: err});
    }
    var auth = {
      accesskey: result.accesskey,
      secretkey: result.secretkey
    };
    db.get_stack({"Name":req.params.name}, function(err, results){
      if(err){
        console.log(err);
        return res.send({Success: false, Error:err});
      }
      var stack = results;

      // Replace CidrIp with SGsource in

      if (stack.Template.Resources){
        console.log("found resources");
        for (var key in stack.Template.Resources){
          console.log("found a resource");
          var resource = stack.Template.Resources[key];
          console.log(resource);
          if (resource.Type == "AWS::EC2::SecurityGroup"){
            console.log("found SG");
            if (resource.Properties.SecurityGroupIngress){
              console.log("found SGIngress");
              for (var i = 0; i < resource.Properties.SecurityGroupIngress.length; i++){
                console.log("found model");
                var model = resource.Properties.SecurityGroupIngress[i];
                console.log(model);
                if (model.CidrIp && (model.CidrIp.indexOf("sg-") === 0)){
                  console.log("found SGsource to replace");
                  model.SourceSecurityGroupId = model.CidrIp;
                  delete model.CidrIp;
                  console.log(resource.Properties.SecurityGroupIngress);
                }
              }
            }
          }
        }
      }

      var cf = new aws.CloudFormation({accessKeyId: auth.accesskey, secretAccessKey: auth.secretkey, region: stack.Region});
      var stackname = stack.Name;
      cf.describeStacks({"StackName": stackname}, function(err, data){
        if(err){
          console.log("Creating stack");
          cf.createStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2)}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
        else{
          cf.updateStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2), "UsePreviousTemplate":false}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
      });
    });
  });
});

module.exports = router;
<commit_msg>no more debugs, cidrIp replacement works now<commit_after>/*
* Copyright 2015 CareerBuilder, LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
var express = require('express');
var db = require('../tools/db_tool.js');
var aws = require('aws-sdk');
var exec = require('child_process').execFile;
var fs = require('fs');
var aws_obj = {region:global.config.Region};
if('Amazon' in global.config){
  if (global.config.AccessKey && global.config.SecretKey){
    aws_obj.accessKeyId = global.config.AccessKey;
    aws_obj.secretAccessKey = global.config.SecretKey;
  }else{
    console.log('Cant find keys in config');
  }

}
var ec2 = new aws.EC2(aws_obj);
var router = express.Router();

var stacksrepo = global.config.STACKREPO;
if(!stacksrepo){
  console.log("Stacks_Repo not configured");
}

router.get('/regions', function(req, res){
  ec2.describeRegions({}, function(err, data){
    if(err){
      console.log('Error describing regions: ', err);
      return res.send({Success:false, Error: err});
    }
    var regions = [];
    for(var i=0; i<data.Regions.length; i++){
      regions.push(data.Regions[i].RegionName);
    }
    return res.send({Success: true, Regions: regions});
  });
});

router.get('/', function(req, res){
  db.get_stacks({},function(err, results){
    if(err){
      console.log(err);
      return res.send({Success: false, Error: err});
    }
    return res.send({Success:true, Data:results});
  });
});

router.get('/:name', function(req, res){
  db.get_stack({"Name":req.params.name}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success: false, Error:err});
    }
    return res.send({Success:true, Data: result});
  });
});

router.post('/', function(req, res){
  var build = req.body.build;
  var email = req.body.user;
  var name = build.Name.trim();
  var template = build.Template;
  db.put_stack({Name:build.Name}, build, function(err, result){
    if(err){
      console.log(err);
      return res.send({Code: -1, Error:err});
    }
    else{
      if(stacksrepo){
        var stackspath = stacksrepo + "/" + name +".stack";
        fs.writeFile(stackspath, JSON.stringify(template), function(err){
          if(err){
            console.log(err);
            return res.send({Code: 399, Message: "Stack not saved!", Error:err});
          }
          else{
            try{
              var userstring = '"'+email.split('@')[0].replace('\.', ' ') +' <'+email+'>'+'"';
              exec('./VersionControl.sh', [userstring, stacksrepo], function(err, stdout, stderr){
                if(err){
                  console.log(err);
                  return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
                }
                console.log(stdout, '\n', stderr);
                return res.send({Code: 400, Message: "Stack Saved!"});
              });
            } catch(e){
              return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
            }
          }
        });
      }
      else{
        console.log("Added stack without git hook");
        return res.send({Code: 388, Message: "No Stack Repo configured"});
      }
    }
  });
});

router.post('/build/:name', function(req, res){
  var auth = req.body.userid;
  db.get_user({"confirm":auth}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success:false, Error: err});
    }
    var auth = {
      accesskey: result.accesskey,
      secretkey: result.secretkey
    };
    db.get_stack({"Name":req.params.name}, function(err, results){
      if(err){
        console.log(err);
        return res.send({Success: false, Error:err});
      }
      var stack = results;

      // Replace CidrIp with SGsource in

      if (stack.Template.Resources){
        for (var key in stack.Template.Resources){
          var resource = stack.Template.Resources[key];
          if (resource.Type == "AWS::EC2::SecurityGroup"){
            if (resource.Properties.SecurityGroupIngress){
              for (var i = 0; i < resource.Properties.SecurityGroupIngress.length; i++){
                var model = resource.Properties.SecurityGroupIngress[i];
                if (model.CidrIp && (model.CidrIp.indexOf("sg-") === 0)){
                  model.SourceSecurityGroupId = model.CidrIp;
                  delete model.CidrIp;
                }
              }
            }
          }
        }
      }

      var cf = new aws.CloudFormation({accessKeyId: auth.accesskey, secretAccessKey: auth.secretkey, region: stack.Region});
      var stackname = stack.Name;
      cf.describeStacks({"StackName": stackname}, function(err, data){
        if(err){
          console.log("Creating stack");
          cf.createStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2)}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
        else{
          cf.updateStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2), "UsePreviousTemplate":false}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
      });
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>/*
* Copyright 2015 CareerBuilder, LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
var express = require('express');
var db = require('../tools/db_tool.js');
var aws = require('aws-sdk');
var exec = require('child_process').execFile;
var fs = require('fs');
var aws_obj = {region:global.config.Region};
if('Amazon' in global.config){
  if (global.config.AccessKey && global.config.SecretKey){
    aws_obj.accessKeyId = global.config.AccessKey;
    aws_obj.secretAccessKey = global.config.SecretKey;
  }else{
    console.log('Cant find keys in config');
  }

}
var ec2 = new aws.EC2(aws_obj);
var router = express.Router();

var stacksrepo = global.config.STACKREPO;
if(!stacksrepo){
  console.log("Stacks_Repo not configured");
}

router.get('/regions', function(req, res){
  ec2.describeRegions({}, function(err, data){
    if(err){
      console.log('Error describing regions: ', err);
      return res.send({Success:false, Error: err});
    }
    var regions = [];
    for(var i=0; i<data.Regions.length; i++){
      regions.push(data.Regions[i].RegionName);
    }
    return res.send({Success: true, Regions: regions});
  });
});

router.get('/', function(req, res){
  db.get_stacks({},function(err, results){
    if(err){
      console.log(err);
      return res.send({Success: false, Error: err});
    }
    return res.send({Success:true, Data:results});
  });
});

router.get('/:name', function(req, res){
  db.get_stack({"Name":req.params.name}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success: false, Error:err});
    }
    return res.send({Success:true, Data: result});
  });
});

router.post('/', function(req, res){
  var build = req.body.build;
  var email = req.body.user;
  var name = build.Name.trim();
  var template = build.Template;
  db.put_stack({Name:build.Name}, build, function(err, result){
    if(err){
      console.log(err);
      return res.send({Code: -1, Error:err});
    }
    else{
      if(stacksrepo){
        var stackspath = stacksrepo + "/" + name +".stack";
        fs.writeFile(stackspath, JSON.stringify(template), function(err){
          if(err){
            console.log(err);
            return res.send({Code: 399, Message: "Stack not saved!", Error:err});
          }
          else{
            try{
              var userstring = '"'+email.split('@')[0].replace('\.', ' ') +' <'+email+'>'+'"';
              exec('./VersionControl.sh', [userstring, stacksrepo], function(err, stdout, stderr){
                if(err){
                  console.log(err);
                  return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
                }
                console.log(stdout, '\n', stderr);
                return res.send({Code: 400, Message: "Stack Saved!"});
              });
            } catch(e){
              return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
            }
          }
        });
      }
      else{
        console.log("Added stack without git hook");
        return res.send({Code: 388, Message: "No Stack Repo configured"});
      }
    }
  });
});

router.post('/build/:name', function(req, res){
  var auth = req.body.userid;
  db.get_user({"confirm":auth}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success:false, Error: err});
    }
    var auth = {
      accesskey: result.accesskey,
      secretkey: result.secretkey
    };
    db.get_stack({"Name":req.params.name}, function(err, results){
      if(err){
        console.log(err);
        return res.send({Success: false, Error:err});
      }
      var stack = results;

      // Replace CidrIp with SGsource in

      if (stack.Template.Resources){
        console.log("found resources");
        for (var key in stack.Template.Resources){
          console.log("found a resource");
          var resource = stack.Template.Resources[key];
          console.log(resource);
          if (resource.Type == "AWS::EC2::SecurityGroup"){
            console.log("found SG");
            if (resource.Properties.SecurityGroupIngress){
              console.log("found SGIngress");
              for (var i = 0; i < resource.Properties.SecurityGroupIngress.length; i++){
                console.log("found model");
                var model = resource.Properties.SecurityGroupIngress[i];
                if (model.CidrIp.Value && (model.CidrIp.Value.indexOf("sg-") === 0)){
                  console.log("found SGsource to replace");
                  model.SourceSecurityGroupId = model.CidrIp;
                  delete model.CidrIp;
                  console.log(resource.Properties.SecurityGroupIngress);
                }
              }
            }
          }
        }
      }

      var cf = new aws.CloudFormation({accessKeyId: auth.accesskey, secretAccessKey: auth.secretkey, region: stack.Region});
      var stackname = stack.Name;
      cf.describeStacks({"StackName": stackname}, function(err, data){
        if(err){
          console.log("Creating stack");
          cf.createStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2)}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
        else{
          cf.updateStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2), "UsePreviousTemplate":false}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
      });
    });
  });
});

module.exports = router;
<commit_msg>debug<commit_after>/*
* Copyright 2015 CareerBuilder, LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
var express = require('express');
var db = require('../tools/db_tool.js');
var aws = require('aws-sdk');
var exec = require('child_process').execFile;
var fs = require('fs');
var aws_obj = {region:global.config.Region};
if('Amazon' in global.config){
  if (global.config.AccessKey && global.config.SecretKey){
    aws_obj.accessKeyId = global.config.AccessKey;
    aws_obj.secretAccessKey = global.config.SecretKey;
  }else{
    console.log('Cant find keys in config');
  }

}
var ec2 = new aws.EC2(aws_obj);
var router = express.Router();

var stacksrepo = global.config.STACKREPO;
if(!stacksrepo){
  console.log("Stacks_Repo not configured");
}

router.get('/regions', function(req, res){
  ec2.describeRegions({}, function(err, data){
    if(err){
      console.log('Error describing regions: ', err);
      return res.send({Success:false, Error: err});
    }
    var regions = [];
    for(var i=0; i<data.Regions.length; i++){
      regions.push(data.Regions[i].RegionName);
    }
    return res.send({Success: true, Regions: regions});
  });
});

router.get('/', function(req, res){
  db.get_stacks({},function(err, results){
    if(err){
      console.log(err);
      return res.send({Success: false, Error: err});
    }
    return res.send({Success:true, Data:results});
  });
});

router.get('/:name', function(req, res){
  db.get_stack({"Name":req.params.name}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success: false, Error:err});
    }
    return res.send({Success:true, Data: result});
  });
});

router.post('/', function(req, res){
  var build = req.body.build;
  var email = req.body.user;
  var name = build.Name.trim();
  var template = build.Template;
  db.put_stack({Name:build.Name}, build, function(err, result){
    if(err){
      console.log(err);
      return res.send({Code: -1, Error:err});
    }
    else{
      if(stacksrepo){
        var stackspath = stacksrepo + "/" + name +".stack";
        fs.writeFile(stackspath, JSON.stringify(template), function(err){
          if(err){
            console.log(err);
            return res.send({Code: 399, Message: "Stack not saved!", Error:err});
          }
          else{
            try{
              var userstring = '"'+email.split('@')[0].replace('\.', ' ') +' <'+email+'>'+'"';
              exec('./VersionControl.sh', [userstring, stacksrepo], function(err, stdout, stderr){
                if(err){
                  console.log(err);
                  return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
                }
                console.log(stdout, '\n', stderr);
                return res.send({Code: 400, Message: "Stack Saved!"});
              });
            } catch(e){
              return res.send({Code: 399, Message: "Stack saved to datastore, but not git", Error: err});
            }
          }
        });
      }
      else{
        console.log("Added stack without git hook");
        return res.send({Code: 388, Message: "No Stack Repo configured"});
      }
    }
  });
});

router.post('/build/:name', function(req, res){
  var auth = req.body.userid;
  db.get_user({"confirm":auth}, function(err, result){
    if(err){
      console.log(err);
      return res.send({Success:false, Error: err});
    }
    var auth = {
      accesskey: result.accesskey,
      secretkey: result.secretkey
    };
    db.get_stack({"Name":req.params.name}, function(err, results){
      if(err){
        console.log(err);
        return res.send({Success: false, Error:err});
      }
      var stack = results;

      // Replace CidrIp with SGsource in

      if (stack.Template.Resources){
        console.log("found resources");
        for (var key in stack.Template.Resources){
          console.log("found a resource");
          var resource = stack.Template.Resources[key];
          console.log(resource);
          if (resource.Type == "AWS::EC2::SecurityGroup"){
            console.log("found SG");
            if (resource.Properties.SecurityGroupIngress){
              console.log("found SGIngress");
              for (var i = 0; i < resource.Properties.SecurityGroupIngress.length; i++){
                console.log("found model");
                var model = resource.Properties.SecurityGroupIngress[i];
                console.log(model);
                if (model.CidrIp.Value && (model.CidrIp.Value.indexOf("sg-") === 0)){
                  console.log("found SGsource to replace");
                  model.SourceSecurityGroupId = model.CidrIp;
                  delete model.CidrIp;
                  console.log(resource.Properties.SecurityGroupIngress);
                }
              }
            }
          }
        }
      }

      var cf = new aws.CloudFormation({accessKeyId: auth.accesskey, secretAccessKey: auth.secretkey, region: stack.Region});
      var stackname = stack.Name;
      cf.describeStacks({"StackName": stackname}, function(err, data){
        if(err){
          console.log("Creating stack");
          cf.createStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2)}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
        else{
          cf.updateStack({"StackName": stackname, "Capabilities":['CAPABILITY_IAM'], "TemplateBody":JSON.stringify(stack.Template,null,2), "UsePreviousTemplate":false}, function(err, data){
            if(err){
              console.log(err);
              return res.send({Success: false, Error:err.message});
            }
            return res.send({Success: true, Data: data});
          });
        }
      });
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var searchService = require('../services/SearchService');
var matchService = require('../services/MatchService');
var express = require('express');
var router = express.Router();

/* Toont de statuspagina. */
router.get('/', function (req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.redirect('/login');
    }

    // Heeft deze user wel searchorders en is er minimaal één afgerond?
    searchService.getAllSearchOrdersByFaceBookId(req.session.user.fbid).then( function (searchorders) {
        if (!searchorders || searchorders.length == 0) {
            // Geen searchorders voor deze ID, doorverwijzen naar de filters om er een aan te maken.
            req.session.last_error = "";
            res.redirect('/filters');
        } else {
            // Zijn alle searchorders afgerond?
            var all_completed = true;
            searchorders.forEach(function (el) {
                if (el.MatchCriteria.Complete !== 1) { all_completed = false;}
            });

            if (!all_completed) {
                // Er is een openstaande searchorder, door naar het filterscherm.
                req.session.last_error = "";
                res.redirect('/filters');
            } else {
                // Alle searchorders afgerond, we kunnen het statusscherm tonen. We geven een lijst mee van
                //  searchorders.
                var orders = [];
                var genders = {'m': 'man', 'v': 'vrouw', 'b': 'bi'};
                searchorders.forEach(function (el) {
                    var desc = genders[el.MatchCriteria.Gender] + ' - ' + el.MatchCriteria.Age.min + ' tot ' +
                        el.MatchCriteria.Age.max + ' - ' + el.MatchCriteria.Range + ' km van ' + el.MatchCriteria.City;
                    orders.push({order_id: el._id, val: desc});
                });

                req.session.last_error = "";
                res.render('status', { searchorders: orders, session: req.session});
            }
        }
    }).fail(function (error) {
        req.session.last_error = 'Fout bij ophalen searchorders: ' + error.message;
        res.render('status', { session: req.session });
    }).done();

});

router.get('/getMatchesList', function(req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.status(403).end();
    }

    var order_id = req.param('id', '');
    var searchorder = searchService.getSearchOrderById(order_id).then(function (searchorder) {
        if (!searchorder) {
            // Ongeldige search order meegegeven.
            req.session.last_error = "";
            res.status(404).end();
        } else {
            // TODO - checken of dit wel een searchorder is van de ingelogde gebruiker.

            // Ophalen alle TinderMatches en response vullen.
            var match_list = [];

            searchorder.Matches.forEach(function(el) {
                var status = 'unknown';
                if (el.Success === true) {
                    status = 'success';
                } else if (el.Success === false) {
                    status = 'fail';
                } else if (el.Success === null) {
                    if (el.Response.length > 0) {
                        status = 'response';
                    } else if (el.Response.LikedBack === true) {
                        status = 'waiting';
                    }
                }

                var birth_date = new Date(el.UserInfo.birth_date);
                var age = ~~((Date.now() - birth_date) / (31557600000));

                match_list.push({match_id: el.UserInfo._id,
                    name: el.UserInfo.name,
                    bio: el.UserInfo.bio,
                    photo: el.UserInfo.photos[0].url,
                    gender: (el.UserInfo.gender == 1) ? 'v' : 'm',
                    age: age,
                    distance: el.UserInfo.distance_mi * 1.6,
                    status: status});
            });

            req.session.last_error = '';
            res.json(match_list);
        }
    }).done();
});

router.get('/getMatch', function(req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.status(403).end();
    }

    var order_id = req.param('order_id', '');
    var match_id = req.param('match_id', '');
    var searchorder = searchService.getSearchOrderById(order_id).then(function (searchorder) {
        if (!searchorder) {
            // Ongeldige searchorderid meegegeven.
            req.session.last_error = "";
            res.status(404).end();
        } else {
            // TODO - checken of dit wel een searchorder is van de ingelogde gebruiker.

            // Ophalen juiste match binnen de searchorder.
            var match = null;
            searchorder.Matches.every ( function (el) {
                if (el.UserInfo._id == match_id) {
                    match = el;
                    return false;
                }
                return true;
            });
            if (!match) {
                // Ongeldige matchid meegegeven.
                req.session.last_error = "";
                res.status(404).end();
            }

            // Checken of deze match wel een status 'response' heeft.
            // TODO - enablen.
            if (false /*match.Success !== null || match.Response.length == 0*/) {
                req.session.last_error = "";
                res.status(404).end();
            } else {
                // Teruggeven gegevens van deze match.
                var birth_date = new Date(match.UserInfo.birth_date);
                var age = ~~((Date.now() - birth_date) / (31557600000));

                req.session.last_error = '';
                res.json({order_id: searchorder._id,
                    match_id: match.UserInfo._id,
                    name: match.UserInfo.name,
                    bio: match.UserInfo.bio,
                    photo: match.UserInfo.photos[0].url,
                    gender: (match.UserInfo.gender == 1) ? 'v' : 'm',
                    age: age,
                    distance: match.UserInfo.distance_mi * 1.6,
                    // TODO
                    responses: [
                            'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
                            'Nog een zin!!!1 fdjfdh%&^%*%^%^%^',
                            'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, etc.'
                    ]     });
                    //responses: match.Response});
            }
        }
    }).done();

});

module.exports = router;
<commit_msg>Eerste versie matchresponse<commit_after>var searchService = require('../services/SearchService');
var matchService = require('../services/MatchService');
var express = require('express');
var router = express.Router();

/* Toont de statuspagina. */
router.get('/', function (req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.redirect('/login');
    }

    // Heeft deze user wel searchorders en is er minimaal één afgerond?
    searchService.getAllSearchOrdersByFaceBookId(req.session.user.fbid).then( function (searchorders) {
        if (!searchorders || searchorders.length == 0) {
            // Geen searchorders voor deze ID, doorverwijzen naar de filters om er een aan te maken.
            req.session.last_error = "";
            res.redirect('/filters');
        } else {
            // Zijn alle searchorders afgerond?
            var all_completed = true;
            searchorders.forEach(function (el) {
                if (el.MatchCriteria.Complete !== 1) { all_completed = false;}
            });

            if (!all_completed) {
                // Er is een openstaande searchorder, door naar het filterscherm.
                req.session.last_error = "";
                res.redirect('/filters');
            } else {
                // Alle searchorders afgerond, we kunnen het statusscherm tonen. We geven een lijst mee van
                //  searchorders.
                var orders = [];
                var genders = {'m': 'man', 'v': 'vrouw', 'b': 'bi'};
                searchorders.forEach(function (el) {
                    var desc = genders[el.MatchCriteria.Gender] + ' - ' + el.MatchCriteria.Age.min + ' tot ' +
                        el.MatchCriteria.Age.max + ' - ' + el.MatchCriteria.Range + ' km van ' + el.MatchCriteria.City;
                    orders.push({order_id: el._id, val: desc});
                });

                req.session.last_error = "";
                res.render('status', { searchorders: orders, session: req.session});
            }
        }
    }).fail(function (error) {
        req.session.last_error = 'Fout bij ophalen searchorders: ' + error.message;
        res.render('status', { session: req.session });
    }).done();

});

router.get('/getMatchesList', function(req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.status(403).end();
    }

    var order_id = req.param('id', '');
    var searchorder = searchService.getSearchOrderById(order_id).then(function (searchorder) {
        if (!searchorder) {
            // Ongeldige search order meegegeven.
            req.session.last_error = "";
            res.status(404).end();
        } else {
            // TODO - checken of dit wel een searchorder is van de ingelogde gebruiker.

            // Ophalen alle TinderMatches en response vullen.
            var match_list = [];

            searchorder.Matches.forEach(function(el) {
                var status = 'unknown';
                if (el.Success === true) {
                    status = 'success';
                } else if (el.Success === false) {
                    status = 'fail';
                } else if (el.Success === null) {
                    if (el.Response.length > 0) {
                        status = 'response';
                    } else if (el.Response.LikedBack === true) {
                        status = 'waiting';
                    }
                }

                var birth_date = new Date(el.UserInfo.birth_date);
                var age = ~~((Date.now() - birth_date) / (31557600000));

                match_list.push({match_id: el.UserInfo._id,
                    name: el.UserInfo.name,
                    bio: el.UserInfo.bio,
                    photo: el.UserInfo.photos[0].url,
                    gender: (el.UserInfo.gender == 1) ? 'v' : 'm',
                    age: age,
                    distance: el.UserInfo.distance_mi * 1.6,
                    status: status});
            });

            req.session.last_error = '';
            res.json(match_list);
        }
    }).done();
});

router.get('/getMatch', function(req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.status(403).end();
    }

    var order_id = req.param('order_id', '');
    var match_id = req.param('match_id', '');
    var searchorder = searchService.getSearchOrderById(order_id).then(function (searchorder) {
        if (!searchorder) {
            // Ongeldige searchorderid meegegeven.
            req.session.last_error = "";
            res.status(404).end();
        } else {
            // TODO - checken of dit wel een searchorder is van de ingelogde gebruiker.

            // Ophalen juiste match binnen de searchorder.
            var match = null;
            searchorder.Matches.every ( function (el) {
                if (el.UserInfo._id == match_id) {
                    match = el;
                    return false;
                }
                return true;
            });
            if (!match) {
                // Ongeldige matchid meegegeven.
                req.session.last_error = "";
                res.status(404).end();
            }

            // Checken of deze match wel een status 'response' heeft.
            // TODO - enablen.
            if (false /*match.Success !== null || match.Response.length == 0*/) {
                req.session.last_error = "";
                res.status(404).end();
            } else {
                // Teruggeven gegevens van deze match.
                var birth_date = new Date(match.UserInfo.birth_date);
                var age = ~~((Date.now() - birth_date) / (31557600000));

                req.session.last_error = '';
                res.json({order_id: searchorder._id,
                    match_id: match.UserInfo._id,
                    name: match.UserInfo.name,
                    bio: match.UserInfo.bio,
                    photo: match.UserInfo.photos[0].url,
                    gender: (match.UserInfo.gender == 1) ? 'v' : 'm',
                    age: age,
                    distance: match.UserInfo.distance_mi * 1.6,
                    // TODO
                    responses: [
                            'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
                            'Nog een zin!!!1 fdjfdh%&^%*%^%^%^',
                            'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, etc.'
                    ]     });
                    //responses: match.Response});
            }
        }
    }).done();

});

router.get('/setMatchResponse', function (req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        req.session.last_error = "";
        res.status(403).end();
        return;
    }

    var order_id = req.param('order_id', '');
    var match_id = req.param('match_id', '');
    var success = req.param('success','');

    if (success === '') {
        // Ontbrekende response.
        req.session.last_error = "";
        res.status(404).end();
        return;
    }
    success = parseInt(success, 10);
    if (success != 0 && success != 1) {
        // Ongeldige response.
        req.session.last_error = "";
        res.status(404).end();
        return;
    }
    success = (success == 1);

    var searchorder = searchService.getSearchOrderById(order_id).then(function (searchorder) {
        if (!searchorder) {
            // Ongeldige searchorderid meegegeven.
            req.session.last_error = "";
            res.status(404).end();
        } else {
            // TODO - checken of dit wel een searchorder is van de ingelogde gebruiker.

            // Ophalen juiste match binnen de searchorder.
            var match = null;
            searchorder.Matches.every ( function (el) {
                if (el.UserInfo._id == match_id) {
                    match = el;
                    return false;
                }
                return true;
            });
            if (!match) {
                // Ongeldige matchid meegegeven.
                req.session.last_error = "";
                res.status(404).end();
                return;
            }

            // Checken of deze match wel een status 'response' heeft.
            // TODO - enablen.
            if (false /*match.Success !== null || match.Response.length == 0*/) {
                req.session.last_error = "";
                res.status(404).end();
            } else {
                // Updaten van deze match binnen de searchorder.
                searchorder.Matches.every ( function (el) {
                    if (el.UserInfo._id == match_id) {
                        el.Success = success;
                        return false;
                    }
                    return true;
                });

                // Nu de gewijzigde searchorder terugschieten.
                searchService.updateRunningSearchOrder(searchorder).then(function(result){
                    req.session.last_error = "";
                    res.status(200).end();
                }).fail( function (error) {
                    console.log('error updating searchorder: ' + error.message);
                    req.session.last_error = "";
                    res.status(500).end();
                }).done();
            }
        }
    }).done();
})

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

/**
 * world.js is loaded by the cucumber framework before loading the step definitions and feature files
 * it is responsible for setting up and exposing the driver/browser/expect/assert etc required within each step definition
 */

var fs = require('fs-plus');
var path = require('path');
var requireDir = require('require-dir');
var merge = require('merge');
var chalk = require('chalk');
var selenium = require('selenium-webdriver');
var expect = require('chai').expect;
var assert = require('chai').assert;
var reporter = require('cucumber-html-reporter');
var cucumberJunit = require('cucumber-junit');

/**
 * create the selenium browser based on global var set in index.js
 */
function getDriverInstance() {

    var driver;
    switch (browserName || '') {

        case 'firefox': {
            driver = require("./firefoxDriver")();
        } break;

        case 'phantomjs': {
            driver = require("./phantomDriver")();
        } break;

        case 'chrome': {
            driver = require("./chromeDriver")();
        } break;

        // try to load from file
        default: {
            var driverFileName = path.resolve(process.cwd(), browserName);
            if (!fs.isFileSync(driverFileName)) {
                throw "Could not find driver file: " + driverFileName;
            }
            driver = require(driverFileName)();
        }
    }

    return driver;
}

function consoleInfo() {
    var args = [].slice.call(arguments),
        output = chalk.bgBlue.white('\n>>>>> \n' + args + '\n<<<<<\n');

    console.log(output);
}

function World() {

    // create a list of variables to expose globally and therefore accessible within each step definition
    var runtime = {
        driver: null,           // the browser object
        selenium: selenium,     // the raw nodejs selenium driver
        By: selenium.By,        // in keeping with Java expose selenium By
        by: selenium.By,        // provide a javascript lowercase version
        until: selenium.until,  // provide easy access to selenium until methods
        expect: expect,         // expose chai expect to allow variable testing
        assert: assert,         // expose chai assert to allow variable testing
        trace: consoleInfo,     // expose an info method to log output to the console in a readable/visible format
        page: {},               // empty page objects placeholder
        shared: {}              // empty shared objects placeholder
    };

    // expose properties to step definition methods via global variables
    Object.keys(runtime).forEach(function (key) {

        // make property/method available as a global (no this. prefix required)
        global[key] = runtime[key];
    });

    // import shared objects from multiple paths (after global vars have been created)
    if (global.sharedObjectPaths && Array.isArray(global.sharedObjectPaths) && global.sharedObjectPaths.length > 0) {

        var allDirs = {};

        // first require directories into objects by directory
        global.sharedObjectPaths.forEach(function (itemPath) {

            if (fs.existsSync(itemPath)) {

                var dir = requireDir(itemPath, { camelcase: true });

                merge(allDirs, dir);
            }
        });

        // if we managed to import some directories, expose them
        if (Object.keys(allDirs).length > 0) {

            // expose globally
            global.shared = allDirs;
        }
    }

    // import page objects (after global vars have been created)
    if (global.pageObjectPath && fs.existsSync(global.pageObjectPath)) {

        // require all page objects using camel case as object names
        runtime.page = requireDir(global.pageObjectPath, { camelcase: true });

        // expose globally
        global.page = runtime.page;
    }

    // add helpers
    global.helpers = require('../runtime/helpers.js');
}

// export the "World" required by cucumber to allow it to expose methods within step def's
module.exports = function () {

    this.World = World;

    // set the default timeout for all tests
    this.setDefaultTimeout(global.DEFAULT_TIMEOUT);

    // create the driver before scenario if it's not instantiated
    this.registerHandler('BeforeScenario', function(scenario) {

        if (!global.driver) {
            global.driver = getDriverInstance();
        }
    });

    this.registerHandler('AfterFeatures', function (features, done) {

        var cucumberReportPath = path.resolve(global.reportsPath, 'cucumber-report.json');

        if (global.reportsPath && fs.existsSync(global.reportsPath)) {

            // generate the HTML report
            var reportOptions = {
                theme: 'bootstrap',
                jsonFile: cucumberReportPath,
                output: path.resolve(global.reportsPath, 'cucumber-report.html'),
                reportSuiteAsScenarios: true,
                launchReport: (!global.disableLaunchReport),
                ignoreBadJsonFile: true
            };

            reporter.generate(reportOptions);

            // grab the file data
            var reportRaw = fs.readFileSync(cucumberReportPath).toString().trim();
            var xmlReport = cucumberJunit(reportRaw);
            var junitOutputPath = path.resolve(global.junitPath, 'junit-report.xml');

            fs.writeFileSync(junitOutputPath, xmlReport);
        }

        done();
    });

    // executed after each scenario (always closes the browser to ensure fresh tests)
    this.After(function (scenario) {

        if (scenario.isFailed() && !global.noScreenshot) {

            // add a screenshot to the error report
            return driver.takeScreenshot().then(function (screenShot) {

                scenario.attach(new Buffer(screenShot, 'base64'), 'image/png');

                return driver.close().then(function() {
                    return driver.quit();
                });
            });
        }

        return driver.close().then(function() {
            return driver.quit();
        });
    });
};
<commit_msg>Split the creation of common element to fix #23<commit_after>'use strict';

/**
 * world.js is loaded by the cucumber framework before loading the step definitions and feature files
 * it is responsible for setting up and exposing the driver/browser/expect/assert etc required within each step definition
 */

var fs = require('fs-plus');
var path = require('path');
var requireDir = require('require-dir');
var merge = require('merge');
var chalk = require('chalk');
var selenium = require('selenium-webdriver');
var expect = require('chai').expect;
var assert = require('chai').assert;
var reporter = require('cucumber-html-reporter');
var cucumberJunit = require('cucumber-junit');

/**
 * create the selenium browser based on global var set in index.js
 */
function getDriverInstance() {

    var driver;
    switch (browserName || '') {

        case 'firefox': {
            driver = require("./firefoxDriver")();
        } break;

        case 'phantomjs': {
            driver = require("./phantomDriver")();
        } break;

        case 'chrome': {
            driver = require("./chromeDriver")();
        } break;

        // try to load from file
        default: {
            var driverFileName = path.resolve(process.cwd(), browserName);
            if (!fs.isFileSync(driverFileName)) {
                throw "Could not find driver file: " + driverFileName;
            }
            driver = require(driverFileName)();
        }
    }

    return driver;
}

function consoleInfo() {
    var args = [].slice.call(arguments),
        output = chalk.bgBlue.white('\n>>>>> \n' + args + '\n<<<<<\n');

    console.log(output);
}

function World() {

    // create a list of variables to expose globally and therefore accessible within each step definition
    var runtime = {
        driver: null,           // the browser object
        selenium: selenium,     // the raw nodejs selenium driver
        By: selenium.By,        // in keeping with Java expose selenium By
        by: selenium.By,        // provide a javascript lowercase version
        until: selenium.until,  // provide easy access to selenium until methods
        expect: expect,         // expose chai expect to allow variable testing
        assert: assert,         // expose chai assert to allow variable testing
        trace: consoleInfo,     // expose an info method to log output to the console in a readable/visible format
        page: global.page||{},               // empty page objects placeholder
        shared: global.shared||{}              // empty shared objects placeholder
    };

    // expose properties to step definition methods via global variables
    Object.keys(runtime).forEach(function (key) {

        // make property/method available as a global (no this. prefix required)
        global[key] = runtime[key];
    });
}

function createGlobalObjects() {
    // import shared objects from multiple paths (after global vars have been created)
    if (global.sharedObjectPaths && Array.isArray(global.sharedObjectPaths) && global.sharedObjectPaths.length > 0) {

        var allDirs = {};

        // first require directories into objects by directory
        global.sharedObjectPaths.forEach(function (itemPath) {

            if (fs.existsSync(itemPath)) {

                var dir = requireDir(itemPath, { camelcase: true });

                merge(allDirs, dir);
            }
        });

        // if we managed to import some directories, expose them
        if (Object.keys(allDirs).length > 0) {

            // expose globally
            global.shared = allDirs;
        }
    }

    // import page objects (after global vars have been created)
    if (global.pageObjectPath && fs.existsSync(global.pageObjectPath)) {

        // require all page objects using camel case as object names
        global.page = requireDir(global.pageObjectPath, { camelcase: true });
    }

    // add helpers
    global.helpers = require('../runtime/helpers.js');
}

// export the "World" required by cucumber to allow it to expose methods within step def's
module.exports = function () {
    World();
    createGlobalObjects();

    this.World = World;

    // set the default timeout for all tests
    this.setDefaultTimeout(global.DEFAULT_TIMEOUT);

    // create the driver before scenario if it's not instantiated
    this.registerHandler('BeforeScenario', function(scenario) {

        if (!global.driver) {
            global.driver = getDriverInstance();
        }
    });

    this.registerHandler('AfterFeatures', function (features, done) {

        var cucumberReportPath = path.resolve(global.reportsPath, 'cucumber-report.json');

        if (global.reportsPath && fs.existsSync(global.reportsPath)) {

            // generate the HTML report
            var reportOptions = {
                theme: 'bootstrap',
                jsonFile: cucumberReportPath,
                output: path.resolve(global.reportsPath, 'cucumber-report.html'),
                reportSuiteAsScenarios: true,
                launchReport: (!global.disableLaunchReport),
                ignoreBadJsonFile: true
            };

            reporter.generate(reportOptions);

            // grab the file data
            var reportRaw = fs.readFileSync(cucumberReportPath).toString().trim();
            var xmlReport = cucumberJunit(reportRaw);
            var junitOutputPath = path.resolve(global.junitPath, 'junit-report.xml');

            fs.writeFileSync(junitOutputPath, xmlReport);
        }

        done();
    });

    // executed after each scenario (always closes the browser to ensure fresh tests)
    this.After(function (scenario) {

        if (scenario.isFailed() && !global.noScreenshot) {

            // add a screenshot to the error report
            return driver.takeScreenshot().then(function (screenShot) {

                scenario.attach(new Buffer(screenShot, 'base64'), 'image/png');

                return driver.close().then(function() {
                    return driver.quit();
                });
            });
        }

        return driver.close().then(function() {
            return driver.quit();
        });
    });
};
<|endoftext|>


<commit_before>'use strict';

import * as _ from 'lodash'

import hasDepartment from '../app/helpers/hasDepartment'
import {partialTitle} from '../app/helpers/partialTitle'
import {checkCoursesFor} from '../app/helpers/getCourses'

import {isRequiredCourse} from './commonMajorUtilities'

const csDeptRequiredCourses = [
	{deptnum: 'CSCI 121'}, {deptnum: 'CSCI 125'}, {deptnum: 'CSCI 241'}, {deptnum: 'CSCI 251'},
	{deptnum: 'CSCI 252'}, {deptnum: 'CSCI 231'}, {deptnum: 'CSCI 253'}, {deptnum: 'CSCI 263'},
	{deptnum: 'CSCI 276'}, {deptnum: 'CSCI 333'}, {deptnum: 'CSCI 273'}, {deptnum: 'CSCI 284'},
	{deptnum: 'CSCI 390'},

	{deptnum: 'CSCI 300', name: 'Parallel'},

	{deptnum: 'MATH 232'}, {deptnum: 'MATH 252'},
]

let isRequiredCompSciCourse = _.curry(isRequiredCourse(csDeptRequiredCourses))

function foundationCourses(courses) {
	/* Foundation courses:
		- one of Computer Science 121 or 125;
		- Computer Science 241, 251, and 252;
		- one of Computer Science 231 or Math 232 or Math 252.
	*/

	var cs1 = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:121}),
		checkCoursesFor(courses, {dept:'CSCI', num:125}),
	])

	var design = _.all([
		checkCoursesFor(courses, {dept:'CSCI', num:241}),
		checkCoursesFor(courses, {dept:'CSCI', num:251}),
		checkCoursesFor(courses, {dept:'CSCI', num:252}),
	])

	var mfc = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:231}),
		checkCoursesFor(courses, {dept:'MATH', num:232}),
		checkCoursesFor(courses, {dept:'MATH', num:252}),
	])

	let requirements = [
		{
			title: 'CS1',
			result: cs1,
		},
		{
			title: 'Design',
			result: design,
		},
		{
			title: 'MFC',
			result: mfc,
		},
	]

	return {
		title: 'Foundation',
		description: 'one of Computer Science 121 or 125; Computer Science 241, 251, and 252; one of Computer Science 231 or Math 232 or Math 252.',
		result: _.all(requirements, 'result'),
		type: 'array/boolean',
		details: requirements,
	}
}

function coreCourses(courses) {
	/* Core courses:
		- Computer Science 253;
		- Computer Science 263;
		- either of Computer Science 276 or 333;
		- and either Computer Science 273, 284, or 300 with parallel and distributed computing.
	*/

	var algorithms = checkCoursesFor(courses, {dept:'CSCI', num:253})

	var ethics = checkCoursesFor(courses, {dept:'CSCI', num:263})

	var theory = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:276}),
		checkCoursesFor(courses, {dept:'CSCI', num:333})
	])

	var parallelDistributedComputing = _.chain(courses)
		.filter({dept: 'CSCI', num: 300})
		.filter(partialTitle('Parallel'))
		.size().value() >= 1

	var options = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:273}),
		checkCoursesFor(courses, {dept:'CSCI', num:284}),
		parallelDistributedComputing
	])

	let requirements = [
		{
			title: 'Algorithms',
			result: algorithms,
		},
		{
			title: 'Ethics',
			result: ethics,
		},
		{
			title: 'Theory',
			result: theory,
		},
		{
			title: 'Options',
			result: options
		},
	]

	return {
		title: 'Core',
		type: 'array/boolean',
		description: 'Computer Science 253; Computer Science 263; either Computer Science 276 or 333; and either Computer Science 273, 284, or 300 with parallel and distributed computing.',
		result: _.all(requirements, 'result'),
		details: requirements,
	}
}

function electiveCourses(courses) {
	// Electives: Two approved electives.

	var validCourses = _.chain(courses)
		.filter(hasDepartment('CSCI'))
		.reject(isRequiredCompSciCourse)
		.value()

	var numberTaken = _.size(validCourses)
	var numberNeeded = 2

	return {
		title: 'Electives',
		type: 'object/number',
		description: 'Two approved electives.',
		result: numberTaken >= numberNeeded,
		details: {
			has: numberTaken,
			needs: numberNeeded,
			matches: validCourses,
		}
	}
}

function capstoneCourse(courses) {
	// Capstone: Computer Science 390
	var hasTakenCapstone = checkCoursesFor(courses, {dept:'CSCI', num:390})

	return {
		title: 'Capstone',
		type: 'boolean',
		description: 'Capstone',
		result: hasTakenCapstone
	}
}

function checkComputerScienceMajor(student) {
	var computerScienceMajorRequirements = [
		foundationCourses(student.courses),
		coreCourses(student.courses),
		electiveCourses(student.courses),
		capstoneCourse(student.courses),
	]

	return {
		result: _.all(computerScienceMajorRequirements, 'result'),
		details: computerScienceMajorRequirements,
	}
}

export default checkComputerScienceMajor
<commit_msg>Update the CS major for 2014-15<commit_after>'use strict';

import * as _ from 'lodash'

import hasDepartment from '../app/helpers/hasDepartment'
import {partialNameOrTitle} from '../app/helpers/partialTitle'
import {checkCoursesFor} from '../app/helpers/getCourses'

import {isRequiredCourse} from './commonMajorUtilities'

const csDeptRequiredCourses = [
	{deptnum: 'CSCI 121'}, {deptnum: 'CSCI 125'}, {deptnum: 'CSCI 241'}, {deptnum: 'CSCI 251'},
	{deptnum: 'CSCI 252'}, {deptnum: 'CSCI 231'}, {deptnum: 'CSCI 253'}, {deptnum: 'CSCI 263'},
	{deptnum: 'CSCI 276'}, {deptnum: 'CSCI 333'}, {deptnum: 'CSCI 273'}, {deptnum: 'CSCI 284'},
	{deptnum: 'CSCI 390'},

	{deptnum: 'CSCI 300', name: 'Parallel'},

	{deptnum: 'MATH 232'}, {deptnum: 'MATH 252'},
]

let isRequiredCompSciCourse = _.curry(isRequiredCourse(csDeptRequiredCourses))

function foundationCourses(courses) {
	/* Foundation courses:
		- one of Computer Science 121 or 125;
		- Computer Science 241, 251, and 252;
		- one of Computer Science 231 or Math 232 or Math 252.
	*/

	var cs1 = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:121}),
		checkCoursesFor(courses, {dept:'CSCI', num:125}),
	])

	var design = _.all([
		checkCoursesFor(courses, {dept:'CSCI', num:241}),
		checkCoursesFor(courses, {dept:'CSCI', num:251}),
		checkCoursesFor(courses, {dept:'CSCI', num:252}),
	])

	var proofWriting = _.any([
		checkCoursesFor(courses, {dept:'MATH', num:282, term:20141}),
		checkCoursesFor(courses, {dept:'MATH', num:244}),
		checkCoursesFor(courses, {dept:'MATH', num:252}),
	])

	let requirements = [
		{
			title: 'CS1',
			result: cs1,
		},
		{
			title: 'Design',
			result: design,
		},
		{
			title: 'Proof Writing',
			result: proofWriting,
		},
	]

	return {
		title: 'Foundation',
		description: 'one of Computer Science 121 or 125; Computer Science 241, 251, and 252; one of Computer Science 231 or Math 232 or Math 252.',
		result: _.all(requirements, 'result'),
		type: 'array/boolean',
		details: requirements,
	}
}

function coreCourses(courses) {
	/* Core courses:
		- Computer Science 253;
		- Computer Science 263;
		- either of Computer Science 276 or 333;
		- and either Computer Science 273, 284, or 300 with parallel and distributed computing.
	*/

	var algorithms = checkCoursesFor(courses, {dept:'CSCI', num:253})

	var ethics = checkCoursesFor(courses, {dept:'CSCI', num:263})

	var theory = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:276}),
		checkCoursesFor(courses, {dept:'CSCI', num:333})
	])

	var parallelDistributedComputing = _.chain(courses)
		.filter({dept: 'CSCI', num: 300})
		.filter(partialNameOrTitle('Parallel'))
		.size().value() >= 1

	var options = _.any([
		checkCoursesFor(courses, {dept:'CSCI', num:273}),
		checkCoursesFor(courses, {dept:'CSCI', num:284}),
		parallelDistributedComputing
	])

	let requirements = [
		{
			title: 'Algorithms',
			result: algorithms,
		},
		{
			title: 'Ethics',
			result: ethics,
		},
		{
			title: 'Theory',
			result: theory,
		},
		{
			title: 'Options',
			result: options
		},
	]

	return {
		title: 'Core',
		type: 'array/boolean',
		description: 'Computer Science 253; Computer Science 263; either Computer Science 276 or 333; and either Computer Science 273, 284, or 300 with parallel and distributed computing.',
		result: _.all(requirements, 'result'),
		details: requirements,
	}
}

function electiveCourses(courses) {
	// Electives: Two approved electives.

	var validCourses = _.chain(courses)
		.filter(hasDepartment('CSCI'))
		.reject(isRequiredCompSciCourse)
		.value()

	var numberTaken = _.size(validCourses)
	var numberNeeded = 2

	return {
		title: 'Electives',
		type: 'object/number',
		description: 'Two approved electives.',
		result: numberTaken >= numberNeeded,
		details: {
			has: numberTaken,
			needs: numberNeeded,
			matches: validCourses,
		}
	}
}

function capstoneCourse(courses) {
	// Capstone: Computer Science 390
	var hasTakenCapstone = checkCoursesFor(courses, {dept:'CSCI', num:390})

	return {
		title: 'Capstone',
		type: 'boolean',
		description: 'Capstone',
		result: hasTakenCapstone
	}
}

function checkComputerScienceMajor(student) {
	var computerScienceMajorRequirements = [
		foundationCourses(student.courses),
		coreCourses(student.courses),
		electiveCourses(student.courses),
		capstoneCourse(student.courses),
	]

	return {
		result: _.all(computerScienceMajorRequirements, 'result'),
		details: computerScienceMajorRequirements,
	}
}

export default checkComputerScienceMajor
<|endoftext|>


<commit_before>var _ = require('lodash')
var Promise = require('bluebird')

var hasDepartment = require('../client/helpers/hasDepartment')
var partialTitle = require('../client/helpers/partialTitle').partialTitle
var coursesAtLevel = require('../client/helpers/courseLevels').coursesAtLevel
var coursesAtOrAboveLevel = require('../client/helpers/courseLevels').coursesAtOrAboveLevel
var checkCoursesForDeptNum = require('../client/helpers/getCourses').checkCoursesForDeptNum

var utilities = require('./demo_common_major_utilities')

var csDeptRequiredCourses = [
	{deptnum: 'CSCI 121'}, {deptnum: 'CSCI 125'}, {deptnum: 'CSCI 241'}, {deptnum: 'CSCI 251'},
	{deptnum: 'CSCI 251'}, {deptnum: 'CSCI 231'}, {deptnum: 'CSCI 253'}, {deptnum: 'CSCI 263'},
	{deptnum: 'CSCI 276'}, {deptnum: 'CSCI 333'}, {deptnum: 'CSCI 273'}, {deptnum: 'CSCI 284'},
	{deptnum: 'CSCI 390'},

	{deptnum: 'CSCI 300', name: 'Parallel'},

	{deptnum: 'MATH 232'}, {deptnum: 'MATH 252'},
]

var isRequiredCompSciCourse = _.curry(utilities.isRequiredCourse)(csDeptRequiredCourses)

function foundationCourses(courses) {
	/* Foundation courses:
		- one of Computer Science 121 or 125;
		- Computer Science 241, 251, and 252;
		- one of Computer Science 231 or Math 232 or Math 252.
	*/

	var cs1 = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 121'),
		checkCoursesForDeptNum(courses, 'CSCI 125'),
	])

	var design = Promise.all([
		checkCoursesForDeptNum(courses, 'CSCI 241'),
		checkCoursesForDeptNum(courses, 'CSCI 251'),
		checkCoursesForDeptNum(courses, 'CSCI 252'),
	])

	var mfc = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 231'),
		checkCoursesForDeptNum(courses, 'MATH 232'),
		checkCoursesForDeptNum(courses, 'MATH 252'),
	])

	return Promise.props({
		'CS1': cs1,
		'Design': design.then(_.all),
		'MFC': mfc
	}).then(function(requirements) {
		return {
			title: 'Foundation',
			description: 'one of Computer Science 121 or 125; Computer Science 241, 251, and 252; one of Computer Science 231 or Math 232 or Math 252.',
			result: _.all(requirements),
			details: requirements,
		}
	})
}

function coreCourses(courses) {
	/* Core courses:
		- Computer Science 253;
		- Computer Science 263;
		- either of Computer Science 276 or 333;
		- and either Computer Science 273, 284, or 300 with parallel and distributed computing.
	*/

	var algorithms = checkCoursesForDeptNum(courses, 'CSCI 253')

	var ethics = checkCoursesForDeptNum(courses, 'CSCI 263')

	var theory = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 276'),
		checkCoursesForDeptNum(courses, 'CSCI 333')
	])

	var parallelDistributedComputing = _.chain(courses)
		.filter(hasDepartment('CSCI'))
		.filter({num: 300})
		.filter(partialTitle('Parallel'))
		.size().value() >= 1

	var options = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 273'),
		checkCoursesForDeptNum(courses, 'CSCI 284'),
		Promise.resolve(parallelDistributedComputing)
	])

	return Promise.props({
		'Algorithms': algorithms,
		'Ethics': ethics,
		'Theory': theory,
		'Options': options
	}).then(function(requirements) {
		return {
			title: 'Core',
			description: 'Computer Science 253; Computer Science 263; either Computer Science 276 or 333; and either Computer Science 273, 284, or 300 with parallel and distributed computing.',
			result: _.all(requirements),
			details: requirements,
		}
	})
}

function electiveCourses(courses) {
	// Electives: Two approved electives.

	var validCourses = _.chain(courses)
		.filter(hasDepartment('CSCI'))
		.reject(isRequiredCompSciCourse)
		.value()

	var numberNeeded = 2

	return Promise.resolve({
		title: 'Electives',
		description: 'Two approved electives.',
		result: _.size(validCourses) >= numberNeeded,
		details: {
			has: _.size(validCourses),
			needs: numberNeeded,
			matches: validCourses,
		}
	})
}

function capstoneCourse(courses) {
	// Capstone: Computer Science 390
	return Promise.resolve({
		title: 'Capstone',
		description: 'Capstone',
		result: checkCoursesForDeptNum(courses, 'CSCI 390'),
	})
}

function checkComputerScienceMajor(student) {
	// TODO: Turn off cortex.
	var computerScienceMajorRequirements = Promise.all([
		foundationCourses(student.courses),
		coreCourses(student.courses),
		electiveCourses(student.courses),
		capstoneCourse(student.courses),
	]).then(function(results) {
		// console.log('checkComputerScienceMajor', 'results', results)
		return results
	})

	return Promise.props({
		result: computerScienceMajorRequirements.then(function(results) {
			return _.all(results, 'result')
		}),
		details: computerScienceMajorRequirements
	})
}

module.exports = checkComputerScienceMajor
<commit_msg>Do the same for CS.capstone<commit_after>var _ = require('lodash')
var Promise = require('bluebird')

var hasDepartment = require('../client/helpers/hasDepartment')
var partialTitle = require('../client/helpers/partialTitle').partialTitle
var coursesAtLevel = require('../client/helpers/courseLevels').coursesAtLevel
var coursesAtOrAboveLevel = require('../client/helpers/courseLevels').coursesAtOrAboveLevel
var checkCoursesForDeptNum = require('../client/helpers/getCourses').checkCoursesForDeptNum

var utilities = require('./demo_common_major_utilities')

var csDeptRequiredCourses = [
	{deptnum: 'CSCI 121'}, {deptnum: 'CSCI 125'}, {deptnum: 'CSCI 241'}, {deptnum: 'CSCI 251'},
	{deptnum: 'CSCI 251'}, {deptnum: 'CSCI 231'}, {deptnum: 'CSCI 253'}, {deptnum: 'CSCI 263'},
	{deptnum: 'CSCI 276'}, {deptnum: 'CSCI 333'}, {deptnum: 'CSCI 273'}, {deptnum: 'CSCI 284'},
	{deptnum: 'CSCI 390'},

	{deptnum: 'CSCI 300', name: 'Parallel'},

	{deptnum: 'MATH 232'}, {deptnum: 'MATH 252'},
]

var isRequiredCompSciCourse = _.curry(utilities.isRequiredCourse)(csDeptRequiredCourses)

function foundationCourses(courses) {
	/* Foundation courses:
		- one of Computer Science 121 or 125;
		- Computer Science 241, 251, and 252;
		- one of Computer Science 231 or Math 232 or Math 252.
	*/

	var cs1 = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 121'),
		checkCoursesForDeptNum(courses, 'CSCI 125'),
	])

	var design = Promise.all([
		checkCoursesForDeptNum(courses, 'CSCI 241'),
		checkCoursesForDeptNum(courses, 'CSCI 251'),
		checkCoursesForDeptNum(courses, 'CSCI 252'),
	])

	var mfc = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 231'),
		checkCoursesForDeptNum(courses, 'MATH 232'),
		checkCoursesForDeptNum(courses, 'MATH 252'),
	])

	return Promise.props({
		'CS1': cs1,
		'Design': design.then(_.all),
		'MFC': mfc
	}).then(function(requirements) {
		return {
			title: 'Foundation',
			description: 'one of Computer Science 121 or 125; Computer Science 241, 251, and 252; one of Computer Science 231 or Math 232 or Math 252.',
			result: _.all(requirements),
			details: requirements,
		}
	})
}

function coreCourses(courses) {
	/* Core courses:
		- Computer Science 253;
		- Computer Science 263;
		- either of Computer Science 276 or 333;
		- and either Computer Science 273, 284, or 300 with parallel and distributed computing.
	*/

	var algorithms = checkCoursesForDeptNum(courses, 'CSCI 253')

	var ethics = checkCoursesForDeptNum(courses, 'CSCI 263')

	var theory = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 276'),
		checkCoursesForDeptNum(courses, 'CSCI 333')
	])

	var parallelDistributedComputing = _.chain(courses)
		.filter(hasDepartment('CSCI'))
		.filter({num: 300})
		.filter(partialTitle('Parallel'))
		.size().value() >= 1

	var options = Promise.any([
		checkCoursesForDeptNum(courses, 'CSCI 273'),
		checkCoursesForDeptNum(courses, 'CSCI 284'),
		Promise.resolve(parallelDistributedComputing)
	])

	return Promise.props({
		'Algorithms': algorithms,
		'Ethics': ethics,
		'Theory': theory,
		'Options': options
	}).then(function(requirements) {
		return {
			title: 'Core',
			description: 'Computer Science 253; Computer Science 263; either Computer Science 276 or 333; and either Computer Science 273, 284, or 300 with parallel and distributed computing.',
			result: _.all(requirements),
			details: requirements,
		}
	})
}

function electiveCourses(courses) {
	// Electives: Two approved electives.

	var validCourses = _.chain(courses)
		.filter(hasDepartment('CSCI'))
		.reject(isRequiredCompSciCourse)
		.value()

	var numberNeeded = 2

	return Promise.resolve({
		title: 'Electives',
		description: 'Two approved electives.',
		result: _.size(validCourses) >= numberNeeded,
		details: {
			has: _.size(validCourses),
			needs: numberNeeded,
			matches: validCourses,
		}
	})
}

function capstoneCourse(courses) {
	// Capstone: Computer Science 390
	var hasTakenCapstone = checkCoursesForDeptNum(courses, 'CSCI 390')
	return hasTakenCapstone.then(function(result) {
		return {
			title: 'Capstone',
			description: 'Capstone',
			result: result
		}
	})
}

function checkComputerScienceMajor(student) {
	// TODO: Turn off cortex.
	var computerScienceMajorRequirements = Promise.all([
		foundationCourses(student.courses),
		coreCourses(student.courses),
		electiveCourses(student.courses),
		capstoneCourse(student.courses),
	]).then(function(results) {
		// console.log('checkComputerScienceMajor', 'results', results)
		return results
	})

	return Promise.props({
		result: computerScienceMajorRequirements.then(function(results) {
			return _.all(results, 'result')
		}),
		details: computerScienceMajorRequirements
	})
}

module.exports = checkComputerScienceMajor
<|endoftext|>


<commit_before>'use strict';

import React from 'react-native'
import {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} from 'react-native';
import { colors } from './globalStyle';

class HomeView extends Component {

  constructor(props: any) {
    super(props);
    this.state = {
      selectedButton: null,
      selectedButtonSize: 80,
      navigateToBoopViewInProgress: false,
    };
  }

  increaseButtonSize() {
    this.setState({
      selectedButtonSize: 100,
    });
  }

  navigateToBoopView() {
    this.props.navigator.push({
      name: 'boop-view',
    });
  }

  navigateToBoopViewDelay() {
    if (this.state.navigateToBoopViewInProgress) {
      return;
    }
    this.setState({
      navigateToBoopViewInProgress: true,
    });
    const self = this;
    const t = setTimeout(function() {
      self.navigateToBoopView();
      self.setState({
        navigateToBoopViewInProgress: false,
      });
    }, 1000);
  }

  render() {
    const { data } = this.props;
    const self = this;
    const colors = [
      '#1f77b4',
      '#ff7f0e',
      '#2ca02c',
      '#d62728',
      '#9467bd',
      '#8c564b',
      '#e377c2',
      '#7f7f7f',
      '#bcbd22',
      '#17becf',
    ];
    const friendElems = data.friends.map(function(friend, index) {
      const color = colors[index % colors.length];
      const buttonSize = (
        self.state.selectedButton == friend.id ?
        self.state.selectedButtonSize :
        80
      );
      const circleButtonStyle = {
        width: buttonSize,
        height: buttonSize,
      };
      return (
        <View key={index} style={styles.friendElem}>
          <View style={styles.friendButton}>
          <TouchableHighlight
            style={styles.circleTouchable}
            onPress={() => {
              self.setState({
                selectedButton: friend.id,
              });
              self.increaseButtonSize();
              self.navigateToBoopViewDelay();
            }}
            underlayColor='#CDCDCD'>
              <View style={[styles.circle, circleButtonStyle, {backgroundColor: color}]} />
            </TouchableHighlight>
            <Text
              style={styles.friendName}>
                {friend.firstName}
            </Text>
          </View>
        </View>
      );
    });
    return (
      <View style={styles.container}>
        {friendElems}
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    padding: 20,
    backgroundColor: colors.darkTheme.primary,
  },
  friendElem: {
    height: 120,
    width: 100,
    margin: 4,
  },
  friendButton: {
    flex: 1,
    padding: 10,
    alignItems: 'center',
  },
  circle: {
    borderRadius: 100/2,
    backgroundColor: 'red'
  },
  circleTouchable: {
    borderRadius: 100/2,
  },
  friendName: {
    textAlign: 'center',
    fontSize: 16,
    color: colors.darkTheme.text1,
  },
});

AppRegistry.registerComponent('HomeView', () => HomeView);
export default HomeView;
<commit_msg>Animate friend button on click.<commit_after>'use strict';

import React from 'react-native'
import {
  Animated,
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} from 'react-native';
import { colors } from './globalStyle';

class HomeView extends Component {

  constructor(props: any) {
    super(props);
    this.state = {
      selectedButton: null,
      selectedButtonScale: new Animated.Value(1),
      navigateToBoopViewInProgress: false,
    };
  }

  increaseButtonSize() {
    // this.state.selectedButtonScale.setValue(1.1);
    Animated.timing(
      this.state.selectedButtonScale,
      {
        toValue: 1.4,
        duration: 200,
      }
    ).start();
  }

  navigateToBoopView() {
    this.props.navigator.push({
      name: 'boop-view',
    });
  }

  navigateToBoopViewDelay() {
    // Make sure we're not already in the process of navigating.
    if (this.state.navigateToBoopViewInProgress) {
      return;
    }
    this.setState({
      navigateToBoopViewInProgress: true,
    });
    const self = this;
    const t = setTimeout(function() {
      self.navigateToBoopView();
      self.setState({
        navigateToBoopViewInProgress: false,
      });
    }, 1000);
  }

  render() {
    const { data } = this.props;
    const self = this;
    const colors = [
      '#1f77b4',
      '#ff7f0e',
      '#2ca02c',
      '#d62728',
      '#9467bd',
      '#8c564b',
      '#e377c2',
      '#7f7f7f',
      '#bcbd22',
      '#17becf',
    ];
    // Build all the friend buttons.
    const friendElems = data.friends.map(function(friend, index) {
      // Cycle through the colors for each friend button.
      const color = colors[index % colors.length];
      // If this button is selected, give it the selected
      // tranform value.
      var circleButtonTranformVal = 1;
      if (self.state.selectedButton == friend.id) {
        circleButtonTranformVal = self.state.selectedButtonScale;
      }
      const circleButtonStyle = {
        width: 80,
        height: 80,
        transform: [
          {scale: circleButtonTranformVal},
        ]
      };
      return (
        <View key={index} style={styles.friendElem}>
          <View style={styles.friendButton}>
          <TouchableHighlight
            style={styles.circleTouchable}
            onPress={() => {
              self.setState({
                selectedButton: friend.id,
              });
              self.increaseButtonSize();
              self.navigateToBoopViewDelay();
            }}
            underlayColor='#CDCDCD'>
              <Animated.View style={[styles.circle, circleButtonStyle, {backgroundColor: color}]} />
            </TouchableHighlight>
            <Text
              style={styles.friendName}>
                {friend.firstName}
            </Text>
          </View>
        </View>
      );
    });
    return (
      <View style={styles.container}>
        {friendElems}
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    padding: 20,
    backgroundColor: colors.darkTheme.primary,
  },
  friendElem: {
    height: 120,
    width: 100,
    margin: 4,
  },
  friendButton: {
    flex: 1,
    padding: 10,
    alignItems: 'center',
  },
  circle: {
    borderRadius: 100/2,
    backgroundColor: 'red'
  },
  circleTouchable: {
    borderRadius: 100/2,
  },
  friendName: {
    textAlign: 'center',
    fontSize: 16,
    color: colors.darkTheme.text1,
  },
});

AppRegistry.registerComponent('HomeView', () => HomeView);
export default HomeView;
<|endoftext|>