<commit_before>/*global io*/

// TODO:
//  include socket.io
//  grab on submit and cancel, get values
//  client-side protocol
//  show errors

jQuery.extend({
    getQueryParameters : function(str) {
        return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
    }
});

(function ($) {
    var $url = $("#url")
    ,   $profile = $("#profile")
    ,   $profileOptions = $('#profile option')
    ,   $validation = $("#validation")
    ,   $noRecTrack = $("#noRecTrack")
    ,   $informativeOnly = $("#informativeOnly")
    ,   $echidnaReady = $("#echidnaReady")
    ,   $patentPolicy = $("#patentPolicy")
    ,   $processDocument = $("#processDocument")
    ,   $alert = $("#alert")
    ,   $results = $("#results")
    ,   $resultsBody = $results.find("table")
    ,   $progressContainer = $("#progressBar")
    ,   $progress = $progressContainer.find(".progress-bar")
    ,   $progressStyler = $progress.parent()
    ,   socket = io(location.protocol + "//" + location.host, {path: '/' + location.pathname.substring(1) + 'socket.io'})
    ,   $summary = $("#summary")
    ,   rows = {}
    ,   done = 0
    ,   total = 0
    ,   summary = {}
    ,   friendlyNames = {headers: 'Headers'
        , style: 'Style'
        , sotd: 'Status of this document'
        , echidna: 'Echidna'
        , structure: 'Structure'
        , links: 'Links'
        , heuristic: 'Heuristics'
        , validation: 'Validation'
        }
    ,   levels = {done: 0, info: 1, warning: 2, error: 3}
    ,   icons = {done: '\u2714', info: '\u2714', warning: '\u2714', error: '\u2718'}
    ;

    // handshake
    socket.on("handshake", function (data) {
        console.log("Using version", data.version);
        $(".navbar-brand small").remove();
        $('head title').text($('head title').text() + ' ' + data.version);
        $('.navbar-brand').append(' ' + data.version);
    });

    // show errors
    function showError (string) {
        $alert.clone()
              .find("span")
                .text(string)
              .end()
              .removeClass("hide")
              .insertAfter($alert);
    }

    // clear errors
    function clearError () {
        $('.alert:not(\'#about\')').filter(":not('.hide')")
                   .remove();
    }

    // show progress
    function progress () {
        $progress.attr({
            "aria-valuenow":    done
        ,   "aria-valuemax":    total
        ,   "style":            "width: " + (total ? (done/total)*100 : 0) + "%"
        });
        $progress.text(done + '/' + total);
    }

    // validate
    function validate (options) {
        $resultsBody.find("tr:not(.h)").remove();
        socket.emit("validate", {
            url:                decodeURIComponent(options.url)
        ,   profile:            options.profile
        ,   validation:         options.validation
        ,   noRecTrack:         (true === options.noRecTrack)
        ,   informativeOnly:    (true === options.informativeOnly)
        ,   echidnaReady:       (true === options.echidnaReady)
        ,   patentPolicy:       options.patentPolicy
        ,   processDocument:    options.processDocument
        });
    }

    // extractMetadata
    function extractMetadata (url) {
        socket.emit("extractMetadata", {
            url: decodeURIComponent(url)
        });
    }

    // terminate validation
    function endValidation () {
        $progressContainer.hide();
    }

    // handle results
    function row (id, wording) {
        if (rows[id]) return rows[id];
        rows[id] =  $("

")
                        .find(".test")
                          .text(id)
                        .end()
                        .appendTo($resultsBody)
        ;
        return rows[id];
    }
    var type2class = {
        error:      "text-danger"
    ,   warning:    "text-warning"
    ,   info:       "text-info"
    };
    var type2bgclass = {
        error:      "bg-danger"
    ,   warning:    "bg-warning"
    ,   info:       "bg-info"
    };
    function addMessage ($row, type, msg, wording) {
        var $ul = $row.find("ul." + type, wording);
        if (!$ul.length) $ul = $("

").addClass(type).appendTo($row.find(".results"));
        $('' + type + ' ').prependTo($("

")
            .addClass(type2class[type])
            .html(' ' + msg)
            .appendTo($ul));
    }

    // protocol
    socket.on("exception", function (data) {
        console.log("exception", data);
        showError("Exception: " + data.message);
        endValidation();
    });
    socket.on("start", function (data) {
        console.log("start", data);
        rows = {};
        for (var i = 0, n = data.rules.length; i < n; i++) row(data.rules[i]);
        done = 0;
        total = data.rules.length;
        $progressStyler.addClass("active progress-striped");
        progress();
        $progressContainer.fadeIn();
        $results.fadeIn();
        resetSummary();
        $summary.show();
    });
    socket.on("ok", function (data) {
        console.log("ok", data);
        row(data.name)
            .find(".status")
                .append("\u2714 ok")
            .end()
            .find(".results")
                .prepend("Ok")
            .end();
    });
    socket.on("warning", function (data) {
        updateSummary(data, 'warning');
        addMessage(row(data.name), "warning", data.message, data.wording);
    });
    socket.on('info', function (data) {
        updateSummary(data, 'info');
        addMessage(row(data.name), 'info', data.message, data.wording);
    });
    socket.on("err", function (data) {
        updateSummary(data, 'error');
        var $row = row(data.name);
        addMessage(row(data.name), "error", data.message, data.wording);
        if (!$row.find(".status .text-danger").length) {
            $row
                .find(".status")
                    .append("\u2718 fail")
                .end();
        }
    });
    socket.on("done", function (data) {
        updateSummary(data, 'done');
        done++;
        progress();
    });
    socket.on("finished", function () {
        console.log("END");
        $progressStyler.removeClass("active progress-striped");
        $progressContainer.hide();
        $progress.text('Done!');
        attachCustomScroll();
        // endValidation();
    });
    socket.on("finishedExtraction", function (data) {
      $(".manual").toggle(true);
      var processDocument = (data.processdocument && data.processDocument.indexOf('Process-20051014') > -1) ? "2005" : "2015";
      $profile.val(data.profile);
      $processDocument.find("label#2005").toggleClass("active", (processDocument === "2005"));
      $processDocument.find("label#2015").toggleClass("active", (processDocument === "2015"));
      $noRecTrack.prop('checked', !data.rectrack);
      $informativeOnly.prop('checked', data.informativeOnly);
      var options = {
                        "url"             : data.url
                      , "profile"         : data.profile
                      , "validation"      : true
                      , "noRecTrack"      : !data.rectrack || false
                      , "informativeOnly" : data.informativeOnly || false
                      , "echidnaReady"    : false
                      , "patentPolicy"    : "pp2004"
                      , "processDocument" : processDocument
                    };
      validate(options);
      var newurl = document.URL.split('?')[0] + "?" + $.param(options)
      history.pushState(options, url + " - " + profile, newurl);
    });

    // handle the form
    $("#options").submit(function () {
        clearError();
        if ($profile.val() === "auto") {
            extractMetadata($url.val());
        } else {
            var url = $url.val()
            ,   profile = $profile.val()
            ,   validation = $validation.val()
            ,   noRecTrack = $noRecTrack.is(":checked") || false
            ,   informativeOnly = $informativeOnly.is(":checked") || false
            ,   echidnaReady = $echidnaReady.is(":checked") || false
            ,   patentPolicy = $patentPolicy.find('label.active').attr('id')
            ,   processDocument = $processDocument.find('label.active').attr('id')
            ;
            if (!url) showError("Missing URL parameter.");
            if (!profile) showError("Missing profile parameter.");
            if (echidnaReady) profile += '-Echidna';
            var options = {
                              "url"             : url
                            , "profile"         : profile
                            , "validation"      : validation
                            , "noRecTrack"      : noRecTrack
                            , "informativeOnly" : informativeOnly
                            , "echidnaReady"    : echidnaReady
                            , "patentPolicy"    : patentPolicy
                            , "processDocument" : processDocument
                          };
            validate(options);
            var newurl = document.URL.split('?')[0] + "?" + $.param(options)
            history.pushState(options, url + " - " + profile, newurl);
        }
        return false;
    });

    function resetSummary() {
        $summary.find('.panel-body').empty();
        summary = {};
    }

    function updateSummary(data, level) {

      var id
      ,   status;

      if(data && data.name) {
        id = data.name.split('.')[0];

        if(summary.hasOwnProperty(id)) {
          status = summary[id];
        }
        else {
          status = {current: -1, count: 0};
          summary[id] = status;
          $('
 ' + friendlyNames[id] + '
')
            .appendTo($summary.find('.panel-body'));
        }

        if(levels[level] > status['current']) {
          summary[id]['current'] = levels[level];
          $summary.find('p#link-' + id).find('> span.icon').text(icons[level]);
        }

        if(levels[level] > 2) {
          summary[id]['count'] = summary[id]['count'] + 1;
          $summary.find('p#link-' + id + ' > a > span.badge').text(status['count'] + '');
        }

      }

    }

    function attachCustomScroll() {

      $summary.find('a').click(function() {
        var location = $(this).attr("href")
        ,   offset = $(location).offset().top;
        $("body").scrollTop(offset-50);
        return false;
      });

    }

    function disableProfilesIfNeeded(checkbox) {
        if (checkbox.prop('checked')) {
            $profileOptions.each(function (_, el) {
                if ($(el).val() !== 'WD' && $(el).val() !== 'WG-NOTE')
                  $(el).prop('disabled', true);
            });
            if ($profile.val() !== 'WD' && $(el).val() !== 'WG-NOTE')
              $profile.val('');
        }
        else $profileOptions.each(function (_, el) {
            if ($(el).val() !== '') $(el).prop('disabled', false);
        });
    }

    function disableProcessIfNeeded(profile) {
        var isFPCR = (profile.val() === "FPCR");
        if (isFPCR) {
            $processDocument.find("label#2005").toggleClass("active", !isFPCR);
            $processDocument.find("label#2015").toggleClass("active", isFPCR);
        }
        $processDocument.find("label#2005").toggleClass("disabled", isFPCR);
    }

    function setFormParams(options) {
        // Option "echidnaReady" processed first, as it may restrict the list of enabled profiles.
        if (options.echidnaReady === "true") $echidnaReady.prop('checked', true);
        if (options.url) $url.val(decodeURIComponent(options.url));
        // "profile" might be eg "WD-Echidna". Normalise.
        if (options.profile) {
          var newProfile = options.profile;
          if (newProfile.indexOf('-Echidna') > -1) {
            newProfile = newProfile.substring(0, newProfile.indexOf('-Echidna'));
          }
          $profile.find('option[value=' + newProfile + ']').prop('selected', true);
          disableProcessIfNeeded($profile);
        }
        if (options.validation) $validation.val(options.validation);
        if (options.noRecTrack === "true") $noRecTrack.prop('checked', true);
        if (options.informativeOnly === "true") $informativeOnly.prop('checked', true);
        if (options.processDocument) {
          $processDocument.find('label').removeClass('active');
          $processDocument.find('label#' + options.processDocument).addClass('active');
        }
        if (options.patentPolicy) {
          $patentPolicy.find('label').removeClass('active');
          $patentPolicy.find('label#' + options.patentPolicy).addClass('active');
        }
    }

    window.addEventListener('popstate', function(event) {
        var options = event.state;
        if (options == null) return;
        setFormParams(options);
        validate(options);
    });

    $patentPolicy.find("label").on("click", function() {
        var isPP2002 = ($(this).attr("id") === "pp2002");
        $noRecTrack.prop("disabled", isPP2002);
        $informativeOnly.prop("disabled", isPP2002);
    });

    $profile.change(function() {
        var profile = $(this);
        $(".manual").toggle(profile.val() !== 'auto');
        disableProcessIfNeeded(profile);
    });

    $echidnaReady.change(function () {
        disableProfilesIfNeeded($echidnaReady);
    });

    $(document).ready(function() {
        $.getJSON('data/profiles.json', function(data) {
            $profile.append($('<option value="auto">Auto-detect</option>'));
            $.each(data.tracks, function(foo, track) {
                optgroup = $('<optgroup label="' + track.name + '"></optgroup>');
                $.each(track.profiles, function(bar, profile) {
                    var option = $('<option value="' + profile.id + '">' + profile.id + ' — ' + profile.name + '</option>');
                    optgroup.append(option);
                });
                $profile.append(optgroup);
            });
            $profileOptions = $('#profile option');
            $(".manual").toggle();
            var options = $.getQueryParameters();
            setFormParams(options);
            if (options.url && options.profile) validate(options);
        });
    });

}(jQuery));
<commit_msg>bug fix on form options<commit_after>/*global io*/

// TODO:
//  include socket.io
//  grab on submit and cancel, get values
//  client-side protocol
//  show errors

jQuery.extend({
    getQueryParameters : function(str) {
        return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
    }
});

(function ($) {
    var $url = $("#url")
    ,   $profile = $("#profile")
    ,   $profileOptions = $('#profile option')
    ,   $validation = $("#validation")
    ,   $noRecTrack = $("#noRecTrack")
    ,   $informativeOnly = $("#informativeOnly")
    ,   $echidnaReady = $("#echidnaReady")
    ,   $patentPolicy = $("#patentPolicy")
    ,   $processDocument = $("#processDocument")
    ,   $alert = $("#alert")
    ,   $results = $("#results")
    ,   $resultsBody = $results.find("table")
    ,   $progressContainer = $("#progressBar")
    ,   $progress = $progressContainer.find(".progress-bar")
    ,   $progressStyler = $progress.parent()
    ,   socket = io(location.protocol + "//" + location.host, {path: '/' + location.pathname.substring(1) + 'socket.io'})
    ,   $summary = $("#summary")
    ,   rows = {}
    ,   done = 0
    ,   total = 0
    ,   summary = {}
    ,   friendlyNames = {headers: 'Headers'
        , style: 'Style'
        , sotd: 'Status of this document'
        , echidna: 'Echidna'
        , structure: 'Structure'
        , links: 'Links'
        , heuristic: 'Heuristics'
        , validation: 'Validation'
        }
    ,   levels = {done: 0, info: 1, warning: 2, error: 3}
    ,   icons = {done: '\u2714', info: '\u2714', warning: '\u2714', error: '\u2718'}
    ;

    // handshake
    socket.on("handshake", function (data) {
        console.log("Using version", data.version);
        $(".navbar-brand small").remove();
        $('head title').text($('head title').text() + ' ' + data.version);
        $('.navbar-brand').append(' ' + data.version);
    });

    // show errors
    function showError (string) {
        $alert.clone()
              .find("span")
                .text(string)
              .end()
              .removeClass("hide")
              .insertAfter($alert);
    }

    // clear errors
    function clearError () {
        $('.alert:not(\'#about\')').filter(":not('.hide')")
                   .remove();
    }

    // show progress
    function progress () {
        $progress.attr({
            "aria-valuenow":    done
        ,   "aria-valuemax":    total
        ,   "style":            "width: " + (total ? (done/total)*100 : 0) + "%"
        });
        $progress.text(done + '/' + total);
    }

    // validate
    function validate (options) {
        $resultsBody.find("tr:not(.h)").remove();
        socket.emit("validate", {
            url:                decodeURIComponent(options.url)
        ,   profile:            options.profile
        ,   validation:         options.validation
        ,   noRecTrack:         (true === options.noRecTrack)
        ,   informativeOnly:    (true === options.informativeOnly)
        ,   echidnaReady:       (true === options.echidnaReady)
        ,   patentPolicy:       options.patentPolicy
        ,   processDocument:    options.processDocument
        });
    }

    // extractMetadata
    function extractMetadata (url) {
        socket.emit("extractMetadata", {
            url: decodeURIComponent(url)
        });
    }

    // terminate validation
    function endValidation () {
        $progressContainer.hide();
    }

    // handle results
    function row (id, wording) {
        if (rows[id]) return rows[id];
        rows[id] =  $("

")
                        .find(".test")
                          .text(id)
                        .end()
                        .appendTo($resultsBody)
        ;
        return rows[id];
    }
    var type2class = {
        error:      "text-danger"
    ,   warning:    "text-warning"
    ,   info:       "text-info"
    };
    var type2bgclass = {
        error:      "bg-danger"
    ,   warning:    "bg-warning"
    ,   info:       "bg-info"
    };
    function addMessage ($row, type, msg, wording) {
        var $ul = $row.find("ul." + type, wording);
        if (!$ul.length) $ul = $("

").addClass(type).appendTo($row.find(".results"));
        $('' + type + ' ').prependTo($("

")
            .addClass(type2class[type])
            .html(' ' + msg)
            .appendTo($ul));
    }

    // protocol
    socket.on("exception", function (data) {
        console.log("exception", data);
        showError("Exception: " + data.message);
        endValidation();
    });
    socket.on("start", function (data) {
        console.log("start", data);
        rows = {};
        for (var i = 0, n = data.rules.length; i < n; i++) row(data.rules[i]);
        done = 0;
        total = data.rules.length;
        $progressStyler.addClass("active progress-striped");
        progress();
        $progressContainer.fadeIn();
        $results.fadeIn();
        resetSummary();
        $summary.show();
    });
    socket.on("ok", function (data) {
        console.log("ok", data);
        row(data.name)
            .find(".status")
                .append("\u2714 ok")
            .end()
            .find(".results")
                .prepend("Ok")
            .end();
    });
    socket.on("warning", function (data) {
        updateSummary(data, 'warning');
        addMessage(row(data.name), "warning", data.message, data.wording);
    });
    socket.on('info', function (data) {
        updateSummary(data, 'info');
        addMessage(row(data.name), 'info', data.message, data.wording);
    });
    socket.on("err", function (data) {
        updateSummary(data, 'error');
        var $row = row(data.name);
        addMessage(row(data.name), "error", data.message, data.wording);
        if (!$row.find(".status .text-danger").length) {
            $row
                .find(".status")
                    .append("\u2718 fail")
                .end();
        }
    });
    socket.on("done", function (data) {
        updateSummary(data, 'done');
        done++;
        progress();
    });
    socket.on("finished", function () {
        console.log("END");
        $progressStyler.removeClass("active progress-striped");
        $progressContainer.hide();
        $progress.text('Done!');
        attachCustomScroll();
        // endValidation();
    });
    socket.on("finishedExtraction", function (data) {
      $(".manual").toggle(true);
      var processDocument = (data.processdocument && data.processDocument.indexOf('Process-20051014') > -1) ? "2005" : "2015";
      $profile.val(data.profile);
      $processDocument.find("label#2005").toggleClass("active", (processDocument === "2005"));
      $processDocument.find("label#2015").toggleClass("active", (processDocument === "2015"));
      $noRecTrack.prop('checked', !data.rectrack);
      $informativeOnly.prop('checked', data.informativeOnly);
      $validation.val('simple-validation');
      var options = {
                        "url"             : data.url
                      , "profile"         : data.profile
                      , "validation"      : 'simple-validation'
                      , "noRecTrack"      : !data.rectrack || false
                      , "informativeOnly" : data.informativeOnly || false
                      , "echidnaReady"    : false
                      , "patentPolicy"    : "pp2004"
                      , "processDocument" : processDocument
                    };
      validate(options);
      var newurl = document.URL.split('?')[0] + "?" + $.param(options)
      history.pushState(options, url + " - " + profile, newurl);
    });

    // handle the form
    $("#options").submit(function () {
        clearError();
        if ($profile.val() === "auto") {
            extractMetadata($url.val());
        } else {
            var url = $url.val()
            ,   profile = $profile.val()
            ,   validation = $validation.val()
            ,   noRecTrack = $noRecTrack.is(":checked") || false
            ,   informativeOnly = $informativeOnly.is(":checked") || false
            ,   echidnaReady = $echidnaReady.is(":checked") || false
            ,   patentPolicy = $patentPolicy.find('label.active').attr('id')
            ,   processDocument = $processDocument.find('label.active').attr('id')
            ;
            if (!url) showError("Missing URL parameter.");
            if (!profile) showError("Missing profile parameter.");
            if (echidnaReady) profile += '-Echidna';
            var options = {
                              "url"             : url
                            , "profile"         : profile
                            , "validation"      : validation
                            , "noRecTrack"      : noRecTrack
                            , "informativeOnly" : informativeOnly
                            , "echidnaReady"    : echidnaReady
                            , "patentPolicy"    : patentPolicy
                            , "processDocument" : processDocument
                          };
            validate(options);
            var newurl = document.URL.split('?')[0] + "?" + $.param(options)
            history.pushState(options, url + " - " + profile, newurl);
        }
        return false;
    });

    function resetSummary() {
        $summary.find('.panel-body').empty();
        summary = {};
    }

    function updateSummary(data, level) {

      var id
      ,   status;

      if(data && data.name) {
        id = data.name.split('.')[0];

        if(summary.hasOwnProperty(id)) {
          status = summary[id];
        }
        else {
          status = {current: -1, count: 0};
          summary[id] = status;
          $('
 ' + friendlyNames[id] + '
')
            .appendTo($summary.find('.panel-body'));
        }

        if(levels[level] > status['current']) {
          summary[id]['current'] = levels[level];
          $summary.find('p#link-' + id).find('> span.icon').text(icons[level]);
        }

        if(levels[level] > 2) {
          summary[id]['count'] = summary[id]['count'] + 1;
          $summary.find('p#link-' + id + ' > a > span.badge').text(status['count'] + '');
        }

      }

    }

    function attachCustomScroll() {

      $summary.find('a').click(function() {
        var location = $(this).attr("href")
        ,   offset = $(location).offset().top;
        $("body").scrollTop(offset-50);
        return false;
      });

    }

    function disableProfilesIfNeeded(checkbox) {
        if (checkbox.prop('checked')) {
            $profileOptions.each(function (_, el) {
                if ($(el).val() !== 'WD' && $(el).val() !== 'WG-NOTE')
                  $(el).prop('disabled', true);
            });
            if ($profile.val() !== 'WD' && $(el).val() !== 'WG-NOTE')
              $profile.val('');
        }
        else $profileOptions.each(function (_, el) {
            if ($(el).val() !== '') $(el).prop('disabled', false);
        });
    }

    function disableProcessIfNeeded(profile) {
        var isFPCR = (profile.val() === "FPCR");
        if (isFPCR) {
            $processDocument.find("label#2005").toggleClass("active", !isFPCR);
            $processDocument.find("label#2015").toggleClass("active", isFPCR);
        }
        $processDocument.find("label#2005").toggleClass("disabled", isFPCR);
    }

    function setFormParams(options) {
        // Option "echidnaReady" processed first, as it may restrict the list of enabled profiles.
        if (options.echidnaReady === "true") $echidnaReady.prop('checked', true);
        if (options.url) $url.val(decodeURIComponent(options.url));
        // "profile" might be eg "WD-Echidna". Normalise.
        if (options.profile) {
          var newProfile = options.profile;
          if (newProfile.indexOf('-Echidna') > -1) {
            newProfile = newProfile.substring(0, newProfile.indexOf('-Echidna'));
          }
          $profile.find('option[value=' + newProfile + ']').prop('selected', true);
          disableProcessIfNeeded($profile);
        }
        if (options.validation) $validation.val(options.validation);
        if (options.noRecTrack === "true") $noRecTrack.prop('checked', true);
        if (options.informativeOnly === "true") $informativeOnly.prop('checked', true);
        if (options.processDocument) {
          $processDocument.find('label').removeClass('active');
          $processDocument.find('label#' + options.processDocument).addClass('active');
        }
        if (options.patentPolicy) {
          $patentPolicy.find('label').removeClass('active');
          $patentPolicy.find('label#' + options.patentPolicy).addClass('active');
        }
    }

    window.addEventListener('popstate', function(event) {
        var options = event.state;
        if (options == null) return;
        setFormParams(options);
        validate(options);
    });

    $patentPolicy.find("label").on("click", function() {
        var isPP2002 = ($(this).attr("id") === "pp2002");
        $noRecTrack.prop("disabled", isPP2002);
        $informativeOnly.prop("disabled", isPP2002);
    });

    $profile.change(function() {
        var profile = $(this);
        $(".manual").toggle(profile.val() !== 'auto');
        disableProcessIfNeeded(profile);
    });

    $echidnaReady.change(function () {
        disableProfilesIfNeeded($echidnaReady);
    });

    $(document).ready(function() {
        $.getJSON('data/profiles.json', function(data) {
            $profile.append($('<option value="auto">Auto-detect</option>'));
            $.each(data.tracks, function(foo, track) {
                optgroup = $('<optgroup label="' + track.name + '"></optgroup>');
                $.each(track.profiles, function(bar, profile) {
                    var option = $('<option value="' + profile.id + '">' + profile.id + ' — ' + profile.name + '</option>');
                    optgroup.append(option);
                });
                $profile.append(optgroup);
            });
            $profileOptions = $('#profile option');
            var options = $.getQueryParameters();
            setFormParams(options);
            $(".manual").toggle($profile.val() !== 'auto');
            if (options.url && options.profile) validate(options);
        });
    });

}(jQuery));
<|endoftext|>


<commit_before>//@ts-check
const BookReader = /** @type {typeof import('../BookReader').default} */(window.BookReader);

class TextSelectionPlugin {

  constructor() {
    /**@type {PromiseLike<JQuery<HTMLElement>>} */
    this.djvuPagesPromise = null;
  }

  /**
   * @param {string} ocaid
   */
  init(ocaid) {
    this.djvuPagesPromise = $.ajax({
      type: "GET",
      url: `https://cors.archive.org/cors/${ocaid}/${ocaid}_djvu.xml`,
      dataType: "xml",

      error: function (e) {
        return undefined;
      }
    }).then(function (response) {
      const xmlMap = response;

      if (xmlMap != undefined) {
        return $(xmlMap).find("OBJECT");
      }
    });
  }

  /**
   * @param {number} index
   * @returns {Promise<HTMLElement>}
   */
  async getPageText(index) {
    return (await this.djvuPagesPromise)[index];
  }

  /**
   * @param {JQuery} $container
   */
  stopPageFlip($container){
    const $svg = $container.find('svg');
    $svg.on("mousedown", (event) => {
      if ($(event.target).is('text')) {
        event.stopPropagation();
        $container.one("mouseup", (event) => event.stopPropagation());
      }
    });
  }

  /**
   * @param {number} pageIndex
   * @param {JQuery} $container
   */
  async createTextLayer(pageIndex, $container) {
    const $svgLayers = $container.find('textSelctionSVG');
    if (!$svgLayers.length) {
      const XMLpage = await this.getPageText(pageIndex);
      const XMLwidth = $(XMLpage).attr("width");
      const XMLheight = $(XMLpage).attr("height");

      const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      svg.setAttribute("viewBox", "0 0 " + XMLwidth + " " + XMLheight);
      $container.append(svg);
      $(svg).addClass('textSelctionSVG');
      svg.setAttribute('preserveAspectRatio', 'none');
      $(svg).css({
        "width": "100%",
        "position": "absolute",
        "height": "100%",
        "top": "0",
        "left": "0",
      });

      $(XMLpage).find("LINE").each((i, line) => {
        const lineArr = $(line).find("WORD")
        for(i = 0; i < lineArr.length; i++) {
          const currWord = lineArr[i];
          // eslint-disable-next-line no-unused-vars
          const [left, bottom, right, top] = $(currWord).attr("coords").split(',').map(parseFloat);
          const textSvg = document.createElementNS("http://www.w3.org/2000/svg", "text");
          textSvg.setAttribute("x", left.toString());
          textSvg.setAttribute("y", bottom.toString());
          textSvg.setAttribute("font-size", (bottom - top).toString());
          textSvg.setAttribute("textLength", (right - left).toString());
          $(textSvg).css({
            "fill": "red",
            "cursor": "text",
          });
          const textNode = document.createTextNode(currWord.textContent);
          textSvg.append(textNode);
          svg.append(textSvg);
          if(i < lineArr.length - 1){
            const nextWord = lineArr[i + 1];
            // eslint-disable-next-line no-unused-vars
            const [leftNext, bottomNext, rightNext, topNext] = $(nextWord).attr("coords").split(',').map(parseFloat);
            const spaceSvg = document.createElementNS("http://www.w3.org/2000/svg", "text");
            spaceSvg.setAttribute("x", right.toString());
            spaceSvg.setAttribute("y", Math.max(bottom, bottomNext).toString());
            spaceSvg.setAttribute("font-size", (Math.max(bottom, bottomNext) - Math.min(top, topNext)).toString());
            spaceSvg.setAttribute("textLength", (leftNext - right).toString());
            $(spaceSvg).css({
              'white-space': 'pre',

            });
            const spaceTextNode = document.createTextNode(" ");
            spaceSvg.append(spaceTextNode);
            svg.append(spaceSvg);
          }
        }
      })
      this.stopPageFlip($container);
    }
  }
}

class BookreaderWithTextSelection extends BookReader {
  init() {
    if(this.enableTextSelection){
      this.enableTextSelection = true;
      const OCAID = this.bookId;
      this.textSelectionPlugin = new TextSelectionPlugin();
      this.textSelectionPlugin.init(OCAID);
    }
    super.init();
  }

  /**
   * @param {PageModel} page
   */
  _createPageContainer(page, styles = {}) {
    const $container = super._createPageContainer(page, styles);
    if(this.enableTextSelection){
      this.textSelectionPlugin.createTextLayer(page.index, $container);
    }
    return $container;
  }
}
window.BookReader = BookreaderWithTextSelection;<commit_msg>changed layer to have text element for each line and a tspan for each word or space. Added baseline<commit_after>//@ts-check
const BookReader = /** @type {typeof import('../BookReader').default} */(window.BookReader);

class TextSelectionPlugin {

  constructor() {
    /**@type {PromiseLike<JQuery<HTMLElement>>} */
    this.djvuPagesPromise = null;
  }

  /**
   * @param {string} ocaid
   */
  init(ocaid) {
    this.djvuPagesPromise = $.ajax({
      type: "GET",
      url: `https://cors.archive.org/cors/${ocaid}/${ocaid}_djvu.xml`,
      dataType: "xml",

      error: function (e) {
        return undefined;
      }
    }).then(function (response) {
      const xmlMap = response;

      if (xmlMap != undefined) {
        return $(xmlMap).find("OBJECT");
      }
    });
  }

  /**
   * @param {number} index
   * @returns {Promise<HTMLElement>}
   */
  async getPageText(index) {
    return (await this.djvuPagesPromise)[index];
  }

  /**
   * @param {JQuery} $container
   */
  stopPageFlip($container){
    const $svg = $container.find('svg');
    $svg.on("mousedown", (event) => {
      if ($(event.target).is('tspan')) {
        event.stopPropagation();
        $container.one("mouseup", (event) => event.stopPropagation());
      }
    });
  }

  /**
   * @param {number} pageIndex
   * @param {JQuery} $container
   */
  async createTextLayer(pageIndex, $container) {
    const $svgLayers = $container.find('textSelctionSVG');
    if (!$svgLayers.length) {
      const XMLpage = await this.getPageText(pageIndex);
      const XMLwidth = $(XMLpage).attr("width");
      const XMLheight = $(XMLpage).attr("height");

      const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      svg.setAttribute("viewBox", "0 0 " + XMLwidth + " " + XMLheight);
      $container.append(svg);
      $(svg).addClass('textSelctionSVG');
      svg.setAttribute('preserveAspectRatio', 'none');
      $(svg).css({
        "width": "100%",
        "position": "absolute",
        "height": "100%",
        "top": "0",
        "left": "0",
      });

      $(XMLpage).find("LINE").each((i, line) => {
        // adding text element for each line in the page
        const lineSvg = document.createElementNS("http://www.w3.org/2000/svg", "text");
        const lineArr = $(line).find("WORD");
        let [leftMin, bottomMax, rightMax, topMin] = [Infinity, 0, 0, Infinity];

        for(i = 0; i < lineArr.length; i++) {
          // adding tspan for each word in line
          const currWord = lineArr[i];
          // eslint-disable-next-line no-unused-vars
          const [left, bottom, right, top] = $(currWord).attr("coords").split(',').map(parseFloat);
          if(left < leftMin) leftMin = left;
          if(bottom > bottomMax) bottomMax = bottom;
          if(right > rightMax) rightMax = right;
          if(top < topMin) topMin = top;
          const wordTspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
          wordTspan.setAttribute("x", left.toString());
          wordTspan.setAttribute("textLength", (right - left).toString());
          const textNode = document.createTextNode(currWord.textContent);
          wordTspan.append(textNode);
          lineSvg.append(wordTspan);

          // adding spaces after words not at the end of the line
          if(i < lineArr.length - 1){
            const nextWord = lineArr[i + 1];
            // eslint-disable-next-line no-unused-vars
            const [leftNext, bottomNext, rightNext, topNext] = $(nextWord).attr("coords").split(',').map(parseFloat);
            const spaceTspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
            spaceTspan.setAttribute("x", right.toString());
            spaceTspan.setAttribute("textLength", (leftNext - right).toString());
            const spaceTextNode = document.createTextNode(" ");
            spaceTspan.append(spaceTextNode);
            lineSvg.append(spaceTspan);
          }
        }
        lineSvg.setAttribute("x", leftMin.toString());
        lineSvg.setAttribute("y", bottomMax.toString());
        lineSvg.setAttribute("font-size", (bottomMax - topMin).toString());
        lineSvg.setAttribute("textLength", (rightMax - leftMin).toString());
        $(lineSvg).css({
          "fill": "red",
          "cursor": "text",
          'white-space': 'pre',
          "dominant-baseline": "text-after-edge",
          // "fill-opacity": "0",
        });
        svg.append(lineSvg);
      })
      this.stopPageFlip($container);
    }
  }
}

class BookreaderWithTextSelection extends BookReader {
  init() {
    if(this.enableTextSelection){
      this.enableTextSelection = true;
      const OCAID = this.bookId;
      this.textSelectionPlugin = new TextSelectionPlugin();
      this.textSelectionPlugin.init(OCAID);
    }
    super.init();
  }

  /**
   * @param {PageModel} page
   */
  _createPageContainer(page, styles = {}) {
    const $container = super._createPageContainer(page, styles);
    if(this.enableTextSelection){
      this.textSelectionPlugin.createTextLayer(page.index, $container);
    }
    return $container;
  }
}
window.BookReader = BookreaderWithTextSelection;<|endoftext|>


<commit_before>function Teams() {
    this.teams = [
        {
            id: "TeamRenaissance",
            name: "Renaissance",
            teamLead: "Anton Valadzko",
            qaTeamLead: "Aliaksandra Kutynka",
            developers: [
                "Dzianis Arlouski",
                "Hanna Kastsian",
                "Iryna Kucharenka1",
                "Ivan Izmer",
                "Mark Varabyou",
                "Raman But-Husaim",
                "Siarhei Abrazhevich",
                "Yauheni Lohinau",

                "Artsiom Rusak",
                "Aliaksei Astashkin",
                "Aliaksandr Koush",
                "Alena Charnova",
                "Nicolay Kostroma"
            ],
            testers: [
                "Pavel Vysotsky",
                "Viktoriya Harbatsenkava",
                "Hanna Prykhodzka",
                "Kseniya Kavalchuk",
                "Yuliya Tukaila",
                "Aliaksandra Kutynka"
            ]
        },
        {
            id: "TeamInspiration",
            name: "Inspiration",
            teamLead: "Sergey Tischenko",
            qaTeamLead: "Denys Pugachov",
            developers: [
                "Borys Roshal",
                "Denys Poliakov",
                "Dmytro Komar",
                "Kostiantyn Lazurenko",
                "Oleksandr Stukalov",
                "Oleksii Bespalko",
                "Yevhenii Havryliuk",
                "Yuriy Shestyora",
                "Ihor Bershov",
                "Oleksandr Zhyltsov",
                "Oleksii Suriadnyi",
                "Roman Golovchenko",
                "Serhiy Haponenko",
                "Yevhenii Lomov"
            ],
            testers: [
                "Mila Botnar",
                "Yuri Timchenko",
                "Anastasia Kotenyova",
                "Pavlo Golovashchenko",
                "Svitlana Peleshenko",
                "Denys Pugachov"
            ]
        },
        {
            id: "TeamNova",
            name: "Nova",
            teamLead: "Heorhi Vilkitski",
            qaTeamLead: "Valiantsina Krautsevich",
            developers: [
                "Andrei Kandybovich",
                "Dzmitry Siamchonak",
                "Mikita Stalpinski",
                "Uladzimir Harabtsou",
                "Aliaksandr Nikulin",
                "Ilya Kazlou1",
                "Katsiaryna Kaliukhovich",
                "Vadzim Vysotski",
                "Aliaksei Labachou",
                "Edhar Liashok",
                "Raman Prakofyeu",
                "Ruslan Khilmanovich"
            ],
            testers: [
                "Aliaksei Burnosenka",
                "Yuliya Kalasouskaya",
                "Viktar Mikalayenka",
                "Viktoryia Darashenka",
                "Valiantsina Krautsevich"
            ]
        },
        {
            id: "TeamLiberty",
            name: "Liberty",
            teamLead: "Dzmitry Tabolich",
            qaTeamLead: "Iryna Kutsko",
            developers: [
                "Mariya Babich",
                "Volha Shandrokha",
                "Andrei Krasnou",
                "Aliaksandr Rusak",
                "Katsiaryna Tsalabanava"
            ],
            testers: [
                "Iryna Kutsko"
            ]
        },
        {
            id: "TeamViva",
            name: "Viva",
            teamLead: "Valentine Zhuck",
            qaTeamLead: "Katsiaryna Kuchko",
            developers: [
                "Maryna Furman",
                "Siarhei Zhalezka",
                "Yury Yamoryk",
                "Aliaksandr Kladau",
                "Maksim Tsikhan",
                "Petr Falitarchyk",
                "Aliaksandr Rykau",
                "Ivan Dziameshka",
                "Siarhei Bahdanovich"
            ],
            testers: [
                "Iryna Shuliak",
                "Iryna Koush",
                "Maryia Kireyeva",
                "Katsiaryna Kuchko",
                "Iryna Razorionova"
            ]
        },
        {
            id: "TeamAutomation",
            name: "Automation",
            teamLead: "Aliaksandr Basau",
            developers: [
                "Aliaksandr Basau",
                "Julia Zhavnerchik",
                "Nadzeya Mishurava",
                "Stepan Zelenin",
                "Viachaslau Naimovich",
                "Vitali Sonchyk",
                "Katsiaryna Firsava",
                "Katsiaryna Kulbitskaya"
            ]
        }
    ]
}

exports.AllTeams = new Teams();
<commit_msg>-- update nova team employee list<commit_after>function Teams() {
    this.teams = [
        {
            id: "TeamRenaissance",
            name: "Renaissance",
            teamLead: "Anton Valadzko",
            qaTeamLead: "Aliaksandra Kutynka",
            developers: [
                "Dzianis Arlouski",
                "Hanna Kastsian",
                "Iryna Kucharenka1",
                "Ivan Izmer",
                "Mark Varabyou",
                "Raman But-Husaim",
                "Siarhei Abrazhevich",
                "Yauheni Lohinau",

                "Artsiom Rusak",
                "Aliaksei Astashkin",
                "Aliaksandr Koush",
                "Alena Charnova",
                "Nicolay Kostroma"
            ],
            testers: [
                "Pavel Vysotsky",
                "Viktoriya Harbatsenkava",
                "Hanna Prykhodzka",
                "Kseniya Kavalchuk",
                "Yuliya Tukaila",
                "Aliaksandra Kutynka"
            ]
        },
        {
            id: "TeamInspiration",
            name: "Inspiration",
            teamLead: "Sergey Tischenko",
            qaTeamLead: "Denys Pugachov",
            developers: [
                "Borys Roshal",
                "Denys Poliakov",
                "Dmytro Komar",
                "Kostiantyn Lazurenko",
                "Oleksandr Stukalov",
                "Oleksii Bespalko",
                "Yevhenii Havryliuk",
                "Yuriy Shestyora",
                "Ihor Bershov",
                "Oleksandr Zhyltsov",
                "Oleksii Suriadnyi",
                "Roman Golovchenko",
                "Serhiy Haponenko",
                "Yevhenii Lomov"
            ],
            testers: [
                "Mila Botnar",
                "Yuri Timchenko",
                "Anastasia Kotenyova",
                "Pavlo Golovashchenko",
                "Svitlana Peleshenko",
                "Denys Pugachov"
            ]
        },
        {
            id: "TeamNova",
            name: "Nova",
            teamLead: "Heorhi Vilkitski",
            qaTeamLead: "Valiantsina Krautsevich",
            developers: [
                "Andrei Kandybovich",
                "Dzmitry Siamchonak",
                "Mikita Stalpinski",
                "Uladzimir Harabtsou",
                "Aliaksandr Nikulin",
                "Ilya Kazlou1",
                "Katsiaryna Kaliukhovich",
                "Vadzim Vysotski",
                "Aliaksei Labachou",
                "Edhar Liashok",
                "Raman Prakofyeu",
                "Ruslan Khilmanovich",
                "Anton Kratenok"
            ],
            testers: [
                "Aliaksei Burnosenka",
                "Yuliya Kalasouskaya",
                "Viktar Mikalayenka",
                "Viktoryia Darashenka",
                "Valiantsina Krautsevich"
            ]
        },
        {
            id: "TeamLiberty",
            name: "Liberty",
            teamLead: "Dzmitry Tabolich",
            qaTeamLead: "Iryna Kutsko",
            developers: [
                "Mariya Babich",
                "Volha Shandrokha",
                "Andrei Krasnou",
                "Aliaksandr Rusak",
                "Katsiaryna Tsalabanava"
            ],
            testers: [
                "Iryna Kutsko"
            ]
        },
        {
            id: "TeamViva",
            name: "Viva",
            teamLead: "Valentine Zhuck",
            qaTeamLead: "Katsiaryna Kuchko",
            developers: [
                "Maryna Furman",
                "Siarhei Zhalezka",
                "Yury Yamoryk",
                "Aliaksandr Kladau",
                "Maksim Tsikhan",
                "Petr Falitarchyk",
                "Aliaksandr Rykau",
                "Ivan Dziameshka",
                "Siarhei Bahdanovich"
            ],
            testers: [
                "Iryna Shuliak",
                "Iryna Koush",
                "Maryia Kireyeva",
                "Katsiaryna Kuchko",
                "Iryna Razorionova"
            ]
        },
        {
            id: "TeamAutomation",
            name: "Automation",
            teamLead: "Aliaksandr Basau",
            developers: [
                "Aliaksandr Basau",
                "Julia Zhavnerchik",
                "Nadzeya Mishurava",
                "Stepan Zelenin",
                "Viachaslau Naimovich",
                "Vitali Sonchyk",
                "Katsiaryna Firsava",
                "Katsiaryna Kulbitskaya"
            ]
        }
    ]
}

exports.AllTeams = new Teams();
<|endoftext|>


<commit_before>function setupDdox()
{
	$(".tree-view").children(".package").click(toggleTree);
	$(".tree-view.collapsed").children("ul").hide();
}

function toggleTree()
{
	node = $(this).parent();
	node.toggleClass("collapsed");
	if( node.hasClass("collapsed") ){
		node.children("ul").hide();
	} else {
		node.children("ul").show();
	}
	return false;
}

var searchCounter = 0;
var lastSearchString = "";

function performSymbolSearch(maxlen)
{
	if (maxlen === 'undefined') maxlen = 26;

	var searchstring = $("#symbolSearch").val().toLowerCase();

	if (searchstring == lastSearchString) return;
	lastSearchString = searchstring;

	var scnt = ++searchCounter;
	$('#symbolSearchResults').hide();
	$('#symbolSearchResults').empty();

	var terms = $.trim(searchstring).split(/\s+/);
	if (terms.length == 0 || (terms.length == 1 && terms[0].length < 2)) return;

	var results = [];
	for (i in symbols) {
		var sym = symbols[i];
		var all_match = true;
		for (j in terms)
			if (sym.name.toLowerCase().indexOf(terms[j]) < 0) {
				all_match = false;
				break;
			}
		if (!all_match) continue;

		results.push(sym);
	}

	function compare(a, b) {
		var adep = a.attributes.indexOf("deprecated") >= 0;
		var bdep = b.attributes.indexOf("deprecated") >= 0;
		if (adep != bdep) return adep - bdep;

		var aname = a.name.toLowerCase();
		var bname = b.name.toLowerCase();

		var anameparts = aname.split(".");
		var bnameparts = bname.split(".");

		var aexact = terms.indexOf(anameparts[anameparts.length-1]) >= 0;
		var bexact = terms.indexOf(bnameparts[bnameparts.length-1]) >= 0;
		if (aexact != bexact) return bexact - aexact;

		if (anameparts.length < bnameparts.length) return -1;
		if (anameparts.length > bnameparts.length) return 1;

		if (aname < bname) return -1;
		if (aname > bname) return 1;
		return 0;
	}

	results.sort(compare);

	for (i = 0; i < results.length && i < 100; i++) {
			var sym = results[i];

			var el = $(document.createElement("li"));
			el.addClass(sym.kind);
			for (j in sym.attributes)
				el.addClass(sym.attributes[j]);

			var name = sym.name;

			// compute a length limited representation of the full name
			var nameparts = name.split(".");
			var np = nameparts.length-1;
			var shortname = "." + nameparts[np];
			while (np > 0 && nameparts[np-1].length + shortname.length <= maxlen) {
				np--;
				shortname = "." + nameparts[np] + shortname;
			}
			if (np > 0) shortname = ".." + shortname;
			else shortname = shortname.substr(1);

			el.append(''+shortname+'');
			$('#symbolSearchResults').append(el);
		}

	if (results.length > 100) {
		$('#symbolSearchResults').append("
…"+(results.length-100)+" additional results
");
	}

	$('#symbolSearchResults').show();
}
<commit_msg>Slightly improve search result ordering.<commit_after>function setupDdox()
{
	$(".tree-view").children(".package").click(toggleTree);
	$(".tree-view.collapsed").children("ul").hide();
}

function toggleTree()
{
	node = $(this).parent();
	node.toggleClass("collapsed");
	if( node.hasClass("collapsed") ){
		node.children("ul").hide();
	} else {
		node.children("ul").show();
	}
	return false;
}

var searchCounter = 0;
var lastSearchString = "";

function performSymbolSearch(maxlen)
{
	if (maxlen === 'undefined') maxlen = 26;

	var searchstring = $("#symbolSearch").val().toLowerCase();

	if (searchstring == lastSearchString) return;
	lastSearchString = searchstring;

	var scnt = ++searchCounter;
	$('#symbolSearchResults').hide();
	$('#symbolSearchResults').empty();

	var terms = $.trim(searchstring).split(/\s+/);
	if (terms.length == 0 || (terms.length == 1 && terms[0].length < 2)) return;

	var results = [];
	for (i in symbols) {
		var sym = symbols[i];
		var all_match = true;
		for (j in terms)
			if (sym.name.toLowerCase().indexOf(terms[j]) < 0) {
				all_match = false;
				break;
			}
		if (!all_match) continue;

		results.push(sym);
	}

	function compare(a, b) {
		// prefer non-deprecated matches
		var adep = a.attributes.indexOf("deprecated") >= 0;
		var bdep = b.attributes.indexOf("deprecated") >= 0;
		if (adep != bdep) return adep - bdep;

		// normalize the names
		var aname = a.name.toLowerCase();
		var bname = b.name.toLowerCase();

		var anameparts = aname.split(".");
		var bnameparts = bname.split(".");

		var asname = anameparts[anameparts.length-1];
		var bsname = bnameparts[bnameparts.length-1];

		// prefer exact matches
		var aexact = terms.indexOf(asname) >= 0;
		var bexact = terms.indexOf(bsname) >= 0;
		if (aexact != bexact) return bexact - aexact;

		// prefer elements with less nesting
		if (anameparts.length < bnameparts.length) return -1;
		if (anameparts.length > bnameparts.length) return 1;

		// prefer matches with a shorter name
		if (asname.length < bsname.length) return -1;
		if (asname.length > bsname.length) return 1;

		// sort the rest alphabetically
		if (aname < bname) return -1;
		if (aname > bname) return 1;
		return 0;
	}

	results.sort(compare);

	for (i = 0; i < results.length && i < 100; i++) {
			var sym = results[i];

			var el = $(document.createElement("li"));
			el.addClass(sym.kind);
			for (j in sym.attributes)
				el.addClass(sym.attributes[j]);

			var name = sym.name;

			// compute a length limited representation of the full name
			var nameparts = name.split(".");
			var np = nameparts.length-1;
			var shortname = "." + nameparts[np];
			while (np > 0 && nameparts[np-1].length + shortname.length <= maxlen) {
				np--;
				shortname = "." + nameparts[np] + shortname;
			}
			if (np > 0) shortname = ".." + shortname;
			else shortname = shortname.substr(1);

			el.append(''+shortname+'');
			$('#symbolSearchResults').append(el);
		}

	if (results.length > 100) {
		$('#symbolSearchResults').append("
…"+(results.length-100)+" additional results
");
	}

	$('#symbolSearchResults').show();
}
<|endoftext|>


<commit_before>define(['realtime-set-interval', 'underscore', 'backbone', 'd3'], function(realtimeSetInterval) {
    return function() {
        var user = {}
        _.extend(user, Backbone.Events)
        // User won't notice higher intervals than these
        setInterval(function() { user.trigger('read') }, 250)
        d3.timer(function() { user.trigger('view') })
        realtimeSetInterval(function() { user.trigger('hear') }, 100)
        return user
    }
})
<commit_msg>Fix comment<commit_after>define(['realtime-set-interval', 'underscore', 'backbone', 'd3'], function(realtimeSetInterval) {
    return function() {
        var user = {}
        _.extend(user, Backbone.Events)
        // User won't notice lower intervals than these
        setInterval(function() { user.trigger('read') }, 250)
        d3.timer(function() { user.trigger('view') })
        realtimeSetInterval(function() { user.trigger('hear') }, 100)
        return user
    }
})
<|endoftext|>


<commit_before>var waze = {};

waze.map = (function() {
    var map;

	function _initMap() {
		map = L.map('map').setView([51.505, -0.09], 13);

		L.tileLayer('http://{s}.tile.cloudmade.com/d1954fa5c5934eecbd0f07c6f7d2d339/997/256/{z}/{x}/{y}.png', {
    					attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade',
    					maxZoom: 18
					}).addTo(map);

		map.on('click', function(e) {
			var marker = L.marker(e.latlng);
			marker.addTo(map);
			marker.bindPopup("
Hello world!
").openPopup();

		});

        _refreshBounds();

        map.on('viewreset', function(e) {
        	_refreshBounds();
        });

        map.on('drag', function(e) {
        	_refreshBounds();
        });
	};

	function _refreshBounds() {
       	var bounds = map.getBounds();
        $("#mapInfo .west").text(bounds.getWest().toFixed(4));
    	$("#mapInfo .south").text(bounds.getSouth().toFixed(4));
	}

	function _initNotifications(e) {
		$.ajax({
				url: "notifications",
				cache: false
			}).done(function(data) {
  			console.log(data);
		});
	}

    function _initUpdate() {

        var latlng = map.getCenter();
        $("#lat").val(latlng.lat);
        $("#lon").val(latlng.lng);
        $("#mapInfo button").click(function() {
            var latlng = new L.LatLng($("#lat").val(), $("#lon").val());

            map.setView(latlng, map.getZoom());

        });
    }

	return {
		init : function() {
			_initMap();
			_initNotifications();
            _initUpdate();
		}
	}

})();

$(waze.map.init);<commit_msg>Initial attempt with Backbone.js<commit_after>if (typeof waze === 'undefined') {
    waze = {};
}

waze.notification = Backbone.Model.extend({
});

waze.notificationList = Backbone.Collection.extend({
    model : waze.notification
});

waze.notificationView = Backbone.View.extend({
    tagName:  "li",
    render: function() {
      this.$el.html("hello");
      return this;
    }
});

waze.map = (function() {
    var map,
        notifications;

	function _initMap() {
		map = L.map('map').setView([51.505, -0.09], 13);

		L.tileLayer('http://{s}.tile.cloudmade.com/d1954fa5c5934eecbd0f07c6f7d2d339/997/256/{z}/{x}/{y}.png', {
    					attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade',
    					maxZoom: 18
					}).addTo(map);

		map.on('click', function(e) {
			var marker = L.marker(e.latlng);
			marker.addTo(map);
			marker.bindPopup("
Hello world!
").openPopup();

		});

        _refreshBounds();

        map.on('viewreset', function(e) {
        	_refreshBounds();
        });

        map.on('drag', function(e) {
        	_refreshBounds();
        });
	};

	function _refreshBounds() {
       	var bounds = map.getBounds();
        $("#mapInfo .west").text(bounds.getWest().toFixed(4));
    	$("#mapInfo .south").text(bounds.getSouth().toFixed(4));
	}

	function _initNotifications(e) {
        notifications = new waze.notificationList;
		$.ajax({
				url: "notifications",
				cache: false
			}).done(function(data) {
                var notificationsArray = _.map(data, function(el) {
                    return new waze.notification({
                        id : el.id,
                        title : el.title,
                        description : el.description,
                        lon : el.lon,
                        lat : el.lat
                    });
                });
                notifications.add(notificationsArray);
            });
	}

    function _initUpdate() {

        var latlng = map.getCenter();
        $("#lat").val(latlng.lat);
        $("#lon").val(latlng.lng);
        $("#mapInfo button").click(function() {
            var latlng = new L.LatLng($("#lat").val(), $("#lon").val());

            map.setView(latlng, map.getZoom());

        });
    }

	return {
		init : function() {
			_initMap();
			_initNotifications();
            _initUpdate();
		}
	}

})();

$(waze.map.init);<|endoftext|>


<commit_before>#!/usr/bin/env node

function buildWordListBuffer() {
  console.log('Building alphabetical word list')

  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  const words = [];

  for (let a = 0; a < 26; a++) {
    for (let b = 0; b < 26; b++) {
      for (let c = 0; c < 26; c++) {
        for (let d = 0; d < 26; d++) {
          for (let e = 0; e < 10; e++) {
            words.push(alphabet[a] + alphabet[b] + alphabet[c] + alphabet[d] + alphabet[e]);
          }
        }
      }
    }
  }

  const tokensBuffer = Buffer.from(words.join('\n'), 'utf-8');

  console.log('%d words, %d bytes', words.length, tokensBuffer.length);
  return tokensBuffer;
}

function buildSearchStringBuffer() {
  console.log('Building search string')

  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  const searchWords = [];

  for (let a = 0; a < 26; a++) {
    for (let b = 0; b < 26; b++) {
      for (let c = 0; c < 26; c++) {
        searchWords.push(alphabet[a] + 'b' + alphabet[c] + 'de');
        searchWords.push(alphabet[a] + 'b' + alphabet[c] + 'dx');
      }
    }
  }

  const searchBuffer = Buffer.from(searchWords.join(' ', 'utf-8'));

  console.log('%d words, %d bytes', searchWords.length, searchBuffer.length);

  return searchBuffer;
}

function profileInitializeAndBuildSet(tokensBuffer) {
  const Set = require('../index');
  let set;

  console.time('Initializing tree 5 times');
  for (let i = 0; i < 5; i++) {
    set = new Set(tokensBuffer);
  }
  console.timeEnd('Initializing tree 5 times');

  return set;
}

function profileSearch(set, searchBuffer) {
  let ret

  console.time('Searching tree 100 times with maxNgramSize=2');
  for (let i = 0; i < 100; i++) {
    ret = set.findAllMatches(searchBuffer, 2);
  }
  console.timeEnd('Searching tree 100 times with maxNgramSize=2');

  console.log('Match length', ret.length, 'first match', ret[0]);
}

function profileAll() {
  const tokensBuffer = buildWordListBuffer();
  const searchBuffer = buildSearchStringBuffer();
  const set = profileInitializeAndBuildSet(tokensBuffer);

  profileSearch(set, searchBuffer);
}

profileAll()

// Collect garbage, so Valgrind can find leaks
if (!global.gc) {
  console.warn('Running without garbage collection. Run node with --expose-gc to remove this warning and get better results');
} else {
  global.gc();
}
<commit_msg>Improve perf tests.<commit_after>#!/usr/bin/env node

function buildWordListBuffer() {
  console.log('Building alphabetical word list')

  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  const words = [];

  for (let a = 0; a < 26; a++) {
    for (let b = 0; b < 26; b++) {
      for (let c = 0; c < 26; c++) {
        for (let d = 0; d < 26; d++) {
          for (let e = 0; e < 10; e++) {
            words.push(alphabet[a] + alphabet[b] + alphabet[c] + alphabet[d] + alphabet[e]);
          }
        }
      }
    }
  }

  const tokensBuffer = Buffer.from(words.join('\n'), 'utf-8');

  console.log('%d words, %d bytes', words.length, tokensBuffer.length);
  return tokensBuffer;
}

function buildSearchStringBuffer() {
  console.log('Building search string')

  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  const searchWords = [];

  for (let a = 0; a < 26; a++) {
    for (let b = 0; b < 26; b++) {
      for (let c = 0; c < 26; c++) {
        searchWords.push(alphabet[a] + 'b' + alphabet[c] + 'de');
        searchWords.push(alphabet[a] + 'b' + alphabet[c] + 'dx');
      }
    }
  }

  const searchBuffer = Buffer.from(searchWords.join(' ', 'utf-8'));

  console.log('%d words, %d bytes', searchWords.length, searchBuffer.length);

  return searchBuffer;
}

function profileInitializeAndBuildSet(tokensBuffer) {
  const Set = require('../index');
  let set;

  console.time('Initializing tree 5 times');
  for (let i = 0; i < 5; i++) {
    set = new Set(tokensBuffer);
  }
  console.timeEnd('Initializing tree 5 times');

  return set;
}

function profileContains(set, searchBuffer) {
  let ret

  const searchBuffers = searchBuffer.toString().split(' ').map(Buffer.from);

  console.time('100x tree.contains() with %d Buffers', searchBuffers.length);
  for (let i = 0; i < 100; i++) {
    searchBuffers.forEach(x => set.contains(x));
  }
  console.timeEnd('100x tree.contains() with %d Buffers', searchBuffers.length);

  const searchStrings = searchBuffer.toString().split(' ');
  console.time('100x tree.contains() with %d Strings', searchStrings.length);
  for (let i = 0; i < 100; i++) {
    searchStrings.forEach(x => set.contains(x));
  }
  console.timeEnd('100x tree.contains() with %d Strings', searchStrings.length);
}

function profileSearch(set, searchBuffer) {
  let ret

  console.time('100x tree.findAllMatches() with Buffer and maxNgramSize=2');
  for (let i = 0; i < 100; i++) {
    ret = set.findAllMatches(searchBuffer, 2);
  }
  console.timeEnd('100x tree.findAllMatches() with Buffer and maxNgramSize=2');

  const searchString = searchBuffer.toString();
  console.time('100x tree.findAllMatches() with String and maxNgramSize=2');
  for (let i = 0; i < 100; i++) {
    ret = set.findAllMatches(searchString, 2);
  }
  console.timeEnd('100x tree.findAllMatches() with String and maxNgramSize=2');

  console.log('Match length', ret.length, 'first match', ret[0]);
}

function profileAll() {
  const tokensBuffer = buildWordListBuffer();
  const searchBuffer = buildSearchStringBuffer();
  const set = profileInitializeAndBuildSet(tokensBuffer);

  profileContains(set, searchBuffer);
  profileSearch(set, searchBuffer);
}

profileAll()

// Collect garbage, so Valgrind can find leaks
if (!global.gc) {
  console.warn('Running without garbage collection. Run node with --expose-gc to remove this warning and get better results');
} else {
  global.gc();
}
<|endoftext|>


<commit_before>import 'babel-register';
import is from 'check-types';
import test from 'ava';

import Pagarme from '../src/pagarme';
import Plan from '../src/plan';

test.beforeEach(() => Pagarme.setApiKey('ak_test_TSgC3nvXtdYnDoGKgNLIOfk3TFfkl9'));

test('create a plan', async t => {
	const plan = new Plan({
		amount: 1000,
		days: 30,
		name: 'test-api'
	});

	const p = await plan.create();

	t.ok(is.not.undefined(p));
	t.ok(is.object(p));
	t.is(p.object, 'plan');
	t.is(p.amount, 1000);
	t.is(p.days, 30);
	t.is(p.name, 'test-api');
});

test('create a plan without the amount property', t => {
	const plan = new Plan({
		days: 30,
		name: 'test-api'
	});

	t.throws(() => plan.create());
});

test('create a plan without the days property', t => {
	const plan = new Plan({
		amount: 1000,
		name: 'test-api'
	});

	t.throws(() => plan.create());
});

test('create a plan without the name property', t => {
	const plan = new Plan({
		amount: 1000,
		days: 30
	});

	t.throws(() => plan.create());
});

test('create a plan with an id', t => {
	const plan = new Plan({
		amount: 1000,
		days: 30,
		name: 'test-api',
		id: 25000
	});

	t.throws(() => plan.create());
});

test('find all plans', async t => {
	const plan = new Plan();

	const plans = await plan.findAll();

	t.ok(is.not.undefined(plans));
	t.ok(is.array(plans));
	t.is(plans[0].object, 'plan');
});

test('find a plan with an id', async t => {
	const plan = new Plan({
		id: 25937
	});

	const p = await plan.find();

	t.ok(is.not.undefined('object'));
	t.ok(is.object(p));
	t.is(p.object, 'plan');
	t.is(p.id, 25937);
});

test('find a plan passing an id', async t => {
	const plan = new Plan();

	const p = await plan.find(25937);

	t.ok(is.not.undefined('object'));
	t.ok(is.object(p));
	t.is(p.object, 'plan');
	t.is(p.id, 25937);
});

test('find a plan with no id', t => {
	const plan = new Plan();

	t.throws(() => plan.find());
});

test.only('update a plan', async t => {
	let plan = new Plan({
		amount: 1000,
		days: 30,
		name: 'test-api'
	});

	plan = await plan.create();

	const p = await plan.update({
		name: 'test-api-updated',
		trial_days: 14
	});

	t.is(p.name, 'test-api-updated');
	t.is(p.trial_days, 14);
});
<commit_msg>Fix test coverage for plans<commit_after>import 'babel-register';
import is from 'check-types';
import test from 'ava';

import Pagarme from '../src/pagarme';
import Plan from '../src/plan';

test.beforeEach(() => Pagarme.setApiKey('ak_test_TSgC3nvXtdYnDoGKgNLIOfk3TFfkl9'));

test('create a plan', async t => {
	const plan = new Plan({
		amount: 1000,
		days: 30,
		name: 'test-api'
	});

	const p = await plan.create();

	t.ok(is.not.undefined(p));
	t.ok(is.object(p));
	t.is(p.object, 'plan');
	t.is(p.amount, 1000);
	t.is(p.days, 30);
	t.is(p.name, 'test-api');
});

test('create a plan without the amount property', t => {
	const plan = new Plan({
		days: 30,
		name: 'test-api'
	});

	t.throws(() => plan.create());
});

test('create a plan without the days property', t => {
	const plan = new Plan({
		amount: 1000,
		name: 'test-api'
	});

	t.throws(() => plan.create());
});

test('create a plan without the name property', t => {
	const plan = new Plan({
		amount: 1000,
		days: 30
	});

	t.throws(() => plan.create());
});

test('create a plan with an id', t => {
	const plan = new Plan({
		amount: 1000,
		days: 30,
		name: 'test-api',
		id: 25000
	});

	t.throws(() => plan.create());
});

test('find all plans', async t => {
	const plan = new Plan();

	const plans = await plan.findAll();

	t.ok(is.not.undefined(plans));
	t.ok(is.array(plans));
	t.is(plans[0].object, 'plan');
});

test('find a plan with an id', async t => {
	const plan = new Plan({
		id: 25937
	});

	const p = await plan.find();

	t.ok(is.not.undefined('object'));
	t.ok(is.object(p));
	t.is(p.object, 'plan');
	t.is(p.id, 25937);
});

test('find a plan passing an id', async t => {
	const plan = new Plan();

	const p = await plan.find(25937);

	t.ok(is.not.undefined('object'));
	t.ok(is.object(p));
	t.is(p.object, 'plan');
	t.is(p.id, 25937);
});

test('find a plan with no id', t => {
	const plan = new Plan();

	t.throws(() => plan.find());
});

test('update a plan', async t => {
	let plan = new Plan({
		amount: 1000,
		days: 30,
		name: 'test-api'
	});

	plan = await plan.create();

	const p = await plan.update({
		name: 'test-api-updated',
		trial_days: 14
	});

	t.is(p.name, 'test-api-updated');
	t.is(p.trial_days, 14);
});
<|endoftext|>


<commit_before>/**
 * @authors : hoozi
 * @webSite : https://github.com/hoozi
 * @email   : 287036406@qq.com
 * @date    : 2015-06-02 13:15:34
 * @version : 0.0.1
 */
var signUp = angular.module('signUp', []);
signUp.controller('signUpForm', ['$scope', function($scope){
	$scope.submitForm = function(v,event) {

		if(!v) {
			alert("error");
			event.preventDefault(); //标准
       	 	event.returnValue = false //IE
			return false;
		}
	}
}])

<commit_msg>commit<commit_after>/**
 * @authors : hoozi
 * @webSite : https://github.com/hoozi
 * @email   : 287036406@qq.com
 * @date    : 2015-06-02 13:15:34
 * @version : 0.0.1
 */
var signUp = angular.module("signUp", ["validator"]);

signUp.controller("signUpForm", ["$scope", "$http", function($scope, $http){

}])

<|endoftext|>


<commit_before>
var st = require('../lib/stocktwits');

var token = 'YOUR_ACCESS_TOKEN';

describe('POST', function () {
    it('should make a POST request', function (done) {
        st.post('messages/create', {access_token:token}, {body:'message'}, function (err, res) {
            if (err) return done(err);
            res.body.response.status.should.equal(200);
            res.body.message.body.should.equal('message');
            done();
        });
    });
});
<commit_msg>Return error on missing access token<commit_after>
var st = require('../lib/stocktwits');

var token = 'YOUR_ACCESS_TOKEN';

describe('POST', function () {
    it('should make a POST request', function (done) {
        if (token == 'YOUR_ACCESS_TOKEN') return done(new Error('Access token required'));

        st.post('messages/create', {access_token:token}, {body:'message'}, function (err, res) {
            if (err) return done(err);
            res.body.response.status.should.equal(200);
            res.body.message.body.should.equal('message');
            done();
        });
    });
});
<|endoftext|>


<commit_before>
var async = require('../')
var pull = require('pull-stream')
var many = require('pull-many')
var assert = require('assert')
//var tape = require('tape')
//
//
//tape('paramap', function (t) {
//
//  async.test(function (async) {
//
//    pull(
//      pull.values([1,2,3,4,5,6,7]),
//      pull.paraMap(function (d, cb) {
//        async(cb) (null, d*10)
//      }),
//      pull.collect(function (err, ary) {
//        console.log(ary)
//        assert.deepEqual(ary, [10,20,30,40,50,60,70])
//        async.done()
//      })
//    )
//
//  }, function (err, results, stats) {
//    t.equal(stats.passes, 100)
//    t.end()
//  })
//
//})
//
//tape('many', function (t) {
//

//async.test(strange, function (err, results, stats) {
//    console.log(results)
//  })
//
function strange (async) {

    function p (read) {
      return function (abort, cb) {
        read(abort, async(cb))
      }
    }

    pull(
      //pull many must return a result in the same partial order.
      //so if we have a stream of even and a stream of odd numbers
      //then those should be in the same order in the output.
      many([
        pull.values([1,3,5,7]),
        pull.values([2,4,6,8])
      ].map(p)),
      function (read) {
        return function (abort, cb) {
          read(abort, function (end, data) {
            console.log(end, data)
            cb(end, data)
          })
        }
      },
      pull.collect(function (err, ary) {
        console.log(ary)
        var odd  = ary.filter(function (e) { return e % 2 })
        var even = ary.filter(function (e) { return !(e % 2) })

        assert.deepEqual(even, [2,4,6,8])
        assert.deepEqual(odd, [1,3,5,7])
        async.done()
      })
    )

  }

strange(async(95, console.error))

<commit_msg>heavy duty tests<commit_after>
var async = require('../')
var pull = require('pull-stream')
var many = require('pull-many')
var assert = require('assert')
//var tape = require('tape')
//
//
//tape('paramap', function (t) {
//
//  async.test(function (async) {
//
//    pull(
//      pull.values([1,2,3,4,5,6,7]),
//      pull.paraMap(function (d, cb) {
//        async(cb) (null, d*10)
//      }),
//      pull.collect(function (err, ary) {
//        console.log(ary)
//        assert.deepEqual(ary, [10,20,30,40,50,60,70])
//        async.done()
//      })
//    )
//
//  }, function (err, results, stats) {
//    t.equal(stats.passes, 100)
//    t.end()
//  })
//
//})
//
//tape('many', function (t) {
//

async.test(strange, function (err, results, stats) {
    console.log(results)
    assert.equal(stats.failures, 0)
    console.log('passed')
  })

function strange (async) {

    function p (read) {
      return function (abort, cb) {
        read(abort, async(cb))
      }
    }

    pull(
      //pull many must return a result in the same partial order.
      //so if we have a stream of even and a stream of odd numbers
      //then those should be in the same order in the output.
      many([
        pull.values([1,3,5,7]),
        pull.values([2,4,6,8])
      ].map(p)),
      function (read) {
        return function (abort, cb) {
          read(abort, function (end, data) {
            console.log(end, data)
            cb(end, data)
          })
        }
      },
      pull.collect(function (err, ary) {
        console.log(ary)
        var odd  = ary.filter(function (e) { return e % 2 })
        var even = ary.filter(function (e) { return !(e % 2) })

        assert.deepEqual(even, [2,4,6,8])
        assert.deepEqual(odd, [1,3,5,7])
        async.done()
      })
    )

  }

//strange(async(95, console.error))

<|endoftext|>


<commit_before>casper.test.begin('Important Information', function suite(test) {

    casper.start("http://khs-minithon.github.io/website/", function() {

        test.assertHttpStatus(200, 'Connected to main page');
        test.assertUrlMatch('/website', 'URL is root');

        test.assertTitle('Kennett High School Mini-THON', 'Title is correct');

        // Event Name
        test.assertExists('#event-name', 'Event Name Found');
        test.assertEquals(this.fetchText('#event-name'), 'Kennett High School Mini-THON', 'Correct Event Name');

        // Event Date
        test.assertExists('#event-date', 'Event Date Found');
        test.assertEquals(this.fetchText('#event-date'), "Join Us on February 26, 2016", "Correct Event Date");

        // Event Slogan
        test.assertExists('#event-slogan', 'Slogan Found');
        test.assertEquals(this.fetchText('#event-slogan'), "For The Fight. For The Cure. For The Kids.", "Correct Event Slogan");

        // About Section
        test.assertElementCount('.about', 4, '4 About Boxes Found');

            // Who Are We?
            test.assertEquals(this.fetchText(".about:nth-child(1) h4"), "Who Are We?", "Who Are We? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(1) p"), "We are a group of KHS students dedicated to raise as much money as possible to fight childhood cancer.", "Who Are We? - Correct Text ");

            // What Do We Do?
            test.assertEquals(this.fetchText(".about:nth-child(2) h4"), "What Do We Do?", "What Do We Do? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(2) p"), "The KHS Mini-THON raises money through fundraisers and our annual Mini-THON to benefit the Four Diamonds Research.", "What Do We Do? - Correct Text ");

            // Why We Do It?
            test.assertEquals(this.fetchText(".about:nth-child(3) h4"), "Why We Do It?", "Why We Do It? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(3) p"), "We do it for the fight. For the cure. For The Kids living with cancer.", "Why We Do It? - Correct Text ");

            // Since When?
            test.assertEquals(this.fetchText(".about:nth-child(4) h4"), "Since When?", "Since When? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(4) p"), "We have been fighting childhood cancer since 2015 with our first annual Mini-THON being held in February of 2016.", "Since When? - Correct Text ");

        // Impact Section
        test.assertElementCount('.services', 4, '4 Services Boxes Found');

            // Mini-THONs
            test.assertEquals(this.fetchText(".services:nth-child(1) h4"), "Mini-THONs", "Mini-THONS - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(1) p"), "Mini-THONs are multi-hour, interactive, fun-filled events that are completely student-led. They can also be 3 month projects or year-long activities where students raise awareness and funds for Four Diamonds.", "Mini-THONS - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(1) a', 'href'), 'http://fourdiamonds.donordrive.com/index.cfm?fuseaction=cms.page&id=1007', 'Mini-THON Correct Link');

            // Donations
            test.assertEquals(this.fetchText(".services:nth-child(2) h4"), "Donations", "Donations - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(2) p"), "By raising money, we can assure that the children get the help they need and deserve. Thanks to donations, 100% of children with cancer at Penn State Hershey Children's Hospital are eligible for assistance.", "Donations - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(2) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usfinancials', 'Mini-THONS Correct Link');

            // Raising Awareness
            test.assertEquals(this.fetchText(".services:nth-child(3) h4"), "Raising Awareness", "Raising Awareness - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(3) p"), "By reaching out the community, we make everyone come together to help fight for this noble cause.", "Raising Awareness - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(3) a', 'href'), 'http://www.fourdiamonds.org/about-childhood-cancer/', 'Raising Awareness Correct Link');

            // Research
            test.assertEquals(this.fetchText(".services:nth-child(4) h4"), "Research", "Research - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(4) p"), "Through Four Diamonds, Penn State Hershey Children's Hospital is seeking improved treatments and cures to benefit those around the world.", "Research - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(4) a', 'href'), 'https://www.youtube.com/watch?v=C7SPFR2T3tg', 'Research Correct Link');

            /* Add this exactly like this Travis going to flip
        // Four Diamonds Links
        test.assertElementCount('.imp-links li', 6, '6 Four Diamonds Links Found');

            // About
            test.assertEquals(this.fetchText('.imp-links li:nth-child(1)'), 'About', 'About - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(1) a', 'href'), 'http://www.fourdiamonds.org/about-us/#sidr-main', 'About - Correct Link');

            // History
            test.assertEquals(this.fetchText('.imp-links li:nth-child(2)'), 'History', 'History - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(2) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usour-history', 'History - Correct Link');

            // Financials
            test.assertEquals(this.fetchText('.imp-links li:nth-child(3)'), 'Financials', 'Financials - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(3) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usfinancials', 'Financials - Correct Link');

            // Penn State
            test.assertEquals(this.fetchText('.imp-links li:nth-child(4)'), 'Penn State', 'Penn State - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(4) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usrelationship-to-penn-state', 'Penn State - Correct Link');

            // Staff
            test.assertEquals(this.fetchText('.imp-links li:nth-child(5)'), 'Staff', 'Staff - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(5) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usstaff', 'Staff - Correct Link');

            // Families
            test.assertEquals(this.fetchText('.imp-links li:nth-child(6)'), 'Families', 'Families - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(6) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usmeet-our-families', 'Families - Correct Link');
            */
    });

    casper.run(function() {
        test.done();
    });

});

casper.test.begin('Important Links', function suite(test) {

    casper.start("http://khs-minithon.github.io/website/", function() {

        // Navigation Bar
        test.assertExists('.navbar-nav', 'Navigation Bar Found');
        test.assertElementCount('.navbar-nav li', 7, '7 Sections in Navigation Bar Found');

            // Home
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(1) a'), "Home", "Correct Navigation-Home Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(1) a', 'href'), 'body', 'Correct Navigation-Home Link');

            // About
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(2) a'), "About", "Correct Navigation-About Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(2) a', 'href'), '#about-section', 'Correct Navigation-About Link');

            // Services
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(3) a'), "Services", "Correct Navigation-Services Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(3) a', 'href'), '#services-section', 'Correct Navigation-Services Link');

            // Impact
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(4) a'), "Impact", "Correct Navigation-Impact Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(4) a', 'href'), '#portfolio-section', 'Correct Navigation-Impact Link');

            // Sign Up
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(5) a'), "Sign Up", "Correct Navigation-SignUp Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(5) a', 'href'), '#signup-section', 'Correct Navigation-Sign Up Link');

            // Team
            //test.assertEquals(this.fetchText('.navbar-nav li:nth-child(6) a'), "Team", "Correct Navigation-Team Text");
            //test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(6) a', 'href'), '#team-section', 'Correct Navigation-Team Link');

            // Partners
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(6) a'), "Partners", "Correct Navigation-Partners Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(6) a', 'href'), '#partners-section', 'Correct Navigation-Partners Link');

            // Social
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(7) a'), "Social", "Correct Navigation-Social Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(7) a', 'href'), '#social-section', 'Correct Navigation-Social Link');

        // Sign Up Button
        test.assertExists('#sign-up', 'Sign Up Button Found');
        test.assertEquals(this.fetchText('#sign-up strong'), "Sign up", "Correct Sign Up Button Text");
        test.assertEquals(this.getElementAttribute('#sign-up', 'href'), 'http://fourdiamonds.donordrive.com/event/khs16', 'Correct Sign Up Link');

        // Donate Button
        test.assertExists('#donate', 'Donate Button Found');
        test.assertEquals(this.fetchText('#donate'), "Donate", "Correct Donate Button Text");
        test.assertEquals(this.getElementAttribute('#donate', 'href'), 'https://fourdiamonds.donordrive.com/index.cfm?fuseaction=donate.event&eventID=1179', 'Correct Donate Link');

        // Social Media Buttons
        test.assertElementCount('.social-list li', 4, '4 Social Media Buttons Found');

            // Facebook
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(1) a', 'href'), 'https://www.facebook.com/FourDiamondsFund', 'Correct Facebook Link');

            // Twitter
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(2) a', 'href'), 'https://twitter.com/khsminithon', 'Correct Twitter Link');

            // Instagram
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(3) a', 'href'), 'https://instagram.com/khsminithon/', 'Correct Instagram Link');

            // Google Group
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(4) a', 'href'), 'https://groups.google.com/forum/#!forum/khsminithon/join', 'Correct Google Group Link');

    });

    casper.run(function() {
        test.done();

         // work around "Unsafe JavaScript attempt to access frame with URL about:blank" error
        // http://stackoverflow.com/questions/26608391/using-phantomjs-to-embed-all-images-of-a-webpage-produces-warnings-but-works/26688062#26688062
        setTimeout(function() {
            phantom.exit();
        }, 0);

    });

});
<commit_msg>shut up travis<commit_after>casper.test.begin('Important Information', function suite(test) {

    casper.start("http://khs-minithon.github.io/website/", function() {

        test.assertHttpStatus(200, 'Connected to main page');
        test.assertUrlMatch('/website', 'URL is root');

        test.assertTitle('Kennett High School Mini-THON', 'Title is correct');

        // Event Name
        test.assertExists('#event-name', 'Event Name Found');
        test.assertEquals(this.fetchText('#event-name'), 'Kennett High School Mini-THON', 'Correct Event Name');

        // Event Date
        test.assertExists('#event-date', 'Event Date Found');
        test.assertEquals(this.fetchText('#event-date'), "Join Us on February 26, 2016", "Correct Event Date");

        // Event Slogan
        test.assertExists('#event-slogan', 'Slogan Found');
        test.assertEquals(this.fetchText('#event-slogan'), "For The Fight. For The Cure. For The Kids.", "Correct Event Slogan");

        // About Section
        test.assertElementCount('.about', 4, '4 About Boxes Found');

            // Who Are We?
            test.assertEquals(this.fetchText(".about:nth-child(1) h4"), "Who Are We?", "Who Are We? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(1) p"), "We are a group of KHS students dedicated to raise as much money as possible to fight childhood cancer.", "Who Are We? - Correct Text ");

            // What Do We Do?
            test.assertEquals(this.fetchText(".about:nth-child(2) h4"), "What Do We Do?", "What Do We Do? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(2) p"), "The KHS Mini-THON raises money through fundraisers and our annual Mini-THON to benefit the Four Diamonds Research.", "What Do We Do? - Correct Text ");

            // Why We Do It?
            test.assertEquals(this.fetchText(".about:nth-child(3) h4"), "Why We Do It?", "Why We Do It? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(3) p"), "We do it for the fight. For the cure. For The Kids living with cancer.", "Why We Do It? - Correct Text ");

            // Since When?
            test.assertEquals(this.fetchText(".about:nth-child(4) h4"), "Since When?", "Since When? - Correct Title ");
            test.assertEquals(this.fetchText(".about:nth-child(4) p"), "We have been fighting childhood cancer since 2015 with our first annual Mini-THON being held in February of 2016.", "Since When? - Correct Text ");

        // Impact Section
        test.assertElementCount('.services', 4, '4 Services Boxes Found');

            // Mini-THONs
            test.assertEquals(this.fetchText(".services:nth-child(1) h4"), "Mini-THONs", "Mini-THONS - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(1) p"), "Mini-THONs are multi-hour, interactive, fun-filled events that are completely student-led. They can also be 3 month projects or year-long activities where students raise awareness and funds for Four Diamonds.", "Mini-THONS - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(1) a', 'href'), 'http://fourdiamonds.donordrive.com/index.cfm?fuseaction=cms.page&id=1007', 'Mini-THON Correct Link');

            // Donations
            test.assertEquals(this.fetchText(".services:nth-child(2) h4"), "Donations", "Donations - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(2) p"), "By raising money, we can assure that the children get the help they need and deserve. Thanks to donations, 100% of children with cancer at Penn State Hershey Children's Hospital are eligible for assistance.", "Donations - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(2) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usfinancials', 'Mini-THONS Correct Link');

            // Raising Awareness
            test.assertEquals(this.fetchText(".services:nth-child(3) h4"), "Raising Awareness", "Raising Awareness - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(3) p"), "By reaching out the community, we make everyone come together to help fight for this noble cause.", "Raising Awareness - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(3) a', 'href'), 'http://www.fourdiamonds.org/about-childhood-cancer/', 'Raising Awareness Correct Link');

            // Research
            test.assertEquals(this.fetchText(".services:nth-child(4) h4"), "Research", "Research - Correct Title ");
            test.assertEquals(this.fetchText(".services:nth-child(4) p"), "Through Four Diamonds, Penn State Hershey Children's Hospital is seeking improved treatments and cures to benefit those around the world.", "Research - Correct Text ");
            test.assertEquals(this.getElementAttribute('.services:nth-child(4) a', 'href'), 'https://www.youtube.com/watch?v=C7SPFR2T3tg', 'Research Correct Link');

            /* Add this exactly like this Travis going to flip
        // Four Diamonds Links
        test.assertElementCount('.imp-links li', 6, '6 Four Diamonds Links Found');

            // About
            test.assertEquals(this.fetchText('.imp-links li:nth-child(1)'), 'About', 'About - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(1) a', 'href'), 'http://www.fourdiamonds.org/about-us/#sidr-main', 'About - Correct Link');

            // History
            test.assertEquals(this.fetchText('.imp-links li:nth-child(2)'), 'History', 'History - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(2) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usour-history', 'History - Correct Link');

            // Financials
            test.assertEquals(this.fetchText('.imp-links li:nth-child(3)'), 'Financials', 'Financials - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(3) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usfinancials', 'Financials - Correct Link');

            // Penn State
            test.assertEquals(this.fetchText('.imp-links li:nth-child(4)'), 'Penn State', 'Penn State - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(4) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usrelationship-to-penn-state', 'Penn State - Correct Link');

            // Staff
            test.assertEquals(this.fetchText('.imp-links li:nth-child(5)'), 'Staff', 'Staff - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(5) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usstaff', 'Staff - Correct Link');

            // Families
            test.assertEquals(this.fetchText('.imp-links li:nth-child(6)'), 'Families', 'Families - Correct Text');
            test.assertEquals(this.getElementAttribute('.imp-links li:nth-child(6) a', 'href'), 'http://www.fourdiamonds.org/about-us/#about-usmeet-our-families', 'Families - Correct Link');
            */
    });

    casper.run(function() {
        test.done();
    });

});

casper.test.begin('Important Links', function suite(test) {

    casper.start("http://khs-minithon.github.io/website/", function() {

        // Navigation Bar
        test.assertExists('.navbar-nav', 'Navigation Bar Found');
        test.assertElementCount('.navbar-nav li', 8, '8 Sections in Navigation Bar Found');

            // Home
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(1) a'), "Home", "Correct Navigation-Home Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(1) a', 'href'), 'body', 'Correct Navigation-Home Link');

            // About
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(2) a'), "About", "Correct Navigation-About Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(2) a', 'href'), '#about-section', 'Correct Navigation-About Link');

            // Services
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(3) a'), "Services", "Correct Navigation-Services Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(3) a', 'href'), '#services-section', 'Correct Navigation-Services Link');

            // Impact
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(4) a'), "Impact", "Correct Navigation-Impact Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(4) a', 'href'), '#portfolio-section', 'Correct Navigation-Impact Link');

            // Sign Up
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(5) a'), "Sign Up", "Correct Navigation-SignUp Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(5) a', 'href'), '#signup-section', 'Correct Navigation-Sign Up Link');

            // Team
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(6) a'), "Team", "Correct Navigation-Team Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(6) a', 'href'), '#team-section', 'Correct Navigation-Team Link');

            // Partners
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(7) a'), "Partners", "Correct Navigation-Partners Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(7) a', 'href'), '#partners-section', 'Correct Navigation-Partners Link');

            // Social
            test.assertEquals(this.fetchText('.navbar-nav li:nth-child(8) a'), "Social", "Correct Navigation-Social Text");
            test.assertEquals(this.getElementAttribute('.navbar-nav li:nth-child(8) a', 'href'), '#social-section', 'Correct Navigation-Social Link');

        // Sign Up Button
        test.assertExists('#sign-up', 'Sign Up Button Found');
        test.assertEquals(this.fetchText('#sign-up strong'), "Sign up", "Correct Sign Up Button Text");
        test.assertEquals(this.getElementAttribute('#sign-up', 'href'), 'http://fourdiamonds.donordrive.com/event/khs16', 'Correct Sign Up Link');

        // Donate Button
        test.assertExists('#donate', 'Donate Button Found');
        test.assertEquals(this.fetchText('#donate'), "Donate", "Correct Donate Button Text");
        test.assertEquals(this.getElementAttribute('#donate', 'href'), 'https://fourdiamonds.donordrive.com/index.cfm?fuseaction=donate.event&eventID=1179', 'Correct Donate Link');

        // Social Media Buttons
        test.assertElementCount('.social-list li', 4, '4 Social Media Buttons Found');

            // Facebook
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(1) a', 'href'), 'https://www.facebook.com/FourDiamondsFund', 'Correct Facebook Link');

            // Twitter
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(2) a', 'href'), 'https://twitter.com/khsminithon', 'Correct Twitter Link');

            // Instagram
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(3) a', 'href'), 'https://instagram.com/khsminithon/', 'Correct Instagram Link');

            // Google Group
            test.assertEquals(this.getElementAttribute('.social-list li:nth-child(4) a', 'href'), 'https://groups.google.com/forum/#!forum/khsminithon/join', 'Correct Google Group Link');

    });

    casper.run(function() {
        test.done();

         // work around "Unsafe JavaScript attempt to access frame with URL about:blank" error
        // http://stackoverflow.com/questions/26608391/using-phantomjs-to-embed-all-images-of-a-webpage-produces-warnings-but-works/26688062#26688062
        setTimeout(function() {
            phantom.exit();
        }, 0);

    });

});
<|endoftext|>