<commit_before>/*
 * notie.js - A clean and simple notification plugin (alert/growl style) for javascript, with no dependencies.
 *
 * Copyright (c) 2015 Jared Reich
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 * https://jaredreich.com/projects/notie.js
 *
 * Version:  1.1.1
 *
*/

var notie = function(){

    // SETTINGS
    // *********************************************

    // General
    var shadow = true;
    var font_size_small = '18px';
    var font_size_big = '24px';
    var font_change_screen_width = 600;
    var animation_delay = 0.3;

    // notie.alert colors
    var alert_color_success_background = '#57BF57';
    var alert_color_warning_background = '#E3B771';
    var alert_color_error_background = '#E1715B';
    var alert_color_info_background = '#4D82D6';
    var alert_color_text = '#FFF';

    // notie.confirm colors
    var confirm_color_background = '#4D82D6';
    var confirm_color_yes_background = '#57bf57';
    var confirm_color_no_background = '#E1715B';
    var confirm_color_text = '#FFF';
    var confirm_color_yes_text = '#FFF';
    var confirm_color_no_text = '#FFF';

    // ID's for use within your own .css file (OPTIONAL)
    // (Be sure to use !important to override the javascript)
    // Example: #notie-alert-inner { padding: 30px !important; }
    var alert_outer_id = 'notie-alert-outer';
    var alert_inner_id = 'notie-alert-inner';
    var alert_text_id = 'notie-alert-text';
    var confirm_outer_id = 'notie-confirm-outer';
    var confirm_inner_id = 'notie-confirm-inner';
    var confirm_backdrop_id = 'notie-confirm-backdrop';
    var confirm_yes_id = 'notie-confirm-yes';
    var confirm_no_id = 'notie-confirm-no';
    var confirm_text_id = 'notie-confirm-text';
    var confirm_yes_text_id = 'notie-confirm-yes-text';
    var confirm_no_text_id = 'notie-confirm-no-text';

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

    // NOTIE.ALERT
    // *********************************************

    // notie elements and styling
    var alert_outer = document.createElement('div');
    alert_outer.id = alert_outer_id;
    alert_outer.style.position = 'fixed';
    alert_outer.style.top = '0';
    alert_outer.style.left = '0';
    alert_outer.style.zIndex = '999999999';
    alert_outer.style.height = 'auto';
    alert_outer.style.width = '100%';
    alert_outer.style.display = 'none';
    alert_outer.style.textAlign = 'center';
    alert_outer.style.cursor = 'default';
    alert_outer.style.MozTransition = '';
    alert_outer.style.WebkitTransition = '';
    alert_outer.style.transition = '';
    alert_outer.style.cursor = 'pointer';
    alert_outer.addEventListener('click', function() {
        clearTimeout(alert_timeout_1);
        clearTimeout(alert_timeout_2);
        alert_hide();
    });
    var alert_inner = document.createElement('div');
    alert_inner.id = alert_inner_id;
    alert_inner.style.padding = '20px';
    alert_inner.style.display = 'table-cell';
    alert_inner.style.verticalAlign = 'middle';
    alert_outer.appendChild(alert_inner);

    // Initialize notie text
    var alert_text = document.createElement('span');
    alert_text.id = alert_text_id;
    alert_text.style.color = alert_color_text;
    if (window.innerWidth <= font_change_screen_width) { alert_text.style.fontSize = font_size_small; }
    else { alert_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { alert_text.style.fontSize = font_size_small; }
        else { alert_text.style.fontSize = font_size_big; }
    }, true);
    alert_inner.appendChild(alert_text);

    // Attach notie to the body element
    document.body.appendChild(alert_outer);

    // Declare variables
    var height = 0;
    var is_showing = false;
    var alert_timeout_1;
    var alert_timeout_2;
    var was_clicked_counter = 0;

    function alert(type, message, seconds) {

        was_clicked_counter++;

        setTimeout(function() {
            was_clicked_counter--;
        }, (animation_delay * 1000 + 10));

        if (was_clicked_counter == 1) {

            if (is_showing) {

                clearTimeout(alert_timeout_1);
                clearTimeout(alert_timeout_2);

                alert_hide(function() {
                    alert_show(type, message, seconds);
                });

            }
            else {
                alert_show(type, message, seconds);
            }

        }

    }

    function alert_show(type, message, seconds) {

        is_showing = true;

        var duration = 0;
        if (typeof seconds == 'undefined') {
            var duration = 3000;
        }
        else if (seconds < 1) {
            duration = 1000;
        }
        else {
            duration = seconds * 1000;
        }

        // Set notie type (background color)
        switch(type) {
            case 1:
                alert_outer.style.backgroundColor = alert_color_success_background;
                break;
            case 2:
                alert_outer.style.backgroundColor = alert_color_warning_background;
                break;
            case 3:
                alert_outer.style.backgroundColor = alert_color_error_background;
                break;
            case 4:
                alert_outer.style.backgroundColor = alert_color_info_background;
                break;
        }

        // Set notie text
        alert_text.innerHTML = message;

        // Get notie's height
        alert_outer.style.top = '-10000px';
        alert_outer.style.display = 'table';
        alert_outer.style.top = '-' + alert_outer.offsetHeight - 5 + 'px';

        alert_timeout_1 = setTimeout(function() {

            if (shadow) { alert_outer.style.boxShadow = '0px 0px 10px 0px rgba(0,0,0,0.5)'; }
            alert_outer.style.MozTransition = 'all ' + animation_delay + 's ease';
            alert_outer.style.WebkitTransition = 'all ' + animation_delay + 's ease';
            alert_outer.style.transition = 'all ' + animation_delay + 's ease';

            alert_outer.style.top = 0;

            alert_timeout_2 = setTimeout(function() {

                alert_hide(function() {
                    // Nothing
                });

            }, duration);

        }, 20);

    }

    function alert_hide(callback) {

        alert_outer.style.top = '-' + alert_outer.offsetHeight - 5 + 'px';

        setTimeout(function() {

            if (shadow) { alert_outer.style.boxShadow = ''; }
            alert_outer.style.MozTransition = '';
            alert_outer.style.WebkitTransition = '';
            alert_outer.style.transition = '';

            alert_outer.style.top = '-10000px';

            is_showing = false;

            callback();

        }, (animation_delay * 1000 + 10));

    }

    // NOTIE.CONFIRM
    // *********************************************

    // confirm elements and styling
    var confirm_outer = document.createElement('div');
    confirm_outer.id = confirm_outer_id;
    confirm_outer.style.position = 'fixed';
    confirm_outer.style.top = '0';
    confirm_outer.style.left = '0';
    confirm_outer.style.zIndex = '999999998';
    confirm_outer.style.height = 'auto';
    confirm_outer.style.width = '100%';
    confirm_outer.style.display = 'none';
    confirm_outer.style.textAlign = 'center';
    confirm_outer.style.MozTransition = '';
    confirm_outer.style.WebkitTransition = '';
    confirm_outer.style.transition = '';

    var confirm_backdrop = document.createElement('div');
    confirm_backdrop.id = confirm_backdrop_id;
    confirm_backdrop.style.position = 'fixed';
    confirm_backdrop.style.top = '0';
    confirm_backdrop.style.left = '0';
    confirm_backdrop.style.zIndex = '999999997';
    confirm_backdrop.style.height = '100%';
    confirm_backdrop.style.width = '100%';
    confirm_backdrop.style.display = 'none';
    confirm_backdrop.style.backgroundColor = 'white';
    confirm_backdrop.style.MozTransition = 'all ' + animation_delay + 's ease';
    confirm_backdrop.style.WebkitTransition = 'all ' + animation_delay + 's ease';
    confirm_backdrop.style.transition = 'all ' + animation_delay + 's ease';
    confirm_backdrop.style.opacity = '0';
    confirm_backdrop.onclick = function() { confirm_hide(); }

    var confirm_inner = document.createElement('div');
    confirm_inner.id = confirm_inner_id;
    confirm_inner.style.boxSizing = 'border-box';
    confirm_inner.style.width = '100%';
    confirm_inner.style.padding = '20px';
    confirm_inner.style.display = 'block';
    confirm_inner.style.cursor = 'default';
    confirm_inner.style.backgroundColor = confirm_color_background;
    confirm_outer.appendChild(confirm_inner);

    var confirm_yes = document.createElement('div');
    confirm_yes.id = confirm_yes_id;
    confirm_yes.style.cssFloat = 'left';
    confirm_yes.style.height = '50px';
    confirm_yes.style.lineHeight = '50px';
    confirm_yes.style.width = '50%';
    confirm_yes.style.cursor = 'pointer';
    confirm_yes.style.backgroundColor = confirm_color_yes_background;
    confirm_outer.appendChild(confirm_yes);

    var confirm_no = document.createElement('div');
    confirm_no.id = confirm_no_id;
    confirm_no.style.cssFloat = 'right';
    confirm_no.style.height = '50px';
    confirm_no.style.lineHeight = '50px';
    confirm_no.style.width = '50%';
    confirm_no.style.cursor = 'pointer';
    confirm_no.style.backgroundColor = confirm_color_no_background;
    confirm_no.onclick = function() { confirm_hide(); }
    confirm_outer.appendChild(confirm_no);

    // Initialize confirm text
    var confirm_text = document.createElement('span');
    confirm_text.id = confirm_text_id;
    confirm_text.style.color = confirm_color_text;
    if (window.innerWidth <= font_change_screen_width) { confirm_text.style.fontSize = font_size_small; }
    else { confirm_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { confirm_text.style.fontSize = font_size_small; }
        else { confirm_text.style.fontSize = font_size_big; }
    }, true);
    confirm_inner.appendChild(confirm_text);

    var confirm_yes_text = document.createElement('span');
    confirm_yes_text.id = confirm_yes_text_id;
    confirm_yes_text.style.color = confirm_color_yes_text;
    if (window.innerWidth <= font_change_screen_width) { confirm_yes_text.style.fontSize = font_size_small; }
    else { confirm_yes_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { confirm_yes_text.style.fontSize = font_size_small; }
        else { confirm_yes_text.style.fontSize = font_size_big; }
    }, true);
    confirm_yes.appendChild(confirm_yes_text);

    var confirm_no_text = document.createElement('span');
    confirm_no_text.id = confirm_no_text_id;
    confirm_no_text.style.color = confirm_color_no_text;
    if (window.innerWidth <= font_change_screen_width) { confirm_no_text.style.fontSize = font_size_small; }
    else { confirm_no_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { confirm_no_text.style.fontSize = font_size_small; }
        else { confirm_no_text.style.fontSize = font_size_big; }
    }, true);
    confirm_no.appendChild(confirm_no_text);

    // Attach confirm elements to the body element
    document.body.appendChild(confirm_outer);
    document.body.appendChild(confirm_backdrop);

    // Declare variables
    var confirm_height = 0;
    var confirm_is_showing = false;

    function confirm(title, yes_text, no_text, yes_callback) {

        confirm_show(title, yes_text, no_text, yes_callback);

        // Hide notie.alert
        clearTimeout(alert_timeout_1);
        clearTimeout(alert_timeout_2);
        alert_hide();

    }
    function confirm_show(title, yes_text, no_text, yes_callback) {

        scroll_disable();

        // Yes callback function
        confirm_yes.onclick = function() {
            confirm_hide();
            setTimeout(function() {
                yes_callback();
            }, (animation_delay * 1000 + 10));
        }

        function confirm_show_inner() {

            // Set confirm text
            confirm_text.innerHTML = title;
            confirm_yes_text.innerHTML = yes_text;
            confirm_no_text.innerHTML = no_text;

            // Get confirm's height
            confirm_outer.style.top = '-10000px';
            confirm_outer.style.display = 'table';
            confirm_outer.style.top = '-' + confirm_outer.offsetHeight - 5 + 'px';
            confirm_backdrop.style.display = 'block';

            setTimeout(function() {

                if (shadow) { confirm_outer.style.boxShadow = '0px 0px 10px 0px rgba(0,0,0,0.5)'; }
                confirm_outer.style.MozTransition = 'all ' + animation_delay + 's ease';
                confirm_outer.style.WebkitTransition = 'all ' + animation_delay + 's ease';
                confirm_outer.style.transition = 'all ' + animation_delay + 's ease';

                confirm_outer.style.top = 0;
                confirm_backdrop.style.opacity = '0.75';

                setTimeout(function() {
                    confirm_is_showing = true;
                }, (animation_delay * 1000 + 10));

            }, 20);

        }

        if (confirm_is_showing) {
            confirm_hide();
            setTimeout(function() {
                confirm_show_inner();
            }, (animation_delay * 1000 + 10));
        }
        else {
            confirm_show_inner();
        }

    }

    function confirm_hide() {

        confirm_outer.style.top = '-' + confirm_outer.offsetHeight - 5 + 'px';
        confirm_backdrop.style.opacity = '0';

        setTimeout(function() {

            if (shadow) { confirm_outer.style.boxShadow = ''; }
            confirm_outer.style.MozTransition = '';
            confirm_outer.style.WebkitTransition = '';
            confirm_outer.style.transition = '';
            confirm_backdrop.style.display = 'none';

            confirm_outer.style.top = '-10000px';

            scroll_enable();

            confirm_is_showing = false;

        }, (animation_delay * 1000 + 10));

    }

    // SCROLL DISABLE AND ENABLE FOR NOTIE.CONFIRM
    // *********************************************
    var original_body_height, original_body_overflow;
    function scroll_disable() {
        original_body_height = document.body.style.height;
        original_body_overflow = document.body.style.overflow;
        document.body.style.height = '100%;';
        document.body.style.overflow = 'hidden';
    }
    function scroll_enable() {
        document.body.style.height = original_body_height;
        document.body.style.overflow = original_body_overflow;
    }

    return {
        alert: alert,
        confirm: confirm
    };

}();
<commit_msg>Support for CommonJS style loading<commit_after>/*
 * notie.js - A clean and simple notification plugin (alert/growl style) for javascript, with no dependencies.
 *
 * Copyright (c) 2015 Jared Reich
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 * https://jaredreich.com/projects/notie.js
 *
 * Version:  1.1.1
 *
*/

var notie = function(){

    // SETTINGS
    // *********************************************

    // General
    var shadow = true;
    var font_size_small = '18px';
    var font_size_big = '24px';
    var font_change_screen_width = 600;
    var animation_delay = 0.3;

    // notie.alert colors
    var alert_color_success_background = '#57BF57';
    var alert_color_warning_background = '#E3B771';
    var alert_color_error_background = '#E1715B';
    var alert_color_info_background = '#4D82D6';
    var alert_color_text = '#FFF';

    // notie.confirm colors
    var confirm_color_background = '#4D82D6';
    var confirm_color_yes_background = '#57bf57';
    var confirm_color_no_background = '#E1715B';
    var confirm_color_text = '#FFF';
    var confirm_color_yes_text = '#FFF';
    var confirm_color_no_text = '#FFF';

    // ID's for use within your own .css file (OPTIONAL)
    // (Be sure to use !important to override the javascript)
    // Example: #notie-alert-inner { padding: 30px !important; }
    var alert_outer_id = 'notie-alert-outer';
    var alert_inner_id = 'notie-alert-inner';
    var alert_text_id = 'notie-alert-text';
    var confirm_outer_id = 'notie-confirm-outer';
    var confirm_inner_id = 'notie-confirm-inner';
    var confirm_backdrop_id = 'notie-confirm-backdrop';
    var confirm_yes_id = 'notie-confirm-yes';
    var confirm_no_id = 'notie-confirm-no';
    var confirm_text_id = 'notie-confirm-text';
    var confirm_yes_text_id = 'notie-confirm-yes-text';
    var confirm_no_text_id = 'notie-confirm-no-text';

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

    // NOTIE.ALERT
    // *********************************************

    // notie elements and styling
    var alert_outer = document.createElement('div');
    alert_outer.id = alert_outer_id;
    alert_outer.style.position = 'fixed';
    alert_outer.style.top = '0';
    alert_outer.style.left = '0';
    alert_outer.style.zIndex = '999999999';
    alert_outer.style.height = 'auto';
    alert_outer.style.width = '100%';
    alert_outer.style.display = 'none';
    alert_outer.style.textAlign = 'center';
    alert_outer.style.cursor = 'default';
    alert_outer.style.MozTransition = '';
    alert_outer.style.WebkitTransition = '';
    alert_outer.style.transition = '';
    alert_outer.style.cursor = 'pointer';
    alert_outer.addEventListener('click', function() {
        clearTimeout(alert_timeout_1);
        clearTimeout(alert_timeout_2);
        alert_hide();
    });
    var alert_inner = document.createElement('div');
    alert_inner.id = alert_inner_id;
    alert_inner.style.padding = '20px';
    alert_inner.style.display = 'table-cell';
    alert_inner.style.verticalAlign = 'middle';
    alert_outer.appendChild(alert_inner);

    // Initialize notie text
    var alert_text = document.createElement('span');
    alert_text.id = alert_text_id;
    alert_text.style.color = alert_color_text;
    if (window.innerWidth <= font_change_screen_width) { alert_text.style.fontSize = font_size_small; }
    else { alert_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { alert_text.style.fontSize = font_size_small; }
        else { alert_text.style.fontSize = font_size_big; }
    }, true);
    alert_inner.appendChild(alert_text);

    // Attach notie to the body element
    document.body.appendChild(alert_outer);

    // Declare variables
    var height = 0;
    var is_showing = false;
    var alert_timeout_1;
    var alert_timeout_2;
    var was_clicked_counter = 0;

    function alert(type, message, seconds) {

        was_clicked_counter++;

        setTimeout(function() {
            was_clicked_counter--;
        }, (animation_delay * 1000 + 10));

        if (was_clicked_counter == 1) {

            if (is_showing) {

                clearTimeout(alert_timeout_1);
                clearTimeout(alert_timeout_2);

                alert_hide(function() {
                    alert_show(type, message, seconds);
                });

            }
            else {
                alert_show(type, message, seconds);
            }

        }

    }

    function alert_show(type, message, seconds) {

        is_showing = true;

        var duration = 0;
        if (typeof seconds == 'undefined') {
            var duration = 3000;
        }
        else if (seconds < 1) {
            duration = 1000;
        }
        else {
            duration = seconds * 1000;
        }

        // Set notie type (background color)
        switch(type) {
            case 1:
                alert_outer.style.backgroundColor = alert_color_success_background;
                break;
            case 2:
                alert_outer.style.backgroundColor = alert_color_warning_background;
                break;
            case 3:
                alert_outer.style.backgroundColor = alert_color_error_background;
                break;
            case 4:
                alert_outer.style.backgroundColor = alert_color_info_background;
                break;
        }

        // Set notie text
        alert_text.innerHTML = message;

        // Get notie's height
        alert_outer.style.top = '-10000px';
        alert_outer.style.display = 'table';
        alert_outer.style.top = '-' + alert_outer.offsetHeight - 5 + 'px';

        alert_timeout_1 = setTimeout(function() {

            if (shadow) { alert_outer.style.boxShadow = '0px 0px 10px 0px rgba(0,0,0,0.5)'; }
            alert_outer.style.MozTransition = 'all ' + animation_delay + 's ease';
            alert_outer.style.WebkitTransition = 'all ' + animation_delay + 's ease';
            alert_outer.style.transition = 'all ' + animation_delay + 's ease';

            alert_outer.style.top = 0;

            alert_timeout_2 = setTimeout(function() {

                alert_hide(function() {
                    // Nothing
                });

            }, duration);

        }, 20);

    }

    function alert_hide(callback) {

        alert_outer.style.top = '-' + alert_outer.offsetHeight - 5 + 'px';

        setTimeout(function() {

            if (shadow) { alert_outer.style.boxShadow = ''; }
            alert_outer.style.MozTransition = '';
            alert_outer.style.WebkitTransition = '';
            alert_outer.style.transition = '';

            alert_outer.style.top = '-10000px';

            is_showing = false;

            callback();

        }, (animation_delay * 1000 + 10));

    }

    // NOTIE.CONFIRM
    // *********************************************

    // confirm elements and styling
    var confirm_outer = document.createElement('div');
    confirm_outer.id = confirm_outer_id;
    confirm_outer.style.position = 'fixed';
    confirm_outer.style.top = '0';
    confirm_outer.style.left = '0';
    confirm_outer.style.zIndex = '999999998';
    confirm_outer.style.height = 'auto';
    confirm_outer.style.width = '100%';
    confirm_outer.style.display = 'none';
    confirm_outer.style.textAlign = 'center';
    confirm_outer.style.MozTransition = '';
    confirm_outer.style.WebkitTransition = '';
    confirm_outer.style.transition = '';

    var confirm_backdrop = document.createElement('div');
    confirm_backdrop.id = confirm_backdrop_id;
    confirm_backdrop.style.position = 'fixed';
    confirm_backdrop.style.top = '0';
    confirm_backdrop.style.left = '0';
    confirm_backdrop.style.zIndex = '999999997';
    confirm_backdrop.style.height = '100%';
    confirm_backdrop.style.width = '100%';
    confirm_backdrop.style.display = 'none';
    confirm_backdrop.style.backgroundColor = 'white';
    confirm_backdrop.style.MozTransition = 'all ' + animation_delay + 's ease';
    confirm_backdrop.style.WebkitTransition = 'all ' + animation_delay + 's ease';
    confirm_backdrop.style.transition = 'all ' + animation_delay + 's ease';
    confirm_backdrop.style.opacity = '0';
    confirm_backdrop.onclick = function() { confirm_hide(); }

    var confirm_inner = document.createElement('div');
    confirm_inner.id = confirm_inner_id;
    confirm_inner.style.boxSizing = 'border-box';
    confirm_inner.style.width = '100%';
    confirm_inner.style.padding = '20px';
    confirm_inner.style.display = 'block';
    confirm_inner.style.cursor = 'default';
    confirm_inner.style.backgroundColor = confirm_color_background;
    confirm_outer.appendChild(confirm_inner);

    var confirm_yes = document.createElement('div');
    confirm_yes.id = confirm_yes_id;
    confirm_yes.style.cssFloat = 'left';
    confirm_yes.style.height = '50px';
    confirm_yes.style.lineHeight = '50px';
    confirm_yes.style.width = '50%';
    confirm_yes.style.cursor = 'pointer';
    confirm_yes.style.backgroundColor = confirm_color_yes_background;
    confirm_outer.appendChild(confirm_yes);

    var confirm_no = document.createElement('div');
    confirm_no.id = confirm_no_id;
    confirm_no.style.cssFloat = 'right';
    confirm_no.style.height = '50px';
    confirm_no.style.lineHeight = '50px';
    confirm_no.style.width = '50%';
    confirm_no.style.cursor = 'pointer';
    confirm_no.style.backgroundColor = confirm_color_no_background;
    confirm_no.onclick = function() { confirm_hide(); }
    confirm_outer.appendChild(confirm_no);

    // Initialize confirm text
    var confirm_text = document.createElement('span');
    confirm_text.id = confirm_text_id;
    confirm_text.style.color = confirm_color_text;
    if (window.innerWidth <= font_change_screen_width) { confirm_text.style.fontSize = font_size_small; }
    else { confirm_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { confirm_text.style.fontSize = font_size_small; }
        else { confirm_text.style.fontSize = font_size_big; }
    }, true);
    confirm_inner.appendChild(confirm_text);

    var confirm_yes_text = document.createElement('span');
    confirm_yes_text.id = confirm_yes_text_id;
    confirm_yes_text.style.color = confirm_color_yes_text;
    if (window.innerWidth <= font_change_screen_width) { confirm_yes_text.style.fontSize = font_size_small; }
    else { confirm_yes_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { confirm_yes_text.style.fontSize = font_size_small; }
        else { confirm_yes_text.style.fontSize = font_size_big; }
    }, true);
    confirm_yes.appendChild(confirm_yes_text);

    var confirm_no_text = document.createElement('span');
    confirm_no_text.id = confirm_no_text_id;
    confirm_no_text.style.color = confirm_color_no_text;
    if (window.innerWidth <= font_change_screen_width) { confirm_no_text.style.fontSize = font_size_small; }
    else { confirm_no_text.style.fontSize = font_size_big; }
    window.addEventListener('resize', function(){
        if (window.innerWidth <= font_change_screen_width) { confirm_no_text.style.fontSize = font_size_small; }
        else { confirm_no_text.style.fontSize = font_size_big; }
    }, true);
    confirm_no.appendChild(confirm_no_text);

    // Attach confirm elements to the body element
    document.body.appendChild(confirm_outer);
    document.body.appendChild(confirm_backdrop);

    // Declare variables
    var confirm_height = 0;
    var confirm_is_showing = false;

    function confirm(title, yes_text, no_text, yes_callback) {

        confirm_show(title, yes_text, no_text, yes_callback);

        // Hide notie.alert
        clearTimeout(alert_timeout_1);
        clearTimeout(alert_timeout_2);
        alert_hide();

    }
    function confirm_show(title, yes_text, no_text, yes_callback) {

        scroll_disable();

        // Yes callback function
        confirm_yes.onclick = function() {
            confirm_hide();
            setTimeout(function() {
                yes_callback();
            }, (animation_delay * 1000 + 10));
        }

        function confirm_show_inner() {

            // Set confirm text
            confirm_text.innerHTML = title;
            confirm_yes_text.innerHTML = yes_text;
            confirm_no_text.innerHTML = no_text;

            // Get confirm's height
            confirm_outer.style.top = '-10000px';
            confirm_outer.style.display = 'table';
            confirm_outer.style.top = '-' + confirm_outer.offsetHeight - 5 + 'px';
            confirm_backdrop.style.display = 'block';

            setTimeout(function() {

                if (shadow) { confirm_outer.style.boxShadow = '0px 0px 10px 0px rgba(0,0,0,0.5)'; }
                confirm_outer.style.MozTransition = 'all ' + animation_delay + 's ease';
                confirm_outer.style.WebkitTransition = 'all ' + animation_delay + 's ease';
                confirm_outer.style.transition = 'all ' + animation_delay + 's ease';

                confirm_outer.style.top = 0;
                confirm_backdrop.style.opacity = '0.75';

                setTimeout(function() {
                    confirm_is_showing = true;
                }, (animation_delay * 1000 + 10));

            }, 20);

        }

        if (confirm_is_showing) {
            confirm_hide();
            setTimeout(function() {
                confirm_show_inner();
            }, (animation_delay * 1000 + 10));
        }
        else {
            confirm_show_inner();
        }

    }

    function confirm_hide() {

        confirm_outer.style.top = '-' + confirm_outer.offsetHeight - 5 + 'px';
        confirm_backdrop.style.opacity = '0';

        setTimeout(function() {

            if (shadow) { confirm_outer.style.boxShadow = ''; }
            confirm_outer.style.MozTransition = '';
            confirm_outer.style.WebkitTransition = '';
            confirm_outer.style.transition = '';
            confirm_backdrop.style.display = 'none';

            confirm_outer.style.top = '-10000px';

            scroll_enable();

            confirm_is_showing = false;

        }, (animation_delay * 1000 + 10));

    }

    // SCROLL DISABLE AND ENABLE FOR NOTIE.CONFIRM
    // *********************************************
    var original_body_height, original_body_overflow;
    function scroll_disable() {
        original_body_height = document.body.style.height;
        original_body_overflow = document.body.style.overflow;
        document.body.style.height = '100%;';
        document.body.style.overflow = 'hidden';
    }
    function scroll_enable() {
        document.body.style.height = original_body_height;
        document.body.style.overflow = original_body_overflow;
    }

    return {
        alert: alert,
        confirm: confirm
    };

}();

if (module) {
    module.exports = notie;
}<|endoftext|>


<commit_before>const path = require('path')
const TextBuffer = require('../src/text-buffer')

describe('when a buffer is already open', () => {
  const filePath = path.join(__dirname, 'fixtures', 'sample.js')
  const buffer = new TextBuffer()

  it('replaces foo( with bar( using /\bfoo\\(\b/gim', () => {
    buffer.setPath(filePath)
    buffer.setText('foo(x)')
    buffer.replace(/\bfoo\(\b/gim, 'bar(')

    expect(buffer.getText()).toBe('bar(x)')
  })

  describe('should properly replace regex literals', () => {
    it('replaces tstat_fvars()->curr_setpoint[HEAT_EN] = new_tptr->heat_limit; with tstat_set_curr_setpoint(HEAT_EN, new_tptr->heat_limit);', () => {
      buffer.setPath(filePath)
      buffer.setText('tstat_fvars()->curr_setpoint[HEAT_EN] = new_tptr->heat_limit;')
      buffer.replace(/tstat_fvars\(\)->curr_setpoint\[(.+?)\] = (.+?);/, 'tstat_set_curr_setpoint($1, $2);')

      expect(buffer.getText()).toBe('tstat_set_curr_setpoint(HEAT_EN, new_tptr->heat_limit);')
    })

    it('replaces atom/flight-manual.atom.io with atom/flight-manualatomio', () => {
      buffer.setText('atom/flight-manual.atom.io')
      buffer.replace(/\.(atom)\./, '$1')

      expect(buffer.getText()).toBe('atom/flight-manualatomio')
    })
  })
})
<commit_msg>simplified test cases<commit_after>const path = require('path')
const TextBuffer = require('../src/text-buffer')

describe('when a buffer is already open', () => {
  const filePath = path.join(__dirname, 'fixtures', 'sample.js')
  const buffer = new TextBuffer()

  it('replaces foo( with bar( using /\bfoo\\(\b/gim', () => {
    buffer.setPath(filePath)
    buffer.setText('foo(x)')
    buffer.replace(/\bfoo\(\b/gim, 'bar(')

    expect(buffer.getText()).toBe('bar(x)')
  })

  describe('Texts should be replaced properly with strings containing literals when using the regex option', () => {
    it('replaces tstat_fvars()->curr_setpoint[HEAT_EN] with tstat_set_curr_setpoint($1, $2);', () => {
      buffer.setPath(filePath)
      buffer.setText('tstat_fvars()->curr_setpoint[HEAT_EN] = new_tptr->heat_limit;')
      buffer.replace(/tstat_fvars\(\)->curr_setpoint\[(.+?)\] = (.+?);/, 'tstat_set_curr_setpoint($1, $2);')

      expect(buffer.getText()).toBe('tstat_set_curr_setpoint(HEAT_EN, new_tptr->heat_limit);')
    })

    it('replaces atom/flight-manualatomio with $1', () => {
      buffer.setText('atom/flight-manualatomio')
      buffer.replace($1, '$1')

      expect(buffer.getText()).toBe('atom/flight-manualatomio')
    })
  })
})
<|endoftext|>


<commit_before>
module.exports = {
	'Display error message when provided a nonexistent account': (client) => {
		const loginPage = client.page.loginPage();

		client.maximizeWindow();

		loginPage
			.navigate()
			.login("fakeuser@inter.net", "badpass")
			.expect.element("@errorMessage").text.to.equal('user name and or password invalid');

		client.end();
	},
	'Log in when provided a valid account': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		client.maximizeWindow();

		loginPage
			.navigate()
			.login(client.globals.accounts.user.username, client.globals.accounts.user.password);

		landingPage.expect.element("@pageTitle").text.to.equal('Welcome to the DATA Act Broker');

		client.end();
	},
	'Admin button appears when an admin user logs in': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		client.maximizeWindow();

		loginPage
			.navigate()
			.login(client.globals.accounts.admin.username, client.globals.accounts.admin.password);

		landingPage.expect.element("@adminButton").to.be.visible;

		client.end();
	},
	'Admin button does not appear when a non-admin user logs in': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		loginPage
			.navigate()
			.login(client.globals.accounts.user.username, client.globals.accounts.user.password);

		// make sure the page title is in pace in order to ensure the landing page has loaded when the admin check is performed
		landingPage.expect.element("@pageTitle").text.to.equal('Welcome to the DATA Act Broker');
		landingPage.expect.element("@adminButton").to.not.be.present;
		client.end();
	},
	'User button displays the user\'s name': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		loginPage
			.navigate()
			.login(client.globals.accounts.user.username, client.globals.accounts.user.password);

		landingPage.expect.element("@userButton").text.to.equal(client.globals.accounts.user.name);
		client.end();
	}
}<commit_msg>Login message changed<commit_after>
module.exports = {
	'Display error message when provided a nonexistent account': (client) => {
		const loginPage = client.page.loginPage();

		client.maximizeWindow();

		loginPage
			.navigate()
			.login("fakeuser@inter.net", "badpass")
			.expect.element("@errorMessage").text.to.equal('Invalid username and/or password');

		client.end();
	},
	'Log in when provided a valid account': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		client.maximizeWindow();

		loginPage
			.navigate()
			.login(client.globals.accounts.user.username, client.globals.accounts.user.password);

		landingPage.expect.element("@pageTitle").text.to.equal('Welcome to the DATA Act Broker');

		client.end();
	},
	'Admin button appears when an admin user logs in': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		client.maximizeWindow();

		loginPage
			.navigate()
			.login(client.globals.accounts.admin.username, client.globals.accounts.admin.password);

		landingPage.expect.element("@adminButton").to.be.visible;

		client.end();
	},
	'Admin button does not appear when a non-admin user logs in': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		loginPage
			.navigate()
			.login(client.globals.accounts.user.username, client.globals.accounts.user.password);

		// make sure the page title is in pace in order to ensure the landing page has loaded when the admin check is performed
		landingPage.expect.element("@pageTitle").text.to.equal('Welcome to the DATA Act Broker');
		landingPage.expect.element("@adminButton").to.not.be.present;
		client.end();
	},
	'User button displays the user\'s name': (client) => {
		const loginPage = client.page.loginPage();
		const landingPage = client.page.landingPage();

		loginPage
			.navigate()
			.login(client.globals.accounts.user.username, client.globals.accounts.user.password);

		landingPage.expect.element("@userButton").text.to.equal(client.globals.accounts.user.name);
		client.end();
	}
}<|endoftext|>


<commit_before>'use strict'

var dgram = require('dgram')
var transports = require('stun-js').transports
var TurnClient = require('../lib/turn_client')

var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')
var expect = chai.expect
chai.use(chaiAsPromised)
chai.should()

if (!process.env.TURN_ADDR) {
  throw new Error('TURN_ADDR undefined -- giving up')
}
if (!process.env.TURN_PORT) {
  throw new Error('TURN_PORT undefined -- giving up')
}
if (!process.env.TURN_USER) {
  throw new Error('TURN_USER undefined -- giving up')
}
if (!process.env.TURN_PASS) {
  throw new Error('TURN_PASS undefined -- giving up')
}

var turnAddr = process.env.TURN_ADDR
var turnPort = parseInt(process.env.TURN_PORT)
var turnUser = process.env.TURN_USER
var turnPwd = process.env.TURN_PASS
var socketPort = 33333

var winston = require('winston-debug')
winston.level = 'debug'

describe('#TURN operations', function () {
  this.timeout(15000)

  it('should execute TURN allocate operation over UDP socket using promises', function (done) {
    var retransmissionTimer
    // send a TURN allocate request and verify the reply
    var sendAllocateRequest = function (client, socket) {
      client.allocateP()
        .then(function (result) {
          // end retransmissionTimer
          clearTimeout(retransmissionTimer)
          // test results
          expect(result).not.to.be.undefined
          expect(result).to.have.property('mappedAddress')
          expect(result.mappedAddress).to.have.property('address')
          expect(result.mappedAddress).to.have.property('port')
          // expect(result.mappedAddress.address).to.equal(testGW)
          expect(result).to.have.property('relayedAddress')
          expect(result.relayedAddress).to.have.property('address')
          expect(result.relayedAddress).to.have.property('port')
          // expect(result.relayedAddress.address).to.equal(turnAddr)
          return client.closeP()
        })
        .then(function () {
          expect(socket.listeners('message').length).to.equal(1)
          expect(socket.listeners('error').length).to.equal(1)
          // close socket
          socket.close(function () {
            done()
          })
        })
        .catch(function (error) {
          done(error)
        })
    }
    // create socket
    var socket = dgram.createSocket('udp4')
    socket.on('message', function (message, rinfo) { //
      done(new Error('message callback should not be fired'))
    })
    socket.on('error', function (error) {
      done(error)
    })
    socket.on('listening', function () {
      // create turn client and pass socket over
      var transport = new transports.UDP(socket)
      var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)
      client.init(function () {
        // retransmission timer -- we're using UDP ...
        retransmissionTimer = setTimeout(function () {
          console.log('resending ALLOCATE request')
          sendAllocateRequest(client, socket)
        }, 5000)
        // allocate request
        sendAllocateRequest(client, socket)
      })
    })
    socket.bind(socketPort)
  })

  it('should execute TURN allocate operation over TCP socket using callbacks', function (done) {
    var transport = new transports.TCP()
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)

    var onError = function (error) {
      done(error)
    }
    var onReady = function (result) {
      expect(result).not.to.be.undefined
      expect(result).to.have.property('mappedAddress')
      expect(result.mappedAddress).to.have.property('address')
      expect(result.mappedAddress).to.have.property('port')
      // expect(result.mappedAddress.address).to.equal(testGW)
      expect(result).to.have.property('relayedAddress')
      expect(result.relayedAddress).to.have.property('address')
      expect(result.relayedAddress).to.have.property('port')
      // expect(result.relayedAddress.address).to.equal(turnAddr)
      client.close(
        function () {
          done()
        },
        onError
      )
    }

    client.init(function () {
      client.allocate(onReady, onError)
    })

  })

  it('should execute TURN allocate operation over unspecified UDP socket using promises', function (done) {
    var retransmissionTimer
    // send a TURN allocate request and verify the reply
    var sendAllocateRequest = function (client) {
      client.allocateP()
        .then(function (result) {
          // end retransmissionTimer
          clearTimeout(retransmissionTimer)
          // test results
          expect(result).not.to.be.undefined
          expect(result).to.have.property('mappedAddress')
          expect(result.mappedAddress).to.have.property('address')
          expect(result.mappedAddress).to.have.property('port')
          // expect(result.mappedAddress.address).to.equal(testGW)
          expect(result).to.have.property('relayedAddress')
          expect(result.relayedAddress).to.have.property('address')
          expect(result.relayedAddress).to.have.property('port')
          // expect(result.relayedAddress.address).to.equal(turnAddr)
          return client.closeP()
        })
        .then(function () {
          done()
        })
        .catch(function (error) {
          done(error)
        })
    }
    // create turn client
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd)
    client.init(function () {
      // retransmission timer -- we're using UDP ...
      retransmissionTimer = setTimeout(function () {
        console.log('resending ALLOCATE request')
        sendAllocateRequest(client)
      }, 5000)
      // allocate request
      sendAllocateRequest(client)
    })

  })

  it('should execute TURN allocate followed by refresh over UDP socket using promises', function (done) {
    var lifetime = 3600
    var retransmissionTimer
    // send a TURN allocate request and verify the reply
    var sendAllocateAndRefreshRequest = function (client) {
      client.allocateP()
        .then(function (result) {
          return client.refreshP(lifetime)
        })
        .then(function (duration) {
          // end retransmissionTimer
          clearTimeout(retransmissionTimer)
          // test results
          expect(duration).to.equal(lifetime)
          // close turn client
          return client.closeP()
        })
        .then(function () {
          expect(socket.listeners('message').length).to.equal(1)
          expect(socket.listeners('error').length).to.equal(1)
          done()
        })
        .catch(function (error) {
          done(error)
        })
    }
    // create socket
    var socket = dgram.createSocket('udp4')
    socket.on('message', function (message, rinfo) { //
      done(new Error('message callback should not be fired'))
    })
    socket.on('error', function (error) {
      done(error)
    })
    socket.on('listening', function () {
      // create stun client and pass socket over
      var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd)
      client.init(function () {
        // retransmission timer -- we're using UDP ...
        retransmissionTimer = setTimeout(function () {
          console.log('resending ALLOCATE and REFRESH request')
          sendAllocateAndRefreshRequest(client)
        }, 5000)
        sendAllocateAndRefreshRequest(client)
      })
    })
    socket.bind(socketPort)
  })

  it('should execute TURN allocate followed by create permission over TCP socket using promises', function () {
    var transport = new transports.TCP()
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)
    var turnAddress = '1.2.3.4'
    return client.initP()
      .then(function () {
        return client.allocateP()
      })
      .then(function (result) {
        return client.createPermissionP(turnAddress)
      })
      .then(function () {
        return client.closeP()
      })
  })

  it('should execute TURN allocate followed by two consecutive create permissions (testing permission refresh) over TCP socket using promises', function () {
    var transport = new transports.TCP()
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)
    var turnAddress = '1.2.3.4'
    return client.initP()
      .then(function () {
        return client.allocateP()
      })
      .then(function (result) {
        return client.createPermissionP(turnAddress)
      })
      .then(function () {
        return client.createPermissionP(turnAddress)
      })
      .then(function () {
        return client.closeP()
      })
  })

  it('should receive messages that are sent via relay server over TCP sockets', function (done) {
    var testData = 'hello there'
    var testRuns = 10
    var messagesReceived = 0

    // alice's client
    var clientAlice = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    // bob's client
    var clientBob = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    var srflxAddressAlice, srflxAddressBob, relayAddressAlice, relayAddressBob

    var sendTestMessageFromAliceToBob = function () {
      var bytes = new Buffer(testData)
      clientAlice.sendToRelay(
        bytes,
        relayAddressBob.address,
        relayAddressBob.port,
        function () {
          console.log('message sent to ' + relayAddressBob.address + ':' + relayAddressBob.port)
        }, // on success
        function (error) {
          done(error)
        }
      )
    }

    // subscribe to incoming messages
    clientBob.on('relayed-message', function (bytes, peerAddress) {
      var message = bytes.toString()
      expect(message).to.equal(testData)
      console.log('receiving test message ' + message)
      messagesReceived++
      if (messagesReceived === testRuns) {
        clientBob.closeP()
          .then(function () {
            return clientAlice.closeP()
          })
          .then(function () {
            done()
          })
          .catch(function (error) {
            done(error)
          })
      } else {
        sendTestMessageFromAliceToBob()
      }
    })

    // init alice and bob + allocate relaying session for alice
    clientBob.initP()
      .then(function () {
        return clientAlice.initP()
      })
      .then(function () {
        return clientAlice.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressAlice = allocateAddress.mappedAddress
        relayAddressAlice = allocateAddress.relayedAddress
        console.log("alice's srflx address = " + srflxAddressAlice.address + ':' + srflxAddressAlice.port)
        console.log("alice's relay address = " + relayAddressAlice.address + ':' + relayAddressAlice.port)
        // allocate relaying session for bob
        return clientBob.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressBob = allocateAddress.mappedAddress
        relayAddressBob = allocateAddress.relayedAddress
        console.log("bob's address = " + srflxAddressBob.address + ':' + srflxAddressBob.port)
        console.log("bob's relay address = " + relayAddressBob.address + ':' + relayAddressBob.port)
        // create permission for alice to send messages to bob
        return clientBob.createPermissionP(relayAddressAlice.address)
      })
      .then(function () {
        // create permission for bob to send messages to alice
        return clientAlice.createPermissionP(relayAddressBob.address)
      })
      .then(function () {
        // send test message
        sendTestMessageFromAliceToBob()
      })
      .catch(function (error) {
        done(error)
      })
  })

  it('should execute TURN channel binding and receive messages sent via these channels over TCP sockets using promises', function (done) {
    var testData = 'hello there'
    var testRuns = 10
    var messagesReceived = 0

    // alice's client
    var clientAlice = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    // bob's client
    var clientBob = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    var srflxAddressAlice, srflxAddressBob, relayAddressAlice, relayAddressBob
    var channelId

    var sendTestMessageFromAliceToBob = function () {
      var bytes = new Buffer(testData)
      clientAlice.sendToChannel(
        bytes,
        channelId,
        function () {
          console.log('message sent to channel ' + channelId)
        },
        function (error) {
          done(error)
        }
      )
    }

    // subscribe to incoming messages
    clientBob.on('relayed-message', function (bytes, peerAddress) {
      var message = bytes.toString()
      expect(message).to.equal(testData)
      console.log('receiving test message ' + message)
      messagesReceived++
      if (messagesReceived === testRuns) {
        clientBob.closeP()
          .then(function () {
            return clientAlice.closeP()
          })
          .then(function () {
            done()
          })
          .catch(function (error) {
            done(error)
          })
      } else {
        sendTestMessageFromAliceToBob()
      }
    })

    // init alice and bob + allocate relaying session for alice
    clientBob.initP()
      .then(function () {
        return clientAlice.initP()
      })
      .then(function () {
        return clientAlice.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressAlice = allocateAddress.mappedAddress
        relayAddressAlice = allocateAddress.relayedAddress
        console.log("alice's srflx address = " + srflxAddressAlice.address + ':' + srflxAddressAlice.port)
        console.log("alice's relay address = " + relayAddressAlice.address + ':' + relayAddressAlice.port)
        // allocate relaying session for bob
        return clientBob.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressBob = allocateAddress.mappedAddress
        relayAddressBob = allocateAddress.relayedAddress
        console.log("bob's address = " + srflxAddressBob.address + ':' + srflxAddressBob.port)
        console.log("bob's relay address = " + relayAddressBob.address + ':' + relayAddressBob.port)
        // create permission for alice to send messages to bob
        return clientBob.createPermissionP(relayAddressAlice.address)
      })
      .then(function () {
        // create channel from alice to bob
        return clientAlice.bindChannelP(relayAddressBob.address, relayAddressBob.port)
      })
      .then(function (channel) {
        expect(channel).not.to.be.undefined
        channelId = channel
        // mimic refreshing of channel binding
        return clientAlice.bindChannelP(relayAddressBob.address, relayAddressBob.port, channel)
      })
      .then(function (channel) {
        expect(channel).to.equal(channelId)
        //  create permission for bob to send messages to alice
        return clientAlice.createPermissionP(relayAddressBob.address)
      })
      .then(function () {
        // create channel from bob to alice
        return clientBob.bindChannelP(relayAddressAlice.address, relayAddressAlice.port)
      })
      .then(function (anotherChannel) {
        // send test message
        sendTestMessageFromAliceToBob()
      })
      .catch(function (error) {
        done(error)
      })
  })
})
<commit_msg>standard-format<commit_after>'use strict'

var dgram = require('dgram')
var transports = require('stun-js').transports
var TurnClient = require('../lib/turn_client')

var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')
var expect = chai.expect
chai.use(chaiAsPromised)
chai.should()

if (!process.env.TURN_ADDR) {
  throw new Error('TURN_ADDR undefined -- giving up')
}
if (!process.env.TURN_PORT) {
  throw new Error('TURN_PORT undefined -- giving up')
}
if (!process.env.TURN_USER) {
  throw new Error('TURN_USER undefined -- giving up')
}
if (!process.env.TURN_PASS) {
  throw new Error('TURN_PASS undefined -- giving up')
}

var turnAddr = process.env.TURN_ADDR
var turnPort = parseInt(process.env.TURN_PORT)
var turnUser = process.env.TURN_USER
var turnPwd = process.env.TURN_PASS
var socketPort = 33333

var winston = require('winston-debug')
winston.level = 'debug'

describe('#TURN operations', function () {
  this.timeout(15000)

  it('should execute TURN allocate operation over UDP socket using promises', function (done) {
    var retransmissionTimer
    // send a TURN allocate request and verify the reply
    var sendAllocateRequest = function (client, socket) {
      client.allocateP()
        .then(function (result) {
          // end retransmissionTimer
          clearTimeout(retransmissionTimer)
          // test results
          expect(result).not.to.be.undefined
          expect(result).to.have.property('mappedAddress')
          expect(result.mappedAddress).to.have.property('address')
          expect(result.mappedAddress).to.have.property('port')
          // expect(result.mappedAddress.address).to.equal(testGW)
          expect(result).to.have.property('relayedAddress')
          expect(result.relayedAddress).to.have.property('address')
          expect(result.relayedAddress).to.have.property('port')
          // expect(result.relayedAddress.address).to.equal(turnAddr)
          return client.closeP()
        })
        .then(function () {
          expect(socket.listeners('message').length).to.equal(1)
          expect(socket.listeners('error').length).to.equal(1)
          // close socket
          socket.close(function () {
            done()
          })
        })
        .catch(function (error) {
          done(error)
        })
    }
    // create socket
    var socket = dgram.createSocket('udp4')
    socket.on('message', function (message, rinfo) { //
      done(new Error('message callback should not be fired'))
    })
    socket.on('error', function (error) {
      done(error)
    })
    socket.on('listening', function () {
      // create turn client and pass socket over
      var transport = new transports.UDP(socket)
      var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)
      client.init(function () {
        // retransmission timer -- we're using UDP ...
        retransmissionTimer = setTimeout(function () {
          console.log('resending ALLOCATE request')
          sendAllocateRequest(client, socket)
        }, 5000)
        // allocate request
        sendAllocateRequest(client, socket)
      })
    })
    socket.bind(socketPort)
  })

  it('should execute TURN allocate operation over TCP socket using callbacks', function (done) {
    var transport = new transports.TCP()
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)

    var onError = function (error) {
      done(error)
    }
    var onReady = function (result) {
      expect(result).not.to.be.undefined
      expect(result).to.have.property('mappedAddress')
      expect(result.mappedAddress).to.have.property('address')
      expect(result.mappedAddress).to.have.property('port')
      // expect(result.mappedAddress.address).to.equal(testGW)
      expect(result).to.have.property('relayedAddress')
      expect(result.relayedAddress).to.have.property('address')
      expect(result.relayedAddress).to.have.property('port')
      // expect(result.relayedAddress.address).to.equal(turnAddr)
      client.close(
        function () {
          done()
        },
        onError
      )
    }

    client.init(function () {
      client.allocate(onReady, onError)
    })
  })

  it('should execute TURN allocate operation over unspecified UDP socket using promises', function (done) {
    var retransmissionTimer
    // send a TURN allocate request and verify the reply
    var sendAllocateRequest = function (client) {
      client.allocateP()
        .then(function (result) {
          // end retransmissionTimer
          clearTimeout(retransmissionTimer)
          // test results
          expect(result).not.to.be.undefined
          expect(result).to.have.property('mappedAddress')
          expect(result.mappedAddress).to.have.property('address')
          expect(result.mappedAddress).to.have.property('port')
          // expect(result.mappedAddress.address).to.equal(testGW)
          expect(result).to.have.property('relayedAddress')
          expect(result.relayedAddress).to.have.property('address')
          expect(result.relayedAddress).to.have.property('port')
          // expect(result.relayedAddress.address).to.equal(turnAddr)
          return client.closeP()
        })
        .then(function () {
          done()
        })
        .catch(function (error) {
          done(error)
        })
    }
    // create turn client
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd)
    client.init(function () {
      // retransmission timer -- we're using UDP ...
      retransmissionTimer = setTimeout(function () {
        console.log('resending ALLOCATE request')
        sendAllocateRequest(client)
      }, 5000)
      // allocate request
      sendAllocateRequest(client)
    })
  })

  it('should execute TURN allocate followed by refresh over UDP socket using promises', function (done) {
    var lifetime = 3600
    var retransmissionTimer
    // send a TURN allocate request and verify the reply
    var sendAllocateAndRefreshRequest = function (client) {
      client.allocateP()
        .then(function (result) {
          return client.refreshP(lifetime)
        })
        .then(function (duration) {
          // end retransmissionTimer
          clearTimeout(retransmissionTimer)
          // test results
          expect(duration).to.equal(lifetime)
          // close turn client
          return client.closeP()
        })
        .then(function () {
          expect(socket.listeners('message').length).to.equal(1)
          expect(socket.listeners('error').length).to.equal(1)
          done()
        })
        .catch(function (error) {
          done(error)
        })
    }
    // create socket
    var socket = dgram.createSocket('udp4')
    socket.on('message', function (message, rinfo) { //
      done(new Error('message callback should not be fired'))
    })
    socket.on('error', function (error) {
      done(error)
    })
    socket.on('listening', function () {
      // create stun client and pass socket over
      var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd)
      client.init(function () {
        // retransmission timer -- we're using UDP ...
        retransmissionTimer = setTimeout(function () {
          console.log('resending ALLOCATE and REFRESH request')
          sendAllocateAndRefreshRequest(client)
        }, 5000)
        sendAllocateAndRefreshRequest(client)
      })
    })
    socket.bind(socketPort)
  })

  it('should execute TURN allocate followed by create permission over TCP socket using promises', function () {
    var transport = new transports.TCP()
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)
    var turnAddress = '1.2.3.4'
    return client.initP()
      .then(function () {
        return client.allocateP()
      })
      .then(function (result) {
        return client.createPermissionP(turnAddress)
      })
      .then(function () {
        return client.closeP()
      })
  })

  it('should execute TURN allocate followed by two consecutive create permissions (testing permission refresh) over TCP socket using promises', function () {
    var transport = new transports.TCP()
    var client = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, transport)
    var turnAddress = '1.2.3.4'
    return client.initP()
      .then(function () {
        return client.allocateP()
      })
      .then(function (result) {
        return client.createPermissionP(turnAddress)
      })
      .then(function () {
        return client.createPermissionP(turnAddress)
      })
      .then(function () {
        return client.closeP()
      })
  })

  it('should receive messages that are sent via relay server over TCP sockets', function (done) {
    var testData = 'hello there'
    var testRuns = 10
    var messagesReceived = 0

    // alice's client
    var clientAlice = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    // bob's client
    var clientBob = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    var srflxAddressAlice, srflxAddressBob, relayAddressAlice, relayAddressBob

    var sendTestMessageFromAliceToBob = function () {
      var bytes = new Buffer(testData)
      clientAlice.sendToRelay(
        bytes,
        relayAddressBob.address,
        relayAddressBob.port,
        function () {
          console.log('message sent to ' + relayAddressBob.address + ':' + relayAddressBob.port)
        }, // on success
        function (error) {
          done(error)
        }
      )
    }

    // subscribe to incoming messages
    clientBob.on('relayed-message', function (bytes, peerAddress) {
      var message = bytes.toString()
      expect(message).to.equal(testData)
      console.log('receiving test message ' + message)
      messagesReceived++
      if (messagesReceived === testRuns) {
        clientBob.closeP()
          .then(function () {
            return clientAlice.closeP()
          })
          .then(function () {
            done()
          })
          .catch(function (error) {
            done(error)
          })
      } else {
        sendTestMessageFromAliceToBob()
      }
    })

    // init alice and bob + allocate relaying session for alice
    clientBob.initP()
      .then(function () {
        return clientAlice.initP()
      })
      .then(function () {
        return clientAlice.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressAlice = allocateAddress.mappedAddress
        relayAddressAlice = allocateAddress.relayedAddress
        console.log("alice's srflx address = " + srflxAddressAlice.address + ':' + srflxAddressAlice.port)
        console.log("alice's relay address = " + relayAddressAlice.address + ':' + relayAddressAlice.port)
        // allocate relaying session for bob
        return clientBob.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressBob = allocateAddress.mappedAddress
        relayAddressBob = allocateAddress.relayedAddress
        console.log("bob's address = " + srflxAddressBob.address + ':' + srflxAddressBob.port)
        console.log("bob's relay address = " + relayAddressBob.address + ':' + relayAddressBob.port)
        // create permission for alice to send messages to bob
        return clientBob.createPermissionP(relayAddressAlice.address)
      })
      .then(function () {
        // create permission for bob to send messages to alice
        return clientAlice.createPermissionP(relayAddressBob.address)
      })
      .then(function () {
        // send test message
        sendTestMessageFromAliceToBob()
      })
      .catch(function (error) {
        done(error)
      })
  })

  it('should execute TURN channel binding and receive messages sent via these channels over TCP sockets using promises', function (done) {
    var testData = 'hello there'
    var testRuns = 10
    var messagesReceived = 0

    // alice's client
    var clientAlice = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    // bob's client
    var clientBob = new TurnClient(turnAddr, turnPort, turnUser, turnPwd, new transports.TCP())
    var srflxAddressAlice, srflxAddressBob, relayAddressAlice, relayAddressBob
    var channelId

    var sendTestMessageFromAliceToBob = function () {
      var bytes = new Buffer(testData)
      clientAlice.sendToChannel(
        bytes,
        channelId,
        function () {
          console.log('message sent to channel ' + channelId)
        },
        function (error) {
          done(error)
        }
      )
    }

    // subscribe to incoming messages
    clientBob.on('relayed-message', function (bytes, peerAddress) {
      var message = bytes.toString()
      expect(message).to.equal(testData)
      console.log('receiving test message ' + message)
      messagesReceived++
      if (messagesReceived === testRuns) {
        clientBob.closeP()
          .then(function () {
            return clientAlice.closeP()
          })
          .then(function () {
            done()
          })
          .catch(function (error) {
            done(error)
          })
      } else {
        sendTestMessageFromAliceToBob()
      }
    })

    // init alice and bob + allocate relaying session for alice
    clientBob.initP()
      .then(function () {
        return clientAlice.initP()
      })
      .then(function () {
        return clientAlice.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressAlice = allocateAddress.mappedAddress
        relayAddressAlice = allocateAddress.relayedAddress
        console.log("alice's srflx address = " + srflxAddressAlice.address + ':' + srflxAddressAlice.port)
        console.log("alice's relay address = " + relayAddressAlice.address + ':' + relayAddressAlice.port)
        // allocate relaying session for bob
        return clientBob.allocateP()
      })
      .then(function (allocateAddress) {
        srflxAddressBob = allocateAddress.mappedAddress
        relayAddressBob = allocateAddress.relayedAddress
        console.log("bob's address = " + srflxAddressBob.address + ':' + srflxAddressBob.port)
        console.log("bob's relay address = " + relayAddressBob.address + ':' + relayAddressBob.port)
        // create permission for alice to send messages to bob
        return clientBob.createPermissionP(relayAddressAlice.address)
      })
      .then(function () {
        // create channel from alice to bob
        return clientAlice.bindChannelP(relayAddressBob.address, relayAddressBob.port)
      })
      .then(function (channel) {
        expect(channel).not.to.be.undefined
        channelId = channel
        // mimic refreshing of channel binding
        return clientAlice.bindChannelP(relayAddressBob.address, relayAddressBob.port, channel)
      })
      .then(function (channel) {
        expect(channel).to.equal(channelId)
        //  create permission for bob to send messages to alice
        return clientAlice.createPermissionP(relayAddressBob.address)
      })
      .then(function () {
        // create channel from bob to alice
        return clientBob.bindChannelP(relayAddressAlice.address, relayAddressAlice.port)
      })
      .then(function (anotherChannel) {
        // send test message
        sendTestMessageFromAliceToBob()
      })
      .catch(function (error) {
        done(error)
      })
  })
})
<|endoftext|>


<commit_before>/**
 * .reel Unit Tests
 */
(function($){

  module('Computation', { teardown: function teardown(){
    $('.jquery-reel').trigger('teardown');
  }});

  asyncTest( '`fractionChange` accepts and normalizes any real fraction passed', function(){
    expect(10);
    var
      selector= '#image',
      $reel= $(selector).reel(),
      entries= {
        '3': 0,
        '-2.1': 0.9,
        '-3.7': 0.3,
        '1.8': 0.8,
        '3.4': 0.4,
        '3.5': 0.5,
        '-0.3': 0.7,
        '1.23456': 0.2346,
        '-1.23456': 0.7654,
        '-1.2': 0.8
      }
    $reel.one('loaded', function(){
      $.each(entries, function(ix,it){
        $reel.trigger('fractionChange', Number(ix));
        equal( $reel.data('fraction').toFixed(4), it, 'Passed '+ix);
      });
      start();
    });
  });

  asyncTest( '`rowChange` accepts and normalizes any real row fraction passed', function(){
    expect(7);
    var
      selector= '#image',
      $reel= $(selector).reel({ rows: 3 }),
      entries= {
        '4': 1,
        '-2.1': 0,
        '1.8': 0.4,
        '0.4': 0,
        '-0.3': 0,
        '1.23456': 0.1173,
        '-1.23456': 0
      }
    $reel.one('loaded', function(){
      $.each(entries, function(ix,it){
        $reel.trigger('rowChange', Number(ix));
        equal( $reel.data('row').toFixed(4), it, 'Fraction '+ix);
      });
      start();
    });
  });

  asyncTest( 'Positive direction/spped is not detected as reversed', function(){
    expect(1);
    var
      selector= '#image',
      $reel= $(selector).reel({ speed: 1 })

    equal( $reel.data('backwards'), false, 'Not reversed at positive speed');
    start();
  });

  asyncTest( 'Negative direction/spped is detected as reversed', function(){
    expect(1);
    var
      selector= '#image',
      $reel= $(selector).reel({ speed: -1 })

    equal( $reel.data('backwards'), true, 'Reversed at negative speeds');
    start();
  });

  test( 'Default `$.reel.math.spread`', function(){
    expect(11);
    var
      probes= {
        10: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10],
            frames: 10,
            frame: 1
          },
          ordered: '1,6,4,9,2,7,5,10,3,8'.split(/, ?/)
        },
        12: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12],
            frames: 12,
            frame: 1
          },
          ordered: '1,7,4,10,3,9,6,12,2,8,5,11'.split(/, ?/)
        },
        15: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
            frames: 15,
            frame: 1
          },
          ordered: '1,9,5,13,3,11,7,15,2,10,6,14,4,12,8'.split(/, ?/)
        },
        18: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],
            frames: 18,
            frame: 1
          },
          ordered: '1,10,6,15,3,12,8,17,2,11,7,16,4,13,9,18,5,14'.split(/, ?/)
        },
        24: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
            frames: 24,
            frame: 1
          },
          ordered: '1,13, 7,19, 4,16,10,22, 3,15,9,21,6,18,12,24, 2,14,8,20,5,17,11,23'.split(/, ?/)
        },
        36: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],
            frames: 36,
            frame: 1
          },
          ordered: '1,19, 10,28, 6,24,15,33, 3,21,12,30,8,26,17,35, 2,20,11,29,7,25,16,34,4,22,13,31,9,27,18,36, 5,23,14,32'.split(/, ?/)
        },
        48: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],
            frames: 48,
            frame: 1
          },
          ordered: '1,25, 13,37, 7,31,19,43, 4,28,16,40,10,34,22,46, 3,27,15,39,9,33,21,45,6,30,18,42,12,36,24,48, 2,26,14,38,8,32,20,44,5,29,17,41,11,35,23,47'.split(/, ?/)
        },

        // Atypicals with different starting points
        17: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],
            frames: 17,
            frame: 7
          },
          ordered: '7,16, 11,3, 9,1,13,5, 8,17,12,4,10,2,14,6, 15'.split(/, ?/)
        },
        23: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
            frames: 23,
            frame: 11
          },
          ordered: '11,23, 17,6, 14,3,20,9, 12,1,18,7,15,4,21,10, 13,2,19,8,16,5,22'.split(/, ?/)
        },
        27: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27],
            frames: 27,
            frame: 27
          },
          ordered: '27,14, 7,21, 3,17,10,24, 2,16,9,23,5,19,12,26, 1,15,8,22,4,18,11,25,6,20,13'.split(/, ?/)
        }
      }

    ok( typeof $.reel.math.spread == 'function', '`$.reel.math.spread` available');

    $.each(probes, function(ix, def){
      var
        $reel= $('#image').reel(def.options)
      deepEqual( $reel.data('images'), def.ordered, ix+' frames starting at frame '+def.options.frame);
    });

  });

})(jQuery);
<commit_msg>Adding multi-row and dual-orbit test cases. #10<commit_after>/**
 * .reel Unit Tests
 */
(function($){

  module('Computation', { teardown: function teardown(){
    $('.jquery-reel').trigger('teardown');
  }});

  asyncTest( '`fractionChange` accepts and normalizes any real fraction passed', function(){
    expect(10);
    var
      selector= '#image',
      $reel= $(selector).reel(),
      entries= {
        '3': 0,
        '-2.1': 0.9,
        '-3.7': 0.3,
        '1.8': 0.8,
        '3.4': 0.4,
        '3.5': 0.5,
        '-0.3': 0.7,
        '1.23456': 0.2346,
        '-1.23456': 0.7654,
        '-1.2': 0.8
      }
    $reel.one('loaded', function(){
      $.each(entries, function(ix,it){
        $reel.trigger('fractionChange', Number(ix));
        equal( $reel.data('fraction').toFixed(4), it, 'Passed '+ix);
      });
      start();
    });
  });

  asyncTest( '`rowChange` accepts and normalizes any real row fraction passed', function(){
    expect(7);
    var
      selector= '#image',
      $reel= $(selector).reel({ rows: 3 }),
      entries= {
        '4': 1,
        '-2.1': 0,
        '1.8': 0.4,
        '0.4': 0,
        '-0.3': 0,
        '1.23456': 0.1173,
        '-1.23456': 0
      }
    $reel.one('loaded', function(){
      $.each(entries, function(ix,it){
        $reel.trigger('rowChange', Number(ix));
        equal( $reel.data('row').toFixed(4), it, 'Fraction '+ix);
      });
      start();
    });
  });

  asyncTest( 'Positive direction/spped is not detected as reversed', function(){
    expect(1);
    var
      selector= '#image',
      $reel= $(selector).reel({ speed: 1 })

    equal( $reel.data('backwards'), false, 'Not reversed at positive speed');
    start();
  });

  asyncTest( 'Negative direction/spped is detected as reversed', function(){
    expect(1);
    var
      selector= '#image',
      $reel= $(selector).reel({ speed: -1 })

    equal( $reel.data('backwards'), true, 'Reversed at negative speeds');
    start();
  });

  test( 'Default `$.reel.math.spread`', function(){
    expect(14);
    var
      probes= {
        10: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10],
            frames: 10,
            frame: 1
          },
          ordered: '1,6,4,9,2,7,5,10,3,8'.split(/, ?/)
        },
        12: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12],
            frames: 12,
            frame: 1
          },
          ordered: '1,7,4,10,3,9,6,12,2,8,5,11'.split(/, ?/)
        },
        15: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
            frames: 15,
            frame: 1
          },
          ordered: '1,9,5,13,3,11,7,15,2,10,6,14,4,12,8'.split(/, ?/)
        },
        18: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],
            frames: 18,
            frame: 1
          },
          ordered: '1,10,6,15,3,12,8,17,2,11,7,16,4,13,9,18,5,14'.split(/, ?/)
        },
        24: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
            frames: 24,
            frame: 1
          },
          ordered: '1,13, 7,19, 4,16,10,22, 3,15,9,21,6,18,12,24, 2,14,8,20,5,17,11,23'.split(/, ?/)
        },
        36: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],
            frames: 36,
            frame: 1
          },
          ordered: '1,19, 10,28, 6,24,15,33, 3,21,12,30,8,26,17,35, 2,20,11,29,7,25,16,34,4,22,13,31,9,27,18,36, 5,23,14,32'.split(/, ?/)
        },
        48: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],
            frames: 48,
            frame: 1
          },
          ordered: '1,25, 13,37, 7,31,19,43, 4,28,16,40,10,34,22,46, 3,27,15,39,9,33,21,45,6,30,18,42,12,36,24,48, 2,26,14,38,8,32,20,44,5,29,17,41,11,35,23,47'.split(/, ?/)
        },

        // Atypicals with different starting points
        17: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],
            frames: 17,
            frame: 7
          },
          ordered: '7,16, 11,3, 9,1,13,5, 8,17,12,4,10,2,14,6, 15'.split(/, ?/)
        },
        23: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
            frames: 23,
            frame: 11
          },
          ordered: '11,23, 17,6, 14,3,20,9, 12,1,18,7,15,4,21,10, 13,2,19,8,16,5,22'.split(/, ?/)
        },
        27: {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27],
            frames: 27,
            frame: 27
          },
          ordered: '27,14, 7,21, 3,17,10,24, 2,16,9,23,5,19,12,26, 1,15,8,22,4,18,11,25,6,20,13'.split(/, ?/)
        },

        // Multi-rows
        '2x10': {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
            frames: 10,
            frame: 1,
            rows: 2
          },
          ordered: '1,6, 4,9, 2,7,5,10, 3,8, 11,16, 14,19, 12,17,15,20, 13,18'.split(/, ?/)
        },
        '4x10': {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40],
            frames: 10,
            frame: 1,
            rows: 4,
            row: 2
          },
          ordered: '11,16, 14,19, 12,17,15,20, 13,18, 1,6,21,26,31,36, 4,9,24,29,34,39, 2,7,22,27,32,37,5,25,30,35,40, 3,8,23,28,33,38'.split(/, ?/)
        },
        'orbital': {
          options: {
            images: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],
            footage: 9,
            frame: 1,
            orbital: 3
          },
          ordered: '1,6, 3,8, 2,7,4,9, 5, 10,15, 12,17, 11,16,13,18, 14'.split(/, ?/)
        }
      }

    ok( typeof $.reel.math.spread == 'function', '`$.reel.math.spread` available');

    $.each(probes, function(ix, def){
      var
        $reel= $('#image').reel(def.options)
      deepEqual( $reel.data('images'), def.ordered, ix+' frames starting at frame '+def.options.frame);
    });

  });

})(jQuery);
<|endoftext|>


<commit_before>var keypair          = StellarBase.Keypair.master();
let unencodedBuffer  = keypair.rawPublicKey();
let unencoded        = unencodedBuffer.toString();
let accountIdEncoded = keypair.address();
let seedEncoded      = StellarBase.encodeCheck("seed", unencodedBuffer);

describe('StellarBase#decodeCheck', function() {

  it("decodes correctly", function() {
    expectBuffersToBeEqual(StellarBase.decodeCheck("accountId", accountIdEncoded), unencodedBuffer);
    expectBuffersToBeEqual(StellarBase.decodeCheck("seed", seedEncoded), unencodedBuffer);
  });

  it("throws an error when the version byte is not defined", function() {
    expect(() => StellarBase.decodeCheck("notreal", "gpvQBfBaMiGQZ2xUqW9KNR")).to.throw(/notreal is not a valid/);
    expect(() => StellarBase.decodeCheck("broken", "n3GdokGwy1qJ11qLmsTzoL")).to.throw(/broken is not a valid/);
  });

  it("throws an error when the version byte is wrong", function() {
    expect(() => StellarBase.decodeCheck("seed", "GBPXXOA5N4JYPESHAADMQKBPWZWQDQ64ZV6ZL2S3LAGW4SY7NTCMWIVL")).to.throw(/invalid version/);
    expect(() => StellarBase.decodeCheck("accountId", "SBGWKM3CD4IL47QN6X54N6Y33T3JDNVI6AIJ6CD5IM47HG3IG4O36XCU")).to.throw(/invalid version/);
  });

  it("throws an error when the checksum is wrong", function() {
    expect(() => StellarBase.decodeCheck("accountId", "GBPXXOA5N4JYPESHAADMQKBPWZWQDQ64ZV6ZL2S3LAGW4SY7NTCMWIVT")).to.throw(/invalid checksum/);
    expect(() => StellarBase.decodeCheck("seed", "SBGWKM3CD4IL47QN6X54N6Y33T3JDNVI6AIJ6CD5IM47HG3IG4O36XCX")).to.throw(/invalid checksum/);
  });
});

describe('StellarBase#encodeCheck', function() {

  it("encodes a buffer correctly", function() {
    expect(StellarBase.encodeCheck("accountId", unencodedBuffer)).to.eql(accountIdEncoded);
    expect(StellarBase.encodeCheck("seed", unencodedBuffer)).to.eql(seedEncoded);
  });

  it("encodes a buffer correctly", function() {
    expect(StellarBase.encodeCheck("accountId", unencodedBuffer)).to.eql(accountIdEncoded);
    expect(StellarBase.encodeCheck("seed", unencodedBuffer)).to.eql(seedEncoded);
  });

  it("throws an error when the data is null", function() {
    expect(() => StellarBase.encodeCheck("seed", null)).to.throw(/null data/);
    expect(() => StellarBase.encodeCheck("accountId", null)).to.throw(/null data/);
  });

  it("throws an error when the version byte is not defined", function() {
    expect(() => StellarBase.encodeCheck("notreal", unencoded)).to.throw(/notreal is not a valid/);
    expect(() => StellarBase.encodeCheck("broken", unencoded)).to.throw(/broken is not a valid/);
  });
});

function expectBuffersToBeEqual(left, right) {
  let leftHex = left.toString('hex');
  let rightHex = right.toString('hex');

  expect(leftHex).to.eql(rightHex);
}
<commit_msg>Fixed StellarBase#decodeCheck test<commit_after>var keypair          = StellarBase.Keypair.master();
let unencodedBuffer  = keypair.rawPublicKey();
let unencoded        = unencodedBuffer.toString();
let accountIdEncoded = keypair.address();
let seedEncoded      = StellarBase.encodeCheck("seed", unencodedBuffer);

describe('StellarBase#decodeCheck', function() {

  it("decodes correctly", function() {
    expectBuffersToBeEqual(StellarBase.decodeCheck("accountId", accountIdEncoded), unencodedBuffer);
    expectBuffersToBeEqual(StellarBase.decodeCheck("seed", seedEncoded), unencodedBuffer);
  });

  it("throws an error when the version byte is not defined", function() {
    expect(() => StellarBase.decodeCheck("notreal", "GBPXXOA5N4JYPESHAADMQKBPWZWQDQ64ZV6ZL2S3LAGW4SY7NTCMWIVL")).to.throw(/notreal is not a valid/);
    expect(() => StellarBase.decodeCheck("broken", "SBGWKM3CD4IL47QN6X54N6Y33T3JDNVI6AIJ6CD5IM47HG3IG4O36XCU")).to.throw(/broken is not a valid/);
  });

  it("throws an error when the version byte is wrong", function() {
    expect(() => StellarBase.decodeCheck("seed", "GBPXXOA5N4JYPESHAADMQKBPWZWQDQ64ZV6ZL2S3LAGW4SY7NTCMWIVL")).to.throw(/invalid version/);
    expect(() => StellarBase.decodeCheck("accountId", "SBGWKM3CD4IL47QN6X54N6Y33T3JDNVI6AIJ6CD5IM47HG3IG4O36XCU")).to.throw(/invalid version/);
  });

  it("throws an error when the checksum is wrong", function() {
    expect(() => StellarBase.decodeCheck("accountId", "GBPXXOA5N4JYPESHAADMQKBPWZWQDQ64ZV6ZL2S3LAGW4SY7NTCMWIVT")).to.throw(/invalid checksum/);
    expect(() => StellarBase.decodeCheck("seed", "SBGWKM3CD4IL47QN6X54N6Y33T3JDNVI6AIJ6CD5IM47HG3IG4O36XCX")).to.throw(/invalid checksum/);
  });
});

describe('StellarBase#encodeCheck', function() {

  it("encodes a buffer correctly", function() {
    expect(StellarBase.encodeCheck("accountId", unencodedBuffer)).to.eql(accountIdEncoded);
    expect(StellarBase.encodeCheck("seed", unencodedBuffer)).to.eql(seedEncoded);
  });

  it("encodes a buffer correctly", function() {
    expect(StellarBase.encodeCheck("accountId", unencodedBuffer)).to.eql(accountIdEncoded);
    expect(StellarBase.encodeCheck("seed", unencodedBuffer)).to.eql(seedEncoded);
  });

  it("throws an error when the data is null", function() {
    expect(() => StellarBase.encodeCheck("seed", null)).to.throw(/null data/);
    expect(() => StellarBase.encodeCheck("accountId", null)).to.throw(/null data/);
  });

  it("throws an error when the version byte is not defined", function() {
    expect(() => StellarBase.encodeCheck("notreal", unencoded)).to.throw(/notreal is not a valid/);
    expect(() => StellarBase.encodeCheck("broken", unencoded)).to.throw(/broken is not a valid/);
  });
});

function expectBuffersToBeEqual(left, right) {
  let leftHex = left.toString('hex');
  let rightHex = right.toString('hex');

  expect(leftHex).to.eql(rightHex);
}
<|endoftext|>


<commit_before>angular.module('genome.self', [])
.controller('SelfController', function ($scope, $cookies, $location, SelfFactory, d3Service, $rootScope) {

  $scope.outcomes = $scope.outcomes || [];
  $scope.current = {};

   var whichView = function() {
    $rootScope.view = $location.$$path;
  }
  whichView();

  $rootScope.removeHelix = function () {
    d3.select("svg").remove();
  }

    /* The 'FILLS' block will determine the availability of colors, balls and lines
     * and what quantity and other attributes the d3 plot should contain */
  var fills = ['#E74C3C', '#3498DB', '#2ECC71'],
    h = 800,
    w = 150,
    numX = 0,
    numY = 0,
    speed = 0.01,
    torsion = 0.3,
    x = d3.scale.linear().range([20, w - 20]),
    y = d3.scale.linear().range([h - 100, 20]),
    z = d3.scale.linear().range([18, 5]);
      /**
        * This block will append the built svg elements to the "body" of the HTML
      **/
  var svg = d3.select(".BodyContainer")
      .append("svg")
      .attr("id", "helix")
      .attr("width", w)
      .attr("height", h);

  /** Appends the inner SVG to a larger SVG container **/
  svg.append("DNAHelix")
      .attr("width", w)
      .attr("height", h)
      .attr("fill", "white");
  var container = svg.append("g");
  var counter = 0;

  function generateData() {
    counter++;
    // Creating a range of numX (set to outcomes length) and then map
    var data = d3.range(numX).map(function (d, i) {
        var t = d * torsion - speed * counter;
          return [{ x: Math.cos(t),
                    y: d,
                    z: Math.sin(t),
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome
                  },
                  { x: Math.cos(t - Math.PI),
                    y: d,
                    z: Math.sin(t - Math.PI),
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome
                  }];
        });
      var flat = _.flatten(data);
      x.domain(d3.extent(flat, function(d){ return d.x; }));
      y.domain(d3.extent(flat, function(d){ return d.y; }));
      z.domain(d3.extent(flat, function(d){ return d.z; }));
      return data;
  }
  function draw () {
    var cont = container.selectAll("g").data(generateData());
    cont.exit().remove();
    var enter = cont.enter()
      .append("g")
      .each(function (d, index) {
          d3.select(this)
            .selectAll("circle")
            .data(d)
            .enter()
            .append("circle")
            .attr("fill", "black")
            .on("click", function () {
                console.log('clicking on a ball!!!');
              });
          d3.select(this).append('line')
              .attr("stroke", function (d, i) {
                return fills[index%3];
              })
              .attr("stroke-width", 2);
          });

        cont.each(function (d, index) {
          var inverted = (d[0].y < d[1].x) ? 1 : -1;
          d3.select(this)
            .selectAll("circle")
            .data(d)
            .attr("cx", function (d) { return x(d.x); })
            .attr("cy", function (d) { return y(d.y); })
            .attr("r",  function (d) { return z(d.z); })
            .attr("fill-opacity", function (d) { return z(d.z) / 10;})
            .attr("fill", function (d, i) { return fills[index%3]; })
            .attr("rsid", function(d){ return d.rsid; })
            .attr("pair", function(d){ return d.pair; })
            .attr("outcome", function(d){ return d.outcome; })
            .on("mouseover", function (d, i) {
              // Using $scope.$apply to force angular to rerender once the scope has been updated with the current snp
              $scope.$apply($scope.current = { rsid: d.rsid, pair: d.pair, outcome: d.outcome });
            });
          d3.select(this)
              .select('line')
              .attr("x2", x(d[0].x) + inverted * z(d[0].z))
              .attr("x1", x(d[1].x) - inverted * z(d[1].z))
              .attr("y2", y(d[0].y))
              .attr("y1", y(d[0].y));
          });
      }

      SelfFactory.getSnps($cookies.user_profile_id).then(function (outcomes) {
        for (var key in outcomes) {
          $scope.outcomes.push(outcomes[key]);
        }
        $scope.current = {
          rsid: 'rs1337',
          pair: 'GG',
          outcome: 'A very interesting fact'
        },
        numX = $scope.outcomes.length;
        setInterval(draw, 25);
      });

})

.factory('SelfFactory', function ($http) {
/**
  * Used to retrieve information about SNPs pertaining to currently logged in user
**/
  var getSnps = function (userId) {
    return $http({
      method: 'POST',
      url: '/api/getsnps',
      data: userId
    }).then(function (snps) {
      return snps.data.outcomes;
    }).catch(function (err) {
      console.error('An error occured retreiving your SNPs ', err);
    });
  };

  return {
    getSnps: getSnps
  };
});
<commit_msg>Edited intro message<commit_after>angular.module('genome.self', [])
.controller('SelfController', function ($scope, $cookies, $location, SelfFactory, d3Service, $rootScope) {

  $scope.outcomes = $scope.outcomes || [];
  $scope.current = {};

   var whichView = function() {
    $rootScope.view = $location.$$path;
  }
  whichView();

  $rootScope.removeHelix = function () {
    d3.select("svg").remove();
  }

    /* The 'FILLS' block will determine the availability of colors, balls and lines
     * and what quantity and other attributes the d3 plot should contain */
  var fills = ['#E74C3C', '#3498DB', '#2ECC71'],
    h = 800,
    w = 150,
    numX = 0,
    numY = 0,
    speed = 0.01,
    torsion = 0.3,
    x = d3.scale.linear().range([20, w - 20]),
    y = d3.scale.linear().range([h - 100, 20]),
    z = d3.scale.linear().range([18, 5]);
      /**
        * This block will append the built svg elements to the "body" of the HTML
      **/
  var svg = d3.select(".BodyContainer")
      .append("svg")
      .attr("id", "helix")
      .attr("width", w)
      .attr("height", h);

  /** Appends the inner SVG to a larger SVG container **/
  svg.append("DNAHelix")
      .attr("width", w)
      .attr("height", h)
      .attr("fill", "white");
  var container = svg.append("g");
  var counter = 0;

  function generateData() {
    counter++;
    // Creating a range of numX (set to outcomes length) and then map
    var data = d3.range(numX).map(function (d, i) {
        var t = d * torsion - speed * counter;
          return [{ x: Math.cos(t),
                    y: d,
                    z: Math.sin(t),
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome
                  },
                  { x: Math.cos(t - Math.PI),
                    y: d,
                    z: Math.sin(t - Math.PI),
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome
                  }];
        });
      var flat = _.flatten(data);
      x.domain(d3.extent(flat, function(d){ return d.x; }));
      y.domain(d3.extent(flat, function(d){ return d.y; }));
      z.domain(d3.extent(flat, function(d){ return d.z; }));
      return data;
  }
  function draw () {
    var cont = container.selectAll("g").data(generateData());
    cont.exit().remove();
    var enter = cont.enter()
      .append("g")
      .each(function (d, index) {
          d3.select(this)
            .selectAll("circle")
            .data(d)
            .enter()
            .append("circle")
            .attr("fill", "black")
            .on("click", function () {
                console.log('clicking on a ball!!!');
              });
          d3.select(this).append('line')
              .attr("stroke", function (d, i) {
                return fills[index%3];
              })
              .attr("stroke-width", 2);
          });

        cont.each(function (d, index) {
          var inverted = (d[0].y < d[1].x) ? 1 : -1;
          d3.select(this)
            .selectAll("circle")
            .data(d)
            .attr("cx", function (d) { return x(d.x); })
            .attr("cy", function (d) { return y(d.y); })
            .attr("r",  function (d) { return z(d.z); })
            .attr("fill-opacity", function (d) { return z(d.z) / 10;})
            .attr("fill", function (d, i) { return fills[index%3]; })
            .attr("rsid", function(d){ return d.rsid; })
            .attr("pair", function(d){ return d.pair; })
            .attr("outcome", function(d){ return d.outcome; })
            .on("mouseover", function (d, i) {
              // Using $scope.$apply to force angular to rerender once the scope has been updated with the current snp
              $scope.$apply($scope.current = { rsid: d.rsid, pair: d.pair, outcome: d.outcome });
            });
          d3.select(this)
              .select('line')
              .attr("x2", x(d[0].x) + inverted * z(d[0].z))
              .attr("x1", x(d[1].x) - inverted * z(d[1].z))
              .attr("y2", y(d[0].y))
              .attr("y1", y(d[0].y));
          });
      }

      SelfFactory.getSnps($cookies.user_profile_id).then(function (outcomes) {
        for (var key in outcomes) {
          $scope.outcomes.push(outcomes[key]);
        }
        $scope.current = {
          rsid: 'rs12345',
          pair: 'AA',
          outcome: 'A very interesting fact'
        },
        numX = $scope.outcomes.length;
        setInterval(draw, 25);
      });

})

.factory('SelfFactory', function ($http) {
/**
  * Used to retrieve information about SNPs pertaining to currently logged in user
**/
  var getSnps = function (userId) {
    return $http({
      method: 'POST',
      url: '/api/getsnps',
      data: userId
    }).then(function (snps) {
      return snps.data.outcomes;
    }).catch(function (err) {
      console.error('An error occured retreiving your SNPs ', err);
    });
  };

  return {
    getSnps: getSnps
  };
});
<|endoftext|>


<commit_before>angular.module('genome.self', [])

.controller('SelfController', function ($scope, $rootScope, $location) {

  $scope.stuff = [1,2,3,4];
})

.factory('selfFactory', function ($http) {

});
<commit_msg>Flushed out blueprint for self controller/factory<commit_after>angular.module('genome.self', [])

.controller('SelfController', function ($scope, $rootScope, $location, SelfFactory) {
 	//Build out retreival functions to send out request on initialization for SNPs
 	//$scope.snps will hold each snp as the key, and a string of detailed information regarding each snp
 	$scope.snps = {};

})

.factory('SelfFactory', function ($http) {

/**
	* Used to retrieve information about SNPs pertaining to currently logged in user
**/
	var getSnps = function (userId) {
		return $http({
			method: 'POST',
			url: '/api/snpsdata'
			data: userId
		}).then(function (snps) {
			//do something with the snps retrieved here
		}).catch(function (err) {
			console.error('An error occured retreiving your SNPs ', err);
		});
	};

	return {
		getSnps: getSnps
	}

});
<|endoftext|>