<commit_before>(function ($) {
   'use strict';

    var igcFile = null;
    var barogramPlot = null;
    var altitudeConversionFactor = 1.0; // Conversion from metres to required units

    function positionDisplay(position)  {
        function toDegMins(degreevalue) {
            var wholedegrees= Math.floor(degreevalue);
            var minutevalue = (60*(degreevalue-wholedegrees)).toFixed(3);
            return wholedegrees + '\u00B0\u00A0'  + minutevalue  + '\u00B4';
        }

        var positionLatitude= toDegMins(Math.abs(position[0]));
        var positionLongitude=toDegMins(Math.abs(position[1]));
        if(position[0]  >  0)  {
            positionLatitude += "N";
        }
        else  {
            positionLatitude += "S";
        }
        if(position[1]  >  0)  {
            positionLongitude += "E";
        }
        else  {
            positionLongitude += "W";
        }
        return positionLatitude + ",   " + positionLongitude;
    }

    function pad(n) {
        return (n < 10) ? ("0" + n.toString()) : n.toString();
    }

    function plotBarogram() {
        var nPoints = igcFile.recordTime.length;
        var pressureBarogramData = [];
        var gpsBarogramData = [];
        var j;
        var timestamp;

        for (j = 0; j < nPoints; j++) {
            timestamp = igcFile.recordTime[j].getTime();
            pressureBarogramData.push([timestamp, igcFile.pressureAltitude[j] * altitudeConversionFactor]);
            gpsBarogramData.push([timestamp, igcFile.gpsAltitude[j] * altitudeConversionFactor]);
        }

        var baro = $.plot($('#barogram'), [{
            label: 'Pressure altitude',
            data: pressureBarogramData
        }, {
            label: 'GPS altitude',
            data: gpsBarogramData
        }], {
            axisLabels: {
                show: true
            },
            xaxis: {
                axisLabel: 'Time',
                tickFormatter: function (t, axis) {
                     return moment(t).format('HH:mm');
                },
                ticks: function (axis) {
                    var ticks = [];
                    var startMoment = moment(axis.min);
                    var endMoment = moment(axis.max);
                    var durationMinutes = endMoment.diff(startMoment, 'minutes');
                    var interval;
                    if (durationMinutes <= 10) {
                       interval = 1;
                    }
                    if (durationMinutes <= 50) {
                       interval = 5;
                    }
                    else if (durationMinutes <= 100) {
                       interval = 10;
                    }
                    else if (durationMinutes <= 150) {
                       interval = 15;
                    }
                    else if (durationMinutes <= 300) {
                       interval = 30;
                    }
                    else if (durationMinutes <= 600) {
                       interval = 60;
                    }
                    else {
                       interval = 120;
                    }

                    var tick = startMoment.clone();
                    tick.minutes(0).seconds(0);
                    while (tick < endMoment) {
                        if (tick > startMoment) {
                            ticks.push(tick.valueOf());
                        }
                        tick.add(interval, 'minutes');
                    }

                    return ticks;
                }
            },
            yaxis: {
                axisLabel: 'Altitude / ' + $('#altitudeUnits').val()
            },

            crosshair: {
                mode: 'xy'
            },

            grid: {
                clickable: true,
                autoHighlight: false
            }
        });

        return baro;
    }

    function updateTimeline (timeIndex, mapControl) {
        var currentPosition = igcFile.latLong[timeIndex];
        var positionText=positionDisplay(currentPosition);
        var unitName = $('#altitudeUnits').val();
        $('#timePositionDisplay').text(
            moment(igcFile.recordTime[timeIndex]).format('HH:mm:ss') + ': ' +
            (igcFile.pressureAltitude[timeIndex] * altitudeConversionFactor).toFixed(0) + ' ' +
            unitName + ' (barometric) / ' +
            (igcFile.gpsAltitude[timeIndex] * altitudeConversionFactor).toFixed(0) + ' ' +
            unitName + ' (GPS); ' +
            positionText
        );

        mapControl.setTimeMarker(timeIndex);

        barogramPlot.lockCrosshair({
           x: igcFile.recordTime[timeIndex].getTime(),
           y: igcFile.pressureAltitude[timeIndex] * altitudeConversionFactor
        });
    }

    function displayIgc(mapControl) {
        // Display the headers.
        var displayDate = moment(igcFile.recordTime[0]).format('LL');
        var headerTable = $('#headerInfo tbody');
        headerTable.html('')
                   .append(
                       $('

').append($('	').text('Date'))
                              .append($('	').text(displayDate))
                   );
        var headerName;
        var headerIndex;
        for (headerIndex = 0; headerIndex < igcFile.headers.length; headerIndex++) {
            headerTable.append(
                $('

').append($('	').text(igcFile.headers[headerIndex].name))
                              .append($('	').text(igcFile.headers[headerIndex].value))
            );
        }

        // Show the task declaration if it is present.

        if (igcFile.task.coordinates.length > 0) {
            //eliminate anything with empty start line coordinates
            if(igcFile.task.coordinates[0][0] !==0) {
                    $('#task').show();
                    var taskList = $('#task ul').first().html('');
                    var j;
                    //Now add TP numbers.  Change to unordered list
                    if(igcFile.task.takeoff.length > 0) {
                               taskList.append($('

').text("Takeoff: " + igcFile.task.takeoff));
                    }
                    for (j =0; j <igcFile.task.names.length; j++) {
                            switch(j)  {
                            case 0:
                                    taskList.append($('

').text("Start: " + igcFile.task.names[j]));
                                    break;
                            case ( igcFile.task.names.length-1):
                                    taskList.append($('

').text("Finish: " + igcFile.task.names[j]));
                                    break;
                            default:
                                    taskList.append($('

').text("TP" + (j).toString() + ": " + igcFile.task.names[j]));
                        }
                    }
                 if(igcFile.task.landing.length > 0) {
                        taskList.append($('

').text("Landing: : " + igcFile.task.landing));
                 }
                mapControl.addTask(igcFile.task.coordinates, igcFile.task.names);
                }
        }
        else {
            $('#task').hide();
        }

        // Reveal the map and graph. We have to do this before
        // setting the zoom level of the map or plotting the graph.
        $('#igcFileDisplay').show();

        mapControl.addTrack(igcFile.latLong);
        barogramPlot = plotBarogram(igcFile);

        $('#timeSlider').prop('max', igcFile.recordTime.length - 1);
        updateTimeline(0, mapControl);
    }

    $(document).ready(function () {
        var mapControl = createMapControl('map');

        var timeZoneSelect = $('#timeZoneSelect');
        $.each(moment.tz.names(), function(index, name) {
            timeZoneSelect.append(
                 $('<option></option>', { value: name }).text(name));
        });
        var timeZone = 'UTC'; // There is no easy way to get local time zone!
        timeZoneSelect.val(timeZone);
        moment.tz.setDefault(timeZone);

        timeZoneSelect.change(function () {
            moment.tz.setDefault($(this).val());
            if (igcFile !== null) {
                barogramPlot = plotBarogram();
                updateTimeline($('#timeSlider').val(), mapControl);
                $('#headerInfo td').first().text(moment(igcFile.recordTime[0]).format('LL'));
            }
        });

        $('#fileControl').change(function () {
            if (this.files.length > 0) {
                var reader = new FileReader();
                reader.onload = function(e)  {
                  try {
                      $('#errorMessage').text('');
                      mapControl.reset();
                      $('#timeSlider').val(0);

                      igcFile = parseIGC(this.result);
                      displayIgc(mapControl);
                  } catch (ex) {
                      if (ex instanceof IGCException) {
                          $('#errorMessage').text(ex.message);
                      }
                      else {
                          throw ex;
                      }
                  }
                };
                reader.readAsText(this.files[0]);
            }
        });

        $('#altitudeUnits').change(function (e, raisedProgrammatically) {
            var altitudeUnit = $(this).val();
            if (altitudeUnit === 'feet') {
                altitudeConversionFactor = 3.2808399;
            }
            else {
                altitudeConversionFactor = 1.0;
            }

            if (igcFile !== null) {
                barogramPlot = plotBarogram();
                updateTimeline($('#timeSlider').val(), mapControl);
            }

            if (window.localStorage && !raisedProgrammatically) {
                try {
                    localStorage.setItem("altitudeUnit", altitudeUnit);
                }
                catch (e) {
                    // If local storage permission is denied, ignore the error.
                }
            }
        });

        // We need to handle the 'change' event for IE, but
        // 'input' for Chrome and Firefox in order to update smoothly
        // as the range input is dragged.
        $('#timeSlider').on('input', function() {
          var t = parseInt($(this).val(), 10);
          updateTimeline(t, mapControl);
        });
        $('#timeSlider').on('change', function() {
           var t = parseInt($(this).val(), 10);
           updateTimeline(t, mapControl);
        });

        $('#timeBack').click(function() {
           var slider = $('#timeSlider');
           var curTime = parseInt(slider.val(), 10);
           curTime--;
           if(curTime < 0) {
                 curTime = 0;
           }
           slider.val(curTime);
           updateTimeline(curTime, mapControl);
        });

         $('#timeForward').click(function() {
           var slider = $('#timeSlider');
           var curTime = parseInt(slider.val(), 10);
           var maxval= slider.prop('max');
           curTime++;
           if(curTime >  maxval) {
                 curTime = maxval;
           }
           slider.val(curTime);
           updateTimeline(curTime, mapControl);
        });

         $('#barogram').on('plotclick', function (event, pos, item) {
             console.log('plot click');
             if (item) {
                 updateTimeline(item.dataIndex, mapControl);
                 $('#timeSlider').val(item.dataIndex);
             }
         });

         if (window.localStorage) {
             try {
                 var altitudeUnit = localStorage.getItem("altitudeUnit");
                 if (altitudeUnit) {
                     $('#altitudeUnits').val(altitudeUnit).trigger('change', true);
                 }
             }
             catch (e) {
                 // If permission is denied, ignore the error.
             }
         }
    });
}(jQuery));
<commit_msg>Remember selected time zone using local storage (feature #18).<commit_after>(function ($) {
   'use strict';

    var igcFile = null;
    var barogramPlot = null;
    var altitudeConversionFactor = 1.0; // Conversion from metres to required units

    function positionDisplay(position)  {
        function toDegMins(degreevalue) {
            var wholedegrees= Math.floor(degreevalue);
            var minutevalue = (60*(degreevalue-wholedegrees)).toFixed(3);
            return wholedegrees + '\u00B0\u00A0'  + minutevalue  + '\u00B4';
        }

        var positionLatitude= toDegMins(Math.abs(position[0]));
        var positionLongitude=toDegMins(Math.abs(position[1]));
        if(position[0]  >  0)  {
            positionLatitude += "N";
        }
        else  {
            positionLatitude += "S";
        }
        if(position[1]  >  0)  {
            positionLongitude += "E";
        }
        else  {
            positionLongitude += "W";
        }
        return positionLatitude + ",   " + positionLongitude;
    }

    function pad(n) {
        return (n < 10) ? ("0" + n.toString()) : n.toString();
    }

    function plotBarogram() {
        var nPoints = igcFile.recordTime.length;
        var pressureBarogramData = [];
        var gpsBarogramData = [];
        var j;
        var timestamp;

        for (j = 0; j < nPoints; j++) {
            timestamp = igcFile.recordTime[j].getTime();
            pressureBarogramData.push([timestamp, igcFile.pressureAltitude[j] * altitudeConversionFactor]);
            gpsBarogramData.push([timestamp, igcFile.gpsAltitude[j] * altitudeConversionFactor]);
        }

        var baro = $.plot($('#barogram'), [{
            label: 'Pressure altitude',
            data: pressureBarogramData
        }, {
            label: 'GPS altitude',
            data: gpsBarogramData
        }], {
            axisLabels: {
                show: true
            },
            xaxis: {
                axisLabel: 'Time',
                tickFormatter: function (t, axis) {
                     return moment(t).format('HH:mm');
                },
                ticks: function (axis) {
                    var ticks = [];
                    var startMoment = moment(axis.min);
                    var endMoment = moment(axis.max);
                    var durationMinutes = endMoment.diff(startMoment, 'minutes');
                    var interval;
                    if (durationMinutes <= 10) {
                       interval = 1;
                    }
                    if (durationMinutes <= 50) {
                       interval = 5;
                    }
                    else if (durationMinutes <= 100) {
                       interval = 10;
                    }
                    else if (durationMinutes <= 150) {
                       interval = 15;
                    }
                    else if (durationMinutes <= 300) {
                       interval = 30;
                    }
                    else if (durationMinutes <= 600) {
                       interval = 60;
                    }
                    else {
                       interval = 120;
                    }

                    var tick = startMoment.clone();
                    tick.minutes(0).seconds(0);
                    while (tick < endMoment) {
                        if (tick > startMoment) {
                            ticks.push(tick.valueOf());
                        }
                        tick.add(interval, 'minutes');
                    }

                    return ticks;
                }
            },
            yaxis: {
                axisLabel: 'Altitude / ' + $('#altitudeUnits').val()
            },

            crosshair: {
                mode: 'xy'
            },

            grid: {
                clickable: true,
                autoHighlight: false
            }
        });

        return baro;
    }

    function updateTimeline (timeIndex, mapControl) {
        var currentPosition = igcFile.latLong[timeIndex];
        var positionText=positionDisplay(currentPosition);
        var unitName = $('#altitudeUnits').val();
        $('#timePositionDisplay').text(
            moment(igcFile.recordTime[timeIndex]).format('HH:mm:ss') + ': ' +
            (igcFile.pressureAltitude[timeIndex] * altitudeConversionFactor).toFixed(0) + ' ' +
            unitName + ' (barometric) / ' +
            (igcFile.gpsAltitude[timeIndex] * altitudeConversionFactor).toFixed(0) + ' ' +
            unitName + ' (GPS); ' +
            positionText
        );

        mapControl.setTimeMarker(timeIndex);

        barogramPlot.lockCrosshair({
           x: igcFile.recordTime[timeIndex].getTime(),
           y: igcFile.pressureAltitude[timeIndex] * altitudeConversionFactor
        });
    }

    function displayIgc(mapControl) {
        // Display the headers.
        var displayDate = moment(igcFile.recordTime[0]).format('LL');
        var headerTable = $('#headerInfo tbody');
        headerTable.html('')
                   .append(
                       $('

').append($('	').text('Date'))
                              .append($('	').text(displayDate))
                   );
        var headerName;
        var headerIndex;
        for (headerIndex = 0; headerIndex < igcFile.headers.length; headerIndex++) {
            headerTable.append(
                $('

').append($('	').text(igcFile.headers[headerIndex].name))
                              .append($('	').text(igcFile.headers[headerIndex].value))
            );
        }

        // Show the task declaration if it is present.

        if (igcFile.task.coordinates.length > 0) {
            //eliminate anything with empty start line coordinates
            if(igcFile.task.coordinates[0][0] !==0) {
                    $('#task').show();
                    var taskList = $('#task ul').first().html('');
                    var j;
                    //Now add TP numbers.  Change to unordered list
                    if(igcFile.task.takeoff.length > 0) {
                               taskList.append($('

').text("Takeoff: " + igcFile.task.takeoff));
                    }
                    for (j =0; j <igcFile.task.names.length; j++) {
                            switch(j)  {
                            case 0:
                                    taskList.append($('

').text("Start: " + igcFile.task.names[j]));
                                    break;
                            case ( igcFile.task.names.length-1):
                                    taskList.append($('

').text("Finish: " + igcFile.task.names[j]));
                                    break;
                            default:
                                    taskList.append($('

').text("TP" + (j).toString() + ": " + igcFile.task.names[j]));
                        }
                    }
                 if(igcFile.task.landing.length > 0) {
                        taskList.append($('

').text("Landing: : " + igcFile.task.landing));
                 }
                mapControl.addTask(igcFile.task.coordinates, igcFile.task.names);
                }
        }
        else {
            $('#task').hide();
        }

        // Reveal the map and graph. We have to do this before
        // setting the zoom level of the map or plotting the graph.
        $('#igcFileDisplay').show();

        mapControl.addTrack(igcFile.latLong);
        barogramPlot = plotBarogram(igcFile);

        $('#timeSlider').prop('max', igcFile.recordTime.length - 1);
        updateTimeline(0, mapControl);
    }

    $(document).ready(function () {
        var mapControl = createMapControl('map');

        var timeZoneSelect = $('#timeZoneSelect');
        $.each(moment.tz.names(), function(index, name) {
            timeZoneSelect.append(
                 $('<option></option>', { value: name }).text(name));
        });

        timeZoneSelect.change(function () {
            var selectedZone = $(this).val();
            moment.tz.setDefault(selectedZone);
            if (igcFile !== null) {
                barogramPlot = plotBarogram();
                updateTimeline($('#timeSlider').val(), mapControl);
                $('#headerInfo td').first().text(moment(igcFile.recordTime[0]).format('LL'));
            }

            if (window.localStorage) {
                try {
                    localStorage.setItem('timeZone', selectedZone);
                }
                catch (e) {
                    // If we can't save default time zone, ignore the error.
                    // It will default to UTC on the next visit.
                }
            }
        });

        $('#fileControl').change(function () {
            if (this.files.length > 0) {
                var reader = new FileReader();
                reader.onload = function(e)  {
                  try {
                      $('#errorMessage').text('');
                      mapControl.reset();
                      $('#timeSlider').val(0);

                      igcFile = parseIGC(this.result);
                      displayIgc(mapControl);
                  } catch (ex) {
                      if (ex instanceof IGCException) {
                          $('#errorMessage').text(ex.message);
                      }
                      else {
                          throw ex;
                      }
                  }
                };
                reader.readAsText(this.files[0]);
            }
        });

        $('#altitudeUnits').change(function (e, raisedProgrammatically) {
            var altitudeUnit = $(this).val();
            if (altitudeUnit === 'feet') {
                altitudeConversionFactor = 3.2808399;
            }
            else {
                altitudeConversionFactor = 1.0;
            }

            if (igcFile !== null) {
                barogramPlot = plotBarogram();
                updateTimeline($('#timeSlider').val(), mapControl);
            }

            if (window.localStorage && !raisedProgrammatically) {
                try {
                    localStorage.setItem("altitudeUnit", altitudeUnit);
                }
                catch (e) {
                    // If local storage permission is denied, ignore the error.
                }
            }
        });

        // We need to handle the 'change' event for IE, but
        // 'input' for Chrome and Firefox in order to update smoothly
        // as the range input is dragged.
        $('#timeSlider').on('input', function() {
          var t = parseInt($(this).val(), 10);
          updateTimeline(t, mapControl);
        });
        $('#timeSlider').on('change', function() {
           var t = parseInt($(this).val(), 10);
           updateTimeline(t, mapControl);
        });

        $('#timeBack').click(function() {
           var slider = $('#timeSlider');
           var curTime = parseInt(slider.val(), 10);
           curTime--;
           if(curTime < 0) {
                 curTime = 0;
           }
           slider.val(curTime);
           updateTimeline(curTime, mapControl);
        });

         $('#timeForward').click(function() {
           var slider = $('#timeSlider');
           var curTime = parseInt(slider.val(), 10);
           var maxval= slider.prop('max');
           curTime++;
           if(curTime >  maxval) {
                 curTime = maxval;
           }
           slider.val(curTime);
           updateTimeline(curTime, mapControl);
        });

         $('#barogram').on('plotclick', function (event, pos, item) {
             console.log('plot click');
             if (item) {
                 updateTimeline(item.dataIndex, mapControl);
                 $('#timeSlider').val(item.dataIndex);
             }
         });

        // Load preferences from local storage, if available.

         var altitudeUnit = '';
         var timeZone = '';

         if (window.localStorage) {
             try {
                 altitudeUnit = localStorage.getItem('altitudeUnit');
                 if (altitudeUnit) {
                     $('#altitudeUnits').val(altitudeUnit).trigger('change', true);
                 }

                 timeZone = localStorage.getItem('timeZone');
             }
             catch (e) {
                 // If permission is denied, ignore the error.
             }
         }

         if (!timeZone) {
             timeZone = 'UTC';
         }

         timeZoneSelect.val(timeZone);
         moment.tz.setDefault(timeZone);
    });
}(jQuery));
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "editors", "ui", "settings", "tabManager", "ace", "menus", "commands",
        "console"
    ];
    main.provides = ["immediate"];
    return main;

    function main(options, imports, register) {
        var editors   = imports.editors;
        var settings  = imports.settings;
        var tabs      = imports.tabManager;
        var ui        = imports.ui;
        var menus     = imports.menus;
        var commands  = imports.commands;
        var c9console = imports.console;

        var Repl     = require("plugins/c9.ide.ace.repl/repl").Repl;
        var markup   = require("text!./immediate.xml");

        var counter  = 0;

        /***** Initialization *****/

        var extensions = [];

        var handle = editors.register("immediate", "Immediate Window",
                                      Immediate, extensions);
        var emit   = handle.getEmitter();

        var replTypes = {}; //Shared across Immediate windows

        handle.on("load", function(){
            handle.addElement(
                tabs.getElement("mnuEditors").appendChild(
                    new ui.item({
                        caption : "New Immediate Window",
                        onclick : function(e){
                            tabs.open({
                                active     : true,
                                pane       : this.parentNode.pane,
                                editorType : "immediate"
                            }, function(){});
                        }
                    })
                )
            );

            menus.addItemByPath("Window/New Immediate Window", new ui.item({
                onclick : function(){
                    tabs.open({
                        active     : true,
                        pane       : this.parentNode.pane,
                        editorType : "immediate"
                    }, function(){});
                }
            }), 31, handle);

            commands.addCommand({
                name    : "showimmediate",
                group   : "Panels",
                exec    : function (editor) {
                    // Search for the output pane
                    if (search()) return;

                    // If not found show the console
                    c9console.show();

                    // Search again
                    if (search()) return;

                    // Else open the output panel in the console
                    tabs.open({
                        editorType : "immediate",
                        active     : true,
                        pane        : c9console.getPanes()[0],
                    }, function(){});
                }
            }, handle);

            // Insert some CSS
            ui.insertCss(require("text!./style.css"), options.staticPrefix, handle);
        });

        //Search through pages
        function search(){
            return !tabs.getTabs().every(function(tab){
                if (tab.editorType == "immediate") {
                    tabs.focusTab(tab);
                    return false;
                }
                return true;
            });
        }

        function Immediate(){
            var Baseclass = editors.findEditor("ace");

            var deps   = main.consumes.splice(0, main.consumes.length - 1);
            var plugin = new Baseclass(true, [], deps);
            // var emit   = plugin.getEmitter();

            var ddType, btnClear, ace;

            plugin.on("draw", function(e){
                // Create UI elements
                ui.insertMarkup(e.tab, markup, plugin);

                ddType    = plugin.getElement("ddType");
                btnClear  = plugin.getElement("btnClear");

                ace = plugin.ace;

                ace.setOption("printMargin", false);
                ace.setOption("scrollPastEnd", 0);
                ace.setOption("fontSize", 11);
                ace.setOption("showFoldWidgets", false);
                ace.setOption("highlightActiveLine", false);
                ace.setOption("highlightGutterLine", false);
                ace.container.style.lineHeight = "17px";

                e.htmlNode.className += " immediate";

                ddType.on("afterchange", function(){
                    if (currentDocument)
                        currentDocument.getSession().changeType(ddType.value);
                });
                btnClear.on("click", function(){
                    plugin.clear();
                });

                for (var type in replTypes){
                    var t = replTypes[type];
                    addType(t.caption, type, t.plugin);
                }

                handle.on("addEvaluator", function(e){
                    addType(e.caption, e.id, e.plugin);
                });
            });

            /***** Method *****/

            function addType(caption, value, plugin){
                var item = ddType.appendChild(new ui.item({
                    caption : caption,
                    value   : value
                }));

                plugin.addElement(item);
            }

            // Set the tab in loading state - later this could be the output block
            // currentDocument.tab.className.add("loading");
            // settings.save();

            /***** Lifecycle *****/

            plugin.on("load", function(){
            });

            var currentDocument;
            plugin.on("documentLoad", function(e){
                var doc     = e.doc;
                var session = doc.getSession();

                doc.undoManager.on("change", function(e){
                    if (!doc.undoManager.isAtBookmark())
                        doc.undoManager.bookmark();
                });

                doc.title = "Immediate";

                if (session.repl) return;

                session.changeType = function(type){
                    handle.findEvaluator(type, function(type, evaluator){
                        session.type = type;

                        if (!session.repl) {
                            session.repl = new Repl(session.session, {
                                mode      : evaluator.mode,
                                evaluator : evaluator,
                                message   : evaluator.message
                            });

                            if (currentDocument
                              && currentDocument.getSession() == session)
                                session.repl.attach(ace);
                        }
                        else {
                            session.repl.setEvaluator(evaluator);
                            session.repl.session.setMode(evaluator.mode);
                        }
                    });
                };

                session.changeType(session.type || ddType.value);
            });
            plugin.on("documentActivate", function(e){
                currentDocument = e.doc;
                var session = e.doc.getSession();

                if (session.type)
                    ddType.setValue(session.type);

                if (session.repl)
                    session.repl.attach(ace);
            });
            plugin.on("documentUnload", function(e){
                var session = e.doc.getSession();
                if (session.repl)
                    session.repl.detach();
                // TODO: this breaks moving repl between splits
                // delete session.repl;
            });
            plugin.on("getState", function(e){
                // @todo at one for each value container
                e.state.type      = e.doc.getSession().type;
            });
            plugin.on("setState", function(e){
                if (e.state.type)
                    ddType.setValue(e.state.type);
            });
            plugin.on("clear", function(){
            });
            plugin.on("focus", function(){
            });
            plugin.on("enable", function(){
            });
            plugin.on("disable", function(){
            });
            plugin.on("unload", function(){
            });

            /***** Register and define API *****/

            /**
             * Immediate Pane for Cloud9 IDE
             * @class immediate.Immediate
             * @extends Editor
             */
            /**
             * The type of editor. Use this to create an immediate pane using
             * {@link tabManager#openEditor} or {@link editors#createEditor}.
             * @property {"immediate"} type
             * @readonly
             */
            plugin.freezePublicAPI({

            });

            plugin.load("immediate" + counter++);

            return plugin;
        }

        /**
         * The immediate handle, provides an API for adding
         * {@link Evaluator evaluators} to the immediate panes.
         * An evaluator is a plugin that can take the expressions from the
         * multi-line REPL and return resuls. The results can be
         * rendered as HTML and are fully interactive.
         *
         * This is the object you get when you request the immediate service
         * in your plugin.
         *
         * Example:
         *
         *     define(function(require, exports, module) {
         *         main.consumes = ["immediate", "Plugin"];
         *         main.provides = ["myplugin"];
         *         return main;
         *
         *         function main(options, imports, register) {
         *             var immediate = imports.immediate;
         *             var plugin    = new imports.Plugin("Your Name", main.consumes);
         *
         *             plugin.on("load", function(){
         *                 var evaluator = {
         *                     mode        : "ace/mode/go",
         *                     message     : "",
         *                     canEvaluate : function(str) { return str.trim() ? true : false; },
         *                     evaluate    : function(expression, cell, done) {
         *
         *                         executeCommand(expression, function(result){
         *                             cell.addWidget({
         *                                 html       : "
"
         *                                     + result + "
",
         *                                 coverLine  : true,
         *                                 fixedWidth : true
         *                             });
         *
         *                             done();
         *                         });
         *
         *                     }
         *                 };
         *
         *                 immediate.addEvaluator("Go Language", "go", evaluator, plugin);
         *             });
         *         });
         *     });
         *
         *
         * @class immediate
         * @extends Plugin
         * @singleton
         */
        handle.freezePublicAPI({
            _events : [
                /**
                 * Fires when an evaluator is added.
                 * @event addEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "addEvaluator",
                /**
                 * Fires when an evaluator is removed.
                 * @event removeEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "removeEvaluator"
            ],

            /**
             * Adds a new evaluator to all immediate panes. The user is able
             * to choose the evaluator from a dropdown in the UI of the
             * immediate pane.
             * @param {String}              caption     The caption in the dropdown.
             * @param {String}              id          The unique identifier of this evaluator.
             * @param {Evaluator} evaluator   The evaluator for your runtime.
             * @param {Plugin}              plugin      The plugin responsible for adding the evaluator.
             * @fires addEvaluator
             */
            addEvaluator : function(caption, id, evaluator, plugin){
                if (replTypes[id])
                    throw new Error("An evaluator is already registered with "
                        + "the id '" + id + "'");

                replTypes[id] = {
                    caption   : caption,
                    id        : id,
                    evaluator : evaluator,
                    plugin    : plugin
                };
                emit("addEvaluator", replTypes[id]);

                plugin.addOther(function(){
                    handle.removeEvaluator(id);
                });
            },

            /**
             * Retrieves an evaluator based on it's id. When the evaluator is
             * not yet registered, the callback will be returned when the
             * evaluator is registered.
             * @param {String}              id                  The id of the evaluator to retrieve.
             * @param {Function}            callback            Called when the evaluator is available.
             * @param {Error}               callback.id         The id of the requested evaluator.
             * @param {Evaluator} callback.evaluator  The evaluator requested.
             */
            findEvaluator : function(id, callback){
                if (!id || !replTypes[id]) {
                    handle.on("addEvaluator", function wait(e){
                        if (!id || e.id == id)
                            callback(e.id, replTypes[e.id].evaluator);

                        handle.off("addEvaluator", wait);
                    });
                }
                else {
                    callback(id, replTypes[id].evaluator);
                }
            },

            /**
             * Removes an evaluator from all immediate panes.
             * @param {String} id  The unique identifier of the evaluator to remove.
             */
            removeEvaluator : function(id){
                emit("removeEvaluator", replTypes[id]);
                delete replTypes[id];
            }
        });

        register(null, {
            immediate: handle
        });
    }
});<commit_msg>Persist session type<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "editors", "ui", "settings", "tabManager", "ace", "menus", "commands",
        "console"
    ];
    main.provides = ["immediate"];
    return main;

    function main(options, imports, register) {
        var editors   = imports.editors;
        var settings  = imports.settings;
        var tabs      = imports.tabManager;
        var ui        = imports.ui;
        var menus     = imports.menus;
        var commands  = imports.commands;
        var c9console = imports.console;

        var Repl     = require("plugins/c9.ide.ace.repl/repl").Repl;
        var markup   = require("text!./immediate.xml");

        var counter  = 0;

        /***** Initialization *****/

        var extensions = [];

        var handle = editors.register("immediate", "Immediate Window",
                                      Immediate, extensions);
        var emit   = handle.getEmitter();

        var replTypes = {}; //Shared across Immediate windows

        handle.on("load", function(){
            handle.addElement(
                tabs.getElement("mnuEditors").appendChild(
                    new ui.item({
                        caption : "New Immediate Window",
                        onclick : function(e){
                            tabs.open({
                                active     : true,
                                pane       : this.parentNode.pane,
                                editorType : "immediate"
                            }, function(){});
                        }
                    })
                )
            );

            menus.addItemByPath("Window/New Immediate Window", new ui.item({
                onclick : function(){
                    tabs.open({
                        active     : true,
                        pane       : this.parentNode.pane,
                        editorType : "immediate"
                    }, function(){});
                }
            }), 31, handle);

            commands.addCommand({
                name    : "showimmediate",
                group   : "Panels",
                exec    : function (editor) {
                    // Search for the output pane
                    if (search()) return;

                    // If not found show the console
                    c9console.show();

                    // Search again
                    if (search()) return;

                    // Else open the output panel in the console
                    tabs.open({
                        editorType : "immediate",
                        active     : true,
                        pane        : c9console.getPanes()[0],
                    }, function(){});
                }
            }, handle);

            // Insert some CSS
            ui.insertCss(require("text!./style.css"), options.staticPrefix, handle);
        });

        //Search through pages
        function search(){
            return !tabs.getTabs().every(function(tab){
                if (tab.editorType == "immediate") {
                    tabs.focusTab(tab);
                    return false;
                }
                return true;
            });
        }

        function Immediate(){
            var Baseclass = editors.findEditor("ace");

            var deps   = main.consumes.splice(0, main.consumes.length - 1);
            var plugin = new Baseclass(true, [], deps);
            // var emit   = plugin.getEmitter();

            var ddType, btnClear, ace;

            plugin.on("draw", function(e){
                // Create UI elements
                ui.insertMarkup(e.tab, markup, plugin);

                ddType    = plugin.getElement("ddType");
                btnClear  = plugin.getElement("btnClear");

                ace = plugin.ace;

                ace.setOption("printMargin", false);
                ace.setOption("scrollPastEnd", 0);
                ace.setOption("fontSize", 11);
                ace.setOption("showFoldWidgets", false);
                ace.setOption("highlightActiveLine", false);
                ace.setOption("highlightGutterLine", false);
                ace.container.style.lineHeight = "17px";

                e.htmlNode.className += " immediate";

                ddType.on("afterchange", function(){
                    if (currentDocument)
                        currentDocument.getSession().changeType(ddType.value);
                });
                btnClear.on("click", function(){
                    plugin.clear();
                });

                for (var type in replTypes){
                    var t = replTypes[type];
                    addType(t.caption, type, t.plugin);
                }

                handle.on("addEvaluator", function(e){
                    addType(e.caption, e.id, e.plugin);
                });
            });

            /***** Method *****/

            function addType(caption, value, plugin){
                var item = ddType.appendChild(new ui.item({
                    caption : caption,
                    value   : value
                }));

                plugin.addElement(item);
            }

            // Set the tab in loading state - later this could be the output block
            // currentDocument.tab.className.add("loading");
            // settings.save();

            /***** Lifecycle *****/

            plugin.on("load", function(){
            });

            var currentDocument;
            plugin.on("documentLoad", function(e){
                var doc     = e.doc;
                var session = doc.getSession();

                doc.undoManager.on("change", function(e){
                    if (!doc.undoManager.isAtBookmark())
                        doc.undoManager.bookmark();
                });

                doc.title = "Immediate";

                if (session.repl) return;

                session.changeType = function(type){
                    handle.findEvaluator(type, function(type, evaluator){
                        session.type = type;

                        if (!session.repl) {
                            session.repl = new Repl(session.session, {
                                mode      : evaluator.mode,
                                evaluator : evaluator,
                                message   : evaluator.message
                            });

                            if (currentDocument
                              && currentDocument.getSession() == session)
                                session.repl.attach(ace);
                        }
                        else {
                            session.repl.setEvaluator(evaluator);
                            session.repl.session.setMode(evaluator.mode);
                        }
                    });
                };

                session.changeType(session.type || ddType.value);
            });
            plugin.on("documentActivate", function(e){
                currentDocument = e.doc;
                var session = e.doc.getSession();

                if (session.type)
                    ddType.setValue(session.type);

                if (session.repl)
                    session.repl.attach(ace);
            });
            plugin.on("documentUnload", function(e){
                var session = e.doc.getSession();
                if (session.repl)
                    session.repl.detach();
                // TODO: this breaks moving repl between splits
                // delete session.repl;
            });
            plugin.on("getState", function(e){
                // @todo at one for each value container
                e.state.type      = e.doc.getSession().type;
            });
            plugin.on("setState", function(e){
                if (e.state.type) {
                    e.doc.getSession().type = e.state.type;
                    ddType.setValue(e.state.type);
                }
            });
            plugin.on("clear", function(){
            });
            plugin.on("focus", function(){
            });
            plugin.on("enable", function(){
            });
            plugin.on("disable", function(){
            });
            plugin.on("unload", function(){
            });

            /***** Register and define API *****/

            /**
             * Immediate Pane for Cloud9 IDE
             * @class immediate.Immediate
             * @extends Editor
             */
            /**
             * The type of editor. Use this to create an immediate pane using
             * {@link tabManager#openEditor} or {@link editors#createEditor}.
             * @property {"immediate"} type
             * @readonly
             */
            plugin.freezePublicAPI({

            });

            plugin.load("immediate" + counter++);

            return plugin;
        }

        /**
         * The immediate handle, provides an API for adding
         * {@link Evaluator evaluators} to the immediate panes.
         * An evaluator is a plugin that can take the expressions from the
         * multi-line REPL and return resuls. The results can be
         * rendered as HTML and are fully interactive.
         *
         * This is the object you get when you request the immediate service
         * in your plugin.
         *
         * Example:
         *
         *     define(function(require, exports, module) {
         *         main.consumes = ["immediate", "Plugin"];
         *         main.provides = ["myplugin"];
         *         return main;
         *
         *         function main(options, imports, register) {
         *             var immediate = imports.immediate;
         *             var plugin    = new imports.Plugin("Your Name", main.consumes);
         *
         *             plugin.on("load", function(){
         *                 var evaluator = {
         *                     mode        : "ace/mode/go",
         *                     message     : "",
         *                     canEvaluate : function(str) { return str.trim() ? true : false; },
         *                     evaluate    : function(expression, cell, done) {
         *
         *                         executeCommand(expression, function(result){
         *                             cell.addWidget({
         *                                 html       : "
"
         *                                     + result + "
",
         *                                 coverLine  : true,
         *                                 fixedWidth : true
         *                             });
         *
         *                             done();
         *                         });
         *
         *                     }
         *                 };
         *
         *                 immediate.addEvaluator("Go Language", "go", evaluator, plugin);
         *             });
         *         });
         *     });
         *
         *
         * @class immediate
         * @extends Plugin
         * @singleton
         */
        handle.freezePublicAPI({
            _events : [
                /**
                 * Fires when an evaluator is added.
                 * @event addEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "addEvaluator",
                /**
                 * Fires when an evaluator is removed.
                 * @event removeEvaluator
                 * @param {Object}              e
                 * @param {String}              e.caption     The caption of the evaluator.
                 * @param {String}              e.id          The unique identifier of the evaluator.
                 * @param {Evaluator} e.evaluator   The evaluator.
                 * @param {Plugin}              e.plugin      The plugin responsible for adding the evaluator.
                 */
                "removeEvaluator"
            ],

            /**
             * Adds a new evaluator to all immediate panes. The user is able
             * to choose the evaluator from a dropdown in the UI of the
             * immediate pane.
             * @param {String}              caption     The caption in the dropdown.
             * @param {String}              id          The unique identifier of this evaluator.
             * @param {Evaluator} evaluator   The evaluator for your runtime.
             * @param {Plugin}              plugin      The plugin responsible for adding the evaluator.
             * @fires addEvaluator
             */
            addEvaluator : function(caption, id, evaluator, plugin){
                if (replTypes[id])
                    throw new Error("An evaluator is already registered with "
                        + "the id '" + id + "'");

                replTypes[id] = {
                    caption   : caption,
                    id        : id,
                    evaluator : evaluator,
                    plugin    : plugin
                };
                emit("addEvaluator", replTypes[id]);

                plugin.addOther(function(){
                    handle.removeEvaluator(id);
                });
            },

            /**
             * Retrieves an evaluator based on it's id. When the evaluator is
             * not yet registered, the callback will be returned when the
             * evaluator is registered.
             * @param {String}              id                  The id of the evaluator to retrieve.
             * @param {Function}            callback            Called when the evaluator is available.
             * @param {Error}               callback.id         The id of the requested evaluator.
             * @param {Evaluator} callback.evaluator  The evaluator requested.
             */
            findEvaluator : function(id, callback){
                if (!id || !replTypes[id]) {
                    handle.on("addEvaluator", function wait(e){
                        if (!id || e.id == id)
                            callback(e.id, replTypes[e.id].evaluator);

                        handle.off("addEvaluator", wait);
                    });
                }
                else {
                    callback(id, replTypes[id].evaluator);
                }
            },

            /**
             * Removes an evaluator from all immediate panes.
             * @param {String} id  The unique identifier of the evaluator to remove.
             */
            removeEvaluator : function(id){
                emit("removeEvaluator", replTypes[id]);
                delete replTypes[id];
            }
        });

        register(null, {
            immediate: handle
        });
    }
});<|endoftext|>


<commit_before>
var Plottables = {};

function loadScript(url, callback) {
  var element = document.createElement("script");
  element.type = "text/javascript";
  element.src = url;
  element.onload = callback;
  document.head.appendChild(element);
}

function loadPlottable(branchName, callback) {
  var url;
  if (branchName != null) {
    url = "https://rawgithub.com/palantir/plottable/" + branchName + "/plottable.js";
  } else {
    branchName = "#local";
    url = "../plottable.js"; //load local version
  }
  var inner = function() {
    console.log("loaded Plottable:" + branchName);
    Plottables[branchName] = Plottable;
    Plottable = null;
    callback();
  }
  loadScript(url, inner);
}

var quicktests = []
function loadQuicktests(qts, callback) {
  var nLoaded = 0;

  var inner = function() {
    if (++nLoaded === qts.length) callback();
  }

  qts.forEach(function(q) {
    loadScript("quicktests/" + q.name + ".js", inner);
  });
}

function loadAllQuicktests(callback) {
  loadScript("quicktests/list_of_quicktests.js", function() {
    console.log("about to load quicktests", callback);
    loadQuicktests(list_of_quicktests, callback);
  });
}

function loadQuickTestsAndPlottables(otherBranch, callback) {
  var loaded = 0;
  var inner = function() {
    if (++loaded === 3) callback();
  }

  loadPlottable("master", inner);
  loadPlottable(otherBranch, inner);
  console.log("about to load all quicktests", inner);
  loadAllQuicktests(inner);
}

var data1 = makeRandomData(50);
var data2 = makeRandomData(50);

function loadSingleQuicktest(container, quickTest, Plottable) {
  container.append("p").text(quickTest.quicktestName);
  var svg = container.append("svg").attr("height", 500);
  quickTest(svg, _.cloneDeep([data1, data2]), Plottable);
}

function runQuicktest(tableSelection, quickTest, Plottable1, Plottable2) {
  var tr = tableSelection.append("tr");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable1);
  tr.append("td");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable2);
}

function() {
  var table = d3.select("table");
  quicktests.forEach(function(q) {
    runQuicktest(table, q, Plottables["master"], Plottables["master"]);
  });
}

window.onload = function() {loadQuickTestsAndPlottables("master", function() {
              var table = d3.select("table");
              quicktests.forEach(function(q) {
                runQuicktest(table, q, Plottables["master"], Plottables["master"]);
              });
            }
);

var button = document.getElementById('button');
button.onclick = function () {
  var fb = $('#featureBranch').val();
  console.log(fb);
  loadQuickTestsAndPlottables(fb, main);
);
<commit_msg>Update quicktest.js<commit_after>
var Plottables = {};

function loadScript(url, callback) {
  var element = document.createElement("script");
  element.type = "text/javascript";
  element.src = url;
  element.onload = callback;
  document.head.appendChild(element);
}

function loadPlottable(branchName, callback) {
  var url;
  if (branchName != null) {
    url = "https://rawgithub.com/palantir/plottable/" + branchName + "/plottable.js";
  } else {
    branchName = "#local";
    url = "../plottable.js"; //load local version
  }
  var inner = function() {
    console.log("loaded Plottable:" + branchName);
    Plottables[branchName] = Plottable;
    Plottable = null;
    callback();
  }
  loadScript(url, inner);
}

var quicktests = []
function loadQuicktests(qts, callback) {
  var nLoaded = 0;

  var inner = function() {
    if (++nLoaded === qts.length) callback();
  }

  qts.forEach(function(q) {
    loadScript("quicktests/" + q.name + ".js", inner);
  });
}

function loadAllQuicktests(callback) {
  loadScript("quicktests/list_of_quicktests.js", function() {
    console.log("about to load quicktests", callback);
    loadQuicktests(list_of_quicktests, callback);
  });
}

function loadQuickTestsAndPlottables(otherBranch, callback) {
  var loaded = 0;
  var inner = function() {
    if (++loaded === 3) callback();
  }

  loadPlottable("master", inner);
  loadPlottable(otherBranch, inner);
  console.log("about to load all quicktests", inner);
  loadAllQuicktests(inner);
}

var data1 = makeRandomData(50);
var data2 = makeRandomData(50);

function loadSingleQuicktest(container, quickTest, Plottable) {
  container.append("p").text(quickTest.quicktestName);
  var svg = container.append("svg").attr("height", 500);
  quickTest(svg, _.cloneDeep([data1, data2]), Plottable);
}

function runQuicktest(tableSelection, quickTest, Plottable1, Plottable2) {
  var tr = tableSelection.append("tr");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable1);
  tr.append("td");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable2);
}

/*function() {
  var table = d3.select("table");
  quicktests.forEach(function(q) {
    runQuicktest(table, q, Plottables["master"], Plottables["master"]);
  });
}
*/

window.onload = function() {loadQuickTestsAndPlottables("master", function() {
              var table = d3.select("table");
              quicktests.forEach(function(q) {
                runQuicktest(table, q, Plottables["master"], Plottables["master"]);
              });
            }
);

var button = document.getElementById('button');
button.onclick = function () {
  var fb = $('#featureBranch').val();
  console.log(fb);
  loadQuickTestsAndPlottables(fb, main);
);
<|endoftext|>


<commit_before>
var Plottables = {};

function loadScript(url, id, callback) {
  var element = document.createElement("script");
  element.type = "text/javascript";
  element.src = url;
  element.id = id;
  element.onload = callback;
  document.head.appendChild(element);
}

function loadPlottable(branchName, callback) {
  var url;
  if (branchName != null) {
    url = "https://rawgithub.com/palantir/plottable/" + branchName + "/plottable.js";
  } else {
    branchName = "#local";
    url = "../plottable.js"; //load local version
  }
  var inner = function() {
    console.log("loaded Plottable:" + branchName);
    Plottables[branchName] = Plottable;
    Plottable = null;
    callback();
  }
  loadScript(url, branchName, inner);
}

var quicktests = [];
var quicktestsToLoad = [];

function loadQuicktests(qts, callback) {
  var nLoaded = 0;

  var filterword = $('#filterWord').val();
  if(filterword === "" || filterword === undefined){
    quicktestsToLoad = qts;
  } else {
    quicktestsToLoad = qts.filter(function(q) {return q.categories.indexOf(filterword) > -1})
  }

  var inner = function() {
    if (++nLoaded === quicktestsToLoad.length) callback();
  }

  quicktestsToLoad.forEach(function(q) {
    loadScript("quicktests/" + q.name + ".js", q.name, inner);
  });
}

function loadAllQuicktests(callback) {
  loadScript("quicktests/list_of_quicktests.js", "list_of_quicktests", function() {
    console.log("about to load quicktests", callback);
    loadQuicktests(list_of_quicktests, callback);
  });
}

function loadQuickTestsAndPlottables(otherBranch, callback) {
  var loaded = 0;
  var inner = function() {
    if (++loaded === 3) callback();
  }

  loadPlottable("master", inner);
  loadPlottable(otherBranch, inner);
  console.log("about to load all quicktests", inner);
  loadAllQuicktests(inner);
}

var data1 = makeRandomData(50);
var data2 = makeRandomData(50);

function loadSingleQuicktest(container, quickTest, Plottable) {
  container.append("p").text(quickTest.quicktestName);
  var svg = container.append("svg").attr("height", 500);
  quickTest(svg, _.cloneDeep([data1, data2]), Plottable);
}

function runQuicktest(tableSelection, quickTest, Plottable1, Plottable2) {
  var tr = tableSelection.append("tr");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable1);
  tr.append("td");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable2);
}

function makeMainFunctionForGivenBranch(branch) {
  return function () {
    var table = d3.select("table");
    quicktests.forEach(function(q) {
      runQuicktest(table, q, Plottables["master"], Plottables[branch]);
    });
  }
}

var button = document.getElementById('button');
button.onclick = function () {
  d3.selectAll("tr").remove();

  var fb = $('#featureBranch').val();
  loadQuickTestsAndPlottables(fb, makeMainFunctionForGivenBranch(fb));
};
<commit_msg>Update quicktest.js<commit_after>
var Plottables = {};

function loadScript(url, id, callback) {
  var element = document.createElement("script");
  element.type = "text/javascript";
  element.src = url;
  element.id = id;
  element.onload = callback;
  document.head.appendChild(element);
}

function loadPlottable(branchName, callback) {
  var url;
  if (branchName != null) {
    url = "https://rawgithub.com/palantir/plottable/" + branchName + "/plottable.js";
  } else {
    branchName = "#local";
    url = "../plottable.js"; //load local version
  }
  var inner = function() {
    console.log("loaded Plottable:" + branchName);
    Plottables[branchName] = Plottable;
    Plottable = null;
    callback();
  }
  loadScript(url, branchName, inner);
}

var quicktests = [];
var quicktestsToLoad = [];

function loadQuicktests(qts, callback) {
  var nLoaded = 0;

  var filterword = $('#filterWord').val();
  if(filterword === "" || filterword === undefined){
    quicktestsToLoad = qts;
  } else {
    quicktestsToLoad = qts.filter(function(q) {return q.categories.indexOf(filterword) > -1})
  }

  var inner = function() {
    if (++nLoaded === quicktestsToLoad.length) callback();
  }

  quicktestsToLoad.forEach(function(q) {
    loadScript("quicktests/" + q.name + ".js", q.name, inner);
  });
}

function loadAllQuicktests(callback) {
  loadScript("quicktests/list_of_quicktests.js", "list_of_quicktests", function() {
    console.log("about to load quicktests", callback);
    loadQuicktests(list_of_quicktests, callback);
  });
}

function loadQuickTestsAndPlottables(otherBranch, callback) {
  var loaded = 0;
  var inner = function() {
    if (++loaded === 3) callback();
  }

  loadPlottable("master", inner);
  loadPlottable(otherBranch, inner);
  console.log("about to load all quicktests", inner);
  loadAllQuicktests(inner);
}

var data1 = makeRandomData(50);
var data2 = makeRandomData(50);

function loadSingleQuicktest(container, quickTest, Plottable) {
  container.append("p").text(quickTest.quicktestName);
  var svg = container.append("svg").attr("height", 500);
  quickTest(svg, _.cloneDeep([data1, data2]), Plottable);
}

function runQuicktest(tableSelection, quickTest, Plottable1, Plottable2) {
  var tr = tableSelection.append("tr").classed("quicktest-row", true);
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable1);
  tr.append("td");
  loadSingleQuicktest(tr.append("td"), quickTest, Plottable2);
}

function makeMainFunctionForGivenBranch(branch) {
  return function () {
    var table = d3.select("table");
    quicktests.forEach(function(q) {
      runQuicktest(table, q, Plottables["master"], Plottables[branch]);
    });
  }
}

var button = document.getElementById('button');
button.onclick = function () {
  d3.selectAll(".quicktest-row").remove();

  var fb = $('#featureBranch').val();
  loadQuickTestsAndPlottables(fb, makeMainFunctionForGivenBranch(fb));
};
<|endoftext|>


<commit_before>import inquirer from 'inquirer'
import semafor from 'semafor'
import glue from 'glue-path'
import packager from 'electron-packager'
import colors from 'colors'

export default function interactive(verbose = true) {

  let log = semafor();

  let default_version = "0.30.4";
  let default_src = process.cwd();
  let default_out = glue([process.cwd(), "releases"]);

  let get_package_name = () => {
    try {
      var pkg_path = glue([process.cwd(), "package.json"]);
      var pkg = require(pkg_path);
      return pkg.name;
    }catch(e){}
    return "";
  }

  let settings = {
    dir: default_src,
    name: null,
    platform: "all",
    arch: "all",
    version: default_version,
    out: default_out,
    "app-bundle-id": "",
    "app-version": "",
    overwrite: true,
    asar: false
  };

  let error = (msg) => {
    log.fail(msg.toString());
    process.exit(1);
  }

  let ask_overwrite = (cb) => {
    let overwrite_prompt = {
      type : 'confirm',
      name : "overwrite",
      message: "Overwrite output directory ?",
      default: true
    }
    inquirer.prompt(overwrite_prompt, (response) => {
      cb(response.overwrite);
    });
  }

  let ask_asar = (cb) => {
    let asar_prompt = {
      type : 'confirm',
      name : "asar",
      message: "Use asar source packaging ?",
      default: false
    }
    inquirer.prompt(asar_prompt, (response) => {
      cb(response.asar);
    });
  }

  let ask_sourcedir = (cb) => {
    let sourcedir_prompt = {
      type : 'input',
      name : "sourcedir",
      message: "Select Electron app source directory:",
      default: default_src
    }
    inquirer.prompt(sourcedir_prompt, (response) => {
      var sourcedir = response.sourcedir.trim();
      if(sourcedir == "") {
        sourcedir = default_src;
      }
      cb(sourcedir);
    });
  }

  let ask_out = (cb) => {
    let out_prompt = {
      type : 'input',
      name : "out",
      message: "Select Electron app output directory:",
      default: default_out
    }
    inquirer.prompt(out_prompt, (response) => {
      var out = response.out.trim();
      if(out == "") {
        out = default_out;
      }
      cb(out);
    });
  }

  let ask_appname = (cb) => {
    let appname_prompt = {
      type : 'input',
      name : "appname",
      message: "Select Application name:",
      default: get_package_name()
    }
    inquirer.prompt(appname_prompt, (response) => {
      var appname = response.appname.trim();
      if(appname == "") {
        error("Must provide the application name");
        return;
      }
      cb(appname);
    });
  }

  let ask_app_bundle_id = (cb) => {
    let bundle_id_prompt = {
      type : 'input',
      name : "bundle_id",
      message: "Select App Bundle Id (optional):"
    }
    inquirer.prompt(bundle_id_prompt, (response) => {
      cb(response.bundle_id);
    });
  }

  let ask_app_version = (cb) => {
    let app_version_prompt = {
      type : 'input',
      name : "app_version",
      message: "Select App Version(optional):",
      default: "0.0.1"
    }
    inquirer.prompt(app_version_prompt, (response) => {
      cb(response.app_version);
    });
  }

  let ask_electron_version = (cb) => {
    let version_prompt = {
      type : 'input',
      name : "version",
      message: "Select Electron version release:",
      default: default_version
    }
    inquirer.prompt(version_prompt, (response) => {
      var version = response.version.trim();
      if(version == "") {
        version == default_version;
      }
      cb(version);
    });
  }

  let ask_arch = (cb) => {
    let choices = ['all', 'ia32', 'x64'];
    let arch_prompt = {
      type : 'checkbox',
      name : "arch",
      message: "Select architecture:",
      choices: choices
    }
    inquirer.prompt(arch_prompt, (response) => {
      let arch = response.arch;
      if(arch.length == 0) {
        cb("all");
        return;
      }
      if(arch.indexOf('all') != -1) {
        cb("all");
        return;
      }
      if(arch.indexOf('ia32') != -1 &&
          arch.indexOf('x63') != -1) {
        cb("all");
        return;
      }
      cb(arch.join(","));
    });
  }

  let ask_platform = (cb) => {
    let choices = ['all', 'linux', 'darwin', 'win32'];
    let platform_prompt = {
      type : 'checkbox',
      name : "platforms",
      message: "Select platforms:",
      choices: choices
    }
    inquirer.prompt(platform_prompt, (response) => {
      let platforms = response.platforms;
      if(platforms.length == 0) {
        cb("all");
        return;
      }
      if(platforms.indexOf('all') != -1) {
        cb("all");
        return;
      }
      if(platforms.indexOf('linux') != -1 &&
          platforms.indexOf('darwin') != -1 &&
          platforms.indexOf('win32') != -1) {
        cb("all");
        return;
      }
      cb(platforms.join(","));
    });
  }

  let run_electron_packager = (settings) => {
    log.log("Electron packager settings:".white);
    log.log(settings);

    packager(settings, (err, appPath) => {
      if(err) {
        error(err);
        return;
      }
      log.ok("Application packaged successfuly!")
      log.log(appPath);
    });
  }

  ask_appname( (appname) => {
    settings.name = appname;
  ask_sourcedir( (src) => {
    settings.dir = src;
  ask_platform( (platforms) => {
    settings.platforms = platforms;
  ask_arch( (arch) => {
    settings.arch = arch;
  ask_electron_version( (version) => {
    settings.version = version;
  ask_out( (out) => {
    settings.out = out;
  ask_overwrite( (overwrite) => {
    settings.overwrite = overwrite;
  ask_asar( (asar) => {
    settings.asar = asar;
  ask_app_bundle_id( (bundle_id) => {
    settings["app-bundle-id"] = bundle_id;
  ask_app_version( (app_version) => {
    settings["app-version"] = app_version;

  run_electron_packager(settings);

  })})})})})})})})})}); // <- this is ugly

}
<commit_msg>set the correct platform value<commit_after>import inquirer from 'inquirer'
import semafor from 'semafor'
import glue from 'glue-path'
import packager from 'electron-packager'
import colors from 'colors'

export default function interactive(verbose = true) {

  let log = semafor();

  let default_version = "0.30.4";
  let default_src = process.cwd();
  let default_out = glue([process.cwd(), "releases"]);

  let get_package_name = () => {
    try {
      var pkg_path = glue([process.cwd(), "package.json"]);
      var pkg = require(pkg_path);
      return pkg.name;
    }catch(e){}
    return "";
  }

  let settings = {
    dir: default_src,
    name: null,
    platform: "all",
    arch: "all",
    version: default_version,
    out: default_out,
    "app-bundle-id": "",
    "app-version": "",
    overwrite: true,
    asar: false
  };

  let error = (msg) => {
    log.fail(msg.toString());
    process.exit(1);
  }

  let ask_overwrite = (cb) => {
    let overwrite_prompt = {
      type : 'confirm',
      name : "overwrite",
      message: "Overwrite output directory ?",
      default: true
    }
    inquirer.prompt(overwrite_prompt, (response) => {
      cb(response.overwrite);
    });
  }

  let ask_asar = (cb) => {
    let asar_prompt = {
      type : 'confirm',
      name : "asar",
      message: "Use asar source packaging ?",
      default: false
    }
    inquirer.prompt(asar_prompt, (response) => {
      cb(response.asar);
    });
  }

  let ask_sourcedir = (cb) => {
    let sourcedir_prompt = {
      type : 'input',
      name : "sourcedir",
      message: "Select Electron app source directory:",
      default: default_src
    }
    inquirer.prompt(sourcedir_prompt, (response) => {
      var sourcedir = response.sourcedir.trim();
      if(sourcedir == "") {
        sourcedir = default_src;
      }
      cb(sourcedir);
    });
  }

  let ask_out = (cb) => {
    let out_prompt = {
      type : 'input',
      name : "out",
      message: "Select Electron app output directory:",
      default: default_out
    }
    inquirer.prompt(out_prompt, (response) => {
      var out = response.out.trim();
      if(out == "") {
        out = default_out;
      }
      cb(out);
    });
  }

  let ask_appname = (cb) => {
    let appname_prompt = {
      type : 'input',
      name : "appname",
      message: "Select Application name:",
      default: get_package_name()
    }
    inquirer.prompt(appname_prompt, (response) => {
      var appname = response.appname.trim();
      if(appname == "") {
        error("Must provide the application name");
        return;
      }
      cb(appname);
    });
  }

  let ask_app_bundle_id = (cb) => {
    let bundle_id_prompt = {
      type : 'input',
      name : "bundle_id",
      message: "Select App Bundle Id (optional):"
    }
    inquirer.prompt(bundle_id_prompt, (response) => {
      cb(response.bundle_id);
    });
  }

  let ask_app_version = (cb) => {
    let app_version_prompt = {
      type : 'input',
      name : "app_version",
      message: "Select App Version(optional):",
      default: "0.0.1"
    }
    inquirer.prompt(app_version_prompt, (response) => {
      cb(response.app_version);
    });
  }

  let ask_electron_version = (cb) => {
    let version_prompt = {
      type : 'input',
      name : "version",
      message: "Select Electron version release:",
      default: default_version
    }
    inquirer.prompt(version_prompt, (response) => {
      var version = response.version.trim();
      if(version == "") {
        version == default_version;
      }
      cb(version);
    });
  }

  let ask_arch = (cb) => {
    let choices = ['all', 'ia32', 'x64'];
    let arch_prompt = {
      type : 'checkbox',
      name : "arch",
      message: "Select architecture:",
      choices: choices
    }
    inquirer.prompt(arch_prompt, (response) => {
      let arch = response.arch;
      if(arch.length == 0) {
        cb("all");
        return;
      }
      if(arch.indexOf('all') != -1) {
        cb("all");
        return;
      }
      if(arch.indexOf('ia32') != -1 &&
          arch.indexOf('x63') != -1) {
        cb("all");
        return;
      }
      cb(arch.join(","));
    });
  }

  let ask_platform = (cb) => {
    let choices = ['all', 'linux', 'darwin', 'win32'];
    let platform_prompt = {
      type : 'checkbox',
      name : "platforms",
      message: "Select platforms:",
      choices: choices
    }
    inquirer.prompt(platform_prompt, (response) => {
      let platforms = response.platforms;
      if(platforms.length == 0) {
        cb("all");
        return;
      }
      if(platforms.indexOf('all') != -1) {
        cb("all");
        return;
      }
      if(platforms.indexOf('linux') != -1 &&
          platforms.indexOf('darwin') != -1 &&
          platforms.indexOf('win32') != -1) {
        cb("all");
        return;
      }
      cb(platforms.join(","));
    });
  }

  let run_electron_packager = (settings) => {
    log.log("Electron packager settings:".white);
    log.log(settings);

    packager(settings, (err, appPath) => {
      if(err) {
        error(err);
        return;
      }
      log.ok("Application packaged successfuly!")
      log.log(appPath);
    });
  }

  ask_appname( (appname) => {
    settings.name = appname;
  ask_sourcedir( (src) => {
    settings.dir = src;
  ask_platform( (platforms) => {
    settings.platform = platforms;
  ask_arch( (arch) => {
    settings.arch = arch;
  ask_electron_version( (version) => {
    settings.version = version;
  ask_out( (out) => {
    settings.out = out;
  ask_overwrite( (overwrite) => {
    settings.overwrite = overwrite;
  ask_asar( (asar) => {
    settings.asar = asar;
  ask_app_bundle_id( (bundle_id) => {
    settings["app-bundle-id"] = bundle_id;
  ask_app_version( (app_version) => {
    settings["app-version"] = app_version;

  run_electron_packager(settings);

  })})})})})})})})})}); // <- this is ugly

}
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var Moment = require('moment');
var TimerMixin = require('react-native-timer-mixin');

var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  PushNotificationIOS
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  mixins: [TimerMixin],

  pressure: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];

    return {
      pressure: pressure,
      selectedBar: pressure.bar,
      minutesOfAir: pressure.minutes
    };
  },

  startTimer: function() {
    if (this.state.timerRunning) {
     AlertIOS.alert(
      'Stop the timer?',
      'Are you sure you want to stop the timer?', [
        {text: 'Yes', onPress: () => this.setState({timerRunning: false})},
        {text: 'No'}
      ])

       return;
    }

    var timeInSeconds = this.pressure().minutesOfAir * 60 * 1000;
    this.setTimeout(() => this.setState({timerRunning: false}), timeInSeconds);

    this.setState({timerRunning: true, inTime: Moment()});
  },

  getInitialState: function() {
    return {
      barPressure: '110',
      minutes: 15,
      timerRunning: false,
      inTime: null
    };
  },

  timesRunning: function(pressure) {
    if(this.state.inTime != null){
      var inTime = Moment(this.state.inTime);
      var outTime = Moment(this.state.inTime).add(pressure.minutes, 'minutes');

      var reliefAssemblyTime = Moment(outTime).subtract(15, 'minutes');
      var reliefInTime = Moment(outTime).subtract(10, 'minutes');
    }

    if(this.state.timerRunning) {
      return (
          <Text>
          <Text>Time In: {inTime.format('HH:mm')}</Text>
          <Text>Relief Assembly: {reliefAssemblyTime.format('HH:mm')}</Text>
          <Text>Relief In: {reliefInTime.format('HH:mm')}</Text>
          <Text>Time Out: {outTime.format('HH:mm')}</Text>
          </Text>
          );
    } else {
      return (<Text>Nothing to see here</Text>);
    }
  },

  render: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];
    var selectedBar = pressure.bar
    var minutesOfAir =  pressure.minutes

    return (
        <View style={[styles.background, styles.base,]}>
        <Text ></Text>
        <Text style={{fontWeight: 'bold',  textAlign: 'center', fontSize: 18}}>Enter Cylinder Pressure </Text>
        <PickerIOS
          selectedValue={this.state.barPressure}
          onValueChange={(barPressure) => this.setState({barPressure})}>
          {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
            <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
            )
          )}
        </PickerIOS>

        <Text>{selectedBar}bar</Text>
        <Text>{minutesOfAir}minutes air</Text>

        {this.timesRunning(pressure)}

        <TouchableHighlight style={styles.buttonContainer} onPress={this.startTimer}>
          <Text style={styles.button}>
            {this.state.timerRunning ? 'Stop' : 'Go!'}
          </Text>
        </TouchableHighlight>
      </View>
    );
  },
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);

var styles = ({
  base: {
    padding: 20,
  },

  background: {
    backgroundColor: '#EFEFEF',
  },

  button: {
    color: '#007aff'
  },

  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  }

});
<commit_msg>Update render variables to use the pressure function<commit_after>'use strict';

var React = require('react-native');
var Moment = require('moment');
var TimerMixin = require('react-native-timer-mixin');

var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  PushNotificationIOS
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  mixins: [TimerMixin],

  pressure: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];

    return {
      pressureData: pressure,
      selectedBar: pressure.bar,
      minutesOfAir: pressure.minutes
    };
  },

  startTimer: function() {
    if (this.state.timerRunning) {
     AlertIOS.alert(
      'Stop the timer?',
      'Are you sure you want to stop the timer?', [
        {text: 'Yes', onPress: () => this.setState({timerRunning: false})},
        {text: 'No'}
      ])

       return;
    }

    var timeInSeconds = this.pressure().minutesOfAir * 60 * 1000;
    this.setTimeout(() => this.setState({timerRunning: false}), timeInSeconds);

    this.setState({timerRunning: true, inTime: Moment()});
  },

  getInitialState: function() {
    return {
      barPressure: '110',
      minutes: 15,
      timerRunning: false,
      inTime: null
    };
  },

  timesRunning: function(pressure) {
    if(this.state.inTime != null){
      var inTime = Moment(this.state.inTime);
      var outTime = Moment(this.state.inTime).add(pressure.minutes, 'minutes');

      var reliefAssemblyTime = Moment(outTime).subtract(15, 'minutes');
      var reliefInTime = Moment(outTime).subtract(10, 'minutes');
    }

    if(this.state.timerRunning) {
      return (
          <Text>
          <Text>Time In: {inTime.format('HH:mm')}</Text>
          <Text>Relief Assembly: {reliefAssemblyTime.format('HH:mm')}</Text>
          <Text>Relief In: {reliefInTime.format('HH:mm')}</Text>
          <Text>Time Out: {outTime.format('HH:mm')}</Text>
          </Text>
          );
    } else {
      return (<Text>Nothing to see here</Text>);
    }
  },

  render: function() {
    var pressure = this.pressure().pressureData;
    var selectedBar = this.pressure().selectedBar;
    var minutesOfAir =  this.pressure().minutesOfAir;

    return (
        <View style={[styles.background, styles.base,]}>
        <Text ></Text>
        <Text style={{fontWeight: 'bold',  textAlign: 'center', fontSize: 18}}>Enter Cylinder Pressure </Text>
        <PickerIOS
          selectedValue={this.state.barPressure}
          onValueChange={(barPressure) => this.setState({barPressure})}>
          {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
            <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
            )
          )}
        </PickerIOS>

        <Text>{selectedBar}bar</Text>
        <Text>{minutesOfAir}minutes air</Text>

        {this.timesRunning(pressure)}

        <TouchableHighlight style={styles.buttonContainer} onPress={this.startTimer}>
          <Text style={styles.button}>
            {this.state.timerRunning ? 'Stop' : 'Go!'}
          </Text>
        </TouchableHighlight>
      </View>
    );
  },
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);

var styles = ({
  base: {
    padding: 20,
  },

  background: {
    backgroundColor: '#EFEFEF',
  },

  button: {
    color: '#007aff'
  },

  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  }

});
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

const STORAGE_KEY = 'restaurantsKey';

import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  TextInput,
  Navigator,
  AsyncStorage,
  TouchableOpacity,
  Image
} from 'react-native';

var Restaurant = require('./views/restaurants');
var RestaurantInfo = require('./views/restaurantInfo');
var EndPage = require('./views/endpage');
var LoadingScreen = require('./views/loadingScreen');
var ImageModal = require('./views/imageModal');

class EasyNoms extends Component {

  constructor(props) {
    super(props);
    this.state = {
      restaurants: null,
    }
  }

  renderRestaurant(route, navigator) {
    if(route.index >= this.state.restaurants.length) {
      return <EndPage/>
    };
    return(
      <Restaurant
        restaurant={this.state.restaurants[route.index]}
        index={route.index}
        navigator={navigator}
      />
    );
  }

  renderScene(route, navigator){

    switch(route.component) {
      case Restaurant:
        return this.renderRestaurant(route, navigator);
      case ImageModal:
        return <ImageModal navigator={navigator} uri={route.url}/>
      case RestaurantInfo:
        return(
          <RestaurantInfo
            restaurant={route.passProps.restaurant}
            navigator={navigator}
          /> );
      default:
        return <EndPage/>
    }
  }

  render() {
    console.log(this.state.restaurants)
    if(!this.state.restaurants) {
      return <LoadingScreen />;
    }

    return(
      <View style={styles.wrapper}>
        <Navigator
          style={styles.wrapper}
          initialRoute={{
            title: 'Easy Noms',
            component: Restaurant,
            index: 0
          }}
          renderScene={this.renderScene.bind(this)}
          configureScene={this.configScene.bind(this)}
        />
      </View>
    );
  }

  configScene(route, routeStack) {
    console.log(Navigator.SceneConfigs)
    switch(route.component) {
      case ImageModal:
        return Navigator.SceneConfigs.FloatFromBottom;
      default:
        return Navigator.SceneConfigs.FloatFromRight;
    }
  }

  getRestaurant(index) {
    if(this.state.restaurants) {
      return this.state.restaurants[index];
    };
    return null;
  }

  componentDidMount() {
    // Leave for potential caching / debuggin purposes
    AsyncStorage.getItem(STORAGE_KEY).then((value) => {
      this.setState({restaurants: JSON.parse(value)})
    })
    // Gets data based on geo coordinates
    // navigator.geolocation.getCurrentPosition(( position) => {this.fetchData(position.coords)});
  }

  fetchData({latitude, longitude}) {
    console.log(latitude);
    var promise = fetch('http://floating-hamlet-80631.heroku.com/restaurants.json?latitude=' + latitude + '&longitude=' + longitude);
    promise.then((response) => response.json()).then((restaurants) => {
        // AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(restaurants));
        this.setState({restaurants: restaurants });
    })
    .catch( (error) => console.log(error) )
    .done();
  }
}

var styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },

});

AppRegistry.registerComponent('EasyNoms', () => EasyNoms);
<commit_msg>Turn of asynchronous storage<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

const STORAGE_KEY = 'restaurantsKey';

import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  TextInput,
  Navigator,
  AsyncStorage,
  TouchableOpacity,
  Image
} from 'react-native';

var Restaurant = require('./views/restaurants');
var RestaurantInfo = require('./views/restaurantInfo');
var EndPage = require('./views/endpage');
var LoadingScreen = require('./views/loadingScreen');
var ImageModal = require('./views/imageModal');

class EasyNoms extends Component {

  constructor(props) {
    super(props);
    this.state = {
      restaurants: null,
    }
  }

  renderRestaurant(route, navigator) {
    if(route.index >= this.state.restaurants.length) {
      return <EndPage/>
    };
    return(
      <Restaurant
        restaurant={this.state.restaurants[route.index]}
        index={route.index}
        navigator={navigator}
      />
    );
  }

  renderScene(route, navigator){

    switch(route.component) {
      case Restaurant:
        return this.renderRestaurant(route, navigator);
      case ImageModal:
        return <ImageModal navigator={navigator} uri={route.url}/>
      case RestaurantInfo:
        return(
          <RestaurantInfo
            restaurant={route.passProps.restaurant}
            navigator={navigator}
          /> );
      default:
        return <EndPage/>
    }
  }

  render() {
    console.log(this.state.restaurants)
    if(!this.state.restaurants) {
      return <LoadingScreen />;
    }

    return(
      <View style={styles.wrapper}>
        <Navigator
          style={styles.wrapper}
          initialRoute={{
            title: 'Easy Noms',
            component: Restaurant,
            index: 0
          }}
          renderScene={this.renderScene.bind(this)}
          configureScene={this.configScene.bind(this)}
        />
      </View>
    );
  }

  configScene(route, routeStack) {
    console.log(Navigator.SceneConfigs)
    switch(route.component) {
      case ImageModal:
        return Navigator.SceneConfigs.FloatFromBottom;
      default:
        return Navigator.SceneConfigs.FloatFromRight;
    }
  }

  getRestaurant(index) {
    if(this.state.restaurants) {
      return this.state.restaurants[index];
    };
    return null;
  }

  componentDidMount() {
    // Leave for potential caching / debuggin purposes
    // AsyncStorage.getItem(STORAGE_KEY).then((value) => {
    //   this.setState({restaurants: JSON.parse(value)})
    // })
    // Gets data based on geo coordinates
    navigator.geolocation.getCurrentPosition(( position) => {this.fetchData(position.coords)});
  }

  fetchData({latitude, longitude}) {
    console.log(latitude);
    var promise = fetch('http://floating-hamlet-80631.heroku.com/restaurants.json?latitude=' + latitude + '&longitude=' + longitude);
    promise.then((response) => response.json()).then((restaurants) => {
        // AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(restaurants));
        this.setState({restaurants: restaurants });
    })
    .catch( (error) => console.log(error) )
    .done();
  }
}

var styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },

});

AppRegistry.registerComponent('EasyNoms', () => EasyNoms);
<|endoftext|>