<commit_before>'use strict';

/* Directives */

angular.module('visualizeApp.directives', [])//.
  // directive('appVersion', ['version', function(version) {
    // return function(scope, elm, attrs) {
      // elm.text(version);
    // };
  // }]);
<commit_msg>added ngWebgl directive to replace threeService<commit_after>'use strict';

/* Directives */

var app_directives = angular.module('visualizeApp.directives', [])//.
// directive('appVersion', ['version', function(version) {
// return function(scope, elm, attrs) {
  // elm.text(version);
// };
// }]);

app_directives.directive('ngWebgl',function () {
    return {
      restrict: 'A',
      scope: {
        'width': '=',
        'height': '=',
        'fillcontainer': '=',
        'scale': '=',
        'materialType': '='
      },
    link: function postLink(scope, element, attrs) {

        var container;
        var tooltip;

        var controls,
        scene,
        camera,
        renderer,
        projector,
        geometry,
        material,
        cube;

        var tracing_template;
        var objects = [],plane;
        var color = new THREE.Color("rgb(42,42,42)");

        var mouse = new THREE.Vector2(),
        offset = new THREE.Vector3(),
        INTERSECTED, SELECTED;

        // Initializes threeJS stuff
        scope.init = function ( ) {

            scene = new THREE.Scene();
            camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            renderer = new THREE.WebGLRenderer( {alpha: true});
            projector = new THREE.Projector();

            container = document.createElement('div');

            document.body.appendChild(container);

            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setClearColor( color, 1);
            container.appendChild(renderer.domElement);
            camera.position.z = 50;

            controls = new THREE.TrackballControls(camera, container);
            controls.rotateSpeed = 1.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;
            controls.noZoom = false;
            controls.noPan = false;
            controls.staticMoving = true;
            controls.dynamicDampingFactor = 0.3;

            plane = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000, 8, 8), new THREE.MeshBasicMaterial({
                        color : 0x000000,
                        opacity : 0.25,
                        transparent : true,
                        wireframe : true
                    }));
            plane.visible = false;
            scene.add(plane);

            renderer.domElement.addEventListener('mousemove', onDocumentMouseMove, false);
            renderer.domElement.addEventListener('mousedown', onDocumentMouseDown, false);
            renderer.domElement.addEventListener('mouseup', onDocumentMouseUp, false);

            window.addEventListener('resize', onWindowResize, false);
        }(this);

        // Changes the active tracing template.
        threeService.set_tracing_template = function (tracing_template_name) {

             // Each template has a constructor function called template_constructor
            $.getScript( "js/tracing_templates/"+tracing_template_name+".js", function(script) {
               tracing_template = template_constructor;
            });
        };

        // Adds a tracing to the scene by combining a set of data with a corresponding tracing template
        threeService.add_tracing = function (queryresult) {
             queryresult.data.forEach(function(result_chunk){
                result_chunk.forEach(function(trace_chunk){
                    var trace_properties = trace_chunk.data;
                    var trace = tracing_template(trace_properties);
                    objects.push(trace);
                    scene.add(trace);
                });
            });
            threeService.animate();
        };

        // **** Helper Functions***

        // Clear the scene geometry
        threeService.clear_scene = function () {
            objects.forEach(function(object){
                scene.remove(object);
            });
        };

        // Animate the scene
        threeService.animate = function () {
            controls.update();
            requestAnimationFrame(threeService.animate);

             objects.forEach(function(object){
                object.animate();
            });

            renderer.render(scene, camera);
        };

        threeService.display_tooltip = function(text, location){
            tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.innerHTML = text;
            tooltip.style.top = location.y + 'px';
            tooltip.style.left = location.x + 'px';
            document.body.appendChild(tooltip);
        }

        threeService.hide_tooltip = function(){
            if (tooltip != undefined){
                document.body.removeChild(tooltip);
                console.log("removed");
            }
        }

        // **** ThreeJS Helper Functions***
        // BORROWED FROM: http://mrdoob.github.io/three.js/examples/webgl_interactive_draggablecubes.html

        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );
        }

        function onDocumentMouseMove( event ) {
            event.preventDefault();

            mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
            mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

            var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
            projector.unprojectVector( vector, camera );
            var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

            if ( SELECTED ) {

                var intersects = raycaster.intersectObject( plane );
                SELECTED.position.copy( intersects[ 0 ].point.sub( offset ) );
                return;
            }

            var intersects = raycaster.intersectObjects( objects );

            if ( intersects.length > 0 ) {
                if ( INTERSECTED != intersects[ 0 ].object ) {
                    if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

                    INTERSECTED = intersects[ 0 ].object;
                    INTERSECTED.currentHex = INTERSECTED.material.color.getHex();

                    plane.position.copy( INTERSECTED.position );
                    plane.lookAt( camera.position );
                }

                container.style.cursor = 'pointer';
            } else {

                if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
                INTERSECTED = null;
                container.style.cursor = 'auto';
            }
        }

        function onDocumentMouseDown( event ) {

            event.preventDefault();

            var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
            projector.unprojectVector( vector, camera );

            var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

            var intersects = raycaster.intersectObjects( objects );

            if ( intersects.length > 0 ) {
                controls.enabled = false;
                SELECTED = intersects[ 0 ].object;
                var intersects = raycaster.intersectObject( plane );
                offset.copy( intersects[ 0 ].point ).sub( plane.position );
                container.style.cursor = 'move';
            }

        }

        function onDocumentMouseUp( event ) {

            event.preventDefault();
            controls.enabled = true;

            if ( INTERSECTED ) {
                plane.position.copy( INTERSECTED.position );
                SELECTED = null;

                // Find location on canvas and show tweet as overlay
                var pos = toXYCoords(INTERSECTED.position);
                var text = INTERSECTED.get_metadata();
                threeService.hide_tooltip();
                threeService.display_tooltip(text, pos);
            }

            container.style.cursor = 'auto';
        }

        // Projects 3D position to x,y position on canvas
        var toXYCoords = function (pos) {
            var vector = projector.projectVector(pos.clone(), camera);
            vector.x = (vector.x + 1)/2 * window.innerWidth;
            vector.y = -(vector.y - 1)/2 * window.innerHeight;
            return vector;
        }

    }
});
<|endoftext|>


<commit_before>/*
    Use to fix hidden section headers behind the navbar when using links with targets
    See: http://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header
*/
$(function() {
  $('a[href*=#]:not([href=#])').on('click', function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {

      //var target = $('a.headerlink[href="#'+this.hash+'"]');

      var target = $(this.hash);

      target = target.length ? target : $('a.headerlink[href="#' + this.hash.slice(1) +'""]');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 60 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('a.headerlink[href="#'+location.href.split("#")[1]+'"]');

      //var target = $('#'+location.href.split("#")[1]);

      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 60 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});<commit_msg>Reverted some jQuery to fix problems were code was performing consistently across browsers and servers. [ref #1520]<commit_after>/*
    Use to fix hidden section headers behind the navbar when using links with targets
    See: http://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header
*/
$(function() {
  $('a[href*=#]:not([href=#])').on('click', function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('a.headerlink[href="#' + this.hash.slice(1) +'""]');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 60 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('#'+location.href.split("#")[1]);
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 60 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});<|endoftext|>


<commit_before>'use strict';
/* Directives */
angular.module('KMC.directives', ['colorpicker.module'])
    .directive('timeago', [function() {
        return {
            scope: {timestamp: '@'},
            restrict: 'C',
            link: function(scope, iElement, iAttrs) {
                if (typeof $.timeago == 'function')
                    scope.$watch('timestamp', function(newVal, oldVal) {
                            if (newVal) {
                                var date = scope.timestamp * 1000;
                                iElement.text($.timeago(date));
                            }
                        }
                    )

            }
        }
    }])
    .directive('menuHead', ['menuSvc', '$compile', function(menuSvc, $compile) {
        return {
            restrict: 'E',
            template: "

",
            replace: true,
            link: function(scope, iElement, iAttrs) {
                var ul = iElement.find('ul');
                var elements = menuSvc.get();
                angular.forEach(elements, function(value, key) {
                    var elm = angular.element('

');
                    elm.html('');
                    elm.on('click', function() {
                        menuSvc.setMenu(value.model);
                    });
                    $compile(elm)(scope).appendTo(ul);

                })
            }
        }
    }])
    .directive('navmenu', ["$compile", '$parse', 'menuSvc' , function($compile, $parse, menuSvc) {
        return  {
            template: "" +
                "
" +
                "
" +
                "

" +
                "
" +
                "
" +
                "",
            replace: true,
            restrict: 'E',
            transclude: true,
            controller: function($scope, $element, $attrs) {
                var BaseData = $attrs['data'];
                var menuObj = menuSvc.get();
                var menuList = $element.find('ul[ng-transclude]:first');
                angular.forEach(menuObj, function(value, key) {
                    menuSvc.renderMenuItems(value, menuList, BaseData, $scope);
                });

            }, link: function($scope, $element, $attrs) {
                //open first level
                $element.find('#mp-base >ul > li > div.mp-level').addClass('mp-level-open');
            }
        }
    }]).
    directive('menuLevel', ['menuSvc', function(menuSvc) {
        return  {
            template: "
" +
                "{{label}}" +
                "
" +
                "Back" +
                "
{{label}}
" +
                "{{description}}" +
                "

" +
                "
" +
                "
",
            replace: true,
            restrict: 'E',
            controller: function($scope, $element) {
                $scope.goBack = function() {
                    $scope.isOnTop = false;
                }
                $scope.openLevel = function(arg) {
                    if (typeof arg == 'undefined')
                        $scope.isOnTop = true;

                    else {
                        if (arg == $scope.pagename) {
                            $scope.isOnTop = true;
                        }
                        else {
                            $scope.isOnTop = false;
                        }
                    }
                }
                $scope.isOnTop = false;
                $scope.$on('menuChange', function(event, arg) {
                    $scope.openLevel(arg);
                });
                $scope.$watch('isOnTop', function(newVal, oldVal) {
                    if (newVal != oldVal) {
                        if (newVal) { // open
                            $element.parents('.mp-level:first').addClass('mp-level-in-stack');
                            $element.children('.mp-level').addClass('mp-level-open');
                        }
                        else { //close
                            $element.find('.mp-level').removeClass('mp-level-open');
                            $element.parents('.mp-level').removeClass('mp-level-in-stack');
                        }
                    }
                });
            },
            scope: {
                'label': '@',
                'pagename': '@',
                'description': '@'
            },
            transclude: 'true'
        };
    }])
    .directive('modelColor',function() {
        return  {
            restrict: 'E',
            replace: true,
            scope: {
                class: '@',
                label: '@',
                model: '='
            },
            template: '{{label}} \n\
                                <input colorpicker class="colorinput {{class}}" type="text" ng-model="model" />\n\
                                \n\
                            '
        };
    }).directive('modelText',function() {
        return {
            replace: true,
            restrict: 'E',
            scope: {
                label: "@",
                model: "=",
                icon: '@'
            },
            template: "" +
                "<input class='form-control' tooltip-placement='right' tooltip='{{label}}' type='text' ng-model='model'/>"        };
    }).directive('modelSelect',function() {
        return {
            replace: true,
            restrict: 'E',
            scope: {
                label: "@",
                model: "=",
                initvalue: '@',
                selectOpts: '@'
            },
            link: function($scope, $element, $attrs) {
                if (typeof $attrs.options != 'undefined') {
                    $scope.options = JSON.parse($attrs.options);
                }
            },
            controller: function($scope, $element, $attrs) {
                $scope.options = [];
                if ($scope.model == '' || typeof $scope.model == 'undefined') {
                    $scope.model = $attrs.initvalue;
                }

                this.setOptions = function(optsArr) {
                    $scope.options = optsArr;

                }
            },

            template: '{{label}}' +
                '<select ui-select2="selectOpts" ng-model="model" ng-options="item.value as item.label for item in options"> ' +
                '</select>'
        }
    }
).
    directive('modelChecbox',function() {
        return  {
            template: '{{label}}' +
                '
' +
                '<input type="checkbox" class="pretty-checkable" ng-model="model">' +
                '' +
                '
',
            replace: true,
            restrict: 'E',
            scope: {
                label: '@',
                model: '='
            },
            link: function(scope, iElement, iAttrs) {
                var input = iElement.find('input').hide();
                input.on('change', function() {
                    $(iElement).find('a').toggleClass('checked');
                });
                iElement.on('click', 'a', function(e) {
                    e.preventDefault();
                    input.trigger('click');
                    return false;
                })
            }
        };
    }).directive('modelNumber', function() {
        return{
            templateUrl: 'template/spinedit/spinedit.html',
            replace: true,
            restrict: 'EA',
            scope: {
                model: '=',
                from: '@',
                to: '@',
                label: '@',
                stepsize: '@',
                initvalue: '@',
                numberofdecimals: '@'
            },
            link: function($scope, $element, $attrs) {

                var $spinner = $element.find('input').spinedit({
                    minimum: parseInt($scope.from),
                    maximum: parseInt($scope.to),
                    step: parseInt($scope.stepsize),
                    value: parseInt($scope.initvalue),
                    numberOfDecimals: parseInt($scope.numberofdecimals)
                });
                $spinner.on("valueChanged", function(e) {
                    if (typeof e.value == 'number') {
                        $scope.$apply(function() {
                            $scope.model = e.value;
                        });
                    }

                });
            },
            controller: function($scope, $element, $attrs) {
                if (!$attrs.from) $scope.from = 0;
                else $scope.from = $attrs.from;
                if (!$attrs.to) $scope.to = 10;
                $scope.to = $attrs.to;
                if (!$attrs.stepsize) $scope.stepsize = 1;
                $scope.stepsize = $attrs.stepsize;
                if (!$attrs.numberofdecimals) $scope.numberofdecimals = 0;
                $scope.numberofdecimals = $attrs.numberofdecimals;
                if (typeof $scope.model != 'undefined') {
                    $scope.initvalue = $scope.model;
                } else {
                    if (!$attrs['default']) $scope.initvalue = 1;
                    else  $scope.initvalue = $attrs['default'];
                }

            }
        }
    })
    .directive('loadingWidget', ['requestNotificationChannel', function(requestNotificationChannel) {
        return {
            restrict: "E",
            scope: {},
            replace: true,
            template: "

",
            controller: function($scope, $element) {
                $scope.spinner = null;
                $scope.spinRunning = false;
                $scope.opts = {
                    lines: 15, // The number of lines to draw
                    length: 27, // The length of each line
                    width: 8, // The line thickness
                    radius: 60, // The radius of the inner circle
                    corners: 1, // Corner roundness (0..1)
                    rotate: 0, // The rotation offset
                    direction: 1, // 1: clockwise, -1: counterclockwise
                    color: '#000', // #rgb or #rrggbb or array of colors
                    speed: 0.6, // Rounds per second
                    trail: 24, // Afterglow percentage
                    shadow: true, // Whether to render a shadow
                    hwaccel: true, // Whether to use hardware acceleration
                    className: 'spinner', // The CSS class to assign to the spinner
                    zIndex: 2e9, // The z-index (defaults to 2000000000)
                    top: 'auto', // Top position relative to parent in px
                    left: 'auto' // Left position relative to parent in px
                };
                var initSpin = function() {
                    $scope.spinner = new Spinner($scope.opts).spin();
                }
                $scope.endSpin = function() {
                    if ($scope.spinner)
                        $scope.spinner.stop();
                    $scope.spinRunning = false;
                }
                $scope.spin = function() {
                    if ($scope.spinRunning) return;
                    var target = $element.find('#spinWrapper');
                    if ($scope.spinner == null)
                        initSpin();
                    $scope.spinner.spin(target[0]);
                    $scope.spinRunning = true;
                }
            },
            link: function(scope, element) {
                // hide the element initially
                element.hide();

                var startRequestHandler = function() {
                    // got the request start notification, show the element
                    element.show();
                    scope.spin();
                };

                var endRequestHandler = function() {
                    // got the request start notification, show the element
                    element.hide();
                    scope.endSpin();
                };

                requestNotificationChannel.onRequestStarted(scope, startRequestHandler);

                requestNotificationChannel.onRequestEnded(scope, endRequestHandler);
            }
        };
    }]).directive('onFinishRender', ["$timeout", 'requestNotificationChannel', function($timeout, requestNotificationChannel) {
        return {
            restrict: 'A',
            controller: function() {
                requestNotificationChannel.requestStarted('list');
            },
            link: function(scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function() {
                        requestNotificationChannel.requestEnded('list');
                    });
                }
            }
        };
    }
    ]
    ).directive('submitOnEnter',function(){
        return {
            link:function(scope,element){
                element.on('keypress')
            }
        }
    })
<commit_msg>oups that was not needed<commit_after>'use strict';
/* Directives */
angular.module('KMC.directives', ['colorpicker.module'])
    .directive('timeago', [function() {
        return {
            scope: {timestamp: '@'},
            restrict: 'C',
            link: function(scope, iElement, iAttrs) {
                if (typeof $.timeago == 'function')
                    scope.$watch('timestamp', function(newVal, oldVal) {
                            if (newVal) {
                                var date = scope.timestamp * 1000;
                                iElement.text($.timeago(date));
                            }
                        }
                    )

            }
        }
    }])
    .directive('menuHead', ['menuSvc', '$compile', function(menuSvc, $compile) {
        return {
            restrict: 'E',
            template: "

",
            replace: true,
            link: function(scope, iElement, iAttrs) {
                var ul = iElement.find('ul');
                var elements = menuSvc.get();
                angular.forEach(elements, function(value, key) {
                    var elm = angular.element('

');
                    elm.html('');
                    elm.on('click', function() {
                        menuSvc.setMenu(value.model);
                    });
                    $compile(elm)(scope).appendTo(ul);

                })
            }
        }
    }])
    .directive('navmenu', ["$compile", '$parse', 'menuSvc' , function($compile, $parse, menuSvc) {
        return  {
            template: "" +
                "
" +
                "
" +
                "

" +
                "
" +
                "
" +
                "",
            replace: true,
            restrict: 'E',
            transclude: true,
            controller: function($scope, $element, $attrs) {
                var BaseData = $attrs['data'];
                var menuObj = menuSvc.get();
                var menuList = $element.find('ul[ng-transclude]:first');
                angular.forEach(menuObj, function(value, key) {
                    menuSvc.renderMenuItems(value, menuList, BaseData, $scope);
                });

            }, link: function($scope, $element, $attrs) {
                //open first level
                $element.find('#mp-base >ul > li > div.mp-level').addClass('mp-level-open');
            }
        }
    }]).
    directive('menuLevel', ['menuSvc', function(menuSvc) {
        return  {
            template: "
" +
                "{{label}}" +
                "
" +
                "Back" +
                "
{{label}}
" +
                "{{description}}" +
                "

" +
                "
" +
                "
",
            replace: true,
            restrict: 'E',
            controller: function($scope, $element) {
                $scope.goBack = function() {
                    $scope.isOnTop = false;
                }
                $scope.openLevel = function(arg) {
                    if (typeof arg == 'undefined')
                        $scope.isOnTop = true;

                    else {
                        if (arg == $scope.pagename) {
                            $scope.isOnTop = true;
                        }
                        else {
                            $scope.isOnTop = false;
                        }
                    }
                }
                $scope.isOnTop = false;
                $scope.$on('menuChange', function(event, arg) {
                    $scope.openLevel(arg);
                });
                $scope.$watch('isOnTop', function(newVal, oldVal) {
                    if (newVal != oldVal) {
                        if (newVal) { // open
                            $element.parents('.mp-level:first').addClass('mp-level-in-stack');
                            $element.children('.mp-level').addClass('mp-level-open');
                        }
                        else { //close
                            $element.find('.mp-level').removeClass('mp-level-open');
                            $element.parents('.mp-level').removeClass('mp-level-in-stack');
                        }
                    }
                });
            },
            scope: {
                'label': '@',
                'pagename': '@',
                'description': '@'
            },
            transclude: 'true'
        };
    }])
    .directive('modelColor',function() {
        return  {
            restrict: 'E',
            replace: true,
            scope: {
                class: '@',
                label: '@',
                model: '='
            },
            template: '{{label}} \n\
                                <input colorpicker class="colorinput {{class}}" type="text" ng-model="model" />\n\
                                \n\
                            '
        };
    }).directive('modelText',function() {
        return {
            replace: true,
            restrict: 'E',
            scope: {
                label: "@",
                model: "=",
                icon: '@'
            },
            template: "" +
                "<input class='form-control' tooltip-placement='right' tooltip='{{label}}' type='text' ng-model='model'/>"        };
    }).directive('modelSelect',function() {
        return {
            replace: true,
            restrict: 'E',
            scope: {
                label: "@",
                model: "=",
                initvalue: '@',
                selectOpts: '@'
            },
            link: function($scope, $element, $attrs) {
                if (typeof $attrs.options != 'undefined') {
                    $scope.options = JSON.parse($attrs.options);
                }
            },
            controller: function($scope, $element, $attrs) {
                $scope.options = [];
                if ($scope.model == '' || typeof $scope.model == 'undefined') {
                    $scope.model = $attrs.initvalue;
                }

                this.setOptions = function(optsArr) {
                    $scope.options = optsArr;

                }
            },

            template: '{{label}}' +
                '<select ui-select2="selectOpts" ng-model="model" ng-options="item.value as item.label for item in options"> ' +
                '</select>'
        }
    }
).
    directive('modelChecbox',function() {
        return  {
            template: '{{label}}' +
                '
' +
                '<input type="checkbox" class="pretty-checkable" ng-model="model">' +
                '' +
                '
',
            replace: true,
            restrict: 'E',
            scope: {
                label: '@',
                model: '='
            },
            link: function(scope, iElement, iAttrs) {
                var input = iElement.find('input').hide();
                input.on('change', function() {
                    $(iElement).find('a').toggleClass('checked');
                });
                iElement.on('click', 'a', function(e) {
                    e.preventDefault();
                    input.trigger('click');
                    return false;
                })
            }
        };
    }).directive('modelNumber', function() {
        return{
            templateUrl: 'template/spinedit/spinedit.html',
            replace: true,
            restrict: 'EA',
            scope: {
                model: '=',
                from: '@',
                to: '@',
                label: '@',
                stepsize: '@',
                initvalue: '@',
                numberofdecimals: '@'
            },
            link: function($scope, $element, $attrs) {

                var $spinner = $element.find('input').spinedit({
                    minimum: parseInt($scope.from),
                    maximum: parseInt($scope.to),
                    step: parseInt($scope.stepsize),
                    value: parseInt($scope.initvalue),
                    numberOfDecimals: parseInt($scope.numberofdecimals)
                });
                $spinner.on("valueChanged", function(e) {
                    if (typeof e.value == 'number') {
                        $scope.$apply(function() {
                            $scope.model = e.value;
                        });
                    }

                });
            },
            controller: function($scope, $element, $attrs) {
                if (!$attrs.from) $scope.from = 0;
                else $scope.from = $attrs.from;
                if (!$attrs.to) $scope.to = 10;
                $scope.to = $attrs.to;
                if (!$attrs.stepsize) $scope.stepsize = 1;
                $scope.stepsize = $attrs.stepsize;
                if (!$attrs.numberofdecimals) $scope.numberofdecimals = 0;
                $scope.numberofdecimals = $attrs.numberofdecimals;
                if (typeof $scope.model != 'undefined') {
                    $scope.initvalue = $scope.model;
                } else {
                    if (!$attrs['default']) $scope.initvalue = 1;
                    else  $scope.initvalue = $attrs['default'];
                }

            }
        }
    })
    .directive('loadingWidget', ['requestNotificationChannel', function(requestNotificationChannel) {
        return {
            restrict: "E",
            scope: {},
            replace: true,
            template: "

",
            controller: function($scope, $element) {
                $scope.spinner = null;
                $scope.spinRunning = false;
                $scope.opts = {
                    lines: 15, // The number of lines to draw
                    length: 27, // The length of each line
                    width: 8, // The line thickness
                    radius: 60, // The radius of the inner circle
                    corners: 1, // Corner roundness (0..1)
                    rotate: 0, // The rotation offset
                    direction: 1, // 1: clockwise, -1: counterclockwise
                    color: '#000', // #rgb or #rrggbb or array of colors
                    speed: 0.6, // Rounds per second
                    trail: 24, // Afterglow percentage
                    shadow: true, // Whether to render a shadow
                    hwaccel: true, // Whether to use hardware acceleration
                    className: 'spinner', // The CSS class to assign to the spinner
                    zIndex: 2e9, // The z-index (defaults to 2000000000)
                    top: 'auto', // Top position relative to parent in px
                    left: 'auto' // Left position relative to parent in px
                };
                var initSpin = function() {
                    $scope.spinner = new Spinner($scope.opts).spin();
                }
                $scope.endSpin = function() {
                    if ($scope.spinner)
                        $scope.spinner.stop();
                    $scope.spinRunning = false;
                }
                $scope.spin = function() {
                    if ($scope.spinRunning) return;
                    var target = $element.find('#spinWrapper');
                    if ($scope.spinner == null)
                        initSpin();
                    $scope.spinner.spin(target[0]);
                    $scope.spinRunning = true;
                }
            },
            link: function(scope, element) {
                // hide the element initially
                element.hide();

                var startRequestHandler = function() {
                    // got the request start notification, show the element
                    element.show();
                    scope.spin();
                };

                var endRequestHandler = function() {
                    // got the request start notification, show the element
                    element.hide();
                    scope.endSpin();
                };

                requestNotificationChannel.onRequestStarted(scope, startRequestHandler);

                requestNotificationChannel.onRequestEnded(scope, endRequestHandler);
            }
        };
    }]).directive('onFinishRender', ["$timeout", 'requestNotificationChannel', function($timeout, requestNotificationChannel) {
        return {
            restrict: 'A',
            controller: function() {
                requestNotificationChannel.requestStarted('list');
            },
            link: function(scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function() {
                        requestNotificationChannel.requestEnded('list');
                    });
                }
            }
        };
    }
    ]
    )
<|endoftext|>


<commit_before>define(['backbone', 'views/header', 'views/row'], function(Backbone, Header, Row) {

  var Datagrid = Backbone.View.extend({
    tagName: 'table',

    initialize: function() {
      this.columns = this.options.columns;
      this.collection.on('reset', this.render, this);
      this._prepareColumns();
    },

    render: function() {
      var header = new Header({columns: this.columns});
      this.$el.append(header.render().el);

      this.$el.append('

');

      this.collection.forEach(this.renderRow, this);

      return this;
    },

    renderRow: function(model) {
      var row = new Row({model: model, columns: this.columns});
      this.$('tbody').append(row.render(this.columns).el);
    },

    sort: function(column) {
      this.collection.comparator = function(model) {
        return model.get(column.property);
      };
      this.collection.sort();
    },

    _prepareColumns: function() {
      if (!this.columns || _.isEmpty(this.columns)) {
        this.columns = [];
        var model = this.collection.first();
        for (var p in model.toJSON()) {
          this.columns.push({
            title:    p.charAt(0).toUpperCase() + p.substr(1),
            property: p
          });
        }
      }
    }
  });

  return Datagrid;

});
<commit_msg>Fix rendering issue.<commit_after>define(['backbone', 'views/header', 'views/row'], function(Backbone, Header, Row) {

  var Datagrid = Backbone.View.extend({
    tagName: 'table',

    initialize: function() {
      this.columns = this.options.columns;
      this.collection.on('reset', this.render, this);
      this._prepareColumns();
    },

    render: function() {
      var header = new Header({columns: this.columns});
      this.$el.html(header.render().el);

      this.$el.append('

');

      this.collection.forEach(this.renderRow, this);

      return this;
    },

    renderRow: function(model) {
      var row = new Row({model: model, columns: this.columns});
      this.$('tbody').append(row.render(this.columns).el);
    },

    sort: function(column) {
      this.collection.comparator = function(model) {
        return model.get(column);
      };
      this.collection.sort();
    },

    _prepareColumns: function() {
      if (!this.columns || _.isEmpty(this.columns)) {
        this.columns = [];
        var model = this.collection.first();
        for (var p in model.toJSON()) {
          this.columns.push({
            title:    p.charAt(0).toUpperCase() + p.substr(1),
            property: p
          });
        }
      }
    }
  });

  return Datagrid;

});
<|endoftext|>


<commit_before>'use strict';

/* Directives */

var app = angular.module('myApp.directives', []);

app.directive('appVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
            elm.text(version);
        };
    }]);

app.directive('editor', function($timeout) {
    return function(scope, element, attrs) {
        $timeout(function() {
            var lang = attrs.editor;
            console.log('Lang to highlight: ' + lang);

            var editor = ace.edit(element[0]);
            editor.setTheme("ace/theme/textmate");
            editor.getSession().setMode("ace/mode/" + lang);
        }, 0);
    };
});<commit_msg>"tomorrow" theme of ACE fits much better IMO.<commit_after>'use strict';

/* Directives */

var app = angular.module('myApp.directives', []);

app.directive('appVersion', ['version', function(version) {
        return function(scope, elm, attrs) {
            elm.text(version);
        };
    }]);

app.directive('editor', function($timeout) {
    return function(scope, element, attrs) {
        $timeout(function() {
            var lang = attrs.editor;
            console.log('Lang to highlight: ' + lang);

            var editor = ace.edit(element[0]);
            editor.setTheme("ace/theme/tomorrow");
            editor.getSession().setMode("ace/mode/" + lang);
        }, 0);
    };
});<|endoftext|>


<commit_before>
// -----------Golbal variable-----------
var map, geocoder,_lat,_lng;
var marker={},info={}; var taipei = new google.maps.LatLng(25.0366641,121.5499766);

var global_district;
var markerCluster;
var isfirst = true;
var minZoomLevel = 5;
// -----------Golbal variable-----------
// $(document).ready(function() { initialize('hospital'); });
window.onload=initialize('hospital');

var type;
function initialize(classfication){
	// var type;
	geocoder = new google.maps.Geocoder();
	var mapOptions = {
		zoom: 11,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("section_for_googlemap"),mapOptions);
	if(classfication=="clinic")
		type="clinic";
	else
		type="hospital";
	map.setCenter(taipei);
	ajaxGetJson_1(map,25.0366641,121.5499766,type);
	getCurrentPosition(true,type);

	/* limit the minimum zoom */
	google.maps.event.addListener(map, 'zoom_changed', function(){
		if(map.getZoom() < minZoomLevel)
			map.setZoom(minZoomLevel);
	});
}

// for controller to initial a map
function after_select_init(){
	geocoder = new google.maps.Geocoder();
	var mapOptions = {
		//center: latlng,
		zoom: 12,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("section_for_googlemap"),mapOptions);

	/* limit the minimum zoom */
	google.maps.event.addListener(map, 'zoom_changed', function(){
		if(map.getZoom() < minZoomLevel)
			map.setZoom(minZoomLevel);
	});

	return map;

}

function getCurrentPosition(init,type){
	if(navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
			_lat=position.coords.latitude;
			_lng=position.coords.longitude;
			// 基隆
			// _lat = 25.128531;
			// _lng = 121.751905;

			initialLocation = new google.maps.LatLng(_lat,_lng);
			map.setCenter(initialLocation);
			console.log('getCUrrrentPosition');
			console.log("initial lat: " +_lat);
			console.log("initial lng: " +_lng);
			if(init)
				ajaxGetJson(map,_lat,_lng,type);
		}, function() {
			console.log("%s",browserSupportFlag);
			handleNoGeolocation(browserSupportFlag);
		});
	}
	// Browser doesn't support Geolocation
	else {
		browserSupportFlag = false;
		handleNoGeolocation(browserSupportFlag);
	}

	function handleNoGeolocation(errorFlag) {
		if (errorFlag == true)
			alert("地圖定位失敗");
		else
			alert("您的瀏覽器不支援定位服務");
		// alert("set location to Taipei");
		initialLocation = taipei;
		map.setCenter(initialLocation);
		// Taipei
		_lat=25.0366641;
		_lng=121.5499766;
		if(init)
			ajaxGetJson(map,_lat,_lng,type);
		alert("Set location to Taipei");

	}
}

function addMarker(map,locationName,lat,lng,tele,count){
	console.log("addMarker");
	var after_drag = false;
	var latlng = new google.maps.LatLng(lat,lng);
	marker[count] = new google.maps.Marker({
		// map:map,
		position:latlng,
		title: locationName
	});
	// marker.setMap(map);
	// marker.setMap(null);
	// 新增InfoWindow：
	var infowindow = new google.maps.InfoWindow();    //初始一個物件
	info[count] = infowindow;
	infowindow.setContent("名稱："+locationName+"
"+"電話："+tele);    //InfoWindow的內容，可用Html語法

		// 在Marker click時，顯示InfoWindow：
		google.maps.event.addListener(marker[count], 'click', function() {
			//先清除其他marker
			for(var i=0; i<Object.size(marker); i++)
				info[i].close();
			//open
			infowindow.open(map, marker[count]);
		});
		google.maps.event.addListener(marker[count],"mouseover",function()
		{
			for(var i=0; i<Object.size(marker); i++)
				info[i].close();
			//open
			infowindow.open(map, marker[count]);
		});

		google.maps.event.addListener(marker[count],"mouseout",function()
		{
			for(var i=0; i<Object.size(marker); i++)
				info[i].close();
		});
	}

	Object.size = function(obj) {
		var size = 0, key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) size++;
		}
		return size;
	};

	function ajaxGetJson(map,lat,lng,classfication){
		// var classfication = 'hospital';
		var obj = {"lat":lat,"lng":lng,"class":classfication};
		$.ajax({
			url: "./php/getAddress.php",
			type: "POST",
			dataType: "json",
			data: obj,
			success: function(data) {
				// console.log(data);
				removeMarkers();
				// if(!isfirst){
					unsetCluster();
					// isfirst = false;
				// }
				for( var i=0; i<data.length; i++){
					addMarker(map,data[i]['name'],data[i]['lat'],data[i]['lng'],data[i]['tele'],i);
				}
				google.maps.event.addListener(map,"drag",function()
				{
					console.log("draging");
					after_drag = true;
				});

				google.maps.event.addListener(map,"dragend",function()
				{
					console.log(map.getCenter().lat());
					console.log(map.getCenter().lng());
					ajaxGetJson(map, map.getCenter().lat(), map.getCenter().lng(), type);

				});
				clusterMarkers(map,50, 15);
				global_district = data[0]['district'];
				global_city = data[0]['city'];
				console.log("initial~ district: " + global_district);
				console.log("initial~ city: " + global_city);
			},
			error: function(){
				alert("ajax error");
			}
		});
}

function ajaxGetJson_1(map,lat,lng,classfication){
		// var classfication = 'hospital';
		var obj = {"lat":lat,"lng":lng,"class":classfication};
		$.ajax({
			url: "./php/getAddress.php",
			type: "POST",
			dataType: "json",
			data: obj,
			success: function(data) {
				// console.log(data);
				// removeMarkers();
				// if(!isfirst){
					// unsetCluster();
					// isfirst = false;
				// }
				for( var i=0; i<data.length; i++){
					addMarker(map,data[i]['name'],data[i]['lat'],data[i]['lng'],data[i]['tele'],i);
				}
				clusterMarkers(map,50, 15);
				global_district = data[0]['district'];
				global_city = data[0]['city'];
				console.log("initial~ district: " + global_district);
				console.log("initial~ city: " + global_city);
			},
			error: function(){
				alert("ajax error");
			}
		});
	}

	function removeMarkers(){
		for(var i=0; i< Object.size(marker); i++)
			marker[i].setMap(null);
		marker = [];
	}
	function unsetCluster(){
		markerCluster.clearMarkers();
	}
	function clusterMarkers(map,gridsize, zoom){
		var mcOptions = {gridSize: gridsize, maxZoom: zoom};
		markerCluster = new MarkerClusterer(map, marker, mcOptions);
	}
	function getInitialDistrict(){
		return global_district;
	}
	function getInitialCity(){
		return global_city;
	}
	function getInitialLat(){
		return _lat;
	}
	function getInitialLng(){
		return _lng;
	}

<commit_msg>nothing<commit_after>
// -----------Golbal variable-----------
var map, geocoder,_lat,_lng;
var marker={},info={}; var taipei = new google.maps.LatLng(25.0366641,121.5499766);

var global_district;
var markerCluster;
var isfirst = true;
var minZoomLevel = 5;
// -----------Golbal variable-----------
// $(document).ready(function() { initialize('hospital'); });
window.onload=initialize('hospital');

var type;
function initialize(classfication){
	// var type;
	geocoder = new google.maps.Geocoder();
	var mapOptions = {
		zoom: 11,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("section_for_googlemap"),mapOptions);
	if(classfication=="clinic")
		type="clinic";
	else
		type="hospital";
	map.setCenter(taipei);
	ajaxGetJson_1(map,25.0366641,121.5499766,type);
	getCurrentPosition(true,type);

	/* limit the minimum zoom */
	google.maps.event.addListener(map, 'zoom_changed', function(){
		if(map.getZoom() < minZoomLevel)
			map.setZoom(minZoomLevel);
	});
}

// for controller to initial a map
function after_select_init(){
	geocoder = new google.maps.Geocoder();
	var mapOptions = {
		//center: latlng,
		zoom: 12,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("section_for_googlemap"),mapOptions);

	/* limit the minimum zoom */
	google.maps.event.addListener(map, 'zoom_changed', function(){
		if(map.getZoom() < minZoomLevel)
			map.setZoom(minZoomLevel);
	});

	return map;

}

function getCurrentPosition(init,type){
	if(navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
			_lat=position.coords.latitude;
			_lng=position.coords.longitude;
			// 基隆
			// _lat = 25.128531;
			// _lng = 121.751905;

			initialLocation = new google.maps.LatLng(_lat,_lng);
			map.setCenter(initialLocation);
			console.log('getCUrrrentPosition');
			console.log("initial lat: " +_lat);
			console.log("initial lng: " +_lng);
			if(init)
				ajaxGetJson(map,_lat,_lng,type);
		}, function() {
			console.log("%s",browserSupportFlag);
			handleNoGeolocation(browserSupportFlag);
		});
	}
	// Browser doesn't support Geolocation
	else {
		browserSupportFlag = false;
		handleNoGeolocation(browserSupportFlag);
	}

	function handleNoGeolocation(errorFlag) {
		if (errorFlag == true)
			alert("地圖定位失敗");
		else
			alert("您的瀏覽器不支援定位服務");
		// alert("set location to Taipei");
		initialLocation = taipei;
		map.setCenter(initialLocation);
		// Taipei
		_lat=25.0366641;
		_lng=121.5499766;
		if(init)
			ajaxGetJson(map,_lat,_lng,type);
		alert("Set location to Taipei");

	}
}

function addMarker(map,locationName,lat,lng,tele,count){
	console.log("addMarker");
	var after_drag = false;
	var latlng = new google.maps.LatLng(lat,lng);
	marker[count] = new google.maps.Marker({
		// map:map,
		position:latlng,
		title: locationName
	});
	// marker.setMap(map);
	// marker.setMap(null);
	// 新增InfoWindow：
	var infowindow = new google.maps.InfoWindow();    //初始一個物件
	info[count] = infowindow;
	infowindow.setContent("名稱："+locationName+"
"+"電話："+tele);    //InfoWindow的內容，可用Html語法

		// 在Marker click時，顯示InfoWindow：
		google.maps.event.addListener(marker[count], 'click', function() {
			//先清除其他marker
			for(var i=0; i<Object.size(marker); i++)
				info[i].close();
			//open
			infowindow.open(map, marker[count]);
		});
		google.maps.event.addListener(marker[count],"mouseover",function()
		{
			for(var i=0; i<Object.size(marker); i++)
				info[i].close();
			//open
			infowindow.open(map, marker[count]);
		});

		google.maps.event.addListener(marker[count],"mouseout",function()
		{
			for(var i=0; i<Object.size(marker); i++)
				info[i].close();
		});
	}

	Object.size = function(obj) {
		var size = 0, key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) size++;
		}
		return size;
	};

	function ajaxGetJson(map,lat,lng,classfication){
		// var classfication = 'hospital';
		var obj = {"lat":lat,"lng":lng,"class":classfication};
		$.ajax({
			url: "./php/getAddress.php",
			type: "POST",
			dataType: "json",
			data: obj,
			success: function(data) {
				// console.log(data);
				removeMarkers();
				// if(!isfirst){
					unsetCluster();
					// isfirst = false;
				// }
				for( var i=0; i<data.length; i++){
					addMarker(map,data[i]['name'],data[i]['lat'],data[i]['lng'],data[i]['tele'],i);
				}
				google.maps.event.addListener(map,"drag",function()
				{
					console.log("draging");
					after_drag = true;
				});

				google.maps.event.addListener(map,"dragend",function()
				{
					console.log(map.getCenter().lat());
					console.log(map.getCenter().lng());
					ajaxGetJson(map, map.getCenter().lat(), map.getCenter().lng(), type);

				});
				clusterMarkers(map,50, 15);
				global_district = data[0]['district'];
				global_city = data[0]['city'];
				console.log("initial~ district: " + global_district);
				console.log("initial~ city: " + global_city);
			},
			error: function(){
				console.log("ajax error");
			}
		});
}

function ajaxGetJson_1(map,lat,lng,classfication){
		// var classfication = 'hospital';
		var obj = {"lat":lat,"lng":lng,"class":classfication};
		$.ajax({
			url: "./php/getAddress.php",
			type: "POST",
			dataType: "json",
			data: obj,
			success: function(data) {
				// console.log(data);
				// removeMarkers();
				// if(!isfirst){
					// unsetCluster();
					// isfirst = false;
				// }
				for( var i=0; i<data.length; i++){
					addMarker(map,data[i]['name'],data[i]['lat'],data[i]['lng'],data[i]['tele'],i);
				}
				clusterMarkers(map,50, 15);
				global_district = data[0]['district'];
				global_city = data[0]['city'];
				console.log("initial~ district: " + global_district);
				console.log("initial~ city: " + global_city);
			},
			error: function(){
				alert("ajax error");
			}
		});
	}

	function removeMarkers(){
		for(var i=0; i< Object.size(marker); i++)
			marker[i].setMap(null);
		marker = [];
	}
	function unsetCluster(){
		markerCluster.clearMarkers();
	}
	function clusterMarkers(map,gridsize, zoom){
		var mcOptions = {gridSize: gridsize, maxZoom: zoom};
		markerCluster = new MarkerClusterer(map, marker, mcOptions);
	}
	function getInitialDistrict(){
		return global_district;
	}
	function getInitialCity(){
		return global_city;
	}
	function getInitialLat(){
		return _lat;
	}
	function getInitialLng(){
		return _lng;
	}

<|endoftext|>


<commit_before>'use strict';

app.service('exportService', ['constantService', function(constants){

                //for timing
                //var seconds = new Date().getTime() / 1000;

                var dataExport = {};

                dataExport.downloadCSV = function(volume){

                    volume.get(['records', 'containers']).then(function(data){
                        createCSV(data);

                    });

                };

                function createCSV(data){

                    console.log(constants.category);
                    console.log(constants.metric);
                    var body = '';
                    var payload = '';

                    var array = typeof data !== 'object' ? JSON.parse(data) : data;

                    var containers = array.containers;
                    var records = array.records;

                    var baseHeaders = [
                        'session id',
                        'session date',
                        'record id',
                        'category'
                    ];

                    var headerIndex = getIndex(constants.category);
                    var metricIndex = getIndex(constants.metric);

                    var lonliestNumber = metricIndex.shift();

                    console.log("Header Index = " + headerIndex);
                    console.log("Metric Index = " + metricIndex);

                    var moreHeaders = makeHeadersText(headerIndex);

                    var header = baseHeaders.concat(moreHeaders).join(',');

                    console.log(containers);
                    console.log(records);

                    for(var k in containers){

                        if(containers[k].top !== true){ //exclude materials for now
                            for(var j in containers[k].records){
                               alert(containers[k].records[j].id);

                               var recID = containers[k].records[j].id;
                               var recCode = records[recID].category;

                               var colVals = [];

                               var recordMetricIndex = getIndex(records[recID].measures);

                               for(var z=0; z < headerIndex.length; z++){
                                  console.log(recCode);
                                  console.log(headerIndex[z]);

                                  if(recCode == headerIndex[z]){

                                    for(var m in records[recID].measures){
                                      console.log(m);
                                      for(var y=0; y < metricIndex.length; y++){
                                        if(m == metricIndex[y]){
                                          colVals.push(records[recID].measures[m]);
                                        } else {

                                          colVals.push('');
                                        }

                                      }
                                    }

                                  } else {
                                    colVals.push('');

                                  }

                               }

                               //colVals, at this point, should be the same length as moreHeaders.
                               if(colVals.length === moreHeaders.length){
                                console.log("good job, all values in");
                                console.log(colVals);

                               } else {
                                console.log("uh, oh, not all values in");
                                console.log(colVals);

                               }

                              /* this */
                               var metricCodes = Object.keys(records[recID].measures);
                               var metricText = makeMeasureText(metricCodes); //TODO remove this, only a placeholder
                               var metricVals = [];

                               for(var m=0; m < metricCodes.length; m++){

                                    try{
                                        if(recCode !== -300){ //TODO: Cannot use this in production, temporarily limits tasks out re: vol. 8
                                            metricVals.push(records[recID].measures[metricCodes[m]]);  //This causes Chrome to crash on vol. 8 (so many tasks)
                                        }
                                    } catch(e) {

                                      console.log(e);

                                    }
                               }
                               /*endthis*/

                               body += containers[k].id + ',' +
                                       containers[k].date + ',' +
                                       recID + ',' + recCode + ',' + metricText + "," + metricVals + '\n';

                            }
                      }

                    }

                    payload = header + '\n' + body;

                    createPayload(payload);

                }

                function createPayload(payload){

                    var filename = 'download.csv';
                    var uri = 'data:text/csv;charset=utf-8,' + encodeURI(payload);

                    var link = document.createElement('a');
                    link.href = uri;

                    link.style = "visibility:hidden";
                    link.download = filename;

                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);

                    //var timenow = new Date().getTime() / 1000;
                    //var timeto = (timenow - seconds);

                    //console.log("That took: " + timeto + " seconds");
                }

                /*--------------object manipulation functions-----------------*/

                function getIndex(recObj){
                  var index = [];
                  for(var k in recObj){
                    if(index.indexOf(k) === -1){
                      index.push(k);
                    }

                  }

                  return index.sort().reverse();

                }

                function makeHeadersText(arr){

                    var output = [];

                    arr.forEach(function(item){

                      var colPrefix = constants.category[item].name;
                      var childArr = [];

                      for(var i=0; i<constants.category[item].template.length; i++){
                        childArr.push(constants.category[item].template[i]);

                      }

                      childArr = childArr.sort().reverse();

                      childArr.forEach(function(child){
                         var colSuffix = constants.metric[child].name;

                         output.push(colPrefix + ' ' + colSuffix);

                      });

                    });

                    return output;

                }

                function makeMeasureText(arr){

                    return arr.map(function(code){
                       return constants.metric[code].name;
                    });
                }

               return dataExport;
            }

    ]);
<commit_msg>loop tooling<commit_after>'use strict';

app.service('exportService', ['constantService', function(constants){

                //for timing
                //var seconds = new Date().getTime() / 1000;

                var dataExport = {};

                dataExport.downloadCSV = function(volume){

                    volume.get(['records', 'containers']).then(function(data){
                        createCSV(data);

                    });

                };

                function createCSV(data){

                    console.log(constants.category);
                    console.log(constants.metric);
                    var body = '';
                    var payload = '';

                    var array = typeof data !== 'object' ? JSON.parse(data) : data;

                    var containers = array.containers;
                    var records = array.records;

                    var baseHeaders = [
                        'session id',
                        'session date',
                        'record id',
                        'category'
                    ];

                    var headerIndex = getIndex(constants.category);
                    var metricIndex = getIndex(constants.metric);

                    var lonliestNumber = metricIndex.shift();

                    console.log("Header Index = " + headerIndex);
                    console.log("Metric Index = " + metricIndex);

                    var moreHeaders = makeHeadersText(headerIndex);

                    var header = baseHeaders.concat(moreHeaders).join(',');

                    console.log(containers);
                    console.log(records);

                    for(var k in containers){

                        if(containers[k].top !== true){ //exclude materials for now
                            for(var j in containers[k].records){
                               alert(containers[k].records[j].id);

                               var recID = containers[k].records[j].id;
                               var recCode = records[recID].category;

                               var colVals = [];

                               var recordMetricIndex = getIndex(records[recID].measures);

                               for(var z=0; z < headerIndex.length; z++){
                                  //console.log(recCode);
                                  //console.log(headerIndex[z]);

                                  if(recCode == headerIndex[z]){

                                    for(var m in records[recID].measures){
                                      console.log(containers[k].id);
                                      for(var y=0; y < metricIndex.length; y++){
                                        if(m == metricIndex[y]){
                                          colVals.push(records[recID].measures[m]);
                                        } else {

                                          //colVals.push('');
                                        }

                                      }
                                    }

                                  } else {
                                    colVals.push('');

                                  }

                               }

                               //colVals, at this point, should be the same length as moreHeaders.
                               if(colVals.length === moreHeaders.length){
                                console.log("good job, all values in");
                                console.log(colVals);

                               } else {
                                console.log("uh, oh, not all values in");
                                console.log(colVals);

                               }

                              /* this
                               var metricCodes = Object.keys(records[recID].measures);
                               var metricText = makeMeasureText(metricCodes); //TODO remove this, only a placeholder
                               var metricVals = [];

                               for(var m=0; m < metricCodes.length; m++){

                                    try{
                                        if(recCode !== -300){ //TODO: Cannot use this in production, temporarily limits tasks out re: vol. 8
                                            metricVals.push(records[recID].measures[metricCodes[m]]);  //This causes Chrome to crash on vol. 8 (so many tasks)
                                        }
                                    } catch(e) {

                                      console.log(e);

                                    }
                               }
                               endthis*/

                               body += containers[k].id + ',' +
                                       containers[k].date + ',' +
                                       recID + ',' + recCode /*+ ',' + metricText + "," + metricVals*/ + '\n';

                            }
                      }

                    }

                    payload = header + '\n' + body;

                    createPayload(payload);

                }

                function createPayload(payload){

                    var filename = 'download.csv';
                    var uri = 'data:text/csv;charset=utf-8,' + encodeURI(payload);

                    var link = document.createElement('a');
                    link.href = uri;

                    link.style = "visibility:hidden";
                    link.download = filename;

                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);

                    //var timenow = new Date().getTime() / 1000;
                    //var timeto = (timenow - seconds);

                    //console.log("That took: " + timeto + " seconds");
                }

                /*--------------object manipulation functions-----------------*/

                function getIndex(recObj){
                  var index = [];
                  for(var k in recObj){
                    if(index.indexOf(k) === -1){
                      index.push(k);
                    }

                  }

                  return index.sort().reverse();

                }

                function makeHeadersText(arr){

                    var output = [];

                    arr.forEach(function(item){

                      var colPrefix = constants.category[item].name;
                      var childArr = [];

                      for(var i=0; i<constants.category[item].template.length; i++){
                        childArr.push(constants.category[item].template[i]);

                      }

                      childArr = childArr.sort().reverse();

                      childArr.forEach(function(child){
                         var colSuffix = constants.metric[child].name;

                         output.push(colPrefix + ' ' + colSuffix);

                      });

                    });

                    return output;

                }

                function makeMeasureText(arr){

                    return arr.map(function(code){
                       return constants.metric[code].name;
                    });
                }

               return dataExport;
            }

    ]);
<|endoftext|>


<commit_before>var fork = require('child_process').fork;
var EventEmitter = require('events').EventEmitter;

var Uglifier = function (options) {
	var self = this;

	this._options = {
		mangle: true,
		timeout: 60000
	};

	for (var i in options) {
		this._options[i] = options[i];
	}

	this._launchUglifier();
};

Uglifier.prototype = Object.create(EventEmitter.prototype);

Uglifier.prototype._triggerError = function (err) {
	this.emit('error', err);
};

Uglifier.prototype._triggerNotice = function (err) {
	this.emit('notice', err);
};

Uglifier.prototype._launchUglifier = function () {
	var self = this;

	this._idSeed = 1;
	this._pendingTasks = {};
	this._uglifier = fork(__dirname + '/uglify-process.node.js');

	this._uglifier.on('error', function (err) {
		if (!(err instanceof Error)) {
			err = new Error(err);
		}
		for (var i in self._pendingTasks) {
			clearTimeout(self._pendingTasks[i].timeout);
			self._pendingTasks[i].callback(err);
			delete self._pendingTasks[i];
		}
		self._triggerError(err);
		self._uglifier.kill();
	});
	this._uglifier.on('exit', function () {
		for (var i in self._pendingTasks) {
			var err = new Error('Uglifier exited');
			clearTimeout(self._pendingTasks[i].timeout);
			self._pendingTasks[i].callback(err);
			delete self._pendingTasks[i];
		}
		self._launchUglifier();
	});

	this._uglifier.on('message', function (m) {
		if (m.type == 'result') {
			var id = m.id;
			if (self._pendingTasks[id]) {
				clearTimeout(self._pendingTasks[id].timeout);
				self._pendingTasks[id].callback(null, m.data);
				delete self._pendingTasks[id];
			}
		} else if (m.type == 'ack') {
			var id = m.id;
			if (self._pendingTasks[id]) {
				self._pendingTasks[id].timeout = setTimeout(function () {
					var err = new Error('The minification task timed out');
					self._pendingTasks[id].callback(err);
					delete self._pendingTasks[id];
					self._triggerNotice(err);
				}, self._options.timeout)
			}
		} else if (m.type == 'error') {
			var id = m.id;
			var err = m.data;
			if (!(err instanceof Error)) {
				err = new Error(err);
			}
			if (self._pendingTasks[id]) {
				clearTimeout(self._pendingTasks[id].timeout);
				self._pendingTasks[id].callback(err);
				delete self._pendingTasks[id];
			}
			self._triggerNotice(err);
		}
	});

	this._uglifier.send({
		type: 'init',
		data: this._options
	});
};

Uglifier.prototype._nextId = function () {
	return this._idSeed++;
};

Uglifier.prototype.minifyJS = function (content, callback) {
	var self = this;

	var id = this._nextId();
	this._pendingTasks[id] = {
		callback: callback
	};
	this._uglifier.send({
		type: 'minify',
		id: id,
		data: {
			type: 'javascript',
			content: content
		}
	});
};

Uglifier.prototype.minifyCSS = function (content, callback) {
	var self = this;

	var id = this._nextId();
	this._pendingTasks[id] = {
		callback: callback
	};
	this._uglifier.send({
		type: 'minify',
		id: id,
		data: {
			type: 'css',
			content: content
		}
	});
};

module.exports.Uglifier = Uglifier;<commit_msg>Changed error message<commit_after>var fork = require('child_process').fork;
var EventEmitter = require('events').EventEmitter;

var Uglifier = function (options) {
	var self = this;

	this._options = {
		mangle: true,
		timeout: 60000
	};

	for (var i in options) {
		this._options[i] = options[i];
	}

	this._launchUglifier();
};

Uglifier.prototype = Object.create(EventEmitter.prototype);

Uglifier.prototype._triggerError = function (err) {
	this.emit('error', err);
};

Uglifier.prototype._triggerNotice = function (err) {
	this.emit('notice', err);
};

Uglifier.prototype._launchUglifier = function () {
	var self = this;

	this._idSeed = 1;
	this._pendingTasks = {};
	this._uglifier = fork(__dirname + '/uglify-process.node.js');

	this._uglifier.on('error', function (err) {
		if (!(err instanceof Error)) {
			err = new Error(err);
		}
		for (var i in self._pendingTasks) {
			clearTimeout(self._pendingTasks[i].timeout);
			self._pendingTasks[i].callback(err);
			delete self._pendingTasks[i];
		}
		self._triggerError(err);
		self._uglifier.kill();
	});
	this._uglifier.on('exit', function () {
		for (var i in self._pendingTasks) {
			var err = new Error('Uglifier exited');
			clearTimeout(self._pendingTasks[i].timeout);
			self._pendingTasks[i].callback(err);
			delete self._pendingTasks[i];
		}
		self._launchUglifier();
	});

	this._uglifier.on('message', function (m) {
		if (m.type == 'result') {
			var id = m.id;
			if (self._pendingTasks[id]) {
				clearTimeout(self._pendingTasks[id].timeout);
				self._pendingTasks[id].callback(null, m.data);
				delete self._pendingTasks[id];
			}
		} else if (m.type == 'ack') {
			var id = m.id;
			if (self._pendingTasks[id]) {
				self._pendingTasks[id].timeout = setTimeout(function () {
					var err = new Error('Minification task timed out');
					self._pendingTasks[id].callback(err);
					delete self._pendingTasks[id];
					self._triggerNotice(err);
				}, self._options.timeout)
			}
		} else if (m.type == 'error') {
			var id = m.id;
			var err = m.data;
			if (!(err instanceof Error)) {
				err = new Error(err);
			}
			if (self._pendingTasks[id]) {
				clearTimeout(self._pendingTasks[id].timeout);
				self._pendingTasks[id].callback(err);
				delete self._pendingTasks[id];
			}
			self._triggerNotice(err);
		}
	});

	this._uglifier.send({
		type: 'init',
		data: this._options
	});
};

Uglifier.prototype._nextId = function () {
	return this._idSeed++;
};

Uglifier.prototype.minifyJS = function (content, callback) {
	var self = this;

	var id = this._nextId();
	this._pendingTasks[id] = {
		callback: callback
	};
	this._uglifier.send({
		type: 'minify',
		id: id,
		data: {
			type: 'javascript',
			content: content
		}
	});
};

Uglifier.prototype.minifyCSS = function (content, callback) {
	var self = this;

	var id = this._nextId();
	this._pendingTasks[id] = {
		callback: callback
	};
	this._uglifier.send({
		type: 'minify',
		id: id,
		data: {
			type: 'css',
			content: content
		}
	});
};

module.exports.Uglifier = Uglifier;<|endoftext|>


<commit_before>import {sendableSteps} from "prosemirror-collab"

/* Sets up communicating with server (retrieving document,
  saving, collaboration, etc.).
 */
export class ModServerCommunications {
    constructor(editor) {
        editor.mod.serverCommunications = this
        this.editor = editor
            /* A list of messages to be sent. Only used when temporarily offline.
            Messages will be sent when returning back online. */
        this.messagesToSend = []

        this.connected = false
            /* Whether the connection is established for the first time. */
        this.firstTimeConnection = true
    }

    init() {
        this.createWSConnection()
    }

    createWSConnection() {
        let websocketProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        // Messages object used to ensure that data is received in right order.
        this.messages = {
            server: 0,
            client: 0,
            lastTen: []
        }
        try {
            this.ws = new window.WebSocket(`${websocketProtocol}//${window.websocketServer}${window.websocketPort}/ws/document/${this.editor.docInfo.id}`)
            this.ws.onopen = () => {
                jQuery('#unobtrusive_messages').html('')
            }
        } catch (err) {
            console.error(err)
        }

        this.ws.onmessage = event => {
            let data = JSON.parse(event.data)
            let expectedServer = this.messages.server + 1
            if (data.type === 'request_resend') {
                this.resend_messages(data.from)
            } else if (data.s < expectedServer) {
                // Receive a message already received at least once. Ignore.
                return
            } else if (data.s > expectedServer) {
                // Messages from the server have been lost.
                // Request resend.
                this.ws.send(JSON.stringify({
                    type: 'request_resend',
                    from: this.messages.server
                }))
            } else {
                this.messages.server = expectedServer
                if (data.c === this.messages.client) {
                    this.receive(data)
                } else if (data.c < this.messages.client) {
                    // We have received all server messages, but the server seems
                    // to have missed some of the client's messages. They could
                    // have been sent simultaneously.
                    // The server wins over the client in this case.
                    let clientDifference = this.messages.client - data.c
                    this.messages.client = data.c
                    if (clientDifference > this.messages.lastTen.length) {
                        // We cannot fix the situation
                        this.send(() =>({type: 'get_document'}))
                        return
                    }
                    this.messages['lastTen'].slice(0-clientDifference).forEach(getData => {
                        let data = getData()
                        if (!data) {
                            // message is empty
                            return
                        }
                        this.messages.client += 1
                        data.c = this.messages.client
                        data.s = this.messages.server
                        this.ws.send(JSON.stringify(data))
                    })
                    this.receive(data)
                }
            }
        }

        this.ws.onclose = event => {
            this.connected = false
            window.clearInterval(this.wsPinger)
            window.setTimeout(() => {
                this.createWSConnection()
            }, 2000)
            if(!this.editor.view.state.plugins.length) {
                console.warn('doc not initiated')
                return
            }
            let toSend = sendableSteps(this.editor.view.state)
            if (toSend) {
                jQuery('#unobtrusive_messages').html(''+gettext('Warning! Not all your changes have been saved! You could suffer data loss. Attempting to reconnect...')+'')
            } else {
                jQuery('#unobtrusive_messages').html(gettext('Disconnected. Attempting to reconnect...'))
            }

        }
        this.wsPinger = window.setInterval(() => {
            this.send(() => ({
                'type': 'ping'
            }))
        }, 50000)
    }

    activateConnection() {
        this.connected = true
        if (this.firstTimeConnection) {
            this.editor.waitingForDocument = false
            this.editor.askForDocument()
        } else {
            this.editor.mod.footnotes.fnEditor.renderAllFootnotes()
            this.editor.mod.collab.docChanges.checkVersion()
            this.send(() => ({
                type: 'participant_update'
            }))
            while (this.messagesToSend.length > 0) {
                this.send(this.messagesToSend.shift())
            }
        }
        this.firstTimeConnection = false
    }

    /** Sends data to server or keeps it in a list if currently offline. */
    send(getData) {
        if (this.connected) {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            this.messages.lastTen.push(getData)
            this.messages.lastTen = this.messages['lastTen'].slice(-10)
            this.ws.send(JSON.stringify(data))
        } else {
            this.messagesToSend.push(getData)
        }
    }

    resend_messages(from) {
        let toSend = this.messages.client - from
        this.messages.client = from
        if (toSend > this.messages.lastTen.length) {
            // Too many messages requested. Abort.
            this.send(() => ({type: 'get_document'}))
            return
        }
        this.messages.lastTen.slice(0-toSend).forEach(getData => {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            this.ws.send(JSON.stringify(data))
        })
    }

    receive(data) {
        switch (data.type) {
            case 'chat':
                this.editor.mod.collab.chat.newMessage(data)
                break
            case 'connections':
                this.editor.mod.collab.updateParticipantList(data.participant_list)
                break
            case 'welcome':
                this.editor.mod.styles.setStyles(data.styles)
                this.activateConnection()
                break
            case 'doc_data':
                this.editor.receiveDocument(data)
                break
            case 'confirm_version':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.enableDiffSending()
                break
            case 'selection_change':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveSelectionChange(data)
                break
            case 'diff':
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveFromCollaborators(data)
                break
            case 'confirm_diff':
                this.editor.mod.collab.docChanges.confirmDiff(data["rid"])
                break
            case 'reject_diff':
                this.editor.mod.collab.docChanges.rejectDiff(data["rid"])
                break
            case 'access_denied':
                window.location.href = '/'
                break
        }
    }

}
<commit_msg>log client<commit_after>import {sendableSteps} from "prosemirror-collab"

/* Sets up communicating with server (retrieving document,
  saving, collaboration, etc.).
 */
export class ModServerCommunications {
    constructor(editor) {
        editor.mod.serverCommunications = this
        this.editor = editor
            /* A list of messages to be sent. Only used when temporarily offline.
            Messages will be sent when returning back online. */
        this.messagesToSend = []

        this.connected = false
            /* Whether the connection is established for the first time. */
        this.firstTimeConnection = true
    }

    init() {
        this.createWSConnection()
    }

    createWSConnection() {
        let websocketProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        // Messages object used to ensure that data is received in right order.
        this.messages = {
            server: 0,
            client: 0,
            lastTen: []
        }
        try {
            this.ws = new window.WebSocket(`${websocketProtocol}//${window.websocketServer}${window.websocketPort}/ws/document/${this.editor.docInfo.id}`)
            this.ws.onopen = () => {
                jQuery('#unobtrusive_messages').html('')
            }
        } catch (err) {
            console.error(err)
        }

        this.ws.onmessage = event => {
            let data = JSON.parse(event.data)
            let expectedServer = this.messages.server + 1
            console.log({data, expectedServer})
            if (data.type === 'request_resend') {
                this.resend_messages(data.from)
            } else if (data.s < expectedServer) {
                // Receive a message already received at least once. Ignore.
                return
            } else if (data.s > expectedServer) {
                // Messages from the server have been lost.
                // Request resend.
                this.ws.send(JSON.stringify({
                    type: 'request_resend',
                    from: this.messages.server
                }))
            } else {
                this.messages.server = expectedServer
                if (data.c === this.messages.client) {
                    this.receive(data)
                } else if (data.c < this.messages.client) {
                    // We have received all server messages, but the server seems
                    // to have missed some of the client's messages. They could
                    // have been sent simultaneously.
                    // The server wins over the client in this case.
                    let clientDifference = this.messages.client - data.c
                    this.messages.client = data.c
                    if (clientDifference > this.messages.lastTen.length) {
                        // We cannot fix the situation
                        this.send(() =>({type: 'get_document'}))
                        return
                    }
                    this.messages['lastTen'].slice(0-clientDifference).forEach(getData => {
                        let data = getData()
                        if (!data) {
                            // message is empty
                            return
                        }
                        this.messages.client += 1
                        data.c = this.messages.client
                        data.s = this.messages.server
                        this.ws.send(JSON.stringify(data))
                    })
                    this.receive(data)
                }
            }
        }

        this.ws.onclose = event => {
            this.connected = false
            window.clearInterval(this.wsPinger)
            window.setTimeout(() => {
                this.createWSConnection()
            }, 2000)
            if(!this.editor.view.state.plugins.length) {
                console.warn('doc not initiated')
                return
            }
            let toSend = sendableSteps(this.editor.view.state)
            if (toSend) {
                jQuery('#unobtrusive_messages').html(''+gettext('Warning! Not all your changes have been saved! You could suffer data loss. Attempting to reconnect...')+'')
            } else {
                jQuery('#unobtrusive_messages').html(gettext('Disconnected. Attempting to reconnect...'))
            }

        }
        this.wsPinger = window.setInterval(() => {
            this.send(() => ({
                'type': 'ping'
            }))
        }, 50000)
    }

    activateConnection() {
        this.connected = true
        if (this.firstTimeConnection) {
            this.editor.waitingForDocument = false
            this.editor.askForDocument()
        } else {
            this.editor.mod.footnotes.fnEditor.renderAllFootnotes()
            this.editor.mod.collab.docChanges.checkVersion()
            this.send(() => ({
                type: 'participant_update'
            }))
            while (this.messagesToSend.length > 0) {
                this.send(this.messagesToSend.shift())
            }
        }
        this.firstTimeConnection = false
    }

    /** Sends data to server or keeps it in a list if currently offline. */
    send(getData) {
        if (this.connected) {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            this.messages.lastTen.push(getData)
            this.messages.lastTen = this.messages['lastTen'].slice(-10)
            this.ws.send(JSON.stringify(data))
        } else {
            this.messagesToSend.push(getData)
        }
    }

    resend_messages(from) {
        let toSend = this.messages.client - from
        this.messages.client = from
        if (toSend > this.messages.lastTen.length) {
            // Too many messages requested. Abort.
            this.send(() => ({type: 'get_document'}))
            return
        }
        this.messages.lastTen.slice(0-toSend).forEach(getData => {
            this.messages.client += 1
            let data = getData()
            if (!data) {
                // message is empty
                return
            }
            data.c = this.messages.client
            data.s = this.messages.server
            this.ws.send(JSON.stringify(data))
        })
    }

    receive(data) {
        switch (data.type) {
            case 'chat':
                this.editor.mod.collab.chat.newMessage(data)
                break
            case 'connections':
                this.editor.mod.collab.updateParticipantList(data.participant_list)
                break
            case 'welcome':
                this.editor.mod.styles.setStyles(data.styles)
                this.activateConnection()
                break
            case 'doc_data':
                this.editor.receiveDocument(data)
                break
            case 'confirm_version':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.enableDiffSending()
                break
            case 'selection_change':
                this.editor.mod.collab.docChanges.cancelCurrentlyCheckingVersion()
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveSelectionChange(data)
                break
            case 'diff':
                if (data["v"] !== this.editor.docInfo.version) {
                    this.editor.mod.collab.docChanges.checkVersion()
                    return
                }
                this.editor.mod.collab.docChanges.receiveFromCollaborators(data)
                break
            case 'confirm_diff':
                this.editor.mod.collab.docChanges.confirmDiff(data["rid"])
                break
            case 'reject_diff':
                this.editor.mod.collab.docChanges.rejectDiff(data["rid"])
                break
            case 'access_denied':
                window.location.href = '/'
                break
        }
    }

}
<|endoftext|>


<commit_before>import React from 'react';
import BasicTable from './basic-table';
import HoverStripedTable from './hover-striped-table';
import BorderlessTable from './borderless-table';
import ScrollTable from './scroll-table';
import LargeColumnTable from './large-column-table';

import {Col, Panel} from 'react-bootstrap';

class Demo extends React.Component {
  render() {
    return (
      <Col md={8} mdOffset={1}>
        <Panel header={"A basic react-bootstrap-table"}>

Source in /examples/js/basic/basic-table.js

          <BasicTable/>
        </Panel>
        <Panel header={"Table hover, striped and condensed Example"}>

Source in /examples/js/basic/borderless-table.js

          <BorderlessTable/>
        </Panel>
        <Panel header={"Borderless table Example"}>

Source in /examples/js/basic/hover-striped-table.js

          <HoverStripedTable/>
        </Panel>
        <Panel header={"A Large Column Table Demo"}>

Source in /examples/js/basic/large-column-table.js

Warning

            There is one restriction when you want to make a large column table scrollable:

            You need set the width on some column to make the total width of table exceed the width of outter.

          <LargeColumnTable/>
        </Panel>
        <Panel header={"Table Scroll Example"}>

Source in /examples/js/basic/scroll-table.js

          <ScrollTable/>
        </Panel>
      </Col>
    );
  }
}

export default Demo;
<commit_msg>fix wrong examples<commit_after>import React from 'react';
import BasicTable from './basic-table';
import HoverStripedTable from './hover-striped-table';
import BorderlessTable from './borderless-table';
import ScrollTable from './scroll-table';
import LargeColumnTable from './large-column-table';

import {Col, Panel} from 'react-bootstrap';

class Demo extends React.Component {
  render() {
    return (
      <Col md={8} mdOffset={1}>
        <Panel header={"A basic react-bootstrap-table"}>

Source in /examples/js/basic/basic-table.js

          <BasicTable/>
        </Panel>
        <Panel header={"Table hover, striped and condensed Example"}>

Source in /examples/js/basic/borderless-table.js

          <HoverStripedTable/>
        </Panel>
        <Panel header={"Borderless table Example"}>

Source in /examples/js/basic/hover-striped-table.js

          <BorderlessTable/>
        </Panel>
        <Panel header={"A Large Column Table Demo"}>

Source in /examples/js/basic/large-column-table.js

Warning

            There is one restriction when you want to make a large column table scrollable:

            You need set the width on some column to make the total width of table exceed the width of outter.

          <LargeColumnTable/>
        </Panel>
        <Panel header={"Table Scroll Example"}>

Source in /examples/js/basic/scroll-table.js

          <ScrollTable/>
        </Panel>
      </Col>
    );
  }
}

export default Demo;
<|endoftext|>