<commit_before>console.log('Calmer than you are.');

//get Master firefox version
function getFirefoxMasterVersion(userAgent) {
    var version = 0;
    var ua = userAgent || navigator.userAgent;

    var matches = /Firefox\/([0-9]+).[0-9]+(?:.[0-9]+)?/.exec(
        ua
    );

    if (matches !== null && matches.length > 0) {
        version = parseInt(matches[1], 10);
    }

    return version;
}

function isFirefox(userAgent) {
    var ua = userAgent || navigator.userAgent;
    // camino UA string contains 'like Firefox'
    return (
        (/\sFirefox/).test(ua) &&
        !(/like Firefox/i).test(ua) &&
        !(/SeaMonkey/i).test(ua)
    );
}

function isAustralis() {
    // Check if the visitor is using Firefox and it's v29+
    if (isFirefox()) {
        var fx_version = getFirefoxMasterVersion();
        var minimumAustralisVersion = 29;
        return (fx_version >= minimumAustralisVersion);
    } else {
        return false;
    }
}

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

function getJsonDataUrl() {
    var $body = $('body');
    var staticDataUrl = $body.data('staticDataUrl');

    // NOTE: will be 0 when redis is off or returns nothing
    var latestTimestamp = $body.data('timestamp'); // an int

    if (!latestTimestamp) {
        // guess at the latest timestamp (mostly for dev)
        var coeff = 1000 * 60;
        var date = new Date().addHours(7);
        latestTimestamp = new Date(Math.round(date.getTime() / coeff) * 60).getTime();
    }

    // two minutes ago
    latestTimestamp -= 120;  // seconds
    var url = staticDataUrl + 'stats_' + latestTimestamp + '.json';
    console.log(url);
    return url;
}

var $stats_panel_tab_title = $('.stats-panel-tab .title');
var stats_panel_opened_title = $stats_panel_tab_title.data('open-title');
var stats_panel_closed_title = $stats_panel_tab_title.text();

function openStatsPanel() {
    // hide glows on stats panel open
    if (showing_glows) {
        hideGlows();
    } else {
        showGlows();
    }

    showing_glows = !showing_glows;

    // update tab title
    if ($('body').hasClass('stats-panel-open')) {
        $stats_panel_tab_title.text(stats_panel_opened_title);
    } else {
        $stats_panel_tab_title.text(stats_panel_closed_title);
    }
}

$(document).ready(function () {

    var $choice_modal = $('.choice-modal');
    var $choices = $('.choices .btn');
    var events = 'transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd';

    $('.choice-footer-container').on(
        events,
        function (event) {
            if (event.target === event.currentTarget) {
                var state = $(this).data('state');
                if (state === 'opening-height') {
                    $(this).data('state', '');
                    $('.choice-footnotes').css('display', 'block');
                    $('.choice-footer-content, .choice-footnotes')
                        .data('state', 'opening-opacity')
                        .css('opacity', '1');
                }
            }
        }
    );

    $('.choice-footnotes').on(
        events,
        function (event) {
            if (event.target === event.currentTarget) {
                var state = $(this).data('state');
                if (state === 'closing-opacity') {
                    $(this).data('state', '').css('display', 'none');
                }
            }
        }
    );

    $('.choice-footer-content').on(
        events,
        function (event) {
            if (event.target === event.currentTarget) {
                var state = $(this).data('state');
                if (state === 'closing-opacity') {
                    $('.choice-footer-container')
                        .data('state', 'closing-height')
                        .css('height', 0);
                }
            }
        }
    );

    $choice_modal.find('.choice-body-container').on(
        events,
        function (event) {
            var $body = $(this);
            if (event.target === event.currentTarget) {
                var state = $body.data('state');
                if (state === 'opening-opacity-out') {
                    $('.choices').removeClass('in-progress');
                    $choices.each(function(i) {
                        $(this).removeClass('selected');
                    });

                    var from_height = $body.height();

                    // TODO: we need to ignore this transition
                    $body.css('height', from_height);

                    $choice_modal.addClass('choice-modal-interstitial');

                    var to_height = $body.find('.modal-body').outerHeight();

                    setTimeout(function() {
                        // TODO: this gets triggered on initial height event
                        $body.data('state', 'opening-height');
                        $body.css('height', to_height);
                    }, 0);
                } else if (state === 'opening-height') {
                    $body.data('state', 'opening-opacity-in').css('opacity', 1);
                } else if (state === 'opening-opacity-in') {
                    $body.data('state', '');
                }
            }
        }
    );

    function showShareButtons() {
        var height = $('.choice-footer-container .modal-footer').outerHeight();
        $('.choice-footer-container').data('state', 'opening-height').height(height);
    }

    function hideShareButtons() {
        $('.choice-footnotes, .choice-footer-content')
            .data('state', 'closing-opacity')
            .css('opacity', 0);
    }

    function openInterstitialModal(choice) {
        hideShareButtons();

        $choice_modal.find('.choice-body-container')
            .data('state', 'opening-opacity-out')
            .css('opacity', 0);

        $choices.each(function(i) {
            $choice_modal.removeClass('interstitial-modal-' + $(this).data('choice'));
        });

        if (choice) {
            $choice_modal.addClass('interstitial-modal-' + choice);
        }
    }

    function handleChoiceModalOpen() {
        var $choice_modal = $(this);

        // remove any selection
        $choices.each(function(i) {
            $choice_modal.removeClass('interstitial-modal-' + $(this).data('choice'));
        });

        // make sure we're on the first page
        $choice_modal.removeClass('choice-modal-interstitial')
        $choice_modal.find('.choice-body-container').css('height', 'auto');

        // center it vertically
        $choice_modal.css('display', 'block');
        var $dialog = $choice_modal.find('.modal-dialog');

        setTimeout(function() {
            var offset = Math.max(
                // 150 pixels to approximately account for share buttons
                ($(window).height() - $dialog.height() - 150) / 2,
                20
            );
            $dialog.css('margin-top', offset);
        }, 20);
    }

    $choice_modal.on('show.bs.modal', handleChoiceModalOpen);

    var hash = window.location.hash;

    if (isAustralis()) {
        // if the browser is Australis, add a class to HTML tag
        // and show the primary choice modal
        var $html = $(document.documentElement);
        $('html').addClass('australis');

        // if we're on australis and there's no hash tag, show the choice modal
        if (hash.indexOf("#") === -1) {
            $choice_modal.modal();
        }
    } else {
        $('html').addClass('non-australis');
    }

    if (hash.indexOf("choice") != -1) {
        // if #choice is in the URL, show the choice modal
        $choice_modal.modal();
    } else if (hash.indexOf("video") != -1) {
        // if #video is in the URL, show the video modal
        $( '#video-modal' ).modal();
        insertVideo();
    } else if (hash.indexOf("number") != -1) {
        // if #number is in the URL, show the number modal
        $( '#number-modal' ).modal();
    } else if (hash.indexOf("stats") != -1) {
        // if #number is in the URL, show the number modal
        $( 'body' ).addClass('stats-panel-open');
        openStatsPanel();
    }

    $( '.stats-panel-tab' ).click(function() {
        $( 'body' ).toggleClass( "stats-panel-open" );
        openStatsPanel();
    });

    // turn on fading for choice modal after initial load so it fades
    // on subsequent open/closes, but not the first time
    $choice_modal.addClass('fade');

    // "Share the map" popopver
    $('.popover-markup > .trigger').popover({
        html : true,
        title: function() {
          return $(this).parent().find('.head').html();
        },
        content: function() {
          return $(this).parent().find('.content').html();
        },
        container: 'body'
    });

    // Close popover on click outside of popover
    $('body').on('click', function (e) {
        $('[data-toggle="popover"]').each(function () {
            //the 'is' for buttons that trigger popups
            //the 'has' for icons within a button that triggers a popup
            if (!$(this).is(e.target) &&
                $(this).has(e.target).length === 0 &&
                $('.popover').has(e.target).length === 0) {
                $(this).popover('hide');
            }
        });
    });

    $choices.click(function() {
        $choices.removeClass('selected');
        $(this).addClass('selected');
        $('.choices').addClass('in-progress');
        showShareButtons();
    });

    function openShareWindow(href) {
        $('.popover-markup  .trigger').popover('hide');
        window.open(href, '_blank', "height=420,width=550");
    }

    function shareChoice(choice) {
        var url = $choice_modal.data('share-url');
        if (url) {
            $.post(url, { 'issue': choice });
        }
    }

    // Open .share-window links in a new window, and close any popovers
    $(document).on('click', '.share-window', function(event) {
        event.preventDefault();
        openShareWindow(this.href);
    });

    $('.modal-footer .share-twitter').click(function(e) {
        var $selected = $('.choices .selected');
        if ($selected.length) {
            openShareWindow($selected.data('twitter'));
            openInterstitialModal($selected.data('choice'));
            shareChoice($selected.data('choice'));
        }
    });

    $('.modal-footer .share-facebook').click(function(e) {
        var $selected = $('.choices .selected');
        if ($selected.length) {
            openShareWindow($selected.data('facebook'));
            openInterstitialModal($selected.data('choice'));
            shareChoice($selected.data('choice'));
        }
    });

    $('.choice-footnotes .share-local').click(function(e) {
        var $selected = $('.choices .selected');
        if ($selected.length) {
            openInterstitialModal($selected.data('choice'));
            shareChoice($selected.data('choice'));
        }
    });

    // Insert YouTube video into #video modal
    function insertVideo(autoplay) {
        if (autoplay) {
            autoplay = '1';
        } else {
            autoplay = '0';
        }
        var width = 853;
        var height = 480;
        var id = 'WB98kYqQt9c';
        $('#video-modal .modal-body').html('<iframe width="' + width + '" height="' +
            height + '" src="//www.youtube-nocookie.com/embed/' +
            id + '?autoplay=' + autoplay + '&' +
            '" frameborder="0" allowfullscreen></iframe>')
    }

    $('#video-modal').on('show.bs.modal', function (e) {
        // Insert YouTube player when video modal is opened
        insertVideo(true);
    });

    $('#video-modal').on('hidden.bs.modal', function (e) {
        // Stop YouTube player when video modal is closed
        $('#video-modal .modal-body').html('');
    });

});
<commit_msg>Add back auto-updating nature of getJsonDataUrl.<commit_after>//get Master firefox version
function getFirefoxMasterVersion(userAgent) {
    var version = 0;
    var ua = userAgent || navigator.userAgent;

    var matches = /Firefox\/([0-9]+).[0-9]+(?:.[0-9]+)?/.exec(
        ua
    );

    if (matches !== null && matches.length > 0) {
        version = parseInt(matches[1], 10);
    }

    return version;
}

function isFirefox(userAgent) {
    var ua = userAgent || navigator.userAgent;
    // camino UA string contains 'like Firefox'
    return (
        (/\sFirefox/).test(ua) &&
        !(/like Firefox/i).test(ua) &&
        !(/SeaMonkey/i).test(ua)
    );
}

function isAustralis() {
    // Check if the visitor is using Firefox and it's v29+
    if (isFirefox()) {
        var fx_version = getFirefoxMasterVersion();
        var minimumAustralisVersion = 29;
        return (fx_version >= minimumAustralisVersion);
    } else {
        return false;
    }
}

var _currentDataTimestamp = 0;

// TODO: make this better and less hacky
// should not be in global scope, nor should
// most of this file.
window.setInterval(function(){
    // bump forward 1 minute
    if (_currentDataTimestamp) {
        // only move forward if it's been set
        _currentDataTimestamp += 60;
    }
}, 60000);  // 60s

function getDevTimestamp() {
    // TODO REMOVE ME
    // confirmed manually that this is equal to
    // smithers.utils.get_epoch_minute()
    var unixtime = (new Date()).getTime() / 1000  // seconds since epoch
    return Math.floor(unixtime / 60) * 60  // round down to minute
}

function getJsonDataUrl() {
    var $body = $('body');
    var staticDataUrl = $body.data('staticDataUrl');

    if (!_currentDataTimestamp) {
        // NOTE: will be 0 when redis is off or returns nothing
        var latestTimestamp = $body.data('timestamp'); // an int

        if (!latestTimestamp) {
            // TODO REMOVE ME
            // guess at the latest timestamp (for dev)
            console.log('USING DEV TIMESTAMP!');
            // take off 3 extra minutes for fewer 404s
            latestTimestamp = getDevTimestamp() - 180;
        }

        // two minutes ago
        _currentDataTimestamp = latestTimestamp - 120;
    }
    console.log('Current timestamp', _currentDataTimestamp);
    var url = staticDataUrl + 'stats_' + _currentDataTimestamp + '.json';
    console.log(url);
    return url;
}

var $stats_panel_tab_title = $('.stats-panel-tab .title');
var stats_panel_opened_title = $stats_panel_tab_title.data('open-title');
var stats_panel_closed_title = $stats_panel_tab_title.text();

function openStatsPanel() {
    // hide glows on stats panel open
    if (showing_glows) {
        hideGlows();
    } else {
        showGlows();
    }

    showing_glows = !showing_glows;

    // update tab title
    if ($('body').hasClass('stats-panel-open')) {
        $stats_panel_tab_title.text(stats_panel_opened_title);
    } else {
        $stats_panel_tab_title.text(stats_panel_closed_title);
    }
}

$(document).ready(function () {

    var $choice_modal = $('.choice-modal');
    var $choices = $('.choices .btn');
    var events = 'transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd';

    $('.choice-footer-container').on(
        events,
        function (event) {
            if (event.target === event.currentTarget) {
                var state = $(this).data('state');
                if (state === 'opening-height') {
                    $(this).data('state', '');
                    $('.choice-footnotes').css('display', 'block');
                    $('.choice-footer-content, .choice-footnotes')
                        .data('state', 'opening-opacity')
                        .css('opacity', '1');
                }
            }
        }
    );

    $('.choice-footnotes').on(
        events,
        function (event) {
            if (event.target === event.currentTarget) {
                var state = $(this).data('state');
                if (state === 'closing-opacity') {
                    $(this).data('state', '').css('display', 'none');
                }
            }
        }
    );

    $('.choice-footer-content').on(
        events,
        function (event) {
            if (event.target === event.currentTarget) {
                var state = $(this).data('state');
                if (state === 'closing-opacity') {
                    $('.choice-footer-container')
                        .data('state', 'closing-height')
                        .css('height', 0);
                }
            }
        }
    );

    $choice_modal.find('.choice-body-container').on(
        events,
        function (event) {
            var $body = $(this);
            if (event.target === event.currentTarget) {
                var state = $body.data('state');
                if (state === 'opening-opacity-out') {
                    $('.choices').removeClass('in-progress');
                    $choices.each(function(i) {
                        $(this).removeClass('selected');
                    });

                    var from_height = $body.height();

                    // TODO: we need to ignore this transition
                    $body.css('height', from_height);

                    $choice_modal.addClass('choice-modal-interstitial');

                    var to_height = $body.find('.modal-body').outerHeight();

                    setTimeout(function() {
                        // TODO: this gets triggered on initial height event
                        $body.data('state', 'opening-height');
                        $body.css('height', to_height);
                    }, 0);
                } else if (state === 'opening-height') {
                    $body.data('state', 'opening-opacity-in').css('opacity', 1);
                } else if (state === 'opening-opacity-in') {
                    $body.data('state', '');
                }
            }
        }
    );

    function showShareButtons() {
        var height = $('.choice-footer-container .modal-footer').outerHeight();
        $('.choice-footer-container').data('state', 'opening-height').height(height);
    }

    function hideShareButtons() {
        $('.choice-footnotes, .choice-footer-content')
            .data('state', 'closing-opacity')
            .css('opacity', 0);
    }

    function openInterstitialModal(choice) {
        hideShareButtons();

        $choice_modal.find('.choice-body-container')
            .data('state', 'opening-opacity-out')
            .css('opacity', 0);

        $choices.each(function(i) {
            $choice_modal.removeClass('interstitial-modal-' + $(this).data('choice'));
        });

        if (choice) {
            $choice_modal.addClass('interstitial-modal-' + choice);
        }
    }

    function handleChoiceModalOpen() {
        var $choice_modal = $(this);

        // remove any selection
        $choices.each(function(i) {
            $choice_modal.removeClass('interstitial-modal-' + $(this).data('choice'));
        });

        // make sure we're on the first page
        $choice_modal.removeClass('choice-modal-interstitial')
        $choice_modal.find('.choice-body-container').css('height', 'auto');

        // center it vertically
        $choice_modal.css('display', 'block');
        var $dialog = $choice_modal.find('.modal-dialog');

        setTimeout(function() {
            var offset = Math.max(
                // 150 pixels to approximately account for share buttons
                ($(window).height() - $dialog.height() - 150) / 2,
                20
            );
            $dialog.css('margin-top', offset);
        }, 20);
    }

    $choice_modal.on('show.bs.modal', handleChoiceModalOpen);

    var hash = window.location.hash;

    if (isAustralis()) {
        // if the browser is Australis, add a class to HTML tag
        // and show the primary choice modal
        var $html = $(document.documentElement);
        $('html').addClass('australis');

        // if we're on australis and there's no hash tag, show the choice modal
        if (hash.indexOf("#") === -1) {
            $choice_modal.modal();
        }
    } else {
        $('html').addClass('non-australis');
    }

    if (hash.indexOf("choice") != -1) {
        // if #choice is in the URL, show the choice modal
        $choice_modal.modal();
    } else if (hash.indexOf("video") != -1) {
        // if #video is in the URL, show the video modal
        $( '#video-modal' ).modal();
        insertVideo();
    } else if (hash.indexOf("number") != -1) {
        // if #number is in the URL, show the number modal
        $( '#number-modal' ).modal();
    } else if (hash.indexOf("stats") != -1) {
        // if #number is in the URL, show the number modal
        $( 'body' ).addClass('stats-panel-open');
        openStatsPanel();
    }

    $( '.stats-panel-tab' ).click(function() {
        $( 'body' ).toggleClass( "stats-panel-open" );
        openStatsPanel();
    });

    // turn on fading for choice modal after initial load so it fades
    // on subsequent open/closes, but not the first time
    $choice_modal.addClass('fade');

    // "Share the map" popopver
    $('.popover-markup > .trigger').popover({
        html : true,
        title: function() {
          return $(this).parent().find('.head').html();
        },
        content: function() {
          return $(this).parent().find('.content').html();
        },
        container: 'body'
    });

    // Close popover on click outside of popover
    $('body').on('click', function (e) {
        $('[data-toggle="popover"]').each(function () {
            //the 'is' for buttons that trigger popups
            //the 'has' for icons within a button that triggers a popup
            if (!$(this).is(e.target) &&
                $(this).has(e.target).length === 0 &&
                $('.popover').has(e.target).length === 0) {
                $(this).popover('hide');
            }
        });
    });

    $choices.click(function() {
        $choices.removeClass('selected');
        $(this).addClass('selected');
        $('.choices').addClass('in-progress');
        showShareButtons();
    });

    function openShareWindow(href) {
        $('.popover-markup  .trigger').popover('hide');
        window.open(href, '_blank', "height=420,width=550");
    }

    function shareChoice(choice) {
        var url = $choice_modal.data('share-url');
        if (url) {
            $.post(url, { 'issue': choice });
        }
    }

    // Open .share-window links in a new window, and close any popovers
    $(document).on('click', '.share-window', function(event) {
        event.preventDefault();
        openShareWindow(this.href);
    });

    $('.modal-footer .share-twitter').click(function(e) {
        var $selected = $('.choices .selected');
        if ($selected.length) {
            openShareWindow($selected.data('twitter'));
            openInterstitialModal($selected.data('choice'));
            shareChoice($selected.data('choice'));
        }
    });

    $('.modal-footer .share-facebook').click(function(e) {
        var $selected = $('.choices .selected');
        if ($selected.length) {
            openShareWindow($selected.data('facebook'));
            openInterstitialModal($selected.data('choice'));
            shareChoice($selected.data('choice'));
        }
    });

    $('.choice-footnotes .share-local').click(function(e) {
        var $selected = $('.choices .selected');
        if ($selected.length) {
            openInterstitialModal($selected.data('choice'));
            shareChoice($selected.data('choice'));
        }
    });

    // Insert YouTube video into #video modal
    function insertVideo(autoplay) {
        if (autoplay) {
            autoplay = '1';
        } else {
            autoplay = '0';
        }
        var width = 853;
        var height = 480;
        var id = 'WB98kYqQt9c';
        $('#video-modal .modal-body').html('<iframe width="' + width + '" height="' +
            height + '" src="//www.youtube-nocookie.com/embed/' +
            id + '?autoplay=' + autoplay + '&' +
            '" frameborder="0" allowfullscreen></iframe>')
    }

    $('#video-modal').on('show.bs.modal', function (e) {
        // Insert YouTube player when video modal is opened
        insertVideo(true);
    });

    $('#video-modal').on('hidden.bs.modal', function (e) {
        // Stop YouTube player when video modal is closed
        $('#video-modal .modal-body').html('');
    });

});
<|endoftext|>


<commit_before>FLOW.SurveyGroup.FIXTURES = [{
	id:1,
	keyId: 1,
	code: 'Urban sanitation surveys'
}, {
	id:2,
	keyId: 2,
	code: 'Elise Surveys'
}, {
	id:3,
	keyId: 3,
	code: 'Test Survey group'
},{
	id:4,
	keyId: 4,
	code: 'Upande - SNVVERMIS'
},{
	id:5,
	keyId: 5,
	code: 'Akvo test surveys'
}];

FLOW.Survey.FIXTURES = [{
	id:1,
	keyId: 1,
	displayName: 'Water point survey',
	name:'Water point survey',
	surveyGroupId: 1
}, {
	id:2,
	keyId: 2,
	displayName: 'Sanitation survey',
	name:'Sanitation survey',
	surveyGroupId: 1
}, {
	id:3,
	keyId: 3,
	displayName: 'Baseline WASH',
	name:'Baseline WASH',
	surveyGroupId: 1
}, {
	id:4,
	keyId: 4,
	displayName: 'Akvo RSR update',
	name:'Akvo RSR update',
	surveyGroupId: 1
},
{
	id:5,
	keyId: 5,
	displayName: 'Akvo update',
	name:'Akvo update',
	surveyGroupId: 1
},
{
	id:6,
	keyId: 6,
	displayName: 'Loics survey',
	name:'Loics survey',
	surveyGroupId: 1
},
{
	id:7,
	keyId: 7,
	displayName: 'Farmer survey',
	name:'Farmer survey',
	surveyGroupId: 1
},
{
	id:8,
	keyId: 8,
	displayName: 'Rabbit',
	name:'Rabbit',
	surveyGroupId: 1
},
{
	id:9,
	keyId: 9,
	displayName: 'Rabbit II',
	name:'Rabbit II',
	surveyGroupId: 1
}];

FLOW.QuestionGroup.FIXTURES = [{
	id:1,
	keyId: 1,
	surveyId:1,
	order:1,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu. ",
	name: 'Location',
	displayName: 'Location'

}, {
	id:2,
	keyId: 2,
	surveyId:1,
	order:2,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Occupation',
	displayName: 'Occupation'

}, {
	id:3,
	keyId: 3,
	surveyId:1,
	order:3,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Water system',
	displayName: 'Water system'

}, {
	id:4,
	keyId: 4,
	surveyId:1,
	order:4,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Sanitation system',
	displayName: 'Sanitation system'

},
{
	id:5,
	keyId: 5,
	surveyId:2,
	order:5,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Something else',
	displayName: 'Something else'

}

];

FLOW.Question.FIXTURES = [{
	id:1,
	keyId: 1,
	text: 'What is the name of the community?',
	displayName: 'What is the name of the community?',
	mandatory: false,
	order:1,
	questionTypeString:'freeText',
	questionSetId: 1
}, {
	id:2,
	keyId: 2,
	text: 'What is your occupation?',
	displayName: 'What is your occupation?',
	mandatory: false,
	order:2,
	questionTypeString:'option',
	questionSetId: 1
}, {
	id:3,
	keyId: 3,
	text: 'How much children do you have?',
	displayName: 'How much children do you have?',
	mandatory: false,
	order:3,
	questionTypeString:'number',
	questionSetId: 1
}, {
	id:4,
	keyId: 4,
	text: 'Please take a geolocation',
	displayName: 'Please take a geolocation',
	mandatory: false,
	order:4,
	questionTypeString:'geoLoc',
	questionSetId: 1
},{
	id:5,
	keyId: 5,
	text: 'Please take a picture',
	displayName: 'Please take a picture',
	mandatory: false,
	order:5,
	questionTypeString:'photo',
	questionSetId: 1
},	{
	id:6,
	keyId: 6,
	text: 'Please make a video',
	displayName: 'Please make a video',
	questionTypeString:'video',
	order:6,
	mandatory: false,
	questionSetId: 1
},	{
	id:7,
	keyId: 7,
	text: 'What is the date today?',
	displayName: 'What is the date today?',
	questionTypeString:'date',
	order:7,
	mandatory: false,
	questionSetId: 1
}];

FLOW.QuestionOption.FIXTURES = [{
	id:1,
	keyId: 1,
	text: 'teacher',
	questionId: 1
}, {
	id:2,
	keyId: 2,
	text: 'cook',
	questionId: 1
},{
	id:3,
	keyId: 3,
	text: 'minister',
	questionId: 1
},{
	id:4,
	keyId: 4,
	text: 'programmer',
	questionId: 1
}];

FLOW.DeviceGroup.FIXTURES = [
{
	id:1,
	displayName:'Malawi',
	code:'malawi'
},{
	id:2,
	displayName:'Bolivia',
	code:'bolivia'
}
];

FLOW.Device.FIXTURES = [{
	id:1,
	keyId:1,
	phoneNumber:"3f:d4:8f:2a:8c:9f",
	deviceIdentifier:"Keri phone 1",
	deviceGroup:"WFP general",
	lastUpdate:"21 May 2012 20:30:00",
	lastLocationBeaconTime:"22 May 2012 20:30:00",
	lastKnownLat:23.132132321,
	lastKnownLong:12.23232332
}, {
	id:2,
	keyId:2,
	phoneNumber:"2a:8c:9f:3f:d4:8f",
	deviceIdentifier:" Keri phone 2",
	deviceGroup:"WFP general",
	lastUpdate:"21 Apr 2012 20:30:00",
	lastLocationBeaconTime:"27 Feb 2012 20:30:00",
	lastKnownLat:43.33434343,
	lastKnownLong:-5.32332343
}, {
	id:3,
	keyId:3,
	phoneNumber:"31648492710",
	deviceIdentifier:"Marks phone",
	deviceGroup:"WFP general",
	lastUpdate:"01 Sep 2012 20:30:00",
	lastLocationBeaconTime:"12 Aug 2012 20:30:00",
	lastKnownLat:34.222334234,
	lastKnownLong:-7.44343434
}, {
	id:4,
	keyId:4,
	phoneNumber:"34029392833",
	deviceIdentifier:"WFP colombia-1",
	deviceGroup:"Colombia",
	lastUpdate:"21 Aug 2012 20:30:00",
	lastLocationBeaconTime:"04 Jan 2012 20:30:00",
	lastKnownLat:2.334343434,
	lastKnownLong:-23.33433432
}, {
	id:5,
	keyId:5,
	phoneNumber:"3f:d4:8f:8b:8c:3e",
	deviceIdentifier:"WFP colombia 2",
	deviceGroup:"Colombia",
	lastUpdate:"12 Apr 2012 20:30:00",
	lastLocationBeaconTime:"31 Oct 2012 20:30:00",
	lastKnownLat:8.55454435,
	lastKnownLong:54.88399473
}, {
	id:6,
	keyId:6,
	phoneNumber:"2a:8c:9f:3f:d4:8f",
	deviceIdentifier:"WFP phone 3",
	deviceGroup:"Malawi",
	lastUpdate:"17 Jul 2012 20:30:00",
	lastLocationBeaconTime:"16 Jun 2012 20:30:00",
	lastKnownLat:23.988332,
	lastKnownLong:-64.88399483
}, {
	id:7,
	keyId:7,
	phoneNumber:"3403928293",
	deviceIdentifier:"WFP phone 4",
	deviceGroup:"Malawi",
	lastUpdate:"11 Dec 2012 20:30:00",
	lastLocationBeaconTime:"14 Nov 2012 20:30:00",
	lastKnownLat:23.3323432,
	lastKnownLong:9.88873633
}];

FLOW.SurveyedLocale.FIXTURES = [{
  description:  "Welkom in Amsterdam!",
  keyId:        1,
  latitude:     52.370216,
  longitude:    4.895168,
  typeMark:     "WATER_POINT"
}, {
  description:  "Welcome to London!",
  keyId:        2,
  latitude:     51.507335,
  longitude:    -0.127683,
  typeMark:     "WATER_POINT"
}, {
  description:  "Välkommen till Stockholm!",
  keyId:        3,
  latitude:     59.32893,
  longitude:    18.06491,
  typeMark:     "WATER_POINT"
}];
<commit_msg>change QuestionGroup fixtures from "name" to "code"<commit_after>FLOW.SurveyGroup.FIXTURES = [{
	id:1,
	keyId: 1,
	code: 'Urban sanitation surveys'
}, {
	id:2,
	keyId: 2,
	code: 'Elise Surveys'
}, {
	id:3,
	keyId: 3,
	code: 'Test Survey group'
},{
	id:4,
	keyId: 4,
	code: 'Upande - SNVVERMIS'
},{
	id:5,
	keyId: 5,
	code: 'Akvo test surveys'
}];

FLOW.Survey.FIXTURES = [{
	id:1,
	keyId: 1,
	displayName: 'Water point survey',
	name:'Water point survey',
	surveyGroupId: 1
}, {
	id:2,
	keyId: 2,
	displayName: 'Sanitation survey',
	name:'Sanitation survey',
	surveyGroupId: 1
}, {
	id:3,
	keyId: 3,
	displayName: 'Baseline WASH',
	name:'Baseline WASH',
	surveyGroupId: 1
}, {
	id:4,
	keyId: 4,
	displayName: 'Akvo RSR update',
	name:'Akvo RSR update',
	surveyGroupId: 1
},
{
	id:5,
	keyId: 5,
	displayName: 'Akvo update',
	name:'Akvo update',
	surveyGroupId: 1
},
{
	id:6,
	keyId: 6,
	displayName: 'Loics survey',
	name:'Loics survey',
	surveyGroupId: 1
},
{
	id:7,
	keyId: 7,
	displayName: 'Farmer survey',
	name:'Farmer survey',
	surveyGroupId: 1
},
{
	id:8,
	keyId: 8,
	displayName: 'Rabbit',
	name:'Rabbit',
	surveyGroupId: 1
},
{
	id:9,
	keyId: 9,
	displayName: 'Rabbit II',
	name:'Rabbit II',
	surveyGroupId: 1
}];

FLOW.QuestionGroup.FIXTURES = [{
	id:1,
	keyId: 1,
	surveyId:1,
	order:1,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu. ",
	code: 'Location',
	displayName: 'Location'

}, {
	id:2,
	keyId: 2,
	surveyId:1,
	order:2,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	code: 'Occupation',
	displayName: 'Occupation'

}, {
	id:3,
	keyId: 3,
	surveyId:1,
	order:3,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	code: 'Water system',
	displayName: 'Water system'

}, {
	id:4,
	keyId: 4,
	surveyId:1,
	order:4,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	code: 'Sanitation system',
	displayName: 'Sanitation system'

},
{
	id:5,
	keyId: 5,
	surveyId:2,
	order:5,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	code: 'Something else',
	displayName: 'Something else'

}

];

FLOW.Question.FIXTURES = [{
	id:1,
	keyId: 1,
	text: 'What is the name of the community?',
	displayName: 'What is the name of the community?',
	mandatory: false,
	order:1,
	questionTypeString:'freeText',
	questionSetId: 1
}, {
	id:2,
	keyId: 2,
	text: 'What is your occupation?',
	displayName: 'What is your occupation?',
	mandatory: false,
	order:2,
	questionTypeString:'option',
	questionSetId: 1
}, {
	id:3,
	keyId: 3,
	text: 'How much children do you have?',
	displayName: 'How much children do you have?',
	mandatory: false,
	order:3,
	questionTypeString:'number',
	questionSetId: 1
}, {
	id:4,
	keyId: 4,
	text: 'Please take a geolocation',
	displayName: 'Please take a geolocation',
	mandatory: false,
	order:4,
	questionTypeString:'geoLoc',
	questionSetId: 1
},{
	id:5,
	keyId: 5,
	text: 'Please take a picture',
	displayName: 'Please take a picture',
	mandatory: false,
	order:5,
	questionTypeString:'photo',
	questionSetId: 1
},	{
	id:6,
	keyId: 6,
	text: 'Please make a video',
	displayName: 'Please make a video',
	questionTypeString:'video',
	order:6,
	mandatory: false,
	questionSetId: 1
},	{
	id:7,
	keyId: 7,
	text: 'What is the date today?',
	displayName: 'What is the date today?',
	questionTypeString:'date',
	order:7,
	mandatory: false,
	questionSetId: 1
}];

FLOW.QuestionOption.FIXTURES = [{
	id:1,
	keyId: 1,
	text: 'teacher',
	questionId: 1
}, {
	id:2,
	keyId: 2,
	text: 'cook',
	questionId: 1
},{
	id:3,
	keyId: 3,
	text: 'minister',
	questionId: 1
},{
	id:4,
	keyId: 4,
	text: 'programmer',
	questionId: 1
}];

FLOW.DeviceGroup.FIXTURES = [
{
	id:1,
	displayName:'Malawi',
	code:'malawi'
},{
	id:2,
	displayName:'Bolivia',
	code:'bolivia'
}
];

FLOW.Device.FIXTURES = [{
	id:1,
	keyId:1,
	phoneNumber:"3f:d4:8f:2a:8c:9f",
	deviceIdentifier:"Keri phone 1",
	deviceGroup:"WFP general",
	lastUpdate:"21 May 2012 20:30:00",
	lastLocationBeaconTime:"22 May 2012 20:30:00",
	lastKnownLat:23.132132321,
	lastKnownLong:12.23232332
}, {
	id:2,
	keyId:2,
	phoneNumber:"2a:8c:9f:3f:d4:8f",
	deviceIdentifier:" Keri phone 2",
	deviceGroup:"WFP general",
	lastUpdate:"21 Apr 2012 20:30:00",
	lastLocationBeaconTime:"27 Feb 2012 20:30:00",
	lastKnownLat:43.33434343,
	lastKnownLong:-5.32332343
}, {
	id:3,
	keyId:3,
	phoneNumber:"31648492710",
	deviceIdentifier:"Marks phone",
	deviceGroup:"WFP general",
	lastUpdate:"01 Sep 2012 20:30:00",
	lastLocationBeaconTime:"12 Aug 2012 20:30:00",
	lastKnownLat:34.222334234,
	lastKnownLong:-7.44343434
}, {
	id:4,
	keyId:4,
	phoneNumber:"34029392833",
	deviceIdentifier:"WFP colombia-1",
	deviceGroup:"Colombia",
	lastUpdate:"21 Aug 2012 20:30:00",
	lastLocationBeaconTime:"04 Jan 2012 20:30:00",
	lastKnownLat:2.334343434,
	lastKnownLong:-23.33433432
}, {
	id:5,
	keyId:5,
	phoneNumber:"3f:d4:8f:8b:8c:3e",
	deviceIdentifier:"WFP colombia 2",
	deviceGroup:"Colombia",
	lastUpdate:"12 Apr 2012 20:30:00",
	lastLocationBeaconTime:"31 Oct 2012 20:30:00",
	lastKnownLat:8.55454435,
	lastKnownLong:54.88399473
}, {
	id:6,
	keyId:6,
	phoneNumber:"2a:8c:9f:3f:d4:8f",
	deviceIdentifier:"WFP phone 3",
	deviceGroup:"Malawi",
	lastUpdate:"17 Jul 2012 20:30:00",
	lastLocationBeaconTime:"16 Jun 2012 20:30:00",
	lastKnownLat:23.988332,
	lastKnownLong:-64.88399483
}, {
	id:7,
	keyId:7,
	phoneNumber:"3403928293",
	deviceIdentifier:"WFP phone 4",
	deviceGroup:"Malawi",
	lastUpdate:"11 Dec 2012 20:30:00",
	lastLocationBeaconTime:"14 Nov 2012 20:30:00",
	lastKnownLat:23.3323432,
	lastKnownLong:9.88873633
}];

FLOW.SurveyedLocale.FIXTURES = [{
  description:  "Welkom in Amsterdam!",
  keyId:        1,
  latitude:     52.370216,
  longitude:    4.895168,
  typeMark:     "WATER_POINT"
}, {
  description:  "Welcome to London!",
  keyId:        2,
  latitude:     51.507335,
  longitude:    -0.127683,
  typeMark:     "WATER_POINT"
}, {
  description:  "Välkommen till Stockholm!",
  keyId:        3,
  latitude:     59.32893,
  longitude:    18.06491,
  typeMark:     "WATER_POINT"
}];
<|endoftext|>


<commit_before>// Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';

Accounts.ui.config({
    forceEmailLowercase: true,
    forceUsernameLowercase: true,
    requestPermissions: {},
    extraSignupFields: [{
        fieldName: 'username',
        fieldLabel: 'Username',
        inputType: 'text',
        visible: true,
        validate: function(value, errorFunction) {
          if (!value) {
            errorFunction("Please write your username");
            return false;
          } else {
            return true;
          }
        }
    }, {
        fieldName: 'first-name',
        fieldLabel: 'First name',
        inputType: 'text',
        visible: true,
        validate: function(value, errorFunction) {
          if (!value) {
            errorFunction("Please write your first name");
            return false;
          } else {
            return true;
          }
        }
    }, {
        fieldName: 'last-name',
        fieldLabel: 'Last name',
        inputType: 'text',
        visible: true,
    }, {
        fieldName: 'terms',
        fieldLabel: 'I accept the terms and conditions *',
        inputType: 'checkbox',
        visible: true,
        saveToProfile: false,
        validate: function(value, errorFunction) {
            if (value) {
                return true;
            } else {
                errorFunction('You must accept the terms and conditions.');
                return false;
            }
        }
    }]
});
<commit_msg>Fix config.js<commit_after>// Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';

Accounts.ui.config({
    forceEmailLowercase: true,
    forceUsernameLowercase: true,
    requestPermissions: {},
    extraSignupFields: [{
        fieldName: 'username',
        fieldLabel: 'Username',
        inputType: 'text',
        visible: true,
        validate: function(value, errorFunction) {
          if (!value) {
            errorFunction("Please write your username");
            return false;
          } else {
            return true;
          }
        }
    }, {
        fieldName: 'first-name',
        fieldLabel: 'First name',
        inputType: 'text',
        visible: true,
        validate: function(value, errorFunction) {
          if (!value) {
            errorFunction("Please write your first name");
            return false;
          } else {
            return true;
          }
        }
    }, {
        fieldName: 'last-name',
        fieldLabel: 'Last name',
        inputType: 'text',
        visible: true,
    }, {
        fieldName: 'terms',
        fieldLabel: 'I accept the terms and conditions *',
        inputType: 'checkbox',
        visible: true,
        saveToProfile: true,
        validate: function(value, errorFunction) {
            if (value) {
                return true;
            } else {
                errorFunction('You must accept the terms and conditions.');
                return false;
            }
        }
    }]
});
<|endoftext|>


<commit_before>/**
 * Pc2bimController
 */

var PC2BIM = require('../../bindings/pc2bim');

function startExtraction(filename, duraarkStoragePath) {
  var pc2bim = new PC2BIM(duraarkStoragePath);
  return pc2bim.extract(filename);
}

/**
 * @apiDefine ExtractionSuccess
 * @apiSuccess (Response) {String} input Location of the input file.
 * @apiSuccess (Response) {String} output Location of the reconstructed output file.
 * @apiSuccess (Response) {String} error 'null' if extraction was successfull, otherwise contains error message.
 */

module.exports = {
  /**
   * @api {post} /pc2bim/ Extract BIM model
   * @apiVersion 0.8.0
   * @apiName PostPc2bim
   * @apiGroup PC2BIM
   * @apiPermission none
   *
   * @apiDescription Schedule the extraction of a BIM model as IFC file from a given E57 point cloud file.
   *
   * @apiParam (File) {String} path Location of the File as provided by the [DURAARK Sessions API](http://data.duraark.eu/services/api/sessions/).
   *
   * @apiUse ExtractionSuccess
   *
   * @apiSuccessExample Success-Response:
   *     HTTP/1.1 200 OK
   *     {
   *        "input": "/duraark-storage/files/Nygade_Scan1001.e57",
   *        "output": "/duraark-storage/files/Nygade_Scan1001_RECONSTRUCTED.ifc",
   *        "error": null
   *      }
   */
  create: function(req, res, next) {
    var inputFile = req.param('inputFile'),
      duraarkStoragePath = process.env.DURAARK_STORAGE_PATH || '/duraark-storage';

    // console.log('duraarkStoragePath: ' + duraarkStoragePath);

    console.log('POST /pc2bim: Scheduled conversion from ' + inputFile);

    res.setTimeout(0);

    Pc2bim.findOne({
      "where": {
        "inputFile": {
          "equals": inputFile
        }
      }
    }).then(function(pc2bim) {
      // console.log('pc2bim: ' + JSON.stringify(pc2bim, null, 4));

      if (!pc2bim) {
        Pc2bim.create({
          inputFile: inputFile,
          outputFile: null,
          status: "pending"
        }).then(function(pc2bim) {
          startExtraction(inputFile, duraarkStoragePath).then(function(result) {
            console.log('Extraction finished: ' + JSON.stringify(result, null, 4));
            pc2bim.outputFile = result.outputFile;
            pc2bim.status = "finished";
            pc2bim.save().then(function(pc2bimRecord) {
              res.send(pc2bimRecord).status(200);
            });
          }).catch(function(err) {
            console.log('[Pc2bimController] Error:\n' + err);

            if (err === "") {
              err = "'pc2bim' could not start. Are you sure that your CPU is from Intel? AMD is not supported at the moment."
            }
            pc2bim.status = "error";
            pc2bim.errorText = err;

            pc2bim.save().then(function() {
              res.send({
                inputFile: inputFile,
                outputFile: null,
                status: "error",
                errorText: err
              }).status(200); // NOTE: we send 200 here, as an extraction error is a valid result.
            });
          });

        });
      } else {
        if (pc2bim.status === "finished") {
          console.log('Returning cached result: ' + JSON.stringify(pc2bim, null, 4));
          res.send(pc2bim).status(201);
        }

        if (pc2bim.status === "pending") {
          console.log('Extraction pending: ' + JSON.stringify(pc2bim, null, 4));
          res.send(pc2bim).status(200);
        }

        if (pc2bim.status === "error") {
          console.log('Extraction error: ' + JSON.stringify(pc2bim, null, 4));
          res.send(pc2bim).status(200);
        }
      }
    }).catch(function(err) {
      console.log('[PC2BIMController] Error: ' + err);
    });
  }
}
<commit_msg>added 'restart' functionality<commit_after>/**
 * Pc2bimController
 */

var PC2BIM = require('../../bindings/pc2bim');

function pc2bimRun(filename, duraarkStoragePath) {
  var pc2bim = new PC2BIM(duraarkStoragePath);
  return pc2bim.extract(filename);
}

function startExtraction(config) {
  var runState = config.runState,
    res = config.res,
    inputFile = config.inputFile;

  pc2bimRun(config.inputFile, config.duraarkStoragePath).then(function(result) {
    console.log('Extraction finished: ' + JSON.stringify(result, null, 4));

    runState.outputFile = result.outputFile;
    runState.status = "finished";
    runState.save().then(function(pc2bimRecord) {
      res.send(pc2bimRecord).status(200);
    });
  }).catch(function(err) {
    console.log('[Pc2bimController] Error:\n' + err);

    if (err === "") {
      err = "'pc2bim' could not start. Are you sure that your CPU is from Intel? AMD is not supported at the moment."
    }
    runState.status = "error";
    runState.errorText = err;

    runState.save().then(function() {
      res.send({
        inputFile: inputFile,
        outputFile: null,
        status: "error",
        errorText: err
      }).status(200); // NOTE: we send 200 here, as an extraction error is a valid result.
    });
  });
}

/**
 * @apiDefine ExtractionSuccess
 * @apiSuccess (Response) {String} input Location of the input file.
 * @apiSuccess (Response) {String} output Location of the reconstructed output file.
 * @apiSuccess (Response) {String} error 'null' if extraction was successfull, otherwise contains error message.
 */

module.exports = {
  /**
   * @api {post} /pc2bim/ Extract BIM model
   * @apiVersion 0.8.0
   * @apiName PostPc2bim
   * @apiGroup PC2BIM
   * @apiPermission none
   *
   * @apiDescription Schedule the extraction of a BIM model as IFC file from a given E57 point cloud file.
   *
   * @apiParam (File) {String} path Location of the File as provided by the [DURAARK Sessions API](http://data.duraark.eu/services/api/sessions/).
   *
   * @apiUse ExtractionSuccess
   *
   * @apiSuccessExample Success-Response:
   *     HTTP/1.1 200 OK
   *     {
   *        "input": "/duraark-storage/files/Nygade_Scan1001.e57",
   *        "output": "/duraark-storage/files/Nygade_Scan1001_RECONSTRUCTED.ifc",
   *        "error": null
   *      }
   */
  create: function(req, res, next) {
    var inputFile = req.param('inputFile'),
      restart = req.param('restart'),
      duraarkStoragePath = process.env.DURAARK_STORAGE_PATH || '/duraark-storage';

    // console.log('duraarkStoragePath: ' + duraarkStoragePath);

    console.log('POST /pc2bim: Scheduled conversion from ' + inputFile);

    res.setTimeout(0);

    Pc2bim.findOne({
      "where": {
        "inputFile": {
          "equals": inputFile
        }
      }
    }).then(function(runState) {
      // console.log('runState: ' + JSON.stringify(runState, null, 4));

      if (!runState) {
        Pc2bim.create({
          inputFile: inputFile,
          outputFile: null,
          status: "pending"
        }).then(function(runState) {
          startExtraction({
            runState: runState,
            inputFile: inputFile,
            duraarkStoragePath: duraarkStoragePath,
            res: res
          });
        });
      } else {
        if (runState.status === "finished") {
          console.log('Returning cached result: ' + JSON.stringify(runState, null, 4));
          res.send(runState).status(201);
        }

        if (runState.status === "pending") {
          console.log('Extraction pending: ' + JSON.stringify(runState, null, 4));
          res.send(runState).status(200);
        }

        if (runState.status === "error") {
          console.log('Extraction error: ' + JSON.stringify(runState, null, 4));
          if (restart) {
            startExtraction({
              runState: runState,
              inputFile: inputFile,
              duraarkStoragePath: duraarkStoragePath,
              res: res
            });
          } else {
            res.send(runState).status(200);
          }
        }
      }
    }).catch(function(err) {
      console.log('[PC2BIMController] Error: ' + err);
    });
  }
}
<|endoftext|>


<commit_before>const {app, BrowserWindow, protocol, remote, Menu } = require('electron');
const path = require('path');
const url = require('url');
const fs = require('fs');
const mime = require('mime-types');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow () {

    // TODO - Use the altair protocol to replace the file protocol
    protocol.registerBufferProtocol('altair', (request, callback) => {
        const url = request.url.substr(7);
        fs.readFile(path.normalize(`${url}`), 'utf8', function (err, data) {
            if (err) {
                return console.log('Error loading file to buffer.', err);
            }

            // Load the data from the file into a buffer and pass it to the callback
            // Using the mime package to get the mime type for the file, based on the file name
            callback({ mimeType: mime.lookup(url), data: new Buffer(data) });
            // console.log(data);
        });
        // callback({path: path.normalize(`${__dirname}/${url}`)})
    }, (error) => {
        if (error) console.error('Failed to register protocol')
    });

    // Create the browser window.
    win = new BrowserWindow({
      width: 1280,
      height: 800,
      titleBarStyle: 'hidden-inset',
      fullscreen: true
    });

    // Populate the application menu
    createMenu();

    // and load the index.html of the app.
    win.loadURL(url.format({
        pathname: path.join(__dirname, '../dist/index.html'),
        protocol: 'altair:',
        slashes: true
    }));
    // win.loadURL('altair://' + __dirname + '/../dist/index.html')

    // Open the DevTools.
    // win.webContents.openDevTools()

    // Prevent the app from navigating away from the app
    win.webContents.on('will-navigate', (e, url) => e.preventDefault());

    // Emitted when the window is closed.
    win.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        win = null;
    })
}

function createMenu () {
  const template = [
    {
      label: "Edit",
      submenu: [
        { role: "undo" },
        { role: "redo" },
        { type: "separator" },
        { role: "cut" },
        { role: "copy" },
        { role: "paste" },
        { role: "pasteandmatchstyle" },
        { role: "delete" },
        { role: "selectall" }
      ]
    },
    {
      label: "View",
      submenu: [
        { role: "reload" },
        { role: "forcereload" },
        { role: "toggledevtools" },
        { type: "separator" },
        { role: "togglefullscreen" }
      ]
    },
    {
      role: "window",
      submenu: [{ role: "minimize" }, { role: "close" }]
    }
  ];

  if (process.platform === "darwin") {
    template.unshift({
      label: app.getName(),
      submenu: [
        { role: "about" },
        { type: "separator" },
        { role: "services", submenu: [] },
        { type: "separator" },
        { role: "hide" },
        { role: "hideothers" },
        { role: "unhide" },
        { type: "separator" },
        { role: "quit" }
      ]
    });

    // Edit menu
    template[1].submenu.push(
      { type: "separator" },
      {
        label: "Speech",
        submenu: [{ role: "startspeaking" }, { role: "stopspeaking" }]
      }
    );

    // Window menu
    template[3].submenu = [
      { role: "close" },
      { role: "minimize" },
      { type: "separator" },
      { role: "front" }
    ];
  }

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

protocol.registerStandardSchemes(['altair']);

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow()
    }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<commit_msg>Removed fullScreen option when creating browser window.<commit_after>const {app, BrowserWindow, protocol, remote, Menu } = require('electron');
const path = require('path');
const url = require('url');
const fs = require('fs');
const mime = require('mime-types');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow () {

    // TODO - Use the altair protocol to replace the file protocol
    protocol.registerBufferProtocol('altair', (request, callback) => {
        const url = request.url.substr(7);
        fs.readFile(path.normalize(`${url}`), 'utf8', function (err, data) {
            if (err) {
                return console.log('Error loading file to buffer.', err);
            }

            // Load the data from the file into a buffer and pass it to the callback
            // Using the mime package to get the mime type for the file, based on the file name
            callback({ mimeType: mime.lookup(url), data: new Buffer(data) });
            // console.log(data);
        });
        // callback({path: path.normalize(`${__dirname}/${url}`)})
    }, (error) => {
        if (error) console.error('Failed to register protocol')
    });

    // Create the browser window.
    win = new BrowserWindow({
      width: 1280,
      height: 800,
      titleBarStyle: 'hidden-inset'
    });

    // Populate the application menu
    createMenu();

    // and load the index.html of the app.
    win.loadURL(url.format({
        pathname: path.join(__dirname, '../dist/index.html'),
        protocol: 'altair:',
        slashes: true
    }));
    // win.loadURL('altair://' + __dirname + '/../dist/index.html')

    // Open the DevTools.
    // win.webContents.openDevTools()

    // Prevent the app from navigating away from the app
    win.webContents.on('will-navigate', (e, url) => e.preventDefault());

    // Emitted when the window is closed.
    win.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        win = null;
    })
}

function createMenu () {
  const template = [
    {
      label: "Edit",
      submenu: [
        { role: "undo" },
        { role: "redo" },
        { type: "separator" },
        { role: "cut" },
        { role: "copy" },
        { role: "paste" },
        { role: "pasteandmatchstyle" },
        { role: "delete" },
        { role: "selectall" }
      ]
    },
    {
      label: "View",
      submenu: [
        { role: "reload" },
        { role: "forcereload" },
        { role: "toggledevtools" },
        { type: "separator" },
        { role: "togglefullscreen" }
      ]
    },
    {
      role: "window",
      submenu: [{ role: "minimize" }, { role: "close" }]
    }
  ];

  if (process.platform === "darwin") {
    template.unshift({
      label: app.getName(),
      submenu: [
        { role: "about" },
        { type: "separator" },
        { role: "services", submenu: [] },
        { type: "separator" },
        { role: "hide" },
        { role: "hideothers" },
        { role: "unhide" },
        { type: "separator" },
        { role: "quit" }
      ]
    });

    // Edit menu
    template[1].submenu.push(
      { type: "separator" },
      {
        label: "Speech",
        submenu: [{ role: "startspeaking" }, { role: "stopspeaking" }]
      }
    );

    // Window menu
    template[3].submenu = [
      { role: "close" },
      { role: "minimize" },
      { type: "separator" },
      { role: "front" }
    ];
  }

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

protocol.registerStandardSchemes(['altair']);

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow()
    }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery');
var ko = require('knockout');
var bootbox = require('bootbox');
var Raven = require('raven-js');

var ConnectedProject = function(data) {
    var self = this;
    self.title = data.title;
    self.id = data.id;
    self.urls = data.urls;
};

var ExternalAccount = function(data) {
    var self = this;
    self.name = data.display_name;
    self.id = data.id;
    self.profileUrl = data.profile_url;

    self.connectedNodes = ko.observableArray();

    ko.utils.arrayMap(data.nodes, function(item) {
        self.connectedNodes.push(new ConnectedProject(item));
    });

    self.deauthorizeNode = function(node) {
        var url = node.urls.deauthorize;
        var request = $.ajax({
            url: url,
            type: 'DELETE'
        });
        request.done(function(data) {
            self.connectedNodes.remove(node);
        });
        request.fail(function(xhr, status, error) {
            Raven.captureMessage('Error deauthorizing node: ' + node.id, {
                url: url, status: status, error: error
            });
        });
        return request;
    };
};

var OAuthAddonSettingsViewModel = function(name, displayName) {
    var self = this;
    self.name = name;
    self.properName = displayName;
    self.accounts = ko.observableArray();
    self.message = ko.observable('');
    self.messageClass = ko.observable('');

    self.setMessage = function(msg, cls) {
        self.message(msg);
        self.messageClass(cls || 'text-info');
    };

    self.connectAccount = function() {
        window.oauthComplete = function() {
            self.updateAccounts();
            self.setMessage('Add-on successfully authorized. To link this add-on to an OSF project, go to the settings page of the project, enable ' + self.properName + ', and choose content to connect.', '.text-success');
        };
        window.open('/oauth/connect/' + self.name + '/');
    };

    self.askDisconnect = function(account) {
        bootbox.confirm({
            title: 'Delete account?',
            message: '
' +
                'Are you sure you want to delete account ' +
                account.name + '?' +
                '
',
            callback: function(confirm) {
                if (confirm) {
                    self.disconnectAccount(account);
                }
            }
        });
    };

    self.disconnectAccount = function(account) {
        var url = '/api/v1/oauth/accounts/' + account.id + '/';
        var request = $.ajax({
            url: url,
            type: 'DELETE'
        });
        request.done(function(data) {
            self.updateAccounts();
        });
        request.fail(function(xhr, status, error) {
            Raven.captureMessage('Error while removing addon authorization for ' + account.id, {
                url: url, status: status, error: error
            });
        });
        return request;
    };

    self.updateAccounts = function() {
        var url = '/api/v1/settings/' + self.name + '/accounts/';
        var request = $.get(url);
        request.done(function(data) {
            self.accounts($.map(data.accounts, function(account) {
                return new ExternalAccount(account);
            }));
        });
        request.fail(function(xhr, status, error) {
            Raven.captureMessage('Error while updating addon account', {
                url: url, status: status, error: error
            });
        });
        return request;
    };
};

module.exports = {
    ConnectedProject: ConnectedProject,
    ExternalAccount: ExternalAccount,
    OAuthAddonSettingsViewModel: OAuthAddonSettingsViewModel
};
<commit_msg>Add confirmation modal to Zendeley auth revoking<commit_after>'use strict';

var $ = require('jquery');
var ko = require('knockout');
var bootbox = require('bootbox');
var Raven = require('raven-js');
var ADDON_NAMES = require('js/addonNames');

var ConnectedProject = function(data) {
    var self = this;
    self.title = data.title;
    self.id = data.id;
    self.urls = data.urls;
};

var ExternalAccount = function(data) {
    var self = this;
    self.name = data.display_name;
    self.id = data.id;
    self.profileUrl = data.profile_url;
    self.provider_name = data.provider_name;

    self.connectedNodes = ko.observableArray();

    ko.utils.arrayMap(data.nodes, function(item) {
        self.connectedNodes.push(new ConnectedProject(item));
    });

    self.deauthorizeNode = function(node) {
        bootbox.confirm({
            title: 'Remove addon?',
            message: 'Are you sure you want to remove the ' + ADDON_NAMES[self.provider_name] + ' authorization from this project?',
            callback: function (confirm) {
                if (confirm) {
                    var url = node.urls.deauthorize;
                    var request = $.ajax({
                        url: url,
                        type: 'DELETE'
                    });
                    request.done(function(data) {
                        self.connectedNodes.remove(node);
                    });
                    request.fail(function(xhr, status, error) {
                        Raven.captureMessage('Error deauthorizing node: ' + node.id, {
                            url: url, status: status, error: error
                        });
                    });
                    return request;
                }
            }
        });
    };
};

var OAuthAddonSettingsViewModel = function(name, displayName) {
    var self = this;
    self.name = name;
    self.properName = displayName;
    self.accounts = ko.observableArray();
    self.message = ko.observable('');
    self.messageClass = ko.observable('');

    self.setMessage = function(msg, cls) {
        self.message(msg);
        self.messageClass(cls || 'text-info');
    };

    self.connectAccount = function() {
        window.oauthComplete = function() {
            self.updateAccounts();
            self.setMessage('Add-on successfully authorized. To link this add-on to an OSF project, go to the settings page of the project, enable ' + self.properName + ', and choose content to connect.', '.text-success');
        };
        window.open('/oauth/connect/' + self.name + '/');
    };

    self.askDisconnect = function(account) {
        bootbox.confirm({
            title: 'Delete account?',
            message: '
' +
                'Are you sure you want to delete account ' +
                account.name + '?' +
                '
',
            callback: function(confirm) {
                if (confirm) {
                    self.disconnectAccount(account);
                }
            }
        });
    };

    self.disconnectAccount = function(account) {
        var url = '/api/v1/oauth/accounts/' + account.id + '/';
        var request = $.ajax({
            url: url,
            type: 'DELETE'
        });
        request.done(function(data) {
            self.updateAccounts();
        });
        request.fail(function(xhr, status, error) {
            Raven.captureMessage('Error while removing addon authorization for ' + account.id, {
                url: url, status: status, error: error
            });
        });
        return request;
    };

    self.updateAccounts = function() {
        var url = '/api/v1/settings/' + self.name + '/accounts/';
        var request = $.get(url);
        request.done(function(data) {
            self.accounts($.map(data.accounts, function(account) {
                return new ExternalAccount(account);
            }));
        });
        request.fail(function(xhr, status, error) {
            Raven.captureMessage('Error while updating addon account', {
                url: url, status: status, error: error
            });
        });
        return request;
    };
};

module.exports = {
    ConnectedProject: ConnectedProject,
    ExternalAccount: ExternalAccount,
    OAuthAddonSettingsViewModel: OAuthAddonSettingsViewModel
};
<|endoftext|>


<commit_before>const ganache = require("ganache-core");
const Web3 = require("web3");
const assert = require("assert");
const Reporter = require("truffle-reporters").migrationsV5;
const EventEmitter = require("events");

const Deployer = require("../index");
const utils = require("./helpers/utils");

describe.only("Deployer (sync)", function() {
  let owner;
  let options;
  let networkId;
  let deployer;
  let reporter;
  let output = "";
  let Example;
  let UsesExample;
  let IsLibrary;
  let UsesLibrary;

  const provider = ganache.provider({
    vmErrorsOnRPCResponse: false
  });

  const mockMigration = {
    emitter: new EventEmitter()
  };

  const web3 = new Web3(provider);

  beforeEach(async function() {
    networkId = await web3.eth.net.getId();
    const accounts = await web3.eth.getAccounts();

    owner = accounts[0];
    await utils.compile();

    Example = utils.getContract("Example", provider, networkId, owner);
    ExampleRevert = utils.getContract(
      "ExampleRevert",
      provider,
      networkId,
      owner
    );
    UsesExample = utils.getContract("UsesExample", provider, networkId, owner);
    UsesLibrary = utils.getContract("UsesLibrary", provider, networkId, owner);
    IsLibrary = utils.getContract("IsLibrary", provider, networkId, owner);
    Abstract = utils.getContract("Abstract", provider, networkId, owner);

    options = {
      contracts: [
        Example,
        ExampleRevert,
        UsesExample,
        IsLibrary,
        UsesLibrary,
        Abstract
      ],
      networks: {
        test: {
          // TODO:
        }
      },
      network: "test",
      network_id: networkId,
      provider: provider,
      logger: {
        log: val => {
          if (val) output += `${val}\n`;
        },
        error: val => {
          if (val) output += `${val}\n`;
        }
      }
    };
    deployer = new Deployer(options);
    reporter = new Reporter();
    reporter.setDeployer(deployer);
    reporter.setMigration(mockMigration);
    reporter.listen();
  });

  afterEach(() => {
    output = "";
    utils.cleanUp();
    deployer.finish();
  });

  it("deploy()", async function() {
    const migrate = function() {
      deployer.deploy(Example);
    };

    migrate();

    await deployer.start();

    assert(Example.address !== null);
    assert(Example.transactionHash !== null);

    const example = await Example.deployed();
    const id = await example.id();

    assert(id === "Example");
    assert(output.includes("Example"));
    assert(output.includes("Deploying"));
    assert(output.includes("transaction hash"));
    assert(output.includes("address"));
    assert(output.includes("gas used"));
  });

  it("deploy().then", async function() {
    function migrate() {
      deployer
        .deploy(Example)
        .then(() => deployer.deploy(UsesExample, Example.address));
    }

    migrate();
    await deployer.start();

    const example = await Example.deployed();
    const usesExample = await UsesExample.deployed();
    const exampleId = await example.id();
    const usesExampleId = await usesExample.id();
    const other = await usesExample.other();

    assert(Example.address !== null);
    assert(exampleId === "Example");
    assert(usesExampleId === "UsesExample");
    assert(other === Example.address);

    assert(output.includes("Replacing"));
    assert(output.includes("Deploying"));
    assert(output.includes("Example"));
    assert(output.includes("UsesExample"));
  });

  it("deployer.then", async function() {
    function migrate() {
      deployer.then(async function() {
        const example = await deployer.deploy(Example);
        await deployer.deploy(UsesExample, example.address);
      });
    }

    migrate();
    await deployer.start();

    const example = await Example.deployed();
    const usesExample = await UsesExample.deployed();
    const exampleId = await example.id();
    const usesExampleId = await usesExample.id();
    const other = await usesExample.other();

    assert(Example.address !== null);
    assert(exampleId === "Example");
    assert(usesExampleId === "UsesExample");
    assert(other === Example.address);

    assert(output.includes("Replacing"));
    assert(output.includes("Example"));
    assert(output.includes("UsesExample"));
  });

  it("deployer.link", async function() {
    const migrate = function() {
      deployer.deploy(IsLibrary);
      deployer.link(IsLibrary, UsesLibrary);
      deployer.deploy(UsesLibrary);
    };

    migrate();

    await deployer.start();

    assert(UsesLibrary.address !== null);
    assert(IsLibrary.address !== null);

    const usesLibrary = await UsesLibrary.deployed();
    await usesLibrary.fireIsLibraryEvent(5);
    await usesLibrary.fireUsesLibraryEvent(7);

    eventOptions = { fromBlock: 0, toBlock: "latest" };
    const events = await usesLibrary.getPastEvents("allEvents", eventOptions);

    assert(events[0].args.eventID.toNumber() === 5);
    assert(events[1].args.eventID.toNumber() === 7);

    assert(output.includes("Deploying"));
    assert(output.includes("Linking"));
    assert(output.includes("IsLibrary"));
    assert(output.includes("UsesLibrary"));
  });

  // There's a chain like this in the truffle-core solidity-tests
  it("deployer.deploy().then()", async function() {
    const migrate = function() {
      deployer
        .deploy(Example)
        .then(function() {
          return Example.deployed();
        })
        .then(function(instance) {
          return instance.id();
        })
        .then(function() {
          return deployer
            .deploy(UsesExample, utils.zeroAddress)
            .then(function() {
              return UsesExample.deployed();
            })
            .then(function(usesExample) {
              return usesExample.id();
            });
        });
    };
    migrate();

    await deployer.start();
    assert(output.includes("Example"));
    assert(output.includes("UsesExample"));
  });

  it.only("waits for confirmations", async function() {
    this.timeout(15000);
    const startBlock = await web3.eth.getBlockNumber();

    utils.startAutoMine(web3, 1500);

    const migrate = function() {
      deployer.deploy(IsLibrary);
      deployer.deploy(Example);
    };

    migrate();

    deployer.confirmations = 2;
    await deployer.start();

    utils.stopAutoMine();

    await IsLibrary.deployed();
    await Example.deployed();

    const libReceipt = await web3.eth.getTransactionReceipt(
      IsLibrary.transactionHash
    );
    const exampleReceipt = await web3.eth.getTransactionReceipt(
      Example.transactionHash
    );

    // The first confirmation is the block that accepts the tx. Then we wait two more.
    // Then Example is deployed in the consequent block.
    assert(libReceipt.blockNumber === startBlock + 1);
    assert(exampleReceipt.blockNumber === libReceipt.blockNumber + 3);

    deployer.confirmationsRequired = 0;
  });

  it("emits block events while waiting for a tx to mine", async function() {
    this.timeout(15000);
    await web3.eth.getBlockNumber();

    utils.startAutoMine(web3, 4000);

    const migrate = function() {
      deployer.then(async function() {
        await deployer._startBlockPolling(web3);
        await utils.waitMS(9000);
        deployer._startBlockPolling();
      });
    };

    migrate();
    await deployer.start();
    utils.stopAutoMine();

    // We used to test output here but the ora spinner doesn't use the logger
    // Keeping this test just to run the logic, make sure it's not crashing.
  });
});
<commit_msg>remove .only()s from tests<commit_after>const ganache = require("ganache-core");
const Web3 = require("web3");
const assert = require("assert");
const Reporter = require("truffle-reporters").migrationsV5;
const EventEmitter = require("events");

const Deployer = require("../index");
const utils = require("./helpers/utils");

describe("Deployer (sync)", function() {
  let owner;
  let options;
  let networkId;
  let deployer;
  let reporter;
  let output = "";
  let Example;
  let UsesExample;
  let IsLibrary;
  let UsesLibrary;

  const provider = ganache.provider({
    vmErrorsOnRPCResponse: false
  });

  const mockMigration = {
    emitter: new EventEmitter()
  };

  const web3 = new Web3(provider);

  beforeEach(async function() {
    networkId = await web3.eth.net.getId();
    const accounts = await web3.eth.getAccounts();

    owner = accounts[0];
    await utils.compile();

    Example = utils.getContract("Example", provider, networkId, owner);
    ExampleRevert = utils.getContract(
      "ExampleRevert",
      provider,
      networkId,
      owner
    );
    UsesExample = utils.getContract("UsesExample", provider, networkId, owner);
    UsesLibrary = utils.getContract("UsesLibrary", provider, networkId, owner);
    IsLibrary = utils.getContract("IsLibrary", provider, networkId, owner);
    Abstract = utils.getContract("Abstract", provider, networkId, owner);

    options = {
      contracts: [
        Example,
        ExampleRevert,
        UsesExample,
        IsLibrary,
        UsesLibrary,
        Abstract
      ],
      networks: {
        test: {
          // TODO:
        }
      },
      network: "test",
      network_id: networkId,
      provider: provider,
      logger: {
        log: val => {
          if (val) output += `${val}\n`;
        },
        error: val => {
          if (val) output += `${val}\n`;
        }
      }
    };
    deployer = new Deployer(options);
    reporter = new Reporter();
    reporter.setDeployer(deployer);
    reporter.setMigration(mockMigration);
    reporter.listen();
  });

  afterEach(() => {
    output = "";
    utils.cleanUp();
    deployer.finish();
  });

  it("deploy()", async function() {
    const migrate = function() {
      deployer.deploy(Example);
    };

    migrate();

    await deployer.start();

    assert(Example.address !== null);
    assert(Example.transactionHash !== null);

    const example = await Example.deployed();
    const id = await example.id();

    assert(id === "Example");
    assert(output.includes("Example"));
    assert(output.includes("Deploying"));
    assert(output.includes("transaction hash"));
    assert(output.includes("address"));
    assert(output.includes("gas used"));
  });

  it("deploy().then", async function() {
    function migrate() {
      deployer
        .deploy(Example)
        .then(() => deployer.deploy(UsesExample, Example.address));
    }

    migrate();
    await deployer.start();

    const example = await Example.deployed();
    const usesExample = await UsesExample.deployed();
    const exampleId = await example.id();
    const usesExampleId = await usesExample.id();
    const other = await usesExample.other();

    assert(Example.address !== null);
    assert(exampleId === "Example");
    assert(usesExampleId === "UsesExample");
    assert(other === Example.address);

    assert(output.includes("Replacing"));
    assert(output.includes("Deploying"));
    assert(output.includes("Example"));
    assert(output.includes("UsesExample"));
  });

  it("deployer.then", async function() {
    function migrate() {
      deployer.then(async function() {
        const example = await deployer.deploy(Example);
        await deployer.deploy(UsesExample, example.address);
      });
    }

    migrate();
    await deployer.start();

    const example = await Example.deployed();
    const usesExample = await UsesExample.deployed();
    const exampleId = await example.id();
    const usesExampleId = await usesExample.id();
    const other = await usesExample.other();

    assert(Example.address !== null);
    assert(exampleId === "Example");
    assert(usesExampleId === "UsesExample");
    assert(other === Example.address);

    assert(output.includes("Replacing"));
    assert(output.includes("Example"));
    assert(output.includes("UsesExample"));
  });

  it("deployer.link", async function() {
    const migrate = function() {
      deployer.deploy(IsLibrary);
      deployer.link(IsLibrary, UsesLibrary);
      deployer.deploy(UsesLibrary);
    };

    migrate();

    await deployer.start();

    assert(UsesLibrary.address !== null);
    assert(IsLibrary.address !== null);

    const usesLibrary = await UsesLibrary.deployed();
    await usesLibrary.fireIsLibraryEvent(5);
    await usesLibrary.fireUsesLibraryEvent(7);

    eventOptions = { fromBlock: 0, toBlock: "latest" };
    const events = await usesLibrary.getPastEvents("allEvents", eventOptions);

    assert(events[0].args.eventID.toNumber() === 5);
    assert(events[1].args.eventID.toNumber() === 7);

    assert(output.includes("Deploying"));
    assert(output.includes("Linking"));
    assert(output.includes("IsLibrary"));
    assert(output.includes("UsesLibrary"));
  });

  // There's a chain like this in the truffle-core solidity-tests
  it("deployer.deploy().then()", async function() {
    const migrate = function() {
      deployer
        .deploy(Example)
        .then(function() {
          return Example.deployed();
        })
        .then(function(instance) {
          return instance.id();
        })
        .then(function() {
          return deployer
            .deploy(UsesExample, utils.zeroAddress)
            .then(function() {
              return UsesExample.deployed();
            })
            .then(function(usesExample) {
              return usesExample.id();
            });
        });
    };
    migrate();

    await deployer.start();
    assert(output.includes("Example"));
    assert(output.includes("UsesExample"));
  });

  it("waits for confirmations", async function() {
    this.timeout(15000);
    const startBlock = await web3.eth.getBlockNumber();

    utils.startAutoMine(web3, 1500);

    const migrate = function() {
      deployer.deploy(IsLibrary);
      deployer.deploy(Example);
    };

    migrate();

    deployer.confirmations = 2;
    await deployer.start();

    utils.stopAutoMine();

    await IsLibrary.deployed();
    await Example.deployed();

    const libReceipt = await web3.eth.getTransactionReceipt(
      IsLibrary.transactionHash
    );
    const exampleReceipt = await web3.eth.getTransactionReceipt(
      Example.transactionHash
    );

    // The first confirmation is the block that accepts the tx. Then we wait two more.
    // Then Example is deployed in the consequent block.
    assert(libReceipt.blockNumber === startBlock + 1);
    assert(exampleReceipt.blockNumber === libReceipt.blockNumber + 3);

    deployer.confirmationsRequired = 0;
  });

  it("emits block events while waiting for a tx to mine", async function() {
    this.timeout(15000);
    await web3.eth.getBlockNumber();

    utils.startAutoMine(web3, 4000);

    const migrate = function() {
      deployer.then(async function() {
        await deployer._startBlockPolling(web3);
        await utils.waitMS(9000);
        deployer._startBlockPolling();
      });
    };

    migrate();
    await deployer.start();
    utils.stopAutoMine();

    // We used to test output here but the ora spinner doesn't use the logger
    // Keeping this test just to run the logic, make sure it's not crashing.
  });
});
<|endoftext|>


<commit_before>'use strict'

const {EventEmitter} = require('events')
const Fanfou = require('fanfou-sdk')
const retimer = require('retimer')

const {
  CONSUMER_KEY,
  CONSUMER_SECRET
} = require('../config')

class Streamer extends EventEmitter {
  constructor (tokens) {
    super()
    tokens = tokens || {}
    this.oauth_token = tokens.oauthToken
    this.oauth_token_secret = tokens.oauthTokenSecret
    this._init()
  }

  _init () {
    const ff = new Fanfou({
      auth_type: 'oauth',
      consumer_key: CONSUMER_KEY,
      consumer_secret: CONSUMER_SECRET,
      oauth_token: this.oauth_token,
      oauth_token_secret: this.oauth_token_secret
    })
    ff.get('/account/verify_credentials', {}, (err, res) => {
      if (err) console.log(err)
      else {
        this.id = res.id
        this.proto = ff.stream()
        this._reg()
        this.timer = retimer(() => {
          // this.stop()
        }, 604800)
      }
    })
  }

  _reg () {
    this.proto.on('connected', () => {
      console.log(this.id, 'connected')
      this.emit('connected')
    })

    this.proto.on('close', () => {
      console.log(this.id, 'close')
      this.emit('close')
    })

    this.proto.on('message', data => {
      if (data.is_mentioned && this.id !== data.source.id) {
        this.emit('mention', {
          by: data.mentioned_by,
          status: data.object
        })
      }

      if (data.is_replied && this.id !== data.source.id) {
        this.emit('reply', {
          by: data.replied_by,
          status: data.object
        })
      }
    })

    this.proto.on('fav', data => {
      if (data.action === 'create') {
        this.emit('add-fav', {
          by: data.source.name,
          status: data.object
        })
      }
      if (data.action === 'delete') {
        this.emit('del-fav', {
          by: data.source.name,
          status: data.object
        })
      }
    })

    this.proto.on('error', data => {
      console.log(this.id, 'error')
    })
  }

  renew () {
    if (!this.proto.is_streaming) this._init()
    this.timer.reschedule(604800)
  }

  stop () {
    this.proto.stop()
  }
}

module.exports = Streamer
<commit_msg>fix retimer<commit_after>'use strict'

const {EventEmitter} = require('events')
const Fanfou = require('fanfou-sdk')
const retimer = require('retimer')

const {
  CONSUMER_KEY,
  CONSUMER_SECRET
} = require('../config')

class Streamer extends EventEmitter {
  constructor (tokens) {
    super()
    tokens = tokens || {}
    this.is_stop = false
    this.oauth_token = tokens.oauthToken
    this.oauth_token_secret = tokens.oauthTokenSecret
    this._init()
  }

  _init () {
    const ff = new Fanfou({
      auth_type: 'oauth',
      consumer_key: CONSUMER_KEY,
      consumer_secret: CONSUMER_SECRET,
      oauth_token: this.oauth_token,
      oauth_token_secret: this.oauth_token_secret
    })
    ff.get('/account/verify_credentials', {}, (err, res) => {
      if (err) console.log(err)
      else {
        this.id = res.id
        this.proto = ff.stream()
        this._reg()
        this.stopTimer = retimer(() => {
          this.stop()
        }, 604800000)
        this.renewTimer = retimer(() => {
          this.renew()
        }, 10000)
      }
    })
  }

  _reg () {
    this.proto.on('connected', () => {
      console.log(this.id, 'connected')
      this.emit('connected')
    })

    this.proto.on('close', () => {
      console.log(this.id, 'close')
      this.emit('close')
    })

    this.proto.on('message', data => {
      if (data.is_mentioned && this.id !== data.source.id) {
        this.emit('mention', {
          by: data.mentioned_by,
          status: data.object
        })
      }

      if (data.is_replied && this.id !== data.source.id) {
        this.emit('reply', {
          by: data.replied_by,
          status: data.object
        })
      }
    })

    this.proto.on('fav', data => {
      if (data.action === 'create') {
        this.emit('add-fav', {
          by: data.source.name,
          status: data.object
        })
      }
      if (data.action === 'delete') {
        this.emit('del-fav', {
          by: data.source.name,
          status: data.object
        })
      }
    })

    this.proto.on('error', data => {
      console.log(this.id, 'error')
    })

    this.proto.on('close', data => {
      console.log(this.id, 'streaming closed')
    })
  }

  renew () {
    if (!this.proto.is_streaming && !this.is_stop) {
      this._init()
      this.renewTimer.reschedule(10000)
    }
    this.stopTimer.reschedule(604800000)
  }
  stop () {
    this.is_stop = true
    this.proto.stop()
  }
}

module.exports = Streamer
<|endoftext|>


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

/*global require, process, __dirname*/
require("systemjs")

var modules   = require("lively.modules")
var resource  = lively.resources.resource;
var parseArgs = require('minimist');
var glob      = require('glob');
var mochaEs6  = require("../mocha-es6.js")
var path      = require("path");
var fs        = require("fs");
var flatn     = require("flatn");
var dir       = process.cwd();
var mochaDir  = path.join(__dirname, "..");
var depDir    = path.join(dir, ".dependencies")
var step      = 1;
var args;

lively.lang.promise.chain([
  () => { // prep
    modules.System.trace = true
    cacheMocha(modules.System, "file://" + mochaDir);
    modules.unwrapModuleLoad();
    readProcessArgs();
  },
  () => setupFlatn(),
  () => runPreScript(),
  () => console.log(`${step++}. Looking for test files via globs ${args.files.join(", ")}`),
  () => findTestFiles(args.files),
  (files, state) => state.testFiles = files,
  () => console.log(`${step++}. Preparing lively.modules`),
  () => setupLivelyModulesTestSystem(),
  (_, state) => console.log(`${step++}. Running tests in\n  ${state.testFiles.join("\n  ")}`),
  (_, state) => mochaEs6.runTestFiles(state.testFiles, {package: "file://" + dir}),
  failureCount => process.exit(failureCount)
]).catch(err => {
  console.error(err.stack || err);
  process.exit(1);
})

function readProcessArgs() {
  args = parseArgs(process.argv.slice(2), {
    alias: {}
  });
  args.files = args._;
}

function runPreScript() {
  var scriptPath = args["pre-script"];
  if (!scriptPath) return;
  if (!path.isAbsolute(scriptPath))
    scriptPath = path.join(process.cwd(), scriptPath);
  console.log(`${step++}. Running pre-script ${scriptPath}`);
  return require(scriptPath)
}

function findTestFiles(files) {
  return Promise.resolve()
    .then(() => {
      if (!files || !files.length)
        throw new Error("No test files specfied!");
      return Promise.all(files.map(f =>
        new Promise((resolve, reject) =>
          glob(f, {nodir: true, cwd: dir}, (err, files) =>
            err ? reject(err) : resolve(files))))); })
    .then(allFiles => allFiles.reduce((all, files) => all.concat(files)))
    .then(files => files.map(f => "file://" + path.join(dir, f)))
}

function cacheMocha(System, mochaDirURL) {
  if (typeof System !== "undefined" && !System.get(mochaDirURL + "/mocha-es6.js")) {
    System.config({
      map: {
        "mocha-es6": mochaDirURL + "/index.js",
        "mocha": mochaDirURL + "/dist/mocha.js",
        "chai": mochaDirURL + "/dist/chai.js"
      }
    });
    System.set(mochaDirURL + "/node_modules/lively.modules/dist/lively.modules.js", System.newModule(modules));
    System.set(mochaDirURL + "/index.js", System.newModule(mochaEs6));
    System.set(mochaDirURL + "/mocha-es6.js", System.newModule(mochaEs6));
    System.set(mochaDirURL + "/dist/mocha.js", System.newModule(mochaEs6.mocha));
    System.set(mochaDirURL + "/dist/chai.js", System.newModule(mochaEs6.chai));
  }
}

function setupLivelyModulesTestSystem() {
  var baseURL = "file://" + dir,
      System = lively.modules.getSystem("system-for-test", {baseURL}),
      registry = System["__lively.modules__packageRegistry"] = new modules.PackageRegistry(System);
  registry.packageBaseDirs = ["file://" + depDir].map(resource);
  registry.devPackageDirs = [baseURL].map(resource);
  lively.modules.changeSystem(System, true);
  cacheMocha(System, "file://" + mochaDir);
  mochaEs6.installSystemInstantiateHook();
  // System.debug = true;
  return registry.update()
}

function setupFlatn() {
  // 1. env
  console.log("Preparing flatn environment");
  require("flatn/module-resolver.js");
  let flatnBinDir = path.join(require.resolve("flatn"), "../bin"),
      env = process.env;
  if (!env.PATH.includes(flatnBinDir)) {
    console.log(`Adding ${flatnBinDir} to PATH`);
    env.PATH = flatnBinDir + ":" + env.PATH;
  }
  if (!env.FLATN_DEV_PACKAGE_DIRS || !env.FLATN_DEV_PACKAGE_DIRS.includes(dir)) {
    console.log("Setting FLATN_DEV_PACKAGE_DIRS");
    let dirs = env.FLATN_DEV_PACKAGE_DIRS ? env.FLATN_DEV_PACKAGE_DIRS.split(":") : [];
    env.FLATN_DEV_PACKAGE_DIRS = [dir].concat(dirs).join(":");
  }
  if (env.FLATN_PACKAGE_COLLECTION_DIRS) {
    depDir = env.FLATN_PACKAGE_COLLECTION_DIRS.split(":")[0]
    console.log("Using existing FLATN_PACKAGE_COLLECTION_DIR " + depDir);
  } else {
    console.log("Setting FLATN_PACKAGE_COLLECTION_DIRS");
    env.FLATN_PACKAGE_COLLECTION_DIRS = [depDir].join(":");
  }

  return flatn.installDependenciesOfPackage(
    dir,
    depDir,
    flatn.buildPackageMap([depDir], [], [dir]),
    ["dependencies", "devDependencies"],
    true);
}
<commit_msg>use existing flatn env<commit_after>#! /usr/bin/env node

/*global require, process, __dirname*/
require("systemjs")

var modules   = require("lively.modules")
var resource  = lively.resources.resource;
var parseArgs = require('minimist');
var glob      = require('glob');
var mochaEs6  = require("../mocha-es6.js")
var path      = require("path");
var fs        = require("fs");
var flatn     = require("flatn");
var dir       = process.cwd();
var mochaDir  = path.join(__dirname, "..");
var depDir    = path.join(dir, ".dependencies")
var step      = 1;
var args;

lively.lang.promise.chain([
  () => { // prep
    modules.System.trace = true
    cacheMocha(modules.System, "file://" + mochaDir);
    modules.unwrapModuleLoad();
    readProcessArgs();
  },
  () => setupFlatn(),
  () => runPreScript(),
  () => console.log(`${step++}. Looking for test files via globs ${args.files.join(", ")}`),
  () => findTestFiles(args.files),
  (files, state) => state.testFiles = files,
  () => console.log(`${step++}. Preparing lively.modules`),
  () => setupLivelyModulesTestSystem(),
  (_, state) => console.log(`${step++}. Running tests in\n  ${state.testFiles.join("\n  ")}`),
  (_, state) => mochaEs6.runTestFiles(state.testFiles, {package: "file://" + dir}),
  failureCount => process.exit(failureCount)
]).catch(err => {
  console.error(err.stack || err);
  process.exit(1);
})

function readProcessArgs() {
  args = parseArgs(process.argv.slice(2), {
    alias: {}
  });
  args.files = args._;
}

function runPreScript() {
  var scriptPath = args["pre-script"];
  if (!scriptPath) return;
  if (!path.isAbsolute(scriptPath))
    scriptPath = path.join(process.cwd(), scriptPath);
  console.log(`${step++}. Running pre-script ${scriptPath}`);
  return require(scriptPath)
}

function findTestFiles(files) {
  return Promise.resolve()
    .then(() => {
      if (!files || !files.length)
        throw new Error("No test files specfied!");
      return Promise.all(files.map(f =>
        new Promise((resolve, reject) =>
          glob(f, {nodir: true, cwd: dir}, (err, files) =>
            err ? reject(err) : resolve(files))))); })
    .then(allFiles => allFiles.reduce((all, files) => all.concat(files)))
    .then(files => files.map(f => "file://" + path.join(dir, f)))
}

function cacheMocha(System, mochaDirURL) {
  if (typeof System !== "undefined" && !System.get(mochaDirURL + "/mocha-es6.js")) {
    System.config({
      map: {
        "mocha-es6": mochaDirURL + "/index.js",
        "mocha": mochaDirURL + "/dist/mocha.js",
        "chai": mochaDirURL + "/dist/chai.js"
      }
    });
    System.set(mochaDirURL + "/node_modules/lively.modules/dist/lively.modules.js", System.newModule(modules));
    System.set(mochaDirURL + "/index.js", System.newModule(mochaEs6));
    System.set(mochaDirURL + "/mocha-es6.js", System.newModule(mochaEs6));
    System.set(mochaDirURL + "/dist/mocha.js", System.newModule(mochaEs6.mocha));
    System.set(mochaDirURL + "/dist/chai.js", System.newModule(mochaEs6.chai));
  }
}

function setupLivelyModulesTestSystem() {
  var baseURL = "file://" + dir,
      System = lively.modules.getSystem("system-for-test", {baseURL}),
      registry = System["__lively.modules__packageRegistry"] = new modules.PackageRegistry(System),
      env = process.env;
  registry.packageBaseDirs = env.FLATN_PACKAGE_COLLECTION_DIRS.split(":").map(resourcify);
  registry.individualPackageDirs = (env.FLATN_PACKAGE_DIRS || "").split(":").map(resourcify);
  registry.devPackageDirs = env.FLATN_DEV_PACKAGE_DIRS.split(":").map(resourcify);
  lively.modules.changeSystem(System, true);
  cacheMocha(System, "file://" + mochaDir);
  mochaEs6.installSystemInstantiateHook();
  // System.debug = true;
  return registry.update();

  function resourcify(path) { return resource("file://" + path).asDirectory(); }
}

function setupFlatn() {
  // 1. env
  console.log("Preparing flatn environment");
  require("flatn/module-resolver.js");
  let flatnBinDir = path.join(require.resolve("flatn"), "../bin"),
      env = process.env;
  if (!env.PATH.includes(flatnBinDir)) {
    console.log(`Adding ${flatnBinDir} to PATH`);
    env.PATH = flatnBinDir + ":" + env.PATH;
  }
  if (!env.FLATN_DEV_PACKAGE_DIRS || !env.FLATN_DEV_PACKAGE_DIRS.includes(dir)) {
    console.log("Setting FLATN_DEV_PACKAGE_DIRS");
    let dirs = env.FLATN_DEV_PACKAGE_DIRS ? env.FLATN_DEV_PACKAGE_DIRS.split(":") : [];
    env.FLATN_DEV_PACKAGE_DIRS = [dir].concat(dirs).join(":");
  }
  if (env.FLATN_PACKAGE_COLLECTION_DIRS) {
    depDir = env.FLATN_PACKAGE_COLLECTION_DIRS.split(":")[0]
    console.log("Using existing FLATN_PACKAGE_COLLECTION_DIR " + depDir);
  } else {
    console.log("Setting FLATN_PACKAGE_COLLECTION_DIRS");
    env.FLATN_PACKAGE_COLLECTION_DIRS = [depDir].join(":");
  }

  let devPackageDirs = env.FLATN_DEV_PACKAGE_DIRS.split(":"),
      packageDirs = (env.FLATN_PACKAGE_DIRS || "").split(":"),
      packageCollectionDirs = env.FLATN_PACKAGE_COLLECTION_DIRS.split(":");

  return flatn.installDependenciesOfPackage(
    dir,
    depDir,
    flatn.buildPackageMap(packageCollectionDirs, packageDirs, devPackageDirs),
    ["dependencies", "devDependencies"],
    false/*verbose*/);
}
<|endoftext|>