<commit_before>Array.prototype.select = function (key) {
    var newList = [];
    for (var i = 0; i < this.length; i++) {
        var obj = {};
        obj[key] = this[i][key];
        newList.insert(i,obj);
    }
    return newList;
};
Array.prototype.insert = function (index, item) {
    this.splice(index, 1, item);
};

Array.prototype.clear = function () {
    this.length = 0;
};

Array.prototype.removeAt = function (index) {
    this.splice(index, 1);
};

Array.prototype.empty = function (query) {
    if (typeof (query) === "function") {
        return this.where(query).length === 0;
    }
    return this.length === 0;
};

Array.prototype.any = function (query) {
    if (typeof(query) === "function") {
        return this.where(query).length > 0;
    }
    return this.length > 0;
};

Array.prototype.removeFirst = function (item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) {
            this.splice(i, 1);
            return item;
        }
    }
};

Array.prototype.removeAll = function (item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) {
            this.splice(i, 1);
        }
    }
};

Array.prototype.equals = function (array) {
    var a1 = JSON.stringify(this);
    var a2 = JSON.stringify(array);

    return a1 === a2;
}

Array.prototype.seekAndDestroy = function (w) {
    var founds = [];
    for (var i = 0; i < this.length; i++) {
        if (typeof(w) === "function" && w(this[i])) {
            this.removeAt(i);
            i--;
        }else if(this[i]===w){
            this.removeAt(i);
            i--;
        }
    }
};

Array.prototype.where = function (w) {
    var founds = [];
    for (var i = 0; i < this.length; i++) {
        if (w(this[i])) {
            founds.push(this[i]);
        }
    }
    return founds;
};

Array.prototype.each = function (callback) {
    for (var i = 0; i < this.length; i++) {
        var r = callback(this[i], i);
        if (r == false) break;
    }
};

Array.prototype.map = function (callback) {
    var map = [];
    for (var i = 0; i < this.length; i++) {
        var r = callback(this[i], i);
        map.push(r);
    }
    return map;
};

Array.prototype.contains = function (array) {
    if (!array) return false;
    if (this.length == 0) return false;
    var temp = [];
    var a = array;
    var b = this;
    if (array.length > this.length) {
        a = this;
        b = array;
    }

    for (var i = 0; i < a.length; i++) {
        for (var j = 0; j < b.length; j++) {
            if (b[j] == a[i]) {
                temp.push(b[j]);
                break;
            }
        }
    }
    return a.equals(temp);

};

Array.prototype.last = function () {
    if (this.length > 0) {
        return this[this.length - 1];
    }
    return null;
};

Array.prototype.update = function (array, callback) {
    var i = 0;
    var j = 0;
    for (i = 0; i < array.length; i++) {
        for (j = 0; j < this.length; j++) {
            if (callback(this[j], array[i])) {
                break;
            }
        }
        this[j] = array[i];
    }
}
Array.prototype.innerFor = function (innerArray, callback) {
    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j < innerArray.length; j++) {
            if (callback(this[i], innerArray[j])) {
                return;
            }
        }
    }
}

Array.prototype.sum = function (callback) {
    var acc = 0;
    for (var i = 0; i < this.length; i++) {
        acc += callback(this[i]);
    }
    return acc;
};

Array.prototype.first = function (callback) {
    if (typeof(callback) === "function") {
        for (var i = 0; i < this.length; i++) {
            if (callback(this[i])) {
                return this[i];
            }
        }
    } else {
        if (this.length > 0) {
            return this[0];
        }
        return null;
    }
};

Array.prototype.findIndex = function (callback) {
    if (typeof (callback) === "function") {
        for (var i = 0; i < this.length; i++) {
            if (callback(this[i])) {
                return i;
            }
        }
    }
};

Array.prototype.groupBy = function (key) {
    if(typeof(key) === "function" || typeof(key) === "string"){
        var array = [];
        for (var i = 0; i < this.length; i++) {
            var position, keyValue;
            if(typeof(key) === "string"){
                if(this[i][key] === undefined) throw "Invalid key arg";
                keyValue = this[i][key];
            }else{
                keyValue = key(this[i]);
            }
            position = array.findIndex(function (x) { return x.Key === keyValue });
            if (position !== undefined) {
                array[position].Values.push(this[i]);
            } else {
                array.push({ Key: keyValue, Values: [this[i]] });
            }
        }
        return array;
    }
};
<commit_msg>added method flatMap<commit_after>Array.prototype.select = function (key) {
    var newList = [];
    for (var i = 0; i < this.length; i++) {
        var obj = {};
        obj[key] = this[i][key];
        newList.insert(i,obj);
    }
    return newList;
};
Array.prototype.insert = function (index, item) {
    this.splice(index, 1, item);
};

Array.prototype.clear = function () {
    this.length = 0;
};

Array.prototype.removeAt = function (index) {
    this.splice(index, 1);
};

Array.prototype.empty = function (query) {
    if (typeof (query) === "function") {
        return this.where(query).length === 0;
    }
    return this.length === 0;
};

Array.prototype.any = function (query) {
    if (typeof(query) === "function") {
        return this.where(query).length > 0;
    }
    return this.length > 0;
};

Array.prototype.removeFirst = function (item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) {
            this.splice(i, 1);
            return item;
        }
    }
};

Array.prototype.removeAll = function (item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) {
            this.splice(i, 1);
        }
    }
};

Array.prototype.equals = function (array) {
    var a1 = JSON.stringify(this);
    var a2 = JSON.stringify(array);

    return a1 === a2;
}

Array.prototype.seekAndDestroy = function (w) {
    var founds = [];
    for (var i = 0; i < this.length; i++) {
        if (typeof(w) === "function" && w(this[i])) {
            this.removeAt(i);
            i--;
        }else if(this[i]===w){
            this.removeAt(i);
            i--;
        }
    }
};

Array.prototype.where = function (w) {
    var founds = [];
    for (var i = 0; i < this.length; i++) {
        if (w(this[i])) {
            founds.push(this[i]);
        }
    }
    return founds;
};

Array.prototype.each = function (callback) {
    for (var i = 0; i < this.length; i++) {
        var r = callback(this[i], i);
        if (r == false) break;
    }
};

Array.prototype.map = function (callback) {
    var map = [];
    for (var i = 0; i < this.length; i++) {
        var r = callback(this[i], i);
        map.push(r);
    }
    return map;
};

Array.prototype.contains = function (array) {
    if (!array) return false;
    if (this.length == 0) return false;
    var temp = [];
    var a = array;
    var b = this;
    if (array.length > this.length) {
        a = this;
        b = array;
    }

    for (var i = 0; i < a.length; i++) {
        for (var j = 0; j < b.length; j++) {
            if (b[j] == a[i]) {
                temp.push(b[j]);
                break;
            }
        }
    }
    return a.equals(temp);

};

Array.prototype.last = function () {
    if (this.length > 0) {
        return this[this.length - 1];
    }
    return null;
};

Array.prototype.update = function (array, callback) {
    var i = 0;
    var j = 0;
    for (i = 0; i < array.length; i++) {
        for (j = 0; j < this.length; j++) {
            if (callback(this[j], array[i])) {
                break;
            }
        }
        this[j] = array[i];
    }
}
Array.prototype.innerFor = function (innerArray, callback) {
    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j < innerArray.length; j++) {
            if (callback(this[i], innerArray[j])) {
                return;
            }
        }
    }
}

Array.prototype.sum = function (callback) {
    var acc = 0;
    for (var i = 0; i < this.length; i++) {
        acc += callback(this[i]);
    }
    return acc;
};

Array.prototype.first = function (callback) {
    if (typeof(callback) === "function") {
        for (var i = 0; i < this.length; i++) {
            if (callback(this[i])) {
                return this[i];
            }
        }
    } else {
        if (this.length > 0) {
            return this[0];
        }
        return null;
    }
};

Array.prototype.findIndex = function (callback) {
    if (typeof (callback) === "function") {
        for (var i = 0; i < this.length; i++) {
            if (callback(this[i])) {
                return i;
            }
        }
    }
};

Array.prototype.flatMap = function () {
    var result = [];
    for (var i = 0; i < this.length; i++) {
        if (Array.isArray(this[i])) {
            for(var j=0;j<this[i].length;j++){
              result.push(this[i][j]);
            }
        }else{
            result.push(this[i]);
        }
    }
    return result;
};

Array.prototype.groupBy = function (key) {
    if(typeof(key) === "function" || typeof(key) === "string"){
        var array = [];
        for (var i = 0; i < this.length; i++) {
            var position, keyValue;
            if(typeof(key) === "string"){
                if(this[i][key] === undefined) throw "Invalid key arg";
                keyValue = this[i][key];
            }else{
                keyValue = key(this[i]);
            }
            position = array.findIndex(function (x) { return x.Key === keyValue });
            if (position !== undefined) {
                array[position].Values.push(this[i]);
            } else {
                array.push({ Key: keyValue, Values: [this[i]] });
            }
        }
        return array;
    }
};
<|endoftext|>


<commit_before>/*
Author: David Wibowo
Created: [01/07/2016]
Title:  homepage
Associated Files: homepage.html, homepage.js and homepage.css
*/
if(Meteor.isClient)
{
  Template.homepage.onRendered(function()
    {
      $('.Search-dot').css("display", "block");
      Session.set('categories', []);
      Session.set('criteria', []);
      if(Session.get('criteria').length == 0)
      {
        $('#Search').css('display', 'none');
      }
    })

  Template.homepage.helpers({
    loggedIn: function(){
      if(!Meteor.userId()){
        return false;
      }
      return true;
    },
    userNumber: function(){
      if(!Meteor.userId()){
        return 0;
      }
      else{
        return Jobs.find({owner: Meteor.userId()}).count();
      }
    },
    categories:[{
      name: "Programming",
      short: "Programming",
      number: function() {
        return Jobs.find({category: "Programming"}).count();
      },
      color: "#FF0000"
    },{
      name: "Design",
      short: "Design",
      number: function() {
        return Jobs.find({category: "Design"}).count();
      },
      color: "#FF6600"
    },{
      name:"Business Development",
      short: "Business",
      number: function() {
        return Jobs.find({category: "Business Development"}).count();
      },
      color: "#009900"
    },{
      name: "IT Admin / Support",
      short: "IT",
      number: function() {
        return Jobs.find({category: "IT Admin / Support"}).count();
      },
      color: "#0000FF"
    },{
      name:"Marketing",
      short: "Marketing",
      number: function() {
        return Jobs.find({category: "Marketing"}).count();
      },
      color: "#6600CC"
    },
    {
      name:function() {
        var name = "Search: ";
        var data = Session.get('criteria');
        if(data != undefined)
        {
          name += data;
        }
          return name;
      },
      short: 'Search',
      number: '',
      color: 'grey'
    }],

    listing: function() {
      categories = Session.get('categories');
      criteria = Session.get('criteria');
      userRequired = false;

      if(categories != undefined)
      {
        for(var i = 0; i < categories.length; i++)
        {
          if(categories[i] == "User")
          {
            userRequired = true;
          }
        }

        // Only show users listings
        if(userRequired)
        {
          // Categories selected
          if(categories.length > 1)
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // Category, Search, User
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{'owner': Meteor.userId()},{$or: [{'title': {$regex: keyword}},{'company': {$regex: keyword}}, {'description': {$regex: keyword}}]}, {'category': {$in: categories}}]},{sort: {createdAt: -1}}).fetch();
            }
            else
            {
              // Category, No Search, User
              return Jobs.find({$and: [{'owner': Meteor.userId()},
              {'category': {$in: categories}}]},
              {sort: {createdAt: -1}}).fetch();
            }
          }
          // No Categories selected
          else
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // No Category, Search, User
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{'owner': Meteor.userId()},
              {$or: [{'title': {$regex: keyword}},{'company': {$regex: keyword}},
              {'description': {$regex: keyword}}]}]},
              {sort: {createdAt: -1}}).fetch();
            }
            // No Search Criteria selected
            else
            {
              // No Category, No Search, User
              return Jobs.find({'owner': Meteor.userId()},
              {sort: {createdAt: -1}}).fetch();
            }
          }
        }
        // Show all unexpired listings
        else
        {
          // Categories selected
          if(categories.length > 0)
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // Category, Search, No User
              console.log('Category, Search, No User');
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()}, {'isExpired': false}]},{$or: [{'title': {$regex: keyword}},{'company': {$regex: keyword}}, {'description': {$regex: keyword}}]}, {'category': {$in: categories}}]},{sort: {createdAt: -1}}).fetch();
            }
            else
            {
              // Category, No Search, No User
              return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()},
              {'isExpired': false}]}, {'category': {$in: categories}}]},
              {sort: {createdAt: -1}}).fetch();
            }
          }
          // No Categories selected
          else
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // No Category, Search, No User
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()},
              {'isExpired': false}]},{$or: [{'title': {$regex: keyword}},
              {'company': {$regex: keyword}}, {'description': {$regex: keyword}}]}]},
              {sort: {createdAt: -1}}).fetch();
            }
            // No Search Criteria selected
            else
            {
              // No Category, No Search, No User
              return Jobs.find(
                {
                  $or: [{'owner': Meteor.userId()}, {'isExpired': false}]
                },
                {
                  sort: {createdAt: -1}
                }
              ).fetch();
            }
          }
        }
      }

    //   if(categories != undefined)
    //   {
    //     for(var i = 0; i < categories.length; i++){
    //       if(categories[i] == "User"){
    //         userRequired = true;
    //       }
    //     }
    //     if(userRequired){
    //       if(categories.length == 1 && criteria.length == 0)
    //       {
    //         return Jobs.find({'owner': Meteor.userId()}, {sort: {createdAt: -1}}).fetch();
    //       }
    //       else if(criteria.length == 0)
    //       {
    //         return Jobs.find({$and: [{'owner': Meteor.userId()}, {'category': {$in: categories}}]}, {sort: {createdAt: -1}}).fetch();
    //       }
    //     }
    //     else{
    //       if(categories.length == 0 && criteria.length == 0)
    //       {
    //         return Jobs.find({$or: [{'owner': Meteor.userId()}, {'isExpired': false}]}, {sort: {createdAt: -1}}).fetch();
    //       }
    //       else if(criteria.length == 0)
    //       {
    //         return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()}, {'isExpired': false}]}, {'category': {$in: categories}}]}, {sort: {createdAt: -1}}).fetch();
    //       }
    //     }
    //   }
    //   if(criteria != undefined)
    //   {
    //     if(criteria.length != 0)
    //     {
    //       var search = new RegExp(criteria, "i");
    //       return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()}, {'isExpired': false}]}, {$or: [{'title': {$regex: search}}, {'company': {$regex: search}}, {'description': {$regex: search}}]} ]}, {sort: {createdAt: -1}}).fetch();
    //     }
    //   }
   }
  });

  Template.homepage.events({
    'click #Programming': function(e, t) {
      $('#Programming').toggleClass('red_fade');
      data = Session.get('categories');
      if(data.indexOf("Programming") == -1)
      {
        data.push('Programming');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Programming');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Design': function(e, t) {
      $('#Design').toggleClass('orange_fade');
      data = Session.get('categories');
      if(data.indexOf("Design") == -1)
      {
        data.push('Design');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Design');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Business': function(e, t) {
      $('#Business').toggleClass('green_fade');
      data = Session.get('categories');
      if(data.indexOf("Business Development") == -1)
      {
        data.push('Business Development');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Business Development');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #IT': function(e, t) {
      $('#IT').toggleClass('blue_fade');
      data = Session.get('categories');
      if(data.indexOf("IT Admin / Support") == -1)
      {
        data.push('IT Admin / Support');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('IT Admin / Support');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Marketing': function(e, t) {
      $('#Marketing').toggleClass('purple_fade');
      data = Session.get('categories');
      if(data.indexOf("Marketing") == -1)
      {
        data.push('Marketing');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Marketing');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Search': function(e, t) {
      Session.set('criteria', []);
      $('#Search').css('display', 'none');
    },
    'click #User': function(e, t) {
      $('#User').toggleClass('user_fade');
      data = Session.get('categories');
      if(data.indexOf("User") == -1)
      {
        data.push('User');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('User');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },

    'click .home-tag': function(e,t){
      var dot = "."+$(e.target).attr('id')+"-dot";
      if($(dot).css("display") == "none"){
        $(dot).css("display", "block");
      }else{
        $(dot).css("display", "none");
      }

    },

    'click .fa-times': function(e,t){

      var dot = "."+$(e.target).attr('id');

      if($(dot).css("display") == "none"){
        $(dot).css("display", "block");
      }else{
        $(dot).css("display", "none");
      }

    },

    'click button': function(e,t){
      event.preventDefault();
    }
  });

  Handlebars.registerHelper("isOwner", function(owner){
    return Meteor.userId() == owner;
  })
}
<commit_msg>Tag Count Fix<commit_after>/*
Author: David Wibowo
Created: [01/07/2016]
Title:  homepage
Associated Files: homepage.html, homepage.js and homepage.css
*/
if(Meteor.isClient)
{
  Template.homepage.onRendered(function()
    {
      $('.Search-dot').css("display", "block");
      Session.set('categories', []);
      Session.set('criteria', []);
      if(Session.get('criteria').length == 0)
      {
        $('#Search').css('display', 'none');
      }
    })

  Template.homepage.helpers({
    loggedIn: function(){
      if(!Meteor.userId()){
        return false;
      }
      return true;
    },
    userNumber: function(){
      if(!Meteor.userId()){
        return 0;
      }
      else{
        var categoryArray = Session.get('categories');
        if (categoryArray.length > 0){
          var userCount = 0;
          Jobs.find({owner: Meteor.userId()}).forEach(function(userListing){
            if(categoryArray.indexOf(userListing.category) != -1 || (categoryArray.indexOf("User") != -1 && categoryArray.length == 1)){
              userCount += 1;
            }
          });
          return userCount;
        }
        else{
          return Jobs.find({owner: Meteor.userId()}).count();
        }
      }
    },
    categories:[{
      name: "Programming",
      short: "Programming",
      number: function() {
        var array = Session.get('categories');
        if(array.length == 0 || array.indexOf(this.name)!= -1){
          return Jobs.find({category: this.name}).count();
        }else {
          return 0;
        }
      },
      color: "#FF0000"
    },{
      name: "Design",
      short: "Design",
      number: function() {
        var array = Session.get('categories');
        if(array.length == 0 || array.indexOf(this.name)!= -1){
          return Jobs.find({category: this.name}).count();
        }else {
          return 0;
        }
      },
      color: "#FF6600"
    },{
      name:"Business Development",
      short: "Business",
      number: function() {
        var array = Session.get('categories');
        if(array.length == 0 || array.indexOf(this.name)!= -1){
          return Jobs.find({category: this.name}).count();
        }else {
          return 0;
        }
      },
      color: "#009900"
    },{
      name: "IT Admin / Support",
      short: "IT",
      number: function() {
        var array = Session.get('categories');
        if(array.length == 0 || array.indexOf(this.name)!= -1){
          return Jobs.find({category: this.name}).count();
        }else {
          return 0;
        }
      },
      color: "#0000FF"
    },{
      name:"Marketing",
      short: "Marketing",
      number: function() {
        var array = Session.get('categories');
        if(array.length == 0 || array.indexOf(this.name)!= -1){
          return Jobs.find({category: this.name}).count();
        }else {
          return 0;
        }
      },
      color: "#6600CC"
    },
    {
      name:function() {
        var name = "Search: ";
        var data = Session.get('criteria');
        if(data != undefined)
        {
          name += data;
        }
          return name;
      },
      short: 'Search',
      number: '',
      color: 'grey'
    }],

    listing: function() {
      categories = Session.get('categories');
      criteria = Session.get('criteria');
      userRequired = false;

      if(categories != undefined)
      {
        for(var i = 0; i < categories.length; i++)
        {
          if(categories[i] == "User")
          {
            userRequired = true;
          }
        }

        // Only show users listings
        if(userRequired)
        {
          // Categories selected
          if(categories.length > 1)
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // Category, Search, User
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{'owner': Meteor.userId()},{$or: [{'title': {$regex: keyword}},{'company': {$regex: keyword}}, {'description': {$regex: keyword}}]}, {'category': {$in: categories}}]},{sort: {createdAt: -1}}).fetch();
            }
            else
            {
              // Category, No Search, User
              return Jobs.find({$and: [{'owner': Meteor.userId()},
              {'category': {$in: categories}}]},
              {sort: {createdAt: -1}}).fetch();
            }
          }
          // No Categories selected
          else
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // No Category, Search, User
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{'owner': Meteor.userId()},
              {$or: [{'title': {$regex: keyword}},{'company': {$regex: keyword}},
              {'description': {$regex: keyword}}]}]},
              {sort: {createdAt: -1}}).fetch();
            }
            // No Search Criteria selected
            else
            {
              // No Category, No Search, User
              return Jobs.find({'owner': Meteor.userId()},
              {sort: {createdAt: -1}}).fetch();
            }
          }
        }
        // Show all unexpired listings
        else
        {
          // Categories selected
          if(categories.length > 0)
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // Category, Search, No User
              console.log('Category, Search, No User');
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()}, {'isExpired': false}]},{$or: [{'title': {$regex: keyword}},{'company': {$regex: keyword}}, {'description': {$regex: keyword}}]}, {'category': {$in: categories}}]},{sort: {createdAt: -1}}).fetch();
            }
            else
            {
              // Category, No Search, No User
              return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()},
              {'isExpired': false}]}, {'category': {$in: categories}}]},
              {sort: {createdAt: -1}}).fetch();
            }
          }
          // No Categories selected
          else
          {
            // Search Criteria selected
            if(criteria.length != 0)
            {
              // No Category, Search, No User
              keyword = new RegExp(criteria, 'i');
              return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()},
              {'isExpired': false}]},{$or: [{'title': {$regex: keyword}},
              {'company': {$regex: keyword}}, {'description': {$regex: keyword}}]}]},
              {sort: {createdAt: -1}}).fetch();
            }
            // No Search Criteria selected
            else
            {
              // No Category, No Search, No User
              return Jobs.find(
                {
                  $or: [{'owner': Meteor.userId()}, {'isExpired': false}]
                },
                {
                  sort: {createdAt: -1}
                }
              ).fetch();
            }
          }
        }
      }

    //   if(categories != undefined)
    //   {
    //     for(var i = 0; i < categories.length; i++){
    //       if(categories[i] == "User"){
    //         userRequired = true;
    //       }
    //     }
    //     if(userRequired){
    //       if(categories.length == 1 && criteria.length == 0)
    //       {
    //         return Jobs.find({'owner': Meteor.userId()}, {sort: {createdAt: -1}}).fetch();
    //       }
    //       else if(criteria.length == 0)
    //       {
    //         return Jobs.find({$and: [{'owner': Meteor.userId()}, {'category': {$in: categories}}]}, {sort: {createdAt: -1}}).fetch();
    //       }
    //     }
    //     else{
    //       if(categories.length == 0 && criteria.length == 0)
    //       {
    //         return Jobs.find({$or: [{'owner': Meteor.userId()}, {'isExpired': false}]}, {sort: {createdAt: -1}}).fetch();
    //       }
    //       else if(criteria.length == 0)
    //       {
    //         return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()}, {'isExpired': false}]}, {'category': {$in: categories}}]}, {sort: {createdAt: -1}}).fetch();
    //       }
    //     }
    //   }
    //   if(criteria != undefined)
    //   {
    //     if(criteria.length != 0)
    //     {
    //       var search = new RegExp(criteria, "i");
    //       return Jobs.find({$and: [{$or: [{'owner': Meteor.userId()}, {'isExpired': false}]}, {$or: [{'title': {$regex: search}}, {'company': {$regex: search}}, {'description': {$regex: search}}]} ]}, {sort: {createdAt: -1}}).fetch();
    //     }
    //   }
   }
  });

  Template.homepage.events({
    'click #Programming': function(e, t) {
      $('#Programming').toggleClass('red_fade');
      data = Session.get('categories');
      if(data.indexOf("Programming") == -1)
      {
        data.push('Programming');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Programming');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Design': function(e, t) {
      $('#Design').toggleClass('orange_fade');
      data = Session.get('categories');
      if(data.indexOf("Design") == -1)
      {
        data.push('Design');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Design');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Business': function(e, t) {
      $('#Business').toggleClass('green_fade');
      data = Session.get('categories');
      if(data.indexOf("Business Development") == -1)
      {
        data.push('Business Development');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Business Development');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #IT': function(e, t) {
      $('#IT').toggleClass('blue_fade');
      data = Session.get('categories');
      if(data.indexOf("IT Admin / Support") == -1)
      {
        data.push('IT Admin / Support');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('IT Admin / Support');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Marketing': function(e, t) {
      $('#Marketing').toggleClass('purple_fade');
      data = Session.get('categories');
      if(data.indexOf("Marketing") == -1)
      {
        data.push('Marketing');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('Marketing');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },
    'click #Search': function(e, t) {
      Session.set('criteria', []);
      $('#Search').css('display', 'none');
    },
    'click #User': function(e, t) {
      $('#User').toggleClass('user_fade');
      data = Session.get('categories');
      if(data.indexOf("User") == -1)
      {
        data.push('User');
        Session.set('categories', data);
      }
      else {
        index = data.indexOf('User');
        data.splice(index, 1);
        Session.set('categories', data);
      }
    },

    'click .home-tag': function(e,t){
      var dot = "."+$(e.target).attr('id')+"-dot";
      if($(dot).css("display") == "none"){
        $(dot).css("display", "block");
      }else{
        $(dot).css("display", "none");
      }

    },

    'click .fa-times': function(e,t){

      var dot = "."+$(e.target).attr('id');

      if($(dot).css("display") == "none"){
        $(dot).css("display", "block");
      }else{
        $(dot).css("display", "none");
      }

    },

    'click button': function(e,t){
      event.preventDefault();
    }
  });

  Handlebars.registerHelper("isOwner", function(owner){
    return Meteor.userId() == owner;
  })
}
<|endoftext|>


<commit_before>//@flow
import fs from 'fs';
import path from 'path';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import { prepare } from '@webkom/react-prepare';
import Helmet from 'react-helmet';
import Raven from 'raven';
import serialize from 'serialize-javascript';
import routes from '../app/routes';
import configureStore from '../app/utils/configureStore';
import config, { baseConfig } from '../config/env';
import type { $Request, $Response, Middleware } from 'express';
import { createNewRavenInstance } from '../app/utils/universalRaven';
import webpackClient from '../config/webpack.client.js';
import type { State } from '../app/types';

import 'source-map-support/register';

import manifest from '../app/assets/manifest.json';

const serverSideTimeoutInMs = 4000;

// AntiPattern because of babel
// https://github.com/babel/babel/issues/3083
class TimeoutError {
  error: Error;
  constructor(msg) {
    this.error = new Error(msg);
  }
}

const prepareWithTimeout = app =>
  Promise.race([
    prepare(app),
    new Promise(resolve => {
      setTimeout(resolve, serverSideTimeoutInMs);
    }).then(() => {
      throw new TimeoutError(
        'React prepare timeout when server side rendering.'
      );
    })
  ]);

function render(req: $Request, res: $Response, next: Middleware) {
  const render = (
    body: string = '',
    state: State | {||} = Object.freeze({})
  ) => {
    const helmet = Helmet.rewind();
    return res.send(
      renderPage({
        body,
        state,
        helmet
      })
    );
  };

  const log = req.app.get('log');

  if (process.env.NODE_ENV !== 'production') {
    return render();
  }

  match({ routes, location: req.url }, (err, redirect, renderProps) => {
    if (err) {
      return next(err);
    }

    if (redirect) {
      return res.redirect(`${redirect.pathname}${redirect.search}`);
    }

    if (!renderProps) {
      return next();
    }

    const createElement = (Component, props) => <Component {...props} />;

    const raven = createNewRavenInstance(Raven);

    const store = configureStore(
      {},
      { raven, getCookie: key => req.cookies[key] }
    );
    const app = (
      <Provider store={store}>
        <RouterContext {...renderProps} createElement={createElement} />
      </Provider>
    );

    const reportError = (error: Error) => {
      try {
        // $FlowFixMe
        const err = error.error ? error.payload : error;
        log.error(err, 'render_error');
        raven.captureException(err);
      } catch (e) {
        //
      }
    };

    const respond = () => {
      const state: State = store.getState();
      const body = renderToString(app);
      // $FlowFixMe
      const statusCode = state.routing.statusCode || 200;
      res.status(statusCode);
      return render(body, state);
    };

    prepareWithTimeout(app)
      .then(
        () => respond(),
        error => {
          if (error instanceof TimeoutError) {
            reportError(error.error);
            return render();
          }
          reportError(error);
          respond();
        }
      )
      .catch(error => {
        reportError(error);
        render();
      });
  });
}

let cachedAssets;
function retrieveAssets() {
  if (__DEV__ || !cachedAssets) {
    const { app, vendor } = JSON.parse(
      fs
        .readFileSync(
          path.join(webpackClient.output.path, 'webpack-assets.json')
        )
        .toString()
    );

    const styles = [app && app.css]
      .filter(Boolean)
      .map(css => `<link rel="stylesheet" href="${css}">`)
      .join('\n');
    const scripts = [vendor && vendor.js, app && app.js]
      .filter(Boolean)
      .map(js => `<script src="${js}"></script>`)
      .join('\n');

    cachedAssets = { scripts, styles };
  }

  return cachedAssets;
}

const dllPlugin =
  process.env.NODE_ENV !== 'production'
    ? ''
    : '';

function renderPage({
  body,
  state,
  helmet
}: {
  body: string,
  state: State | {||},
  helmet: *
}) {
  const { scripts, styles } = retrieveAssets();
  return `
    <!DOCTYPE html>

        <meta charset="utf-8">
        ${helmet.title.toString()}
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

        <link rel="manifest" href="${manifest}">
        <meta name="theme-color" content="#f2f2f1">
        <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="Abakus Søk">
        <link rel="icon" href="/icon-512x512.png" sizes="512x512"/>
        <link rel="apple-touch-icon" href="/icon-512x512.png" sizes="512x512"/>
        <link rel="icon" href="/icon-384x384.png" sizes="384x384"/>
        <link rel="apple-touch-icon" href="/icon-384x384.png" sizes="384x384"/>
        <link rel="icon" href="/icon-256x256.png" sizes="256x256"/>
        <link rel="apple-touch-icon" href="/icon-256x256.png" sizes="256x256"/>
        <link rel="icon" href="/icon-192x192.png" sizes="192x192"/>
        <link rel="apple-touch-icon" href="/icon-192x192.png" sizes="192x192"/>
        <link rel="icon" href="/icon-96x96.png" sizes="96x96"/>
        <link rel="apple-touch-icon" href="/icon-96x96.png" sizes="96x96"/>
        <link rel="icon" href="/icon-48x48.png" sizes="48x48"/>
        <link rel="apple-touch-icon" href="/icon-48x48.png" sizes="48x48"/>

        <meta name="apple-mobile-web-app-capable" content="yes"/>
        <meta name="mobile-web-app-capable" content="yes"/>
        <meta name="apple-mobile-web-app-title" content="Abakus"/>

        <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

        ${helmet.meta.toString()}

        ${styles}

${body}

        ${
          config.environment === 'production'
            ? ``
            : ''
        }

        ${dllPlugin}
        ${scripts}

   `;
}

export default render;
<commit_msg>Revert to plain segemnt for snoot<commit_after>//@flow
import fs from 'fs';
import path from 'path';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import { prepare } from '@webkom/react-prepare';
import Helmet from 'react-helmet';
import Raven from 'raven';
import serialize from 'serialize-javascript';
import routes from '../app/routes';
import configureStore from '../app/utils/configureStore';
import config, { baseConfig } from '../config/env';
import type { $Request, $Response, Middleware } from 'express';
import { createNewRavenInstance } from '../app/utils/universalRaven';
import webpackClient from '../config/webpack.client.js';
import type { State } from '../app/types';

import 'source-map-support/register';

import manifest from '../app/assets/manifest.json';

const serverSideTimeoutInMs = 4000;

// AntiPattern because of babel
// https://github.com/babel/babel/issues/3083
class TimeoutError {
  error: Error;
  constructor(msg) {
    this.error = new Error(msg);
  }
}

const prepareWithTimeout = app =>
  Promise.race([
    prepare(app),
    new Promise(resolve => {
      setTimeout(resolve, serverSideTimeoutInMs);
    }).then(() => {
      throw new TimeoutError(
        'React prepare timeout when server side rendering.'
      );
    })
  ]);

function render(req: $Request, res: $Response, next: Middleware) {
  const render = (
    body: string = '',
    state: State | {||} = Object.freeze({})
  ) => {
    const helmet = Helmet.rewind();
    return res.send(
      renderPage({
        body,
        state,
        helmet
      })
    );
  };

  const log = req.app.get('log');

  if (process.env.NODE_ENV !== 'production') {
    return render();
  }

  match({ routes, location: req.url }, (err, redirect, renderProps) => {
    if (err) {
      return next(err);
    }

    if (redirect) {
      return res.redirect(`${redirect.pathname}${redirect.search}`);
    }

    if (!renderProps) {
      return next();
    }

    const createElement = (Component, props) => <Component {...props} />;

    const raven = createNewRavenInstance(Raven);

    const store = configureStore(
      {},
      { raven, getCookie: key => req.cookies[key] }
    );
    const app = (
      <Provider store={store}>
        <RouterContext {...renderProps} createElement={createElement} />
      </Provider>
    );

    const reportError = (error: Error) => {
      try {
        // $FlowFixMe
        const err = error.error ? error.payload : error;
        log.error(err, 'render_error');
        raven.captureException(err);
      } catch (e) {
        //
      }
    };

    const respond = () => {
      const state: State = store.getState();
      const body = renderToString(app);
      // $FlowFixMe
      const statusCode = state.routing.statusCode || 200;
      res.status(statusCode);
      return render(body, state);
    };

    prepareWithTimeout(app)
      .then(
        () => respond(),
        error => {
          if (error instanceof TimeoutError) {
            reportError(error.error);
            return render();
          }
          reportError(error);
          respond();
        }
      )
      .catch(error => {
        reportError(error);
        render();
      });
  });
}

let cachedAssets;
function retrieveAssets() {
  if (__DEV__ || !cachedAssets) {
    const { app, vendor } = JSON.parse(
      fs
        .readFileSync(
          path.join(webpackClient.output.path, 'webpack-assets.json')
        )
        .toString()
    );

    const styles = [app && app.css]
      .filter(Boolean)
      .map(css => `<link rel="stylesheet" href="${css}">`)
      .join('\n');
    const scripts = [vendor && vendor.js, app && app.js]
      .filter(Boolean)
      .map(js => `<script src="${js}"></script>`)
      .join('\n');

    cachedAssets = { scripts, styles };
  }

  return cachedAssets;
}

const dllPlugin =
  process.env.NODE_ENV !== 'production'
    ? ''
    : '';

function renderPage({
  body,
  state,
  helmet
}: {
  body: string,
  state: State | {||},
  helmet: *
}) {
  const { scripts, styles } = retrieveAssets();
  return `
    <!DOCTYPE html>

        <meta charset="utf-8">
        ${helmet.title.toString()}
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

        <link rel="manifest" href="${manifest}">
        <meta name="theme-color" content="#f2f2f1">
        <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="Abakus Søk">
        <link rel="icon" href="/icon-512x512.png" sizes="512x512"/>
        <link rel="apple-touch-icon" href="/icon-512x512.png" sizes="512x512"/>
        <link rel="icon" href="/icon-384x384.png" sizes="384x384"/>
        <link rel="apple-touch-icon" href="/icon-384x384.png" sizes="384x384"/>
        <link rel="icon" href="/icon-256x256.png" sizes="256x256"/>
        <link rel="apple-touch-icon" href="/icon-256x256.png" sizes="256x256"/>
        <link rel="icon" href="/icon-192x192.png" sizes="192x192"/>
        <link rel="apple-touch-icon" href="/icon-192x192.png" sizes="192x192"/>
        <link rel="icon" href="/icon-96x96.png" sizes="96x96"/>
        <link rel="apple-touch-icon" href="/icon-96x96.png" sizes="96x96"/>
        <link rel="icon" href="/icon-48x48.png" sizes="48x48"/>
        <link rel="apple-touch-icon" href="/icon-48x48.png" sizes="48x48"/>

        <meta name="apple-mobile-web-app-capable" content="yes"/>
        <meta name="mobile-web-app-capable" content="yes"/>
        <meta name="apple-mobile-web-app-title" content="Abakus"/>

        <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

        ${helmet.meta.toString()}

        ${styles}

${body}

        ${
          config.environment === 'production'
            ? ``
            : ''
        }

        ${dllPlugin}
        ${scripts}

   `;
}

export default render;
<|endoftext|>


<commit_before>var router = require('express').Router();

//Import models
var User = require('./models/User');
var Job = require('./models/Job');
var util = require('./util')

// router.get('/listing/:id', function(req, res){
//   console.log('PARAMS', req.params);
//   console.log('ATTR', req.attr);
// 	Job.find({id: req.params.id}, function(err, doc){
//     console.log("ALL JOBS FOR ID", req.fbId)
//     res.json(doc);
//   });

// });

var orders = { //If adding or removing labels, be sure to edit max value of adjustStatus in listing controller
  'Interested': 0,
  'Outreach': 1,
  'Phone Interview': 2,
  'Coding Challenge': 3,
  'Onsite Interview': 4,
  'Offer Received': 5,
  'Employer Declined': 6,
  'Offer Declined': 7,
  'Offer Accepted': 8
};

router.get('/listing', function(req, res){
  // console.log('ID', req.body)
  Job.find(function(err, doc){
    res.json(doc);
  });

});

router.post("/listing", function(req, res) {

  new Job ({
    'type': req.body.type,
    'company': req.body.company,
    'position': req.body.position,
    'deadline': req.body.deadline,
    'link': req.body.link,
    'status': req.body.status,
    'statusOrder': orders[req.body.status],
    'modifiedAt': new Date()
})
.save(function(err, task){
    res.status(201).json(task)
  });
});

router.delete("/listing", function(req, res) {
  Job.findByIdAndRemove(req.body._id, function (err) {
    if (err) throw err;
    res.send(req.body);
  });
});

router.put("/listing", function(req, res) {
  req.body.statusOrder = orders[req.body.status];
  Job.findByIdAndUpdate(req.body._id, req.body, function (err) {
    if (err) throw err;
    res.send(req.body);
  });
});

module.exports = router;
<commit_msg>sort by added date<commit_after>var router = require('express').Router();

//Import models
var User = require('./models/User');
var Job = require('./models/Job');
var util = require('./util')

// router.get('/listing/:id', function(req, res){
//   console.log('PARAMS', req.params);
//   console.log('ATTR', req.attr);
// 	Job.find({id: req.params.id}, function(err, doc){
//     console.log("ALL JOBS FOR ID", req.fbId)
//     res.json(doc);
//   });

// });

var orders = { //If adding or removing labels, be sure to edit max value of adjustStatus in listing controller
  'Interested': 0,
  'Outreach': 1,
  'Phone Interview': 2,
  'Coding Challenge': 3,
  'Onsite Interview': 4,
  'Offer Received': 5,
  'Employer Declined': 6,
  'Offer Declined': 7,
  'Offer Accepted': 8
};

router.get('/listing', function(req, res){
  // console.log('ID', req.body)
  Job.find(function(err, doc){
    res.json(doc);
  });

});

router.post("/listing", function(req, res) {

  new Job ({
    'type': req.body.type,
    'company': req.body.company,
    'position': req.body.position,
    'deadline': req.body.deadline,
    'link': req.body.link,
    'status': req.body.status,
    'statusOrder': orders[req.body.status],
    'modifiedAt': new Date()
})
.save(function(err, task){
    res.status(201).json(task)
  });
});

router.delete("/listing", function(req, res) {
  Job.findByIdAndRemove(req.body._id, function (err) {
    if (err) throw err;
    res.send(req.body);
  });
});

router.put("/listing", function(req, res) {

  req.body.statusOrder = orders[req.body.status];
  Job.findByIdAndUpdate(req.body._id, req.body, function (err) {
    if (err) throw err;
    res.send(req.body);
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var eventsController = require('./controllers/events-controller.js');
var userController = require('./controllers/user-controller.js');
var chatController = require('./controllers/chat-controller.js');

module.exports = function(app, express) {

  //serve up most recent on home page
  app.get('/', eventsController.getAllEvents);
  //get all events
  app.get('/api/events', eventsController.getAllEvents);
  //get the most recent events
  app.get('/api/events/recent', eventsController.getMostRecent);
  //get events by location
  // app.get('/api/events', eventsController.getByLocation);
  //get single event page
  app.get('/api/event/:id', eventsController.getEvent);
  //create event
  app.post('/api/event', eventsController.postEvent);
  //get user's public profile
  app.get('/api/user/:id', userController.getUser);
  // //create user profile
  app.post('/api/user', userController.postUser);
  // //get all messages for chatroom
  // app.get('/api/chat', chatController.getMessages);
  // //send a message
  app.post('/api/chat', chatController.postMessage);
}<commit_msg>updated routes removing the /:id from user get api endpoint<commit_after>var eventsController = require('./controllers/events-controller.js');
var userController = require('./controllers/user-controller.js');
var chatController = require('./controllers/chat-controller.js');

module.exports = function(app, express) {

  //serve up most recent on home page
  app.get('/', eventsController.getAllEvents);
  //get all events
  app.get('/api/events', eventsController.getAllEvents);
  //get the most recent events
  app.get('/api/events/recent', eventsController.getMostRecent);
  //get events by location
  // app.get('/api/events', eventsController.getByLocation);
  //get single event page
  app.get('/api/event/:id', eventsController.getEvent);
  //create event
  app.post('/api/event', eventsController.postEvent);
  //get user's public profile
  app.get('/api/user', userController.getUser);
  // //create user profile
  app.post('/api/user', userController.postUser);
  // //get all messages for chatroom
  // app.get('/api/chat', chatController.getMessages);
  // //send a message
  app.post('/api/chat', chatController.postMessage);
  //post to EventParticipant when user joins event
  app.post('/api/joinevent', userController.postJoinEvent);
}<|endoftext|>


<commit_before>const bleno = require('bleno')

const TestCharacteristic = require('./characteristics/test')
const LightCharacteristic = require('./characteristics/light')
const AntiTheftCharacteristic = require('./characteristics/antiTheft')

const ids = require('../global/ble').bleIds

const bikeService = new bleno.PrimaryService({
  uuid: ids.get('SERVICE').uuid,
  characteristics: [
    new TestCharacteristic(),
    new LightCharacteristic(),
    new AntiTheftCharacteristic()
  ]
});

bleno.on('stateChange', function(state) {
  console.log('State changed to: ' + state)

  if (state === 'poweredOn') {
    bleno.startAdvertising(ids.get('PI').name, [ids.get('PI').uuid])
    bleno.startAdvertising(ids.get('SERVICE').name, [bikeService.uuid])
  } else {
    bleno.stopAdvertising()
  }
})

bleno.on('advertisingStart', function(error) {
  console.log('Advertising started: ' + (error ? 'error ' + error : 'success'))
  if (!error) {
    bleno.setServices([bikeService])
    console.log('Advertising ' + ids.get('SERVICE').name + ' with UUID ' + bikeService.uuid)
  }
})

process.on('SIGTERM', function () {
  bleno.stopAdvertising()
})<commit_msg>Change to previous Char format<commit_after>const bleno = require('bleno')

const TestCharacteristic = require('./characteristics/test')
const LightCharacteristic = require('./characteristics/light')
const AntiTheftCharacteristic = require('./characteristics/antiTheft')

const ids = require('../global/ble').bleIds

const testCharacteristic = new TestCharacteristic()
const lightCharacteristic = new LightCharacteristic()
const antiTheftCharacteristic = new AntiTheftCharacteristic()

const bikeService = new bleno.PrimaryService({
  uuid: ids.get('SERVICE').uuid,
  characteristics: [
    testCharacteristic,
    lightCharacteristic,
    antiTheftCharacteristic
  ]
});

bleno.on('stateChange', function(state) {
  console.log('State changed to: ' + state)

  if (state === 'poweredOn') {
    bleno.startAdvertising(ids.get('PI').name, [ids.get('PI').uuid])
    bleno.startAdvertising(ids.get('SERVICE').name, [bikeService.uuid])
  } else {
    bleno.stopAdvertising()
  }
})

bleno.on('advertisingStart', function(error) {
  console.log('Advertising started: ' + (error ? 'error ' + error : 'success'))
  if (!error) {
    bleno.setServices([bikeService])
    console.log('Advertising ' + ids.get('SERVICE').name + ' with UUID ' + bikeService.uuid)
  }
})

process.on('SIGTERM', function () {
  bleno.stopAdvertising()
})<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    path = require('path'),
    config = process.env.PORT ? (require('./config_azure')) : (require('./config')),
    db = new (require('./db'))(config),
    bodyParser = require('body-parser');

app.use(express.static(path.join(__dirname, '../app')));
app.listen(process.env.PORT || config.port, function() {
    console.log('on air');
});
app.use(bodyParser.json());

var fs = require('fs'),
    nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'isa.yahiev@gmail.com',
        pass: '03ch01me93go'
    }
});

app.get('/sendmail', function(req, res) {
    console.log("aloha!");
    res.writeHead(200, { 'Content-Type': 'text/html' });

    fs.readFile('email_template.html', function (err, logData) {
        if (err) throw err;

        var text = logData.toString();

        var mailOptions = {
            from: 'Isa Yakhiev <isa.yahiev@gmail.com>', // sender address
            to: 'isa.ya@mail.ru', // list of receivers
            subject: 'Hello', // Subject line
            text: 'Hello world', // plaintext body
            html: text // html body
        };

        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                res.send('Sending error:' + error);
            } else {
                res.send('Message sent!');
            }
        });
    });
});

app.post('/adduser', function(req, res) {
    db.addUser(req.body, function (data) {
        res.send(data)
    });
});

app.post('/getuser', function(req, res) {
    db.getUser(req.body, function (data) {
        res.send(data)
    });
});

app.post('/getproject', function(req, res) {
    db.getProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/updateproject', function(req, res) {
    db.updateProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/deleteproject', function(req, res) {
    db.deleteProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/newproject', function(req, res) {
    db.addProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/gettask', function(req, res) {
    db.getTask(req.body, function (data) {
        res.send(data)
    });
});

app.post('/newtask', function(req, res) {
    db.addTask(req.body, function (data) {
        res.send(data)
    });
});

app.post('/updatetask', function(req, res) {
    db.updateTask(req.body, function (data) {
        res.send(data)
    });
});

app.post('/deletetask', function(req, res) {
    db.deleteTask(req.body, function (data) {
        res.send(data)
    });
});

app.all('*', function(req, res) {
    console.log("all");
    res.redirect("/");
});
<commit_msg>first commit<commit_after>var express = require('express'),
    app = express(),
    path = require('path'),
    config = process.env.PORT ? (require('./config_azure')) : (require('./config')),
    db = new (require('./db'))(config),
    bodyParser = require('body-parser');

app.use(express.static(path.join(__dirname, '../app')));
app.listen(process.env.PORT || config.port, function() {
    console.log('on air');
});
app.use(bodyParser.json());

var fs = require('fs'),
    nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'isa.yahiev@gmail.com',
        pass: '03ch01me93go'
    }
});

app.post('/adduser', function(req, res) {
    db.addUser(req.body, function (data) {
        res.send(data)
    });
});

app.post('/getuser', function(req, res) {
    db.getUser(req.body, function (data) {
        res.send(data)
    });
});

app.post('/getproject', function(req, res) {
    console.log("aloha!");
    res.writeHead(200, { 'Content-Type': 'text/html' });

    fs.readFile('email_template.html', function (err, logData) {
        if (err) throw err;

        var text = logData.toString();

        var mailOptions = {
            from: 'Isa Yakhiev <isa.yahiev@gmail.com>', // sender address
            to: 'isa.ya@mail.ru', // list of receivers
            subject: 'Hello', // Subject line
            text: 'Hello world', // plaintext body
            html: text // html body
        };

        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                res.send('Sending error:' + error);
            } else {
                res.send('Message sent!');
            }
        });
    });
    /*db.getProject(req.body, function (data) {
        res.send(data)
    });*/
});

app.post('/updateproject', function(req, res) {
    db.updateProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/deleteproject', function(req, res) {
    db.deleteProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/newproject', function(req, res) {
    db.addProject(req.body, function (data) {
        res.send(data)
    });
});

app.post('/gettask', function(req, res) {
    db.getTask(req.body, function (data) {
        res.send(data)
    });
});

app.post('/newtask', function(req, res) {
    db.addTask(req.body, function (data) {
        res.send(data)
    });
});

app.post('/updatetask', function(req, res) {
    db.updateTask(req.body, function (data) {
        res.send(data)
    });
});

app.post('/deletetask', function(req, res) {
    db.deleteTask(req.body, function (data) {
        res.send(data)
    });
});

app.all('*', function(req, res) {
    console.log("all");
    res.redirect("/");
});
<|endoftext|>


<commit_before>'use strict';
  // The data is simply the message that we're sending back

var http = require('http');
var buttons = require('./input.js');
var types = require('./types.js');
var server = http.createServer(function(request, response) {});

server.listen(1337, function() {
  console.log((new Date()) + ' Server is listening on port 1337');
});

var WebSocketServer = require('websocket').server;
var wsServer = new WebSocketServer({
  httpServer: server
});

var count = 0;
var clients = {};
var bullets = [];

wsServer.on('request', function(r) {
  // Code here to run on connection

  var connection = r.accept('echo-protocol', r.origin);

  // Specific id for this client & increment count
  var id = count++;
  // Store the connection method so we can loop through & contact all clients
  clients[id] = connection;

  connection.player = generatePlayer();

  console.log((new Date()) + ' Connection accepted [' + id + ']');

  // Create event listener
  connection.on('message', function(message) {

    // The string message that was sent to us
    var event = JSON.parse(message.utf8Data);
    if(event.type == 'inputs') {
      connection.player.input = [false].concat(event.inputs);
    }
  });

  connection.on('close', function(reasonCode, description) {
    delete clients[id];
    console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
  });

});

function loop() {
  time = getTime();
  var deltaTime = time -oldTime;
  updateTickAccumulator += deltaTime;
  networkTickAccumulator += deltaTime;
  oldTime = time;
  while(updateTickAccumulator > UPDATE_TICK_LENGTH_IN_MS) {
    updateTickAccumulator -= UPDATE_TICK_LENGTH_IN_MS;
    processInput();
    update();
  }
  if(networkTickAccumulator > NETWORK_TICK_LENGTH_IN_MS) {
    networkTickAccumulator = networkTickAccumulator % NETWORK_TICK_LENGTH_IN_MS;
    sendNetworkState();
  }
  setTimeout(loop);
}

loop();

var initialTime = getTime();
var time = getTime();
var oldTime = time;
var deltaTime = 0;
var updateTickAccumulator = 0;
var networkTickAccumulator = 0;
var UPDATE_TICK_LENGTH_IN_MS = 15;
var NETWORK_TICK_LENGTH_IN_MS = 50;
var FRICTION_COEFFICIENT = 0.98;

function getTime() {
  return +new Date() / 1;
}

function log() {
  var message = Array.prototype.join.call(arguments, '')
  console.log.apply(
    console, ['[' + (getTime() - initialTime | 0) + ']'].concat(message));
}

function generatePlayer() {
  return {
    name: null,
    x: Math.random() * 16,
    y: Math.random() * 9,
    dx: 0,
    dy: 0,
    input: []
  };
}

function processInput() {
  //log('processInput');
}

function update() {
  //log('update');
  for(var i in clients) {
    if(!clients.hasOwnProperty(i)) {
      continue;
    }
    var player = clients[i].player;
    var motionButtonPressed = false;
    if(player.input[buttons.MOVE_UP]) {
      player.dy = -1;
      motionButtonPressed = true;
    }
    if(player.input[buttons.MOVE_DOWN]) {
      player.dy = 1;
      motionButtonPressed = true;
    }
    if(player.input[buttons.MOVE_LEFT]) {
      player.dx = -1;
      motionButtonPressed = true;
    }
    if(player.input[buttons.MOVE_RIGHT]) {
      player.dx = 1;
      motionButtonPressed = true;
    }
    var normalizer = Math.sqrt(player.dx * player.dx + player.dy * player.dy);
    if(normalizer > 1) {
      player.dx = player.dx / normalizer;
      player.dy = player.dy / normalizer;
    }
    player.dx *= 0.1;
    player.dy *= 0.1;
    player.dx *= FRICTION_COEFFICIENT;
    player.dy *= FRICTION_COEFFICIENT;
    player.x += player.dx;
    player.y += player.dy;

    if(player.input[buttons.FIRE]){
      var m_x = player.input[buttons.MOUSE_X]
      var m_y = player.input[buttons.MOUSE_Y]

      var fire_dir_x = m_x - player.x;
      var fire_dir_y = m_y - player.y;
      var fire_dir_len = Math.sqrt(fire_dir_x * fire_dir_x + fire_dir_y * fire_dir_y);

      //if you click yourself don't shoot
      if(fire_dir_len > 0.01) {
        //Scale to unit length
        fire_dir_x = fire_dir_x / fire_dir_len;
        fire_dir_y = fire_dir_y / fire_dir_len;

        //Scale to bullet speed
        fire_dir_x = fire_dir_x * 0.05;
        fire_dir_y = fire_dir_y * 0.05;

        bullets.push({x: player.x, y: player.y, dx: fire_dir_x + player.dx, dy: fire_dir_y + player.dy})
      }
    }
  }
  for(var i = 0; i < bullets.length; i++){
    var bullet = bullets[i];
    bullet.x += bullet.dx;
    bullet.y += bullet.dy;
  }
}

function sendNetworkState() {
  //log('network state');
  var state = [];
  for(var i in clients) {
    if(!clients.hasOwnProperty(i)) {
      continue;
    }
    var player = clients[i].player;
    state.push({
      type: types.PLAYER,
      id: i,
      x: player.x,
      y: player.y
    });
  }
  for(var i = 0; i<bullets.length; i++){
    state.push({
      type: types.BULLET,
      x: bullets[i].x,
      y: bullets[i].y
    });
  }
  var stateAsJSON = JSON.stringify(state);
  for(var i in clients) {
    if(!clients.hasOwnProperty(i)) {
      continue;
    }
    clients[i].sendUTF(stateAsJSON);
  }
}
<commit_msg>Make bullets faster but with cooldown<commit_after>'use strict';
  // The data is simply the message that we're sending back

var http = require('http');
var buttons = require('./input.js');
var types = require('./types.js');
var server = http.createServer(function(request, response) {});

server.listen(1337, function() {
  console.log((new Date()) + ' Server is listening on port 1337');
});

var WebSocketServer = require('websocket').server;
var wsServer = new WebSocketServer({
  httpServer: server
});

var count = 0;
var clients = {};
var bullets = [];
var fireCooldownTime = 66;

wsServer.on('request', function(r) {
  // Code here to run on connection

  var connection = r.accept('echo-protocol', r.origin);

  // Specific id for this client & increment count
  var id = count++;
  // Store the connection method so we can loop through & contact all clients
  clients[id] = connection;

  connection.player = generatePlayer();

  console.log((new Date()) + ' Connection accepted [' + id + ']');

  // Create event listener
  connection.on('message', function(message) {

    // The string message that was sent to us
    var event = JSON.parse(message.utf8Data);
    if(event.type == 'inputs') {
      connection.player.input = [false].concat(event.inputs);
    }
  });

  connection.on('close', function(reasonCode, description) {
    delete clients[id];
    console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
  });

});

function loop() {
  time = getTime();
  var deltaTime = time -oldTime;
  updateTickAccumulator += deltaTime;
  networkTickAccumulator += deltaTime;
  oldTime = time;
  while(updateTickAccumulator > UPDATE_TICK_LENGTH_IN_MS) {
    updateTickAccumulator -= UPDATE_TICK_LENGTH_IN_MS;
    processInput();
    update();
  }
  if(networkTickAccumulator > NETWORK_TICK_LENGTH_IN_MS) {
    networkTickAccumulator = networkTickAccumulator % NETWORK_TICK_LENGTH_IN_MS;
    sendNetworkState();
  }
  setTimeout(loop);
}

loop();

var initialTime = getTime();
var time = getTime();
var oldTime = time;
var deltaTime = 0;
var updateTickAccumulator = 0;
var networkTickAccumulator = 0;
var UPDATE_TICK_LENGTH_IN_MS = 15;
var NETWORK_TICK_LENGTH_IN_MS = 50;
var FRICTION_COEFFICIENT = 0.98;

function getTime() {
  return +new Date() / 1;
}

function log() {
  var message = Array.prototype.join.call(arguments, '')
  console.log.apply(
    console, ['[' + (getTime() - initialTime | 0) + ']'].concat(message));
}

function generatePlayer() {
  return {
    name: null,
    x: Math.random() * 16,
    y: Math.random() * 9,
    dx: 0,
    dy: 0,
    input: [],
    fireCooldown: 0
  };
}

function processInput() {
  //log('processInput');
}

function update() {
  //log('update');
  for(var i in clients) {
    if(!clients.hasOwnProperty(i)) {
      continue;
    }
    var player = clients[i].player;
    var motionButtonPressed = false;
    if(player.input[buttons.MOVE_UP]) {
      player.dy = -1;
      motionButtonPressed = true;
    }
    if(player.input[buttons.MOVE_DOWN]) {
      player.dy = 1;
      motionButtonPressed = true;
    }
    if(player.input[buttons.MOVE_LEFT]) {
      player.dx = -1;
      motionButtonPressed = true;
    }
    if(player.input[buttons.MOVE_RIGHT]) {
      player.dx = 1;
      motionButtonPressed = true;
    }
    var normalizer = Math.sqrt(player.dx * player.dx + player.dy * player.dy);
    if(normalizer > 1) {
      player.dx = player.dx / normalizer;
      player.dy = player.dy / normalizer;
    }
    player.dx *= 0.1;
    player.dy *= 0.1;
    player.dx *= FRICTION_COEFFICIENT;
    player.dy *= FRICTION_COEFFICIENT;
    player.x += player.dx;
    player.y += player.dy;

    if(player.fireCooldown > 0){
      player.fireCooldown--;
    }

    if(player.input[buttons.FIRE] && player.fireCooldown <= 0){
      player.fireCooldown = fireCooldownTime;
      var m_x = player.input[buttons.MOUSE_X]
      var m_y = player.input[buttons.MOUSE_Y]

      var fire_dir_x = m_x - player.x;
      var fire_dir_y = m_y - player.y;
      var fire_dir_len = Math.sqrt(fire_dir_x * fire_dir_x + fire_dir_y * fire_dir_y);

      //if you click yourself don't shoot
      if(fire_dir_len > 0.01) {
        //Scale to unit length
        fire_dir_x = fire_dir_x / fire_dir_len;
        fire_dir_y = fire_dir_y / fire_dir_len;

        //Scale to bullet speed
        fire_dir_x = fire_dir_x * 0.3;
        fire_dir_y = fire_dir_y * 0.3;

        bullets.push({x: player.x, y: player.y, dx: fire_dir_x + player.dx, dy: fire_dir_y + player.dy})
      }
    }
  }
  for(var i = 0; i < bullets.length; i++){
    var bullet = bullets[i];
    bullet.x += bullet.dx;
    bullet.y += bullet.dy;
  }
}

function sendNetworkState() {
  //log('network state');
  var state = [];
  for(var i in clients) {
    if(!clients.hasOwnProperty(i)) {
      continue;
    }
    var player = clients[i].player;
    state.push({
      type: types.PLAYER,
      id: i,
      x: player.x,
      y: player.y
    });
  }
  for(var i = 0; i<bullets.length; i++){
    state.push({
      type: types.BULLET,
      x: bullets[i].x,
      y: bullets[i].y
    });
  }
  var stateAsJSON = JSON.stringify(state);
  for(var i in clients) {
    if(!clients.hasOwnProperty(i)) {
      continue;
    }
    clients[i].sendUTF(stateAsJSON);
  }
}
<|endoftext|>


<commit_before>/* Base URL for canvas/bCourses API requests. */
var canvasBaseURL = "https://bcourses.berkeley.edu/api/v1";

function requestParams(params) {
    var baseQuery =  { 'per_page': '100' };
    var qs = _.extend({}, baseQuery, params);
    var options = {
        headers: {
            Authorization: 'Bearer ' + Meteor.user().canvasToken
        },
        params: qs,
        npmRequestOptions: {
            json: true,
            useQueryString: true
        }
    }
    return options;
}

/* Check if an object in arr has value for field. */
function findObjectByField(arr, field, value) {
    for (var i = 0; i < arr.length; i += 1) {
        if (arr[i][field] == value) {
            return i;
        }
    }
    return -1;
}

function coursePath(id) {
    return canvasBaseURL + "/courses"+ (id ? "/" + id : '');
}

Meteor.methods({
    getCourses: function() {
        var result = Meteor.http.get(coursePath(),
                requestParams({'include[]':'term'})).content;
        //var myCourses = Courses.find({user_id: Meteor.userId()});
        var myCourseIds = Meteor.user().courses;
        if (myCourseIds) {
            var myCourses = Courses.find({'id' : { $in : myCourseIds}});
            myCourses = myCourses.fetch();
            for (var i=0; i < myCourses.length; i += 1) {
                var index = findObjectByField(result, 'id', myCourses[i].id);
                if (index != -1) {
                    result[index] = myCourses[i];
                }
            }
        }
        return result;
    },
    getAssignmentList: function(cId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments", requestParams()).content;
        return result;
    },
    getAssignment: function(cId, assignmentId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments/" + assignmentId, requestParams()).content;
        return result;
    },
    getStaff: function(cId) {
        console.log('STAFF SERVER CALLED');
        var tas = requestParams({enrollment_type:'ta',
                'include[]': ['email', 'avatar_url'] });
        var instructors = requestParams({enrollment_type:'teacher',
                'include[]': ['email', 'avatar_url'] });
        var call = Meteor.http.get(coursePath(cId) + "/users", tas);
        console.log(call.content.length);
        return call.content;
    },
    addCourse: function(course) {
        var courseDB = Courses.find({'id': course.id});
        if (courseDB.fetch().length == 0) {
            Courses.insert(course);
        }
        Meteor.users.update({'_id':Meteor.userId()}, {$set: {'courses': Meteor.user().courses ? Meteor.user().courses.push(course.id) : [course.id]}});
        return course;
    }
});
<commit_msg>fixed addition of multiple classes to account<commit_after>/* Base URL for canvas/bCourses API requests. */
var canvasBaseURL = "https://bcourses.berkeley.edu/api/v1";

function requestParams(params) {
    var baseQuery =  { 'per_page': '100' };
    var qs = _.extend({}, baseQuery, params);
    var options = {
        headers: {
            Authorization: 'Bearer ' + Meteor.user().canvasToken
        },
        params: qs,
        npmRequestOptions: {
            json: true,
            useQueryString: true
        }
    }
    return options;
}

/* Check if an object in arr has value for field. */
function findObjectByField(arr, field, value) {
    for (var i = 0; i < arr.length; i += 1) {
        if (arr[i][field] == value) {
            return i;
        }
    }
    return -1;
}

function coursePath(id) {
    return canvasBaseURL + "/courses"+ (id ? "/" + id : '');
}

Meteor.methods({
    getCourses: function() {
        var result = Meteor.http.get(coursePath(),
                requestParams({'include[]':'term'})).content;
        //var myCourses = Courses.find({user_id: Meteor.userId()});
        var myCourseIds = Meteor.user().courses;
        if (myCourseIds) {
            var myCourses = Courses.find({'id' : { $in : myCourseIds}});
            myCourses = myCourses.fetch();
            for (var i=0; i < myCourses.length; i += 1) {
                var index = findObjectByField(result, 'id', myCourses[i].id);
                if (index != -1) {
                    result[index] = myCourses[i];
                }
            }
        }
        return result;
    },
    getAssignmentList: function(cId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments", requestParams()).content;
        return result;
    },
    getAssignment: function(cId, assignmentId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments/" + assignmentId, requestParams()).content;
        return result;
    },
    getStaff: function(cId) {
        console.log('STAFF SERVER CALLED');
        var tas = requestParams({enrollment_type:'ta',
                'include[]': ['email', 'avatar_url'] });
        var instructors = requestParams({enrollment_type:'teacher',
                'include[]': ['email', 'avatar_url'] });
        var call = Meteor.http.get(coursePath(cId) + "/users", tas);
        console.log(call.content.length);
        return call.content;
    },
    addCourse: function(course) {
        var courseDB = Courses.find({'id': course.id});
        if (courseDB.fetch().length == 0) {
            Courses.insert(course);
        }
        Meteor.users.update({'_id':Meteor.userId()}, {$addToSet: {'courses':course.id}});
        return course;
    }
});
<|endoftext|>


<commit_before>var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(8081);

console.log("Starting server on port 8081");

io.on('connection', function (socket) {

  socket.on('login', function (data) {
    console.log("User connected with id:" + data);
    socket.join(data);
  });

  socket.on('pos', function (data) {
    console.log(data);
    io.sockets.in(socket.room).emit('pos', data);
  });

  socket.on('cmd', function (data) {
    console.log(data);
    io.sockets.in(socket.room).emit('cmd', data);
  });

});<commit_msg>quickfix<commit_after>var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(8081);

console.log("Starting server on port 8081");

io.on('connection', function (socket) {

  socket.on('login', function (data) {
    console.log("User connected with id:" + data);
    socket.join(data);
  });

  socket.on('pos', function (data) {
    //console.log(data);
    io.sockets.in(socket.room).emit('pos', data);
  });

  socket.on('cmd', function (data) {
    console.log(data);
    io.sockets.in(socket.room).emit('cmd', data);
  });

});<|endoftext|>


<commit_before>enchant.TextField = enchant.Class.create(enchant.Node, {
  initialize: function(width, height) {
    enchant.Node.call(this);

    // Remove 37 (left-key), 39 (right-key) and 32 (space-key)
    // from 'enchant.ENV.PREVENT_DEFAULT_KEY_CODES'
    this._setPreventDefaultKeyCodes();

    this._width = width;
    this._height = height;

    this.input = document.createElement('input');
    this.input.type = 'text';
    this.input.style.position = 'absolute';
    enchant.Core.instance._element.appendChild(this.input);
  },

  _setPreventDefaultKeyCodes: function() {
    var codes = enchant.ENV.PREVENT_DEFAULT_KEY_CODES;
    codes = codes.filter(function (code) {
      return (code !== 37 & code !== 39 && code !== 32);
    });
    enchant.ENV.PREVENT_DEFAULT_KEY_CODES = codes;
  }
});<commit_msg>Fix a small bug<commit_after>enchant.TextField = enchant.Class.create(enchant.Node, {
  initialize: function(width, height) {
    enchant.Node.call(this);

    // Remove 37 (left-key), 39 (right-key) and 32 (space-key)
    // from 'enchant.ENV.PREVENT_DEFAULT_KEY_CODES'
    this._setPreventDefaultKeyCodes();

    this._width = width;
    this._height = height;

    this.input = document.createElement('input');
    this.input.type = 'text';
    this.input.style.position = 'absolute';
    enchant.Core.instance._element.appendChild(this.input);
  },

  _setPreventDefaultKeyCodes: function() {
    var codes = enchant.ENV.PREVENT_DEFAULT_KEY_CODES;
    codes = codes.filter(function (code) {
      return (code !== 37 && code !== 39 && code !== 32);
    });
    enchant.ENV.PREVENT_DEFAULT_KEY_CODES = codes;
  }
});<|endoftext|>


<commit_before>var express    = require('express');
var bodyParser = require('body-parser');
var route      = require('./route');
var app        = express();

var Annict = require('annict').default;
var annict = new Annict();

app.set('views', __dirname+'/views');
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use('/static', express.static(__dirname+'/../public'));
app.use(route);

var mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI);

var models = {};
models.User = mongoose.model('User', require('./models/user'));

app.set('models', models);

var CronJob = require('cron').CronJob;
const BATCH_INTERBAL = process.env.BATCH_INTERBAL;

const User = models.User;

try {
new CronJob(`*/5 * * * * *`, function() {
  User.find({}, function(err, users) {
    console.log(users);
    users.forEach(user => {
      annict.Me.Work.get({
        access_token: user.access_token,
        filter_status: 'watching',
        per_page: 10
      })
      .then(response => {
        user.watching = response.works;
        user.save();
        console.log('update');
      });
    });
  });

}, function() {}, true, 'Asia/Tokyo');
}
catch(ex) {
  console.log(ex);
}

app.listen(process.env.PORT || 3000);
<commit_msg>insert var to app as config<commit_after>var express    = require('express');
var bodyParser = require('body-parser');
var route      = require('./route');
var app        = express();

app.set('views', __dirname+'/views');
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use('/static', express.static(__dirname+'/../public'));
app.use(route);

const config = {
  MONGODB_URI: process.env.MONGODB_URI,
  ANNICT_FETCH_INTERBAL: process.env.ANNICT_FETCH_INTERBAL
  CLIENT_ID: process.env.CLIENT_ID,
  CLIENT_SECRET: process.env.CLIENT_SECRET,
  REDIRECT_URI: process.env.REDIRECT_URI,
};
app.set('config', config);

var Annict = require('annict').default;
var annict = new Annict();
app.set('middlewares', {
  annict
});

var mongoose = require('mongoose');
var models = {};
mongoose.connect(config.MONGODB_URI);
const User = models.User = mongoose.model('User', require('./models/user'));
app.set('models', models);

/**
 * Noe-Cron Job to fetch new data for all user
 */
const CronJob = require('cron').CronJob;
try {
  new CronJob(`* */5 * * * *`, function() {
    User.find({}, function(err, users) {
      users.forEach(user => {
        annict.Me.Work.get({
          access_token: user.access_token,
          filter_status: 'watching',
          per_page: 10
        })
        .then(response => {
          user.watching = response.works;
          user.save();
        });
      });
    });
  },
  () => {
    console.log('cron job finished');
  },
  true,
  'Asia/Tokyo');
}
catch(ex) {
  console.log(ex);
}

module.exports = app;
<|endoftext|>


<commit_before>'use strict'

var express         = require('express'),
    sass            = require('node-sass-middleware'),
    bodyParser      = require('body-parser'),
    api             = require('./api/routes'),
    secrets         = require('./lib/secrets'),
    session         = require('express-session'),
    path            = require('path'),
    cookieParser    = require('cookie-parser');

//bringing in the database module
var database = require('./lib/mongodb');

var PROJECT_ROOT = path.resolve(__dirname, '..');
var SERVER_ROOT = PROJECT_ROOT + '/build';
var userRoutes = require('./routes/users')
var app = express();
app.use(express.static(SERVER_ROOT));

//session middleware
app.use(session({
  secret: 'doesthismakeitwork',
  resave: false,
  saveUninitialized: true
}))

app.use(function (req, res, next) {
  console.log('SESSION>>>>>>>>>>', req.session)
  next();
})

app.set('port', process.env.PORT || 3000);

//setting the local user value for that response
app.use(function getAuthStatus(req, res, next) {
  if (req.session.user) {
    console.log(req.session.user)
    res.locals.user = req.session.user;
  } else {
    res.locals.user = null;
  }
  next();
})

app.set('view engine', 'jade');
app.use(sass({
  dest: 'www/css',
  outputStyle: 'compressed',
  prefix: '/css',
  sourceMap: app.get('env') === 'production' ? 'false' : true,
  src: '../styles',
  force: true
}));

//makes the body available from post requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// app.use(function (req, res, next) {
//   if (req.session.user) {
//     next();
//   } else {
//     res.status(403).send({redirect: true})
//   }
// })

app.use('/users', userRoutes)
app.use('/api', api);
// app.use('/', routes);

// app.use(function(req, res, next) {
//     var err = new Error('Not Found - hello heroku');
//     err.status = 404;
//     next(err);
// });

app.use(function(err, req, res) {
  res.status(err.status || 500);
  res.end(JSON.stringify({
    message: err.message,
    error: {}
  }));
});

database.connect(onDbConnect);

function onDbConnect(err, db) {
  if (err) {
    console.error('Database Connection Error.' + err)
  } else {
    console.log('Database Connection Established at' + db.options.url);
    startNodeListener();
  }
}

function startNodeListener () {
  var server = app.listen(app.get('port'), function () {
    var port = server.address().port;
    var mode = app.get('env');

    console.log('Server listening on port ' + port + ' in ' + mode + ' mode...');
  });
}

module.exports = app;
<commit_msg>update server.js for heroku test<commit_after>'use strict'

var express         = require('express'),
    sass            = require('node-sass-middleware'),
    bodyParser      = require('body-parser'),
    api             = require('./api/routes'),
    secrets         = require('./lib/secrets'),
    session         = require('express-session'),
    path            = require('path'),
    cookieParser    = require('cookie-parser');

//bringing in the database module
var database = require('./lib/mongodb');

var PROJECT_ROOT = path.resolve(__dirname, '..');
var SERVER_ROOT = PROJECT_ROOT + '/build';
var userRoutes = require('./routes/users')
var app = express();
app.use(express.static(SERVER_ROOT));

//session middleware
app.use(session({
  secret: 'doesthismakeitwork',
  resave: false,
  saveUninitialized: true
}))

app.use(function (req, res, next) {
  console.log('SESSION>>>>>>>>>>', req.session)
  next();
})

app.set('port', process.env.PORT || 3000);

//setting the local user value for that response
app.use(function getAuthStatus(req, res, next) {
  if (req.session.user) {
    console.log(req.session.user)
    res.locals.user = req.session.user;
  } else {
    res.locals.user = null;
  }
  next();
})

app.set('view engine', 'jade');
app.use(sass({
  dest: 'www/css',
  outputStyle: 'compressed',
  prefix: '/css',
  sourceMap: app.get('env') === 'production' ? 'false' : true,
  src: '../styles',
  force: true
}));

//makes the body available from post requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/users', userRoutes)

app.use(function (req, res, next) {
  if (req.session.user) {
    next();
  } else {
    res.status(403).send({redirect: true})
  }
})

app.use('/api', api);
// app.use('/', routes);

database.connect(onDbConnect);

function onDbConnect(err, db) {
  if (err) {
    console.error('Database Connection Error.' + err)
  } else {
    console.log('Database Connection Established at' + db.options.url);
    startNodeListener();
  }
}

function startNodeListener () {
  var server = app.listen(app.get('port'), function () {
    var port = server.address().port;
    var mode = app.get('env');

    console.log('Server listening on port ' + port + ' in ' + mode + ' mode...');
  });
}

module.exports = app;
<|endoftext|>


<commit_before>// set globals
//global.log = require('./config/log');
global.log = require('./config/log');
global._ = require('lodash');
global.Promise = require('bluebird');

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;

String.prototype.toObjectId = function() {
	var ObjectId = mongoose.Types.ObjectId;
	return new ObjectId(this.toString());
};

// allows you to push multiple arrays onto another array
// ex:
// var foo = []
// foo.pushAll([1,2,3],[4,5,6])
Array.prototype.pushAll = function () {
	this.push.apply(this, this.concat.apply([], arguments));
};

var config = require('./config/config');
var app = Promise.promisifyAll(require('./config/express'));
var server = Promise.promisifyAll(require('http').Server(app));
var socketio = require('./config/socketio');

var User = require('./models/User');
var Room = require('./models/Room');

module.exports.run = function (cb) {

	log.info('server - Starting "' + config.environment + '"');

	connectToMongoose()
		.then(startup)
		.then(function () {
			socketio.connect(server);
			return server.listenAsync(config.express.port);
		})
		.then(function () {
			log.info('server - hosted - http://' + config.express.ip + ':' + config.express.port);
		})
		.then(cb)
		.catch(function (error) {
			return log.error('server - Error while starting', error);
		});
};

function connectToMongoose() {
	return new Promise(function (resolve, reject) {
		var url = "mongodb://" + config.db.host + ":" + config.db.port + "/" + config.db.name;
		mongoose.connect(url);
		mongoose.connection.once('open', function (err) {
			if (err) return reject(err);
			log.info('mongoose ' + url);
			resolve();
		});
	});
}

function startup(){
	return Promise.join(
		User.update({}, {sockets: [], typingIn: null}, { multi: true }),
		ensureFirstRoom()
	)
}

function ensureFirstRoom() {
	return Room.findOne({name: 'First'})
		.then(function (firstRoom) {
			if (!firstRoom) return Room.create({name: 'First'});
		})
}
<commit_msg>config file log<commit_after>// set globals
//global.log = require('./config/log');
global.log = require('./config/log');
global._ = require('lodash');
global.Promise = require('bluebird');

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;

String.prototype.toObjectId = function() {
	var ObjectId = mongoose.Types.ObjectId;
	return new ObjectId(this.toString());
};

// allows you to push multiple arrays onto another array
// ex:
// var foo = []
// foo.pushAll([1,2,3],[4,5,6])
Array.prototype.pushAll = function () {
	this.push.apply(this, this.concat.apply([], arguments));
};

var config = require('./config/config');
var app = Promise.promisifyAll(require('./config/express'));
var server = Promise.promisifyAll(require('http').Server(app));
var socketio = require('./config/socketio');

var User = require('./models/User');
var Room = require('./models/Room');

module.exports.run = function (cb) {

	log.info('server - Starting "' + config.environment + '"');

	connectToMongoose()
		.then(startup)
		.then(function () {
			socketio.connect(server);
			return server.listenAsync(config.express.port);
		})
		.then(function () {
			log.info('server - hosted - http://' + config.express.ip + ':' + config.express.port);
			log.info('config file', config);
		})
		.then(cb)
		.catch(function (error) {
			return log.error('server - Error while starting', error);
		});
};

function connectToMongoose() {
	return new Promise(function (resolve, reject) {
		var url = "mongodb://" + config.db.host + ":" + config.db.port + "/" + config.db.name;
		mongoose.connect(url);
		mongoose.connection.once('open', function (err) {
			if (err) return reject(err);
			log.info('mongoose ' + url);
			resolve();
		});
	});
}

function startup(){
	return Promise.join(
		User.update({}, {sockets: [], typingIn: null}, { multi: true }),
		ensureFirstRoom()
	)
}

function ensureFirstRoom() {
	return Room.findOne({name: 'First'})
		.then(function (firstRoom) {
			if (!firstRoom) return Room.create({name: 'First'});
		})
}
<|endoftext|>