<commit_before>// Set up a collection to contain article information. On the server,
// it is backed by a MongoDB collection named "articles".

Players = new Meteor.Collection("articles");

if (Meteor.isClient) {

 Meteor.startup(function () {
  Session.setDefault("voted", []);
  Session.set("vote_count", 0);
});

 voteInSession = function ( votingID ){
  var vTemp = Session.get("voted");

  var vCount = Session.get("vote_count");
  vCount++;
  Session.set("vote_count", vCount);

  console.log("WTF VOTES " + vTemp);

  if(vTemp.indexOf(votingID) >= 0){
    console.log("WTF ALREADY VOTED ");

  }else{
    vTemp.push(votingID);

  }

  Session.set("voted", vTemp);

}

Template.leaderboard.articles = function () {

  return Players.find({}, {sort: {real_score: -1, name: 1}});
};

Template.leaderboard.bestReal = function () {

};
Template.leaderboard.searchString = function () {
  return Session.get("searching");
}

Template.leaderboard.searchResults = function () {
  var s = Session.get("searching");
  if(s != null){

    return Players.find({long_url: s}, {sort: {long_url: -1}});

  }

}

Template.leaderboard.bestOfType = function () {

  if(Session.equals("selected_type", "real")){
    return Players.find({}, {sort: {real_score: -1, name: 1}});

  }

  if(Session.equals("selected_type", "onion")){
    return Players.find({}, {sort: {onion_score: -1, name: 1}});
  }

  return Players.find({}, {sort: {ts: -1}});

};

  getPlayer = function(id) {
    var p = Players.findOne({_id: id});
    if(p != null){
      console.log("p" + p);
    }else{
      console.error("NO P:" + id);
    }
    return p;
}

  getIsOnion = function(id) {
    var p = Players.findOne({_id: id});
    return (p.long_url.indexOf(".theonion.com") > -1);
}

Template.leaderboard.currentScoreVotes = function () {
  return Session.get("vote_count");
};

Template.leaderboard.currentScore = function () {
  var pTemp;
  var s = 0;
  if(Session.equals("selected_type", "real")){
     pTemp = Players.find({}, {sort: {real_score: -1, name: 1}});

  }else if(Session.equals("selected_type", "onion")){
     pTemp = Players.find({}, {sort: {onion_score: -1, name: 1}});
  }else{

   pTemp = Players.find({}, {sort: {ts: -1}});
  }
  pTemp.forEach(function(player){

    var isOnion = getIsOnion(player._id);
    var didVoteOnion = Session.equals("vote_" + player._id, "ONION");
    var didVoteReal = Session.equals("vote_" + player._id, "REAL");

    if(didVoteReal || didVoteOnion){
      //we did vote
      if(   (isOnion && didVoteOnion) || (!isOnion && didVoteReal)   ){
        s++;
      }
    }
  });

  return s;

};

Template.leaderboard.selected_name = function () {
  var article = Players.findOne(Session.get("selected_article"));
  return article && article.name;
};

Template.article.selected = function () {
  return Session.equals("selected_article", this._id) ? "selected" : '';
};

Template.article.voted = function (){
  if(Session.get("voted") == null) return false;

  return Session.get("voted").indexOf(this._id) >= 0;
};
Template.article.ts_ago = function (){
  return moment((this.ts * 1000)).fromNow()
};

Template.article.sessionVote = function (){
  return Session.get("vote_" + this._id)
};

Template.article.articleType = function (){
  if(this.long_url.indexOf(".theonion.com") >= 0)
    return "ONION"
  return "REAL"
};

Template.article.votedOnion = function (){
  return Session.equals("vote_" + this._id, "ONION")
};

Template.article.votedReal = function (){
  return Session.equals("vote_" + this._id, "REAL")
};

Template.article.votedRight = function (){
  return (Session.equals("vote_" + this._id, "ONION") && (this.long_url.indexOf(".theonion.com") >= 0)) || (Session.equals("vote_" + this._id, "REAL") && !(this.long_url.indexOf(".theonion.com") >= 0));
};

Template.article.votedWrong = function (){
  return (Session.equals("vote_" + this._id, "ONION") && !(this.long_url.indexOf(".theonion.com") >= 0)) || (Session.equals("vote_" + this._id, "REAL") && (this.long_url.indexOf(".theonion.com") >= 0));
};

Template.article.votedRightOnion = function (){
  return Session.equals("vote_" + this._id, "ONION") && (this.long_url.indexOf(".theonion.com") >= 0);
};

Template.article.votedRightReal = function (){
  return Session.equals("vote_" + this._id, "REAL") && !(this.long_url.indexOf(".theonion.com") >= 0);
};

Template.article.votedWrongOnion = function (){
  return Session.equals("vote_" + this._id, "ONION") && !(this.long_url.indexOf(".theonion.com") >= 0);
};

Template.article.votedWrongReal = function (){
  return Session.equals("vote_" + this._id, "REAL") && (this.long_url.indexOf(".theonion.com") >= 0);
};

Template.type_tabs.selectedOnion = function () {
  return Session.equals("selected_type", "onion") ? "selected" : '';
};

Template.type_tabs.selectedReal = function () {
  return Session.equals("selected_type", "real") ? "selected" : '';
};

Template.type_tabs.selectedLeader = function () {
  return Session.equals("selected_type", "leader") ? "selected" : '';
};

Template.leaderboard.events({
  'click input.inc-real': function () {
    Players.update(Session.get("selected_article"), {$inc: {real_score: 1}});
    voteInSession(this._id);
    Session.set("vote_" + this._id, "REAL")

  },
  'click input.inc-onion': function () {
    Players.update(Session.get("selected_article"), {$inc: {onion_score: 1}});
    voteInSession(this._id);
    Session.set("vote_" + this._id, "ONION")

  }
});

Template.type_tabs.events({
  'click input.tab_real': function () {
    Session.set("selected_type", "real");
  },
  'click input.tab_onion': function () {
    Session.set("selected_type", "onion");
  },
  'click input.tab_leader': function () {
    Session.set("selected_type", "leader");
  },
});

Template.article.shortlink

Template.article.events({
  'click .remove': function () {
    console.log(this + "\n oooooo \n " + this._id + this.short_url);
    Meteor.call('removeFromBundle', this._id, this.short_url);
    Players.remove
  },
    'click': function () {
    Session.set("selected_article", this._id);
  }
});
Template.new_article.events = {
  'click input.clear': function () {
        Session.set("searching", "");
        console.log(this);
        $('#new_article_name').val('');
  },
  'click input.add': function () {

    var new_article_name = document.getElementById("new_article_name").value;
    var desc = "a silly article";
    var longLink = new_article_name;
    console.log("making " + longLink);
    var title;

    Session.set("searching", longLink)
    //if we have any search results, don't do this

    Meteor.call('fetchFromService', longLink, function(err, respJson) {

      if(respJson != null){
      console.log("new_article_resp " + respJson);
      Session.set("searching", "");
    }else{
      console.error(err);
    }

    });

      //hit the endpoint here

    }
  };
}

// On server startup, create some articles if the database is empty.
if (Meteor.isServer) {

  var Bitly = Meteor.require("bitly-oauth");

  var dummyUser = 'wschornmeteor';

  var b = new Bitly(dummyUser, "throwaway1");

      b.bundleSync = Meteor._wrapAsync(b.bundle.contents);
     // b.getPreview = Meteor._wrapAsync(b.link.info);
     b.getPreviewHTML = Meteor._wrapAsync(b.link.content);
     b.getLinkInfo = Meteor._wrapAsync(b.info);

     b.addToBundle = Meteor._wrapAsync(b.bundle.link_add);
     b.removeFromBundle = Meteor._wrapAsync(b.bundle.link_remove);

  fetchQuizFromBundle =  function(bundleUrl) {
    var newQuiz = {}
      // _wrapAsync is undocumented, but I freaking love it. Any of the bitly-oauth methods can be wrapped this way.

     try {
      var result = b.bundleSync({bundle_link: bundleUrl});

    }
    catch(e) {
      console.error("fetch error: " + e);
    }

    newMysterys = [];

    var links = result.data.bundle.links;
    var previewHTML = "";
    for (var i = 0; i < links.length; i++){
      insertFromLink(links[i]);

    }

    for(var myLink in result.data.bundle.links){
      curr = result.data.bundle.links[myLink];
      ng = {"title": "funny story #" + "" + Math.floor((Math.random() * 100) + 1), "description": "a funny thing happened"};

      newMysterys.push(ng);
    }
    var rdb = result.data.bundle;
      //currently the user photo is stored in the description. this is janky, eventually we should perhaps pull the first link in the bundle?
      newQuiz = {user: rdb.bundle_owner, name: rdb.title, userPhoto: rdb.description, Mysterys: newMysterys, ts_modified: rdb.last_modified_ts};
      return newQuiz;
    };

    insertFromLink = function (linkObject) {
      console.log("inserting: " + JSON.stringify(linkObject));

      try {
        var previewHTML;
        var preview = b.getPreviewHTML({"link": linkObject.link});

        if(preview.status_code == 200){
          previewHTML = preview.data.content;
        }else{
          console.error("preview error: " + JSON.stringify(linkObject) + "\n gives \n" + preview.status_txt);
        }

       // console.log("\n HTML" + previewHTML);

      }
      catch(e){
        console.error("preview2 error: " + e);
      }

      var ts_info;
      try {
       var ts;

        var ts_data = b.getLinkInfo({"shortUrl": linkObject.link});
        var temp = JSON.stringify(ts_data);
        console.log("link info data for call: " + JSON.stringify(linkObject) + " was " + temp);
        if(ts_data.status_code == 200){
        ts_info = ts_data.data.info[0];
        console.log("link info data ii " + ts_info);

        ts = ts_info.created_at;
        var title = ts_info.title;
        if(title == null){
          title = "Untitled Story Happens";
        }
         title = title.replace("| The Onion - America's Finest News Source","");

    }

      }
      catch(e){
        console.error("link info error: " + e);
      }

      var newArticleObj = {"title": title, "real_score": 0, "onion_score": 0, "previewHTML": previewHTML, "ts": ts, long_url: linkObject.long_url, short_url: linkObject.link};
      console.log(newArticleObj);
      Players.insert(newArticleObj);
    }

    Meteor.startup(function () {

      var b1 = "https://bitly.com/bundles/wschornmeteor/1"

      Meteor.methods({

        refreshFromBundle: function () {
          Players.remove({});
          fetchQuizFromBundle();
        },

        bar: function () {

        // QUESTION: HOW TO CALL Meteor.methods.foo
        return 1 + foo;

      },
      removeFromBundle: function(id, shortlink) {

        var result = b.removeFromBundle({"bundle_link": b1, link: shortlink});
        console.log("INPUT: " + b1 + " " + shortlink);
        console.log(JSON.stringify(result));
        Players.remove({_id: id});

      },
      fetchFromService: function(longLink) {
        //var url = "http://api-ssl.bitly.com/v3/bundle/link_add?bundle_link=http%3A%2F%2Fbitly.com%2Fbundles%2Fjennyyin%2F5&access_token=a97cd736e88d60e46cc10eb0edd154fda1675b02&link=" + longLink;
        //synchronous GET

        var result = b.addToBundle({"link": longLink, "bundle_link": b1});

          if(result.status_code == 200){
            var newLink = result.data.bundle.links.pop().link;
            insertFromLink({link: newLink, long_url: longLink});
            console.log("Should be showing newly inserted link");
          }else{

            console.error("fetchFromService error: " + JSON.stringify(result));
            return error;
          }

      }
    });

    if (Players.find().count() < 20){
      Players.remove({});
    this.fetchQuizFromBundle(b1);

    }
  });

}
<commit_msg>change bundle<commit_after>// Set up a collection to contain article information. On the server,
// it is backed by a MongoDB collection named "articles".

Players = new Meteor.Collection("articles");

if (Meteor.isClient) {

 Meteor.startup(function () {
  Session.setDefault("voted", []);
  Session.set("vote_count", 0);
});

 voteInSession = function ( votingID ){
  var vTemp = Session.get("voted");

  var vCount = Session.get("vote_count");
  vCount++;
  Session.set("vote_count", vCount);

  console.log("WTF VOTES " + vTemp);

  if(vTemp.indexOf(votingID) >= 0){
    console.log("WTF ALREADY VOTED ");

  }else{
    vTemp.push(votingID);

  }

  Session.set("voted", vTemp);

}

Template.leaderboard.articles = function () {

  return Players.find({}, {sort: {real_score: -1, name: 1}});
};

Template.leaderboard.bestReal = function () {

};
Template.leaderboard.searchString = function () {
  return Session.get("searching");
}

Template.leaderboard.searchResults = function () {
  var s = Session.get("searching");
  if(s != null){

    return Players.find({long_url: s}, {sort: {long_url: -1}});

  }

}

Template.leaderboard.bestOfType = function () {

  if(Session.equals("selected_type", "real")){
    return Players.find({}, {sort: {real_score: -1, name: 1}});

  }

  if(Session.equals("selected_type", "onion")){
    return Players.find({}, {sort: {onion_score: -1, name: 1}});
  }

  return Players.find({}, {sort: {ts: -1}});

};

  getPlayer = function(id) {
    var p = Players.findOne({_id: id});
    if(p != null){
      console.log("p" + p);
    }else{
      console.error("NO P:" + id);
    }
    return p;
}

  getIsOnion = function(id) {
    var p = Players.findOne({_id: id});
    return (p.long_url.indexOf(".theonion.com") > -1);
}

Template.leaderboard.currentScoreVotes = function () {
  return Session.get("vote_count");
};

Template.leaderboard.currentScore = function () {
  var pTemp;
  var s = 0;
  if(Session.equals("selected_type", "real")){
     pTemp = Players.find({}, {sort: {real_score: -1, name: 1}});

  }else if(Session.equals("selected_type", "onion")){
     pTemp = Players.find({}, {sort: {onion_score: -1, name: 1}});
  }else{

   pTemp = Players.find({}, {sort: {ts: -1}});
  }
  pTemp.forEach(function(player){

    var isOnion = getIsOnion(player._id);
    var didVoteOnion = Session.equals("vote_" + player._id, "ONION");
    var didVoteReal = Session.equals("vote_" + player._id, "REAL");

    if(didVoteReal || didVoteOnion){
      //we did vote
      if(   (isOnion && didVoteOnion) || (!isOnion && didVoteReal)   ){
        s++;
      }
    }
  });

  return s;

};

Template.leaderboard.selected_name = function () {
  var article = Players.findOne(Session.get("selected_article"));
  return article && article.name;
};

Template.article.selected = function () {
  return Session.equals("selected_article", this._id) ? "selected" : '';
};

Template.article.voted = function (){
  if(Session.get("voted") == null) return false;

  return Session.get("voted").indexOf(this._id) >= 0;
};
Template.article.ts_ago = function (){
  return moment((this.ts * 1000)).fromNow()
};

Template.article.sessionVote = function (){
  return Session.get("vote_" + this._id)
};

Template.article.articleType = function (){
  if(this.long_url.indexOf(".theonion.com") >= 0)
    return "ONION"
  return "REAL"
};

Template.article.votedOnion = function (){
  return Session.equals("vote_" + this._id, "ONION")
};

Template.article.votedReal = function (){
  return Session.equals("vote_" + this._id, "REAL")
};

Template.article.votedRight = function (){
  return (Session.equals("vote_" + this._id, "ONION") && (this.long_url.indexOf(".theonion.com") >= 0)) || (Session.equals("vote_" + this._id, "REAL") && !(this.long_url.indexOf(".theonion.com") >= 0));
};

Template.article.votedWrong = function (){
  return (Session.equals("vote_" + this._id, "ONION") && !(this.long_url.indexOf(".theonion.com") >= 0)) || (Session.equals("vote_" + this._id, "REAL") && (this.long_url.indexOf(".theonion.com") >= 0));
};

Template.article.votedRightOnion = function (){
  return Session.equals("vote_" + this._id, "ONION") && (this.long_url.indexOf(".theonion.com") >= 0);
};

Template.article.votedRightReal = function (){
  return Session.equals("vote_" + this._id, "REAL") && !(this.long_url.indexOf(".theonion.com") >= 0);
};

Template.article.votedWrongOnion = function (){
  return Session.equals("vote_" + this._id, "ONION") && !(this.long_url.indexOf(".theonion.com") >= 0);
};

Template.article.votedWrongReal = function (){
  return Session.equals("vote_" + this._id, "REAL") && (this.long_url.indexOf(".theonion.com") >= 0);
};

Template.type_tabs.selectedOnion = function () {
  return Session.equals("selected_type", "onion") ? "selected" : '';
};

Template.type_tabs.selectedReal = function () {
  return Session.equals("selected_type", "real") ? "selected" : '';
};

Template.type_tabs.selectedLeader = function () {
  return Session.equals("selected_type", "leader") ? "selected" : '';
};

Template.leaderboard.events({
  'click input.inc-real': function () {
    Players.update(Session.get("selected_article"), {$inc: {real_score: 1}});
    voteInSession(this._id);
    Session.set("vote_" + this._id, "REAL")

  },
  'click input.inc-onion': function () {
    Players.update(Session.get("selected_article"), {$inc: {onion_score: 1}});
    voteInSession(this._id);
    Session.set("vote_" + this._id, "ONION")

  }
});

Template.type_tabs.events({
  'click input.tab_real': function () {
    Session.set("selected_type", "real");
  },
  'click input.tab_onion': function () {
    Session.set("selected_type", "onion");
  },
  'click input.tab_leader': function () {
    Session.set("selected_type", "leader");
  },
});

Template.article.shortlink

Template.article.events({
  'click .remove': function () {
    console.log(this + "\n oooooo \n " + this._id + this.short_url);
    Meteor.call('removeFromBundle', this._id, this.short_url);
    Players.remove
  },
    'click': function () {
    Session.set("selected_article", this._id);
  }
});
Template.new_article.events = {
  'click input.clear': function () {
        Session.set("searching", "");
        console.log(this);
        $('#new_article_name').val('');
  },
  'click input.add': function () {

    var new_article_name = document.getElementById("new_article_name").value;
    var desc = "a silly article";
    var longLink = new_article_name;
    console.log("making " + longLink);
    var title;

    Session.set("searching", longLink)
    //if we have any search results, don't do this

    Meteor.call('fetchFromService', longLink, function(err, respJson) {

      if(respJson != null){
      console.log("new_article_resp " + respJson);
      Session.set("searching", "");
    }else{
      console.error(err);
    }

    });

      //hit the endpoint here

    }
  };
}

// On server startup, create some articles if the database is empty.
if (Meteor.isServer) {

  var Bitly = Meteor.require("bitly-oauth");

  var dummyUser = 'wschornmeteor';

  var b = new Bitly(dummyUser, "throwaway1");

      b.bundleSync = Meteor._wrapAsync(b.bundle.contents);
     // b.getPreview = Meteor._wrapAsync(b.link.info);
     b.getPreviewHTML = Meteor._wrapAsync(b.link.content);
     b.getLinkInfo = Meteor._wrapAsync(b.info);

     b.addToBundle = Meteor._wrapAsync(b.bundle.link_add);
     b.removeFromBundle = Meteor._wrapAsync(b.bundle.link_remove);

  fetchQuizFromBundle =  function(bundleUrl) {
    var newQuiz = {}
      // _wrapAsync is undocumented, but I freaking love it. Any of the bitly-oauth methods can be wrapped this way.

     try {
      var result = b.bundleSync({bundle_link: bundleUrl});

    }
    catch(e) {
      console.error("fetch error: " + e);
    }

    newMysterys = [];

    var links = result.data.bundle.links;
    var previewHTML = "";
    for (var i = 0; i < links.length; i++){
      insertFromLink(links[i]);

    }

    for(var myLink in result.data.bundle.links){
      curr = result.data.bundle.links[myLink];
      ng = {"title": "funny story #" + "" + Math.floor((Math.random() * 100) + 1), "description": "a funny thing happened"};

      newMysterys.push(ng);
    }
    var rdb = result.data.bundle;
      //currently the user photo is stored in the description. this is janky, eventually we should perhaps pull the first link in the bundle?
      newQuiz = {user: rdb.bundle_owner, name: rdb.title, userPhoto: rdb.description, Mysterys: newMysterys, ts_modified: rdb.last_modified_ts};
      return newQuiz;
    };

    insertFromLink = function (linkObject) {
      console.log("inserting: " + JSON.stringify(linkObject));

      try {
        var previewHTML;
        var preview = b.getPreviewHTML({"link": linkObject.link});

        if(preview.status_code == 200){
          previewHTML = preview.data.content;
        }else{
          console.error("preview error: " + JSON.stringify(linkObject) + "\n gives \n" + preview.status_txt);
        }

       // console.log("\n HTML" + previewHTML);

      }
      catch(e){
        console.error("preview2 error: " + e);
      }

      var ts_info;
      try {
       var ts;

        var ts_data = b.getLinkInfo({"shortUrl": linkObject.link});
        var temp = JSON.stringify(ts_data);
        console.log("link info data for call: " + JSON.stringify(linkObject) + " was " + temp);
        if(ts_data.status_code == 200){
        ts_info = ts_data.data.info[0];
        console.log("link info data ii " + ts_info);

        ts = ts_info.created_at;
        var title = ts_info.title;
        if(title == null){
          title = "Untitled Story Happens";
        }
         title = title.replace("| The Onion - America's Finest News Source","");

    }

      }
      catch(e){
        console.error("link info error: " + e);
      }

      var newArticleObj = {"title": title, "real_score": 0, "onion_score": 0, "previewHTML": previewHTML, "ts": ts, long_url: linkObject.long_url, short_url: linkObject.link};
      console.log(newArticleObj);
      Players.insert(newArticleObj);
    }

    Meteor.startup(function () {

      var b1 = "https://bitly.com/bundles/wschornmeteor/3"

      Meteor.methods({

        refreshFromBundle: function () {
          Players.remove({});
          fetchQuizFromBundle();
        },

        bar: function () {

        // QUESTION: HOW TO CALL Meteor.methods.foo
        return 1 + foo;

      },
      removeFromBundle: function(id, shortlink) {

        var result = b.removeFromBundle({"bundle_link": b1, link: shortlink});
        console.log("INPUT: " + b1 + " " + shortlink);
        console.log(JSON.stringify(result));
        Players.remove({_id: id});

      },
      fetchFromService: function(longLink) {
        //var url = "http://api-ssl.bitly.com/v3/bundle/link_add?bundle_link=http%3A%2F%2Fbitly.com%2Fbundles%2Fjennyyin%2F5&access_token=a97cd736e88d60e46cc10eb0edd154fda1675b02&link=" + longLink;
        //synchronous GET

        var result = b.addToBundle({"link": longLink, "bundle_link": b1});

          if(result.status_code == 200){
            var newLink = result.data.bundle.links.pop().link;
            insertFromLink({link: newLink, long_url: longLink});
            console.log("Should be showing newly inserted link");
          }else{

            console.error("fetchFromService error: " + JSON.stringify(result));
            return error;
          }

      }
    });

    if (Players.find().count() < 20){
      Players.remove({});
    this.fetchQuizFromBundle(b1);

    }
  });

}
<|endoftext|>


<commit_before>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.021'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var i = 0;
var IdleStatus = 0;
var incoming_ONG = 0;
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var NinjaAutoClickStatus = 1;
var RKAutoClickStatus = 0;
var RKAlertFrequency = 8;
var Time_to_ONG = 1800000;
var RKType = 'abc123';

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function RedundaKitty() {
	i = Molpy.redactedToggle - Molpy.redactedCountup;

	if (Molpy.redactedVisible > 0) {
		//Border CSS change works on RK and LC.
		$('#redacteditem').css("border","2px solid red");
		$('#redacteditem').filter(":button" ).css("border","2px solid blue");
		//Clicks if RedundaKitty AutoClicker Enabled and Not a Logicat
		if (RKAutoClickStatus == 1 && Molpy.redactedPuzzleTarget == undefined) {
			Molpy.ClickRedacted();
			//$(":button").click();
		}
		//else if (LCAutoClickStatus == 1 && Molpy.redactedPuzzleTarget != undefined) {
			//Logicat();
		//}
		else {
			//Redundakitty Notifications (Title Bar and Audio)
			document.title = "! kitten !";
			if (Math.floor(i % RKAlertFrequency) == 0 && (AudioAlertsStatus == 1 || AudioAlertsStatus == 3)) {
				audio_Bell.play();
			}
		}
	}
	else {
		document.title = Molpy.redactedToggle-Molpy.redactedCountup;
		if (i != 0) { i = 0; }
	}
}

function Logicat() {
	i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);
	Molpy.redactedPuzzleTarget = undefined;

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 1) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'RKAutoClick' || option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error',1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only';}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG';}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status,1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1)

//Main Loop
setInterval(function() {
	//Molpy.Notify(Molpy.redactedToggle, 0);
	Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
    RedundaKitty();
    Ninja();
}, 1800);
<commit_msg>Continuing testing RK vs LC<commit_after>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.021'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var i = 0;
var IdleStatus = 0;
var incoming_ONG = 0;
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var NinjaAutoClickStatus = 1;
var RKAutoClickStatus = 0;
var RKAlertFrequency = 8;
var Time_to_ONG = 1800000;
var RKType = 'abc123';

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function RedundaKitty() {
	i = Molpy.redactedToggle - Molpy.redactedCountup;

	if (Molpy.redactedVisible > 0) {
		//Border CSS change works on RK and LC.
		g(redacteditem).css("border","2px solid red");
		//var content = $('#redacteditem').innerHTML;
		//Clicks if RedundaKitty AutoClicker Enabled and Not a Logicat
		if (RKAutoClickStatus == 1 && Molpy.redactedPuzzleTarget == undefined) {
			Molpy.ClickRedacted();
			//$(":button").click();
		}
		//else if (LCAutoClickStatus == 1 && Molpy.redactedPuzzleTarget != undefined) {
			//Logicat();
		//}
		else {
			//Redundakitty Notifications (Title Bar and Audio)
			document.title = "! kitten !";
			if (Math.floor(i % RKAlertFrequency) == 0 && (AudioAlertsStatus == 1 || AudioAlertsStatus == 3)) {
				audio_Bell.play();
			}
		}
	}
	else {
		document.title = Molpy.redactedToggle-Molpy.redactedCountup;
		if (i != 0) { i = 0; }
	}
}

function Logicat() {
	i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);
	Molpy.redactedPuzzleTarget = undefined;

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 1) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'RKAutoClick' || option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error',1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only';}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG';}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status,1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1)

//Main Loop
setInterval(function() {
	//Molpy.Notify(Molpy.redactedToggle, 0);
	Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
    RedundaKitty();
    Ninja();
}, 1800);
<|endoftext|>


<commit_before>import React from 'react';
import './NodePanelHeader.css';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { setNodeLag, setNodeProbability } from '../../actions/Nodes';
import Knob from '../UI/Knob';

class NodePanelHeader extends React.Component {
  constructor(props) {
    super(props);
    this.onLagChange = this.onLagChange.bind(this);
    this.onProbabilityChange = this.onProbabilityChange.bind(this);
  }

  onLagChange(value) {
    this.props.setNodeLag(this.props.node.id, value);
  }

  onProbabilityChange(value) {
    this.props.setNodeProbability(this.props.node.id, value);
  }

  render() {
    return (

        <Knob
          label={'Lag'}
          value={this.props.node.lag}
          min={0}
          max={5000}
          onChange={this.onLagChange}
          disabled={this.props.node.disabled}
          type={this.props.node.type}/>
        <Knob
          label={'Probability'}
          value={this.props.node.probability}
          min={0}
          max={1}
          onChange={this.onProbabilityChange}
          disabled={this.props.node.disabled}
          type={this.props.node.type}/>

    );
  }
}

const mapStateToProps = (state) => {
  return {
    nodes: state.nodes
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    setNodeLag: bindActionCreators(setNodeLag, dispatch),
    setNodeProbability: bindActionCreators(setNodeProbability, dispatch)
  };
};

module.exports = connect(mapStateToProps, mapDispatchToProps)(NodePanelHeader);
<commit_msg>Multi-edit node panel header.<commit_after>import React from 'react';
import './NodePanelHeader.css';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { setNodeLag, setNodeProbability } from '../../actions/Nodes';
import Knob from '../UI/Knob';

class NodePanelHeader extends React.Component {
  constructor(props) {
    super(props);
    this.onLagChange = this.onLagChange.bind(this);
    this.onProbabilityChange = this.onProbabilityChange.bind(this);
    this.nodes = [];
    this.props.nodes.forEach((node) => {
      if (node.selected) {
        this.nodes.push(node);
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    this.nodes = [];
    nextProps.nodes.forEach((node) => {
      if (node.selected) {
        this.nodes.push(node);
      }
    });
  }

  onLagChange(value) {
    this.nodes.forEach((node) => {
      this.props.setNodeLag(node.id, value);
    });
  }

  onProbabilityChange(value) {
    this.nodes.forEach((node) => {
      this.props.setNodeProbability(node.id, value);
    });
  }

  render() {
    return (

        <Knob
          label={'Lag'}
          value={this.nodes[0].lag}
          min={0}
          max={5000}
          onChange={this.onLagChange}
          disabled={this.nodes[0].disabled}
          type={this.nodes[0].type}/>
        <Knob
          label={'Probability'}
          value={this.nodes[0].probability}
          min={0}
          max={1}
          onChange={this.onProbabilityChange}
          disabled={this.nodes[0].disabled}
          type={this.nodes[0].type}/>

    );
  }
}

const mapStateToProps = (state) => {
  return {
    nodes: state.nodes
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    setNodeLag: bindActionCreators(setNodeLag, dispatch),
    setNodeProbability: bindActionCreators(setNodeProbability, dispatch)
  };
};

module.exports = connect(mapStateToProps, mapDispatchToProps)(NodePanelHeader);
<|endoftext|>


<commit_before>(function(module) {
    module.directive('detailTabs', detailTabsDirective);
    function detailTabsDirective() {
        return {
            restrict: 'E',
            scope: {
                item: '='
            },
            controller: 'DetailTabsDirectiveController',
            controllerAs: 'ctrl',
            bindToController: true,
            templateUrl: 'application/directives/partials/detail-tabs.html'
        };
    }

    module.controller('DetailTabsDirectiveController', DetailTabsDirectiveController);
    DetailTabsDirectiveController.$inject = [];
    function DetailTabsDirectiveController() {
        var ctrl = this;
        ctrl.tabs = loadTabs();
        ctrl.activeTab = ctrl.tabs[0].name;
        ctrl.setActive = setActive;
        ctrl.isActive = isActive;

        //////////////////

        function setActive(tab) {
            ctrl.activeTab = tab;
        }

        function isActive(tab) {
            return ctrl.activeTab === tab;
        }

        function loadTabs() {
            var tabs = [];

            if ('notes' in ctrl.item && ctrl.item.notes.length) {
                tabs.push(newTab('notes', 'fa-sticky-note', ctrl.item.notes.length));
            }

            if ('reviews' in ctrl.item && ctrl.item.reviews.length) {
                tabs.push(newTab('reviews', 'fa-comment', ctrl.item.reviews.length));
            }

            if ('processes' in ctrl.item && ctrl.item.processes.length) {
                tabs.push(newTab('processes', 'fa-code-fork', ctrl.item.processes.length));
            }

            if ('files' in ctrl.item && ctrl.item.files.length) {
                tabs.push(newTab('files', 'fa-files-o', ctrl.item.files.length));
            }

            if ('samples' in ctrl.item && ctrl.item.samples.length) {
                tabs.push(newTab('samples', 'fa-cubes', ctrl.item.samples.length));
            }

            if ('measurements' in ctrl.item && ctrl.item.measurements.length) {
                tabs.push(newTab('measurements', 'fa-flask', ctrl.item.measurements.length));
            } else if ('property_sets' in ctrl.item && ctrl.item.property_sets.length) {
                tabs.push(newTab('measurements', 'fa-flask', ctrl.item.property_sets.length));
            }

            if ('setup' in ctrl.item && ctrl.item.setup[0].properties.length) {
                tabs.push(newTab('setup', 'fa-cogs', ctrl.item.setup[0].properties.length));
            }

            tabs.sort(function compareByName(t1, t2) {
                if (t1.name < t2.name) {
                    return -1;
                }
                if (t1.name > t2.name) {
                    return 1;
                }
                return 0;
            });

            return tabs;
        }

        function newTab(name, icon, count) {
            return {
                name: name,
                icon: icon,
                count: count
            };
        }
    }
}(angular.module('materialscommons')));<commit_msg>Handle case where there are no tabs.<commit_after>(function(module) {
    module.directive('detailTabs', detailTabsDirective);
    function detailTabsDirective() {
        return {
            restrict: 'E',
            scope: {
                item: '='
            },
            controller: 'DetailTabsDirectiveController',
            controllerAs: 'ctrl',
            bindToController: true,
            templateUrl: 'application/directives/partials/detail-tabs.html'
        };
    }

    module.controller('DetailTabsDirectiveController', DetailTabsDirectiveController);
    DetailTabsDirectiveController.$inject = [];
    function DetailTabsDirectiveController() {
        var ctrl = this;
        ctrl.tabs = loadTabs();
        ctrl.activeTab = ctrl.tabs.length ? ctrl.tabs[0].name : '';
        ctrl.setActive = setActive;
        ctrl.isActive = isActive;

        //////////////////

        function setActive(tab) {
            ctrl.activeTab = tab;
        }

        function isActive(tab) {
            return ctrl.activeTab === tab;
        }

        function loadTabs() {
            var tabs = [];

            if ('notes' in ctrl.item && ctrl.item.notes.length) {
                tabs.push(newTab('notes', 'fa-sticky-note', ctrl.item.notes.length));
            }

            if ('reviews' in ctrl.item && ctrl.item.reviews.length) {
                tabs.push(newTab('reviews', 'fa-comment', ctrl.item.reviews.length));
            }

            if ('processes' in ctrl.item && ctrl.item.processes.length) {
                tabs.push(newTab('processes', 'fa-code-fork', ctrl.item.processes.length));
            }

            if ('files' in ctrl.item && ctrl.item.files.length) {
                tabs.push(newTab('files', 'fa-files-o', ctrl.item.files.length));
            }

            if ('samples' in ctrl.item && ctrl.item.samples.length) {
                tabs.push(newTab('samples', 'fa-cubes', ctrl.item.samples.length));
            }

            if ('measurements' in ctrl.item && ctrl.item.measurements.length) {
                tabs.push(newTab('measurements', 'fa-flask', ctrl.item.measurements.length));
            } else if ('property_sets' in ctrl.item && ctrl.item.property_sets.length) {
                tabs.push(newTab('measurements', 'fa-flask', ctrl.item.property_sets.length));
            }

            if ('setup' in ctrl.item && ctrl.item.setup[0].properties.length) {
                tabs.push(newTab('setup', 'fa-cogs', ctrl.item.setup[0].properties.length));
            }

            tabs.sort(function compareByName(t1, t2) {
                if (t1.name < t2.name) {
                    return -1;
                }
                if (t1.name > t2.name) {
                    return 1;
                }
                return 0;
            });

            return tabs;
        }

        function newTab(name, icon, count) {
            return {
                name: name,
                icon: icon,
                count: count
            };
        }
    }
}(angular.module('materialscommons')));<|endoftext|>


<commit_before>/**
 * Created by Alexey Merzlikin on 08.04.2017.
 */

function DataCollector() {
    this.dataEntities = [];
}

DataCollector.prototype.addEntity = function (entity) {
    this.dataEntities.push(entity);
};

function DataEntity() {
    this.jsonPoints = [];
    this.jsonParams = {};
}

DataEntity.prototype.setPoints = function (data) {
    this.jsonPoints = data;
};

DataEntity.prototype.setParams = function (data) {
    this.jsonParams = Object.assign(this.jsonParams, data);
};

DataCollector.prototype.getJSON = function () {
    var json = JSON.stringify(this);
    // alert(window.thisTask.getSolution());
    window.thisTask.setSolutionOutputValue("result", json);
    // alert(window.thisTask.getSolution());
    // alert(window.thisTask.validate(window.thisTask.getSolution()) + " valid");

    return json;
};
<commit_msg>LT-195 Renamed jsonParams and jsonPoints to parameters and points<commit_after>/**
 * Created by Alexey Merzlikin on 08.04.2017.
 */

function DataCollector() {
    this.dataEntities = [];
}

DataCollector.prototype.addEntity = function (entity) {
    this.dataEntities.push(entity);
};

function DataEntity() {
    this.points = [];
    this.parameters = {};
}

DataEntity.prototype.setPoints = function (data) {
    this.points = data;
};

DataEntity.prototype.setParams = function (data) {
    this.parameters = Object.assign(this.parameters, data);
};

DataCollector.prototype.getJSON = function () {
    var json = JSON.stringify(this);
    window.thisTask.setSolutionOutputValue("result", json);
    return json;
};
<|endoftext|>


<commit_before>import config from 'config';

export function addTrailingSlash(url) {
  if (url.match(/^https?\:\/\/[\w-.]+$/)) {
    url += '/';
  }
  return url;
}

export function capitalize(str) {
  return str.length ? str[0].toUpperCase() + str.slice(1) : '';
}

export function fixMalformedUrls(url) {
  if (!url.match(/^https?:\/\//)) {
    const malformed = url.match(/^([https]+)?[:/]{1,3}/i);
    url = `http://${url.substr(malformed ? malformed[0].length : 0)}`;
  }
  return url;
}

export function isMS() {
  if (/(MSIE|Edge|rv:11)/i.test(navigator.userAgent)) {
    return true;
  }

  return false;
}

export function isSafari() {
  return navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') === -1;
}

export function passwordPassRegex(password) {
  if(!password) return false;

  const rgx = password.match(config.passwordRegex);
  return rgx && rgx[0] === password;
}

export function remoteBrowserMod(rb, ts, sep) {
  let base = ts || '';
  if (rb) {
    base += `$br:${rb}`;
  }
  if (base && sep) {
    base += sep;
  }
  return base;
}

/**
 * Remove trailing slash
 * @param  {string} val url to modify
 * @return {string}     url without trailing slash
 */
export function rts(val) {
  return val.replace(/\/$/, '');
}

export function setTitle(msg, url, title) {
  if (!title) {
    title = url;
  }

  document.title = `${title} (${msg})`;
}

/**
 * Remove http/https from urls
 * @param  {string} val url to modify
 * @return {string}     url without protocol
 */
export function stripProtocol(url) {
  return url.replace(/https?:\/\//i, '');
}

export function truncate(str, length) {
  return str.length > length ? `${str.substr(0, length).trim()}...` : str;
}
<commit_msg>Test for undefined in helper functions<commit_after>import config from 'config';

export function addTrailingSlash(url) {
  if (url.match(/^https?\:\/\/[\w-.]+$/)) {
    url += '/';
  }
  return url;
}

export function capitalize(str) {
  if (!str) {
    return str;
  }

  return str.length ? str[0].toUpperCase() + str.slice(1) : '';
}

export function fixMalformedUrls(url) {
  if (!url.match(/^https?:\/\//)) {
    const malformed = url.match(/^([https]+)?[:/]{1,3}/i);
    url = `http://${url.substr(malformed ? malformed[0].length : 0)}`;
  }
  return url;
}

export function isMS() {
  if (/(MSIE|Edge|rv:11)/i.test(navigator.userAgent)) {
    return true;
  }

  return false;
}

export function isSafari() {
  return navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') === -1;
}

export function passwordPassRegex(password) {
  if(!password) return false;

  const rgx = password.match(config.passwordRegex);
  return rgx && rgx[0] === password;
}

export function remoteBrowserMod(rb, ts, sep) {
  let base = ts || '';
  if (rb) {
    base += `$br:${rb}`;
  }
  if (base && sep) {
    base += sep;
  }
  return base;
}

/**
 * Remove trailing slash
 * @param  {string} val url to modify
 * @return {string}     url without trailing slash
 */
export function rts(val) {
  return val.replace(/\/$/, '');
}

export function setTitle(msg, url, title) {
  if (!title) {
    title = url;
  }

  document.title = `${title} (${msg})`;
}

/**
 * Remove http/https from urls
 * @param  {string} val url to modify
 * @return {string}     url without protocol
 */
export function stripProtocol(url) {
  return url.replace(/https?:\/\//i, '');
}

export function truncate(str, length) {
  if (!str) {
    return str;
  }

  return str.length > length ? `${str.substr(0, length).trim()}...` : str;
}
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

// ********************************************************************************************* //

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cm = Components.manager;

Cm.QueryInterface(Ci.nsIComponentRegistrar);

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");

const MY_URL = "resource://ccdump/";

// ********************************************************************************************* //
// Bootstrap API

var global = this;

function startup(aData, aReason)
{
    var resource = Services.io.getProtocolHandler("resource").
        QueryInterface(Ci.nsIResProtocolHandler);

    resource.setSubstitution("ccdump", aData.resourceURI);
    Cm.registerFactory(AboutCC.prototype.classID,
        AboutCC.prototype.classDescription,
        AboutCC.prototype.contractID,
        AboutCCFactory);
}

function shutdown(aData, aReason)
{
    if (aReason == APP_SHUTDOWN)
        return;

    var resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
    resource.setSubstitution("ccdump", null);
    Cm.unregisterFactory(AboutCC.prototype.classID, AboutCCFactory);
}

function install(aData, aReason)
{
    // xxxHonza: open about:ccdump for the first time?
}

function uninstall(aData, aReason)
{
}

// ********************************************************************************************* //
// about:ccdump

function AboutCC()
{
}

AboutCC.prototype =
{
    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
    classDescription: "about:ccdump",
    classID: Components.ID("{D5889F72-0F01-4aee-9B88-FEACC5038C34}"),
    contractID: "@mozilla.org/network/protocol/about;1?what=ccdump",

    newChannel: function(uri)
    {
        // The module loader is synchronous so, make sure that the

        // is defined before main.js is included. This element represents the entire
        // application UI
        var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
        var html = 'data:text/html,<!DOCTYPE html>\n'
            + '<link href="' + MY_URL + 'skin/classic/main.css" rel="stylesheet" type="text/css">\n'
            + '\n'
            + '\n'
            + "

\n"
            + '\n'
            + "\n";

        var securityManager = Cc["@mozilla.org/scriptsecuritymanager;1"].
            getService(Ci.nsIScriptSecurityManager);

        var principal = securityManager.getSystemPrincipal();
        var channel = ioService.newChannel(html, null, null);
        channel.originalURI = uri;
        channel.owner = principal;

        return channel;
    },

    getURIFlags: function(uri)
    {
        return Ci.nsIAboutModule.ALLOW_SCRIPT;
    }
}

const AboutCCFactory = XPCOMUtils.generateNSGetFactory([AboutCC])(AboutCC.prototype.classID);

// ********************************************************************************************* //
<commit_msg>Avoid warning about not specified encoding<commit_after>/* See license.txt for terms of usage */

// ********************************************************************************************* //

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cm = Components.manager;

Cm.QueryInterface(Ci.nsIComponentRegistrar);

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");

const MY_URL = "resource://ccdump/";

// ********************************************************************************************* //
// Bootstrap API

var global = this;

function startup(aData, aReason)
{
    var resource = Services.io.getProtocolHandler("resource").
        QueryInterface(Ci.nsIResProtocolHandler);

    resource.setSubstitution("ccdump", aData.resourceURI);
    Cm.registerFactory(AboutCC.prototype.classID,
        AboutCC.prototype.classDescription,
        AboutCC.prototype.contractID,
        AboutCCFactory);
}

function shutdown(aData, aReason)
{
    if (aReason == APP_SHUTDOWN)
        return;

    var resource = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
    resource.setSubstitution("ccdump", null);
    Cm.unregisterFactory(AboutCC.prototype.classID, AboutCCFactory);
}

function install(aData, aReason)
{
    // xxxHonza: open about:ccdump for the first time?
}

function uninstall(aData, aReason)
{
}

// ********************************************************************************************* //
// about:ccdump

function AboutCC()
{
}

AboutCC.prototype =
{
    QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
    classDescription: "about:ccdump",
    classID: Components.ID("{D5889F72-0F01-4aee-9B88-FEACC5038C34}"),
    contractID: "@mozilla.org/network/protocol/about;1?what=ccdump",

    newChannel: function(uri)
    {
        // The module loader is synchronous so, make sure that the

        // is defined before main.js is included. This element represents the entire
        // application UI
        var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
        var html = 'data:text/html,<!DOCTYPE html>\n'
            + '<link href="' + MY_URL + 'skin/classic/main.css" rel="stylesheet" type="text/css">\n'
            + '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n'
            + '\n'
            + '\n'
            + "

\n"
            + '\n'
            + "\n";

        var securityManager = Cc["@mozilla.org/scriptsecuritymanager;1"].
            getService(Ci.nsIScriptSecurityManager);

        var principal = securityManager.getSystemPrincipal();
        var channel = ioService.newChannel(html, null, null);
        channel.originalURI = uri;
        channel.owner = principal;

        return channel;
    },

    getURIFlags: function(uri)
    {
        return Ci.nsIAboutModule.ALLOW_SCRIPT;
    }
}

const AboutCCFactory = XPCOMUtils.generateNSGetFactory([AboutCC])(AboutCC.prototype.classID);

// ********************************************************************************************* //
<|endoftext|>


<commit_before>// Credentials
var devId = process.env.DEVID;
var authKey = process.env.AUTHKEY;
var mongoUrl = process.env.MONGOLAB_URI;

// Variables used for app
var md5 = require('MD5'),
    mongo = require('mongodb').MongoClient,
    request = require('request'),
    moment = require('moment'),
    schedule = require('node-schedule');

function SessionSchedule(devId, authKey, mongoUrl) {
    schedule.scheduleJob('0,10,20,30,40,50 * * * *', function createSession() {

        if (devId == null) {
            devId = process.env.devId;
        }
        if (authKey == null) {
            authKey = process.env.authKey;
        }
        if (mongoUrl == undefined) {
            mongoUrl = process.env.mongoUrl;
        }

        var utcTime = moment().utc().format("YYYYMMDDHHmmss"),
            sessionHash = md5(devId + "createsession" + authKey + utcTime),
            fullUrl = ('http://api.smitegame.com/smiteapi.svc/' + 'createsessionJson/' + devId + '/' + sessionHash + '/' + utcTime);

        request({
            url: fullUrl
        }, function(error, response, body) {
            var jsonBody = JSON.parse(body);
            if (jsonBody.ret_msg == 'Approved') {
                mongo.connect(mongoUrl, function(err, db) {
                    if (err) {
                        console.log("MongoDB Connect Error: " + err);
                    } else {
                        var collection = db.collection('sessionid');
                        collection.remove({}, {
                            w: 0
                        });
                        collection.insert({
                            ret_msg: jsonBody.ret_msg,
                            session_id: jsonBody.session_id,
                            timestamp: jsonBody.timestamp
                        }, function(err) {
                            if (err) {
                                console.log("Mongo Insert Error: " + err);
                            }
                            db.close();
                        });
                    }
                });
            } else {
                console.log("API ERROR: ");
                console.log(jsonBody);
                console.log(utcTime);
            }
        });
    });
}

exports.devId = devId;
exports.authKey = authKey;
exports.mongoUrl = mongoUrl;
exports.SessionSchedule = SessionSchedule;
<commit_msg>Small typo in smite-session.js<commit_after>// Credentials
var devId = process.env.DEVID;
var authKey = process.env.AUTHKEY;
var mongoUrl = process.env.MONGOLAB_URI;

// Variables used for app
var md5 = require('MD5'),
    mongo = require('mongodb').MongoClient,
    request = require('request'),
    moment = require('moment'),
    schedule = require('node-schedule');

function SessionSchedule(devId, authKey, mongoUrl) {
    schedule.scheduleJob('0,10,20,30,40,50 * * * *', function createSession() {

        if (devId == null) {
            devId = process.env.DEVID;
        }
        if (authKey == null) {
            authKey = process.env.AUTHKEY;
        }
        if (mongoUrl == undefined) {
            mongoUrl = process.env.MONGOLAB_URI;
        }

        var utcTime = moment().utc().format("YYYYMMDDHHmmss"),
            sessionHash = md5(devId + "createsession" + authKey + utcTime),
            fullUrl = ('http://api.smitegame.com/smiteapi.svc/' + 'createsessionJson/' + devId + '/' + sessionHash + '/' + utcTime);

        request({
            url: fullUrl
        }, function(error, response, body) {
            var jsonBody = JSON.parse(body);
            if (jsonBody.ret_msg == 'Approved') {
                mongo.connect(mongoUrl, function(err, db) {
                    if (err) {
                        console.log("MongoDB Connect Error: " + err);
                    } else {
                        var collection = db.collection('sessionid');
                        collection.remove({}, {
                            w: 0
                        });
                        collection.insert({
                            ret_msg: jsonBody.ret_msg,
                            session_id: jsonBody.session_id,
                            timestamp: jsonBody.timestamp
                        }, function(err) {
                            if (err) {
                                console.log("Mongo Insert Error: " + err);
                            }
                            db.close();
                        });
                    }
                });
            } else {
                console.log("API ERROR: ");
                console.log(jsonBody);
                console.log(utcTime);
            }
        });
    });
}

exports.devId = devId;
exports.authKey = authKey;
exports.mongoUrl = mongoUrl;
exports.SessionSchedule = SessionSchedule;
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
const path = require('path');
require('dotenv').config((process.env.DOT_ENV_FILE) ? {path: process.env.DOT_ENV_FILE} : undefined);

const Pipeline = require('sifttt/lib/beam/Pipeline');
const Read = require('sifttt/lib/beam/Read');
const Write = require('sifttt/lib/beam/Write');
const ct = require('sifttt/lib/beam/coreTransforms');

const yargs = require('yargs');

let argv = yargs
.usage('$0 command')
.version()
.env()
.config()
.global(['config'])
.commandDir(path.join(__dirname, '../lib/beamish/commands'))
.demand(1, 'must provide a valid command')
.help('h')
.alias('h', 'help')
.argv;

// console.error(argv);

const command = argv._[0];

let sourceModulePath;
let sinkModulePath;

if (command === 'source') {
  sourceModulePath = argv.modulePath;
} else {
  sourceModulePath = 'sifttt/lib/beam/StdinSource';
}

if (command === 'sink') {
  sinkModulePath = argv.modulePath;
} else {
  sinkModulePath = 'sifttt/lib/beam/StdoutSink';
}

let Source;
try {
  if (argv.verbose) {
    console.error('About to load source from:', sourceModulePath);
  }
  Source = require(sourceModulePath);
} catch (e) {
  if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
      console.error(`Can't load module '${sourceModulePath}'. Please ensure it is installed.`);
      process.exit(-1);
  } else {
    throw e;
  }
}

let Sink;
try {
  if (argv.verbose) {
    console.error('About to load sink from:', sinkModulePath);
  }
  Sink = require(sinkModulePath);
} catch (e) {
  if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
      console.error(`Can't load module '${sinkModulePath}'. Please ensure it is installed.`);
      process.exit(-1);
  } else {
    throw e;
  }
}

let pipelineIn = Pipeline.create({name: command})
.apply(Read.from(new Source(argv)));

let pipelineTransform = pipelineIn;

if (ct.hasOwnProperty(command)) {
  let Module;

  try {
    Module = require(argv.modulePath);
  } catch (e) {
    if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
        console.error(`Can't load module '${argv.modulePath}'. Please ensure it is installed.`);
        process.exit(-1);
    } else {
      throw e;
    }
  }

  pipelineTransform = pipelineTransform
  .apply(new ct.ParseJSON())
  .apply(new ct[command](Module(argv)));
}

let pipelineOut = pipelineTransform
.apply(new ct.ToVinyl())
.apply(Write.to(new Sink(argv)))
;

pipelineOut.run(() => {
  if (argv.verbose) {
    console.error(`Finished Processing: ${command}`);
  }
});
;
<commit_msg>tweak cli so that a pipeline can be used as a source or sink<commit_after>#!/usr/bin/env node
'use strict';
const path = require('path');
require('dotenv').config((process.env.DOT_ENV_FILE) ? {path: process.env.DOT_ENV_FILE} : undefined);

const Pipeline = require('sifttt/lib/beam/Pipeline');
const Read = require('sifttt/lib/beam/Read');
const Write = require('sifttt/lib/beam/Write');
const ct = require('sifttt/lib/beam/coreTransforms');

const yargs = require('yargs');

let argv = yargs
.usage('$0 command')
.version()
.env()
.config()
.global(['config'])
.commandDir(path.join(__dirname, '../lib/beamish/commands'))
.demand(1, 'must provide a valid command')
.help('h')
.alias('h', 'help')
.argv;

// console.error(argv);

const command = argv._[0];

let sourceModulePath;
let sinkModulePath;

if (command === 'source') {
  sourceModulePath = argv.modulePath;
} else {
  sourceModulePath = 'sifttt/lib/beam/StdinSource';
}

if (command === 'sink') {
  sinkModulePath = argv.modulePath;
} else {
  sinkModulePath = 'sifttt/lib/beam/StdoutSink';
}

let Source;
try {
  if (argv.verbose) {
    console.error('About to load source from:', sourceModulePath);
  }
  Source = require(sourceModulePath);
} catch (e) {
  if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
      console.error(`Can't load module '${sourceModulePath}'. Please ensure it is installed.`);
      process.exit(-1);
  } else {
    throw e;
  }
}

let Sink;
try {
  if (argv.verbose) {
    console.error('About to load sink from:', sinkModulePath);
  }
  Sink = require(sinkModulePath);
} catch (e) {
  if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
      console.error(`Can't load module '${sinkModulePath}'. Please ensure it is installed.`);
      process.exit(-1);
  } else {
    throw e;
  }
}

/**
 * Create an instance of our source, and if it's not a pipeline than wrap it
 * in a Read.from():
 */

let source = new Source(argv);

if (source.getStream) {
  source = Read.from(source);
}

let pipelineIn = Pipeline.create({name: command})
.apply(source);

let pipelineTransform = pipelineIn;

if (ct.hasOwnProperty(command)) {
  let Module;

  try {
    Module = require(argv.modulePath);
  } catch (e) {
    if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {
        console.error(`Can't load module '${argv.modulePath}'. Please ensure it is installed.`);
        process.exit(-1);
    } else {
      throw e;
    }
  }

  pipelineTransform = pipelineTransform
  .apply(new ct.ParseJSON())
  .apply(new ct[command](Module(argv)));
}

/**
 * Create an instance of our sink, and if it's not a pipeline than wrap it
 * in a Write.to():
 */

let sink = new Sink(argv);

if (sink.getStream) {
  sink = Write.to(sink);
}

let pipelineOut = pipelineTransform
.apply(new ct.ToVinyl())
.apply(sink)
;

pipelineOut.run(() => {
  if (argv.verbose) {
    console.error(`Finished Processing: ${command}`);
  }
});
;
<|endoftext|>


<commit_before>/**
 * @author Paul Moon
 * @ngdoc service
 * @name chronosApp.EventFactory
 * @description Factory used for retrieving (filtered) events from a single place.
 */

(function () {
  'use strict';

  angular
    .module('chronosApp')
    .factory('EventFactory', EventFactory);

  EventFactory.$inject = ['$log', '$q', 'RestService', 'StateService', 'settings'];

  /* @ngInject */
  function EventFactory($log, $q, RestService, StateService, settings) {
    var factory = {
      events: [],
      selectedEvents: [],
      savedEvents: [],
      reportedEvents: [],
      votedEvents: [],
      keywords: [],
      tags: [],
      selectedEventsStartRange: undefined,
      selectedEventsEndRange: undefined,
      dateRangeStart: undefined,
      dateRangeEnd: undefined,

      getEvents: getEvents,
      getSelectedEvents: getSelectedEvents,
      getSavedEvents: getSavedEvents,
      setSavedEvents: setSavedEvents,
      getReportedEvents: getReportedEvents,
      setReportedEvents: setReportedEvents,
      getVotedEvents: getVotedEvents,
      setVotedEvents: setVotedEvents,
      getTags: getTags,

      updateKeywords: updateKeywords,
      updateTags: updateTags,
      addTag: addTag,
      updateDateRange: updateDateRange,
      updateDateRangeStart: updateDateRangeStart,
      updateDateRangeEnd: updateDateRangeEnd,
      updateSelectionRange: updateSelectionRange,
      updateEvents: updateEvents,
      refreshEvents: refreshEvents,
    };

    return factory;

    //////////////////////

    /**
     * @description Returns the events that the factory holds.
     * @methodOf chronosApp:EventFactory
     * @returns List of events in the EventFactory.
     */
    function getEvents() {
      return factory.events;
    }

    /**
     * @description Returns the tags that the event factory holds
     * @methodOf chronosApp:EventFactory
     * @returns Joined string of events in the event factory
     */
    function getTags() {
      return factory.tags.join(" ");
    }

    /**
     * @description Returns the events that the application is currently displaying.
     * @methodOf chronosApp:EventFactory
     * @returns List of events that the application is currently showing.
     */
    function getSelectedEvents() {
      return factory.selectedEvents;
    }

    /**
     * @description Get all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @returns savedEvents Saved events
     */
    function getSavedEvents() {
      return factory.savedEvents;
    }

    /**
     * @description Set all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @param savedEvents Saved events
     */
    function setSavedEvents(savedEvents) {
      factory.savedEvents = savedEvents;
    }

    /**
     * @description Get all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @returns savedEvents Saved events
     */
    function getReportedEvents() {
      return factory.reportedEvents;
    }

    /**
     * @description Set all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @param savedEvents Saved events
     */
    function setReportedEvents(reportedEvents) {
      factory.reportedEvents = reportedEvents;
    }

    /**
     * @description Get all events that user has voted on.
     * @methodOf chronosApp:EventFactory
     * @returns getVotedEvents Voted events
     */
    function getVotedEvents() {
      return factory.votedEvents;
    }

    /**
     * @description Set all events that user has voted on.
     * @methodOf chronosApp:EventFactory
     * @param votedEvents
     */
    function setVotedEvents(votedEvents) {
      factory.votedEvents = votedEvents;
    }

    /**
     * @description Allows the user to update the events when a location has changed
     * @methodOf chronosApp:EventFactory
     */
    function refreshEvents() {
      return _updateEvents();
    }

    /**
     * @description add a single tag and update events
     * @methodOf chronosApp:EventFactory
     * @param tag a single new tag to add
     * @returns {*}
     */
    function addTag(tag) {
      var match = false;

      if (factory.tags.length > settings.maxNumberTags) {
        return;
      }

      factory.tags.forEach(function (tag2) {
        if (tag === tag2) {
          match = true;
        }
      });

      if (match) {
        return;
      }

      factory.tags.push(tag);
      return _updateEvents();
    }

    /**
     * @description Update events with given keywords
     * @methodOf chronosApp:EventFactory
     * @param keywords Array of keywords by which keywords will be filtered
     * @returns {*}
     */
    function updateKeywords(keywords) {
      factory.keywords = keywords;
      return _updateEvents();
    }

    /**
     * @description Update events with given tags
     * @methodOf chronosApp:EventFactory
     * @param tags Array of tags by which events will be filtered
     * @returns {*}
     */
    function updateTags(tags) {
      factory.tags = tags;
      return _updateEvents();
    }

    /**
     * Update the events using the specified date range start.
     * @param start Moment type
     * @returns {Promise}
     */
    function updateDateRangeStart(start) {
      factory.dateRangeStart = start;
      return _updateEvents();
    }

    /**
     * Update the events using the specified date range end.
     * @param start Moment type
     * @returns {Promise}
     */
    function updateDateRangeEnd(end) {
      factory.dateRangeEnd = end;
      return _updateEvents();
    }

    /**
     * @description Update events with the given date range
     * @methodOf chronosApp:EventFactory
     * @param start Moment type
     * @param end Moment type
     * @returns {*} List of events filtered with new date range.
     */
    function updateDateRange(start, end) {
      factory.dateRangeStart = start;
      factory.dateRangeEnd = end;
      return _updateEvents();
    }

    /**
     * @description Sets the start and end range for which to display the events. If June 15th selected,
     * then the start time will be June 15th 12:00:00 AM (UTC) and the end time will be June 16th
     * 12:00:00 AM (UTC).
     * @methodOf chronosApp:EventFactory
     * @param start Moment type
     * @param end Moment type
     */
    function updateSelectionRange(start, end) {
      var deferred = $q.defer();

      factory.selectedEventsStartRange = start;
      factory.selectedEventsEndRange = end;
      // The only time we don't display any events is if eventStart > end or eventEnd < start.
      // Converse by De Morgan's Law: If eventStart <= end and eventEnd >= start
      factory.selectedEvents = factory.events.filter(function (element) {

        // If the start and end date are the same, then we are only selecting one day. Then, we filter
        // based on start_date to start_date + 23:59:59
        // Note we will never enter this via Full Calendar because selecting one day always
        // ensures we are checking against the next day
        if (element.start_date.diff(element.end_date) === 0) {
          return element.start_date < start.local().add(1, 'd') && element.end_date >= start.local();
        }

        // This is in case the start and end dates are an actual selection
        // An event ending at 12AM June 15th should not be shown when we select on June 15th. Similarly, an event
        // beginning on June 15th 12AM should not be shown when we click on June 14th (clicked date's end =
        // June 15th 12AM). Since we don't want to show the event because they are on different days,
        // strict inequality is used.
        return ((element.start_date.isAfter(start) || element.start_date.isSame(start)) && (element.start_date.isBefore(end))) ||
          ((element.end_date.isAfter(start)) && (element.end_date.isBefore(end) || element.end_date.isSame(end))) ||
          ((element.start_date.isAfter(start) || element.start_date.isSame(start)) && (element.end_date.isBefore(end) || element.end_date.isSame(end)));
      });

      deferred.resolve("Selected a range");
      return deferred.promise;
    }

    /**
     * @description Batch update the events. New keywords, tags, fromDate and toDate, and other keys in filterParams
     * are used to filter the events. This expects dateRangeStart and dateRangeEnd to be Moment objects. If a
     * filterParams is not specified it is set to nothing. This function should only be used by the "apply filters"
     * button.
     * @methodOf chronosApp:EventFactory
     * @param filterParams Object of {key: value} filter parameters.
     */
    function updateEvents(filterParams) {
      if (filterParams.keywords) {
        factory.keywords = filterParams.keywords;
      } else {
        factory.keywords = [];
      }

      if (filterParams.fromDate) {
        factory.dateRangeStart = filterParams.fromDate;
      } else {
        factory.dateRangeStart = undefined;
      }

      if (filterParams.toDate) {
        factory.dateRangeEnd = filterParams.toDate;
      } else {
        factory.dateRangeEnd = undefined;
      }

      return _updateEvents();
    }

    /**
     * @description Internal method for updating EventFactory.events.
     * @methodOf chronosApp:EventFactory
     * @returns Promise containing list of events if succeeded or rejected promise otherwise.
     * @private
     */
    function _updateEvents() {
      var filterParams = _constructFilterParams();

      return RestService.getFilteredEvents(filterParams)
        .then(function (response) {
          var newEvents = response.data;

          for (var i = 0; i < newEvents.length; i++) {
            // Note that here, we're ensuring all event dates are a moment type in UTC format. This is extremely important
            newEvents[i].start_date = moment.utc(newEvents[i].start_date);
            newEvents[i].end_date = moment.utc(newEvents[i].end_date);
          }

          factory.events = newEvents;
          factory.selectedEvents = newEvents;
          return factory.events;
        }, function (response) {
          $log.warn('Failed to retrieve filtered events: ' + filterParams);
          $log.warn(response);
          return $q.reject(response);
        });
    }

    /**
     * Helper method for constructing {key: value} filter parameter object
     * @methodOf chronosApp:EventFactory
     * @returns {{}} filterParam object
     * @private
     */
    function _constructFilterParams() {
      var filterParams = [];

      if (factory.keywords.length > 0) {
        factory.keywords.forEach(function (keyword) {
          filterParams.push({name: "keyword", value: keyword});
        });
      }

      if (factory.tags.length > 0) {
        factory.tags.forEach(function (tag) {
          filterParams.push({name: "tag", value: tag});
        });
      }

      // Provide YYYY-MM-DDTHH:mm:ss for Django.
      if (factory.dateRangeStart) {
        filterParams.push({name: "fromDate", value: factory.dateRangeStart.utc().format('YYYY-MM-DD[T]HH:mm:ss')});
      }

      if (factory.dateRangeEnd) {
        filterParams.push({name: "toDate", value: factory.dateRangeEnd.utc().format('YYYY-MM-DD[T]HH:mm:ss')});
      }

      if (StateService.getPlaceID()) {
        filterParams.push({name: "placeID", value: StateService.getPlaceID()});
      }

      return filterParams;
    }
  }
})();
<commit_msg>Added comments to make more sense to the date filtering<commit_after>/**
 * @author Paul Moon
 * @ngdoc service
 * @name chronosApp.EventFactory
 * @description Factory used for retrieving (filtered) events from a single place.
 */

(function () {
  'use strict';

  angular
    .module('chronosApp')
    .factory('EventFactory', EventFactory);

  EventFactory.$inject = ['$log', '$q', 'RestService', 'StateService', 'settings'];

  /* @ngInject */
  function EventFactory($log, $q, RestService, StateService, settings) {
    var factory = {
      events: [],
      selectedEvents: [],
      savedEvents: [],
      reportedEvents: [],
      votedEvents: [],
      keywords: [],
      tags: [],
      selectedEventsStartRange: undefined,
      selectedEventsEndRange: undefined,
      dateRangeStart: undefined,
      dateRangeEnd: undefined,

      getEvents: getEvents,
      getSelectedEvents: getSelectedEvents,
      getSavedEvents: getSavedEvents,
      setSavedEvents: setSavedEvents,
      getReportedEvents: getReportedEvents,
      setReportedEvents: setReportedEvents,
      getVotedEvents: getVotedEvents,
      setVotedEvents: setVotedEvents,
      getTags: getTags,

      updateKeywords: updateKeywords,
      updateTags: updateTags,
      addTag: addTag,
      updateDateRange: updateDateRange,
      updateDateRangeStart: updateDateRangeStart,
      updateDateRangeEnd: updateDateRangeEnd,
      updateSelectionRange: updateSelectionRange,
      updateEvents: updateEvents,
      refreshEvents: refreshEvents,
    };

    return factory;

    //////////////////////

    /**
     * @description Returns the events that the factory holds.
     * @methodOf chronosApp:EventFactory
     * @returns List of events in the EventFactory.
     */
    function getEvents() {
      return factory.events;
    }

    /**
     * @description Returns the tags that the event factory holds
     * @methodOf chronosApp:EventFactory
     * @returns Joined string of events in the event factory
     */
    function getTags() {
      return factory.tags.join(" ");
    }

    /**
     * @description Returns the events that the application is currently displaying.
     * @methodOf chronosApp:EventFactory
     * @returns List of events that the application is currently showing.
     */
    function getSelectedEvents() {
      return factory.selectedEvents;
    }

    /**
     * @description Get all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @returns savedEvents Saved events
     */
    function getSavedEvents() {
      return factory.savedEvents;
    }

    /**
     * @description Set all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @param savedEvents Saved events
     */
    function setSavedEvents(savedEvents) {
      factory.savedEvents = savedEvents;
    }

    /**
     * @description Get all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @returns savedEvents Saved events
     */
    function getReportedEvents() {
      return factory.reportedEvents;
    }

    /**
     * @description Set all events that user saved.
     * @methodOf chronosApp:EventFactory
     * @param savedEvents Saved events
     */
    function setReportedEvents(reportedEvents) {
      factory.reportedEvents = reportedEvents;
    }

    /**
     * @description Get all events that user has voted on.
     * @methodOf chronosApp:EventFactory
     * @returns getVotedEvents Voted events
     */
    function getVotedEvents() {
      return factory.votedEvents;
    }

    /**
     * @description Set all events that user has voted on.
     * @methodOf chronosApp:EventFactory
     * @param votedEvents
     */
    function setVotedEvents(votedEvents) {
      factory.votedEvents = votedEvents;
    }

    /**
     * @description Allows the user to update the events when a location has changed
     * @methodOf chronosApp:EventFactory
     */
    function refreshEvents() {
      return _updateEvents();
    }

    /**
     * @description add a single tag and update events
     * @methodOf chronosApp:EventFactory
     * @param tag a single new tag to add
     * @returns {*}
     */
    function addTag(tag) {
      var match = false;

      if (factory.tags.length > settings.maxNumberTags) {
        return;
      }

      factory.tags.forEach(function (tag2) {
        if (tag === tag2) {
          match = true;
        }
      });

      if (match) {
        return;
      }

      factory.tags.push(tag);
      return _updateEvents();
    }

    /**
     * @description Update events with given keywords
     * @methodOf chronosApp:EventFactory
     * @param keywords Array of keywords by which keywords will be filtered
     * @returns {*}
     */
    function updateKeywords(keywords) {
      factory.keywords = keywords;
      return _updateEvents();
    }

    /**
     * @description Update events with given tags
     * @methodOf chronosApp:EventFactory
     * @param tags Array of tags by which events will be filtered
     * @returns {*}
     */
    function updateTags(tags) {
      factory.tags = tags;
      return _updateEvents();
    }

    /**
     * Update the events using the specified date range start.
     * @param start Moment type
     * @returns {Promise}
     */
    function updateDateRangeStart(start) {
      factory.dateRangeStart = start;
      return _updateEvents();
    }

    /**
     * Update the events using the specified date range end.
     * @param start Moment type
     * @returns {Promise}
     */
    function updateDateRangeEnd(end) {
      factory.dateRangeEnd = end;
      return _updateEvents();
    }

    /**
     * @description Update events with the given date range
     * @methodOf chronosApp:EventFactory
     * @param start Moment type
     * @param end Moment type
     * @returns {*} List of events filtered with new date range.
     */
    function updateDateRange(start, end) {
      factory.dateRangeStart = start;
      factory.dateRangeEnd = end;
      return _updateEvents();
    }

    /**
     * @description Sets the start and end range for which to display the events. If June 15th selected,
     * then the start time will be June 15th 12:00:00 AM (UTC) and the end time will be June 16th
     * 12:00:00 AM (UTC).
     * @methodOf chronosApp:EventFactory
     * @param start Moment type
     * @param end Moment type
     */
    function updateSelectionRange(start, end) {
      var deferred = $q.defer();

      factory.selectedEventsStartRange = start;
      factory.selectedEventsEndRange = end;
      // The only time we don't display any events is if eventStart > end or eventEnd < start.
      // Converse by De Morgan's Law: If eventStart <= end and eventEnd >= start
      factory.selectedEvents = factory.events.filter(function (element) {

        // If the start and end date are the same, then we are only selecting one day. Then, we filter
        // based on start_date to start_date + 23:59:59
        // Note we will never enter this via Full Calendar because selecting one day always
        // ensures we are checking against the next day
        if (element.start_date.diff(element.end_date) === 0) {
          return element.start_date < start.local().add(1, 'd') && element.end_date >= start.local();
        }

        // This is in case the start and end dates are an actual selection
        // An event ending at 12AM June 15th should not be shown when we select on June 15th. Similarly, an event
        // beginning on June 15th 12AM should not be shown when we click on June 14th (clicked date's end =
        // June 15th 12AM). Since we don't want to show the event because they are on different days,
        // strict inequality is used.

        // The check goes as follows: (It can probably be simplified I know)
        // 1. Is the start date after or the same as the start of the date range filter AND is the start date before the end of the date range filter OR (start of event is in the date range)
        // 2. Is the end date after the start of the date range filter AND is the end date before or the same as the end of the date range filter OR (end of event is in the date range)
        // 3. Is the start date after or the same as the date range filter AND is the end date before or the same as the end of the date range filter (event exists in between the start and end of date range)
        return ((element.start_date.isAfter(start) || element.start_date.isSame(start)) && (element.start_date.isBefore(end))) ||
          ((element.end_date.isAfter(start)) && (element.end_date.isBefore(end) || element.end_date.isSame(end))) ||
          ((element.start_date.isAfter(start) || element.start_date.isSame(start)) && (element.end_date.isBefore(end) || element.end_date.isSame(end)));
      });

      deferred.resolve("Selected a range");
      return deferred.promise;
    }

    /**
     * @description Batch update the events. New keywords, tags, fromDate and toDate, and other keys in filterParams
     * are used to filter the events. This expects dateRangeStart and dateRangeEnd to be Moment objects. If a
     * filterParams is not specified it is set to nothing. This function should only be used by the "apply filters"
     * button.
     * @methodOf chronosApp:EventFactory
     * @param filterParams Object of {key: value} filter parameters.
     */
    function updateEvents(filterParams) {
      if (filterParams.keywords) {
        factory.keywords = filterParams.keywords;
      } else {
        factory.keywords = [];
      }

      if (filterParams.fromDate) {
        factory.dateRangeStart = filterParams.fromDate;
      } else {
        factory.dateRangeStart = undefined;
      }

      if (filterParams.toDate) {
        factory.dateRangeEnd = filterParams.toDate;
      } else {
        factory.dateRangeEnd = undefined;
      }

      return _updateEvents();
    }

    /**
     * @description Internal method for updating EventFactory.events.
     * @methodOf chronosApp:EventFactory
     * @returns Promise containing list of events if succeeded or rejected promise otherwise.
     * @private
     */
    function _updateEvents() {
      var filterParams = _constructFilterParams();

      return RestService.getFilteredEvents(filterParams)
        .then(function (response) {
          var newEvents = response.data;

          for (var i = 0; i < newEvents.length; i++) {
            // Note that here, we're ensuring all event dates are a moment type in UTC format. This is extremely important
            newEvents[i].start_date = moment.utc(newEvents[i].start_date);
            newEvents[i].end_date = moment.utc(newEvents[i].end_date);
          }

          factory.events = newEvents;
          factory.selectedEvents = newEvents;
          return factory.events;
        }, function (response) {
          $log.warn('Failed to retrieve filtered events: ' + filterParams);
          $log.warn(response);
          return $q.reject(response);
        });
    }

    /**
     * Helper method for constructing {key: value} filter parameter object
     * @methodOf chronosApp:EventFactory
     * @returns {{}} filterParam object
     * @private
     */
    function _constructFilterParams() {
      var filterParams = [];

      if (factory.keywords.length > 0) {
        factory.keywords.forEach(function (keyword) {
          filterParams.push({name: "keyword", value: keyword});
        });
      }

      if (factory.tags.length > 0) {
        factory.tags.forEach(function (tag) {
          filterParams.push({name: "tag", value: tag});
        });
      }

      // Provide YYYY-MM-DDTHH:mm:ss for Django.
      if (factory.dateRangeStart) {
        filterParams.push({name: "fromDate", value: factory.dateRangeStart.utc().format('YYYY-MM-DD[T]HH:mm:ss')});
      }

      if (factory.dateRangeEnd) {
        filterParams.push({name: "toDate", value: factory.dateRangeEnd.utc().format('YYYY-MM-DD[T]HH:mm:ss')});
      }

      if (StateService.getPlaceID()) {
        filterParams.push({name: "placeID", value: StateService.getPlaceID()});
      }

      return filterParams;
    }
  }
})();
<|endoftext|>


<commit_before>var arcService = {
    ogcOptions: {
        format: "image/png",
        transparent: true,
        exceptions: "application/vnd.ogc.se_inimage",
        srs: "EPSG:28992",
        version: "1.1.1",
        maptipids:"kanoroute,mtbroute,law_knelpt,lf_knelpt,regio_tvoost,biro2010,strooi_prov,bvb,kulturhus_mfa,top,energie_pro_biomassa,energie_pro_besparing,energie_pro_kwo,energie_pro_wind,energie_pro_zon,energie_pro_overig,stortplaats,asbest_loc,bouwarchief_niet_gem,bouwarchief_gem,bodemarchief,biro,rijkswegen,vaarwegen,provwegen,luchtkwaliteit_2008_N,luchtkwaliteit_2008_P,overijssel_geluid_lden_rijksw_2006,overijssel_geluid_lnight_rijksw_2006,overijssel_geluid_lden_provw_2006,overijssel_geluid_lnight_provw_2006,natlands,natpark,froutenetwerk,lfroute,lawroute,nat2000,rec_camping,rec_bungalowpark,rec_jachthaven,rec_groepsaccommodatie,recon_zone_polygon,wav_polygon,verzuur_polygon,waterwin_polygon,intrekgebied,grwbes_polygon,rayonwk_polygon,hemelhelderheid_polygon,wbe_polygon,ibis,watschap_ned_polygon,geomorfologie,LGN6,corop,habitattypen_id,ehs,rvz,evz,station,nb_wet,rijksmonumenten,gemeentelijkemonumenten,groenloket_natuurbeheertypen,groenloket_nieuwenatuur_beh,groenloket_nieuwenatuur_amb,groenloket_landschapselementen_beh,groenloket_agrbeh_weidevogel_beh,groenloket_agrbeh_botgrasland_beh,groenloket_agrbeh_botakkerland_beh,groenloket_ganzen_beh,groenloket_probleemgebieden,groenloket_schaapskudde_toeslag,groenloket_rvz_beh,groenloket_evz,groenloket_natuurbeheertypen_amb,groenloket_landschapselementen_amb,groenloket_agrbeh_weidevogel_amb,groenloket_agrbeh_botgrasland_amb,groenloket_agrbeh_botakkerland_amb,groenloket_ganzen_amb,groenloket_rvz_amb,groenloket_evz_amb,salland,boringvrij,fknooppunt,zwemwater_o,zwemwater_no,zwemwater_kand_o,zwemwater_kand_no,bag_pand,bag_adres,bag_ligplaats,bag_adres_ligplaats,bag_standplaats,bag_adres_standplaats,bag_verblijfsobject",
        styles: "",
        legend:"false",
        hidelegendids:"",
        backgroundcolor:"#fbfbfb",
        transcolor:"#fbfbfb",
        alpha:"85",
        fullextent:"160000,457560,287864,543013",
        identifydistance:"20",
        maptipdistance:"20",
        id:"avo",
        name:"atlasoverijssel",
        timeout:"50",
        server:"gisopenbaar.overijssel.nl",
        servlet:"GeoJuli2008/ims",
        mapservice:"atlasoverijssel",
        visible:"true",
        hiddenids:"streetview,streetview_prov,acetate_streetview",
        // visibleids:"regio_tvoost",
        identifyall:"true",
        identifyids:"kanoroute,mtbroute,law_knelpt,lf_knelpt,regio_tvoost,biro2010,N340_bpEnkel,strooi_prov,bvb,kulturhus_mfa,top,energie_pro_biomassa,energie_pro_besparing,energie_pro_kwo,energie_pro_wind,energie_pro_zon,energie_pro_overig,stortplaats,asbest_loc,bouwarchief_niet_gem,bouwarchief_gem,bodemarchief,biro,rijkswegen,vaarwegen,provwegen,luchtkwaliteit_2008_N,luchtkwaliteit_2008_P,overijssel_geluid_lden_rijksw_2006,overijssel_geluid_lnight_rijksw_2006,overijssel_geluid_lden_provw_2006,overijssel_geluid_lnight_provw_2006,natlands,natpark,froutenetwerk,lfroute,lawroute,nat2000,rec_camping,rec_bungalowpark,rec_jachthaven,rec_groepsaccommodatie,recon_zone_polygon,wav_polygon,verzuur_polygon,waterwin_polygon,intrekgebied,grwbes_polygon,rayonwk_polygon,hemelhelderheid_polygon,wbe_polygon,ibis,watschap_ned_polygon,geomorfologie,LGN6,corop,habitattypen_id,ehs,rvz,evz,station,nb_wet,rijksmonumenten,gemeentelijkemonumenten,groenloket_natuurbeheertypen,groenloket_nieuwenatuur_beh,groenloket_nieuwenatuur_amb,groenloket_landschapselementen_beh,groenloket_agrbeh_weidevogel_beh,groenloket_agrbeh_botgrasland_beh,groenloket_agrbeh_botakkerland_beh,groenloket_ganzen_beh,groenloket_probleemgebieden,groenloket_schaapskudde_toeslag,groenloket_rvz_beh,groenloket_evz,groenloket_natuurbeheertypen_amb,groenloket_landschapselementen_amb,groenloket_agrbeh_weidevogel_amb,groenloket_agrbeh_botgrasland_amb,groenloket_agrbeh_botakkerland_amb,groenloket_ganzen_amb,groenloket_rvz_amb,groenloket_evz_amb,salland,boringvrij,fknooppunt,zwemwater_o,zwemwater_no,zwemwater_kand_o,zwemwater_kand_no,bag_pand,bag_adres,bag_ligplaats,bag_adres_ligplaats,bag_standplaats,bag_adres_standplaats,bag_verblijfsobject",
        noCache: false // TODO: Voor achtergrond kaartlagen wel cache gebruiken
    },
    options:{
        timeout: 30,
        retryonerror: 10,
        ratio: 1,
        showerrors: true,
        id: "avo",
        initService: true
    },
    service : "",
    server: "",
    mapservice:"",
    name :""
};<commit_msg>remove old file<commit_after><|endoftext|>