<commit_before>/*global define */
define([
    'queue',
    'carve',
    'data',
    'filter',
    'hbs!templates/splititem',
    'hbs!templates/totals',
    'hbs!templates/classList',
], function (queue, carveVis, warehouse, filter, splitItemTemplate, totalsItemTemplate, classListTemplate) {
    'use strict';

    function errorMsg(msg) {
        console.error(msg);
    }

    var Application = {
        initialize: function(){
            var split_list = '#split_list',
                split_item_class = 'split_item',
                disable_class = '_disabled',
                split_item_class_disabled = split_item_class + disable_class,
                split_item = 'li.' + split_item_class,
                split_item_disabled = 'li.' + split_item_class_disabled;

           var data, data_indices;

            var keys, data, data_filter,
                labels = {"x" : "", "y" : "", list : []},
                insistCategoricalValues = { "x":  [], "y" : [] },
                group = {},
                highlight_label = null;

            function modify_data(property, arr) {
                _.each(arr, function(element) {
                    data[data_indices[element.cName]][property] = element.fValue;
                });
                set_data();
            }

            function set_cases(c_arr) {
                data_indices = {};
                data = new Array(c_arr.length);
                _.each(c_arr, function(c, index) {
                    data_indices[c.cName] = index;
                    data[index] = {id: c.cName};
                });
            }

            function set_data() {
                if (!( data.length && data[0][labels.x] && data[0][labels.y])) return;
                data_filter =  data_filter ? data_filter : filter(data);
                data_filter.addColumn(labels.x).addColumn(labels.y);
                if ( _.isString(labels.class) && !_.isUndefined(data[0][labels.class]) ) {
                   data_filter.addGroup( labels.class );
                }
            }

            function refilter() {
                var initial = {};
                _.each( data_filter.columns(), function(f) {
                    data_filter.resetFilter(f);
                    initial[f]  = {
                        "low" : -Infinity,
                        "high" : Infinity,
                        "values" : []
                        };
                    });

                var s =  _.reduce( $('li.split_item'), function ( memo, el, index) {
                    var split = warehouse.get(el).split;
                    var keys = _.keys(split);
                            return _.extend( memo , _.object(keys, _.map(keys, function(axis) {
                                if (_.isFinite(split[axis].low) ) {
                                return {
                                 low: Math.max( split[axis].low, memo[axis].low ),
                                 high: Math.min( split[axis].high, memo[axis].high )
                                };
                            } else if (_.isArray(split[axis].values)) {
                                 return {
                                 values: _.union( split[axis].values, memo[axis].values )
                                };
                            }
                            })) );
                }, initial );
                filterData(s);
            }

            function filterData(split) {
                var keys = _.keys( split );
                _.each(keys, function(axis) {
                    if (_.isFinite(split[axis].low)) {
                    data_filter.filterColumn(axis, _.map([split[axis].low, split[axis].high], parseFloat));
                } else if ( split[axis].values.length > 0) {
                    data_filter.filterColumn(axis, split[axis].values );
                }
                });
            }

            //spin up jquery hooks
             function jquery_hooks() {

                var $trash = $( '#trash, #trash i, #trash div') ;

                $('#classInfo').on('mouseover', '.classItem', function () {
                    var classLabel = $(this).attr('data-class-label');
                    $('.classItem:not([data-class-label=\"' + classLabel+'\"])').css('opacity',0.3);
                    highlight_label = classLabel;
                    carve
                        .highlight( highlight_label )
                        .render();
                });

                $('#classInfo').on('mouseout', '.classItem', function () {
                    $('.classItem').css('opacity', '');
                    highlight_label = null;
                    carve
                        .highlight('')
                        .render();
                });

                $('#switch_axes').on('click', function (e,ui) {
                    var x = $('#x_autocomplete').val();
                    $('#x_autocomplete').val( $('#y_autocomplete').val() );
                    $('#y_autocomplete').val( x );
                    labels['y'] = x;
                    labels['x'] = $('#x_autocomplete').val();
                    updateCarve();
                });

                $( split_list ).on('click', split_item, function (e,ui) {
                    $(this).removeClass(split_item_class).addClass(split_item_class_disabled);
                    refilter();
                    refreshDisplays();
                });

                $( split_list ).on('click', split_item_disabled, function (e,ui) {
                    $(this).removeClass(split_item_class_disabled).addClass(split_item_class);
                    refilter();
                    refreshDisplays();
                });

                $( split_list ).sortable({
                    placeholder: 'split_placeholder',
                    forcePlaceholderSize: true,
                    containment:'document',
                    cursor: 'move',
                    axis: 'y',
                    opacity: 0.7,
                    scroll: true,
                    scrollSensitivity: 2,
                    scrollSpeed: 20,
                    start: function(event, ui) {
                        $trash.addClass('ui-state-highlight');
                    }
                    }).disableSelection();

                // let the trash be droppable, accepting the split items
                $trash.droppable({
                  accept: split_item + ', ' + split_item_disabled,
                  hoverClass: "ui-state-highlight",
                  activeClass: "ui-state-highlight",
                  tolerance : 'pointer',
                  activate : function( event, ui ) {
                    $(this).addClass('ui-state-highlight');
                  },
                  drop: function( event, ui ) {
                    ui.draggable.fadeOut(function() {
                        ui.draggable.remove();
                        refilter();
                        refreshDisplays();
                    });
                  }
                }).disableSelection();

                queue()
                .defer(d3.json, '/query/dataset/features')
                .defer(d3.json, '/query/dataset/cases')
                .await( function(error, f, c) {
                    if (error) errorMsg(error);
                    var features = _.pluck(f,"fName");
                    $(".fetch_cases").autocomplete({
                            source: features,
                            minLength: 2,
                            delay: 200
                            });
                    set_cases(c);
                });
            }
            jquery_hooks();

    function updateSplitsTemplates() {

    }

    function updateTotalsTemplates() {
        $('#summary').html(totalsItemTemplate({
            filtered_total :  data_filter.totalSize(),
            total : data_filter.currentSize()
        }));

        var color = carve.colorFn();

        if ( data_filter.has(labels.class) ) {
            var group = _.map( data_filter.getGroupEntries( labels.class ), function(group_obj) {
                group_obj.color = color(group_obj.key);
                return group_obj;
            });

            $('#classInfo').html(classListTemplate({
                classLabel: labels.class,
                classList: group
            }));

            $('#classList').sortable({
                    placeholder: 'classItem_placeholder',
                    forcePlaceholderSize: true,
                    containment:'document',
                    cursor: 'move',
                    axis: 'y',
                    opacity: 0.7,
                    scroll: true,
                    scrollSensitivity: 2,
                    scrollSpeed: 20,
                    stop : function() {
                        labels.list = $('li.classItem').map( function (el) { return $(this).attr('data-class-label');}).get();
                        updateCarve();
                    }
                }).disableSelection();

            labels.list = $('li.classItem').map( function (el) { return $(this).attr('data-class-label');}).get();
        } else { $('#classInfo').html(""); labels.list = []; }

    }

    function setInsistCategoricalValues() {
    insistCategoricalValues = {"x" : [], "y" : []};
    if (_.intersection(data_filter.getGroupLabels(labels.x, false), ["false","true"]).length) insistCategoricalValues.x = ["false","true"];
    if (_.intersection(data_filter.getGroupLabels(labels.y, false), ["false","true"]).length) insistCategoricalValues.y = ["false","true"];
    }

    function updateCarve() {
        labels.list = labels.list.length ? labels.list : data_filter.has(labels.class) ? data_filter.getGroupLabels(labels.class) : [];
        carve
        .axisLabel(labels)
        .axisKey(labels)
        .colorBy({
            label : labels.class ? labels.class : '',
            list: labels.list,
            highlight : highlight_label
        })
        .data(data_filter.getRows())
        .render();
    }

    function newCarve() {
        setInsistCategoricalValues();

        carve
        .clear(true)
        .colorBy({
            label : labels.class ? labels.class : '',
            list : data_filter.has( labels.class ) ? data_filter.getGroupLabels( labels.class ) : []
        })
        .axisLabel(labels)
        .axisKey(labels)
        .axisInsistCategoricalValues(insistCategoricalValues)
        .axisValueDictionary( { "x" : { "true" : "true"}})
        .data(data_filter.getRows())
        .render();
    }

    function newDataDisplay() {
        if (!( data.length && data[0][labels.x] && data[0][labels.y])) return;

        if( _.isUndefined(carve)) {
            plotCarve();
            return;
        }
        newCarve();
        updateTotalsTemplates();
    }

    function refreshDisplays() {
        if (!( data.length && data[0][labels.x] && data[0][labels.y])) return;
        updateCarve();
        updateTotalsTemplates();
    }

    function selectElementHooks() {
        _.each(['x','y','class'], function(attr) {
           $('#' + attr + '_autocomplete').on('autocompleteselect', function(e, ui){
           queue()
            .defer(d3.json,'/query/dataset/mValues?feature='+ui.item.value)
            .await(function(error,f){
                modify_data( ui.item.value, f['caseValues'] );
                newDataDisplay();
            });
            labels[attr] = ui.item.value;
          });
        });

       $('#class_autocomplete_cancel').on('click', function (e, ui) {
            labels['class'] = null;
            labels['list'] = [];
            $('#class_autocomplete').val("");
            refreshDisplays();
      });
    }

    selectElementHooks();

    var carve;
    var plot_container = '#plot';
    var format = d3.format('.3f');
   function plotCarve() {
            carve = carveVis({
                radius: 8,
                margin : {
                            top: 10, left: 10, bottom: 30, right: 40
                }
            })(plot_container)
            .on('partitioncomplete',function(split_obj) {

                var keys = _.keys(split_obj);
                var splitItem = _.object(keys, _.map(keys, function( feature ){
                    if ( _.isFinite(split_obj[feature].low) ) {
                        return {
                                    label: feature,
                                    low: format(split_obj[feature].low),
                                    high: format(split_obj[feature].high)
                        };
                    } else {
                        return {
                            label: feature,
                            values: split_obj[feature].values
                        };
                    }
                }));
                   filterData(split_obj);
                   refreshDisplays();

                    var new_el = $.parseHTML( splitItemTemplate({ "splitItem" : splitItem }) )[0];
                    $( split_list ).prepend(new_el);

                    warehouse.set(new_el, {split: split_obj});
                });
            newDataDisplay();;
        };
        }
    };
    return Application;
});<commit_msg>handle empty class selection<commit_after>/*global define */
define([
    'queue',
    'carve',
    'data',
    'filter',
    'hbs!templates/splititem',
    'hbs!templates/totals',
    'hbs!templates/classList',
], function (queue, carveVis, warehouse, filter, splitItemTemplate, totalsItemTemplate, classListTemplate) {
    'use strict';

    function errorMsg(msg) {
        console.error(msg);
    }

    var Application = {
        initialize: function(){
            var split_list = '#split_list',
                split_item_class = 'split_item',
                disable_class = '_disabled',
                split_item_class_disabled = split_item_class + disable_class,
                split_item = 'li.' + split_item_class,
                split_item_disabled = 'li.' + split_item_class_disabled;

           var data, data_indices;

            var keys, data, data_filter,
                labels = {"x" : "", "y" : "", list : []},
                insistCategoricalValues = { "x":  [], "y" : [] },
                group = {},
                highlight_label = null;

            function modify_data(property, arr) {
                _.each(arr, function(element) {
                    data[data_indices[element.cName]][property] = element.fValue;
                });
                set_data();
            }

            function set_cases(c_arr) {
                data_indices = {};
                data = new Array(c_arr.length);
                _.each(c_arr, function(c, index) {
                    data_indices[c.cName] = index;
                    data[index] = {id: c.cName};
                });
            }

            function set_data() {
                if (!( data.length && data[0][labels.x] && data[0][labels.y])) return;
                data_filter =  data_filter ? data_filter : filter(data);
                data_filter.addColumn(labels.x).addColumn(labels.y);
                if ( _.isString(labels.class) && !_.isUndefined(data[0][labels.class]) ) {
                   data_filter.addGroup( labels.class );
                }
            }

            function refilter() {
                var initial = {};
                _.each( data_filter.columns(), function(f) {
                    data_filter.resetFilter(f);
                    initial[f]  = {
                        "low" : -Infinity,
                        "high" : Infinity,
                        "values" : []
                        };
                    });

                var s =  _.reduce( $('li.split_item'), function ( memo, el, index) {
                    var split = warehouse.get(el).split;
                    var keys = _.keys(split);
                            return _.extend( memo , _.object(keys, _.map(keys, function(axis) {
                                if (_.isFinite(split[axis].low) ) {
                                return {
                                 low: Math.max( split[axis].low, memo[axis].low ),
                                 high: Math.min( split[axis].high, memo[axis].high )
                                };
                            } else if (_.isArray(split[axis].values)) {
                                 return {
                                 values: _.union( split[axis].values, memo[axis].values )
                                };
                            }
                            })) );
                }, initial );
                filterData(s);
            }

            function filterData(split) {
                var keys = _.keys( split );
                _.each(keys, function(axis) {
                    if (_.isFinite(split[axis].low)) {
                    data_filter.filterColumn(axis, _.map([split[axis].low, split[axis].high], parseFloat));
                } else if ( split[axis].values.length > 0) {
                    data_filter.filterColumn(axis, split[axis].values );
                }
                });
            }

            //spin up jquery hooks
             function jquery_hooks() {

                var $trash = $( '#trash, #trash i, #trash div') ;

                $('#classInfo').on('mouseover', '.classItem', function () {
                    var classLabel = $(this).attr('data-class-label');
                    $('.classItem:not([data-class-label=\"' + classLabel+'\"])').css('opacity',0.3);
                    highlight_label = classLabel;
                    carve
                        .highlight( highlight_label )
                        .render();
                });

                $('#classInfo').on('mouseout', '.classItem', function () {
                    $('.classItem').css('opacity', '');
                    highlight_label = null;
                    carve
                        .highlight('')
                        .render();
                });

                $('#switch_axes').on('click', function (e,ui) {
                    var x = $('#x_autocomplete').val();
                    $('#x_autocomplete').val( $('#y_autocomplete').val() );
                    $('#y_autocomplete').val( x );
                    labels['y'] = x;
                    labels['x'] = $('#x_autocomplete').val();
                    updateCarve();
                });

                $( split_list ).on('click', split_item, function (e,ui) {
                    $(this).removeClass(split_item_class).addClass(split_item_class_disabled);
                    refilter();
                    refreshDisplays();
                });

                $( split_list ).on('click', split_item_disabled, function (e,ui) {
                    $(this).removeClass(split_item_class_disabled).addClass(split_item_class);
                    refilter();
                    refreshDisplays();
                });

                $( split_list ).sortable({
                    placeholder: 'split_placeholder',
                    forcePlaceholderSize: true,
                    containment:'document',
                    cursor: 'move',
                    axis: 'y',
                    opacity: 0.7,
                    scroll: true,
                    scrollSensitivity: 2,
                    scrollSpeed: 20,
                    start: function(event, ui) {
                        $trash.addClass('ui-state-highlight');
                    }
                    }).disableSelection();

                // let the trash be droppable, accepting the split items
                $trash.droppable({
                  accept: split_item + ', ' + split_item_disabled,
                  hoverClass: "ui-state-highlight",
                  activeClass: "ui-state-highlight",
                  tolerance : 'pointer',
                  activate : function( event, ui ) {
                    $(this).addClass('ui-state-highlight');
                  },
                  drop: function( event, ui ) {
                    ui.draggable.fadeOut(function() {
                        ui.draggable.remove();
                        refilter();
                        refreshDisplays();
                    });
                  }
                }).disableSelection();

                queue()
                .defer(d3.json, '/query/dataset/features')
                .defer(d3.json, '/query/dataset/cases')
                .await( function(error, f, c) {
                    if (error) errorMsg(error);
                    var features = _.pluck(f,"fName");
                    $(".fetch_cases").autocomplete({
                            source: features,
                            minLength: 2,
                            delay: 200
                            });
                    set_cases(c);
                });
            }
            jquery_hooks();

    function updateSplitsTemplates() {

    }

    function updateTotalsTemplates() {
        $('#summary').html(totalsItemTemplate({
            filtered_total :  data_filter.totalSize(),
            total : data_filter.currentSize()
        }));

        var color = carve.colorFn();

        if ( data_filter.has(labels.class) ) {
            var group = _.map( data_filter.getGroupEntries( labels.class ), function(group_obj) {
                group_obj.color = color(group_obj.key);
                return group_obj;
            });

            $('#classInfo').html(classListTemplate({
                classLabel: labels.class,
                classList: group
            }));

            $('#classList').sortable({
                    placeholder: 'classItem_placeholder',
                    forcePlaceholderSize: true,
                    containment:'document',
                    cursor: 'move',
                    axis: 'y',
                    opacity: 0.7,
                    scroll: true,
                    scrollSensitivity: 2,
                    scrollSpeed: 20,
                    stop : function() {
                        labels.list = $('li.classItem').map( function (el) { return $(this).attr('data-class-label');}).get();
                        updateCarve();
                    }
                }).disableSelection();

            labels.list = $('li.classItem').map( function (el) { return $(this).attr('data-class-label');}).get();
        } else { $('#classInfo').html(""); labels.list = []; }

    }

    function setInsistCategoricalValues() {
    insistCategoricalValues = {"x" : [], "y" : []};
    if (_.intersection(data_filter.getGroupLabels(labels.x, false), ["false","true"]).length) insistCategoricalValues.x = ["false","true"];
    if (_.intersection(data_filter.getGroupLabels(labels.y, false), ["false","true"]).length) insistCategoricalValues.y = ["false","true"];
    }

    function updateCarve() {
        if (labels.class) {
            labels.list = labels.list.length ? labels.list : data_filter.has(labels.class) ? data_filter.getGroupLabels(labels.class) : [];
        }
        else {
            labels.class = '';
            labels.list = [];
        }
        carve
        .axisLabel(labels)
        .axisKey(labels)
        .colorBy({
            label : labels.class,
            list: labels.list,
            highlight : highlight_label
        })
        .data(data_filter.getRows())
        .render();
    }

    function newCarve() {
        setInsistCategoricalValues();

        carve
        .clear(true)
        .colorBy({
            label : labels.class ? labels.class : '',
            list : data_filter.has( labels.class ) ? data_filter.getGroupLabels( labels.class ) : []
        })
        .axisLabel(labels)
        .axisKey(labels)
        .axisInsistCategoricalValues(insistCategoricalValues)
        .axisValueDictionary( { "x" : { "true" : "true"}})
        .data(data_filter.getRows())
        .render();
    }

    function newDataDisplay() {
        if (!( data.length && data[0][labels.x] && data[0][labels.y])) return;

        if( _.isUndefined(carve)) {
            plotCarve();
            return;
        }
        newCarve();
        updateTotalsTemplates();
    }

    function refreshDisplays() {
        if (!( data.length && data[0][labels.x] && data[0][labels.y])) return;
        updateCarve();
        updateTotalsTemplates();
    }

    function selectElementHooks() {
        _.each(['x','y','class'], function(attr) {
           $('#' + attr + '_autocomplete').on('autocompleteselect', function(e, ui){
           queue()
            .defer(d3.json,'/query/dataset/mValues?feature='+ui.item.value)
            .await(function(error,f){
                modify_data( ui.item.value, f['caseValues'] );
                newDataDisplay();
            });
            labels[attr] = ui.item.value;
          });
        });

       $('#class_autocomplete_cancel').on('click', function (e, ui) {
            labels['class'] = null;
            labels['list'] = [];
            $('#class_autocomplete').val("");
            refreshDisplays();
      });
    }

    selectElementHooks();

    var carve;
    var plot_container = '#plot';
    var format = d3.format('.3f');
   function plotCarve() {
            carve = carveVis({
                radius: 8,
                margin : {
                            top: 10, left: 10, bottom: 30, right: 40
                }
            })(plot_container)
            .on('partitioncomplete',function(split_obj) {

                var keys = _.keys(split_obj);
                var splitItem = _.object(keys, _.map(keys, function( feature ){
                    if ( _.isFinite(split_obj[feature].low) ) {
                        return {
                                    label: feature,
                                    low: format(split_obj[feature].low),
                                    high: format(split_obj[feature].high)
                        };
                    } else {
                        return {
                            label: feature,
                            values: split_obj[feature].values
                        };
                    }
                }));
                   filterData(split_obj);
                   refreshDisplays();

                    var new_el = $.parseHTML( splitItemTemplate({ "splitItem" : splitItem }) )[0];
                    $( split_list ).prepend(new_el);

                    warehouse.set(new_el, {split: split_obj});
                });
            newDataDisplay();;
        };
        }
    };
    return Application;
});<|endoftext|>


<commit_before>'use strict';
angular.module('confRegistrationWebApp', ['ngRoute', 'ngCookies', 'ngFacebook', 'ui.bootstrap', 'ui.sortable', 'wysiwyg.module'])
  .config(function ($routeProvider, $injector) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/landing.html',
        controller: 'landingCtrl'
      })
      .when('/register/:conferenceId', {
        resolve: {
          redirect: ['$location', '$route', function ($location, $route) {
            $location.path('/register/' + $route.current.params.conferenceId + '/page/');
          }]
        }
      })
      .when('/register/:conferenceId/page/:pageId?', {
        templateUrl: 'views/registration.html',
        controller: 'RegistrationCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          currentRegistration: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            return RegistrationCache.getCurrent($route.current.params.conferenceId);
          }]
        }
      })
      .when('/approvePayment/:paymentHash', {
        templateUrl: 'views/paymentApproval.html',
        controller: 'PaymentApprovalCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth')
        }
      })
      .when('/reviewRegistration/:conferenceId', {
        templateUrl: 'views/reviewRegistration.html',
        controller: 'ReviewRegistrationCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          registration: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            RegistrationCache.emptyCache();
            return RegistrationCache.getCurrent($route.current.params.conferenceId)
              .then(function (currentRegistration) {
                return currentRegistration;
              });
          }],
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }]
        }
      })
      .when('/preview/:conferenceId/page/:pageId?', {
        templateUrl: 'views/registration.html',
        controller: 'RegistrationCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          currentRegistration: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            return RegistrationCache.getCurrent($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventDashboard', {
        templateUrl: 'views/eventDashboard.html',
        controller: 'eventDashboardCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth')
        }
      })
      .when('/eventOverview/:conferenceId', {
        templateUrl: 'views/eventOverview.html',
        controller: 'eventOverviewCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventRegistrations/:conferenceId', {
        templateUrl: 'views/eventRegistrations.html',
        controller: 'eventRegistrationsCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          registrations: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            var visibleBlocks = localStorage.getItem('visibleBlocks:' + $route.current.params.conferenceId);
            if(!_.isNull(visibleBlocks)){
              visibleBlocks = JSON.parse(visibleBlocks);
            }
            return RegistrationCache.getAllForConference($route.current.params.conferenceId, visibleBlocks);
          }],
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventForm/:conferenceId', {
        template: '<ng-include src="templateUrl"></ng-include>',
        controller: 'eventFormCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventDetails/:conferenceId', {
        template: '<ng-include src="templateUrl"></ng-include>',
        controller: 'eventDetailsCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventUsers/:conferenceId', {
        template: '<ng-include src="templateUrl"></ng-include>',
        controller: 'eventPermissionsCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/activatePermission/:permissionAuthCode', {
        template: '{{message}}',
        controller: 'activatePermissionCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth')
        }
      })
      .when('/auth/:token', {
        resolve: {
          redirectToIntendedRoute: ['$location', '$cookies', '$route', '$rootScope', 'ProfileCache',
            function ($location, $cookies, $route, $rootScope, ProfileCache) {
              $cookies.crsAuthProviderType = '';
              if ($cookies.crsToken && ($cookies.crsToken !== $route.current.params.token)) {
                $cookies.crsPreviousToken = $cookies.crsToken;
              }
              $cookies.crsToken = $route.current.params.token;
              $rootScope.crsToken = $cookies.crsToken;
              ProfileCache.getCache(function (data) {
                $cookies.crsAuthProviderType = data.authProviderType;
                if(angular.isDefined($cookies.regType)) {
                  $location.path($cookies.intendedRoute || '/').search('regType', $cookies.regType).replace();
                  delete $cookies.regType;
                } else {
                  $location.path($cookies.intendedRoute || '/').replace();
                }
              });
            }
          ]
        }
      })
      .when('/logout/', {
        resolve: {
          redirect: ['$location', '$cookies', '$window', '$http', '$facebook',
            function ($location, $cookies, $window, $http, $facebook) {
              $http.get('auth/logout').success(function() {
                delete $cookies.crsAuthProviderType;
                delete $cookies.crsPreviousToken;
                delete $cookies.crsToken;

                /* if facebook, then use the FB JavaScript SDK to log out user from FB */
                if ($cookies.crsAuthProviderType === 'FACEBOOK') {
                  $facebook.logout().then(function () {
                    $location.url('/');
                  });
                /* if relay, then then redirect to the Relay logout URL w/ service to bring user
                 * back to ERT home page */
                } else if ($cookies.crsAuthProviderType  === 'RELAY') {
                  var serviceUrl = $location.absUrl().replace('logout', '');
                  $window.location.href = 'https://signin.cru.org/cas/logout?service=' + serviceUrl;
                /* for no auth logins, nothing further is needed, back to ERT home page */
                } else {
                  $location.url('/');
                }
              }).error(function (data, status) {
                alert('Logout failed: ' + status);
              });
            }
          ]
        }
      })
      .when('/help/', {
        templateUrl: 'views/help.html',
        controller: 'helpCtrl'
      })
      .when('/privacy/', {
        templateUrl: 'views/privacy.html',
        controller: 'helpCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .run(function ($rootScope, $cookies, $location, $window) {
    $rootScope.$on('$locationChangeStart', function () {
      //registration mode
      if (_.contains($location.path(), '/preview/')) {
        $rootScope.registerMode = 'preview';
      } else if(_.contains($location.path(), '/register/')) {
        $rootScope.registerMode = 'register';
      }
    });

    $rootScope.$on('$routeChangeSuccess', function () {
      //scroll to top of page when new page is loaded
      $window.scrollTo(0, 0);

      //Google Analytics
      $window.ga('send', 'pageview', {'page': $location.path()});
    });

    $rootScope.generateTitle = function (title) {
      if (title) {
        return title + ' | Event Registration Tool';
      } else {
        return 'Event Registration Tool';
      }
    };
  })
  .config(function ($httpProvider) {
    $httpProvider.interceptors.push('currentRegistrationInterceptor');
    $httpProvider.interceptors.push('httpUrlInterceptor');
    $httpProvider.interceptors.push('authorizationInterceptor');
    $httpProvider.interceptors.push('unauthorizedInterceptor');
    $httpProvider.interceptors.push('debouncePutsInterceptor');
    $httpProvider.interceptors.push('statusInterceptor');
  })
  .run(function () {
    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = '//connect.facebook.net/en_US/all.js';
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  })
  .config( function( $facebookProvider ) {
    $facebookProvider.setAppId('217890171695297');
  });
<commit_msg>don't delete auth provider type before checking to see which logout type is required<commit_after>'use strict';
angular.module('confRegistrationWebApp', ['ngRoute', 'ngCookies', 'ngFacebook', 'ui.bootstrap', 'ui.sortable', 'wysiwyg.module'])
  .config(function ($routeProvider, $injector) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/landing.html',
        controller: 'landingCtrl'
      })
      .when('/register/:conferenceId', {
        resolve: {
          redirect: ['$location', '$route', function ($location, $route) {
            $location.path('/register/' + $route.current.params.conferenceId + '/page/');
          }]
        }
      })
      .when('/register/:conferenceId/page/:pageId?', {
        templateUrl: 'views/registration.html',
        controller: 'RegistrationCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          currentRegistration: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            return RegistrationCache.getCurrent($route.current.params.conferenceId);
          }]
        }
      })
      .when('/approvePayment/:paymentHash', {
        templateUrl: 'views/paymentApproval.html',
        controller: 'PaymentApprovalCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth')
        }
      })
      .when('/reviewRegistration/:conferenceId', {
        templateUrl: 'views/reviewRegistration.html',
        controller: 'ReviewRegistrationCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          registration: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            RegistrationCache.emptyCache();
            return RegistrationCache.getCurrent($route.current.params.conferenceId)
              .then(function (currentRegistration) {
                return currentRegistration;
              });
          }],
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }]
        }
      })
      .when('/preview/:conferenceId/page/:pageId?', {
        templateUrl: 'views/registration.html',
        controller: 'RegistrationCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          currentRegistration: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            return RegistrationCache.getCurrent($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventDashboard', {
        templateUrl: 'views/eventDashboard.html',
        controller: 'eventDashboardCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth')
        }
      })
      .when('/eventOverview/:conferenceId', {
        templateUrl: 'views/eventOverview.html',
        controller: 'eventOverviewCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventRegistrations/:conferenceId', {
        templateUrl: 'views/eventRegistrations.html',
        controller: 'eventRegistrationsCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          registrations: ['$route', 'RegistrationCache', function ($route, RegistrationCache) {
            var visibleBlocks = localStorage.getItem('visibleBlocks:' + $route.current.params.conferenceId);
            if(!_.isNull(visibleBlocks)){
              visibleBlocks = JSON.parse(visibleBlocks);
            }
            return RegistrationCache.getAllForConference($route.current.params.conferenceId, visibleBlocks);
          }],
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventForm/:conferenceId', {
        template: '<ng-include src="templateUrl"></ng-include>',
        controller: 'eventFormCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventDetails/:conferenceId', {
        template: '<ng-include src="templateUrl"></ng-include>',
        controller: 'eventDetailsCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/eventUsers/:conferenceId', {
        template: '<ng-include src="templateUrl"></ng-include>',
        controller: 'eventPermissionsCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth'),
          conference: ['$route', 'ConfCache', function ($route, ConfCache) {
            return ConfCache.get($route.current.params.conferenceId);
          }],
          permissions: ['$route', 'PermissionCache', function ($route, PermissionCache) {
            return PermissionCache.getForConference($route.current.params.conferenceId);
          }]
        }
      })
      .when('/activatePermission/:permissionAuthCode', {
        template: '{{message}}',
        controller: 'activatePermissionCtrl',
        resolve: {
          enforceAuth: $injector.get('enforceAuth')
        }
      })
      .when('/auth/:token', {
        resolve: {
          redirectToIntendedRoute: ['$location', '$cookies', '$route', '$rootScope', 'ProfileCache',
            function ($location, $cookies, $route, $rootScope, ProfileCache) {
              $cookies.crsAuthProviderType = '';
              if ($cookies.crsToken && ($cookies.crsToken !== $route.current.params.token)) {
                $cookies.crsPreviousToken = $cookies.crsToken;
              }
              $cookies.crsToken = $route.current.params.token;
              $rootScope.crsToken = $cookies.crsToken;
              ProfileCache.getCache(function (data) {
                $cookies.crsAuthProviderType = data.authProviderType;
                if(angular.isDefined($cookies.regType)) {
                  $location.path($cookies.intendedRoute || '/').search('regType', $cookies.regType).replace();
                  delete $cookies.regType;
                } else {
                  $location.path($cookies.intendedRoute || '/').replace();
                }
              });
            }
          ]
        }
      })
      .when('/logout/', {
        resolve: {
          redirect: ['$location', '$cookies', '$window', '$http', '$facebook',
            function ($location, $cookies, $window, $http, $facebook) {
              $http.get('auth/logout').success(function() {
                delete $cookies.crsPreviousToken;
                delete $cookies.crsToken;

                /* if facebook, then use the FB JavaScript SDK to log out user from FB */
                if ($cookies.crsAuthProviderType === 'FACEBOOK') {
                  $facebook.logout().then(function () {
                    delete $cookies.crsAuthProviderType;
                    $location.url('/');
                  });
                /* if relay, then then redirect to the Relay logout URL w/ service to bring user
                 * back to ERT home page */
                } else if ($cookies.crsAuthProviderType  === 'RELAY') {
                  delete $cookies.crsAuthProviderType;
                  var serviceUrl = $location.absUrl().replace('logout', '');
                  $window.location.href = 'https://signin.cru.org/cas/logout?service=' + serviceUrl;
                /* for no auth logins, nothing further is needed, back to ERT home page */
                } else {
                  delete $cookies.crsAuthProviderType;
                  $location.url('/');
                }
              }).error(function (data, status) {
                alert('Logout failed: ' + status);
              });
            }
          ]
        }
      })
      .when('/help/', {
        templateUrl: 'views/help.html',
        controller: 'helpCtrl'
      })
      .when('/privacy/', {
        templateUrl: 'views/privacy.html',
        controller: 'helpCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .run(function ($rootScope, $cookies, $location, $window) {
    $rootScope.$on('$locationChangeStart', function () {
      //registration mode
      if (_.contains($location.path(), '/preview/')) {
        $rootScope.registerMode = 'preview';
      } else if(_.contains($location.path(), '/register/')) {
        $rootScope.registerMode = 'register';
      }
    });

    $rootScope.$on('$routeChangeSuccess', function () {
      //scroll to top of page when new page is loaded
      $window.scrollTo(0, 0);

      //Google Analytics
      $window.ga('send', 'pageview', {'page': $location.path()});
    });

    $rootScope.generateTitle = function (title) {
      if (title) {
        return title + ' | Event Registration Tool';
      } else {
        return 'Event Registration Tool';
      }
    };
  })
  .config(function ($httpProvider) {
    $httpProvider.interceptors.push('currentRegistrationInterceptor');
    $httpProvider.interceptors.push('httpUrlInterceptor');
    $httpProvider.interceptors.push('authorizationInterceptor');
    $httpProvider.interceptors.push('unauthorizedInterceptor');
    $httpProvider.interceptors.push('debouncePutsInterceptor');
    $httpProvider.interceptors.push('statusInterceptor');
  })
  .run(function () {
    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = '//connect.facebook.net/en_US/all.js';
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  })
  .config( function( $facebookProvider ) {
    $facebookProvider.setAppId('217890171695297');
  });
<|endoftext|>


<commit_before>'use strict';

angular.module('geboClientApp', ['ngResource'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/token', {
        templateUrl: 'views/token.html',
        controller: 'MainCtrl'
      })
      .when('/app', {
        templateUrl: 'views/app.html',
        controller: 'AppCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

<commit_msg>Get ui-router states<commit_after>'use strict';

angular.module('geboClientApp', ['ngResource', 'ui.bootstrap', 'ui.compat'])
    .config(function($stateProvider, $urlRouterProvider) {

        // For an unmatched URL
        $urlRouterProvider.otherwise('/');

        // States
        $stateProvider.
            state('home', {
                url: '/',
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            }).
            state('token', {
                url: '/token',
                templateUrl: 'views/token.html',
                controller: 'MainCtrl'
            }).
            state('app', {
                url: '/app',
                templateUrl: 'views/app.html',
                controller: 'AppCtrl'
            }).
            state('app.lists', {
                templateUrl: 'views/app.lists.html'
            });

     });
//  .config(function ($routeProvider) {
//    $routeProvider
//      .when('/', {
//        templateUrl: 'views/main.html',
//        controller: 'MainCtrl'
//      })
//      .when('/token', {
//        templateUrl: 'views/token.html',
//        controller: 'MainCtrl'
//      })
//      .when('/app', {
//        templateUrl: 'views/app.html',
//        controller: 'AppCtrl'
//      })
//      .otherwise({
//        redirectTo: '/'
//      });
//  });

<|endoftext|>


<commit_before>'use strict';

angular.module('Lunch', ['ionic',  'openfb', 'push', 'Lunch.profile', 'Lunch.browse', 'Lunch.nomatches', 'Lunch.noshow', 'Lunch.chats', 'Lunch.login','Lunch.factory.Geo', 'Lunch.factory.localStore','Lunch.factory.storedUserData', 'Lunch.factory.matchData', 'Lunch.service.storedChat'])

.config(function($provide, $stateProvider, $urlRouterProvider) {
  // Set application server
  // TODO: Change this to your production server
  $provide.constant('fbAPI', '765912086774968');
  $provide.constant('gcmAPI', '142933827745');
  $provide.constant('AppServer', 'http://127.0.0.1:8008');

  // Set initial paths
  $stateProvider
  .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html'
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/profile');
})

.run(function($ionicPlatform, $rootScope, $state, $window, OpenFB, push, fbAPI, gcmAPI) {
  $ionicPlatform.ready(function() {
    if(window.StatusBar) {
      window.StatusBar.styleDefault();
    }
  });

  // Initialize with localhost to support development
  // (cordova will default to https://www.facebook.com/)
  OpenFB.init(fbAPI, 'http://localhost:9000/oauth.html');
  push.init(gcmAPI);

  // Force authentication
  $rootScope.$on('$stateChangeStart', function(e, state) {
    if ($window.sessionStorage['fbtoken']) {
      if (state.name === 'app.login') {
        $state.go('app.profile');
        e.preventDefault();
      }
    } else {
      if (state.name !== 'app.login') {
        $state.go('app.login');
        e.preventDefault();
      }
    }
  });

  // Catch oAuth2 exceptions
  $rootScope.$on('OAuthException', function() {
    $state.go('app.login');
  });
});
<commit_msg>Changed window to \$window in app.js<commit_after>'use strict';

angular.module('Lunch', ['ionic',  'openfb', 'push', 'Lunch.profile', 'Lunch.browse', 'Lunch.nomatches', 'Lunch.noshow', 'Lunch.chats', 'Lunch.login','Lunch.factory.Geo', 'Lunch.factory.localStore','Lunch.factory.storedUserData', 'Lunch.factory.matchData', 'Lunch.service.storedChat'])

.config(function($provide, $stateProvider, $urlRouterProvider) {
  // Set application server
  // TODO: Change this to your production server
  $provide.constant('fbAPI', '765912086774968');
  $provide.constant('gcmAPI', '142933827745');
  $provide.constant('AppServer', 'http://127.0.0.1:8008');

  // Set initial paths
  $stateProvider
  .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html'
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/profile');
})

.run(function($ionicPlatform, $rootScope, $state, $window, OpenFB, push, fbAPI, gcmAPI) {
  $ionicPlatform.ready(function() {
    if($window.StatusBar) {
      $window.StatusBar.styleDefault();
    }
  });

  // Initialize with localhost to support development
  // (cordova will default to https://www.facebook.com/)
  OpenFB.init(fbAPI, 'http://localhost:9000/oauth.html');
  push.init(gcmAPI);

  // Force authentication
  $rootScope.$on('$stateChangeStart', function(e, state) {
    if ($window.sessionStorage['fbtoken']) {
      if (state.name === 'app.login') {
        $state.go('app.profile');
        e.preventDefault();
      }
    } else {
      if (state.name !== 'app.login') {
        $state.go('app.login');
        e.preventDefault();
      }
    }
  });

  // Catch oAuth2 exceptions
  $rootScope.$on('OAuthException', function() {
    $state.go('app.login');
  });
});
<|endoftext|>


<commit_before>'use strict';

var app = angular.module('2048App', ['Game', 'Grid']);

// Game Controller
app.controller('GameController', ['GameManager', 'GridManager', function(GameManager, GridManager) {
  this.game = GameManager;
  this.grid = GridManager;
}]);<commit_msg>Create newGame method within GameController.<commit_after>'use strict';

var app = angular.module('2048App', ['Game', 'Grid']);

// Game Controller
app.controller('GameController', ['GameManager', 'GridManager', function(GameManager, GridManager) {
  this.game = GameManager;
  this.grid = GridManager;

  this.newGame = function() {
    this.game.newGame();
  };

  this.newGame();
}]);<|endoftext|>


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

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    document.querySelector('#caching-complete').show();
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {
    console.log('Our app is ready to rock!');

    var user = this.user;
    var userID = user.uid;

    var properties = {
      id: userID,
      name: 'User Name',
      email: 'user@email.com',
      other: user
      // other properties ...
    };

    _gs('identify', userID, properties);
  });

  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  // Close drawer after menu item is selected if drawerPanel is narrow
  app.onMenuSelect = function() {
    var drawerPanel = document.querySelector('#paperDrawerPanel');
    if (drawerPanel.narrow) {
      drawerPanel.closeDrawer();
    }
  };
  //<!--  Go Squared  -->
  !function(g,s,q,r,d){r=g[r]=g[r]||function(){(r.q=r.q||[]).push(
  arguments)};d=s.createElement(q);q=s.getElementsByTagName(q)[0];
  d.src='//d1l6p2sc9645hc.cloudfront.net/tracker.js';q.parentNode.
  insertBefore(d,q)}(window,document,'script','_gs');

  _gs('GSN-963825-Q');
  //<!--  End of Go Squared  -->

  //<!-- Start of hi9support Zendesk Widget script -->
  window.zEmbed||function(e,t){var n,o,d,i,s,a=[],r=document.createElement("iframe");window.zEmbed=function(){a.push(arguments)},window.zE=window.zE||window.zEmbed,r.src="javascript:false",r.title="",r.role="presentation",(r.frameElement||r).style.cssText="display: none",d=document.getElementsByTagName("script"),d=d[d.length-1],d.parentNode.insertBefore(r,d),i=r.contentWindow,s=i.document;try{o=s}catch(c){n=document.domain,r.src='javascript:var d=document.open();d.domain="'+n+'";void(0);',o=s}o.open()._l=function(){var o=this.createElement("script");n&&(this.domain=n),o.id="js-iframe-async",o.src=e,this.t=+new Date,this.zendeskHost=t,this.zEQueue=a,this.body.appendChild(o)},o.write('<body onload="document._l();">'),o.close()}("https://assets.zendesk.com/embeddable_framework/main.js","hi9support.zendesk.com");
  //<!-- End of hi9support Zendesk Widget script -->

})(document);
<commit_msg>Update app.js<commit_after>(function(document) {
  'use strict';

  // Grab a reference to our auto-binding template
  // and give it some initial binding values
  // Learn more about auto-binding templates at http://goo.gl/Dx1u2g
  var app = document.querySelector('#app');

  app.displayInstalledToast = function() {
    document.querySelector('#caching-complete').show();
  };

  // Listen for template bound event to know when bindings
  // have resolved and content has been stamped to the page
  app.addEventListener('dom-change', function() {
    console.log('Our app is ready to rock!');
  });

  app.userUpdate = function (user) {
    var user = this.user;
    var userID = user.uid;

    var properties = {
      id: userID,
      name: 'User Name',
      email: 'user@email.com',
      other: user
      // other properties ...
    };

    _gs('identify', userID, properties);

  };

  app.properties = {
    highlight: {
      observer: 'userUpdate(user)'
    }
  }
  // See https://github.com/Polymer/polymer/issues/1381
  window.addEventListener('WebComponentsReady', function() {
    // imports are loaded and elements have been registered
  });

  // Close drawer after menu item is selected if drawerPanel is narrow
  app.onMenuSelect = function() {
    var drawerPanel = document.querySelector('#paperDrawerPanel');
    if (drawerPanel.narrow) {
      drawerPanel.closeDrawer();
    }
  };
  //<!--  Go Squared  -->
  !function(g,s,q,r,d){r=g[r]=g[r]||function(){(r.q=r.q||[]).push(
  arguments)};d=s.createElement(q);q=s.getElementsByTagName(q)[0];
  d.src='//d1l6p2sc9645hc.cloudfront.net/tracker.js';q.parentNode.
  insertBefore(d,q)}(window,document,'script','_gs');

  _gs('GSN-963825-Q');
  //<!--  End of Go Squared  -->

  //<!-- Start of hi9support Zendesk Widget script -->
  window.zEmbed||function(e,t){var n,o,d,i,s,a=[],r=document.createElement("iframe");window.zEmbed=function(){a.push(arguments)},window.zE=window.zE||window.zEmbed,r.src="javascript:false",r.title="",r.role="presentation",(r.frameElement||r).style.cssText="display: none",d=document.getElementsByTagName("script"),d=d[d.length-1],d.parentNode.insertBefore(r,d),i=r.contentWindow,s=i.document;try{o=s}catch(c){n=document.domain,r.src='javascript:var d=document.open();d.domain="'+n+'";void(0);',o=s}o.open()._l=function(){var o=this.createElement("script");n&&(this.domain=n),o.id="js-iframe-async",o.src=e,this.t=+new Date,this.zendeskHost=t,this.zEQueue=a,this.body.appendChild(o)},o.write('<body onload="document._l();">'),o.close()}("https://assets.zendesk.com/embeddable_framework/main.js","hi9support.zendesk.com");
  //<!-- End of hi9support Zendesk Widget script -->

})(document);
<|endoftext|>


<commit_before>/* eslint-disable no-empty */
import path from 'path';
import fse from 'fs-extra';
import get from 'lodash/get';
import has from 'lodash/has';
import pick from 'lodash/pick';
import isPlainObject from 'lodash/isPlainObject';
import invariant from 'invariant';
import identity from 'lodash/identity';
import { Module } from 'oors';
import { PubSub } from 'graphql-subscriptions';
import merge from 'lodash/merge';
import {
  makeExecutableSchema,
  makeRemoteExecutableSchema,
  mergeSchemas,
  addResolveFunctionsToSchema,
  addSchemaLevelResolveFunction,
} from 'graphql-tools';
import { express as voyagerMiddleware } from 'graphql-voyager/middleware';
import { importSchema } from 'graphql-import';
import { Binding } from 'graphql-binding';
import mainResolvers from './graphql/resolvers';
import modulesResolvers from './graphql/modulesResolvers';
import LoadersMap from './libs/LoadersMap';
import * as decorators from './decorators';
import Server from './libs/Server';

class Gql extends Module {
  static schema = {
    type: 'object',
    properties: {
      voyager: {
        type: 'object',
        properties: {
          enabled: {
            type: 'boolean',
            default: true,
          },
          params: {
            type: 'object',
            properties: {
              endpointURL: {
                type: 'string',
                default: '/graphql',
              },
            },
            default: {},
          },
        },
        default: {},
      },
      middlewarePivot: {
        type: 'string',
        default: 'isMethod',
      },
      configureSchema: {
        instanceof: 'Function',
      },
      exposeModules: {
        type: 'boolean',
        default: true,
      },
      serverOptions: {
        type: 'object',
        default: {},
      },
      pubsub: {
        type: 'object',
      },
    },
  };

  name = 'oors.graphQL';

  initialize() {
    this.typeDefs = [];
    this.resolvers = mainResolvers;
    this.resolverMiddlewares = [];
    this.pubsub = this.getConfig('pubsub', new PubSub());
    this.gqlContext = {
      pubsub: this.pubsub,
    };
    this.loaders = new LoadersMap();
    this.contextExtenders = [];
    this.formatters = {
      params: [],
      error: [],
      response: [],
    };
  }

  async setup() {
    await this.runHook(
      'load',
      this.collectFromModule,
      pick(this, [
        'pubsub',
        'addTypeDefs',
        'addTypeDefsByPath',
        'addResolvers',
        'addResolverMiddleware',
        'addLoader',
      ]),
    );

    if (this.getConfig('exposeModules')) {
      this.addResolvers(modulesResolvers);
      await this.addTypeDefsByPath(path.resolve(__dirname, './graphql/modulesTypeDefs.graphql'));
    }

    await this.runHook('buildContext', () => {}, {
      context: this.gqlContext,
    });

    this.schema = await this.buildSchema();
    this.server = this.buildServer();

    this.applyMiddlewares(this.server);

    const binding = this.bindSchema(this.schema);

    this.exportProperties([
      'extendContext',
      'schema',
      'server',
      'loaders',
      'addResolverMiddleware',
      'addLoader',
      'addLoaders',
      'addResolvers',
      'importSchema',
      'bindSchema',
      'binding',
      'setupListen',
      'pubsub',
      'formatters',
    ]);

    this.export({
      context: this.gqlContext,
      addSchemaResolvers: rootResolveFunction =>
        addSchemaLevelResolveFunction(this.schema, rootResolveFunction),
    });

    this.on('after:setup', () => {
      Object.assign(this.gqlContext, {
        binding,
      });
    });
  }

  extendContext = extender => {
    invariant(
      typeof extender === 'function' || isPlainObject(extender),
      'Invalid context extender! Needs to be either a function or a an object that will get assigned to the context.',
    );
    this.contextExtenders.push(extender);
    return this.contextExtenders;
  };

  bindSchema = (schema, options = {}) =>
    new Binding({
      schema,
      ...options,
    });

  addTypeDefs = typeDefs => {
    this.typeDefs.push(typeDefs);
  };

  addResolvers = resolvers => {
    if (this.schema) {
      addResolveFunctionsToSchema({ schema: this.schema, resolvers });
    } else {
      merge(this.resolvers, resolvers);
    }
  };

  addResolverMiddleware = (matcher, middleware) => {
    this.resolverMiddlewares.push({
      matcher: typeof matcher === 'string' ? new RegExp(`^${matcher}$`) : matcher,
      middleware,
    });

    return this;
  };

  addLoader = (...args) => {
    this.loaders.add(...args);
  };

  addLoaders = (...args) => {
    this.loaders.multiAdd(...args);
  };

  addTypeDefsByPath = async filePath => {
    this.addTypeDefs(await fse.readFile(filePath, 'utf8'));
  };

  importSchema = schemaPath => {
    this.addTypeDefs(importSchema(schemaPath));
  };

  async loadFromDir(dirPath) {
    try {
      const stat = await fse.stat(dirPath);
      const isDirectory = stat && stat.isDirectory();
      if (!isDirectory) {
        return;
      }
    } catch (err) {
      return;
    }

    try {
      await this.addTypeDefsByPath(path.join(dirPath, 'typeDefs.graphql'));
    } catch (err) {}

    try {
      // eslint-disable-next-line import/no-dynamic-require, global-require
      const resolvers = require(`${dirPath}/resolvers`);
      if (resolvers.default) {
        Object.assign(resolvers, resolvers.default);
        delete resolvers.default;
      }
      this.addResolvers(resolvers);
    } catch (err) {}
  }

  collectFromModule = async module => {
    if (!module.getConfig('graphql.autoload', true)) {
      return;
    }

    try {
      if (has(module, 'graphql')) {
        this.addTypeDefs(get(module, 'graphql.typeDefs', ''));
        this.addResolvers(get(module, 'graphql.resolvers', {}));
        if (has(module, 'graphql.typeDefsPath')) {
          await this.addTypeDefsByPath(get(module, 'graphql.typeDefsPath'));
        }
      } else {
        await this.loadFromDir(path.resolve(path.dirname(module.filePath), 'graphql'));
      }
    } catch (err) {}
  };

  buildSchema = async () => {
    const schema = makeExecutableSchema(
      this.getConfig('configureSchema', identity)({
        typeDefs: this.typeDefs,
        resolvers: this.applyResolversMiddlewares(this.resolvers),
        logger: {
          log: err => {
            this.emit('error', err);
          },
        },
        allowUndefinedInResolve: false,
      }),
    );

    const schemas = (await this.runHook('getSchema', () => {}, {
      schema,
      mergeSchemas,
      makeExecutableSchema,
      makeRemoteExecutableSchema,
    })).filter(s => s);

    return schemas.length
      ? mergeSchemas({
          schemas: [schema, ...schemas],
        })
      : schema;
  };

  buildServer = (options = {}) => {
    const config = {
      context: this.buildContext,
      formatError: this.format('error'),
      formatParams: this.format('params'),
      formatResponse: this.format('response'),
      schema: this.schema,
      debug: true,
      tracing: true,
      cacheControl: true,
      subscriptions: true,
      introspection: true,
      mocks: false,
      persistedQueries: true,
      ...this.getConfig('serverOptions'),
      ...options,
    };

    const server = new Server(config);

    if (config.subscriptions) {
      server.installSubscriptionHandlers(this.app.server);
    }

    return server;
  };

  buildContext = async ({ req, connection }) => {
    const context = {
      app: this.app,
      ...this.gqlContext,
      loaders: this.loaders.build(),
    };

    if (req) {
      Object.assign(context, {
        ...this.contextExtenders.reduce(
          (acc, extender) => ({
            ...acc,
            ...(typeof extender === 'function'
              ? extender({ req, connection }, this.context)
              : extender),
          }),
          {},
        ),
        req,
        user: req.user,
      });
    } else {
      Object.assign(context, {
        connection,
      });
    }

    return context;
  };

  applyResolversMiddlewares(resolvers) {
    if (!this.resolverMiddlewares.length) {
      return resolvers;
    }

    return Object.keys(resolvers).reduce(
      (resolversAcc, type) => ({
        ...resolversAcc,
        [type]: Object.keys(resolvers[type]).reduce((typeAcc, field) => {
          let resolver = resolvers[type][field];
          const branch = `${type}.${field}`;
          const middlewares = this.resolverMiddlewares.filter(({ matcher }) =>
            matcher.test(branch),
          );

          if (middlewares.length) {
            resolver = [...middlewares]
              .reverse()
              .reduce((acc, { middleware }) => (...args) => middleware(...args, acc), resolver);
          }

          return {
            ...typeAcc,
            [field]: resolver,
          };
        }, {}),
      }),
      {},
    );
  }

  applyMiddlewares(server) {
    this.app.middlewares.insertBefore(
      this.getConfig('middlewarePivot'),
      this.getApolloServerMiddlewares(server),
      this.getVoyagerMiddleware(),
    );
  }

  // eslint-disable-next-line class-methods-use-this
  getApolloServerMiddlewares(server) {
    return {
      id: 'apolloServer',
      apply: ({ app }) => {
        server.applyMiddleware({
          app,
          cors: false,
          bodyParserConfig: false,
          onHealthCheck: req => this.asyncEmit('healthCheck', req),
        });
      },
    };
  }

  getVoyagerMiddleware() {
    return {
      id: 'voyager',
      path: '/voyager',
      factory: ({ endpointURL }) => voyagerMiddleware({ endpointUrl: endpointURL }),
      params: this.getConfig('voyager.params'),
      enabled: this.getConfig('voyager.enabled'),
    };
  }

  format = type => {
    invariant(Array.isArray(this.formatters[type]), `Unknown formatter type - ${type}!`);
    return arg => this.formatters[type].reduce((acc, formatter) => formatter(acc), arg);
  };
}

export { Gql as default, decorators };
export { default as Resolvers } from './libs/Resolvers';
<commit_msg>[oors-graphq] temporary fix for playground's cursor issue<commit_after>/* eslint-disable no-empty */
import path from 'path';
import fse from 'fs-extra';
import get from 'lodash/get';
import has from 'lodash/has';
import pick from 'lodash/pick';
import isPlainObject from 'lodash/isPlainObject';
import invariant from 'invariant';
import identity from 'lodash/identity';
import { Module } from 'oors';
import { PubSub } from 'graphql-subscriptions';
import merge from 'lodash/merge';
import {
  makeExecutableSchema,
  makeRemoteExecutableSchema,
  mergeSchemas,
  addResolveFunctionsToSchema,
  addSchemaLevelResolveFunction,
} from 'graphql-tools';
import { express as voyagerMiddleware } from 'graphql-voyager/middleware';
import { importSchema } from 'graphql-import';
import { Binding } from 'graphql-binding';
import mainResolvers from './graphql/resolvers';
import modulesResolvers from './graphql/modulesResolvers';
import LoadersMap from './libs/LoadersMap';
import * as decorators from './decorators';
import Server from './libs/Server';

class Gql extends Module {
  static schema = {
    type: 'object',
    properties: {
      voyager: {
        type: 'object',
        properties: {
          enabled: {
            type: 'boolean',
            default: true,
          },
          params: {
            type: 'object',
            properties: {
              endpointURL: {
                type: 'string',
                default: '/graphql',
              },
            },
            default: {},
          },
        },
        default: {},
      },
      middlewarePivot: {
        type: 'string',
        default: 'isMethod',
      },
      configureSchema: {
        instanceof: 'Function',
      },
      exposeModules: {
        type: 'boolean',
        default: true,
      },
      serverOptions: {
        type: 'object',
        default: {},
      },
      pubsub: {
        type: 'object',
      },
    },
  };

  name = 'oors.graphQL';

  initialize() {
    this.typeDefs = [];
    this.resolvers = mainResolvers;
    this.resolverMiddlewares = [];
    this.pubsub = this.getConfig('pubsub', new PubSub());
    this.gqlContext = {
      pubsub: this.pubsub,
    };
    this.loaders = new LoadersMap();
    this.contextExtenders = [];
    this.formatters = {
      params: [],
      error: [],
      response: [],
    };
  }

  async setup() {
    await this.runHook(
      'load',
      this.collectFromModule,
      pick(this, [
        'pubsub',
        'addTypeDefs',
        'addTypeDefsByPath',
        'addResolvers',
        'addResolverMiddleware',
        'addLoader',
      ]),
    );

    if (this.getConfig('exposeModules')) {
      this.addResolvers(modulesResolvers);
      await this.addTypeDefsByPath(path.resolve(__dirname, './graphql/modulesTypeDefs.graphql'));
    }

    await this.runHook('buildContext', () => {}, {
      context: this.gqlContext,
    });

    this.schema = await this.buildSchema();
    this.server = this.buildServer();

    this.applyMiddlewares(this.server);

    const binding = this.bindSchema(this.schema);

    this.exportProperties([
      'extendContext',
      'schema',
      'server',
      'loaders',
      'addResolverMiddleware',
      'addLoader',
      'addLoaders',
      'addResolvers',
      'importSchema',
      'bindSchema',
      'binding',
      'setupListen',
      'pubsub',
      'formatters',
    ]);

    this.export({
      context: this.gqlContext,
      addSchemaResolvers: rootResolveFunction =>
        addSchemaLevelResolveFunction(this.schema, rootResolveFunction),
    });

    this.on('after:setup', () => {
      Object.assign(this.gqlContext, {
        binding,
      });
    });
  }

  extendContext = extender => {
    invariant(
      typeof extender === 'function' || isPlainObject(extender),
      'Invalid context extender! Needs to be either a function or a an object that will get assigned to the context.',
    );
    this.contextExtenders.push(extender);
    return this.contextExtenders;
  };

  bindSchema = (schema, options = {}) =>
    new Binding({
      schema,
      ...options,
    });

  addTypeDefs = typeDefs => {
    this.typeDefs.push(typeDefs);
  };

  addResolvers = resolvers => {
    if (this.schema) {
      addResolveFunctionsToSchema({ schema: this.schema, resolvers });
    } else {
      merge(this.resolvers, resolvers);
    }
  };

  addResolverMiddleware = (matcher, middleware) => {
    this.resolverMiddlewares.push({
      matcher: typeof matcher === 'string' ? new RegExp(`^${matcher}$`) : matcher,
      middleware,
    });

    return this;
  };

  addLoader = (...args) => {
    this.loaders.add(...args);
  };

  addLoaders = (...args) => {
    this.loaders.multiAdd(...args);
  };

  addTypeDefsByPath = async filePath => {
    this.addTypeDefs(await fse.readFile(filePath, 'utf8'));
  };

  importSchema = schemaPath => {
    this.addTypeDefs(importSchema(schemaPath));
  };

  async loadFromDir(dirPath) {
    try {
      const stat = await fse.stat(dirPath);
      const isDirectory = stat && stat.isDirectory();
      if (!isDirectory) {
        return;
      }
    } catch (err) {
      return;
    }

    try {
      await this.addTypeDefsByPath(path.join(dirPath, 'typeDefs.graphql'));
    } catch (err) {}

    try {
      // eslint-disable-next-line import/no-dynamic-require, global-require
      const resolvers = require(`${dirPath}/resolvers`);
      if (resolvers.default) {
        Object.assign(resolvers, resolvers.default);
        delete resolvers.default;
      }
      this.addResolvers(resolvers);
    } catch (err) {}
  }

  collectFromModule = async module => {
    if (!module.getConfig('graphql.autoload', true)) {
      return;
    }

    try {
      if (has(module, 'graphql')) {
        this.addTypeDefs(get(module, 'graphql.typeDefs', ''));
        this.addResolvers(get(module, 'graphql.resolvers', {}));
        if (has(module, 'graphql.typeDefsPath')) {
          await this.addTypeDefsByPath(get(module, 'graphql.typeDefsPath'));
        }
      } else {
        await this.loadFromDir(path.resolve(path.dirname(module.filePath), 'graphql'));
      }
    } catch (err) {}
  };

  buildSchema = async () => {
    const schema = makeExecutableSchema(
      this.getConfig('configureSchema', identity)({
        typeDefs: this.typeDefs,
        resolvers: this.applyResolversMiddlewares(this.resolvers),
        logger: {
          log: err => {
            this.emit('error', err);
          },
        },
        allowUndefinedInResolve: false,
      }),
    );

    const schemas = (await this.runHook('getSchema', () => {}, {
      schema,
      mergeSchemas,
      makeExecutableSchema,
      makeRemoteExecutableSchema,
    })).filter(s => s);

    return schemas.length
      ? mergeSchemas({
          schemas: [schema, ...schemas],
        })
      : schema;
  };

  buildServer = (options = {}) => {
    const config = {
      context: this.buildContext,
      formatError: this.format('error'),
      formatParams: this.format('params'),
      formatResponse: this.format('response'),
      schema: this.schema,
      debug: true,
      tracing: true,
      cacheControl: true,
      subscriptions: true,
      introspection: true,
      mocks: false,
      persistedQueries: true,
      playground: {
        settings: {
          'editor.cursorShape': 'line',
        },
      },
      ...this.getConfig('serverOptions'),
      ...options,
    };

    const server = new Server(config);

    if (config.subscriptions) {
      server.installSubscriptionHandlers(this.app.server);
    }

    return server;
  };

  buildContext = async ({ req, connection }) => {
    const context = {
      app: this.app,
      ...this.gqlContext,
      loaders: this.loaders.build(),
    };

    if (req) {
      Object.assign(context, {
        ...this.contextExtenders.reduce(
          (acc, extender) => ({
            ...acc,
            ...(typeof extender === 'function'
              ? extender({ req, connection }, this.context)
              : extender),
          }),
          {},
        ),
        req,
        user: req.user,
      });
    } else {
      Object.assign(context, {
        connection,
      });
    }

    return context;
  };

  applyResolversMiddlewares(resolvers) {
    if (!this.resolverMiddlewares.length) {
      return resolvers;
    }

    return Object.keys(resolvers).reduce(
      (resolversAcc, type) => ({
        ...resolversAcc,
        [type]: Object.keys(resolvers[type]).reduce((typeAcc, field) => {
          let resolver = resolvers[type][field];
          const branch = `${type}.${field}`;
          const middlewares = this.resolverMiddlewares.filter(({ matcher }) =>
            matcher.test(branch),
          );

          if (middlewares.length) {
            resolver = [...middlewares]
              .reverse()
              .reduce((acc, { middleware }) => (...args) => middleware(...args, acc), resolver);
          }

          return {
            ...typeAcc,
            [field]: resolver,
          };
        }, {}),
      }),
      {},
    );
  }

  applyMiddlewares(server) {
    this.app.middlewares.insertBefore(
      this.getConfig('middlewarePivot'),
      this.getApolloServerMiddlewares(server),
      this.getVoyagerMiddleware(),
    );
  }

  // eslint-disable-next-line class-methods-use-this
  getApolloServerMiddlewares(server) {
    return {
      id: 'apolloServer',
      apply: ({ app }) => {
        server.applyMiddleware({
          app,
          cors: false,
          bodyParserConfig: false,
          onHealthCheck: req => this.asyncEmit('healthCheck', req),
        });
      },
    };
  }

  getVoyagerMiddleware() {
    return {
      id: 'voyager',
      path: '/voyager',
      factory: ({ endpointURL }) => voyagerMiddleware({ endpointUrl: endpointURL }),
      params: this.getConfig('voyager.params'),
      enabled: this.getConfig('voyager.enabled'),
    };
  }

  format = type => {
    invariant(Array.isArray(this.formatters[type]), `Unknown formatter type - ${type}!`);
    return arg => this.formatters[type].reduce((acc, formatter) => formatter(acc), arg);
  };
}

export { Gql as default, decorators };
export { default as Resolvers } from './libs/Resolvers';
<|endoftext|>


<commit_before>define(
['jquery', 'pos', 'stem'], function(jquery, pos, stem) {
    var jQuery = jquery,
        Pos = pos,
        Stemmer = stem;

    var _DB_NAME = 'rei_toei';
    return {
        responsePlugins: [],
        sessionStorage: {},
        storage: window.localStorage,

        getFactoid: function(query) {
            var key = jQuery.trim(query.toLowerCase());
            console.log("Looking for a factoid called: " + key);
            var value = this.storage.getItem("factoid." + key);
            return value;
        },
        putFactoid: function(key, value) {
            key = jQuery.trim(key.toLowerCase());
            console.log("Learning that '" + key + "' is '" + value + "'");
            this.storage.setItem("factoid." + key, value);
        },
        dumpFactoids: function() {
            var data = {};
        console.log("dumpFactoids");
            for (i = 0; i <= this.storage.length - 1; i++) {
                console.log("I is "+i);
                key = this.storage.key(i);
                console.log("key is "+key);
                if ( res = key.match(/^factoid\.(.*)$/)) {
                    console.log("Grabbing "+key);
                    data[res[1]] = this.storage.getItem(key);
                }
            }
            return data;
        },

        initializePlugins: function(pluginNames) {
            var that = this;

            // Walk through the list of plugins passed in and load it into
            // memory. Add it to the list of plugins we can use
            //
            // TODO: hook an 'init' method in the plugins
            jQuery.each(pluginNames, function(index, name) {
                requirejs([name],

                function(plugin) {
                    that.responsePlugins.push(plugin);
                    console.log("Loaded plugin: " + name);
                });

            });
        },
        initialize: function(pluginNames) {
            this.initializePlugins(pluginNames);
        },

        handleQuery: function(input) {
            var that = this;
            var responses = {};
            var tokens = new Pos.Lexer().lex(input);
            var tags = new Pos.Tagger().tag(tokens);

            jQuery.each(tags, function(idx, tag) {
                // stem each token in the list of token+POS
                // and add the stem to the end of the list
                // yielding [token, POS, stem]
                tag.push(Stemmer.stem(tag[0]));
            });

            var args = {
                rawInput: input,
                tokens: tags,
                jQuery: jQuery,
                sessionStorage: that.sessionStorage,
                persistentStorage: that.storage
            };
            console.log(args);

            jQuery.each(that.responsePlugins, function(index, plugin) {
                console.log("Asking " + plugin.name + " about " + input);
                responses[plugin.name] = plugin.reply(args);
            });
            return responses;
        }
    }
});
<commit_msg>add the concept of a "best" response to rei's loop<commit_after>define(
['jquery', 'pos', 'stem'], function(jquery, pos, stem) {
    var jQuery = jquery,
        Pos = pos,
        Stemmer = stem;

    var _DB_NAME = 'rei_toei';
    return {
        responsePlugins: [],
        sessionStorage: {},
        storage: window.localStorage,

        getFactoid: function(query) {
            var key = jQuery.trim(query.toLowerCase());
            console.log("Looking for a factoid called: " + key);
            var value = this.storage.getItem("factoid." + key);
            return value;
        },
        putFactoid: function(key, value) {
            key = jQuery.trim(key.toLowerCase());
            console.log("Learning that '" + key + "' is '" + value + "'");
            this.storage.setItem("factoid." + key, value);
        },
        dumpFactoids: function() {
            var data = {};
        console.log("dumpFactoids");
            for (i = 0; i <= this.storage.length - 1; i++) {
                console.log("I is "+i);
                key = this.storage.key(i);
                console.log("key is "+key);
                if ( res = key.match(/^factoid\.(.*)$/)) {
                    console.log("Grabbing "+key);
                    data[res[1]] = this.storage.getItem(key);
                }
            }
            return data;
        },

        initializePlugins: function(pluginNames) {
            var that = this;

            // Walk through the list of plugins passed in and load it into
            // memory. Add it to the list of plugins we can use
            //
            // TODO: hook an 'init' method in the plugins
            jQuery.each(pluginNames, function(index, name) {
                requirejs([name],

                function(plugin) {
                    that.responsePlugins.push(plugin);
                    console.log("Loaded plugin: " + name);
                });

            });
        },
        initialize: function(pluginNames) {
            this.initializePlugins(pluginNames);
        },

        handleQuery: function(input) {
            var that = this;
            var responses = {};
            var tokens = new Pos.Lexer().lex(input);
            var tags = new Pos.Tagger().tag(tokens);

            jQuery.each(tags, function(idx, tag) {
                // stem each token in the list of token+POS
                // and add the stem to the end of the list
                // yielding [token, POS, stem]
                tag.push(Stemmer.stem(tag[0]));
            });

            var args = {
                rawInput: input,
                tokens: tags,
                jQuery: jQuery,
                sessionStorage: that.sessionStorage,
                persistentStorage: that.storage
            };
            console.log(args);

            var bestResponse;
            jQuery.each(that.responsePlugins, function(index, plugin) {
                console.log("Asking " + plugin.name + " about " + input);
                var thisResponse = plugin.reply(args);
                responses[plugin.name] = thisResponse;
                if (!bestResponse || thisResponse[0] > bestResponse[0]) {
                    bestResponse = thisResponse;
                }
            });
            return { responses: responses, bestResponse: bestResponse };
        }
    }
});
<|endoftext|>


<commit_before>angular.module('Ventolone.routing', [
  'ngRouting',
  'Ventolone.resources.services',
  'Ventolone.configuration'
])
  .config(function($locationProvider) {
    $locationProvider.html5Mode(true);
  })
  .config(function(routingProvider, configuration) {
    var resolve = {
      anemometer: function(anemometerService, $route, $rootScope, $location, $q) {
        var anemometerId = $route.current.pathParams.anemometerId
        return $q.when(anemometerDeferred = anemometerService.findById(anemometerId)).then(function(anemometer) {
          $rootScope.anemometer = anemometer
          return anemometer
        }, function() {
          $location.path($rootScope.h.anemometersRoute())
        })
      }
    }

    routingProvider.viewTemplate = configuration.static_path + routingProvider.viewTemplate,

    routingProvider
      .withResolve(resolve)
      .build([{
        model: 'anemometer',
        actions: ['upload']
      }])
      .when('/', {
        redirectTo: '/anemometers'
      })
  })
  .run(function($rootScope, routing) {
    $rootScope.h = routing.helpers
    $rootScope.$on('$locationChangeStart', function() {
      $rootScope.anemometer = null
    })
  })
<commit_msg>fixing new controller<commit_after>angular.module('Ventolone.routing', [
  'ngRouting',
  'Ventolone.resources.services',
  'Ventolone.configuration'
])
  .config(function($locationProvider) {
    $locationProvider.html5Mode(true);
  })
  .config(function(routingProvider, configuration) {
    var resolve = {
      anemometer: function(anemometerService, $route, $rootScope, $location, $q) {
        var anemometerId = $route.current.pathParams.anemometerId

        if ("NewAnemometerCtrl" == $route.current.controller) return {}

        return anemometerService.findById(anemometerId).then(function(anemometer) {
          $rootScope.anemometer = anemometer
          return anemometer
        }, function() {
          $location.path($rootScope.h.anemometersRoute())
        })
      }
    }

    routingProvider.viewTemplate = configuration.static_path + routingProvider.viewTemplate,

    routingProvider
      .withResolve(resolve)
      .build([{
        model: 'anemometer',
        actions: ['upload']
      }])
      .when('/', {
        redirectTo: '/anemometers'
      })
  })
  .run(function($rootScope, routing) {
    $rootScope.h = routing.helpers
    $rootScope.$on('$locationChangeStart', function() {
      $rootScope.anemometer = null
    })
  })
<|endoftext|>


<commit_before>import { createStore, applyMiddleware } from 'redux';

import reducer from '../reducers';
import middleware from './middleware';

// Compose createStore in applyMiddleware w/ middleware...
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);

// Given initialState, return a single store for Provider...
export default function getStore(initialState = {}) {
  const store = createStoreWithMiddleware(reducer, initialState);

  return store;
}
<commit_msg>Enable hmr for reducers<commit_after>import { createStore, applyMiddleware } from 'redux';

import reducer from '../reducers';
import middleware from './middleware';

// Compose createStore in applyMiddleware w/ middleware...
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);

// Given initialState, return a single store for Provider...
export default function getStore(initialState = {}) {
  const store = createStoreWithMiddleware(reducer, initialState);

  if (module.hot) {
    // Enable hot module replacement for reducers
    module.hot.accept(() => {
      const nextRootReducer = require('../reducers').default;
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}
<|endoftext|>