<commit_before>ngapp.config(['$stateProvider', function ($stateProvider) {
    $stateProvider.state('base.edit', {
        templateUrl: 'partials/edit.html',
        controller: 'editController',
        url: '/edit'
    });
}]);

ngapp.controller('editController', function ($scope, layoutService, hotkeyService, viewFactory) {
    let getPluginItem = function(file) {
        return {
            handle: file,
            filename: xelib.Name(file),
            active: true
        }
    };

    let openSaveModal = function(shouldFinalize) {
        let plugins = xelib.GetElements()
            .filter(xelib.GetIsModified)
            .map(getPluginItem);
        if (!shouldFinalize && !plugins.length) return;
        $scope.$emit('openModal', 'save', {
            shouldFinalize: shouldFinalize,
            plugins: plugins
        });
    };

    let createFilterView = function() {
        let treeView = layoutService.findView(function(view) {
            return view.class === 'tree-view';
        });
        let filterView = viewFactory.newView('filterView', true);
        treeView.pane.tabs.forEach(function(tab) {
            tab.active = false;
        });
        treeView.pane.tabs.push(filterView);
        return filterView;
    };

    // scope functions
    $scope.onViewportRender = function() {
        if (verbose) logger.info('Rendering viewport...');
    };

    // event handlers
    $scope.$on('settingsClick', function() {
        if (!$scope.loaded) return;
        $scope.$emit('openModal', 'settings');
    });

    $scope.$on('save', function() {
        if ($scope.$root.modalActive) return;
        openSaveModal(false);
    });

    $scope.$on('linkView', function(e, view) {
        $scope.$broadcast('toggleLinkMode', view);
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$on('searchResults', function(e, options) {
        let filterView = layoutService.findView(function(view) {
            if (view.class === 'filter-view') {
                view.searchOptions.nodes.forEach(function(node) {
                    xelib.Release(node.handle);
                });
                view.results.forEach(xelib.Release);
                return true;
            }
        }) || createFilterView();
        Object.assign(filterView, options);
    });

    $scope.$on('executingScript', function(e, scriptFilename) {
        logger.info(`Executing script ${scriptFilename}...`);
        layoutService.switchToView('log-view');
    });

    $scope.$on('filesLoaded', function() {
        if (verbose) logger.info('Rendering editView');
        $scope.loaded = true;
    });

    // handle hotkeys
    hotkeyService.buildOnKeyDown($scope, 'onKeyDown', 'editView');

    // save data and terminate xelib when application is being closed
    window.onbeforeunload = function(e) {
        if (remote.app.forceClose) return;
        e.returnValue = false;
        if (!$scope.$root.modalActive) openSaveModal(true);
    };

    // initialization
    $scope.mainPane = layoutService.buildDefaultLayout();
});
<commit_msg>now ignoring mouse input while the pluginLoader is active<commit_after>ngapp.config(['$stateProvider', function ($stateProvider) {
    $stateProvider.state('base.edit', {
        templateUrl: 'partials/edit.html',
        controller: 'editController',
        url: '/edit'
    });
}]);

ngapp.controller('editController', function ($scope, $timeout, layoutService, hotkeyService, viewFactory) {
    let getPluginItem = function(file) {
        return {
            handle: file,
            filename: xelib.Name(file),
            active: true
        }
    };

    let openSaveModal = function(shouldFinalize) {
        let plugins = xelib.GetElements()
            .filter(xelib.GetIsModified)
            .map(getPluginItem);
        if (!shouldFinalize && !plugins.length) return;
        $scope.$emit('openModal', 'save', {
            shouldFinalize: shouldFinalize,
            plugins: plugins
        });
    };

    let createFilterView = function() {
        let treeView = layoutService.findView(function(view) {
            return view.class === 'tree-view';
        });
        let filterView = viewFactory.newView('filterView', true);
        treeView.pane.tabs.forEach(function(tab) {
            tab.active = false;
        });
        treeView.pane.tabs.push(filterView);
        return filterView;
    };

    let ignore = function(e) {
        e.stopPropagation();
        e.preventDefault();
    };

    // event handlers
    document.addEventListener('mousedown', ignore, true);
    document.addEventListener('click', ignore, true);
    document.addEventListener('mouseup', ignore, true);

    $scope.onViewportRender = function() {
        if (verbose) logger.info('Rendering viewport...');
    };

    $scope.$on('settingsClick', function() {
        if (!$scope.loaded) return;
        $scope.$emit('openModal', 'settings');
    });

    $scope.$on('save', function() {
        if ($scope.$root.modalActive) return;
        openSaveModal(false);
    });

    $scope.$on('linkView', function(e, view) {
        $scope.$broadcast('toggleLinkMode', view);
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$on('searchResults', function(e, options) {
        let filterView = layoutService.findView(function(view) {
            if (view.class === 'filter-view') {
                view.searchOptions.nodes.forEach(function(node) {
                    xelib.Release(node.handle);
                });
                view.results.forEach(xelib.Release);
                return true;
            }
        }) || createFilterView();
        Object.assign(filterView, options);
    });

    $scope.$on('executingScript', function(e, scriptFilename) {
        logger.info(`Executing script ${scriptFilename}...`);
        layoutService.switchToView('log-view');
    });

    $scope.$on('filesLoaded', function() {
        if (verbose) logger.info('Rendering editView');
        $scope.loaded = true;
        $timeout(() => {
            logger.info('Allowing click events');
            document.removeEventListener('mousedown', ignore, true);
            document.removeEventListener('click', ignore, true);
            document.removeEventListener('mouseup', ignore, true);
        }, 500);
    });

    // handle hotkeys
    hotkeyService.buildOnKeyDown($scope, 'onKeyDown', 'editView');

    // save data and terminate xelib when application is being closed
    window.onbeforeunload = function(e) {
        if (remote.app.forceClose) return;
        e.returnValue = false;
        if (!$scope.$root.modalActive) openSaveModal(true);
    };

    // initialization
    $scope.mainPane = layoutService.buildDefaultLayout();
});
<|endoftext|>


<commit_before>/* eslint-env jasmine, mocha */

import helperFixture from './lib/fixture';

if (!document.registerElement && !window.customElements) {
  require('skatejs-web-components');
}

mocha.setup({ timeout: 10000 }); // eslint-disable-line no-undef

afterEach(() => {
  // Ensure perf tests have enough time to cleanup after themselves.
  mocha.timeout(120000); // eslint-disable-line no-undef
  helperFixture('');
});
<commit_msg>test: Update tests so that it will polyfill v0 supported browsers up to v1.<commit_after>/* eslint-env jasmine, mocha */

import helperFixture from './lib/fixture';

if (!window.customElements) {
  require('skatejs-web-components');
}

mocha.setup({ timeout: 10000 }); // eslint-disable-line no-undef

afterEach(() => {
  // Ensure perf tests have enough time to cleanup after themselves.
  mocha.timeout(120000); // eslint-disable-line no-undef
  helperFixture('');
});
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   if(typeof nodemap[i][j - 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i][j + 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i - 1][j] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i + 1][] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create a branch point
           var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   if(typeof nodemap[i][j - 1] != "undefined"){
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i][j + 1] != "undefined"){
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i - 1][j] != "undefined"){
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }
                   if(typeof nodemap[i + 1][j] != "undefined"){
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }else{
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //create random rooms
           for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>"use strict";

var fs   = require("fs");
var path = require("path");

function checkMeasure(v, what, units) {
	var ret = {};

	ret.num = parseInt(v, 10);

	if(isNaN(ret.num))
		throw new Error("Unknown 'options." + what + "' format: " + v);

	if(ret.num <= 0)
		throw new Error("A positive integer number is expected for 'options." + what + "'");

	ret.unit = v.replace(/^[ 0]*/g, "").substr((ret.num + "").length, 1);

	if(ret.unit.length === 0)
		throw new Error("Missing unit for 'options." + what + "'");

	if(! units[ret.unit])
		throw new Error("Unknown 'options." + what + "' unit: " + ret.unit);

	return ret;
}

var intervalUnits = {
	d: true,
	h: true,
	m: true,
	s: true
};

function checkInterval(v) {
	var ret = checkMeasure(v, "interval", intervalUnits);

	switch(ret.unit) {
	case "m":
		if(parseInt(60 / ret.num, 10) * ret.num !== 60)
			throw new Error("An integer divider of 60 is expected as minutes for 'options.interval'");
		break;

	case "h":
		if(parseInt(24 / ret.num, 10) * ret.num !== 24)
			throw new Error("An integer divider of 24 is expected as hours for 'options.interval'");
		break;

	case "s":
		if(parseInt(60 / ret.num, 10) * ret.num !== 60)
			throw new Error("An integer divider of 60 is expected as seconds for 'options.interval'");
		break;
	}

	return ret;
}

var sizeUnits = {
	B: true,
	G: true,
	K: true,
	M: true
};

function checkSize(v) {
	var ret = checkMeasure(v, "size", sizeUnits);

	if(ret.unit === "K")
		return ret.num * 1024;

	if(ret.unit === "M")
		return ret.num * 1048576;

	if(ret.unit === "G")
		return ret.num * 1073741824;

	return ret.num;
}

var checks = {
	"compress": function(typ, options, val) {
		if(! val)
			throw new Error("A value for 'options.compress' must be specified");

		if(typ === "boolean")
			options.compress = function(src, dst) { return "cat " + src + " | gzip -c9 > " + dst; };
		else
			if(typ === "string") {
				//if(val != "bzip" && val != "gzip")
				if(val !== "gzip")
					throw new Error("Don't know how to handle compression method: " + val);
			}
			else
				if(typ !== "function")
					throw new Error("Don't know how to handle 'options.compress' type: " + typ);
	},

	"highWaterMark": function() {},

	"interval": function(typ, options, val) {
		if(typ !== "string")
			throw new Error("Don't know how to handle 'options.interval' type: " + typ);

		options.interval = checkInterval(val);
	},

	"mode": function() {},

	"path": function(typ) {
		if(typ !== "string")
			throw new Error("Don't know how to handle 'options.path' type: " + typ);
	},

	"rotate": function(typ, options, val) {
		var rotate = parseInt(val, 10);

		if(rotate !== val || rotate <= 0 || typ !== "number")
			throw new Error("'rotate' option must be a positive integer number");
	},

	"rotationTime": function() {},

	"size": function(typ, options, val) {
		if(typ !== "string")
			throw new Error("Don't know how to handle 'options.size' type: " + typ);

		options.size = checkSize(val);
	}
};

function checkOptions(options) {
	if(! options)
		return {};

	if(typeof options !== "object")
		throw new Error("Don't know how to handle 'options' type: " + typeof options);

	var ret = {};

	for(var opt in options) {
		var val = options[opt];
		var typ = typeof val;

		if(! (opt in checks))
			throw new Error("Unknown option: " + opt);

		ret[opt] = options[opt];
		checks[opt](typ, ret, val);
	}

	return ret;
}

function pad(num) {
	return (num > 9 ? "" : "0") + num;
}

function createClassical(filename) {
	return function(index) {
		if(! index)
			return filename;

		return filename + "." + index;
	};
}

function createGenerator(filename) {
	return function(time, index) {
		if(! time)
			return filename;

		var month  = time.getFullYear() + "" + pad(time.getMonth() + 1);
		var day    = pad(time.getDate());
		var hour   = pad(time.getHours());
		var minute = pad(time.getMinutes());

		return month + day + "-" + hour + minute + "-" + pad(index) + "-" + filename;
	};
}

function makePath(name, callback) {
	var dir = path.parse(name).dir;

	fs.mkdir(dir, function(e) {
		if(e) {
			if(e.code === "ENOENT")
				return makePath(dir, callback);

			return callback(e);
		}

		callback();
	});
}

function setEvents(self) {
	self.once("error", function(err) {
		self.err = err;
		self.end();
	});

	self.once("finish", self._clear.bind(self));

	self.on("rotated", function() {
		self.rotation = null;
		self._rewrite();
	});
}

module.exports = {
	checkOptions:    checkOptions,
	createClassical: createClassical,
	createGenerator: createGenerator,
	makePath:        makePath,
	setEvents:       setEvents,
};
<commit_msg>code climate fix<commit_after>"use strict";

var fs   = require("fs");
var path = require("path");

function buildStringCheck(field, check) {
	return function(typ, options, val) {
		if(typ !== "string")
			throw new Error("Don't know how to handle 'options." + field + "' type: " + typ);

		options[field] = check(val);
	};
}

function checkMeasure(v, what, units) {
	var ret = {};

	ret.num = parseInt(v, 10);

	if(isNaN(ret.num))
		throw new Error("Unknown 'options." + what + "' format: " + v);

	if(ret.num <= 0)
		throw new Error("A positive integer number is expected for 'options." + what + "'");

	ret.unit = v.replace(/^[ 0]*/g, "").substr((ret.num + "").length, 1);

	if(ret.unit.length === 0)
		throw new Error("Missing unit for 'options." + what + "'");

	if(! units[ret.unit])
		throw new Error("Unknown 'options." + what + "' unit: " + ret.unit);

	return ret;
}

var intervalUnits = {
	d: true,
	h: true,
	m: true,
	s: true
};

function checkIntervalUnit(ret, unit, amount) {
	if(parseInt(amount / ret.num, 10) * ret.num !== amount)
		throw new Error("An integer divider of " + amount + " is expected as " + unit + " for 'options.interval'");
}

function checkInterval(v) {
	var ret = checkMeasure(v, "interval", intervalUnits);

	switch(ret.unit) {
	case "h":
		checkIntervalUnit(ret, "hours", 24);
		break;

	case "m":
		checkIntervalUnit(ret, "minutes", 60);
		break;

	case "s":
		checkIntervalUnit(ret, "seconds", 60);
		break;
	}

	return ret;
}

var sizeUnits = {
	B: true,
	G: true,
	K: true,
	M: true
};

function checkSize(v) {
	var ret = checkMeasure(v, "size", sizeUnits);

	if(ret.unit === "K")
		return ret.num * 1024;

	if(ret.unit === "M")
		return ret.num * 1048576;

	if(ret.unit === "G")
		return ret.num * 1073741824;

	return ret.num;
}

var checks = {
	"compress": function(typ, options, val) {
		if(! val)
			throw new Error("A value for 'options.compress' must be specified");

		if(typ === "boolean")
			options.compress = function(src, dst) { return "cat " + src + " | gzip -c9 > " + dst; };
		else
			if(typ === "string") {
				//if(val != "bzip" && val != "gzip")
				if(val !== "gzip")
					throw new Error("Don't know how to handle compression method: " + val);
			}
			else
				if(typ !== "function")
					throw new Error("Don't know how to handle 'options.compress' type: " + typ);
	},

	"highWaterMark": function() {},

	"interval": buildStringCheck("interval", checkInterval),

	"mode": function() {},

	"path": function(typ) {
		if(typ !== "string")
			throw new Error("Don't know how to handle 'options.path' type: " + typ);
	},

	"rotate": function(typ, options, val) {
		var rotate = parseInt(val, 10);

		if(rotate !== val || rotate <= 0 || typ !== "number")
			throw new Error("'rotate' option must be a positive integer number");
	},

	"rotationTime": function() {},

	"size": buildStringCheck("size", checkSize)
};

function checkOptions(options) {
	if(! options)
		return {};

	if(typeof options !== "object")
		throw new Error("Don't know how to handle 'options' type: " + typeof options);

	var ret = {};

	for(var opt in options) {
		var val = options[opt];
		var typ = typeof val;

		if(! (opt in checks))
			throw new Error("Unknown option: " + opt);

		ret[opt] = options[opt];
		checks[opt](typ, ret, val);
	}

	return ret;
}

function pad(num) {
	return (num > 9 ? "" : "0") + num;
}

function createClassical(filename) {
	return function(index) {
		if(! index)
			return filename;

		return filename + "." + index;
	};
}

function createGenerator(filename) {
	return function(time, index) {
		if(! time)
			return filename;

		var month  = time.getFullYear() + "" + pad(time.getMonth() + 1);
		var day    = pad(time.getDate());
		var hour   = pad(time.getHours());
		var minute = pad(time.getMinutes());

		return month + day + "-" + hour + minute + "-" + pad(index) + "-" + filename;
	};
}

function makePath(name, callback) {
	var dir = path.parse(name).dir;

	fs.mkdir(dir, function(e) {
		if(e) {
			if(e.code === "ENOENT")
				return makePath(dir, callback);

			return callback(e);
		}

		callback();
	});
}

function setEvents(self) {
	self.once("error", function(err) {
		self.err = err;
		self.end();
	});

	self.once("finish", self._clear.bind(self));

	self.on("rotated", function() {
		self.rotation = null;
		self._rewrite();
	});
}

module.exports = {
	checkOptions:    checkOptions,
	createClassical: createClassical,
	createGenerator: createGenerator,
	makePath:        makePath,
	setEvents:       setEvents,
};
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var fsx = require('fs-extra')

module.exports = yeoman.generators.Base.extend({
  constructor: function() {
    yeoman.generators.Base.apply(this, arguments);
    this.pkg = require('../package.json');
  },

  hasFeature: function(list, feat) {
    return (list || []).indexOf(feat) !== -1;
  },

  hasCfg: function(file) {
    return fsx.readJsonSync(file, { throws: false });
  },

  askFor: function() {
    var done = this.async();
    this.log(yosay('Welcome to the wondrous ' + chalk.red('Ambox') + ' generator!'));
    var prompts = [
      {
        type: 'checkbox',
        name: 'features',
        message: 'What more would you like?',
        choices: [
          {
            name: 'Bower',
            value: 'includeBower',
            checked: true
          },
          {
            name: 'Component',
            value: 'includeComponent',
            checked: false
          },
          {
            name: 'Jade',
            value: 'includeJade',
            checked: true
          },
          {
            name: 'Theme structure',
            value: 'includeTheme',
            checked: true
          },
          {
            name: 'Modernizr',
            value: 'includeModernizr',
            checked: true
          },
          {
            name: 'jQuery',
            value: 'includejQuery',
            checked: true
          }
        ]
      },
      {
        type: 'confirm',
        name: 'HTML5Shiv',
        value: 'includeHTML5Shiv',
        message: 'Would you like to use a crossbrowser workaround to ' + chalk.red('HTML5') + '?',
        when: function(answers) {
          return !this.hasFeature(answers.features, 'includeModernizr');
        }.bind(this)
      },
      {
        type: 'confirm',
        name: 'Sizzle',
        value: 'includeSizzle',
        message: 'Would you like to use a pure-JavaScript CSS selector engine?',
        when: function(answers) {
          return !this.hasFeature(answers.features, 'includejQuery');
        }.bind(this)
      }
    ];
    this.prompt(prompts, function(answers) {
      // Package managers
      this.includeBower = this.hasFeature(answers.features, 'includeBower');
      this.includeComponent = this.hasFeature(answers.features, 'includeComponent');

      // HTML features
      this.includeJade = this.hasFeature(answers.features, 'includeJade');
      this.includeModernizr = this.hasFeature(answers.features, 'includeModernizr');
      this.includeHTML5Shiv = answers.HTML5Shiv;
      this.hasHTML5Feat = this.includeModernizr || this.includeHTML5Shiv;

      // CSS features
      this.includeTheme = this.hasFeature(answers.features, 'includeTheme');

      // JS features
      this.includejQuery = this.hasFeature(answers.features, 'includejQuery');
      this.includeSizzle = answers.Sizzle;
      this.includeJSPM = false;
      this.hasJSFeat = this.includejQuery || this.includeSizzle;

      // Features
      this.hasFeat = this.hasHTML5Feat || this.hasJSFeat;
      done();
    }.bind(this));
  },

  writing: {
    tree: function() {
      this.log(chalk.magenta('Tree:'));
      this.mkdir('source/images');
      this.mkdir('source/scripts');
      this.mkdir('source/styles/env');
      this.mkdir('source/styles/theme/typography');
      this.mkdir('source/styles/theme/modules');
      this.mkdir('source/styles/theme/views');
      this.mkdir('tasks');
    },

    work: function() {
      this.copy('README.md', 'readme.md');
    },

    bower: function() {
      if (this.includeBower) {
        this.log(chalk.green(' ✓', chalk.white('Bower')));
        this.template('_bower.json', 'bower.json');
        this.copy('bower.rc', '.bowerrc');
      }
    },

    component: function() {
      if (this.includeComponent) {
        this.log(chalk.green(' ✓', chalk.white('Component')));
        this.template('_component.json', 'component.json');
      }
    },

    grunt: function() {
      this.log(chalk.green('\n ✓', chalk.white('Grunt')));
      this.copy('_gruntfile.js', 'gruntfile.js');
    },

    npm: function() {
      this.log(chalk.green('\n ✓', chalk.white('NPM')));
      this.template('_package.json', 'package.json');
    },

    git: function() {
      this.log(chalk.green('\n ✓', chalk.white('Git')));
      this.copy('git.ignore', '.gitignore');
    },

    bem: function () {
      this.log(chalk.green('\n ✓', chalk.white('BEM')));
      this.copy('source/styles/env/_Reset.sass', 'source/styles/env/_Reset.sass');
      this.copy('source/styles/env/_Mixins.sass', 'source/styles/env/_Mixins.sass');
      this.copy('source/styles/env/_Vars.sass', 'source/styles/env/_Vars.sass');
      this.copy('source/styles/app.sass', 'source/styles/app.sass');
      this.copy('source/styles/theme/_Vars.sass', 'source/styles/theme/_Vars.sass');
      this.copy('source/styles/theme/_Fonts.sass', 'source/styles/theme/_Fonts.sass');
      this.copy('source/styles/theme/_Animations.sass', 'source/styles/theme/_Animations.sass');
      this.copy('source/styles/theme/_Base.sass', 'source/styles/theme/_Base.sass');
      this.copy('source/styles/theme/_Modules.sass', 'source/styles/theme/_Modules.sass');
      this.copy('source/styles/theme/_States.sass', 'source/styles/theme/_States.sass');
      this.copy('source/styles/theme/_Layout.sass', 'source/styles/theme/_Layout.sass');
      this.copy('source/styles/theme/_Breakpoints.sass', 'source/styles/theme/_Breakpoints.sass');
      this.copy('source/styles/theme/typography/.gitkeep', 'server/.gitkeep');
    },

    images: function() {
      this.log(chalk.green('\n ✓', chalk.white('Images')));
      this.copy('source/images/.gitkeep', 'source/images/.gitkeep');
    },

    scripts: function() {
      this.log(chalk.green('\n ✓', chalk.white('Behaviors')));
      this.template('source/scripts/boot.js', 'source/scripts/boot.js');
    },

    tasks: function() {
      this.log(chalk.green('\n ✓', chalk.white('Tasks')));
      this.copy('tasks/autoprefixer.js', 'tasks/autoprefixer.js');
      this.copy('tasks/browserify.js', 'tasks/browserify.js');
      this.copy('tasks/clean.js', 'tasks/clean.js');
      this.copy('tasks/concurrent.js', 'tasks/concurrent.js');
      this.copy('tasks/copy.js', 'tasks/copy.js');
      this.copy('tasks/cssmin.js', 'tasks/cssmin.js');
      this.template('tasks/exec.js', 'tasks/exec.js');
      this.copy('tasks/imagemin.js', 'tasks/imagemin.js');
      this.copy('tasks/htmlcompressor.js', 'tasks/htmlcompressor.js');
      this.includeJade && this.copy('tasks/jade.js', 'tasks/jade.js');
      this.template('tasks/processhtml.js', 'tasks/processhtml.js');
      this.template('tasks/jshint.js', 'tasks/jshint.js');
      this.copy('tasks/newer.js', 'tasks/newer.js');
      this.copy('tasks/sass.js', 'tasks/sass.js');
      this.copy('tasks/svgmin.js', 'tasks/svgmin.js');
      this.template('tasks/uglify.js', 'tasks/uglify.js');
      this.copy('tasks/watch.js', 'tasks/watch.js');
      this.copy('tasks/aliases.yaml', 'tasks/aliases.yaml');
    },

    writeIndex: function() {
      if (this.includeJade) this.template('source/index.jade', 'source/index.jade');
      else this.template('source/index.html', 'source/index.html');
    }
  },

  install: function() {
    this.hasCfg('component.json') && this.spawnCommand('component', ['install']);
    this.hasCfg('bower.json') && this.bowerInstall();
    this.installDependencies();
  }
});
<commit_msg>Normalize<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var fsx = require('fs-extra')

module.exports = yeoman.generators.Base.extend({
  constructor: function() {
    yeoman.generators.Base.apply(this, arguments);
    this.pkg = require('../package.json');
  },

  hasFeature: function(list, feat) {
    return (list || []).indexOf(feat) !== -1;
  },

  hasCfg: function(file) {
    return fsx.readJsonSync(file, { throws: false });
  },

  askFor: function() {
    var done = this.async();
    this.log(yosay('Welcome to the wondrous ' + chalk.red('Ambox') + ' generator!'));
    var prompts = [
      {
        type: 'checkbox',
        name: 'features',
        message: 'What more would you like?',
        choices: [
          {
            name: 'Bower',
            value: 'includeBower',
            checked: true
          },
          {
            name: 'Component',
            value: 'includeComponent',
            checked: false
          },
          {
            name: 'Jade',
            value: 'includeJade',
            checked: true
          },
          {
            name: 'Theme structure',
            value: 'includeTheme',
            checked: true
          },
          {
            name: 'Modernizr',
            value: 'includeModernizr',
            checked: true
          },
          {
            name: 'jQuery',
            value: 'includejQuery',
            checked: true
          }
        ]
      },
      {
        type: 'confirm',
        name: 'HTML5Shiv',
        value: 'includeHTML5Shiv',
        message: 'Would you like to use a crossbrowser workaround to ' + chalk.red('HTML5') + '?',
        when: function(answers) {
          return !this.hasFeature(answers.features, 'includeModernizr');
        }.bind(this)
      },
      {
        type: 'confirm',
        name: 'Sizzle',
        value: 'includeSizzle',
        message: 'Would you like to use a pure-JavaScript CSS selector engine?',
        when: function(answers) {
          return !this.hasFeature(answers.features, 'includejQuery');
        }.bind(this)
      }
    ];
    this.prompt(prompts, function(answers) {
      // Package managers
      this.includeBower = this.hasFeature(answers.features, 'includeBower');
      this.includeComponent = this.hasFeature(answers.features, 'includeComponent');

      // HTML features
      this.includeJade = this.hasFeature(answers.features, 'includeJade');
      this.includeModernizr = this.hasFeature(answers.features, 'includeModernizr');
      this.includeHTML5Shiv = answers.HTML5Shiv;
      this.hasHTML5Feat = this.includeModernizr || this.includeHTML5Shiv;

      // CSS features
      this.includeTheme = this.hasFeature(answers.features, 'includeTheme');

      // JS features
      this.includejQuery = this.hasFeature(answers.features, 'includejQuery');
      this.includeSizzle = answers.Sizzle;
      this.includeJSPM = false;
      this.hasJSFeat = this.includejQuery || this.includeSizzle;

      // Features
      this.hasFeat = this.hasHTML5Feat || this.hasJSFeat;
      done();
    }.bind(this));
  },

  writing: {
    tree: function() {
      this.log(chalk.magenta('Tree:'));
      this.mkdir('source/images');
      this.mkdir('source/scripts');
      this.mkdir('source/styles/env');
      this.mkdir('source/styles/theme/typography');
      this.mkdir('source/styles/theme/modules');
      this.mkdir('source/styles/theme/views');
      this.mkdir('tasks');
    },

    work: function() {
      this.copy('README.md', 'readme.md');
    },

    bower: function() {
      if (this.includeBower) {
        this.log(chalk.green(' ✓', chalk.white('Bower')));
        this.template('_bower.json', 'bower.json');
        this.copy('bower.rc', '.bowerrc');
      }
    },

    component: function() {
      if (this.includeComponent) {
        this.log(chalk.green(' ✓', chalk.white('Component')));
        this.template('_component.json', 'component.json');
      }
    },

    grunt: function() {
      this.log(chalk.green('\n ✓', chalk.white('Grunt')));
      this.copy('_gruntfile.js', 'gruntfile.js');
    },

    npm: function() {
      this.log(chalk.green('\n ✓', chalk.white('NPM')));
      this.template('_package.json', 'package.json');
    },

    git: function() {
      this.log(chalk.green('\n ✓', chalk.white('Git')));
      this.copy('git.ignore', '.gitignore');
    },

    bem: function () {
      this.log(chalk.green('\n ✓', chalk.white('BEM')));
      this.copy('source/styles/env/_Reset.sass', 'source/styles/env/_Reset.sass');
      this.copy('source/styles/env/_Mixins.sass', 'source/styles/env/_Mixins.sass');
      this.copy('source/styles/env/_Variables.sass', 'source/styles/env/_Variables.sass');
      this.copy('source/styles/app.sass', 'source/styles/app.sass');
      this.copy('source/styles/theme/_Variables.sass', 'source/styles/theme/_Variables.sass');
      this.copy('source/styles/theme/_Fonts.sass', 'source/styles/theme/_Fonts.sass');
      this.copy('source/styles/theme/_Animations.sass', 'source/styles/theme/_Animations.sass');
      this.copy('source/styles/theme/_Base.sass', 'source/styles/theme/_Base.sass');
      this.copy('source/styles/theme/_Modules.sass', 'source/styles/theme/_Modules.sass');
      this.copy('source/styles/theme/_States.sass', 'source/styles/theme/_States.sass');
      this.copy('source/styles/theme/_Layout.sass', 'source/styles/theme/_Layout.sass');
      this.copy('source/styles/theme/_Breakpoints.sass', 'source/styles/theme/_Breakpoints.sass');
      this.copy('source/styles/theme/typography/.gitkeep', 'server/.gitkeep');
    },

    images: function() {
      this.log(chalk.green('\n ✓', chalk.white('Images')));
      this.copy('source/images/.gitkeep', 'source/images/.gitkeep');
    },

    scripts: function() {
      this.log(chalk.green('\n ✓', chalk.white('Behaviors')));
      this.template('source/scripts/boot.js', 'source/scripts/boot.js');
    },

    tasks: function() {
      this.log(chalk.green('\n ✓', chalk.white('Tasks')));
      this.copy('tasks/autoprefixer.js', 'tasks/autoprefixer.js');
      this.copy('tasks/browserify.js', 'tasks/browserify.js');
      this.copy('tasks/clean.js', 'tasks/clean.js');
      this.copy('tasks/concurrent.js', 'tasks/concurrent.js');
      this.copy('tasks/copy.js', 'tasks/copy.js');
      this.copy('tasks/cssmin.js', 'tasks/cssmin.js');
      this.template('tasks/exec.js', 'tasks/exec.js');
      this.copy('tasks/imagemin.js', 'tasks/imagemin.js');
      this.copy('tasks/htmlcompressor.js', 'tasks/htmlcompressor.js');
      this.includeJade && this.copy('tasks/jade.js', 'tasks/jade.js');
      this.template('tasks/processhtml.js', 'tasks/processhtml.js');
      this.template('tasks/jshint.js', 'tasks/jshint.js');
      this.copy('tasks/newer.js', 'tasks/newer.js');
      this.copy('tasks/sass.js', 'tasks/sass.js');
      this.copy('tasks/svgmin.js', 'tasks/svgmin.js');
      this.template('tasks/uglify.js', 'tasks/uglify.js');
      this.copy('tasks/watch.js', 'tasks/watch.js');
      this.copy('tasks/aliases.yaml', 'tasks/aliases.yaml');
    },

    writeIndex: function() {
      if (this.includeJade) this.template('source/index.jade', 'source/index.jade');
      else this.template('source/index.html', 'source/index.html');
    }
  },

  install: function() {
    this.hasCfg('component.json') && this.spawnCommand('component', ['install']);
    this.hasCfg('bower.json') && this.bowerInstall();
    this.installDependencies();
  }
});
<|endoftext|>


<commit_before>import { Map as ImmutableMap, List } from 'immutable';

import React from 'react';
import { connect } from 'react-redux';

import page from 'page';

import { max } from 'd3-array';

import {m52ToAggregated, hierarchicalAggregated, hierarchicalM52}  from '../../../../shared/js/finance/memoized';
import {default as visit, flattenTree} from '../../../../shared/js/finance/visitHierarchical.js';

import { DF, DI } from '../../../../shared/js/finance/constants';

const rubriqueIdToLabel = require('../../../../shared/js/finance/m52FonctionLabels.json');

import StackChart from '../../../../shared/js/components/StackChart';
import {makeAmountString, default as MoneyAmount} from '../../../../shared/js/components/MoneyAmount';

import PageTitle from '../../../../shared/js/components/gironde.fr/PageTitle';
import SecundaryTitle from '../../../../shared/js/components/gironde.fr/SecundaryTitle';
import DownloadSection from '../../../../shared/js/components/gironde.fr/DownloadSection';

import {CHANGE_EXPLORATION_YEAR} from '../../constants/actions';

import colorClassById from '../../colorClassById';

import FinanceElementContext from '../FinanceElementContext';
import RollingNumber from '../RollingNumber';

/*
    In this component, there are several usages of dangerouslySetInnerHTML.

    In the context of the public dataviz project, the strings being used are HTML generated by
    a markdown parser+renderer. This part is considered trusted enough.

    The content being passed to the markdown parser is created and reviewed by the project team and likely
    by the communication team at the Département de la Gironde. So this content is very very unlikely to ever
    contain anything that could cause any harm.

    For these reasons, the usages of dangerouslySetInnerHTML are fine.
*/

/*

interface FinanceElementProps{
    contentId: string,
    amount, // amount of this element
    aboveTotal, // amount of the element in the above category
    topTotal // amount of total expenditures or revenue
    texts: FinanceElementTextsRecord,

    // the partition will be displayed in the order it's passed. Sort beforehand if necessary
    partition: Array<{
        contentId: string,
        partAmount: number,
        texts: FinanceElementTextsRecord,
        url: stringMarkdown
    }>
}

*/

export function FinanceElement({contentId, RDFI, amountByYear, contextElements, texts, partitionByYear, year, m52Rows, changeExplorationYear, screenWidth}) {
    const label = texts && texts.label || '';
    const atemporalText = texts && texts.atemporal;
    const temporalText = texts && texts.temporal;

    const amount = amountByYear.get(year);

    const years = partitionByYear.keySeq().toJS();

    // sort all partitions part according to the order of the last year partition
    let lastYearPartition = partitionByYear.get(max(years))
    lastYearPartition = lastYearPartition && lastYearPartition.sort((p1, p2) => p2.partAmount - p1.partAmount);
    const partitionIdsInOrder = lastYearPartition && lastYearPartition.map(p => p.contentId) || [];

    // reorder all partitions so they adhere to partitionIdsInOrder
    partitionByYear = partitionByYear.map(partition => {
        // indexOf inside a .map leads to O(n^2), but lists are 10 elements long max, so it's ok
        return partition && partition.sort((p1, p2) => partitionIdsInOrder.indexOf(p1.contentId) - partitionIdsInOrder.indexOf(p2.contentId))
    })

    let thisYearPartition = partitionByYear.get(year);

    let barchartPartitionByYear = partitionByYear;
    if(contentId === 'DF'){
        // For DF, for the split thing at the end, the whole partition is needed.
        // However, DF-1 === DF-2, so for the barchart, we only want one of them with the label "solidarité"
        barchartPartitionByYear = barchartPartitionByYear.map(partition => {
            partition = partition.remove(partition.findIndex(p => p.contentId === 'DF-1'))

            const df2 = partition.find(p => p.contentId === 'DF-2');

            return partition.set(partition.findIndex(p => p.contentId === 'DF-2'), {
                contentId: df2.contentId,
                partAmount: df2.partAmount,
                texts: df2.texts && df2.texts.set('label', [
                    'Actions sociales ',
                    React.createElement('a', {href: '#!/finance-details/DF-1'}, '(par prestation)'),
                    ' - ',
                    React.createElement('a', {href: '#!/finance-details/DF-2'}, '(par public)')
                ]),
                url: undefined
            });
        })

        // temporarily don't display DF-1
        thisYearPartition = thisYearPartition && thisYearPartition.remove(
            thisYearPartition.findIndex(p => p.contentId === 'DF-1')
        )
    }

    const legendItemIds = barchartPartitionByYear
    .map(partition => partition.map(part => part.contentId).toSet())
    .toSet().flatten().toArray();

    const legendItems = legendItemIds.map(id => {
        let found;

        barchartPartitionByYear.find(partition => {
            found = partition.find(p => p.contentId === id )
            return found;
        })

        return {
            id: found.contentId,
            className: found.contentId,
            url: found.url,
            text: found.texts && found.texts.label,
            colorClassName: colorClassById.get(found.contentId)
        }
    })

    const RDFIText = RDFI === DF ?
        'Dépense de fonctionnement' :
        RDFI === DI ?
            `Dépense d'investissement`:
            '';

    const isLeaf = !(thisYearPartition && thisYearPartition.size >= 2);

    return React.createElement('article', {className: 'finance-element'},
        React.createElement(PageTitle, {text: RDFI ?
            `${RDFIText} - ${label} en ${year}` :
            `${label} en ${year}`}),
        React.createElement('section', {},
            React.createElement('div', {className: 'top-infos'},
                contextElements ? React.createElement(FinanceElementContext, { contextElements }) : undefined,
                React.createElement('div', {},
                    React.createElement('h2', {}, React.createElement(RollingNumber, {amount})),
                    atemporalText ? React.createElement('div', {className: 'atemporal', dangerouslySetInnerHTML: {__html: atemporalText}}) : undefined
                )
            )
        ),

        React.createElement('section', {},
            React.createElement(SecundaryTitle, {text: 'Évolution sur ces dernières années'}),
            temporalText ? React.createElement('div', {className: 'temporal', dangerouslySetInnerHTML: {__html: temporalText}}) : undefined,
            React.createElement(StackChart, {
                WIDTH: screenWidth >= 800 + 80 ?
                    800 :
                    (screenWidth - 85 >= 600 ? screenWidth - 85 : (
                        screenWidth <= 600 ? screenWidth - 10 : 600
                    )),
                portrait: screenWidth <= 600,
                xs: years,
                ysByX: barchartPartitionByYear.map(partition => partition.map(part => part.partAmount)),
                selectedX: year,
                onSelectedXAxisItem: changeExplorationYear,
                onBrickClicked: !isLeaf ? (year, id) => {
                    const url = barchartPartitionByYear.get(year).find(e => e.contentId === id).url;
                    page(url);
                } : undefined,
                legendItems: !isLeaf ? legendItems : undefined,
                uniqueColorClass: isLeaf ? colorClassById.get(contentId) : undefined,
                yValueDisplay: makeAmountString
            })
        ),

        isLeaf && m52Rows ? React.createElement('section', { className: 'raw-data'},
            React.createElement(SecundaryTitle, {text: `Consultez ces données en détail à la norme comptable M52 pour l'année ${year}`}),
            React.createElement('table', {},
                React.createElement('thead', {},
                    React.createElement('tr', {},
                        React.createElement('th', {}, 'Fonction'),
                        React.createElement('th', {}, 'Nature'),
                        React.createElement('th', {}, 'Montant')
                    )
                ),
                React.createElement('tbody', {},
                    m52Rows
                    .sort((r1, r2) => r2['Montant'] - r1['Montant'])
                    .map(row => {
                        return React.createElement('tr', {},
                            React.createElement('td', {}, rubriqueIdToLabel[row['Rubrique fonctionnelle']]),
                            React.createElement('td', {}, row['Libellé']),
                            React.createElement('td', {},
                                React.createElement(MoneyAmount, {amount: row['Montant']})
                            )
                        )
                    })
                )
            ),
            React.createElement(
                DownloadSection,
                {
                    title: `Données brutes sur datalocale.fr`,
                    items: [
                        {
                            text: 'Comptes administratifs du Département de la Gironde',
                            url: 'https://www.datalocale.fr/dataset/comptes-administratifs-du-departement-de-la-gironde'
                        }
                    ]
                }
            )
        ) : undefined

    );
}

export function makePartition(element, totalById, textsById){
    if(!element){
        return new List();
    }

    let children = element.children;
    children = children && typeof children.toList === 'function' ? children.toList() : children;

    return children && children.size >= 1 ?
        List(children)
        .map(child => ({
            contentId: child.id,
            partAmount: totalById.get(child.id),
            texts: textsById.get(child.id),
            url: `#!/finance-details/${child.id}`
        })) :
        List().push({
            contentId: element.id,
            partAmount: totalById.get(element.id),
            texts: textsById.get(element.id),
            url: `#!/finance-details/${element.id}`
        });
}

export function makeElementById(hierAgg, hierM52 = {}){
    let elementById = new ImmutableMap();

    flattenTree(hierAgg).forEach(aggHierNode => {
        elementById = elementById.set(aggHierNode.id, aggHierNode);
    });

    flattenTree(hierM52).forEach(m52HierNode => {
        elementById = elementById.set(m52HierNode.id, m52HierNode);
    });

    return elementById;
}

function fillChildToParent(tree, wm){
    visit(tree, e => {
        if(e.children){
            e.children.forEach(c => {
                wm.set(c, e);
            })
        }
    });
}

function makeContextList(element, childToParent){
    let contextList = [];
    let next = element;

    while(next){
        contextList.push(next);
        next = childToParent.get(next);
    }

    contextList = contextList
    // furtherest context first
    .reverse()
    // remove TOTAL
    .slice(1);

    if(contextList.length > 4){
        const [c1, c2, c3] = contextList;
        const [last] = contextList.slice(-1);

        contextList = [c1, c2, c3, last];
    }

    return contextList;
}

export default connect(
    state => {
        const { m52InstructionByYear, corrections, textsById, financeDetailId, explorationYear, screenWidth } = state;

        const isM52Element = financeDetailId.startsWith('M52-');

        let RDFI;
        if(isM52Element){
            RDFI = financeDetailId.slice(4, 4+2);
        }

        const m52Instruction = m52InstructionByYear.get(explorationYear);
        const hierM52 = m52Instruction && RDFI && hierarchicalM52(m52Instruction, RDFI);
        const aggregated = m52Instruction && corrections && m52ToAggregated(m52Instruction, corrections);
        const hierAgg = m52Instruction && hierarchicalAggregated(aggregated);

        const childToParent = new WeakMap();
        if(m52Instruction){
            if(hierM52)
                fillChildToParent(hierM52, childToParent);

            fillChildToParent(hierAgg, childToParent);
        }

        const displayedContentId = financeDetailId;

        const elementById = (m52Instruction && makeElementById(hierAgg, hierM52)) || new ImmutableMap();
        const element = elementById.get(displayedContentId);

        const contextList = makeContextList(element, childToParent);

        const partitionByYear = m52InstructionByYear.map(m52i => {
            const elementById = makeElementById(
                hierarchicalAggregated(m52ToAggregated(m52i, corrections)),
                RDFI ? hierarchicalM52(m52i, RDFI): undefined
            );

            const yearElement = elementById.get(displayedContentId);

            return makePartition(yearElement, elementById.map(e => e.total), textsById)
        });

        const amountByYear = m52InstructionByYear.map((m52i) => {
            const elementById = makeElementById(
                hierarchicalAggregated(m52ToAggregated(m52i, corrections)),
                RDFI ? hierarchicalM52(m52i, RDFI): undefined
            );

            const yearElement = elementById.get(displayedContentId);

            return yearElement && yearElement.total;
        });

        const m52Rows = element && (!element.children || element.children.size === 0) ?
            (isM52Element ?
                 element.elements :
                 element.elements.first()['M52Rows']
            ) :
            undefined;

        const texts = textsById.get(displayedContentId);

        return {
            contentId: displayedContentId,
            RDFI,
            amountByYear,
            contextElements: contextList.map((c, i) => ({
                id: c.id,
                url : c.id !== displayedContentId ? '#!/finance-details/'+c.id : undefined,
                proportion : c.total/contextList[0].total,
                colorClass : colorClassById.get(c.id),
                label: textsById.get(c.id).label +
                    (contextList.length >= 2 && i === contextList.length -1 ?
                        ` (${(c.total*100/contextList[0].total).toFixed(1)}%)` :
                        '')
            })),
            texts,
            partitionByYear,
            m52Rows,
            year: explorationYear,
            screenWidth
        }

    },
    dispatch => ({
        changeExplorationYear(year){
            dispatch({
                type: CHANGE_EXPLORATION_YEAR,
                year
            })
        }
    })
)(FinanceElement);
<commit_msg>Correction d'un mismatch entre les légendes et couleurs du stackchart pour les éléments de la M52 par fonction<commit_after>import { Map as ImmutableMap, List, Set as ImmutableSet } from 'immutable';

import React from 'react';
import { connect } from 'react-redux';

import page from 'page';

import { max } from 'd3-array';

import {m52ToAggregated, hierarchicalAggregated, hierarchicalM52}  from '../../../../shared/js/finance/memoized';
import {default as visit, flattenTree} from '../../../../shared/js/finance/visitHierarchical.js';

import { DF, DI } from '../../../../shared/js/finance/constants';

const rubriqueIdToLabel = require('../../../../shared/js/finance/m52FonctionLabels.json');

import StackChart from '../../../../shared/js/components/StackChart';
import {makeAmountString, default as MoneyAmount} from '../../../../shared/js/components/MoneyAmount';

import PageTitle from '../../../../shared/js/components/gironde.fr/PageTitle';
import SecundaryTitle from '../../../../shared/js/components/gironde.fr/SecundaryTitle';
import DownloadSection from '../../../../shared/js/components/gironde.fr/DownloadSection';

import {CHANGE_EXPLORATION_YEAR} from '../../constants/actions';

import colorClassById from '../../colorClassById';

import FinanceElementContext from '../FinanceElementContext';
import RollingNumber from '../RollingNumber';

/*
    In this component, there are several usages of dangerouslySetInnerHTML.

    In the context of the public dataviz project, the strings being used are HTML generated by
    a markdown parser+renderer. This part is considered trusted enough.

    The content being passed to the markdown parser is created and reviewed by the project team and likely
    by the communication team at the Département de la Gironde. So this content is very very unlikely to ever
    contain anything that could cause any harm.

    For these reasons, the usages of dangerouslySetInnerHTML are fine.
*/

/*

interface FinanceElementProps{
    contentId: string,
    amount, // amount of this element
    aboveTotal, // amount of the element in the above category
    topTotal // amount of total expenditures or revenue
    texts: FinanceElementTextsRecord,

    // the partition will be displayed in the order it's passed. Sort beforehand if necessary
    partition: Array<{
        contentId: string,
        partAmount: number,
        texts: FinanceElementTextsRecord,
        url: stringMarkdown
    }>
}

*/

export function FinanceElement({contentId, RDFI, amountByYear, contextElements, texts, partitionByYear, year, m52Rows, changeExplorationYear, screenWidth}) {
    const label = texts && texts.label || '';
    const atemporalText = texts && texts.atemporal;
    const temporalText = texts && texts.temporal;

    const amount = amountByYear.get(year);

    const years = partitionByYear.keySeq().toJS();

    // sort all partitions part according to the order of the last year partition
    let lastYearPartition = partitionByYear.get(max(years))
    lastYearPartition = lastYearPartition && lastYearPartition.sort((p1, p2) => p2.partAmount - p1.partAmount);
    const partitionIdsInOrder = lastYearPartition && lastYearPartition.map(p => p.contentId) || [];

    // reorder all partitions so they adhere to partitionIdsInOrder
    partitionByYear = partitionByYear.map(partition => {
        // indexOf inside a .map leads to O(n^2), but lists are 10 elements long max, so it's ok
        return partition && partition.sort((p1, p2) => partitionIdsInOrder.indexOf(p1.contentId) - partitionIdsInOrder.indexOf(p2.contentId))
    })

    let thisYearPartition = partitionByYear.get(year);

    let barchartPartitionByYear = partitionByYear;
    if(contentId === 'DF'){
        // For DF, for the split thing at the end, the whole partition is needed.
        // However, DF-1 === DF-2, so for the barchart, we only want one of them with the label "solidarité"
        barchartPartitionByYear = barchartPartitionByYear.map(partition => {
            partition = partition.remove(partition.findIndex(p => p.contentId === 'DF-1'))

            const df2 = partition.find(p => p.contentId === 'DF-2');

            return partition.set(partition.findIndex(p => p.contentId === 'DF-2'), {
                contentId: df2.contentId,
                partAmount: df2.partAmount,
                texts: df2.texts && df2.texts.set('label', [
                    'Actions sociales ',
                    React.createElement('a', {href: '#!/finance-details/DF-1'}, '(par prestation)'),
                    ' - ',
                    React.createElement('a', {href: '#!/finance-details/DF-2'}, '(par public)')
                ]),
                url: undefined
            });
        })

        // temporarily don't display DF-1
        thisYearPartition = thisYearPartition && thisYearPartition.remove(
            thisYearPartition.findIndex(p => p.contentId === 'DF-1')
        )
    }

    const legendItemIds = barchartPartitionByYear
    .map(partition => partition.map(part => part.contentId).toSet())
    .toSet().flatten().toArray();

    const legendItems = legendItemIds.map(id => {
        let found;

        barchartPartitionByYear.find(partition => {
            found = partition.find(p => p.contentId === id )
            return found;
        })

        return {
            id: found.contentId,
            className: found.contentId,
            url: found.url,
            text: found.texts && found.texts.label,
            colorClassName: colorClassById.get(found.contentId)
        }
    })

    const RDFIText = RDFI === DF ?
        'Dépense de fonctionnement' :
        RDFI === DI ?
            `Dépense d'investissement`:
            '';

    const isLeaf = !(thisYearPartition && thisYearPartition.size >= 2);

    return React.createElement('article', {className: 'finance-element'},
        React.createElement(PageTitle, {text: RDFI ?
            `${RDFIText} - ${label} en ${year}` :
            `${label} en ${year}`}),
        React.createElement('section', {},
            React.createElement('div', {className: 'top-infos'},
                contextElements ? React.createElement(FinanceElementContext, { contextElements }) : undefined,
                React.createElement('div', {},
                    React.createElement('h2', {}, React.createElement(RollingNumber, {amount})),
                    atemporalText ? React.createElement('div', {className: 'atemporal', dangerouslySetInnerHTML: {__html: atemporalText}}) : undefined
                )
            )
        ),

        React.createElement('section', {},
            React.createElement(SecundaryTitle, {text: 'Évolution sur ces dernières années'}),
            temporalText ? React.createElement('div', {className: 'temporal', dangerouslySetInnerHTML: {__html: temporalText}}) : undefined,
            React.createElement(StackChart, {
                WIDTH: screenWidth >= 800 + 80 ?
                    800 :
                    (screenWidth - 85 >= 600 ? screenWidth - 85 : (
                        screenWidth <= 600 ? screenWidth - 10 : 600
                    )),
                portrait: screenWidth <= 600,
                xs: years,
                ysByX: barchartPartitionByYear.map(partition => partition.map(part => part.partAmount)),
                selectedX: year,
                onSelectedXAxisItem: changeExplorationYear,
                onBrickClicked: !isLeaf ? (year, id) => {
                    const url = barchartPartitionByYear.get(year).find(e => e.contentId === id).url;
                    page(url);
                } : undefined,
                legendItems: !isLeaf ? legendItems : undefined,
                uniqueColorClass: isLeaf ? colorClassById.get(contentId) : undefined,
                yValueDisplay: makeAmountString
            })
        ),

        isLeaf && m52Rows ? React.createElement('section', { className: 'raw-data'},
            React.createElement(SecundaryTitle, {text: `Consultez ces données en détail à la norme comptable M52 pour l'année ${year}`}),
            React.createElement('table', {},
                React.createElement('thead', {},
                    React.createElement('tr', {},
                        React.createElement('th', {}, 'Fonction'),
                        React.createElement('th', {}, 'Nature'),
                        React.createElement('th', {}, 'Montant')
                    )
                ),
                React.createElement('tbody', {},
                    m52Rows
                    .sort((r1, r2) => r2['Montant'] - r1['Montant'])
                    .map(row => {
                        return React.createElement('tr', {},
                            React.createElement('td', {}, rubriqueIdToLabel[row['Rubrique fonctionnelle']]),
                            React.createElement('td', {}, row['Libellé']),
                            React.createElement('td', {},
                                React.createElement(MoneyAmount, {amount: row['Montant']})
                            )
                        )
                    })
                )
            ),
            React.createElement(
                DownloadSection,
                {
                    title: `Données brutes sur datalocale.fr`,
                    items: [
                        {
                            text: 'Comptes administratifs du Département de la Gironde',
                            url: 'https://www.datalocale.fr/dataset/comptes-administratifs-du-departement-de-la-gironde'
                        }
                    ]
                }
            )
        ) : undefined

    );
}

export function makePartition(element, totalById, textsById, possibleChildrenIds){
    if(!element){
        return new List();
    }

    let children = element.children;
    children = children && typeof children.toList === 'function' ? children.toList() : children;

    return children && children.size >= 1 ?
        possibleChildrenIds.map(id => {
            // .find over all possibleChildrenIds is O(n²), but n is small (<= 10)
            const child = children.find(c => c.id === id);

            return {
                contentId: id,
                partAmount: child ? totalById.get(child.id) : 0,
                texts: textsById.get(id),
                url: `#!/finance-details/${id}`
            };
        }) :
        List().push({
            contentId: element.id,
            partAmount: totalById.get(element.id),
            texts: textsById.get(element.id),
            url: `#!/finance-details/${element.id}`
        });
}

export function makeElementById(hierAgg, hierM52 = {}){
    let elementById = new ImmutableMap();

    flattenTree(hierAgg).forEach(aggHierNode => {
        elementById = elementById.set(aggHierNode.id, aggHierNode);
    });

    flattenTree(hierM52).forEach(m52HierNode => {
        elementById = elementById.set(m52HierNode.id, m52HierNode);
    });

    return elementById;
}

function fillChildToParent(tree, wm){
    visit(tree, e => {
        if(e.children){
            e.children.forEach(c => {
                wm.set(c, e);
            })
        }
    });
}

function makeContextList(element, childToParent){
    let contextList = [];
    let next = element;

    while(next){
        contextList.push(next);
        next = childToParent.get(next);
    }

    contextList = contextList
    // furtherest context first
    .reverse()
    // remove TOTAL
    .slice(1);

    if(contextList.length > 4){
        const [c1, c2, c3] = contextList;
        const [last] = contextList.slice(-1);

        contextList = [c1, c2, c3, last];
    }

    return contextList;
}

export default connect(
    state => {
        const { m52InstructionByYear, corrections, textsById, financeDetailId, explorationYear, screenWidth } = state;

        const isM52Element = financeDetailId.startsWith('M52-');

        let RDFI;
        if(isM52Element){
            RDFI = financeDetailId.slice(4, 4+2);
        }

        const m52Instruction = m52InstructionByYear.get(explorationYear);
        const hierM52 = m52Instruction && RDFI && hierarchicalM52(m52Instruction, RDFI);
        const aggregated = m52Instruction && corrections && m52ToAggregated(m52Instruction, corrections);
        const hierAgg = m52Instruction && hierarchicalAggregated(aggregated);

        const childToParent = new WeakMap();
        if(m52Instruction){
            if(hierM52)
                fillChildToParent(hierM52, childToParent);

            fillChildToParent(hierAgg, childToParent);
        }

        const displayedContentId = financeDetailId;

        const elementById = (m52Instruction && makeElementById(hierAgg, hierM52)) || new ImmutableMap();
        const element = elementById.get(displayedContentId);

        const contextList = makeContextList(element, childToParent);

        const elementByIdByYear = m52InstructionByYear.map(m52i => {
            return makeElementById(
                hierarchicalAggregated(m52ToAggregated(m52i, corrections)),
                RDFI ? hierarchicalM52(m52i, RDFI): undefined
            );
        });

        const displayedElementByYear = elementByIdByYear.map(elementById => {
            return elementById.get(displayedContentId);
        })

        // Depending on the year, all elements may not have the same children ids.
        // This is the set of all possible ids for the given years
        const displayedElementPossibleChildrenIds = displayedElementByYear.map(element => {
            if(!element)
                return new ImmutableSet();

            let children = element.children;
            children = children && typeof children.toList === 'function' ? children.toList() : children;

            if(!children)
                return new ImmutableSet();

            return new ImmutableSet(children).map(child => child.id);
        }).toSet().flatten().toList();

        const partitionByYear = elementByIdByYear.map((elementById) => {
            const yearElement = elementById.get(displayedContentId);

            return makePartition(yearElement, elementById.map(e => e.total), textsById, displayedElementPossibleChildrenIds)
        });

        const amountByYear = elementByIdByYear.map((elementById) => {
            const yearElement = elementById.get(displayedContentId);

            return yearElement && yearElement.total;
        });

        const m52Rows = element && (!element.children || element.children.size === 0) ?
            (isM52Element ?
                 element.elements :
                 element.elements.first()['M52Rows']
            ) :
            undefined;

        const texts = textsById.get(displayedContentId);

        return {
            contentId: displayedContentId,
            RDFI,
            amountByYear,
            contextElements: contextList.map((c, i) => ({
                id: c.id,
                url : c.id !== displayedContentId ? '#!/finance-details/'+c.id : undefined,
                proportion : c.total/contextList[0].total,
                colorClass : colorClassById.get(c.id),
                label: textsById.get(c.id).label +
                    (contextList.length >= 2 && i === contextList.length -1 ?
                        ` (${(c.total*100/contextList[0].total).toFixed(1)}%)` :
                        '')
            })),
            texts,
            partitionByYear,
            m52Rows,
            year: explorationYear,
            screenWidth
        }

    },
    dispatch => ({
        changeExplorationYear(year){
            dispatch({
                type: CHANGE_EXPLORATION_YEAR,
                year
            })
        }
    })
)(FinanceElement);
<|endoftext|>


<commit_before>const express = require('express')
const path = require('path')
const nlp = require('compromise')
const sentiment = require('sentiment')
const Twit = require('twit')
const fs = require('fs')

const credentials = require('../../credentials.json')

const app = express()

const analyzeTweet = (tweet) => {

}
const logTweet = (tweet) => {
    const logMessage = `Received tweet: ${JSON.stringify(tweet)}\n\n`
    fs.writeFile(`server/output/tweetResult${tweet.id}.txt`, logMessage, (err) => {
        if (err) {
            return console.log(err)
        }
        console.log(`Logged a tweet: [${tweet.id}]`)
    })
}

const logTweetsWithParams = () => {
    const twitter = new Twit(credentials)
    const sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ]
    const marquetteCampus = [
        '-87.94504165649414', // longitude @ 25th/State St
        '43.04336267974874',  // latitude @ 25th/State St
        '-87.92195320129395', // longitude @ 8th/Michigan St.
        '43.03737183727952'   // latitude @ 8th/Michigan St.
    ]
    const stream = twitter.stream('statuses/filter', { locations: marquetteCampus })
    stream.on('tweet', (tweet) => {
        logTweet(tweet)
    })
}

app.use( (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
    res.setHeader('Access-Control-Allow-Credentials', true)
})

// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'static')))

app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'static', 'public/index.html'))
})

logTweetsWithParams()

module.exports = app<commit_msg>fixed credentials relative filepath<commit_after>const express = require('express')
const path = require('path')
const nlp = require('compromise')
const sentiment = require('sentiment')
const Twit = require('twit')
const fs = require('fs')

const credentials = require('../credentials.json')

const app = express()

const analyzeTweet = (tweet) => {

}
const logTweet = (tweet) => {
    const logMessage = `Received tweet: ${JSON.stringify(tweet)}\n\n`
    fs.writeFile(`server/output/tweetResult${tweet.id}.txt`, logMessage, (err) => {
        if (err) {
            return console.log(err)
        }
        console.log(`Logged a tweet: [${tweet.id}]`)
    })
}

const logTweetsWithParams = () => {
    const twitter = new Twit(credentials)
    const sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ]
    const marquetteCampus = [
        '-87.94504165649414', // longitude @ 25th/State St
        '43.04336267974874',  // latitude @ 25th/State St
        '-87.92195320129395', // longitude @ 8th/Michigan St.
        '43.03737183727952'   // latitude @ 8th/Michigan St.
    ]
    const stream = twitter.stream('statuses/filter', { locations: marquetteCampus })
    stream.on('tweet', (tweet) => {
        logTweet(tweet)
    })
}

app.use( (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
    res.setHeader('Access-Control-Allow-Credentials', true)
})

// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'static')))

app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'static', 'public/index.html'))
})

logTweetsWithParams()

module.exports = app<|endoftext|>


<commit_before>'use strict';

module.exports = function(handler, table) {

    const slots = handler.event.request.intent.slots

    if (slots.Item && slots.Item.value) {
        table
            .find({ hash: handler.event.session.user.userId,
                    range: record
                    })
            .then(function(amount) {
                if (amount != 0) {
                    handler.emit(':tell', this.t('QUANTITY_ZERO', amount.toString()));
                }
                else {
                    handler.emit(':tell', this.t('QUANTITY_NONZERO', amount.toString(), slots.Item.value.toLowerCase()));
                }
            })
            .catch(function(err) {
                console.log(err);
                handler.emit('ERROR');
            });

    } else {
        console.log("error with itemName slot");
        handler.emit('Error')
    }
}
<commit_msg>QueryItem test fix #4?<commit_after>'use strict';

module.exports = function(handler, table) {

    const slots = handler.event.request.intent.slots

    if (slots.Item && slots.Item.value) {
        table
            .find({ hash: handler.event.session.user.userId,
                    range: slots.Item.value
                    })
            .then(function(amount) {
                if (amount != 0) {
                    handler.emit(':tell', this.t('QUANTITY_ZERO', amount.toString()));
                }
                else {
                    handler.emit(':tell', this.t('QUANTITY_NONZERO', amount.toString(), slots.Item.value.toLowerCase()));
                }
            })
            .catch(function(err) {
                console.log(err);
                handler.emit('ERROR');
            });

    } else {
        console.log("error with itemName slot");
        handler.emit('Error')
    }
}
<|endoftext|>