<commit_before>var taskList = [];

function TKTask(title, hours, minutes) {
    this.title = title;
    this.hours = hours;
    this.minutes = minutes;
    this.uid = generateUID();
}

function generateUID(){
    var d = new Date().getTime();
    var uid = 'txxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uid;
};

function zeroPad(n, p, c) {
    var pad_char = typeof c !== 'undefined' ? c : '0';
    var pad = new Array(1 + p).join(pad_char);
    return (pad + n).slice(-pad.length);
}

function redrawTaskList() {
    $('#taskList ul').empty();
    for (var i = taskList.length; i-->0; ) {
        var currentTask = taskList[i];
        var task = "

" + currentTask.title + "

" + zeroPad(currentTask.hours, 2) + ":" + zeroPad(currentTask.minutes, 2) + "

";
        $('#taskList ul').append(task).listview('refresh');
    }
}

$(document).ready( function () {
    $('#addTaskOk').click(function () {
        var title = $('#addTaskTitle').val();
        var hours = parseInt($('#addTaskDurationH').val(), 10) || 0;
        var minutes = parseInt($('#addTaskDurationM').val(), 10) || 0;
        var newTask = new TKTask(title, hours, minutes);
        taskList.push(newTask);
        window.localStorage.setItem('taskList', JSON.stringify(taskList));
        $('#addTaskTitle').val("");
        $('#addTaskDurationH').val("");
        $('#addTaskDurationM').val("");
        redrawTaskList();
    });

    $('#listClearButton').click(function () {
        taskList = [];
        window.localStorage.removeItem('taskList');
        $('#taskList ul').empty();
    });

    taskList = JSON.parse(window.localStorage.getItem('taskList')) || [];
    if (taskList.length != 0) {
        redrawTaskList();
    }
});

<commit_msg>element deletion function<commit_after>var taskList = [];

function TKTask(title, hours, minutes) {
    this.title = title;
    this.hours = hours;
    this.minutes = minutes;
    this.uid = generateUID();
}

function generateUID(){
    var d = new Date().getTime();
    var uid = 'txxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uid;
};

function zeroPad(n, p, c) {
    var pad_char = typeof c !== 'undefined' ? c : '0';
    var pad = new Array(1 + p).join(pad_char);
    return (pad + n).slice(-pad.length);
}

function redrawTaskList() {
    $('#taskList ul').empty();
    for (var i = taskList.length; i-->0; ) {
        var currentTask = taskList[i];
        var task = "

" + currentTask.title + "

" + zeroPad(currentTask.hours, 2) + ":" + zeroPad(currentTask.minutes, 2) + "

";
        $('#taskList ul').append(task).listview('refresh');
    }
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function removeTaskFromList(uid) {
    for (var i = taskList.length; i-->0; ) {
        var currentTask = taskList[i];
        if(currentTask.uid == uid) {
            taskList.remove(i);
            break;
        }
    }
    window.localStorage.setItem('taskList', JSON.stringify(taskList));
    redrawTaskList();
}

$(document).ready( function () {
    $('#addTaskOk').click(function () {
        var title = $('#addTaskTitle').val();
        var hours = parseInt($('#addTaskDurationH').val(), 10) || 0;
        var minutes = parseInt($('#addTaskDurationM').val(), 10) || 0;
        var newTask = new TKTask(title, hours, minutes);
        taskList.push(newTask);
        window.localStorage.setItem('taskList', JSON.stringify(taskList));
        $('#addTaskTitle').val("");
        $('#addTaskDurationH').val("");
        $('#addTaskDurationM').val("");
        redrawTaskList();
    });

    $('#listClearButton').click(function () {
        taskList = [];
        window.localStorage.removeItem('taskList');
        $('#taskList ul').empty();
    });

    taskList = JSON.parse(window.localStorage.getItem('taskList')) || [];
    if (taskList.length != 0) {
        redrawTaskList();
    }
});

<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}
<commit_msg>update function getWinner<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
  if(playerMove === "rock" && computerMove === "scissors") {
      winner = "player";
  } else if(playerMove === "scissors" && computerMove === "paper") {
      winner = "player";
  }  else if(playerMove === "paper" && computerMove === "rock") {
      winner = "player";
  } else if(playerMove === computerMove) {
      winner = "tie";
  } else {
      winner = "computer";
  }
  return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}
<|endoftext|>


<commit_before>// ==UserScript==
// This script works on the PR page. Uses Parse to store data.
// @match https://github.com/*
// ==/UserScript==

// Other file forwarders
var Parse;
var waitForKeyElements;

var findAllThreads = function () {
  var threads = [];

  $('#discussion_bucket .line-comments .comment-holder').each(function () {
    var childComments = $(this).children('.comment');
    if (childComments.length > 0) {
      var firstCommentChild = childComments.first()[0];
      threads.push({
        id: firstCommentChild.id,
        comments: childComments,
        lastCommentId: childComments.last()[0].id,
      });
    }
  });

  $('#discussion_bucket .timeline-comment-wrapper .timeline-comment.js-comment').each(function () {
    if (this.id && this.id.match(/^issuecomment/)) {
      threads.push({
        id: this.id,
        comments: $(this),
        lastCommentId: this.id,
      });
    }
  });

  return threads;
};

var checkThreads = function () {
  var newThreads = findAllThreads();
  if (_.isEqual(_.pluck(newThreads, 'id'), _.pluck(allThreads, 'id'))) {
    if (_.isEqual(_.pluck(newThreads, 'lastCommentId'), _.pluck(allThreads, 'lastCommentId'))) {
      return;
    }
  }
  resetManipulations();
};

var resetManipulations = function () {
  allThreads = findAllThreads();

  annotateWithParseInfo(allThreads).then(function () {
    _.each(allThreads, function (info) { updateThread(info, {suppressMergeUpdate: true}); });
  }).then(function () {
    expandUnresolvedThreads();
    updateMergeButton();
  });
};

var CommentTracker;
var Settings;
var appSettings;

var main = function () {
  /* global chrome */
  chrome.storage.sync.get({
    polling: true
  }, function (items) {
    Parse.initialize("af7O3YCdgoc17ZhLj7uGFypfEvzSYMphi7XbeQCK", "giDSblA98q6dM6aCY0WTJZWBeWGoUDcPMbaVw31H");
    CommentTracker = Parse.Object.extend('CommentTracker');
    Settings = Parse.Object.extend('Settings');

    resetManipulations();

    // waitForKeyElements will trigger for *each* changed/added element.
    // Debounce both to only call checkThreads once, and to call with a slight
    // delay for better compatiblity with the WideGithub extension:
    // https://chrome.google.com/webstore/detail/wide-github/kaalofacklcidaampbokdplbklpeldpj
    var debouncedCheckThreads = _.debounce(checkThreads, 100);
    waitForKeyElements('.comment', debouncedCheckThreads);

    if (items.polling) {
      new Parse.Query(Settings).get("bdWmF0aC6c").then(function (settings) {
        appSettings = settings;
        setInterval(resetManipulations, appSettings.get('pollInterval'));
      });
    }
  });
};

var expandUnresolvedThreads =  function () {
  _.each(allThreads, function (info) {
    if (!info.resolved) {
      var id = info.id;
      var elem = $('#' + id).first();
      var container = elem.parents('.outdated-diff-comment-container');
      if (container.length > 0) {
        container.removeClass('closed').addClass('open');
      }
    }
  });
};

var allThreads;
var initalCanBeMerged = false;

var allThreadsResolved = function () {
  return _.all(allThreads, function (info) {
    return info.resolved;
  });
};

var updateMergeButton = function () {
  if (!initalCanBeMerged) {
    initalCanBeMerged = $('.js-merge-branch-action').hasClass('btn-primary');
  }
  $('.comment-track-status').remove();

  if (initalCanBeMerged) {
    if (allThreadsResolved()) {
      // Make button green
      $('.js-merge-branch-action').addClass('btn-primary');
      $('.branch-action').addClass('branch-action-state-clean').removeClass('branch-action-state-dirty');
      $('.status-heading').text('This pull request can be automatically merged.');
      $('.status-meta').text('Merging can be performed automatically.');
      $('.branch-action-item-icon').removeClass('completeness-indicator-problem').addClass('completeness-indicator-success').html('<svg aria-hidden="true" class="octicon octicon-alert" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>');
    } else {
      // Make button grey
      $('.js-merge-branch-action').removeClass('btn-primary');
      $('.branch-action').removeClass('branch-action-state-clean').addClass('branch-action-state-dirty');
      $('.status-heading').text('Merge with caution!');
      $('.status-meta').text('You have unresolved comments!');
      $('.branch-action-item-icon').removeClass('completeness-indicator-success').addClass('completeness-indicator-problem').html('<svg aria-hidden="true" class="octicon octicon-alert" height="16" role="img" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15.72 12.5l-6.85-11.98C8.69 0.21 8.36 0.02 8 0.02s-0.69 0.19-0.87 0.5l-6.85 11.98c-0.18 0.31-0.18 0.69 0 1C0.47 13.81 0.8 14 1.15 14h13.7c0.36 0 0.69-0.19 0.86-0.5S15.89 12.81 15.72 12.5zM9 12H7V10h2V12zM9 9H7V5h2V9z"></path></svg>');
    }
  } else {
    if (!allThreadsResolved()) {
      $('.merge-message').before(
        '
' +
        '
' +
        '      <svg aria-hidden="true" class="octicon octicon-alert" height="16" role="img" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15.72 12.5l-6.85-11.98C8.69 0.21 8.36 0.02 8 0.02s-0.69 0.19-0.87 0.5l-6.85 11.98c-0.18 0.31-0.18 0.69 0 1C0.47 13.81 0.8 14 1.15 14h13.7c0.36 0 0.69-0.19 0.86-0.5S15.89 12.81 15.72 12.5zM9 12H7V10h2V12zM9 9H7V5h2V9z"></path></svg>' +
        '
' +
        '
This branch has unresolved comments
' +
        '      ' +
        '        See above for red unresolved comments' +
        '      ' +
        '
'
      );
    }
  }
};

var annotateWithParseInfo = function (allThreads) {
  var ids = _.pluck(allThreads, 'id');
  var query = new Parse.Query(CommentTracker);
  query.containedIn('commentId', ids);

  return query.find().then(function (results) {
    _.each(results, function (result) {
      var id = result.get('commentId');
      var info = _.findWhere(allThreads, {id: id});
      if (info) {
        info.resolved = result.get('resolved') && result.get('lastCommentSeen') === info.lastCommentId;
        info.lastCommentSeen = result.get('lastCommentSeen');
        info.tracker = result;
      }
    });
  });
};

var makeButton = function (elem, threadInfo) {
  $(elem).find('.comment-track-action').remove();

  var string;
  if (threadInfo.resolved) {
    string = '';
    $(elem).find('.timeline-comment-actions').prepend(string);

    $(elem).find('.comment-track-unresolve').on('click', function (event) {
      event.preventDefault();
      var tracker = threadInfo.tracker;
      tracker.set('resolved', false);
      tracker.set('lastCommentSeen', null);
      tracker.save();

      threadInfo.resolved = false;

      updateThread(threadInfo);
    });
  } else {
    string = '';
    $(elem).find('.timeline-comment-actions').prepend(string);
    $(elem).find('.comment-track-resolve').on('click', function (event) {
      event.preventDefault();
      var tracker = threadInfo.tracker || new CommentTracker();

      tracker.set('commentId', threadInfo.id);
      tracker.set('resolved', true);
      tracker.set('lastCommentSeen', threadInfo.lastCommentId);

      tracker.save();

      threadInfo.resolved = true;
      threadInfo.tracker = tracker;

      updateThread(threadInfo);
    });
  }
};

var updateThread = function (info, options) {
  options = options || {};
  var id = info.id;
  var elem = $('#' + id).first();

  if (id.match(/^discussion_/)) {
    var threadComments = $(elem).parents('.comment-holder').children('.comment');
    threadComments.each(function () {
      makeButton(this, info);
    });
  } else {
    makeButton(elem, info);
  }

  if (!options.suppressMergeUpdate) {
    updateMergeButton();
  }
};

main();
<commit_msg>Fix for code review github changes<commit_after>// ==UserScript==
// This script works on the PR page. Uses Parse to store data.
// @match https://github.com/*
// ==/UserScript==

// Other file forwarders
var Parse;
var waitForKeyElements;

var findAllThreads = function () {
  var threads = [];

  $('#discussion_bucket .js-line-comments .js-comments-holder').each(function () {
    var childComments = $(this).children('.js-comment');
    if (childComments.length > 0) {
      var firstCommentChild = childComments.first()[0];
      threads.push({
        id: firstCommentChild.id,
        comments: childComments,
        lastCommentId: childComments.last()[0].id,
      });
    }
  });

  $('#discussion_bucket .timeline-comment-wrapper .timeline-comment.js-comment').each(function () {
    if (this.id && this.id.match(/^issuecomment/)) {
      threads.push({
        id: this.id,
        comments: $(this),
        lastCommentId: this.id,
      });
    }
  });

  return threads;
};

var checkThreads = function () {
  var newThreads = findAllThreads();
  if (_.isEqual(_.pluck(newThreads, 'id'), _.pluck(allThreads, 'id'))) {
    if (_.isEqual(_.pluck(newThreads, 'lastCommentId'), _.pluck(allThreads, 'lastCommentId'))) {
      return;
    }
  }
  resetManipulations();
};

var resetManipulations = function () {
  allThreads = findAllThreads();

  annotateWithParseInfo(allThreads).then(function () {
    _.each(allThreads, function (info) { updateThread(info, {suppressMergeUpdate: true}); });
  }).then(function () {
    expandUnresolvedThreads();
    updateMergeButton();
  });
};

var CommentTracker;
var Settings;
var appSettings;

var main = function () {
  /* global chrome */
  chrome.storage.sync.get({
    polling: true
  }, function (items) {
    Parse.initialize("af7O3YCdgoc17ZhLj7uGFypfEvzSYMphi7XbeQCK", "giDSblA98q6dM6aCY0WTJZWBeWGoUDcPMbaVw31H");
    CommentTracker = Parse.Object.extend('CommentTracker');
    Settings = Parse.Object.extend('Settings');

    resetManipulations();

    // waitForKeyElements will trigger for *each* changed/added element.
    // Debounce both to only call checkThreads once, and to call with a slight
    // delay for better compatiblity with the WideGithub extension:
    // https://chrome.google.com/webstore/detail/wide-github/kaalofacklcidaampbokdplbklpeldpj
    var debouncedCheckThreads = _.debounce(checkThreads, 100);
    waitForKeyElements('.comment', debouncedCheckThreads);

    if (items.polling) {
      new Parse.Query(Settings).get("bdWmF0aC6c").then(function (settings) {
        appSettings = settings;
        setInterval(resetManipulations, appSettings.get('pollInterval'));
      });
    }
  });
};

var expandUnresolvedThreads =  function () {
  _.each(allThreads, function (info) {
    if (!info.resolved) {
      var id = info.id;
      var elem = $('#' + id).first();
      var container = elem.parents('.outdated-diff-comment-container');
      if (container.length > 0) {
        container.removeClass('closed').addClass('open');
      }
    }
  });
};

var allThreads;
var initalCanBeMerged = false;

var allThreadsResolved = function () {
  return _.all(allThreads, function (info) {
    return info.resolved;
  });
};

var updateMergeButton = function () {
  if (!initalCanBeMerged) {
    initalCanBeMerged = $('.js-merge-branch-action').hasClass('btn-primary');
  }
  $('.comment-track-status').remove();

  if (initalCanBeMerged) {
    if (allThreadsResolved()) {
      // Make button green
      $('.js-merge-branch-action').addClass('btn-primary');
      $('.branch-action').addClass('branch-action-state-clean').removeClass('branch-action-state-dirty');
      $('.status-heading').text('This pull request can be automatically merged.');
      $('.status-meta').text('Merging can be performed automatically.');
      $('.branch-action-item-icon').removeClass('completeness-indicator-problem').addClass('completeness-indicator-success').html('<svg aria-hidden="true" class="octicon octicon-alert" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path d="M12 5L4 13 0 9l1.5-1.5 2.5 2.5 6.5-6.5 1.5 1.5z"></path></svg>');
    } else {
      // Make button grey
      $('.js-merge-branch-action').removeClass('btn-primary');
      $('.branch-action').removeClass('branch-action-state-clean').addClass('branch-action-state-dirty');
      $('.status-heading').text('Merge with caution!');
      $('.status-meta').text('You have unresolved comments!');
      $('.branch-action-item-icon').removeClass('completeness-indicator-success').addClass('completeness-indicator-problem').html('<svg aria-hidden="true" class="octicon octicon-alert" height="16" role="img" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15.72 12.5l-6.85-11.98C8.69 0.21 8.36 0.02 8 0.02s-0.69 0.19-0.87 0.5l-6.85 11.98c-0.18 0.31-0.18 0.69 0 1C0.47 13.81 0.8 14 1.15 14h13.7c0.36 0 0.69-0.19 0.86-0.5S15.89 12.81 15.72 12.5zM9 12H7V10h2V12zM9 9H7V5h2V9z"></path></svg>');
    }
  } else {
    if (!allThreadsResolved()) {
      $('.merge-message').before(
        '
' +
        '
' +
        '      <svg aria-hidden="true" class="octicon octicon-alert" height="16" role="img" version="1.1" viewBox="0 0 16 16" width="16"><path d="M15.72 12.5l-6.85-11.98C8.69 0.21 8.36 0.02 8 0.02s-0.69 0.19-0.87 0.5l-6.85 11.98c-0.18 0.31-0.18 0.69 0 1C0.47 13.81 0.8 14 1.15 14h13.7c0.36 0 0.69-0.19 0.86-0.5S15.89 12.81 15.72 12.5zM9 12H7V10h2V12zM9 9H7V5h2V9z"></path></svg>' +
        '
' +
        '
This branch has unresolved comments
' +
        '      ' +
        '        See above for red unresolved comments' +
        '      ' +
        '
'
      );
    }
  }
};

var annotateWithParseInfo = function (allThreads) {
  var ids = _.pluck(allThreads, 'id');
  var query = new Parse.Query(CommentTracker);
  query.containedIn('commentId', ids);

  return query.find().then(function (results) {
    _.each(results, function (result) {
      var id = result.get('commentId');
      var info = _.findWhere(allThreads, {id: id});
      if (info) {
        info.resolved = result.get('resolved') && result.get('lastCommentSeen') === info.lastCommentId;
        info.lastCommentSeen = result.get('lastCommentSeen');
        info.tracker = result;
      }
    });
  });
};

var makeButton = function (elem, threadInfo) {
  var $elem = $(elem);
  $elem.find('.comment-track-action').remove();

  var actionSelector = '.review-comment-contents';
  if ($elem.find(actionSelector).length === 0) {
    actionSelector = '.timeline-comment-actions';
  }

  var string;
  if (threadInfo.resolved) {
    string = '';
    $elem.find(actionSelector).prepend(string);

    $elem.find('.comment-track-unresolve').on('click', function (event) {
      event.preventDefault();
      var tracker = threadInfo.tracker;
      tracker.set('resolved', false);
      tracker.set('lastCommentSeen', null);
      tracker.save();

      threadInfo.resolved = false;

      updateThread(threadInfo);
    });
  } else {
    string = '';
    $elem.find(actionSelector).prepend(string);

    $elem.find('.comment-track-resolve').on('click', function (event) {
      event.preventDefault();
      var tracker = threadInfo.tracker || new CommentTracker();

      tracker.set('commentId', threadInfo.id);
      tracker.set('resolved', true);
      tracker.set('lastCommentSeen', threadInfo.lastCommentId);

      tracker.save();

      threadInfo.resolved = true;
      threadInfo.tracker = tracker;

      updateThread(threadInfo);
    });
  }
};

var updateThread = function (info, options) {
  options = options || {};
  var id = info.id;
  var elem = $('#' + id).first();

  if (!id.match(/^issuecomment/)) {
    var threadComments = $(elem).parents('.js-comments-holder').children('.js-comment');
    threadComments.each(function () {
      makeButton(this, info);
    });
  } else {
    makeButton(elem, info);
  }

  if (!options.suppressMergeUpdate) {
    updateMergeButton();
  }
};

main();
<|endoftext|>


<commit_before>// Copyright 2015, EMC, Inc.

'use strict';

module.exports = lookupServiceFactory;

lookupServiceFactory.$provide = 'Services.Lookup';
lookupServiceFactory.$inject = [
    'Promise',
    'Services.Configuration',
    'Services.Waterline',
    'Assert',
    'Errors',
    '_'
];

/**
 * Provides a LookupService singleton.
 * @private
 * @param  {Promise} Promise
 * @param  {configuration} configuration
 * @param  {Waterline} waterline
 * @param  {Assert} assert
 * @param  {Errors} errors
 * @param  {lodash} _
 * @param  {lru-cache} LRU Cache Package
 *
 * @return {LookupService} An instance of the LookupService.
 */
function lookupServiceFactory(
    Promise,
    configuration,
    waterline,
    assert,
    Errors,
    _
) {
    // TODO: stolen from http-service could stand to be a re-usable helper.
    /**
     * Get remote address of the client.
     * @private
     * @param {req} req from express
     * @returns {String|Undefined} either the ip of requester or undefined
     *                             if unavailable
     */
    function remoteAddress(req) {
        assert.ok(req, 'req');

        if (req.ip) {
            return req.ip;
        }

        if (req._remoteAddress) {
            return req._remoteAddress;
        }

        if (req.connection) {
            return req.connection.remoteAddress;
        }

        // TODO: This doesn't appear to ever get hit and causes an assertion
        // in the IP lookup due to undefined not being an IP so we need to investigate
        // what to do in this particular case (which again doesn't seem to have ever
        // actually occurred)
        return undefined;
    }

    /**
     * Provides functionality to correlate various identifiers
     * to their appropriate counterparts.
     * @constructor
     */
    function LookupService () {
      this.resetNodeIdCache();
    }

    /**
     * Reset all cached Node IDs.
     */
    LookupService.prototype.resetNodeIdCache = function () {
        this.nodeIdCache = {};
    };

    /**
     * Reset the cache for a specific IP or MAC address.
     * @param  {String} cache key - IP or MAC address.
     */
    LookupService.prototype.clearNodeIdCache = function (key) {
        this.nodeIdCache[key] = null;
    };

    /**
     * Check the cache for a Node ID by IP or MAC addres.
     * @param  {String} cache key - IP or MAC address.
     * @return {Promise|null} Returns a promise if the Node ID is cached,
                              otherwise null.
     */
    LookupService.prototype.checkNodeIdCache = function (key) {
      if (typeof this.nodeIdCache[key] === 'string') {
          return Promise.resolve(this.nodeIdCache[key]);
      }

      if (Array.isArray(this.nodeIdCache[key])) {
          return new Promise(function (resolve) {
              this.nodeIdCache[key].push(resolve);
          }.bind(this));
      }

      this.nodeIdCache[key] = [];

      return null;
    };

    /**
     * Cache Node ID by either an IP or MAC address.
     * @param  {String} cache key - IP or MAC address.
     * @param  {String} cache value - Node ID.
     * @return {String} value converted to a string.
     */
    LookupService.prototype.assignNodeIdCache = function(key, value) {
        value = value.toString();

        if (Array.isArray(this.nodeIdCache[key])) {
            this.nodeIdCache[key].forEach(function (resolve) {
                resolve(value);
            });
        }

        this.nodeIdCache[key] = value;

        return value;
    };

    /**
     * Provides a middleware function suitable for
     * looking up the request IP via express and adding a req.macaddress and
     * req.macAddress value representing the MAC address used for the HTTP
     * request.
     * @return {function} An express middleware function.
     */
    LookupService.prototype.ipAddressToMacAddressMiddleware = function () {
        var self = this;

        return function(req, res, next) {
            self.ipAddressToMacAddress(remoteAddress(req)).then(function (macAddress) {
                // Provide both lower case and camel case versions.
                req.macaddress = macAddress;
                req.macAddress = macAddress;
            }).finally(function() {
                next();
            });
        };
    };

    /**
     * Converts the given IP address into a MAC address
     * via a lookup in the leaseCache.
     * @param  {String} ip IP Address to correlate to a MAC Address.
     * @return {Promise.<String>}    A promise fulfilled to the MAC address which
     * correlates to the provided IP.
     */
    LookupService.prototype.ipAddressToMacAddress = function (ip) {
        assert.isIP(ip);

        return waterline.lookups.findOneByTerm(ip).then(function (record) {
            return record.macAddress;
        });
    };

    /**
     * macAddressToNode converts the given MAC address into a Node document via
     * a lookup in the DomainService.
     * @param  {String} macAddress MAC Address to correlate to a Node.
     * @return {Promise.<NodeDocument>} A promise fulfilled to the Node which
     * correlates to the provided MAC Address.
     */
    LookupService.prototype.macAddressToNode = function (macAddress) {
        return waterline.lookups.findOneByTerm(macAddress).then(function (record) {
            if (record.node) {
                return waterline.nodes.needOneById(record.node);
            } else {
                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (macAddressToNode)',
                    record
                );
            }
        });
    };

    /**
     * Returns the IP Address associated with the given MAC address.
     * @param {String} macAddress MAC Address to correlate with an IP.
     * @return {Promise.<String>} A promise fulfilled with the IP Address which
     * correlates to the provided MAC Address.
     */
    LookupService.prototype.macAddressToIp = function (macAddress) {
        return waterline.lookups.findOneByTerm(macAddress).then(function (record) {
            if (record.ipAddress) {
                return record.ipAddress;
            } else {
                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (macAddressToIp)',
                    record
                );
            }
        });
    };

    /**
     * Converts the given MAC address into the BSON ID of the node document via
     * a lookup in the DomainService. This function will cache values to avoid
     * excessive round trips to the DB, so its use is recommended when only the
     * BSON ID is needed.
     * @param  {String} macAddress MAC Address to correlate to a Node.
     * @return {Promise.<ObjectId>} A promise fulfilled to the Node ID which
     * correlates to the provided MAC Address.
     */
    LookupService.prototype.macAddressToNodeId = function (macAddress) {
        var cachePromise = this.checkNodeIdCache(macAddress);

        if (cachePromise) {
            return cachePromise;
        }

        return waterline.lookups.findOneByTerm(macAddress).then(function (record) {
            if (record.node) {
                return this.assignNodeIdCache(macAddress, record.node);
            }

            else {
                this.clearNodeIdCache(macAddress);

                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (macAddressToNodeId)',
                    record
                );
            }
        }.bind(this));
    };

    /**
     * Converts the given IP Address into a Node document via
     * a lookup using the leaseCache & DomainService.
     * @param  {String} ip IP Address to correlate to a Node.
     * @return {Promise.<NodeDocument>} A promise fulfilled to the Node which
     * correlates to the provided IP Address.
     */
    LookupService.prototype.ipAddressToNode = function (ip) {
        assert.isIP(ip);

        return waterline.lookups.findOneByTerm(ip).then(function (record) {
            if (record.node) {
                return waterline.nodes.needOneById(record.node);
            } else {
                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (ipAddressToNode)',
                    record
                );
            }
        });
    };

    /**
     * Converts the given IP Address into the BSON ID of the Node via
     * a lookup using the leaseCache & DomainService. This function will cache
     * values to avoid excessive round trips to the DB, so its use is
     * recommended when only the BSON ID is needed.
     * @param  {String} ip IP Address to correlate to a Node.
     * @return {Promise.<ObjectId>} A promise fulfilled to the Node ID which
     * correlates to the provided IP Address.
     */
    LookupService.prototype.ipAddressToNodeId = function (ip) {
        assert.isIP(ip);

        var cachePromise = this.checkNodeIdCache(ip);

        if (cachePromise) {
            return cachePromise;
        }

        return waterline.lookups.findOneByTerm(ip).then(function (record) {
            if (record.node) {
                return this.assignNodeIdCache(ip, record.node);
            }

            else {
                this.clearNodeIdCache(ip);

                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (ipAddressToNodeId)',
                    record
                );
            }
        }.bind(this));
    };

    /**
     * Returns a list of IP Addresses for the given Node ID.
     * @param  {String} id Node ID
     * @return {Promise.<Array>} A promise fulfilled with an array of
     * IP Addresses associated with the Node.
     */
    LookupService.prototype.nodeIdToIpAddresses = function (id) {
        assert.isMongoId(id);

        return waterline.lookups.findByTerm(id).then(function (records) {
            return _.reduce(records, function (ipAddresses, record) {
                if (record.ipAddress) {
                    ipAddresses.push(record.ipAddress);
                }

                return ipAddresses;
            }, []);
        });
    };

    LookupService.prototype.setIpAddress = function (ip, mac) {
        return waterline.lookups.setIp(ip, mac);
    };

    LookupService.prototype.start = function () {
        return Promise.resolve();
    };

    LookupService.prototype.stop = function () {
        return Promise.resolve();
    };

    return new LookupService();
}
<commit_msg>fix whitespace<commit_after>// Copyright 2015, EMC, Inc.

'use strict';

module.exports = lookupServiceFactory;

lookupServiceFactory.$provide = 'Services.Lookup';
lookupServiceFactory.$inject = [
    'Promise',
    'Services.Configuration',
    'Services.Waterline',
    'Assert',
    'Errors',
    '_'
];

/**
 * Provides a LookupService singleton.
 * @private
 * @param  {Promise} Promise
 * @param  {configuration} configuration
 * @param  {Waterline} waterline
 * @param  {Assert} assert
 * @param  {Errors} errors
 * @param  {lodash} _
 * @param  {lru-cache} LRU Cache Package
 *
 * @return {LookupService} An instance of the LookupService.
 */
function lookupServiceFactory(
    Promise,
    configuration,
    waterline,
    assert,
    Errors,
    _
) {
    // TODO: stolen from http-service could stand to be a re-usable helper.
    /**
     * Get remote address of the client.
     * @private
     * @param {req} req from express
     * @returns {String|Undefined} either the ip of requester or undefined
     *                             if unavailable
     */
    function remoteAddress(req) {
        assert.ok(req, 'req');

        if (req.ip) {
            return req.ip;
        }

        if (req._remoteAddress) {
            return req._remoteAddress;
        }

        if (req.connection) {
            return req.connection.remoteAddress;
        }

        // TODO: This doesn't appear to ever get hit and causes an assertion
        // in the IP lookup due to undefined not being an IP so we need to investigate
        // what to do in this particular case (which again doesn't seem to have ever
        // actually occurred)
        return undefined;
    }

    /**
     * Provides functionality to correlate various identifiers
     * to their appropriate counterparts.
     * @constructor
     */
    function LookupService () {
        this.resetNodeIdCache();
    }

    /**
     * Reset all cached Node IDs.
     */
    LookupService.prototype.resetNodeIdCache = function () {
        this.nodeIdCache = {};
    };

    /**
     * Reset the cache for a specific IP or MAC address.
     * @param  {String} cache key - IP or MAC address.
     */
    LookupService.prototype.clearNodeIdCache = function (key) {
        this.nodeIdCache[key] = null;
    };

    /**
     * Check the cache for a Node ID by IP or MAC addres.
     * @param  {String} cache key - IP or MAC address.
     * @return {Promise|null} Returns a promise if the Node ID is cached,
                              otherwise null.
     */
    LookupService.prototype.checkNodeIdCache = function (key) {
        if (typeof this.nodeIdCache[key] === 'string') {
            return Promise.resolve(this.nodeIdCache[key]);
        }

        if (Array.isArray(this.nodeIdCache[key])) {
            return new Promise(function (resolve) {
                this.nodeIdCache[key].push(resolve);
            }.bind(this));
        }

        this.nodeIdCache[key] = [];

        return null;
    };

    /**
     * Cache Node ID by either an IP or MAC address.
     * @param  {String} cache key - IP or MAC address.
     * @param  {String} cache value - Node ID.
     * @return {String} value converted to a string.
     */
    LookupService.prototype.assignNodeIdCache = function(key, value) {
        value = value.toString();

        if (Array.isArray(this.nodeIdCache[key])) {
            this.nodeIdCache[key].forEach(function (resolve) {
                resolve(value);
            });
        }

        this.nodeIdCache[key] = value;

        return value;
    };

    /**
     * Provides a middleware function suitable for
     * looking up the request IP via express and adding a req.macaddress and
     * req.macAddress value representing the MAC address used for the HTTP
     * request.
     * @return {function} An express middleware function.
     */
    LookupService.prototype.ipAddressToMacAddressMiddleware = function () {
        var self = this;

        return function(req, res, next) {
            self.ipAddressToMacAddress(remoteAddress(req)).then(function (macAddress) {
                // Provide both lower case and camel case versions.
                req.macaddress = macAddress;
                req.macAddress = macAddress;
            }).finally(function() {
                next();
            });
        };
    };

    /**
     * Converts the given IP address into a MAC address
     * via a lookup in the leaseCache.
     * @param  {String} ip IP Address to correlate to a MAC Address.
     * @return {Promise.<String>}    A promise fulfilled to the MAC address which
     * correlates to the provided IP.
     */
    LookupService.prototype.ipAddressToMacAddress = function (ip) {
        assert.isIP(ip);

        return waterline.lookups.findOneByTerm(ip).then(function (record) {
            return record.macAddress;
        });
    };

    /**
     * macAddressToNode converts the given MAC address into a Node document via
     * a lookup in the DomainService.
     * @param  {String} macAddress MAC Address to correlate to a Node.
     * @return {Promise.<NodeDocument>} A promise fulfilled to the Node which
     * correlates to the provided MAC Address.
     */
    LookupService.prototype.macAddressToNode = function (macAddress) {
        return waterline.lookups.findOneByTerm(macAddress).then(function (record) {
            if (record.node) {
                return waterline.nodes.needOneById(record.node);
            } else {
                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (macAddressToNode)',
                    record
                );
            }
        });
    };

    /**
     * Returns the IP Address associated with the given MAC address.
     * @param {String} macAddress MAC Address to correlate with an IP.
     * @return {Promise.<String>} A promise fulfilled with the IP Address which
     * correlates to the provided MAC Address.
     */
    LookupService.prototype.macAddressToIp = function (macAddress) {
        return waterline.lookups.findOneByTerm(macAddress).then(function (record) {
            if (record.ipAddress) {
                return record.ipAddress;
            } else {
                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (macAddressToIp)',
                    record
                );
            }
        });
    };

    /**
     * Converts the given MAC address into the BSON ID of the node document via
     * a lookup in the DomainService. This function will cache values to avoid
     * excessive round trips to the DB, so its use is recommended when only the
     * BSON ID is needed.
     * @param  {String} macAddress MAC Address to correlate to a Node.
     * @return {Promise.<ObjectId>} A promise fulfilled to the Node ID which
     * correlates to the provided MAC Address.
     */
    LookupService.prototype.macAddressToNodeId = function (macAddress) {
        var cachePromise = this.checkNodeIdCache(macAddress);

        if (cachePromise) {
            return cachePromise;
        }

        return waterline.lookups.findOneByTerm(macAddress).then(function (record) {
            if (record.node) {
                return this.assignNodeIdCache(macAddress, record.node);
            }

            else {
                this.clearNodeIdCache(macAddress);

                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (macAddressToNodeId)',
                    record
                );
            }
        }.bind(this));
    };

    /**
     * Converts the given IP Address into a Node document via
     * a lookup using the leaseCache & DomainService.
     * @param  {String} ip IP Address to correlate to a Node.
     * @return {Promise.<NodeDocument>} A promise fulfilled to the Node which
     * correlates to the provided IP Address.
     */
    LookupService.prototype.ipAddressToNode = function (ip) {
        assert.isIP(ip);

        return waterline.lookups.findOneByTerm(ip).then(function (record) {
            if (record.node) {
                return waterline.nodes.needOneById(record.node);
            } else {
                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (ipAddressToNode)',
                    record
                );
            }
        });
    };

    /**
     * Converts the given IP Address into the BSON ID of the Node via
     * a lookup using the leaseCache & DomainService. This function will cache
     * values to avoid excessive round trips to the DB, so its use is
     * recommended when only the BSON ID is needed.
     * @param  {String} ip IP Address to correlate to a Node.
     * @return {Promise.<ObjectId>} A promise fulfilled to the Node ID which
     * correlates to the provided IP Address.
     */
    LookupService.prototype.ipAddressToNodeId = function (ip) {
        assert.isIP(ip);

        var cachePromise = this.checkNodeIdCache(ip);

        if (cachePromise) {
            return cachePromise;
        }

        return waterline.lookups.findOneByTerm(ip).then(function (record) {
            if (record.node) {
                return this.assignNodeIdCache(ip, record.node);
            }

            else {
                this.clearNodeIdCache(ip);

                throw new Errors.NotFoundError(
                    'Lookup Record Not Found (ipAddressToNodeId)',
                    record
                );
            }
        }.bind(this));
    };

    /**
     * Returns a list of IP Addresses for the given Node ID.
     * @param  {String} id Node ID
     * @return {Promise.<Array>} A promise fulfilled with an array of
     * IP Addresses associated with the Node.
     */
    LookupService.prototype.nodeIdToIpAddresses = function (id) {
        assert.isMongoId(id);

        return waterline.lookups.findByTerm(id).then(function (records) {
            return _.reduce(records, function (ipAddresses, record) {
                if (record.ipAddress) {
                    ipAddresses.push(record.ipAddress);
                }

                return ipAddresses;
            }, []);
        });
    };

    LookupService.prototype.setIpAddress = function (ip, mac) {
        return waterline.lookups.setIp(ip, mac);
    };

    LookupService.prototype.start = function () {
        return Promise.resolve();
    };

    LookupService.prototype.stop = function () {
        return Promise.resolve();
    };

    return new LookupService();
}
<|endoftext|>


<commit_before>const mv = require("mv");
const path = require("path");
const fs = require("fs");

const getFileName = (file_path) => {
    return path.basename(file_path);
};

const getFolder = (file_path) => {
    return path.dirname(file_path);
};

const createFullPath = (folder, file) => {
    return folder.endsWith('/') ? folder + file : folder + '/' + file;
};

const appendFolder = (file_path, folder) => {
    return file_path.endsWith('/') ? file_path + folder : file_path + '/' + folder;
};

const moveFile = (sourcePath, destinationPath, cb) => {
    mv(sourcePath, destinationPath, {mkdirp: false}, cb);
};

const getPermissions = (path) => {
    return fs.statSync(path);
};

const createDirectory = (path, uid, gid, mode) => {
    var oldmask = process.umask(0);
    if(!fs.existsSync(path)){
        fs.mkdirSync(path, mode, function(err){
            console.log('Got here');
            process.umask(oldmask);
            if(err){
                throw err;
            }
        });
        fs.chownSync(path, uid, gid);
    }
};

module.exports = {
    moveFile: moveFile,
    appendFolder: appendFolder,
    createFullPath: createFullPath,
    getFileName: getFileName,
    getFolder: getFolder,
    createDirectory: createDirectory,
    getPermissions: getPermissions
};<commit_msg>Removed test log<commit_after>const mv = require("mv");
const path = require("path");
const fs = require("fs");

const getFileName = (file_path) => {
    return path.basename(file_path);
};

const getFolder = (file_path) => {
    return path.dirname(file_path);
};

const createFullPath = (folder, file) => {
    return folder.endsWith('/') ? folder + file : folder + '/' + file;
};

const appendFolder = (file_path, folder) => {
    return file_path.endsWith('/') ? file_path + folder : file_path + '/' + folder;
};

const moveFile = (sourcePath, destinationPath, cb) => {
    mv(sourcePath, destinationPath, {mkdirp: false}, cb);
};

const getPermissions = (path) => {
    return fs.statSync(path);
};

const createDirectory = (path, uid, gid, mode) => {
    var oldmask = process.umask(0);
    if(!fs.existsSync(path)){
        fs.mkdirSync(path, mode, function(err){
            process.umask(oldmask);
            if(err){
                throw err;
            }
        });
        fs.chownSync(path, uid, gid);
    }
};

module.exports = {
    moveFile: moveFile,
    appendFolder: appendFolder,
    createFullPath: createFullPath,
    getFileName: getFileName,
    getFolder: getFolder,
    createDirectory: createDirectory,
    getPermissions: getPermissions
};<|endoftext|>


<commit_before>var _     = require('underscore'),
    Hours = require('cloud/models/hours');

module.exports = Parse.Object.extend('Facility', {
  initialize: function() {
    this.set("services", []);
  },
  // no gender restriction or gender == self.gender
  matchesGender: function(targetGender) {
    var g = this.get('gender');

    if ( !g || !targetGender )  {
      return true;
    } else {
      return g.toUpperCase() == targetGender.toUpperCase();
    }
  },

  presentJSON: function() {
    var asJSON = this.toJSON();
    asJSON.services = this.get('services').map(function(service) {
      return service.toJSON();
    });
    asJSON.demographics = this.demographics();
    return asJSON;
  },

  matchesAges: function(ages) {
    var a = this.get('age');
    if ( !ages || !a ) {
      return true;
    }

    return _.any(_.compact(ages), function(targetAge) {
      return _.include(a, targetAge);
    });
  },

  matchesFilter: function(filter) {
    var match = true;

    if ( !filter ) {
      return true;
    }

    match &= this.matchesGender(filter.gender);
    match &= this.matchesAges(filter.age);
    match &= this.hasServiceInCategories(filter.categories);
    return match;
  },

  hasKnownStatus: function() {
    return (this.status() !== 'unknown');
  },

  status: function() {
    var open;

    if ( this._status ) return this._status;

    open = this.hasOpenService(new Date());

    if ( open === true ) {
      this._status = 'open';
    } else if ( open === false ) {
      this._status = 'closed';
    } else {
      this._status = 'unknown';
    }

    return this._status;
  },

  hasOpenService: function(time) {
    var services = this.get('services');
    try {
      return _.any(services, function(service) {
        return service.hours().within(time);
      });
    } catch(e) {
      console.log(e);
      return null;
    }
  },

  hasServiceInCategories: function(categories) {
    if ( !categories )  {
      return true;
    }

    var services = this.get('services');
    return _.any(_.compact(categories), function(targetCategory) {
      return _.any(services, function(facService) {
        return facService.get("category") === targetCategory;
      });
    });
  },

  age_as_string: function(input) {
    switch ( input.toUpperCase() ) {
      case "C":
        return "children";
      case "Y":
        return "teens";
      case "A":
        return "adults";
      case "S":
        return "seniors";
    }
  },

  demographics: function() {
    var g, a, output = "";
    if ( !this.get('age') && !this.get('gender') ) {
      output = "Anyone";
    } else {
      if ( (g = this.get('gender') ) ) {
        if ( this.get('age') ) {
          output = g.toUpperCase() == "F" ? "Female " : "Male ";
        } else {
          output = "Only " + g.toUpperCase() == "F" ? "women" : "men";
        }
      } else {
        output = "All ";
      }

      if ( (a = this.get('age') ) ) {
        // C-Y-A-S
        var translated = _(a).map(this.age_as_string);
        output += _(translated).join(", ");
      }
    }
    return output;
  }
});
<commit_msg>Fixes #91<commit_after>var _     = require('underscore'),
    Hours = require('cloud/models/hours');

module.exports = Parse.Object.extend('Facility', {
  initialize: function() {
    this.set("services", []);
  },
  // no gender restriction or gender == self.gender
  matchesGender: function(targetGender) {
    var g = this.get('gender');

    if ( !g || !targetGender )  {
      return true;
    } else {
      return g.toUpperCase() == targetGender.toUpperCase();
    }
  },

  presentJSON: function() {
    var asJSON = this.toJSON();
    asJSON.services = this.get('services').map(function(service) {
      return service.toJSON();
    });
    asJSON.demographics = this.demographics();
    return asJSON;
  },

  matchesAges: function(ages) {
    var a = this.get('age');
    if ( !ages || !a ) {
      return true;
    }

    return _.any(_.compact(ages), function(targetAge) {
      return _.include(a, targetAge);
    });
  },

  matchesFilter: function(filter) {
    var match = true;

    if ( !filter ) {
      return true;
    }

    match &= this.matchesGender(filter.gender);
    match &= this.matchesAges(filter.age);
    match &= this.hasServiceInCategories(filter.categories);
    return match;
  },

  hasKnownStatus: function() {
    return (this.status() !== 'unknown');
  },

  status: function() {
    var open;

    if ( this._status ) return this._status;

    open = this.hasOpenService(new Date());

    if ( open === true ) {
      this._status = 'open';
    } else if ( open === false ) {
      this._status = 'closed';
    } else {
      this._status = 'unknown';
    }

    return this._status;
  },

  hasOpenService: function(time) {
    var services = this.get('services');
    try {
      return _.any(services, function(service) {
        return service.hours().within(time);
      });
    } catch(e) {
      console.log(e);
      return null;
    }
  },

  hasServiceInCategories: function(categories) {
    if ( !categories )  {
      return true;
    }

    var services = this.get('services');
    return _.any(_.compact(categories), function(targetCategory) {
      return _.any(services, function(facService) {
        return facService.get("category") === targetCategory;
      });
    });
  },

  age_as_string: function(input) {
    switch ( input.toUpperCase() ) {
      case "C":
        return "children";
      case "Y":
        return "teens";
      case "A":
        return "adults";
      case "S":
        return "seniors";
    }
  },

  demographics: function() {
    var g, a, output = "";
    if ( !this.get('age') && !this.get('gender') ) {
      output = "Anyone";
    } else {
      if ( (g = this.get('gender') ) ) {
        if ( this.get('age') ) {
          output = g.toUpperCase() == "F" ? "Female " : "Male ";
        } else {
          output = "Only " + (g.toUpperCase() == "F" ? "women" : "men");
        }
      } else {
        output = "All ";
      }

      if ( (a = this.get('age') ) ) {
        // C-Y-A-S
        var translated = _(a).map(this.age_as_string);
        output += _(translated).join(", ");
      }
    }
    return output;
  }
});
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Updated rps changes<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return    return var move = Math.random();
}

function getComputerMove(move) {
    return    return var move = Math.random();
}

function getWinner(playerMove,computerMove) {
    var winner;
var rock = “R”;
var paper = “P”;
var scissors = “S”;

if (playerMove.equals(computerMove) {
console.log(“Tie”);
}

else if (playerMove.equals(‘R’)) {
  if (computerMove.equals(’S’))
console.log(“Rock beats scissors, you win”);
else if (computerMove.equals(‘P’))
console.log(“Paper beats rock, you lose”);
}

else if (playerMove.equals(“S”)) {
  if (computerMove.equals(“P”))
console.log(“Scissors beats Paper, you win”);
else if (computerMove.equals(“R”))
console.log(“Rock beats scissors, you lose”);
}

else if (playerMove.equals(“P”)) {
  if (computerMove.equals(“R”))
console.log(“Paper beats rock, you win”);
else if (computerMove.equals(“S”))
console.log(“Scissors beats paper, you lose”);
}

else
console.log (“Invalid input”)
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
  for (var playerWins = 0; playerWins < 5; playerWins += 1){
if (playerWins === 5) {
break;
}
for (var computerWins = 0; computerWins < 5; computerWins += 1){

if (computerWins === 5) {
break;
}
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>var util = require('util')
var Base = require('hmpo-form-wizard').Controller

var Controller = function() {
	Base.apply(this, arguments)
}

util.inherits(Controller, Base)

Controller.prototype.get = function successHandler(req, res, callback) {
	if (req.sessionModel.get('change-of-name-reason') == undefined){
		return res.redirect('./declaration')
	} else {
	switch (req.sessionModel.get('change-of-name-reason')) {
		case 'Marriage':
			return res.redirect('./name-change-docs-for-marriage')
		case 'Divorce':
			return res.redirect('./name-change-docs-for-divorce')
		case 'Small':
			return res.redirect('./name-change-docs-for-small-changes')
		case 'Gender':
			return res.redirect('./name-change-docs-for-gender-change')
		case 'Other':
			return res.redirect('./name-change-docs-for-other-changes')
	}
	}
}

module.exports = Controller
<commit_msg>fix routing of name change docs pages<commit_after>var util = require('util')
var Base = require('hmpo-form-wizard').Controller

var Controller = function() {
	Base.apply(this, arguments)
}

util.inherits(Controller, Base)

Controller.prototype.get = function successHandler(req, res, callback) {

	if (req.sessionModel.get('change-name') == false){
		return res.redirect('./declaration')
	} else {
	switch (req.sessionModel.get('change-of-name-reason')) {
		case 'Marriage-or-civil-partnership':
			return res.redirect('./name-change-docs-for-marriage')
		case 'Divorce':
			return res.redirect('./name-change-docs-for-divorce')
		case 'Small':
			return res.redirect('./name-change-docs-for-small-changes')
		case 'Gender-reassigment':
			return res.redirect('./name-change-docs-for-gender-change')
		case 'I-changed-my-name-another-way':
			return res.redirect('./name-change-docs-for-other-changes')
	}
	}
}

module.exports = Controller
<|endoftext|>


<commit_before>var Backbone            = require('backbone'),
    $                   = require('jquery'),
    _                   = require('underscore'),
    Service             = require('cloud/models/service'),
    Hours               = require('cloud/models/hours'),
    gmaps               = require('google-maps'),
    editServiceTemplate = require('templates/_edit_service');

function modelSaveFailCallback(args) {
  this.$("#facilitySaveError").show().focus();
  console.log("failed.");
  console.log(args);
}

function modelSaveSuccessCallback(args) {
  this.$("#facilitySaved").show().focus();
  this.$("#facilitySaved").delay(5000).fadeOut();

  console.log("saved.");
  console.log(args);
}

var days = [
  {key: "MON", name: "Monday"},
  {key: "TUE", name: "Tuesday"},
  {key: "WED", name: "Wednesday"},
  {key: "THU", name: "Thursday"},
  {key: "FRI", name: "Friday"},
  {key: "SAT", name: "Saturday"},
  {key: "SUN", name: "Sunday"}
];

function saveFacility(model, services, successCallback, failCallback) {
  model.save().then(function(foo) {
    _.each(model.get("services"), function(service) {
      service.destroy();
    });

    var serviceObjects = _.map(services, function(serviceData) {
      var service = new Service();
      service.set("facility", model);

      delete serviceData.id;
      service.set(serviceData);

      return service;
    });

    Service.saveAll(serviceObjects, function(services, error) {
      if (services) {
        model.set("services", _.map(services, function(s) {
          var sObj = new Service();
          sObj.id = s.id;
          return sObj;
        }));

        model.save()
          .then(function(fac) {
            successCallback(fac);
          }, function(error) {
            failCallback(error);
          });

      } else {
        failCallback(error);
      }
    });
  },
  failCallback);
}

var EditView = Backbone.View.extend({
  template: require('templates/edit'),

  events: {
    'click #add_category':    'addCategory',
    'click #remove_category': 'removeCategory'
  },

  addCategory: function(argument) {
    var context = { category: this.$('#categories').val() };
    this.$('#services').prepend(editServiceTemplate(context));
    return false;
  },

  removeCategory: function(event) {
    var parent = this.$(event.target).closest('.service-edit-row');
    parent.remove();
    return false;
  },

  parseHourElement: function(hours, el) {
    var closedCheckbox = $(el).next("input.closed");

    if ( closedCheckbox.prop("checked") || el.value === "" || el.value === "CLOSED" ) {
      return;
    }

    try {
      hours.addDay(el.name, el.value);
    } catch(err) {
      $(el).after($("
").html(err.message));
    }
  },

  parseHours: function() {
    var serviceHours = new Hours();

    _(this.$('input.day')).each(function(el) {
      this.parseHourElement(serviceHours, el);
    }.bind(this));

    return serviceHours;
  },

  setupForm: function() {
    var g = this.model.get('gender');
    var el;

    el = this.$('#gender_' + (g ? g : ''));
    el.prop('checked', true);

    this.$("#age_everyone").click(function() {
      this.$('[name="age"]').prop('checked', $(this).prop('checked'));
    }.bind(this));

    if ( this.model.get("age") ) {
      _(this.model.get("age")).each(function(age) {
        this.$("#age_" + age.toUpperCase()).prop('checked', true);
      }.bind(this));
    } else {
      this.$("#age_everyone").click();
    }

    this.$('#submit').click(function() {
      this.saveForm();
    }.bind(this));

    this.$("input.day").first().attr("placeholder", "example: 9am-3pm, 6pm-8pm");

    this.$("input.day").blur(function(ev) {
      this.parseHourElement(new Hours(), ev.target);
      return true;
    }.bind(this));

    this.$("input.closed").change(function(ev) {
      var el = ev.target;
      var textBox = $(el).closest("tr").find("input.day[name='" + el.name + "']");
      $(textBox).prop("disabled", $(el).prop("checked"));
      if ( $(el).prop("checked") ) {
        textBox.val("CLOSED");
      } else {
        textBox.val("");
      }
    });

    this.$("input.day").keyup(function(ev) {
      $(ev.target).next(".dayError").remove();
    });
  },

  saveForm: function() {
    // var self = this;
    var servicePromises = [];
    var formValues = this.$('#facilityForm').serializeObject();
    if ( formValues.gender === "" ) {
      formValues.gender = null;
    }

    if ( this.$("#age_everyone").prop('checked') ) {
      formValues.age = null;
    } else {
      var ages = _.map(this.$("[name=age]input:checked"), function(cb) {
        return $(cb).attr('value');
      });

      ages = _(ages).compact();
      formValues.age = ages;
    }

    var oldServices = _.clone(formValues.services);

    // _.each(formValues.services, function(service, i) {
    //   self.model.get("services")[i].set(service);
    // });

    delete formValues.services;
    this.model.set(formValues);

    var save = _.bind(saveFacility, this);
    save(this.model, oldServices, _.bind(modelSaveSuccessCallback, this), _.bind(modelSaveFailCallback, this));

  },

  render: function() {
    var hours = [];

    for(var idx = 0; idx <= 23; idx++) {
      if (idx < 10) { idx = '0' + idx; }
      hours.push(idx + ':00');
      hours.push(idx + ':30');
    }

    var templateData = this.model.presentJSON();
    templateData.services.forEach(function(service) {
      service.allHours = hours;
      service.days = days;
    });

    $(this.el).html(this.template({facility: templateData}));
    this.setupForm();
    return this;
  }
});

module.exports = EditView;
<commit_msg>hours admin: fixed error message behavior<commit_after>var Backbone            = require('backbone'),
    $                   = require('jquery'),
    _                   = require('underscore'),
    Service             = require('cloud/models/service'),
    Hours               = require('cloud/models/hours'),
    gmaps               = require('google-maps'),
    editServiceTemplate = require('templates/_edit_service');

function modelSaveFailCallback(args) {
  this.$("#facilitySaveError").show().focus();
  console.log("failed.");
  console.log(args);
}

function modelSaveSuccessCallback(args) {
  this.$("#facilitySaved").show().focus();
  this.$("#facilitySaved").delay(5000).fadeOut();

  console.log("saved.");
  console.log(args);
}

var days = [
  {key: "MON", name: "Monday"},
  {key: "TUE", name: "Tuesday"},
  {key: "WED", name: "Wednesday"},
  {key: "THU", name: "Thursday"},
  {key: "FRI", name: "Friday"},
  {key: "SAT", name: "Saturday"},
  {key: "SUN", name: "Sunday"}
];

function saveFacility(model, services, successCallback, failCallback) {
  model.save().then(function(foo) {
    _.each(model.get("services"), function(service) {
      service.destroy();
    });

    var serviceObjects = _.map(services, function(serviceData) {
      var service = new Service();
      service.set("facility", model);

      delete serviceData.id;
      service.set(serviceData);

      return service;
    });

    Service.saveAll(serviceObjects, function(services, error) {
      if (services) {
        model.set("services", _.map(services, function(s) {
          var sObj = new Service();
          sObj.id = s.id;
          return sObj;
        }));

        model.save()
          .then(function(fac) {
            successCallback(fac);
          }, function(error) {
            failCallback(error);
          });

      } else {
        failCallback(error);
      }
    });
  },
  failCallback);
}

var EditView = Backbone.View.extend({
  template: require('templates/edit'),

  events: {
    'click #add_category':    'addCategory',
    'click #remove_category': 'removeCategory'
  },

  addCategory: function(argument) {
    var context = { category: this.$('#categories').val() };
    this.$('#services').prepend(editServiceTemplate(context));
    return false;
  },

  removeCategory: function(event) {
    var parent = this.$(event.target).closest('.service-edit-row');
    parent.remove();
    return false;
  },

  parseHourElement: function(hours, el) {
    var closedCheckbox = $(el).next("input.closed");

    if ( closedCheckbox.prop("checked") || el.value === "" || el.value === "CLOSED" ) {
      return;
    }

    try {
      hours.addDay(el.name, el.value);
    } catch(err) {
      $(el).closest("tr").after($("

").html('' + err.message + '	'));
    }
  },

  parseHours: function() {
    var serviceHours = new Hours();

    _(this.$('input.day')).each(function(el) {
      this.parseHourElement(serviceHours, el);
    }.bind(this));

    return serviceHours;
  },

  setupForm: function() {
    var g = this.model.get('gender');
    var el;

    el = this.$('#gender_' + (g ? g : ''));
    el.prop('checked', true);

    this.$("#age_everyone").click(function() {
      this.$('[name="age"]').prop('checked', $(this).prop('checked'));
    }.bind(this));

    if ( this.model.get("age") ) {
      _(this.model.get("age")).each(function(age) {
        this.$("#age_" + age.toUpperCase()).prop('checked', true);
      }.bind(this));
    } else {
      this.$("#age_everyone").click();
    }

    this.$('#submit').click(function() {
      this.saveForm();
    }.bind(this));

    this.$("input.day").first().attr("placeholder", "example: 9am-3pm, 6pm-8pm");

    this.$("input.day").blur(function(ev) {
      this.parseHourElement(new Hours(), ev.target);
      return true;
    }.bind(this));

    this.$("input.closed").change(function(ev) {
      var el = ev.target;
      var textBox = $(el).closest("tr").find("input.day[name='" + el.name + "']");
      $(textBox).prop("disabled", $(el).prop("checked"));
      if ( $(el).prop("checked") ) {
        textBox.val("CLOSED");
      } else {
        textBox.val("");
      }
    });

    this.$("input.day").keyup(function(ev) {
      $(ev.target).closest("tr").next("tr.dayError").remove();
    });
  },

  saveForm: function() {
    // var self = this;
    var servicePromises = [];
    var formValues = this.$('#facilityForm').serializeObject();
    if ( formValues.gender === "" ) {
      formValues.gender = null;
    }

    if ( this.$("#age_everyone").prop('checked') ) {
      formValues.age = null;
    } else {
      var ages = _.map(this.$("[name=age]input:checked"), function(cb) {
        return $(cb).attr('value');
      });

      ages = _(ages).compact();
      formValues.age = ages;
    }

    var oldServices = _.clone(formValues.services);

    // _.each(formValues.services, function(service, i) {
    //   self.model.get("services")[i].set(service);
    // });

    delete formValues.services;
    this.model.set(formValues);

    var save = _.bind(saveFacility, this);
    save(this.model, oldServices, _.bind(modelSaveSuccessCallback, this), _.bind(modelSaveFailCallback, this));

  },

  render: function() {
    var hours = [];

    for(var idx = 0; idx <= 23; idx++) {
      if (idx < 10) { idx = '0' + idx; }
      hours.push(idx + ':00');
      hours.push(idx + ':30');
    }

    var templateData = this.model.presentJSON();
    templateData.services.forEach(function(service) {
      service.allHours = hours;
      service.days = days;
    });

    $(this.el).html(this.template({facility: templateData}));
    this.setupForm();
    return this;
  }
});

module.exports = EditView;
<|endoftext|>


<commit_before>
/** A simple class to manage a geometric object in XML3D. Elements to be inserted in the defs or
 * xml3d section can be added and removed. The object can be inserted and removed from the
 * document.
 *
 * -- Root Element --
 * Special is the root element. In GeoObject.graph["root"] the root element is placed. We want
 * this to have a unique interface for accessing the root node. Also when attaching the geometry
 * only the root node will be attached. All other elements in the graph attribute can be used
 * for storage. They will be detached from their parents during destruction.
 *
 * -- ID --
 * Each GeoObject has an ID. Storage in the defs and graph sections is addressed by local IDs.
 *
 * For example addShaders() or addTransforms() take local IDs, but construct elements with global
 * IDs, formed by the method globalID().
 */
XMOT.util.GeoObject = new XMOT.Class({

    /** Initializes the object.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string} _id the ID of this object
     *  @param {!Object} _xml3d the xml3d element in which the object will reside
     *  @param {!Object} [_rootGrp] the group to which this object is to be attached. If not given
     *              it will be appended to the given xml3d element.
     */
    initialize: function(_id, _xml3d, _rootGrp)
    {
        this.ID = _id;
        this.xml3d = _xml3d;
        this.defsRoot = XMOT.util.getOrCreateDefs(_xml3d);

        if(_rootGrp)
            this.rootGrp = _rootGrp;
        else
            this.rootGrp = _xml3d;

        this.defs = {};     // local IDs -> defs element
        this.graph = {}; // local IDs -> graph element. this.graph["root"] will hold the root node
    },

    /** Detaches the object and resets the defs and graph.
     *
     *  @this {XMOT.util.GeoObject}
     */
    destroy: function()
    {
        this.detach();

        this.defs = {};
        this.graph = {};
    },

    // ========================================================================
    // --- Attach/Detach ---
    // ========================================================================
    /** Add all defs elements to the defsRoot
     *
     *  @this {XMOT.util.GeoObject}
     */
    attachDefs: function()
    {
        this._appendChildren(this.defsRoot, this.defs);
    },

    /** Add the graph["root"] object to the root group
     *
     *  @this {XMOT.util.GeoObject}
     */
    attachGraph: function()
    {
        this.rootGrp.appendChild(this.graph["root"]);
    },

    /** Remove the graph and defs elements from the DOM.
     *
     *  @this {XMOT.util.GeoObject}
     */
    detach: function()
    {
        this._removeChildren(this.rootGrp, this.graph);
        this._removeChildren(this.defsRoot, this.defs);
    },

    // ========================================================================
    // --- Root Handling ---
    // ========================================================================
    /** Set the given node as the root node in the graph. This is the child node
     *  of this object's root group.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {!Object} rootNode
     */
    setGraphRoot: function(rootNode)
    {
        this.graph["root"] = rootNode;
    },

    /** Add the given array of children to the graph root, set previously by
     *  setGraphRoot().
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {Array.<Object>} children
     */
    addToGraphRoot: function(children)
    {
        if(!this.graph["root"])
            throw "XMOT.util.GeoObject: no root node present.";

        if(children.constructor !== Array)
            children = [children];

        for(var i = 0; i < children.length; i++)
            this.graph["root"].appendChild(children[i]);
    },

    /** Retrieve the graph root node.
     *
     *  @this {XMOT.util.GeoObject}
     *  @return {Object}
     */
    getGraphRoot: function()
    {
        return this.graph["root"];
    },

    // ========================================================================
    // --- Helpers ---
    // ========================================================================

    /** Convert a given id to a global one. This is done by prepending this object's
     *  id to the given id. This could be done without such a function, but it's
     *  pretty often used, so the encapsulation is useful.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string} id a local ID to be converted
     *  @return {string} the converted, global, ID
     */
    globalID: function(id)
    {
        return this.ID + "_" + id;
    },

    /** Creates phong shaders and adds them to the defs elements.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string|Array} IDs a single or array of local IDs for the shader.
     *  @param {Object} [opts] the options for XMOT.creation.phongShader()
     *
     *  The id of the created shaders will be set to global IDs. The options
     *  get applied to each of the given IDs.
     */
    addShaders: function(IDs, opts)
    {
        if(!opts)
            opts = {};

        if(IDs.constructor !== Array)
            IDs = [IDs];

        for(var i = 0; i < IDs.length; i++)
        {
            opts.id = this.globalID(IDs[i]);

            this.defs[IDs[i]] = XMOT.creation.phongShader(opts);
        }
    },

    /** Creates transform elements and adds them to the defs elements.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string|Array} IDs a single or array of local IDs for the transform elements
     *  @param {Object} [opts] the options for XMOT.creation.element()
     *
     *  The id of the created shaders will be set to global IDs. The options will
     *  be applied to each ID.
     */
    addTransforms: function(IDs, opts)
    {
        if(!opts)
            opts = {};

        if(IDs.constructor !== Array)
            IDs = [IDs];

        for(var i = 0; i < IDs.length; i++)
        {
            opts.id = this.globalID(IDs[i]);

            this.defs[IDs[i]] = XMOT.creation.element("transform", opts);
        }
    },

    /** Set the contents of the transform elements, that have the given local IDs,
     *  with the given options. So basically setting a lot of transforms to the same
     *  values with a single call.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string|Array} localIDs a single ID or an array of IDs
     *  @param {!Object} opts an object of options, supported: transl, scale, rot
     */
    updateTransforms: function(localIDs, opts)
    {
        if(localIDs.constructor !== Array)
            localIDs = [localIDs];

        var len = localIDs.length;
        for(var i = 0; i < len; i++)
        {
            var el = this.defs[localIDs[i]];
            if(!el)
                continue;

            if(opts.transl)
                el.setAttribute("translation", opts.transl);
            if(opts.scale)
                el.setAttribute("scale", opts.scale);
            if(opts.rot)
                el.setAttribute("rotation", opts.rot);
        }
    },

    // ========================================================================
    // --- Private ---
    // ========================================================================

    /** Append all children to the given element.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {!Object} targetEl
     *  @param {Array.<Object>} children
     */
    _appendChildren: function(targetEl, children)
    {
        for(var i in children)
            targetEl.appendChild(children[i]);
    },

    /** Remove all childen from the given element.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {!Object} targetEl
     *  @param {Array.<Object>} children
     */
    _removeChildren: function(targetEl, children)
    {
        for(var i in children)
            targetEl.removeChild(children[i]);
    }
});
<commit_msg>util-geoobject: added attach() method<commit_after>
/** A simple class to manage a geometric object in XML3D. Elements to be inserted in the defs or
 * xml3d section can be added and removed. The object can be inserted and removed from the
 * document.
 *
 * -- Root Element --
 * Special is the root element. In GeoObject.graph["root"] the root element is placed. We want
 * this to have a unique interface for accessing the root node. Also when attaching the geometry
 * only the root node will be attached. All other elements in the graph attribute can be used
 * for storage. They will be detached from their parents during destruction.
 *
 * -- ID --
 * Each GeoObject has an ID. Storage in the defs and graph sections is addressed by local IDs.
 *
 * For example addShaders() or addTransforms() take local IDs, but construct elements with global
 * IDs, formed by the method globalID().
 */
XMOT.util.GeoObject = new XMOT.Class({

    /** Initializes the object.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string} _id the ID of this object
     *  @param {!Object} _xml3d the xml3d element in which the object will reside
     *  @param {!Object} [_rootGrp] the group to which this object is to be attached. If not given
     *              it will be appended to the given xml3d element.
     */
    initialize: function(_id, _xml3d, _rootGrp)
    {
        this.ID = _id;
        this.xml3d = _xml3d;
        this.defsRoot = XMOT.util.getOrCreateDefs(_xml3d);

        if(_rootGrp)
            this.rootGrp = _rootGrp;
        else
            this.rootGrp = _xml3d;

        this.defs = {};     // local IDs -> defs element
        this.graph = {}; // local IDs -> graph element. this.graph["root"] will hold the root node
    },

    /** Detaches the object and resets the defs and graph.
     *
     *  @this {XMOT.util.GeoObject}
     */
    destroy: function()
    {
        this.detach();

        this.defs = {};
        this.graph = {};
    },

    // ========================================================================
    // --- Attach/Detach ---
    // ========================================================================
    /** Attach the defs elements and the graph. Alternatively attachDefs() and
     *  attachGraph() can be called seperately.
     *
     *  @this {XMOT.util.GeoObject}
     */
    attach: function()
    {
    	this.attachDefs();
    	this.attachGraph();
    },

    /** Remove the graph and defs elements from the DOM.
     *
     *  @this {XMOT.util.GeoObject}
     */
    detach: function()
    {
        this._removeChildren(this.rootGrp, this.graph);
        this._removeChildren(this.defsRoot, this.defs);
    },

    /** Add all defs elements to the defsRoot
     *
     *  @this {XMOT.util.GeoObject}
     */
    attachDefs: function()
    {
        this._appendChildren(this.defsRoot, this.defs);
    },

    /** Add the graph["root"] object to the root group
     *
     *  @this {XMOT.util.GeoObject}
     */
    attachGraph: function()
    {
        this.rootGrp.appendChild(this.graph["root"]);
    },

    // ========================================================================
    // --- Root Handling ---
    // ========================================================================
    /** Set the given node as the root node in the graph. This is the child node
     *  of this object's root group.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {!Object} rootNode
     */
    setGraphRoot: function(rootNode)
    {
        this.graph["root"] = rootNode;
    },

    /** Add the given array of children to the graph root, set previously by
     *  setGraphRoot().
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {Array.<Object>} children
     */
    addToGraphRoot: function(children)
    {
        if(!this.graph["root"])
            throw "XMOT.util.GeoObject: no root node present.";

        if(children.constructor !== Array)
            children = [children];

        for(var i = 0; i < children.length; i++)
            this.graph["root"].appendChild(children[i]);
    },

    /** Retrieve the graph root node.
     *
     *  @this {XMOT.util.GeoObject}
     *  @return {Object}
     */
    getGraphRoot: function()
    {
        return this.graph["root"];
    },

    // ========================================================================
    // --- Helpers ---
    // ========================================================================

    /** Convert a given id to a global one. This is done by prepending this object's
     *  id to the given id. This could be done without such a function, but it's
     *  pretty often used, so the encapsulation is useful.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string} id a local ID to be converted
     *  @return {string} the converted, global, ID
     */
    globalID: function(id)
    {
        return this.ID + "_" + id;
    },

    /** Creates phong shaders and adds them to the defs elements.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string|Array} IDs a single or array of local IDs for the shader.
     *  @param {Object} [opts] the options for XMOT.creation.phongShader()
     *
     *  The id of the created shaders will be set to global IDs. The options
     *  get applied to each of the given IDs.
     */
    addShaders: function(IDs, opts)
    {
        if(!opts)
            opts = {};

        if(IDs.constructor !== Array)
            IDs = [IDs];

        for(var i = 0; i < IDs.length; i++)
        {
            opts.id = this.globalID(IDs[i]);

            this.defs[IDs[i]] = XMOT.creation.phongShader(opts);
        }
    },

    /** Creates transform elements and adds them to the defs elements.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string|Array} IDs a single or array of local IDs for the transform elements
     *  @param {Object} [opts] the options for XMOT.creation.element()
     *
     *  The id of the created shaders will be set to global IDs. The options will
     *  be applied to each ID.
     */
    addTransforms: function(IDs, opts)
    {
        if(!opts)
            opts = {};

        if(IDs.constructor !== Array)
            IDs = [IDs];

        for(var i = 0; i < IDs.length; i++)
        {
            opts.id = this.globalID(IDs[i]);

            this.defs[IDs[i]] = XMOT.creation.element("transform", opts);
        }
    },

    /** Set the contents of the transform elements, that have the given local IDs,
     *  with the given options. So basically setting a lot of transforms to the same
     *  values with a single call.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {string|Array} localIDs a single ID or an array of IDs
     *  @param {!Object} opts an object of options, supported: transl, scale, rot
     */
    updateTransforms: function(localIDs, opts)
    {
        if(localIDs.constructor !== Array)
            localIDs = [localIDs];

        var len = localIDs.length;
        for(var i = 0; i < len; i++)
        {
            var el = this.defs[localIDs[i]];
            if(!el)
                continue;

            if(opts.transl)
                el.setAttribute("translation", opts.transl);
            if(opts.scale)
                el.setAttribute("scale", opts.scale);
            if(opts.rot)
                el.setAttribute("rotation", opts.rot);
        }
    },

    // ========================================================================
    // --- Private ---
    // ========================================================================

    /** Append all children to the given element.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {!Object} targetEl
     *  @param {Array.<Object>} children
     */
    _appendChildren: function(targetEl, children)
    {
        for(var i in children)
            targetEl.appendChild(children[i]);
    },

    /** Remove all childen from the given element.
     *
     *  @this {XMOT.util.GeoObject}
     *  @param {!Object} targetEl
     *  @param {Array.<Object>} children
     */
    _removeChildren: function(targetEl, children)
    {
        for(var i in children)
            targetEl.removeChild(children[i]);
    }
});
<|endoftext|>


<commit_before>// d3 margin convention
// http://bl.ocks.org/mbostock/3019563
var margin = {
  top: 50,
  right: 50,
  bottom: 50,
  left: 50
};

var width = 960 - margin.left - margin.right;
var height = 300 - margin.bottom - margin.top;

var bbVis = {
  x: 100,
  y: 10,
  w: width - 100,
  h: 200
}

var agencies = [];
var color = d3.scale.category10();

var svg = d3.select('body')
  .append('svg')
  .attr('height', height + margin.top + margin.bottom)
  .attr('width', width + margin.left + margin.right)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ','
    + margin.right + ')')

d3.csv('population-data.csv', function(data) {
  color
    .domain(d3.keys(data[0])
      .filter(function(key) {
        return key !== 'year';
      })
    );

  agencies = color.domain().map(function(agency) {
    return {
      agency: agency,
      values: data.map(function(d) {
        return {
          year: parseInt(d.year),
          est: +d[agency] // unary operator to turn string into int
        };
      })
    }
  });

  return createVis();
});

var createVis = function() {

  var xScale = d3.scale.linear()
    .domain([0, d3.max(agencies, function(agency, i) {
      var max = d3.max(agency.values, function(d) {
        return d.year;
      })
      return max;
    })])
    .range([0, bbVis.w]);

  var yScale = d3.scale.linear()
    // find max value by iterating through all agencies
    // and finding max value in each,
    // then find max value of all the maxes;
    // the key: nested d3.max()
    .domain([0, d3.max(agencies, function(agency, i) {
      var max = d3.max(agency.values, function(d) {
        return d.est;
      })
      return max;
    })])
    .range([bbVis.h, 0]);

  var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient('bottom')

  var yAxis = d3.svg.axis()
    .scale(yScale)
    .ticks(5)
    .orient('left')

  // place x-axis
  svg
    .append('g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(40,' + bbVis.h + ')')
    .call(xAxis)

  // place y-axis
  svg
    .append('g')
    .attr('class', 'y axis')
    .attr('transform', 'translate(40, 0)')
    .call(yAxis)

  var line = d3.svg.line()
    .x(function(d) {
      return xScale(d.year);
    })
    .y(function(d) {
      return yScale(d.est);
    })

  // put dots on the graph for pop estimates
  var agency = svg.selectAll('.agency')
    .data(agencies)
    .enter()
      .append('g')
      .attr('class', 'agency')

  agency
    .append('path')
    .attr('class', 'line')
    .attr('d', function(d) {
      return line(d.values);
    })
    .style('stroke', function(d) {
      return color(d.agency)
    })
    .style('stroke-width', '1.5px');

  // iterate through all 5 agencies,
  // add circle elments classed to name of agency
  for (var i = 0; i < agencies.length; i++) {
    //console.log(i);
    svg
      .selectAll('.' + agencies[i].agency)
      .data(agencies[i].values)
      .enter()
        .append('circle')
        .attr('class', agencies[i].agency)
        .attr('r', 3)
        .attr('cx', function(d) {
          return xScale(d.year);
        })
        .attr('cy', function(d) {
          return yScale(d.est);
        })
        .style('fill', function(d) {
          return color(agencies[i].agency);
        })
  }

  var visFrame = svg.append('g')
    .attr('transform', 'translate(' + bbVis.x + ','
      + (bbVis.y + bbVis.h) + ')');
    // ...

  visFrame.append('rect')
    //.attr('fill', 'cadetblue')
    //.attr('width', 100)
    //.attr('height', 100)
    // ...

} // end createVis()
<commit_msg>removes data points whose value is 0<commit_after>// d3 margin convention
// http://bl.ocks.org/mbostock/3019563
var margin = {
  top: 50,
  right: 50,
  bottom: 50,
  left: 50
};

var width = 960 - margin.left - margin.right;
var height = 300 - margin.bottom - margin.top;

var bbVis = {
  x: 100,
  y: 10,
  w: width - 100,
  h: 200
}

var agencies = [];
var color = d3.scale.category10();

var svg = d3.select('body')
  .append('svg')
  .attr('height', height + margin.top + margin.bottom)
  .attr('width', width + margin.left + margin.right)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ','
    + margin.right + ')')

d3.csv('population-data.csv', function(data) {
  color
    .domain(d3.keys(data[0])
      .filter(function(key) {
        return key !== 'year';
      })
    );

  agencies = color.domain().map(function(agency) {
    return {
      agency: agency,
      values: data.map(function(d) {
        return {
          year: parseInt(d.year),
          est: +d[agency] // unary operator to turn string into int
        };
      })
    }
  });

  return createVis();
});

var createVis = function() {

  var xScale = d3.scale.linear()
    .domain([0, d3.max(agencies, function(agency, i) {
      var max = d3.max(agency.values, function(d) {
        return d.year;
      })
      return max;
    })])
    .range([0, bbVis.w]);

  var yScale = d3.scale.linear()
    // find max value by iterating through all agencies
    // and finding max value in each,
    // then find max value of all the maxes;
    // the key: nested d3.max()
    .domain([0, d3.max(agencies, function(agency, i) {
      var max = d3.max(agency.values, function(d) {
        return d.est;
      })
      return max;
    })])
    .range([bbVis.h, 0]);

  var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient('bottom')

  var yAxis = d3.svg.axis()
    .scale(yScale)
    .ticks(5)
    .orient('left')

  // place x-axis
  svg
    .append('g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(40,' + bbVis.h + ')')
    .call(xAxis)

  // place y-axis
  svg
    .append('g')
    .attr('class', 'y axis')
    .attr('transform', 'translate(40, 0)')
    .call(yAxis)

  var line = d3.svg.line()
    .x(function(d) {
      return xScale(d.year);
    })
    .y(function(d) {
      return yScale(d.est);
    })

  // put dots on the graph for pop estimates
  var agency = svg.selectAll('.agency')
    .data(agencies)
    .enter()
      .append('g')
      .attr('class', 'agency')

  agency
    .append('path')
    .attr('class', 'line')
    .attr('d', function(d, i) {
      //console.log(d.values, i);
      //for (var i = 0; i < d.values.length; i++) {
      //  if (d.values[i].est !== 0) {
      //    return line(d.values)
      //  }
      //  //console.log(d.values[i].est);
      //}
      //console.log(d.values.length);
      //var firstYearWithData;
      //var c = 0;
      //while (c < d.values.length) {
        //if (d.values[c].year !== 0) {
          //firstYearWithData = d.values[c].year;
          //break;
        //}
        //c++;
      //}

      return line(d.values);
    })
    .style('stroke', function(d) {
      return color(d.agency)
    })
    .style('stroke-width', '1.5px');

  // iterate through all 5 agencies,
  // add circle elments classed to name of agency
  for (var i = 0; i < agencies.length; i++) {
    //console.log(i);
    svg
      .selectAll('.' + agencies[i].agency)
      .data(agencies[i].values)
      .enter()
        .append('circle')
        .attr('class', agencies[i].agency)
        .attr('r', function(d) {
          // hide circles whose bound estimate is 0
          if (d.est) {
            return 2;
          }
          //console.log(d.est);
        })
        .attr('cx', function(d) {
          return xScale(d.year);
        })
        .attr('cy', function(d) {
          return yScale(d.est);
        })
        .style('fill', function(d) {
          return color(agencies[i].agency);
        })
  }

  var visFrame = svg.append('g')
    .attr('transform', 'translate(' + bbVis.x + ','
      + (bbVis.y + bbVis.h) + ')');
    // ...

  visFrame.append('rect')
    //.attr('fill', 'cadetblue')
    //.attr('width', 100)
    //.attr('height', 100)
    // ...

} // end createVis()
<|endoftext|>


<commit_before>/* eslint-env node */
module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    'Chrome': {
      "mode": "ci",
      "args": [
        '--disable-gpu',
        '--headless',
        '--remote-debugging-port=9222',
        '--window-size=1440,900'
      ]
    },
  }
};
<commit_msg>Cleaning up quotes<commit_after>/* eslint-env node */
module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: {
      mode: 'ci',
      args: [
        '--disable-gpu',
        '--headless',
        '--remote-debugging-port=9222',
        '--window-size=1440,900'
      ]
    },
  }
};
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var common = require('../modules/common-functions');
var INELIGIBLE_OUTCOMES = require('../modules/constants').INELIGIBLE_OUTCOMES;

module.exports = {
  'Loop through eligible categories': function(client) {
    INELIGIBLE_OUTCOMES.forEach(function(item) {
      common.startPage(client);
      client
        .waitForElementVisible('form[action="/problem"]', 2000)
        .assert.urlContains('/problem')
        .click(util.format('input[name="categories"][value="%s"]', item.category.value))
        .submitForm('form')
        .waitForElementVisible('form[action="/about"]', 2000)
        .assert.urlContains('/about')
      ;
      common.aboutPageSetAllToNo(client);
      common.setYesNoFields(client, 'have_savings', 1);
      client
        .submitForm('form')
        .waitForElementVisible('form[action="/savings"]', 2000)
        .assert.urlContains('/savings')
        .setValue('input[name="savings"]', '50000')
        .setValue('input[name="investments"]', '50000')
        .submitForm('form')
        .waitForElementVisible('a[href="https://www.gov.uk/find-a-legal-adviser"]', 2000)
        .assert.urlContains('/help-organisations/' + item.category.label.toLowerCase().replace(/ /g, '-'))

        .assert.containsText('.org-list ul', item.link.text)

        // skipping this assertion for now as the data is iffy at present
        // .useXpath()
        // .assert.elementPresent(util.format('//div[@class="org-list"]/ul/li/a[@href="%s"]', encodeURI(item.link.href)))
        // .useCss()
      ;
    });

    client.end();
  }

};
<commit_msg>Fix tests<commit_after>'use strict';

var util = require('util');
var common = require('../modules/common-functions');
var INELIGIBLE_OUTCOMES = require('../modules/constants').INELIGIBLE_OUTCOMES;

module.exports = {
  'Loop through eligible categories': function(client) {
    INELIGIBLE_OUTCOMES.forEach(function(item) {
      common.startPage(client);
      client
        .waitForElementVisible('form[action="/problem"]', 2000)
        .assert.urlContains('/problem')
        .click(util.format('input[name="categories"][value="%s"]', item.category.value))
        .submitForm('form')
        .waitForElementVisible('form[action="/about"]', 2000)
        .assert.urlContains('/about')
      ;
      common.aboutPageSetAllToNo(client);
      common.setYesNoFields(client, 'have_savings', 1);
      client
        .submitForm('form')
        .waitForElementVisible('form[action="/savings"]', 2000)
        .assert.urlContains('/savings')
        .setValue('input[name="savings"]', '50000')
        .setValue('input[name="investments"]', '50000')
        .submitForm('form')
        .waitForElementVisible('a[href="https://www.gov.uk/find-a-legal-adviser"]', 2000)
        .assert.urlContains('/help-organisations/' + item.category.label.toLowerCase().replace(/ /g, '-'))

        .assert.containsText('.help-organisations ul', item.link.text)

        // skipping this assertion for now as the data is iffy at present
        // .useXpath()
        // .assert.elementPresent(util.format('//div[@class="org-list"]/ul/li/a[@href="%s"]', encodeURI(item.link.href)))
        // .useCss()
      ;
    });

    client.end();
  }

};
<|endoftext|>