<commit_before>/*
 * addonUploader()
 * Extends fileUploader()
 * Also, this can only be used once per page.  Or you'll have lots of issues with closures and scope :)
 */

(function($) {
    /* Normalize results */
    function getErrors(results) {
      var errors = [];

      if(results.validation.messages) {
          $.each(results.validation.messages, function(i, v){
            if(v.type == "error") {
              errors.push(v.message);
            }
          });
      }
      return errors;
    }

    $.fn.addonUploader = function( options ) {
        var settings = {'filetypes': ['xpi', 'jar', 'xml'], 'getErrors': getErrors, 'cancel': $()};

        if (options) {
            $.extend( settings, options );
        }

        function parseErrorsFromJson(response) {
            var json, errors = [];
            try {
                json = JSON.parse(response);
            } catch(err) {
                errors = [gettext("There was a problem contacting the server.")];
            }
            if (!errors.length) {
                errors = settings['getErrors'](json);
            }
            return {
                errors: errors,
                json: json
            }
        }

        return $(this).each(function(){
            var $upload_field = $(this),
                file = {};

            /* Add some UI */

            var ui_parent = $('
', {'class': 'invisible-upload prominent cta', 'id': 'upload-file-widget'}),
                ui_link = $('', {'class': 'button prominent', 'href': '#', 'text': gettext('Select a file...')}),
                ui_details = $('
', {'class': 'upload-details', 'text': gettext('Your add-on should end with .xpi, .jar or .xml')});

            $upload_field.attr('disabled', false);
            $upload_field.wrap(ui_parent);
            $upload_field.before(ui_link);
            $upload_field.parent().after(ui_details);

            if (!z.capabilities.fileAPI) {
                $('.invisible-upload').addClass('legacy');
            }

            /* Get things started */

            var upload_box, upload_title, upload_progress_outside, upload_progress_inside,
                upload_status, upload_results, upload_status_percent, upload_status_progress,
                upload_status_cancel;

            $upload_field.fileUploader(settings);

            function textSize(bytes) {
                // Based on code by Cary Dunn (http://bit.ly/d8qbWc).
                var s = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
                if(bytes === 0) return bytes + " " + s[1];
                var e = Math.floor( Math.log(bytes) / Math.log(1024) );
                return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
            }

            function updateStatus(percentage, size) {
                if (percentage) {
                    upload_status.show();
                    p = Math.round(percentage);
                    size = (p / 100) * size;

                    // L10n: {0} is the percent of the file that has been uploaded.
                    upload_status_percent.text(format(gettext('{0}% complete'), [p]));

                    // L10n: "{bytes uploaded} of {total filesize}".
                    upload_status_progress.text(format(gettext('{0} of {1}'),
                                [textSize(size), textSize(file.size)]));
                }
            }

            /* Bind the events */

            $upload_field.bind("upload_start", function(e, _file){
                file = _file;

                /* Remove old upload box */
                if(upload_box) {
                    upload_box.remove();
                }

                /* Remove old errors */
                $upload_field.closest('form').find('.errorlist').remove();

                /* Don't allow submitting */
                $('.addon-upload-dependant').attr('disabled', true);
                $('.addon-upload-failure-dependant').attr({'disabled': true,
                                                           'checked': false});

                /* Create elements */
                upload_title = $('', {'id': 'upload-status-text'});
                upload_progress_outside = $('
', {'id': 'upload-status-bar'});
                upload_progress_inside = $('
').css('width', 0);
                upload_status = $('
', {'id': 'uploadstatus'}).hide();
                upload_status_percent = $('');
                upload_status_progress = $('');
                upload_status_cancel_a = $('', {'href': '#', 'text': gettext('Cancel')});
                upload_status_cancel = $(' · ');
                upload_results = $('
', {'id': 'upload-status-results'});
                upload_box = $("
", {'class': 'upload-status ajax-loading'}).hide();

                /* Set up structure */
                upload_box.append(upload_title);
                upload_progress_outside.append(upload_progress_inside);
                upload_box.append(upload_progress_outside);
                upload_status.append(upload_status_percent);
                upload_status.append("  ·  ");
                upload_status.append(upload_status_progress);
                upload_status.append(upload_status_cancel);
                upload_status_cancel.append(upload_status_cancel_a);

                upload_box.append(upload_status);
                upload_box.append(upload_results);

                /* Add to the dom and clean up upload_field */
                ui_details.after(upload_box);

                /* It's showtime! */
                upload_title.html(format(gettext('Uploading {0}'), [escape_(file.name)]));
                upload_box.show();

                upload_box.addClass("ajax-loading");

                upload_status_cancel_a.click(_pd(function(){
                    $upload_field.trigger("upload_action_abort");
                }));
            });

            $upload_field.bind("upload_progress", function(e, file, pct) {
                upload_progress_inside.animate({'width': pct + '%'},
                    {duration: 300, step:function(i){ updateStatus(i, file.size); } });
            });

            $upload_field.bind("upload_errors", function(e, file, errors, results){
                var all_errors = $.extend([], errors);  // be nice to other handlers
                upload_progress_inside.stop().css({'width': '100%'});

                if ($('input#id_upload').val()) {
                    $('.addon-upload-failure-dependant').attr({'disabled': false,
                                                               'checked': false});
                }

                $upload_field.val("").attr('disabled', false);
                $upload_field.trigger("reenable_uploader");

                upload_title.html(format(gettext('Error with {0}'), [escape_(file.name)]));

                upload_progress_outside.attr('class', 'bar-fail');
                upload_progress_inside.fadeOut();

                var error_message = format(ngettext(
                        "Your add-on failed validation with {0} error.",
                        "Your add-on failed validation with {0} errors.",
                        all_errors.length), [all_errors.length]);

                $("").text(error_message).appendTo(upload_results);

                var errors_ul = $('
', {'id': 'upload_errors'});

                $.each(all_errors.splice(0, 5), function(i, error) {
                    errors_ul.append($("
", {'html': error }));
                });

                if(all_errors.length > 0) {
                    var message = format(ngettext('…and {0} more',
                                                  '…and {0} more',
                                                  all_errors.length), [all_errors.length]);
                    errors_ul.append($('
', {'html': message}));
                }

                upload_results.append(errors_ul).addClass('status-fail');

                if (results && results.full_report_url) {
                    // There might not be a link to the full report
                    // if we get an early error like unsupported type.
                    upload_results.append($("", {'href': results.full_report_url,
                                                    'class': 'view-more',
                                                    'target': '_blank',
                                                    'text': gettext('See full validation report')}));
                }

            });

            $upload_field.bind("upload_finished", function(e, file, results) {
                upload_box.removeClass("ajax-loading");
                upload_status_cancel.remove();
            });

            $upload_field.bind("upload_success", function(e, file, results) {
                upload_title.html(format(gettext('Validating {0}'), [escape_(file.name)]));

                var animateArgs = {duration: 300, step:function(i){ updateStatus(i, file.size); }, complete: function() {
                    $upload_field.trigger("upload_success_results", [file, results]);
                }};

                upload_progress_inside.animate({'width': '100%'}, animateArgs);
            });

            $upload_field.bind("upload_onreadystatechange", function(e, file, xhr, aborted) {
                var errors = [],
                    $form = $upload_field.closest('form'),
                    json = {},
                    errOb;
                if (xhr.readyState == 4 && xhr.responseText &&
                        (xhr.status == 200 ||
                         xhr.status == 304 ||
                         xhr.status == 400)) {

                    errOb = parseErrorsFromJson(xhr.responseText);
                    errors = errOb.errors;
                    json = errOb.json;

                    if (json && json.upload && (
                          !json.validation ||
                          !_.some(_.pluck(json.validation.messages, 'fatal')))) {
                        $form.find('input#id_upload').val(json.upload);
                    }
                    if(errors.length > 0) {
                        $upload_field.trigger("upload_errors", [file, errors, json]);
                    } else {
                        $upload_field.trigger("upload_success", [file, json]);
                        $upload_field.trigger("upload_progress", [file, 100]);
                    }
                    $upload_field.trigger("upload_finished", [file]);

                } else if(xhr.readyState == 4 && !aborted) {
                    // L10n: first argument is an HTTP status code
                    errors = [format(gettext("Received an empty response from the server; status: {0}"),
                                     [xhr.status])];

                    $upload_field.trigger("upload_errors", [file, errors]);
                }
            });

            $upload_field.bind("upload_success_results", function(e, file, results) {
                if(results.error) {
                    // This shouldn't happen.  But it might.
                    var error = gettext('Unexpected server error while validating.');
                    $upload_field.trigger("upload_errors", [file, [error]]);
                    return;
                }

                // Validation results?  If not, fetch the json again.
                if(! results.validation) {
                    upload_progress_outside.attr('class', 'progress-idle');
                    // Not loaded yet. Try again!
                    setTimeout(function(){
                        $.ajax({
                            url: results.url,
                            dataType: 'json',
                            success: function(r) {
                                $upload_field.trigger("upload_success_results", [file, r]);
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                var errOb = parseErrorsFromJson(xhr.responseText);
                                $upload_field.trigger("upload_errors", [file, errOb.errors, errOb.json]);
                                $upload_field.trigger("upload_finished", [file]);
                            }
                        });
                    }, 1000);
                } else {
                    var errors = getErrors(results),
                        v = results.validation;
                    if(errors.length > 0) {
                        $upload_field.trigger("upload_errors", [file, errors, results]);
                        return;
                    }

                    $upload_field.val("").attr('disabled', false);

                    /* Allow submitting */
                    $('.addon-upload-dependant').attr('disabled', false);
                    $('.addon-upload-failure-dependant').attr({'disabled': true,
                                                               'checked': false});

                    upload_title.html(format(gettext('Finished validating {0}'), [escape_(file.name)]));

                    var message = "";

                    var warnings = v.warnings + v.notices;
                    if(warnings > 0) {
                        message = format(ngettext(
                                    "Your add-on passed validation with no errors and {0} warning.",
                                    "Your add-on passed validation with no errors and {0} warnings.",
                                    warnings), [warnings]);
                    } else {
                        message = gettext("Your add-on passed validation with no errors or warnings.");
                    }

                    upload_progress_outside.attr('class', 'bar-success');
                    upload_progress_inside.fadeOut();

                    $upload_field.trigger("reenable_uploader");

                    upload_results.addClass("status-pass");

                    $("").text(message).appendTo(upload_results);

                    if (results.full_report_url) {
                        // There might not be a link to the full report
                        // if we get an early error like unsupported type.
                        upload_results.append($("", {'href': results.full_report_url,
                                                        'target': '_blank',
                                                        'text': gettext('See full validation report')}));
                    }

                    $(".platform ul.error").empty();
                    $(".platform ul.errorlist").empty();
                    if (results.validation.detected_type == 'search' ||
                        results.validation.detected_type == 'webapp') {
                        $(".platform").hide();
                    } else {
                        $(".platform:hidden").show();
                        $('.platform label').removeClass('platform-disabled');
                        $('input.platform').attr('disabled', false);
                        if (results.platforms_to_exclude &&
                            results.platforms_to_exclude.length) {
                            // e.g. after uploading a Mobile add-on
                            var excluded = false;
                            $('input.platform').each(function(e) {
                                var $input = $(this);
                                if ($.inArray($input.val(),
                                              results.platforms_to_exclude) !== -1) {
                                    excluded = true;
                                    $('label[for=' + $input.attr('id') + ']').addClass('platform-disabled');
                                    $input.attr('checked', false);
                                    $input.attr('disabled', true);
                                }
                            });
                            $.each(['.desktop-platforms', '.mobile-platforms'], function(i, sel) {
                                var disabled = $(sel + ' input:disabled').length,
                                    all = $(sel + ' input').length;
                                if (disabled > 0 && disabled == all) {
                                    $(sel + ' label').addClass('platform-disabled');
                                }
                            });
                            if (excluded) {
                                var msg = gettext('Some platforms are not available for this type of add-on.');
                                $('.platform').prepend(
                                    format('

{0}

',
                                           msg));
                            }
                        }
                    }
                }

            });

        });
    };
})(jQuery);
<commit_msg>Change wording of validation summary (bug 643595)<commit_after>/*
 * addonUploader()
 * Extends fileUploader()
 * Also, this can only be used once per page.  Or you'll have lots of issues with closures and scope :)
 */

(function($) {
    /* Normalize results */
    function getErrors(results) {
      var errors = [];

      if(results.validation.messages) {
          $.each(results.validation.messages, function(i, v){
            if(v.type == "error") {
              errors.push(v.message);
            }
          });
      }
      return errors;
    }

    $.fn.addonUploader = function( options ) {
        var settings = {'filetypes': ['xpi', 'jar', 'xml'], 'getErrors': getErrors, 'cancel': $()};

        if (options) {
            $.extend( settings, options );
        }

        function parseErrorsFromJson(response) {
            var json, errors = [];
            try {
                json = JSON.parse(response);
            } catch(err) {
                errors = [gettext("There was a problem contacting the server.")];
            }
            if (!errors.length) {
                errors = settings['getErrors'](json);
            }
            return {
                errors: errors,
                json: json
            }
        }

        return $(this).each(function(){
            var $upload_field = $(this),
                file = {};

            /* Add some UI */

            var ui_parent = $('
', {'class': 'invisible-upload prominent cta', 'id': 'upload-file-widget'}),
                ui_link = $('', {'class': 'button prominent', 'href': '#', 'text': gettext('Select a file...')}),
                ui_details = $('
', {'class': 'upload-details', 'text': gettext('Your add-on should end with .xpi, .jar or .xml')});

            $upload_field.attr('disabled', false);
            $upload_field.wrap(ui_parent);
            $upload_field.before(ui_link);
            $upload_field.parent().after(ui_details);

            if (!z.capabilities.fileAPI) {
                $('.invisible-upload').addClass('legacy');
            }

            /* Get things started */

            var upload_box, upload_title, upload_progress_outside, upload_progress_inside,
                upload_status, upload_results, upload_status_percent, upload_status_progress,
                upload_status_cancel;

            $upload_field.fileUploader(settings);

            function textSize(bytes) {
                // Based on code by Cary Dunn (http://bit.ly/d8qbWc).
                var s = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
                if(bytes === 0) return bytes + " " + s[1];
                var e = Math.floor( Math.log(bytes) / Math.log(1024) );
                return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
            }

            function updateStatus(percentage, size) {
                if (percentage) {
                    upload_status.show();
                    p = Math.round(percentage);
                    size = (p / 100) * size;

                    // L10n: {0} is the percent of the file that has been uploaded.
                    upload_status_percent.text(format(gettext('{0}% complete'), [p]));

                    // L10n: "{bytes uploaded} of {total filesize}".
                    upload_status_progress.text(format(gettext('{0} of {1}'),
                                [textSize(size), textSize(file.size)]));
                }
            }

            /* Bind the events */

            $upload_field.bind("upload_start", function(e, _file){
                file = _file;

                /* Remove old upload box */
                if(upload_box) {
                    upload_box.remove();
                }

                /* Remove old errors */
                $upload_field.closest('form').find('.errorlist').remove();

                /* Don't allow submitting */
                $('.addon-upload-dependant').attr('disabled', true);
                $('.addon-upload-failure-dependant').attr({'disabled': true,
                                                           'checked': false});

                /* Create elements */
                upload_title = $('', {'id': 'upload-status-text'});
                upload_progress_outside = $('
', {'id': 'upload-status-bar'});
                upload_progress_inside = $('
').css('width', 0);
                upload_status = $('
', {'id': 'uploadstatus'}).hide();
                upload_status_percent = $('');
                upload_status_progress = $('');
                upload_status_cancel_a = $('', {'href': '#', 'text': gettext('Cancel')});
                upload_status_cancel = $(' · ');
                upload_results = $('
', {'id': 'upload-status-results'});
                upload_box = $("
", {'class': 'upload-status ajax-loading'}).hide();

                /* Set up structure */
                upload_box.append(upload_title);
                upload_progress_outside.append(upload_progress_inside);
                upload_box.append(upload_progress_outside);
                upload_status.append(upload_status_percent);
                upload_status.append("  ·  ");
                upload_status.append(upload_status_progress);
                upload_status.append(upload_status_cancel);
                upload_status_cancel.append(upload_status_cancel_a);

                upload_box.append(upload_status);
                upload_box.append(upload_results);

                /* Add to the dom and clean up upload_field */
                ui_details.after(upload_box);

                /* It's showtime! */
                upload_title.html(format(gettext('Uploading {0}'), [escape_(file.name)]));
                upload_box.show();

                upload_box.addClass("ajax-loading");

                upload_status_cancel_a.click(_pd(function(){
                    $upload_field.trigger("upload_action_abort");
                }));
            });

            $upload_field.bind("upload_progress", function(e, file, pct) {
                upload_progress_inside.animate({'width': pct + '%'},
                    {duration: 300, step:function(i){ updateStatus(i, file.size); } });
            });

            $upload_field.bind("upload_errors", function(e, file, errors, results){
                var all_errors = $.extend([], errors);  // be nice to other handlers
                upload_progress_inside.stop().css({'width': '100%'});

                if ($('input#id_upload').val()) {
                    $('.addon-upload-failure-dependant').attr({'disabled': false,
                                                               'checked': false});
                }

                $upload_field.val("").attr('disabled', false);
                $upload_field.trigger("reenable_uploader");

                upload_title.html(format(gettext('Error with {0}'), [escape_(file.name)]));

                upload_progress_outside.attr('class', 'bar-fail');
                upload_progress_inside.fadeOut();

                var error_message = format(ngettext(
                        "Your add-on failed validation with {0} error.",
                        "Your add-on failed validation with {0} errors.",
                        all_errors.length), [all_errors.length]);

                $("").text(error_message).appendTo(upload_results);

                var errors_ul = $('
', {'id': 'upload_errors'});

                $.each(all_errors.splice(0, 5), function(i, error) {
                    errors_ul.append($("
", {'html': error }));
                });

                if(all_errors.length > 0) {
                    var message = format(ngettext('…and {0} more',
                                                  '…and {0} more',
                                                  all_errors.length), [all_errors.length]);
                    errors_ul.append($('
', {'html': message}));
                }

                upload_results.append(errors_ul).addClass('status-fail');

                if (results && results.full_report_url) {
                    // There might not be a link to the full report
                    // if we get an early error like unsupported type.
                    upload_results.append($("", {'href': results.full_report_url,
                                                    'class': 'view-more',
                                                    'target': '_blank',
                                                    'text': gettext('See full validation report')}));
                }

            });

            $upload_field.bind("upload_finished", function(e, file, results) {
                upload_box.removeClass("ajax-loading");
                upload_status_cancel.remove();
            });

            $upload_field.bind("upload_success", function(e, file, results) {
                upload_title.html(format(gettext('Validating {0}'), [escape_(file.name)]));

                var animateArgs = {duration: 300, step:function(i){ updateStatus(i, file.size); }, complete: function() {
                    $upload_field.trigger("upload_success_results", [file, results]);
                }};

                upload_progress_inside.animate({'width': '100%'}, animateArgs);
            });

            $upload_field.bind("upload_onreadystatechange", function(e, file, xhr, aborted) {
                var errors = [],
                    $form = $upload_field.closest('form'),
                    json = {},
                    errOb;
                if (xhr.readyState == 4 && xhr.responseText &&
                        (xhr.status == 200 ||
                         xhr.status == 304 ||
                         xhr.status == 400)) {

                    errOb = parseErrorsFromJson(xhr.responseText);
                    errors = errOb.errors;
                    json = errOb.json;

                    if (json && json.upload && (
                          !json.validation ||
                          !_.some(_.pluck(json.validation.messages, 'fatal')))) {
                        $form.find('input#id_upload').val(json.upload);
                    }
                    if(errors.length > 0) {
                        $upload_field.trigger("upload_errors", [file, errors, json]);
                    } else {
                        $upload_field.trigger("upload_success", [file, json]);
                        $upload_field.trigger("upload_progress", [file, 100]);
                    }
                    $upload_field.trigger("upload_finished", [file]);

                } else if(xhr.readyState == 4 && !aborted) {
                    // L10n: first argument is an HTTP status code
                    errors = [format(gettext("Received an empty response from the server; status: {0}"),
                                     [xhr.status])];

                    $upload_field.trigger("upload_errors", [file, errors]);
                }
            });

            $upload_field.bind("upload_success_results", function(e, file, results) {
                if(results.error) {
                    // This shouldn't happen.  But it might.
                    var error = gettext('Unexpected server error while validating.');
                    $upload_field.trigger("upload_errors", [file, [error]]);
                    return;
                }

                // Validation results?  If not, fetch the json again.
                if(! results.validation) {
                    upload_progress_outside.attr('class', 'progress-idle');
                    // Not loaded yet. Try again!
                    setTimeout(function(){
                        $.ajax({
                            url: results.url,
                            dataType: 'json',
                            success: function(r) {
                                $upload_field.trigger("upload_success_results", [file, r]);
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                var errOb = parseErrorsFromJson(xhr.responseText);
                                $upload_field.trigger("upload_errors", [file, errOb.errors, errOb.json]);
                                $upload_field.trigger("upload_finished", [file]);
                            }
                        });
                    }, 1000);
                } else {
                    var errors = getErrors(results),
                        v = results.validation;
                    if(errors.length > 0) {
                        $upload_field.trigger("upload_errors", [file, errors, results]);
                        return;
                    }

                    $upload_field.val("").attr('disabled', false);

                    /* Allow submitting */
                    $('.addon-upload-dependant').attr('disabled', false);
                    $('.addon-upload-failure-dependant').attr({'disabled': true,
                                                               'checked': false});

                    upload_title.html(format(gettext('Finished validating {0}'), [escape_(file.name)]));

                    var message = "";

                    var warnings = v.warnings + v.notices;
                    if(warnings > 0) {
                        message = format(ngettext(
                                    "Your add-on passed validation with no errors and {0} message.",
                                    "Your add-on passed validation with no errors and {0} messages.",
                                    warnings), [warnings]);
                    } else {
                        message = gettext("Your add-on passed validation with no errors or warnings.");
                    }

                    upload_progress_outside.attr('class', 'bar-success');
                    upload_progress_inside.fadeOut();

                    $upload_field.trigger("reenable_uploader");

                    upload_results.addClass("status-pass");

                    $("").text(message).appendTo(upload_results);

                    if (results.full_report_url) {
                        // There might not be a link to the full report
                        // if we get an early error like unsupported type.
                        upload_results.append($("", {'href': results.full_report_url,
                                                        'target': '_blank',
                                                        'text': gettext('See full validation report')}));
                    }

                    $(".platform ul.error").empty();
                    $(".platform ul.errorlist").empty();
                    if (results.validation.detected_type == 'search' ||
                        results.validation.detected_type == 'webapp') {
                        $(".platform").hide();
                    } else {
                        $(".platform:hidden").show();
                        $('.platform label').removeClass('platform-disabled');
                        $('input.platform').attr('disabled', false);
                        if (results.platforms_to_exclude &&
                            results.platforms_to_exclude.length) {
                            // e.g. after uploading a Mobile add-on
                            var excluded = false;
                            $('input.platform').each(function(e) {
                                var $input = $(this);
                                if ($.inArray($input.val(),
                                              results.platforms_to_exclude) !== -1) {
                                    excluded = true;
                                    $('label[for=' + $input.attr('id') + ']').addClass('platform-disabled');
                                    $input.attr('checked', false);
                                    $input.attr('disabled', true);
                                }
                            });
                            $.each(['.desktop-platforms', '.mobile-platforms'], function(i, sel) {
                                var disabled = $(sel + ' input:disabled').length,
                                    all = $(sel + ' input').length;
                                if (disabled > 0 && disabled == all) {
                                    $(sel + ' label').addClass('platform-disabled');
                                }
                            });
                            if (excluded) {
                                var msg = gettext('Some platforms are not available for this type of add-on.');
                                $('.platform').prepend(
                                    format('

{0}

',
                                           msg));
                            }
                        }
                    }
                }

            });

        });
    };
})(jQuery);
<|endoftext|>


<commit_before>// Copyright 2014 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// UMD bolierplate based on https://github.com/umdjs/umd/blob/master/returnExports.js
// Supports node.js, AMD and the browser.
//
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.structuredLog = factory();
  }
}(this, function () {
  function MessageTemplate(messageTemplate) {
    var self = this;

    self.raw = messageTemplate;
    self.tokens = [];

    var ptre = /\{@?\w+}/g;
    var res;
    var textStart = 0;
    while ((res = ptre.exec(messageTemplate)) !== null)
    {
      if (res.index !== textStart) {
        self.tokens.push({text: messageTemplate.slice(textStart, res.index)});
      }

      var destructure = false;

      var tok = res[0].slice(1, -1);
      if (tok.indexOf('@') === 0) {
        tok = tok.slice(1);
        destructure = true;
      }

      self.tokens.push({name: tok, destructure: destructure, raw: res[0]});
      textStart = ptre.lastIndex;
    }

    if (textStart >= 0 && textStart < messageTemplate.length) {
      self.tokens.push({text: messageTemplate.slice(textStart)});
    }
  }

  var capture = function(o, destructure) {
    if (typeof o === 'function') {
      return o.toString();
    }
    if (typeof o === 'object') {
      // Could use instanceof Date, but this way will be kinder
      // to values passed from other contexts...
      if (destructure || typeof o.toISOString === 'function') {
        return o;
      }
      return o.toString();
    }
    return o;
  };

  MessageTemplate.prototype.bindProperties = function(positionalArgs) {
    var self = this;
    var result = {};

    var nextArg = 0;
    for(var i = 0; i < self.tokens.length && nextArg < positionalArgs.length; ++i) {
      var token = self.tokens[i];
      if (typeof token.name === 'string') {
        var p = positionalArgs[nextArg];
        result[token.name] = capture(p, token.destructure);
        nextArg++;
      }
    }

    while (nextArg < positionalArgs.length) {
      var px = positionalArgs[nextArg];
      if (typeof px !== 'undefined') {
        result['a' + nextArg] = capture(px);
      }
      nextArg++;
    }

    return result;
  };

  var toText = function(o) {
    if (typeof o === 'undefined') {
      return 'undefined';
    }
    if (o === null) {
      return 'null';
    }
    if (typeof o === 'string') {
      return o;
    }
    if (typeof o === 'number') {
      return o.toString();
    }
    if (typeof o === 'boolean') {
      return o.toString();
    }
    if (typeof o.toISOString === 'function') {
      return o.toISOString();
    }
    if (typeof o === 'object') {
      var s = JSON.stringify(o);
      if (s.length > 70) {
        s = s.slice(0, 67) + '...';
      }
      return s;
    }
    return o.toString();
  };

  MessageTemplate.prototype.render = function(properties) {
    var self = this;

    var result = [];
    for (var i = 0; i < self.tokens.length; ++i) {
      var token = self.tokens[i];
      if (typeof token.name === 'string') {
        if (properties.hasOwnProperty(token.name)) {
          result.push(toText(properties[token.name]));
        } else {
          result.push(token.raw);
        }
      } else {
        result.push(token.text);
      }
    }
    return result.join('');
  };

  var enrich = function(evt, properties, destructure) {
    for (var prop in properties) {
      if (properties.hasOwnProperty(prop) &&
        !evt.properties.hasOwnProperty(prop)) {
        evt.properties[prop] = capture(properties[prop], destructure);
      }
    }
  };

  var createEvent = function(level, messageTemplate) {
    var l = Array.prototype.shift.call(arguments);
    var mt = Array.prototype.shift.call(arguments);
    var parsedTemplate = new MessageTemplate(mt);
    var boundProperties = parsedTemplate.bindProperties(arguments);
    return new LogEvent(new Date(), l, parsedTemplate, boundProperties);
  };

  function LogEvent(timestamp, level, messageTemplate, properties) {
    var self = this;
    self.timestamp = timestamp;
    self.level = level;
    self.messageTemplate = messageTemplate;
    self.properties = properties;
  }

  LogEvent.prototype.renderedMessage = function() {
    var self = this;
    return self.messageTemplate.render(self.properties);
  };

  var errorLevel = 'ERROR';
  var warnLevel = 'WARN';
  var infoLevel = 'INFO';
  var verboseLevel = 'VERBOSE';

  function LevelMap(initial) {
    var self = this;
    self.levels = {};

    if (initial !== 'OFF') {
      var sequence = [errorLevel, warnLevel, infoLevel, verboseLevel];

      var below = false;
      for (var i = 0; i < sequence.length; ++i) {
        var level = sequence[i];
        self.levels[level] = !below;
        if (level === initial) {
          below = true;
        }
      }
    }
  }

  LevelMap.prototype.isEnabled = function(level) {
    var self = this;
    return self.levels[level || 'NONE'] || false;
  };

  function Pipeline(elements, endWith) {
    var self = this;
    self.elements = elements;
    self.endWith = endWith || [];

    var head = function(evt) { };
    var makeHead = function(el) {
      var oldHead = head;
      return function(evt) { el(evt, oldHead); };
    };

    for (var i = self.elements.length - 1; i >= 0; --i) {
      var el = self.elements[i];
      head = makeHead(el);
    }
    self.head = head;
  }

  Pipeline.prototype.execute = function(evt) {
    var self = this;
    self.head(evt);
  };

  Pipeline.prototype.end = function(cb) {
    var self = this;
    var remaining = self.endWith.length;
    if (remaining === 0) {
      cb();
      return;
    }
    var onEnd = function() {
      remaining--;
      if (remaining === 0) {
        cb();
      }
    };
    for (var i = 0; i < self.endWith.length; ++i) {
      self.endWith[i](onEnd);
    }
  };

  var createLogger = function(levelMap, pipeline) {
    var self = function() {
      self.info.apply(null, arguments);
    };

    self.toString = function() { return 'Logger'; };

    self.emit = function(evt) {
      if (!levelMap.isEnabled(evt.level)) {
        return;
      }
      pipeline.execute(evt);
    };

    var invoke = function(level, messageTemplate, args) {
      if (!levelMap.isEnabled(level)) {
        return;
      }

      // Template caching opportunity here
      var parsedTemplate = new MessageTemplate(messageTemplate);
      var boundProperties = parsedTemplate.bindProperties(args);

      var evt = new LogEvent(new Date(), level, parsedTemplate, boundProperties);

      pipeline.execute(evt);
    };

    self.verbose = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(verboseLevel, mt, arguments);
    };

    self.info = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(infoLevel, mt, arguments);
    };

    self.warn = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(warnLevel, mt, arguments);
    };

    self.error = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(errorLevel, mt, arguments);
    };

    self.using = function(properties, destructure){
      var enriched = new Pipeline([
        function(evt, next){
          enrich(evt, properties, destructure);
          pipeline.execute(evt);
          next(evt);
        }
      ]);
      return createLogger(levelMap, enriched);
    };

    self.end = function(cb) {
      pipeline.end(cb);
    };

    return self;
  };

  function LoggerConfiguration() {
    var self = this;

    var minimumLevel = infoLevel;
    var pipeline = [];
    var endWith = [];

    self.pipe = function(element) {
      pipeline.push(element);
      return self;
    };

    self.minimumLevel = function(lvl) {
      if (pipeline.length !== 0) {
        var lm = new LevelMap(lvl);
        return self.filter(function(evt) {
          return lm.isEnabled(evt.level);
        });
      }

      minimumLevel = (lvl || 'INFORMATION').toUpperCase();
      return self;
    };

    self.writeTo = function(sinkOrEmit, onError) {
      if (typeof sinkOrEmit.emit !== 'function' && typeof sinkOrEmit === 'function') {
        return self.writeTo({
          emit: sinkOrEmit,
          toString: function() { return sinkOrEmit.toString(); }
        }, minimumLevel);
      }

      if (typeof sinkOrEmit.end === 'function') {
        endWith.push(sinkOrEmit.end);
      }

      return self.pipe(function(evt, next) {
        try {
          sinkOrEmit.emit(evt);
        } catch (err) {
          if (typeof onError === 'function') {
            onError(err, evt, next);
          } else if (!evt.properties.isSelfLog) {
            var notification = createEvent(errorLevel, 'Failed to write event {@event} to {sink}: {error}', evt, sinkOrEmit, err);
            notification.properties.isSelfLog = true;
            next(notification);
          }
        }
        next(evt);
      });
    };

    self.enrich = function(functionOrProperties, destructure) {
      if (typeof functionOrProperties === 'object') {
        return self.enrich(function(event){
          enrich(event, functionOrProperties, destructure);
        });
      } else if (typeof functionOrProperties === 'function') {
        return self.pipe(function(evt, next) {
          functionOrProperties(evt);
          next(evt);
        });
      } else {
        throw new Error('Events can be enriched using either a function, or a hash of properties');
      }
    };

    self.filter = function(filter) {
      return self.pipe(function(evt, next) {
        if(filter(evt)) {
          next(evt);
        }
      });
    };

    self.createLogger = function() {
      var levelMap = new LevelMap(minimumLevel);
      return createLogger(levelMap, new Pipeline(pipeline, endWith));
    };
  }

  function Serilog() {
    var self = this;

    self.sink = {};
    self.filter = {};
    self.enrich = {};

    self.filter.selfLog = function() {
      return function(evt) {
        return evt.properties.isSelfLog;
      };
    };

    self.filter.notSelfLog = function() {
      return function(evt) {
        return !evt.properties.isSelfLog;
      };
    };

    self.enrich.withStack = function() {
      return function(evt) {
        try {
          throw new Error('getstack');
        } catch (err) {
          var stack = err.stack;
          if (stack.indexOf('Error: getstack') === 0) {
            stack = stack.slice(stack.indexOf('\n') + 1);
          }
          stack = stack.replace(/^[ ]+/g, '');

          if (!evt.properties.hasOwnProperty('stack')) {
            evt.properties.stack = stack;
          }
        }
      };
    };
  }

  Serilog.prototype.configuration = function() {
    return new LoggerConfiguration();
  };

  Serilog.prototype.event = createEvent;

  return new Serilog();
}));
<commit_msg>Fixed tests after changes from INFORMATION to INFO and WARNING to WARN.<commit_after>// Copyright 2014 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// UMD bolierplate based on https://github.com/umdjs/umd/blob/master/returnExports.js
// Supports node.js, AMD and the browser.
//
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.structuredLog = factory();
  }
}(this, function () {
  function MessageTemplate(messageTemplate) {
    var self = this;

    self.raw = messageTemplate;
    self.tokens = [];

    var ptre = /\{@?\w+}/g;
    var res;
    var textStart = 0;
    while ((res = ptre.exec(messageTemplate)) !== null)
    {
      if (res.index !== textStart) {
        self.tokens.push({text: messageTemplate.slice(textStart, res.index)});
      }

      var destructure = false;

      var tok = res[0].slice(1, -1);
      if (tok.indexOf('@') === 0) {
        tok = tok.slice(1);
        destructure = true;
      }

      self.tokens.push({name: tok, destructure: destructure, raw: res[0]});
      textStart = ptre.lastIndex;
    }

    if (textStart >= 0 && textStart < messageTemplate.length) {
      self.tokens.push({text: messageTemplate.slice(textStart)});
    }
  }

  var capture = function(o, destructure) {
    if (typeof o === 'function') {
      return o.toString();
    }
    if (typeof o === 'object') {
      // Could use instanceof Date, but this way will be kinder
      // to values passed from other contexts...
      if (destructure || typeof o.toISOString === 'function') {
        return o;
      }
      return o.toString();
    }
    return o;
  };

  MessageTemplate.prototype.bindProperties = function(positionalArgs) {
    var self = this;
    var result = {};

    var nextArg = 0;
    for(var i = 0; i < self.tokens.length && nextArg < positionalArgs.length; ++i) {
      var token = self.tokens[i];
      if (typeof token.name === 'string') {
        var p = positionalArgs[nextArg];
        result[token.name] = capture(p, token.destructure);
        nextArg++;
      }
    }

    while (nextArg < positionalArgs.length) {
      var px = positionalArgs[nextArg];
      if (typeof px !== 'undefined') {
        result['a' + nextArg] = capture(px);
      }
      nextArg++;
    }

    return result;
  };

  var toText = function(o) {
    if (typeof o === 'undefined') {
      return 'undefined';
    }
    if (o === null) {
      return 'null';
    }
    if (typeof o === 'string') {
      return o;
    }
    if (typeof o === 'number') {
      return o.toString();
    }
    if (typeof o === 'boolean') {
      return o.toString();
    }
    if (typeof o.toISOString === 'function') {
      return o.toISOString();
    }
    if (typeof o === 'object') {
      var s = JSON.stringify(o);
      if (s.length > 70) {
        s = s.slice(0, 67) + '...';
      }
      return s;
    }
    return o.toString();
  };

  MessageTemplate.prototype.render = function(properties) {
    var self = this;

    var result = [];
    for (var i = 0; i < self.tokens.length; ++i) {
      var token = self.tokens[i];
      if (typeof token.name === 'string') {
        if (properties.hasOwnProperty(token.name)) {
          result.push(toText(properties[token.name]));
        } else {
          result.push(token.raw);
        }
      } else {
        result.push(token.text);
      }
    }
    return result.join('');
  };

  var enrich = function(evt, properties, destructure) {
    for (var prop in properties) {
      if (properties.hasOwnProperty(prop) &&
        !evt.properties.hasOwnProperty(prop)) {
        evt.properties[prop] = capture(properties[prop], destructure);
      }
    }
  };

  var createEvent = function(level, messageTemplate) {
    var l = Array.prototype.shift.call(arguments);
    var mt = Array.prototype.shift.call(arguments);
    var parsedTemplate = new MessageTemplate(mt);
    var boundProperties = parsedTemplate.bindProperties(arguments);
    return new LogEvent(new Date(), l, parsedTemplate, boundProperties);
  };

  function LogEvent(timestamp, level, messageTemplate, properties) {
    var self = this;
    self.timestamp = timestamp;
    self.level = level;
    self.messageTemplate = messageTemplate;
    self.properties = properties;
  }

  LogEvent.prototype.renderedMessage = function() {
    var self = this;
    return self.messageTemplate.render(self.properties);
  };

  var errorLevel = 'ERROR';
  var warnLevel = 'WARN';
  var infoLevel = 'INFO';
  var verboseLevel = 'VERBOSE';

  function LevelMap(initial) {
    var self = this;
    self.levels = {};

    if (initial !== 'OFF') {
      var sequence = [errorLevel, warnLevel, infoLevel, verboseLevel];

      var below = false;
      for (var i = 0; i < sequence.length; ++i) {
        var level = sequence[i];
        self.levels[level] = !below;
        if (level === initial) {
          below = true;
        }
      }
    }
  }

  LevelMap.prototype.isEnabled = function(level) {
    var self = this;
    return self.levels[level || 'NONE'] || false;
  };

  function Pipeline(elements, endWith) {
    var self = this;
    self.elements = elements;
    self.endWith = endWith || [];

    var head = function(evt) { };
    var makeHead = function(el) {
      var oldHead = head;
      return function(evt) { el(evt, oldHead); };
    };

    for (var i = self.elements.length - 1; i >= 0; --i) {
      var el = self.elements[i];
      head = makeHead(el);
    }
    self.head = head;
  }

  Pipeline.prototype.execute = function(evt) {
    var self = this;
    self.head(evt);
  };

  Pipeline.prototype.end = function(cb) {
    var self = this;
    var remaining = self.endWith.length;
    if (remaining === 0) {
      cb();
      return;
    }
    var onEnd = function() {
      remaining--;
      if (remaining === 0) {
        cb();
      }
    };
    for (var i = 0; i < self.endWith.length; ++i) {
      self.endWith[i](onEnd);
    }
  };

  var createLogger = function(levelMap, pipeline) {
    var self = function() {
      self.info.apply(null, arguments);
    };

    self.toString = function() { return 'Logger'; };

    self.emit = function(evt) {
      if (!levelMap.isEnabled(evt.level)) {
        return;
      }
      pipeline.execute(evt);
    };

    var invoke = function(level, messageTemplate, args) {
      if (!levelMap.isEnabled(level)) {
        return;
      }

      // Template caching opportunity here
      var parsedTemplate = new MessageTemplate(messageTemplate);
      var boundProperties = parsedTemplate.bindProperties(args);

      var evt = new LogEvent(new Date(), level, parsedTemplate, boundProperties);

      pipeline.execute(evt);
    };

    self.verbose = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(verboseLevel, mt, arguments);
    };

    self.info = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(infoLevel, mt, arguments);
    };

    self.warn = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(warnLevel, mt, arguments);
    };

    self.error = function(messageTemplate) {
      var mt = Array.prototype.shift.call(arguments);
      invoke(errorLevel, mt, arguments);
    };

    self.using = function(properties, destructure){
      var enriched = new Pipeline([
        function(evt, next){
          enrich(evt, properties, destructure);
          pipeline.execute(evt);
          next(evt);
        }
      ]);
      return createLogger(levelMap, enriched);
    };

    self.end = function(cb) {
      pipeline.end(cb);
    };

    return self;
  };

  function LoggerConfiguration() {
    var self = this;

    var minimumLevel = infoLevel;
    var pipeline = [];
    var endWith = [];

    self.pipe = function(element) {
      pipeline.push(element);
      return self;
    };

    self.minimumLevel = function(lvl) {
      if (pipeline.length !== 0) {
        var lm = new LevelMap(lvl);
        return self.filter(function(evt) {
          return lm.isEnabled(evt.level);
        });
      }

      minimumLevel = (lvl || 'INFO').toUpperCase();
      return self;
    };

    self.writeTo = function(sinkOrEmit, onError) {
      if (typeof sinkOrEmit.emit !== 'function' && typeof sinkOrEmit === 'function') {
        return self.writeTo({
          emit: sinkOrEmit,
          toString: function() { return sinkOrEmit.toString(); }
        }, minimumLevel);
      }

      if (typeof sinkOrEmit.end === 'function') {
        endWith.push(sinkOrEmit.end);
      }

      return self.pipe(function(evt, next) {
        try {
          sinkOrEmit.emit(evt);
        } catch (err) {
          if (typeof onError === 'function') {
            onError(err, evt, next);
          } else if (!evt.properties.isSelfLog) {
            var notification = createEvent(errorLevel, 'Failed to write event {@event} to {sink}: {error}', evt, sinkOrEmit, err);
            notification.properties.isSelfLog = true;
            next(notification);
          }
        }
        next(evt);
      });
    };

    self.enrich = function(functionOrProperties, destructure) {
      if (typeof functionOrProperties === 'object') {
        return self.enrich(function(event){
          enrich(event, functionOrProperties, destructure);
        });
      } else if (typeof functionOrProperties === 'function') {
        return self.pipe(function(evt, next) {
          functionOrProperties(evt);
          next(evt);
        });
      } else {
        throw new Error('Events can be enriched using either a function, or a hash of properties');
      }
    };

    self.filter = function(filter) {
      return self.pipe(function(evt, next) {
        if(filter(evt)) {
          next(evt);
        }
      });
    };

    self.createLogger = function() {
      var levelMap = new LevelMap(minimumLevel);
      return createLogger(levelMap, new Pipeline(pipeline, endWith));
    };
  }

  function Serilog() {
    var self = this;

    self.sink = {};
    self.filter = {};
    self.enrich = {};

    self.filter.selfLog = function() {
      return function(evt) {
        return evt.properties.isSelfLog;
      };
    };

    self.filter.notSelfLog = function() {
      return function(evt) {
        return !evt.properties.isSelfLog;
      };
    };

    self.enrich.withStack = function() {
      return function(evt) {
        try {
          throw new Error('getstack');
        } catch (err) {
          var stack = err.stack;
          if (stack.indexOf('Error: getstack') === 0) {
            stack = stack.slice(stack.indexOf('\n') + 1);
          }
          stack = stack.replace(/^[ ]+/g, '');

          if (!evt.properties.hasOwnProperty('stack')) {
            evt.properties.stack = stack;
          }
        }
      };
    };
  }

  Serilog.prototype.configuration = function() {
    return new LoggerConfiguration();
  };

  Serilog.prototype.event = createEvent;

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


<commit_before>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { dbFoundations } from '/db/dbFoundations';
import { dbCompanyArchive } from '/db/dbCompanyArchive';
import { limitMethod } from '/server/imports/rateLimit';
import { debug } from '/server/imports/debug';

Meteor.methods({
  changeFoundCompanyName(foundationId, companyName) {
    check(this.userId, String);
    check(foundationId, String);
    check(companyName, String);
    changeFoundCompanyName(Meteor.user(), foundationId, companyName);

    return true;
  }
});
function changeFoundCompanyName(user, foundationId, companyName) {
  debug.log('changeFoundCompanyName', {user, foundationId, companyName});
  if (! user.profile.isAdmin) {
    throw new Meteor.Error(403, '您並非金融管理會委員，無法進行此操作！');
  }
  const foundCompanyData = dbFoundations.findOne(foundationId, {
    fields: {
      companyName: 1
    }
  });
  if (! foundCompanyData) {
    throw new Meteor.Error(404, '找不到要編輯的新創計劃，該新創計劃可能已經創立成功或失敗！');
  }
  dbFoundations.update(foundationId, {
    $set: {
      companyName: companyName
    }
  });
  dbCompanyArchive.update(foundationId, {
    $set: {
      name: companyName
    }
  });
}
limitMethod('changeFoundCompanyName');
<commit_msg>新創公司更名將會產生公司更名紀錄<commit_after>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { dbFoundations } from '/db/dbFoundations';
import { dbCompanyArchive } from '/db/dbCompanyArchive';
import { dbLog } from '/db/dbLog';
import { limitMethod } from '/server/imports/rateLimit';
import { debug } from '/server/imports/debug';

Meteor.methods({
  changeFoundCompanyName(companyId, newCompanyName) {
    check(this.userId, String);
    check(companyId, String);
    check(newCompanyName, String);
    changeFoundCompanyName(Meteor.user(), companyId, newCompanyName);

    return true;
  }
});
function changeFoundCompanyName(user, companyId, newCompanyName) {
  debug.log('changeFoundCompanyName', {user, companyId, newCompanyName});
  if (! user.profile.isAdmin) {
    throw new Meteor.Error(403, '您並非金融管理會委員，無法進行此操作！');
  }
  const foundCompanyData = dbFoundations.findOne(companyId, {
    fields: {
      companyName: 1
    }
  });
  if (! foundCompanyData) {
    throw new Meteor.Error(404, '找不到要編輯的新創計劃，該新創計劃可能已經創立成功或失敗！');
  }

  const oldCompanyName = foundCompanyData.companyName;

  dbLog.insert({
    logType: '公司更名',
    userId: [user._id],
    companyId: companyId,
    data: {
      oldCompanyName,
      newCompanyName
    },
    createdAt: new Date()
  });
  dbFoundations.update(companyId, {
    $set: {
      companyName: newCompanyName
    }
  });
  dbCompanyArchive.update(companyId, {
    $set: {
      name: newCompanyName
    }
  });
}
limitMethod('changeFoundCompanyName');
<|endoftext|>


<commit_before>/*
 * Require-selector
 *
 * AMD selector module.
 *
 * Used as a fall-back selector module when jQuery or another CSS selector library isn't present.
 * (if one is, then simply add a paths config to map the 'selector' dependency to that instead)
 *
 * The selector module checks for document.querySelectorAll support, and then runs some basic tests
 * to ensure attribute selector, direct child and sibling selector support.
 *
 * If it fails, the Sizzle selector engine is dynamically downloaded from cdnjs.com
 * (http://cdnjs.cloudflare.com/ajax/libs/sizzle/1.4.4/sizzle.min.js).
 *
 * (source: http://caniuse.com/queryselector)
 *
 * Uses the require-is module to conditionally load sizzle
 *
 */
define(['is!~./native-selector?http://cdnjs.cloudflare.com/ajax/libs/sizzle/1.4.4/sizzle.min.js'], function(sizzle) {
  var wrappers = [];

  var selector = function(selector, context) {
    var selected;
    if (typeof selector != 'string')
      selected = selector;
    else
      selected = sizzle ? sizzle(selector, context) : (context || document).querySelectorAll(selector);

    for (var i = 0; i < wrappers.length; i++) {
      if (typeof wrappers[i] == 'function')
        selected = wrappers[i](selected);
    }

    for (var i = 0; i < wrappers.length; i++) {
      if (typeof wrappers[i] == 'object')
        for (var p in wrappers[i]) {
          var curFunc = wrappers[i][p];
          selected[p] = function() {
            curFunc.apply(arguments[0], Array.prototype.splice.call(arguments, 1));
          }
        }
    }
    return selected;
  }

  selector.addWrapper = function(wrapper) {
    wrappers.push(wrapper);
  }

  selector.normalize = function(name, normalize) {
    var names = name.split(',');
    for (var i = 0; i < names.length; i++)
      names[i] = normalize(names[i]);
    return names.join(',');
  }
  selector.load = function(name, req, load, config) {
    var names = name.split(',');
    req(names, function() {
      for (var i = 0; i < arguments.length; i++) {
        var wrapper = arguments[i];
        if (!wrapper)
          continue;
        if (wrappers.indexOf(wrapper) == -1) {
          wrappers.push(wrapper);
          if (wrapper.setSelectorEngine)
            wrapper.setSelectorEngine(selector);
          if (wrapper.setQueryEngine)
            wrapper.setQueryEngine(selector);
        }
      }
      load(selector);
    });
  }
  return selector;
});
<commit_msg>updated wrapper system<commit_after>/*
 * Require-selector
 *
 * AMD selector module.
 *
 * Used as a fall-back selector module when jQuery or another CSS selector library isn't present.
 * (if one is, then simply add a paths config to map the 'selector' dependency to that instead)
 *
 * The selector module checks for document.querySelectorAll support, and then runs some basic tests
 * to ensure attribute selector, direct child and sibling selector support.
 *
 * If it fails, the Sizzle selector engine is dynamically downloaded from cdnjs.com
 * (http://cdnjs.cloudflare.com/ajax/libs/sizzle/1.4.4/sizzle.min.js).
 *
 * (source: http://caniuse.com/queryselector)
 *
 * Uses the require-is module to conditionally load sizzle
 *
 */
define(['is!~./native-selector?http://cdnjs.cloudflare.com/ajax/libs/sizzle/1.4.4/sizzle.min.js'], function(sizzle) {
  var wrappers = [];

  var selector = function(selector, context) {
    var selected;
    if (typeof selector != 'string')
      selected = selector;
    else
      selected = sizzle ? sizzle(selector, context) : (context || document).querySelectorAll(selector);

    for (var i = 0; i < wrappers.length; i++)
      if (typeof wrappers[i] == 'function')
        selected = wrappers[i](selected);
      else if (typeof wrappers[i] == 'object')
        for (var p in wrappers[i]) {
          var curFunc = wrappers[i][p];
          if (typeof curFunc == 'function')
            selected[p] = function() {
              Array.prototype.splice.call(arguments, 0, 0, this);
              curFunc.apply(this, arguments);
            }
        }

    return selected;
  }

  selector.addWrapper = function(wrapper) {
    if (wrapper.setSelectorEngine)
      wrapper.setSelectorEngine(selector);
    if (wrapper.setQueryEngine)
      wrapper.setQueryEngine(selector);
    if (wrappers.indexOf(wrapper) == -1)
      wrappers.push(wrapper);
  }

  selector.normalize = function(name, normalize) {
    var names = name.split(',');
    for (var i = 0; i < names.length; i++)
      names[i] = normalize(names[i]);
    return names.join(',');
  }
  selector.load = function(name, req, load, config) {
    var names = name.split(',');
    req(names, function() {
      for (var i = 0; i < arguments.length; i++) {
        var wrapper = arguments[i];
        if (!wrapper)
          continue;
        selector.addWrapper(wrapper);
      }
      load(selector);
    });
  }
  return selector;
});
<|endoftext|>


<commit_before>const moment = require("moment-timezone");
const PillReminder = require("./schemas");

module.exports = {

	check: function (onReminder) {
		getAllReminders(onReminder);
	},

	setAnswered: function (chatId) {
		setAnswered(chatId);
	},

	setDelay: function (chatId, minutes, onUpdated) {
		setDelay(chatId, minutes, onUpdated);
	},

	insert: function (chatId, date, pillType, time, onInserted) {
		insertReminder(chatId, date, pillType, time, onInserted);
	},

	hasReminder: function (chatId, onHasReminder, onNoReminder) {
		hasReminderByChatId(chatId, onHasReminder, onNoReminder);
	},

	remove: function (chatId, onRemoved) {
		removeReminder(chatId, onRemoved);
	}
}

function getAllReminders(onReminder) {
	let time = moment().format("HH:mm");
	console.info('find by time: \'' + time + '\';');
	let condition = {
		$or: [
			{ time: time },
			{ isWaitingForAnswer: true, delayedTo: null },
			{ isWaitingForAnswer: true, delayedTo: time }
		]
	};

	PillReminder
		.find(condition)
		.exec()
		.then(reminders => {
			console.info(JSON.stringify(reminders));
			console.info(reminders.length + ' rows were received');

			reminders.forEach(reminder => {

				reminder.isWaitingForAnswer = true;
				reminder.delayedTo = null;

				reminder
					.save()
					.then((a) => {
						console.log("isWaitingForAnswer saved " + JSON.stringify(a));
						onReminder(reminder.chatId, reminder.firstDayOfPill, reminder.pillType);
					});
			}, this);
		})
		.catch(ex => console.log(ex));
}

function setAnswered(chatId) {
	console.log("setting aswered for " + chatId);
	PillReminder
		.update({ chatId: chatId }, { isWaitingForAnswer: false, delayedTo: null })
		.then((a) => {
			console.log("set aswered for " + chatId + " " + JSON.stringify(a));
		})
		.catch((ex) => console.log(ex));
}

function setDelay(chatId, minutes, onUpdated) {
	let delayedTo = moment().add(minutes, "minute").format("HH:mm");
	console.log("setting delayed to " + delayedTo);
	PillReminder
		.findOneAndUpdate({ chatId: chatId, isWaitingForAnswer: true }, { delayedTo: delayedTo })
		.then(updatedDoc => {
			console.log("set delay for " + chatId + " " + JSON.stringify(updatedDoc));
			if (!onUpdated) return;
			if (updatedDoc) {
				onUpdated(true);
			}
			else {
				onUpdated(false);
			}
		})
		.catch((ex) => console.log(ex));

}

function insertReminder(chatId, firstDayOfPill, pillType, time, onInserted) {
	console.log("inserting " + chatId + " " + firstDayOfPill + " " + pillType + " " + time);

	// I have to remove all the reminders for this chatId
	removeReminder(chatId, hasRemoved => {

		let reminder = new PillReminder({
			chatId: chatId,
			firstDayOfPill: firstDayOfPill,
			pillType: pillType,
			time: time
		});

		reminder
			.save(saved => {
				console.log("inserted");
				console.log(JSON.stringify(saved));
				if (onInserted) {
					onInserted(hasRemoved);
				}
			})
			.catch(ex => console.log(ex));
	});
}

function removeReminder(chatId, onRemoved) {
	console.log("Deleting: " + chatId);

	PillReminder
		.remove({ chatId: chatId })
		.then((result) => {
			console.log(JSON.stringify(result) + " " + result["n"]);
			let hasRemoved = result.n > 0;
			console.log("Deleted: " + chatId + " n: " + result.n);
			onRemoved(hasRemoved);
		})
		.catch(ex => console.log(ex));
}

function hasReminderByChatId(chatId, onHasReminder, onNoReminder) {
	console.info('find by chatId: \'' + chatId + '\';');

	PillReminder
		.find({ chatId: chatId })
		.then(reminders => {
			console.log(reminders);
			console.log(reminders.length + ' rows were received');

			let reminder = reminders[0];
			if (reminder) {
				onHasReminder(reminder.firstDayOfPill, reminder.pillType, reminder.time);
			}
			else {
				onNoReminder();
			}
		})
		.catch(ex => console.log(ex));
}<commit_msg>fix removereminder<commit_after>const moment = require("moment-timezone");
const PillReminder = require("./schemas");

module.exports = {

	check: function (onReminder) {
		getAllReminders(onReminder);
	},

	setAnswered: function (chatId) {
		setAnswered(chatId);
	},

	setDelay: function (chatId, minutes, onUpdated) {
		setDelay(chatId, minutes, onUpdated);
	},

	insert: function (chatId, date, pillType, time, onInserted) {
		insertReminder(chatId, date, pillType, time, onInserted);
	},

	hasReminder: function (chatId, onHasReminder, onNoReminder) {
		hasReminderByChatId(chatId, onHasReminder, onNoReminder);
	},

	remove: function (chatId, onRemoved) {
		removeReminder(chatId, onRemoved);
	}
}

function getAllReminders(onReminder) {
	let time = moment().format("HH:mm");
	console.info('find by time: \'' + time + '\';');
	let condition = {
		$or: [
			{ time: time },
			{ isWaitingForAnswer: true, delayedTo: null },
			{ isWaitingForAnswer: true, delayedTo: time }
		]
	};

	PillReminder
		.find(condition)
		.exec()
		.then(reminders => {
			console.info(JSON.stringify(reminders));
			console.info(reminders.length + ' rows were received');

			reminders.forEach(reminder => {

				reminder.isWaitingForAnswer = true;
				reminder.delayedTo = null;

				reminder
					.save()
					.then((a) => {
						console.log("isWaitingForAnswer saved " + JSON.stringify(a));
						onReminder(reminder.chatId, reminder.firstDayOfPill, reminder.pillType);
					});
			}, this);
		})
		.catch(ex => console.log(ex));
}

function setAnswered(chatId) {
	console.log("setting aswered for " + chatId);
	PillReminder
		.update({ chatId: chatId }, { isWaitingForAnswer: false, delayedTo: null })
		.then((a) => {
			console.log("set aswered for " + chatId + " " + JSON.stringify(a));
		})
		.catch((ex) => console.log(ex));
}

function setDelay(chatId, minutes, onUpdated) {
	let delayedTo = moment().add(minutes, "minute").format("HH:mm");
	console.log("setting delayed to " + delayedTo);
	PillReminder
		.findOneAndUpdate({ chatId: chatId, isWaitingForAnswer: true }, { delayedTo: delayedTo })
		.then(updatedDoc => {
			console.log("set delay for " + chatId + " " + JSON.stringify(updatedDoc));
			if (!onUpdated) return;
			if (updatedDoc) {
				onUpdated(true);
			}
			else {
				onUpdated(false);
			}
		})
		.catch((ex) => console.log(ex));

}

function insertReminder(chatId, firstDayOfPill, pillType, time, onInserted) {
	console.log("inserting " + chatId + " " + firstDayOfPill + " " + pillType + " " + time);

	// I have to remove all the reminders for this chatId
	removeReminder(chatId, hasRemoved => {

		let reminder = new PillReminder({
			chatId: chatId,
			firstDayOfPill: firstDayOfPill,
			pillType: pillType,
			time: time
		});

		reminder
			.save(saved => {
				console.log("inserted");
				console.log(JSON.stringify(saved));
				if (onInserted) {
					onInserted(hasRemoved);
				}
			})
			.catch(ex => console.log(ex));
	});
}

function removeReminder(chatId, onRemoved) {
	console.log("Deleting: " + chatId);

	PillReminder
		.remove({ chatId: chatId })
		.then((res) => {
			console.log(JSON.stringify(res) + " " + res.result.n);
			let hasRemoved = res.result.n > 0;
			console.log("Deleted: " + chatId + " n: " + res.result.n);
			onRemoved(hasRemoved);
		})
		.catch(ex => console.log(ex));
}

function hasReminderByChatId(chatId, onHasReminder, onNoReminder) {
	console.info('find by chatId: \'' + chatId + '\';');

	PillReminder
		.find({ chatId: chatId })
		.then(reminders => {
			console.log(reminders);
			console.log(reminders.length + ' rows were received');

			let reminder = reminders[0];
			if (reminder) {
				onHasReminder(reminder.firstDayOfPill, reminder.pillType, reminder.time);
			}
			else {
				onNoReminder();
			}
		})
		.catch(ex => console.log(ex));
}<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';

const debug = false;

class CombustionCharges extends Analyzer {
  static dependencies = {
    spellUsable: SpellUsable,
    abilityTracker: AbilityTracker,
  };

  lowPhoenixFlamesCharges = 0;
  lowFireBlastCharges = 0;
  lastCastEvent = null;
  badCast = false;

  constructor(...args) {
    super(...args);
    this.hasPhoenixFlames = this.selectedCombatant.hasTalent(SPELLS.PHOENIX_FLAMES_TALENT.id);
    this.hasFlameOn = this.selectedCombatant.hasTalent(SPELLS.FLAME_ON_TALENT.id);
    this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.COMBUSTION), this.onCombustion);
  }

  //When Combustion is cast, check to see how many charges of Fire Blast and Phoenix Flames are available. If there is less than (Max Charges - 1) then its a bad Combustion cast.
  onCombustion(event) {
    const fireBlastCharges = this.spellUsable.chargesAvailable(SPELLS.FIRE_BLAST.id);
    const phoenixFlamesCharges = (this.spellUsable.chargesAvailable(SPELLS.PHOENIX_FLAMES_TALENT.id) || 0);
    this.badCast = false;
    this.lastCastEvent = event;

    if (this.hasFlameOn && fireBlastCharges < 2) {
      this.lowFireBlastCharges += 1;
      this.badCast = true;
      debug && this.log("Fire Blast Charges: " + fireBlastCharges);
      debug && this.log("Low Fire Blast Charges");
    } else if (!this.hasFlameOn && fireBlastCharges < 1) {
      this.lowFireBlastCharges += 1;
      this.badCast = true;
      debug && this.log("Fire Blast Charges: " + fireBlastCharges);
      debug && this.log("Low Fire Blast Charges");
    }

    if (this.hasPhoenixFlames && phoenixFlamesCharges < 2) {
      this.active.lowPhoenixFlamesCharges += 1;
      this.badCast = true;
      debug && this.log("Phoenix Flames Charges: " + phoenixFlamesCharges);
      debug && this.log("Low Phoenix Flames Charges");
    }

    if (this.badCast) {
      this.flagTimeline();
    }
  }

  flagTimeline() {
    this.lastCastEvent.meta = this.lastCastEvent.meta || {};
    this.lastCastEvent.meta.isInefficientCast = true;
    this.lastCastEvent.meta.inefficientCastReason = `This Combustion was cast with a low amount of Fire Blast ${this.hasPhoenixFlames ? 'and/or Phoenix Flames' : '' }charges. In order to get the most out of your Combustion casts, ensure that you have at least ${this.hasFlameOn ? '2' : '1' } Fire Blast charges${this.hasPhoenixFlames ? ' and 2 Phoenix Flames charges' : '' }. `;
  }

  get phoenixFlamesChargeUtil() {
    return 1 - (this.lowPhoenixFlamesCharges / this.abilityTracker.getAbility(SPELLS.COMBUSTION.id).casts);
  }

  get fireBlastChargeUtil() {
    return 1 - (this.lowFireBlastCharges / this.abilityTracker.getAbility(SPELLS.COMBUSTION.id).casts);
  }

  get phoenixFlamesThresholds() {
    return {
      actual: this.phoenixFlamesChargeUtil,
      isLessThan: {
        minor: 1,
        average: .65,
        major: .45,
      },
      style: 'percentage',
    };
  }

  get fireBlastThresholds() {
    return {
      actual: this.fireBlastChargeUtil,
      isLessThan: {
        minor: 1,
        average: .65,
        major: .45,
      },
      style: 'percentage',
    };
  }

  suggestions(when) {
    if (this.hasPhoenixFlames) {
      when(this.phoenixFlamesThresholds)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(<>You cast <SpellLink id={SPELLS.COMBUSTION.id} /> {this.lowPhoenixFlamesCharges} times with less than 2 charges of <SpellLink id={SPELLS.PHOENIX_FLAMES_TALENT.id} />. Make sure you are saving at least 2 charges while Combustion is on cooldown so you can get as many <SpellLink id={SPELLS.HOT_STREAK.id} /> procs as possible before Combustion ends.</>)
          .icon(SPELLS.COMBUSTION.icon)
          .actual(`${formatPercentage(this.phoenixFlamesChargeUtil)}% Utilization`)
          .recommended(`${formatPercentage(recommended)} is recommended`);
      });
    }
    when(this.fireBlastThresholds)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(<>You cast <SpellLink id={SPELLS.COMBUSTION.id} /> {this.lowFireBlastCharges} times with less than {this.selectedCombatant.hasTalent(SPELLS.FLAME_ON_TALENT.id) ? '2' : '1' } charges of <SpellLink id={SPELLS.FIRE_BLAST.id} />. Make sure you are saving at least {this.selectedCombatant.hasTalent(SPELLS.FLAME_ON_TALENT.id) ? '2' : '1' } charges while Combustion is on cooldown so you can get as many <SpellLink id={SPELLS.HOT_STREAK.id} /> procs as possible before Combustion ends.</>)
          .icon(SPELLS.COMBUSTION.icon)
          .actual(`${formatPercentage(this.fireBlastChargeUtil)}% Utilization`)
          .recommended(`${formatPercentage(recommended)} is recommended`);
      });
  }
}
export default CombustionCharges;
<commit_msg>Update CombustionCharges.js<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';

const debug = false;

class CombustionCharges extends Analyzer {
  static dependencies = {
    spellUsable: SpellUsable,
    abilityTracker: AbilityTracker,
  };

  lowPhoenixFlamesCharges = 0;
  lowFireBlastCharges = 0;
  lastCastEvent = null;
  badCast = false;

  constructor(...args) {
    super(...args);
    this.hasPhoenixFlames = this.selectedCombatant.hasTalent(SPELLS.PHOENIX_FLAMES_TALENT.id);
    this.hasFlameOn = this.selectedCombatant.hasTalent(SPELLS.FLAME_ON_TALENT.id);
    this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.COMBUSTION), this.onCombustion);
  }

  //When Combustion is cast, check to see how many charges of Fire Blast and Phoenix Flames are available. If there is less than (Max Charges - 1) then its a bad Combustion cast.
  onCombustion(event) {
    const fireBlastCharges = this.spellUsable.chargesAvailable(SPELLS.FIRE_BLAST.id);
    const phoenixFlamesCharges = (this.spellUsable.chargesAvailable(SPELLS.PHOENIX_FLAMES_TALENT.id) || 0);
    this.badCast = false;
    this.lastCastEvent = event;

    if (this.hasFlameOn && fireBlastCharges < 2) {
      this.lowFireBlastCharges += 1;
      this.badCast = true;
      debug && this.log("Fire Blast Charges: " + fireBlastCharges);
      debug && this.log("Low Fire Blast Charges");
    } else if (!this.hasFlameOn && fireBlastCharges < 1) {
      this.lowFireBlastCharges += 1;
      this.badCast = true;
      debug && this.log("Fire Blast Charges: " + fireBlastCharges);
      debug && this.log("Low Fire Blast Charges");
    }

    if (this.hasPhoenixFlames && phoenixFlamesCharges < 2) {
      this.lowPhoenixFlamesCharges += 1;
      this.badCast = true;
      debug && this.log("Phoenix Flames Charges: " + phoenixFlamesCharges);
      debug && this.log("Low Phoenix Flames Charges");
    }

    if (this.badCast) {
      this.flagTimeline();
    }
  }

  flagTimeline() {
    this.lastCastEvent.meta = this.lastCastEvent.meta || {};
    this.lastCastEvent.meta.isInefficientCast = true;
    this.lastCastEvent.meta.inefficientCastReason = `This Combustion was cast with a low amount of Fire Blast ${this.hasPhoenixFlames ? 'and/or Phoenix Flames' : '' }charges. In order to get the most out of your Combustion casts, ensure that you have at least ${this.hasFlameOn ? '2' : '1' } Fire Blast charges${this.hasPhoenixFlames ? ' and 2 Phoenix Flames charges' : '' }. `;
  }

  get phoenixFlamesChargeUtil() {
    return 1 - (this.lowPhoenixFlamesCharges / this.abilityTracker.getAbility(SPELLS.COMBUSTION.id).casts);
  }

  get fireBlastChargeUtil() {
    return 1 - (this.lowFireBlastCharges / this.abilityTracker.getAbility(SPELLS.COMBUSTION.id).casts);
  }

  get phoenixFlamesThresholds() {
    return {
      actual: this.phoenixFlamesChargeUtil,
      isLessThan: {
        minor: 1,
        average: .65,
        major: .45,
      },
      style: 'percentage',
    };
  }

  get fireBlastThresholds() {
    return {
      actual: this.fireBlastChargeUtil,
      isLessThan: {
        minor: 1,
        average: .65,
        major: .45,
      },
      style: 'percentage',
    };
  }

  suggestions(when) {
    if (this.hasPhoenixFlames) {
      when(this.phoenixFlamesThresholds)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(<>You cast <SpellLink id={SPELLS.COMBUSTION.id} /> {this.lowPhoenixFlamesCharges} times with less than 2 charges of <SpellLink id={SPELLS.PHOENIX_FLAMES_TALENT.id} />. Make sure you are saving at least 2 charges while Combustion is on cooldown so you can get as many <SpellLink id={SPELLS.HOT_STREAK.id} /> procs as possible before Combustion ends.</>)
          .icon(SPELLS.COMBUSTION.icon)
          .actual(`${formatPercentage(this.phoenixFlamesChargeUtil)}% Utilization`)
          .recommended(`${formatPercentage(recommended)} is recommended`);
      });
    }
    when(this.fireBlastThresholds)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(<>You cast <SpellLink id={SPELLS.COMBUSTION.id} /> {this.lowFireBlastCharges} times with less than {this.selectedCombatant.hasTalent(SPELLS.FLAME_ON_TALENT.id) ? '2' : '1' } charges of <SpellLink id={SPELLS.FIRE_BLAST.id} />. Make sure you are saving at least {this.selectedCombatant.hasTalent(SPELLS.FLAME_ON_TALENT.id) ? '2' : '1' } charges while Combustion is on cooldown so you can get as many <SpellLink id={SPELLS.HOT_STREAK.id} /> procs as possible before Combustion ends.</>)
          .icon(SPELLS.COMBUSTION.icon)
          .actual(`${formatPercentage(this.fireBlastChargeUtil)}% Utilization`)
          .recommended(`${formatPercentage(recommended)} is recommended`);
      });
  }
}
export default CombustionCharges;
<|endoftext|>


<commit_before>'use strict';

// Root controllers manage data at root '/'
// For now only messageInfo notification is handled here.
var rootControllers = angular.module('rootControllers', []);

rootControllers.controller('RootCtrl', ['$rootScope', '$scope', '$location', 'Tournament', function($rootScope, $scope, $location, Tournament) {
  console.log("root controller");
  // get message info from redirects.
  $scope.messageInfo = $rootScope.messageInfo;
  // reset to nil var message info in root scope.
  $rootScope.messageInfo = undefined;

  // fetch World Cup tournament
  $scope.tournamentData =  Tournament.getWorldCup();
}]);
<commit_msg>added title in HTML header for home<commit_after>'use strict';

// Root controllers manage data at root '/'
// For now only messageInfo notification is handled here.
var rootControllers = angular.module('rootControllers', []);

rootControllers.controller('RootCtrl', ['$rootScope', '$scope', '$location', 'Tournament', function($rootScope, $scope, $location, Tournament) {
  console.log("root controller");
  $rootScope.title = 'gonawin';
  // get message info from redirects.
  $scope.messageInfo = $rootScope.messageInfo;
  // reset to nil var message info in root scope.
  $rootScope.messageInfo = undefined;

  // fetch World Cup tournament
  $scope.tournamentData =  Tournament.getWorldCup();
}]);
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch'
import folderReducer from './folder'

// folders actions
const GENERATE_REPORT = 'GENERATE_REPORT'
export function markCompleted(id) {
  return {
    type: GENERATE_REPORT,
    payload: { id },
  }
}

const REQUEST_FOLDERS = 'REQUEST_FOLDERS'
function requestFolders(operator) {
  return {
    type: REQUEST_FOLDERS,
    payload: { operator },
  }
}

const RECEIVE_FOLDERS = 'RECEIVE_FOLDERS'
function receiveFolders(operator, json) {
  return {
    type: RECEIVE_FOLDERS,
    payload: {
      operator,
      folders: json,
      receivedAt: Date.now(),
    },
  }
}

const RECEIVE_FOLDERS_FAILED = 'RECEIVE_FOLDERS_FAILED'
function receiveFoldersFailed(err) {
  return {
    type: RECEIVE_FOLDERS_FAILED,
    payload: err,
    error: true,
  }
}

export function fetchFolders(operator) {
  return dispatch => {
    dispatch(requestFolders(operator))
    return fetch(`http://localhost:3000/operators/${operator}/folders`)
      .then(response => response.json())
      .then(json => dispatch(receiveFolders(operator, json)))
      .catch(err => dispatch(receiveFoldersFailed(err)))
  }
}

// folders reducer
export default function folders(state = {
  isFetching: false,
  error: null,
  list: [],
}, action) {
  const { payload } = action
  switch (action.type) {
    case 'REQUEST_FOLDERS':
      return Object.assign({}, state, { isFetching: true })

    case 'RECEIVE_FOLDERS':
      return Object.assign({}, state, {
        isFetching: false,
        list: payload.folders,
      })

    case 'RECEIVE_FOLDERS_FAILED':
      return Object.assign({}, state, {
        isFetching: false,
        error: payload,
      })

    case 'GENERATE_REPORT':
      return state.list.map(folder => {
        if (payload.id === folder.id) {
          return folderReducer(folder, action)
        }
        return state
      })

    default:
      return state
  }
}
<commit_msg>rename failed request action<commit_after>import fetch from 'isomorphic-fetch'
import folderReducer from './folder'

// folders actions
const GENERATE_REPORT = 'GENERATE_REPORT'
export function markCompleted(id) {
  return {
    type: GENERATE_REPORT,
    payload: { id },
  }
}

const REQUEST_FOLDERS = 'REQUEST_FOLDERS'
function requestFolders(operator) {
  return {
    type: REQUEST_FOLDERS,
    payload: { operator },
  }
}

const RECEIVE_FOLDERS = 'RECEIVE_FOLDERS'
function receiveFolders(operator, json) {
  return {
    type: RECEIVE_FOLDERS,
    payload: {
      operator,
      folders: json,
      receivedAt: Date.now(),
    },
  }
}

const FETCH_FOLDERS_FAILED = 'FETCH_FOLDERS_FAILED'
function receiveFoldersFailed(err) {
  return {
    type: FETCH_FOLDERS_FAILED,
    payload: err,
    error: true,
  }
}

export function fetchFolders(operator) {
  return dispatch => {
    dispatch(requestFolders(operator))
    return fetch(`http://localhost:3000/operators/${operator}/folders`)
      .then(response => response.json())
      .then(json => dispatch(receiveFolders(operator, json)))
      .catch(err => dispatch(receiveFoldersFailed(err)))
  }
}

// folders reducer
export default function folders(state = {
  isFetching: false,
  error: null,
  list: [],
}, action) {
  const { payload } = action
  switch (action.type) {
    case 'REQUEST_FOLDERS':
      return Object.assign({}, state, { isFetching: true })

    case 'RECEIVE_FOLDERS':
      return Object.assign({}, state, {
        isFetching: false,
        list: payload.folders,
      })

    case 'FETCH_FOLDERS_FAILED':
      return Object.assign({}, state, {
        isFetching: false,
        error: payload,
      })

    case 'GENERATE_REPORT':
      return state.list.map(folder => {
        if (payload.id === folder.id) {
          return folderReducer(folder, action)
        }
        return state
      })

    default:
      return state
  }
}
<|endoftext|>