<commit_before>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'],
    function (ext, $, Raphael, Snap) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide = {};
            cur_slide["in"] = data[0];
            this_e.addAnimationSlide(cur_slide);
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'checkio';

            var checkioInput = data.in;
            var checkioInputStr = fname + '(' + JSON.stringify(checkioInput) + ')';

            var failError = function (dError) {
                $content.find('.call').html(checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            $content.find('.call').html(checkioInputStr);
            $content.find('.output').html('Working...');

            if (data.ext) {
                var rightResult = data.ext["answer"];
                var userResult = data.out;
                var result = data.ext["result"];
                var result_addon = data.ext["result_addon"];

                //if you need additional info from tests (if exists)
                var explanation = data.ext["explanation"];
                $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));
                if (!result) {
                    $content.find('.answer').html('Right result: ' + JSON.stringify(rightResult));
                    $content.find('.answer').addClass('error');
                    $content.find('.output').addClass('error');
                    $content.find('.call').addClass('error');
                }
                else {
                    $content.find('.answer').remove();
                }
            }
            else {
                $content.find('.answer').remove();
            }

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        var colorOrange4 = "#F0801A";
        var colorOrange3 = "#FA8F00";
        var colorOrange2 = "#FAA600";
        var colorOrange1 = "#FABA00";

        var colorBlue4 = "#294270";
        var colorBlue3 = "#006CA9";
        var colorBlue2 = "#65A1CF";
        var colorBlue1 = "#8FC7ED";

        var colorGrey4 = "#737370";
        var colorGrey3 = "#9D9E9E";
        var colorGrey2 = "#C5C6C6";
        var colorGrey1 = "#EBEDED";

        var colorWhite = "#FFFFFF";
        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<commit_msg>js function names<commit_after>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'],
    function (ext, $, Raphael, Snap) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide = {};
            cur_slide["in"] = data[0];
            this_e.addAnimationSlide(cur_slide);
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'solver';

            var checkioInput = data.in || ['.XXX.', '...X.', '.X.X.', '.....'];
            var checkioInputStr = fname + '(';
            for (var i = 0; i < checkioInput.length; i++) {
                checkioInputStr += '
u"' + checkioInput[i] + '"';
            }
            checkioInputStr += "),
WORDS)";

            var failError = function (dError) {
                $content.find('.call').html(checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            $content.find('.call').html(checkioInputStr);
            $content.find('.output').html('Working...');

            if (data.ext) {
                var rightResult = data.ext["answer"];
                var userResult = data.out;
                var result = data.ext["result"];
                var result_addon = data.ext["result_addon"];

                //if you need additional info from tests (if exists)
                var explanation = data.ext["explanation"];
                $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));
                if (!result) {
                    $content.find('.answer').html('Right result: ' + JSON.stringify(rightResult));
                    $content.find('.answer').addClass('error');
                    $content.find('.output').addClass('error');
                    $content.find('.call').addClass('error');
                }
                else {
                    $content.find('.answer').remove();
                }
            }
            else {
                $content.find('.answer').remove();
            }

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        var colorOrange4 = "#F0801A";
        var colorOrange3 = "#FA8F00";
        var colorOrange2 = "#FAA600";
        var colorOrange1 = "#FABA00";

        var colorBlue4 = "#294270";
        var colorBlue3 = "#006CA9";
        var colorBlue2 = "#65A1CF";
        var colorBlue1 = "#8FC7ED";

        var colorGrey4 = "#737370";
        var colorGrey3 = "#9D9E9E";
        var colorGrey2 = "#C5C6C6";
        var colorGrey1 = "#EBEDED";

        var colorWhite = "#FFFFFF";
        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.events')
    .directive('browseGrid', browseGrid)
    .controller('BrowseGridController', BrowseGridController);

  // @ngInject
  function browseGrid() {
    var directive = {
      restrict: 'E',
      replace: true,
      scope: {
        mode: '=',
        page: '='
      },
      templateUrl: 'app/views/browse/directives/browseGrid.tpl.html',
      controller: 'BrowseGridController'
    };
    return directive;
  }

  // @ngInject
  function BrowseGridController($scope, $state, $location, $log, uiGridConstants, _,
                                Datatables) {
    var ctrl = $scope.ctrl = {};

    var pageCount = 25;
    var maxRows = ctrl.maxRows = pageCount;

    // declare ui paging/sorting/filtering vars
    ctrl.mode = $scope.mode;
    ctrl.totalItems = Number();
    ctrl.page = $scope.page;
    ctrl.count= Number();

    ctrl.filters = [];
    ctrl.sorting = [{
      field: $scope.mode === 'variants' ? 'variant' : 'name',
      direction: 'asc'
    }];

    $scope.$watch('ctrl.totalItems', function() {
      ctrl.totalPages = Math.ceil(ctrl.totalItems / pageCount);
    });

    ctrl.gridOptions = {
      enablePaginationControls: false,

      useExternalFiltering: true,
      useExternalSorting: true,
      useExternalPaging: true,

      paginationPageSizes: [maxRows],
      paginationPageSize: maxRows,
      minRowsToShow: maxRows + 1,

      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,

      enableFiltering: true,
      enableColumnMenus: false,
      enableSorting: true,
      enableRowSelection: true,
      enableRowHeaderSelection: false,
      multiSelect: false,
      modifierKeysToMultiSelect: false,
      noUnselect: true,
      rowTemplate: 'app/views/browse/browseGridRow.tpl.html'
    };

    // set up column defs and data transforms for each mode
    var modeColumnDefs = {
      'variants': [
        {
          name: 'variant',
          width: '30%',
          sort: { direction: uiGridConstants.ASC },
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'entrez_gene',
          width: '15%',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'diseases',
          displayName: 'Diseases',
          width: '45%',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/browse/browseGridTooltipCell.tpl.html'
        },
        {
          name: 'evidence_item_count',
          width: '10%',
          displayName: 'Evidence',
          enableFiltering: false,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        }
      ],
      'genes': [
        {
          name: 'name',
          width: '15%',
          sort: {direction: uiGridConstants.ASC},
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'gene_aliases',
          width: '30%',
          displayName: 'Gene Aliases',
          enableFiltering: true,
          allowCellFocus: false,
          cellTemplate: 'app/views/browse/browseGridTooltipCell.tpl.html',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'diseases',
          //width: '30%',
          displayName: 'Diseases',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/browse/browseGridTooltipCell.tpl.html'
        },
        {
          name: 'variant_count',
          displayName: 'Variants',
          width: '10%',
          enableFiltering: false,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'evidence_item_count',
          width: '10%',
          displayName: 'Evidence',
          enableFiltering: false,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        }
      ]
    };

    ctrl.gridOptions.onRegisterApi = function(gridApi) {
      ctrl.gridApi = gridApi;
      // called from pagination directive when page changes
      ctrl.pageChanged = function() {
        $log.info('page changed: ' + ctrl.page);
        $location.search('page', ctrl.page);
        updateData();
      };

      // reset paging and do some other stuff on filter changes
      gridApi.core.on.filterChanged($scope, function() {
        $log.info('filter changed.');
        // updateData with new filters
        var filteredCols = _.filter(this.grid.columns, function(col) {
          return _.has(col.filter, 'term') && !_.isEmpty(col.filter.term) && _.isString(col.filter.term);
        });
        if (filteredCols.length > 0) {
          ctrl.filters = _.map(filteredCols, function(col) {
            return {
              'field': col.field,
              'term': col.filter.term
            };
          });
        } else {
          ctrl.filters = [];
        }
        ctrl.page = 1;
        updateData();
      });

      gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
        $log.info('sort changed.');
        if (sortColumns.length > 0) {
          ctrl.sorting = _.map(sortColumns, function(col) {
            return {
              'field': col.field,
              'direction': col.sort.direction
            };
          });
        } else {
          ctrl.sorting = [];
        }
        updateData();
      });

      // called when user clicks on a row
      gridApi.selection.on.rowSelectionChanged($scope, function(row){
        // $log.info(['geneID:', row.entity.id, 'variantId:', row.entity.variant_id].join(' '));
        $log.info(['ctrl.mode:', ctrl.mode, 'geneId:', row.entity.gene_id, 'variantId:', row.entity.variant_id].join(' '));
        if(ctrl.mode === 'variants') {
          $state.go('events.genes.summary.variants.summary', {
            geneId: row.entity.gene_id,
            variantId: row.entity.variant_id,
            '#': 'variant'
          });
        } else {
          $state.go('events.genes.summary', {
            geneId: row.entity.id,
            '#': 'gene'
          });
        }
      });
    };

    function updateData() {
      fetchData(ctrl.mode, ctrl.count, ctrl.page, ctrl.sorting, ctrl.filters)
        .then(function(data){
          ctrl.gridOptions.data = data.result;
          ctrl.gridOptions.columnDefs = modeColumnDefs[ctrl.mode];
          ctrl.totalItems = data.total;
        });
    }

    function fetchData(mode, count, page, sorting, filters) {
      var request;

      request= {
        mode: mode,
        count: count,
        page: page
      };

      if (filters.length > 0) {
        _.each(filters, function(filter) {
          request['filter[' + filter.field + ']'] = filter.term;
        });
      }

      if (sorting.length > 0) {
        _.each(sorting, function(sort) {
          request['sorting[' + sort.field + ']'] = sort.direction;
        });
      }
      return Datatables.query(request);
    }

    updateData();
  }
})();
<commit_msg>Change default sort on 'browse' tables.<commit_after>(function() {
  'use strict';
  angular.module('civic.events')
    .directive('browseGrid', browseGrid)
    .controller('BrowseGridController', BrowseGridController);

  // @ngInject
  function browseGrid() {
    var directive = {
      restrict: 'E',
      replace: true,
      scope: {
        mode: '=',
        page: '='
      },
      templateUrl: 'app/views/browse/directives/browseGrid.tpl.html',
      controller: 'BrowseGridController'
    };
    return directive;
  }

  // @ngInject
  function BrowseGridController($scope, $state, $location, $log, uiGridConstants, _,
                                Datatables) {
    var ctrl = $scope.ctrl = {};

    var pageCount = 25;
    var maxRows = ctrl.maxRows = pageCount;

    // declare ui paging/sorting/filtering vars
    ctrl.mode = $scope.mode;
    ctrl.totalItems = Number();
    ctrl.page = $scope.page;
    ctrl.count= Number();

    ctrl.filters = [];
    ctrl.sorting = [{
      field: 'evidence_item_count',
      direction: 'desc'
    }];

    $scope.$watch('ctrl.totalItems', function() {
      ctrl.totalPages = Math.ceil(ctrl.totalItems / pageCount);
    });

    ctrl.gridOptions = {
      enablePaginationControls: false,

      useExternalFiltering: true,
      useExternalSorting: true,
      useExternalPaging: true,

      paginationPageSizes: [maxRows],
      paginationPageSize: maxRows,
      minRowsToShow: maxRows + 1,

      enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
      enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,

      enableFiltering: true,
      enableColumnMenus: false,
      enableSorting: true,
      enableRowSelection: true,
      enableRowHeaderSelection: false,
      multiSelect: false,
      modifierKeysToMultiSelect: false,
      noUnselect: true,
      rowTemplate: 'app/views/browse/browseGridRow.tpl.html'
    };

    // set up column defs and data transforms for each mode
    var modeColumnDefs = {
      'variants': [
        {
          name: 'variant',
          width: '30%',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'entrez_gene',
          width: '15%',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'diseases',
          displayName: 'Diseases',
          width: '45%',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/browse/browseGridTooltipCell.tpl.html'
        },
        {
          name: 'evidence_item_count',
          width: '10%',
          displayName: 'Evidence',
          sort: {
            direction: uiGridConstants.DESC
          },
          enableFiltering: false,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        }
      ],
      'genes': [
        {
          name: 'name',
          width: '15%',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'gene_aliases',
          width: '30%',
          displayName: 'Gene Aliases',
          enableFiltering: true,
          allowCellFocus: false,
          cellTemplate: 'app/views/browse/browseGridTooltipCell.tpl.html',
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'diseases',
          //width: '30%',
          displayName: 'Diseases',
          enableFiltering: true,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          },
          cellTemplate: 'app/views/browse/browseGridTooltipCell.tpl.html'
        },
        {
          name: 'variant_count',
          displayName: 'Variants',
          width: '10%',
          enableFiltering: false,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        },
        {
          name: 'evidence_item_count',
          width: '10%',
          displayName: 'Evidence',
          sort: {
            direction: uiGridConstants.DESC
          },
          enableFiltering: false,
          allowCellFocus: false,
          filter: {
            condition: uiGridConstants.filter.CONTAINS
          }
        }
      ]
    };

    ctrl.gridOptions.onRegisterApi = function(gridApi) {
      ctrl.gridApi = gridApi;
      // called from pagination directive when page changes
      ctrl.pageChanged = function() {
        $log.info('page changed: ' + ctrl.page);
        $location.search('page', ctrl.page);
        updateData();
      };

      // reset paging and do some other stuff on filter changes
      gridApi.core.on.filterChanged($scope, function() {
        $log.info('filter changed.');
        // updateData with new filters
        var filteredCols = _.filter(this.grid.columns, function(col) {
          return _.has(col.filter, 'term') && !_.isEmpty(col.filter.term) && _.isString(col.filter.term);
        });
        if (filteredCols.length > 0) {
          ctrl.filters = _.map(filteredCols, function(col) {
            return {
              'field': col.field,
              'term': col.filter.term
            };
          });
        } else {
          ctrl.filters = [];
        }
        ctrl.page = 1;
        updateData();
      });

      gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
        $log.info('sort changed.');
        if (sortColumns.length > 0) {
          ctrl.sorting = _.map(sortColumns, function(col) {
            return {
              'field': col.field,
              'direction': col.sort.direction
            };
          });
        } else {
          ctrl.sorting = [];
        }
        updateData();
      });

      // called when user clicks on a row
      gridApi.selection.on.rowSelectionChanged($scope, function(row){
        // $log.info(['geneID:', row.entity.id, 'variantId:', row.entity.variant_id].join(' '));
        $log.info(['ctrl.mode:', ctrl.mode, 'geneId:', row.entity.gene_id, 'variantId:', row.entity.variant_id].join(' '));
        if(ctrl.mode === 'variants') {
          $state.go('events.genes.summary.variants.summary', {
            geneId: row.entity.gene_id,
            variantId: row.entity.variant_id,
            '#': 'variant'
          });
        } else {
          $state.go('events.genes.summary', {
            geneId: row.entity.id,
            '#': 'gene'
          });
        }
      });
    };

    function updateData() {
      fetchData(ctrl.mode, ctrl.count, ctrl.page, ctrl.sorting, ctrl.filters)
        .then(function(data){
          ctrl.gridOptions.data = data.result;
          ctrl.gridOptions.columnDefs = modeColumnDefs[ctrl.mode];
          ctrl.totalItems = data.total;
        });
    }

    function fetchData(mode, count, page, sorting, filters) {
      var request;

      request= {
        mode: mode,
        count: count,
        page: page
      };

      if (filters.length > 0) {
        _.each(filters, function(filter) {
          request['filter[' + filter.field + ']'] = filter.term;
        });
      }

      if (sorting.length > 0) {
        _.each(sorting, function(sort) {
          request['sorting[' + sort.field + ']'] = sort.direction;
        });
      }
      return Datatables.query(request);
    }

    updateData();
  }
})();
<|endoftext|>


<commit_before>var targetter = {

    /** @param {creep} creep**/
    source: function(creep) {
        var sources = creep.room.find(FIND_SOURCES);
        targetSource = sources[0];
        return targetSource
    },

    spawner: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                    structure.energy < structure.energyCapacity;
            }
        });

        targetSpawner = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
        return targetSpawner

    },

    store: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_STORAGE) &&
                    structure.energy < structure.energyCapacity;
            }
        });

        if (targets.length > 0) {
            targetStorage = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetStorage
        } else{
            var targets = creep.room.find(FIND_STRUCTURES, {
                filter: (structure) => {
                    return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                        structure.energy < structure.energyCapacity;
                }
            });

            targetSpawner = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetSpawner
        }

    },

    withdraw: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_STORAGE) &&
                    structure.energy > 0;
            }
        });

        if (targets.length > 0) {
            targetStorage = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetStorage
        } else{
            var targets = creep.room.find(FIND_SOURCES, {
                filter: (source) => {
                    return source.energy < source.energyCapacity;
                }
            });

            targetSource = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetSource
        }

    }
};

module.exports = targetter;<commit_msg>Building targetting added<commit_after>var targetter = {

    /** @param {creep} creep**/
    source: function(creep) {
        var targets = creep.room.find(FIND_SOURCES, {
            filter: (source) => {
                return source.energy < source.energyCapacity;
            }
        });

        targetSource = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
        return targetSource
    },

    spawner: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                    structure.energy < structure.energyCapacity;
            }
        });

        targetSpawner = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
        return targetSpawner

    },

    store: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_STORAGE) &&
                    structure.energy < structure.energyCapacity;
            }
        });

        if (targets.length > 0) {
            targetStorage = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetStorage
        } else{
            var targets = creep.room.find(FIND_STRUCTURES, {
                filter: (structure) => {
                    return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                        structure.energy < structure.energyCapacity;
                }
            });

            targetSpawner = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetSpawner
        }
    },

    withdraw: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_STORAGE) &&
                    structure.energy > 0;
            }
        });

        if (targets.length > 0) {
            targetStorage = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetStorage
        } else{
            var targets = creep.room.find(FIND_SOURCES, {
                filter: (source) => {
                    return source.energy < source.energyCapacity;
                }
            });

            targetSource = _.sortBy(targets, t => creep.pos.getRangeTo(t))[0];
            return targetSource
        }
    },

    build: function(creep) {
        var roads = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_ROAD && structure.hits < 0.20*structure.hitsMax;
            }
        });

        if (roads.length > 0) {
            targetRoad = _.sortBy(roads, r => r.hits)[0];
            return targetRoad
        }

        var constucts = creep.room.find(FIND_CONSTRUCTION_SITES);

        if (constucts.length > 0) {
            targetConstruct = _.sortBy(constucts, c => c.progress/c.progressTotal)[0];
            return targetConstruct
        }

        var walls = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return structure.structureType == STRUCTURE_WALL;
            }
        });

        if (walls.length > 0) {
            targetWall = _.sortBy(walls, w => w.hits)[0];
            return targetWall
        }
    }
};

module.exports = targetter;<|endoftext|>


<commit_before>/* Main endpoints for the Polyfill service public API */

'use strict';

const polyfillio = require('../../lib');
const PolyfillSet = require('../PolyfillSet');
const metrics = require('../metrics');
const express = require('express');

const router = express.Router();  // eslint-disable-line new-cap
const contentTypes = {".js": 'application/javascript', ".css": 'text/css'};
const one_day = 60 * 60 * 24;
const one_week = one_day * 7;
const one_year = one_day * 365;

router.get(/^\/v1\/(.*)/, (req, res) => {

	const qs = Object.keys(req.query).reduce((out, key) => {
		if (key !== 'libVersion' && key !== 'gated') {
			out.push(key+'='+encodeURIComponent(req.query[key]));
		}
		return out;
	}, []).join('&');
	const redirPath = '/v2/' + req.params[0].replace(/[^\w\/\.\+\:]/g, '') + (qs.length ? '?'+qs : '');

	res.status(301);
	res.set('Location', redirPath);
	res.set('Deprecation-Notice', 'API version 1 has been decommissioned - see the body of this response for more information.');
	res.send('API version 1 has been decommissioned. Your request is being redirected to v2.  The `libVersion` and `gated` query string parameters are no longer supported and if present have been removed from your request.\n\nA deprecation period for v1 existed between August and December 2015, during which time v1 requests were honoured but a deprecation warning was added to output.');
});

router.get(/^\/v2\/polyfill(\.\w+)(\.\w+)?/, (req, res) => {
	metrics.counter('hits').inc();
	const respTimeTimer = metrics.timer('respTime').start();
	const firstParameter = req.params[0].toLowerCase();
	const minified = firstParameter === '.min';
	const fileExtension = req.params[1] ? req.params[1].toLowerCase() : firstParameter;
	const uaString = (typeof req.query.ua === 'string' && req.query.ua) || req.header('user-agent');
	const flags = (typeof req.query.flags === 'string') ? req.query.flags.split(',') : [];
	const warnings = [];

	// Currently don't support CSS
	if (fileExtension !== '.js') {
		res.status(404);
		res.set('Content-Type', 'text/plain;charset=utf-8');
		res.send('/* Type not supported.  Only .js is supported at the moment */');
		return;
	}

	const polyfills = PolyfillSet.fromQueryParam(req.query.features, flags);

	// If inbound request did not specify UA on the query string, the cache key must use the HTTP header
	if (!req.query.ua) {
		res.set('Vary', 'User-Agent');
	}

	const params = {
		features: polyfills.get(),
		excludes: (req.query.excludes && req.query.excludes.split(',')) || [],
		minify: minified,
		rum: req.query.rum,
		baseurl: req.protocol+'://'+req.get('host')
	};
	if (req.query.unknown) {
		params.unknown = req.query.unknown;
	}
	if (uaString) {
		params.uaString = uaString;
		metrics.counter('useragentcount.'+polyfillio.normalizeUserAgent(uaString).replace(/^(.*?)\/(\d+)(\..*)?$/, '$1.$2')).inc();
	}

	polyfillio.getPolyfillString(params).then(op => {
		if (warnings.length) {
			op = '/* WARNINGS:\n\n- ' + warnings.join('\n- ') + '\n\n*/\n\n' + op;
		}
		if (req.query.callback && req.query.callback.match(/^[\w\.]+$/)) {
			op += "\ntypeof "+req.query.callback+"==='function' && "+req.query.callback+"();";
		}
		res.set('Content-Type', contentTypes[fileExtension]+';charset=utf-8');
		res.set('Access-Control-Allow-Origin', '*');
		res.send(op);
		respTimeTimer.end();
	});

});

router.get("/v2/normalizeUa", (req, res) => {

	if (req.query.ua) {
		res.status(200);
		res.set('Cache-Control', 'public, max-age='+one_year+', stale-if-error='+(one_year+one_week));
		res.set('Normalized-User-Agent', encodeURIComponent(polyfillio.normalizeUserAgent(req.query.ua)));
		res.send();
	} else {
		res.status(400);
		res.send('ua query param required');
	}
});

module.exports = router;
<commit_msg>Fix https://app.getsentry.com/nextftcom/polyfill-service-prod/issues/116498360/<commit_after>/* Main endpoints for the Polyfill service public API */

'use strict';

const polyfillio = require('../../lib');
const PolyfillSet = require('../PolyfillSet');
const metrics = require('../metrics');
const express = require('express');

const router = express.Router();  // eslint-disable-line new-cap
const contentTypes = {".js": 'application/javascript', ".css": 'text/css'};
const one_day = 60 * 60 * 24;
const one_week = one_day * 7;
const one_year = one_day * 365;

router.get(/^\/v1\/(.*)/, (req, res) => {

	const qs = Object.keys(req.query).reduce((out, key) => {
		if (key !== 'libVersion' && key !== 'gated') {
			out.push(encodeURIComponent(key)+'='+encodeURIComponent(req.query[key]));
		}
		return out;
	}, []).join('&');
	const redirPath = '/v2/' + req.params[0].replace(/[^\w\/\.\+\:]/g, '') + (qs.length ? '?'+qs : '');

	res.status(301);
	res.set('Location', redirPath);
	res.set('Deprecation-Notice', 'API version 1 has been decommissioned - see the body of this response for more information.');
	res.send('API version 1 has been decommissioned. Your request is being redirected to v2.  The `libVersion` and `gated` query string parameters are no longer supported and if present have been removed from your request.\n\nA deprecation period for v1 existed between August and December 2015, during which time v1 requests were honoured but a deprecation warning was added to output.');
});

router.get(/^\/v2\/polyfill(\.\w+)(\.\w+)?/, (req, res) => {
	metrics.counter('hits').inc();
	const respTimeTimer = metrics.timer('respTime').start();
	const firstParameter = req.params[0].toLowerCase();
	const minified = firstParameter === '.min';
	const fileExtension = req.params[1] ? req.params[1].toLowerCase() : firstParameter;
	const uaString = (typeof req.query.ua === 'string' && req.query.ua) || req.header('user-agent');
	const flags = (typeof req.query.flags === 'string') ? req.query.flags.split(',') : [];
	const warnings = [];

	// Currently don't support CSS
	if (fileExtension !== '.js') {
		res.status(404);
		res.set('Content-Type', 'text/plain;charset=utf-8');
		res.send('/* Type not supported.  Only .js is supported at the moment */');
		return;
	}

	const polyfills = PolyfillSet.fromQueryParam(req.query.features, flags);

	// If inbound request did not specify UA on the query string, the cache key must use the HTTP header
	if (!req.query.ua) {
		res.set('Vary', 'User-Agent');
	}

	const params = {
		features: polyfills.get(),
		excludes: (req.query.excludes && req.query.excludes.split(',')) || [],
		minify: minified,
		rum: req.query.rum,
		baseurl: req.protocol+'://'+req.get('host')
	};
	if (req.query.unknown) {
		params.unknown = req.query.unknown;
	}
	if (uaString) {
		params.uaString = uaString;
		metrics.counter('useragentcount.'+polyfillio.normalizeUserAgent(uaString).replace(/^(.*?)\/(\d+)(\..*)?$/, '$1.$2')).inc();
	}

	polyfillio.getPolyfillString(params).then(op => {
		if (warnings.length) {
			op = '/* WARNINGS:\n\n- ' + warnings.join('\n- ') + '\n\n*/\n\n' + op;
		}
		if (req.query.callback && req.query.callback.match(/^[\w\.]+$/)) {
			op += "\ntypeof "+req.query.callback+"==='function' && "+req.query.callback+"();";
		}
		res.set('Content-Type', contentTypes[fileExtension]+';charset=utf-8');
		res.set('Access-Control-Allow-Origin', '*');
		res.send(op);
		respTimeTimer.end();
	});

});

router.get("/v2/normalizeUa", (req, res) => {

	if (req.query.ua) {
		res.status(200);
		res.set('Cache-Control', 'public, max-age='+one_year+', stale-if-error='+(one_year+one_week));
		res.set('Normalized-User-Agent', encodeURIComponent(polyfillio.normalizeUserAgent(req.query.ua)));
		res.send();
	} else {
		res.status(400);
		res.send('ua query param required');
	}
});

module.exports = router;
<|endoftext|>


<commit_before>[
{"id":"layer_new","title":"Neue Ebene"},
{"id":"layer_delete","title":"Ebene löschen"},
{"id":"layer_rename","title":"Benennen Sie die Ebene"},
{"id":"layer_up","title":"Move Up Layer"},
{"id":"layer_down","title":"Move Layer Down"},
{"id":"tool_clear","title":"Neues Bild [N]"},
{"id":"tool_open","title":"Open Image [O]"},
{"id":"tool_save","title":"Bild speichern [S]"},
{"id":"tool_docprops","title":"Dokument-Eigenschaften [I]"},
{"id":"tool_source","title":"Quelle bearbeiten [U]"},
{"id":"tool_undo","title":"Rückgängig [Z]"},
{"id":"tool_redo","title":"Wieder [Y]"},
{"id":"tool_clone","title":"Klon-Element [C]"},
{"id":"tool_delete","title":"Element löschen [Delete/Backspace]"},
{"id":"tool_move_top","title":"Move to Top [Shift Up]"},
{"id":"tool_move_bottom","title":"Move to Bottom [Shift Down]"},
{"id":"group_opacity","title":"Ändern Sie ausgewählte Element Trübung"},
{"id":"angle","title":"Ändern Drehwinkel"},
{"id":"tool_clone_multi","title":"Klon-Elemente [C]"},
{"id":"tool_delete_multi","title":"Ausgewählte Elemente löschen [Delete/Backspace]"},
{"id":"tool_alignleft","title":"Linksbündig"},
{"id":"tool_aligncenter","title":"Zentriert"},
{"id":"tool_alignright","title":"Rechtsbündig"},
{"id":"tool_aligntop","title":"Oben ausrichten"},
{"id":"tool_alignmiddle","title":"Richten Sie Nahen"},
{"id":"tool_alignbottom","title":"Unten ausrichten"},
{"id":"align_relative_to","title":"Richten Sie im Vergleich zu ..."},
{"id":"tool_group","title":"Group Elements [G]"},
{"id":"tool_ungroup","title":"Gruppierung aufheben Elements [G]"},
{"id":"rect_x","title":"Ändern Rechteck X-Koordinate"},
{"id":"rect_y","title":"Ändern Rechteck Y-Koordinate"},
{"id":"rect_width","title":"Ändern Rechteck Breite"},
{"id":"rect_height","title":"Ändern Rechteck Höhe"},
{"id":"rect_rx","title":"Ändern Rectangle Eckenradius"},
{"id":"image_x","title":"Bild ändern X-Koordinate"},
{"id":"image_y","title":"Bild ändern Y-Koordinate"},
{"id":"image_width","title":"Ändern Bildbreite"},
{"id":"image_height","title":"Ändern Bildhöhe"},
{"id":"image_url","title":"URL ändern"},
{"id":"circle_cx","title":"Ändern Kreises zu koordinieren cx"},
{"id":"circle_cy","title":"Ändern Kreises zu koordinieren cy"},
{"id":"circle_r","title":"Ändern Kreisradius"},
{"id":"ellipse_cx","title":"Ändern Ellipse cx koordinieren"},
{"id":"ellipse_cy","title":"Ändern Ellipse zu koordinieren cy"},
{"id":"ellipse_rx","title":"Ändern Ellipse x Radius"},
{"id":"ellipse_ry","title":"Ändern Ellipse y Radius"},
{"id":"line_x1","title":"Ändern Sie Zeile des Anfangs X-Koordinate"},
{"id":"line_y1","title":"Ändern Sie Zeile ist ab Koordinate y"},
{"id":"line_x2","title":"Ändern Sie Zeile die Ende X-Koordinate"},
{"id":"line_y2","title":"Ändern Sie Zeile endet die Koordinate y"},
{"id":"text_x","title":"Ändern Sie Text X-Koordinate"},
{"id":"text_y","title":"Text ändern Y-Koordinate"},
{"id":"tool_bold","title":"Fetter Text [B]"},
{"id":"tool_italic","title":"Italic Text [I]"},
{"id":"font_family","title":"Ändern Schriftfamilie"},
{"id":"font_size","title":"Schriftgröße ändern"},
{"id":"text","title":"Ändern Sie Textinhalte"},
{"id":"tool_select","title":"Wählen Sie Tool [1]"},
{"id":"tool_path","title":"Pencil Tool [2]"},
{"id":"tool_line","title":"Line Tool [3]"},
{"id":"tools_rect_show","title":"Square / Rect Tool [4/Shift 4]"},
{"id":"tools_ellipse_show","title":"Ellipse / Circle Tool [5/Shift 5]"},
{"id":"tool_text","title":"Text-Werkzeug [6]"},
{"id":"tool_poly","title":"Poly-Tool [7]"},
{"id":"tool_image","title":"Image Tool [8]"},
{"id":"tool_zoom","title":"Zoom-Tool [Ctrl Up/Down]"},
{"id":"zoom","title":"Ändern Zoom-Stufe"},
{"id":"fill_color","title":"Ändern Füllfarbe"},
{"id":"stroke_color","title":"Ändern Konturfarbe"},
{"id":"stroke_width","title":"Ändern Strichbreite"},
{"id":"stroke_style","title":"Ändern Schlaganfall Bindestrich Stil"},
{"id":"palette","title":"Click to change Füllfarbe, Shift-Klick zu streicheln Farbwechsel"},
{"id":"tool_square","title":"Quadrat"},
{"id":"tool_rect","title":"Rectangle"},
{"id":"tool_fhrect","title":"Free-Hand Rectangle"},
{"id":"tool_circle","title":"Circle"},
{"id":"tool_ellipse","title":"Ellipse"},
{"id":"tool_fhellipse","title":"Free-Hand Ellipse"},
{"id":"bkgnd_color","title":"Hintergrundfarbe ändern / Trübung"},
{"id":"rwidthLabel","textContent":"Breite:"},
{"id":"rheightLabel","textContent":"Höhe:"},
{"id":"cornerRadiusLabel","textContent":"Eckenradius:"},
{"id":"iwidthLabel","textContent":"Breite:"},
{"id":"iheightLabel","textContent":"Höhe:"},
{"id":"svginfo_width","textContent":"Breite:"},
{"id":"svginfo_height","textContent":"Höhe:"},
{"id":"angleLabel","textContent":"Winkel:"},
{"id":"relativeToLabel","textContent":"im Vergleich zu:"},
{"id":"zoomLabel","textContent":"Zoom:"},
{"id":"svninfo_change_background","textContent":"Canvas Background"},
{"id":"layersLable","textContent":"Layers:"},
{"id":"selectedPredefined","textContent":"Auswahl einer vordefinierten:"},
{"id":"fitToContent","textContent":"Fit to Content"},
{"id":"tool_source_save","textContent":"Sichern"},
{"id":"tool_docprops_save","textContent":"Sichern"},
{"id":"tool_docprops_cancel","textContent":"Abbrechen"},
{"id":"tool_source_cancel","textContent":"Abbrechen"},
{"id":"fit_to_all","textContent":"Fit für alle Inhalte"},
{"id":"fit_to_layer_content","textContent":"Fit auf Layer Content"},
{"id":"fit_to_sel","textContent":"Fit zur Auswahl"},
{"id":"fit_to_canvas","textContent":"Fit auf die Leinwand"},
{"id":"selected_objects","textContent":"gewählten Objekte"},
{"id":"largest_object","textContent":"größte Objekt"},
{"id":"smallest_object","textContent":"kleinstes Objekt"},
{"id":"page","textContent":"Seite"},
{"id":"fill_tool_bottom","textContent":"füllen:"},
{"id":"stroke_tool_bottom","textContent":"Hieb:"},
{"id":"svninfo_dim","textContent":"Canvas Gewicht"}
]
<commit_msg>German translation by Andreas Neumann and rb.proj<commit_after>[
{"id":"layer_new","title":"Neue Ebene"},
{"id":"layer_delete","title":"Ebene löschen"},
{"id":"layer_rename","title":"Ebene umbenennen"},
{"id":"layer_up","title":"Ebene nach oben verschieben"},
{"id":"layer_down","title":"Ebene nach unten verschieben"},
{"id":"tool_clear","title":"Neues Bild [N]"},
{"id":"tool_open","title":"Bild öffnen [O]"},
{"id":"tool_save","title":"Bild speichern [S]"},
{"id":"tool_docprops","title":"Dokument-Eigenschaften [I]"},
{"id":"tool_source","title":"Quellecode bearbeiten [U]"},
{"id":"tool_undo","title":"Rückgängig [Z]"},
{"id":"tool_redo","title":"Wiederherstellen [Y]"},
{"id":"tool_clone","title":"Element klonen [C]"},
{"id":"tool_delete","title":"Element löschen [Delete/Backspace]"},
{"id":"tool_move_top","title":"Ganz nach oben schieben [Shift Up]"},
{"id":"tool_move_bottom","title":"Ganz nach unten schieben [Shift Down]"},
{"id":"group_opacity","title":"Opazität des ausgewählten Elements ändern"},
{"id":"angle","title":"Drehwinkel ändern"},
{"id":"tool_clone_multi","title":"Ausgewählte Elemente klonen [C]"},
{"id":"tool_delete_multi","title":"Ausgewählte Elemente löschen [Delete/Backspace]"},
{"id":"tool_alignleft","title":"Linksbündig ausrichten"},
{"id":"tool_aligncenter","title":"Zentriert ausrichten"},
{"id":"tool_alignright","title":"Rechtsbündig ausrichten"},
{"id":"tool_aligntop","title":"Oben ausrichten"},
{"id":"tool_alignmiddle","title":"In der Mitte ausrichten"},
{"id":"tool_alignbottom","title":"Unten ausrichten"},
{"id":"align_relative_to","title":"Relativ zu anderem Element ausrichten ..."},
{"id":"tool_group","title":"Gruppieren [G]"},
{"id":"tool_ungroup","title":"Gruppierung aufheben [G]"},
{"id":"rect_x","title":"X-Koordinate des Rechtecks ändern"},
{"id":"rect_y","title":"Y-Koordinate des Rechtecks ändern"},
{"id":"rect_width","title":"Breite des Rechtecks ändern"},
{"id":"rect_height","title":"Höhe des Rechtecks ändern"},
{"id":"rect_rx","title":"Eckenradius des Rechtecks ändern"},
{"id":"image_x","title":"X-Koordinate des Bildes ändern"},
{"id":"image_y","title":"Y-Koordinate des Bildes ändern"},
{"id":"image_width","title":"Bildbreite ändern"},
{"id":"image_height","title":"Bildhöhe ändern"},
{"id":"image_url","title":"URL ändern"},
{"id":"circle_cx","title":"Kreiszentrum (cx) ändern"},
{"id":"circle_cy","title":"Kreiszentrum (cy) ändern"},
{"id":"circle_r","title":"Kreisradius (r) ändern"},
{"id":"ellipse_cx","title":"Ellipsenzentrum (cx) ändern"},
{"id":"ellipse_cy","title":"Ellipsenzentrum (cy) ändern"},
{"id":"ellipse_rx","title":"Ellipsenradius (x) ändern"},
{"id":"ellipse_ry","title":"Ellipsenradius (y) ändern"},
{"id":"line_x1","title":"X-Koordinate des Linienanfangs ändern"},
{"id":"line_y1","title":"Y-Koordinate des Linienanfangs  ändern"},
{"id":"line_x2","title":"X-Koordinate des Linienendes ändern"},
{"id":"line_y2","title":"Y-Koordinate des Linienendes ändern"},
{"id":"text_x","title":"X-Koordinate des Textelements ändern"},
{"id":"text_y","title":"Y-Koordinate des Textelements ändern"},
{"id":"tool_bold","title":"Fetter Text [B]"},
{"id":"tool_italic","title":"Kursiver Text [I]"},
{"id":"font_family","title":"Schriftart"},
{"id":"font_size","title":"Schriftgröße"},
{"id":"text","title":"Textinhalt"},
{"id":"tool_select","title":"Werkzeug wählen [1]"},
{"id":"tool_path","title":"Freihandlinie [2]"},
{"id":"tool_line","title":"Linien-Werkzeug [3]"},
{"id":"tools_rect_show","title":"Rechteck-Werkzeug [4/Shift 4]"},
{"id":"tools_ellipse_show","title":"Ellipsen/Kreis-Werkzeug [5/Shift 5]"},
{"id":"tool_text","title":"Text-Werkzeug [6]"},
{"id":"tool_poly","title":"Polygon-Werkzeug [7]"},
{"id":"tool_image","title":"Bild-Werkzeug [8]"},
{"id":"tool_zoom","title":"Zoom-Werkzeug [Ctrl Up/Down]"},
{"id":"zoom","title":"Ändern Zoom-Stufe"},
{"id":"fill_color","title":"Füllfarbe ändern"},
{"id":"stroke_color","title":"Strichfarbe ändern"},
{"id":"stroke_width","title":"Strichbreite ändern"},
{"id":"stroke_style","title":"Strichlierungsstil ändern"},
{"id":"palette","title":"Klick zum Ändern der Füllfarbe, Shift-Klick zum Ändern der Strichfarbe"},
{"id":"tool_square","title":"Quadrat"},
{"id":"tool_rect","title":"Rechteck"},
{"id":"tool_fhrect","title":"Freihand Rechteck"},
{"id":"tool_circle","title":"Kreis"},
{"id":"tool_ellipse","title":"Ellipse"},
{"id":"tool_fhellipse","title":"Freihand Ellipse"},
{"id":"bkgnd_color","title":"Hintergrundfarbe ändern / Opazität"},
{"id":"rwidthLabel","textContent":"Breite:"},
{"id":"rheightLabel","textContent":"Höhe:"},
{"id":"cornerRadiusLabel","textContent":"Eckenradius:"},
{"id":"iwidthLabel","textContent":"Breite:"},
{"id":"iheightLabel","textContent":"Höhe:"},
{"id":"svginfo_width","textContent":"Breite:"},
{"id":"svginfo_height","textContent":"Höhe:"},
{"id":"angleLabel","textContent":"Winkel:"},
{"id":"relativeToLabel","textContent":"im Vergleich zu:"},
{"id":"zoomLabel","textContent":"Zoom:"},
{"id":"svninfo_change_background","textContent":"Ändere den Hintergrund der Zeichenfläche"},
{"id":"layersLable","textContent":"Ebenen:"},
{"id":"selectedPredefined","textContent":"Auswahl einer vordefinierten:"},
{"id":"fitToContent","textContent":"An den Inhalt anpassen"},
{"id":"tool_source_save","textContent":"Speichern"},
{"id":"tool_docprops_save","textContent":"Speichern"},
{"id":"tool_docprops_cancel","textContent":"Abbrechen"},
{"id":"tool_source_cancel","textContent":"Abbrechen"},
{"id":"fit_to_all","textContent":"An gesamten Inhalt anpassen"},
{"id":"fit_to_layer_content","textContent":"An Inhalt der Ebene anpassen"},
{"id":"fit_to_sel","textContent":"An die Auswahl anpassen"},
{"id":"fit_to_canvas","textContent":"An die Zeichenfläche anpassen"},
{"id":"selected_objects","textContent":"gewählte Objekte"},
{"id":"largest_object","textContent":"größtes Objekt"},
{"id":"smallest_object","textContent":"kleinstes Objekt"},
{"id":"page","textContent":"Seite"},
{"id":"fill_tool_bottom","textContent":"Füllung:"},
{"id":"stroke_tool_bottom","textContent":"Strich:"},
{"id":"svninfo_dim","textContent":"Dimensionen der Zeichenfläche"}
]
<|endoftext|>


<commit_before>const admzip = require( 'adm-zip' );
const path = require( 'path' );
const fs = require( 'fs' );

/**
 * This package contains functions that should be run in main process context instead of render process context.
 * Reason: Performance.
 * When running heavy functions with massive data transfer (through ipc?) to render process, performence decreases drastically.
 * Keep amount of functions low to prevent incremental changes => low redistribution frequency of desktop client
 */
var hakuneko = {};

/**
 * Read image data from CBZ archive.
 * Declaration in main process because of performance, usage in render process.
 */
hakuneko.loadChapterPagesCBZ = ( archive, callback ) => {
    let zip = new admzip( archive );
    let pages = zip.getEntries().map( ( entry ) => {
        // TODO: extract files to temp folder and provide direct file links instead of base64 data
        // return 'file://' + entry.entryName;
        console.log( pageFileMime( entry.entryName ) );
        return 'data:' + pageFileMime( entry.entryName ) + ';base64,' + entry.getData().toString('base64');
    });
    callback( pages );
}

/**
 * Read image data from directory.
 * Declaration in main process because of performance, usage in render process.
 */
hakuneko.loadChapterPagesFolder = ( directory, callback ) => {
    fs.readdir( directory, ( error, files ) => {
        let pages = files.map( ( file ) => {
            file = path.join( directory, file );
            // websecurity is disabled => direct access to file links
            return 'file://' + file;
            //return 'data:image/jpeg;base64,' + fs.readFileSync( file ).toString( 'base64' );
        });
        callback( pages );
    });
}

/**
 * Helper function to get the mime time depending on the file extension of the gicen file name.
 */
function pageFileMime( file ) {
    let extension = path.extname( file );
    if( extension === '.jpg' ) {
        return 'image/jpeg';
    }
    if( extension === '.png' ) {
        return 'image/png';
    }
    if( extension === '.gif' ) {
        return 'image/gif';
    }
    if( extension === '.bmp' ) {
        return 'image/bmp';
    }
    if( extension === '.img' ) {
        return 'image/';
    }
    return 'application/octet-stream';
}

module.exports = hakuneko;<commit_msg>removed debug output<commit_after>const admzip = require( 'adm-zip' );
const path = require( 'path' );
const fs = require( 'fs' );

/**
 * This package contains functions that should be run in main process context instead of render process context.
 * Reason: Performance.
 * When running heavy functions with massive data transfer (through ipc?) to render process, performence decreases drastically.
 * Keep amount of functions low to prevent incremental changes => low redistribution frequency of desktop client
 */
var hakuneko = {};

/**
 * Read image data from CBZ archive.
 * Declaration in main process because of performance, usage in render process.
 */
hakuneko.loadChapterPagesCBZ = ( archive, callback ) => {
    let zip = new admzip( archive );
    let pages = zip.getEntries().map( ( entry ) => {
        // TODO: extract files to temp folder and provide direct file links instead of base64 data
        // return 'file://' + entry.entryName;
        return 'data:' + pageFileMime( entry.entryName ) + ';base64,' + entry.getData().toString('base64');
    });
    callback( pages );
}

/**
 * Read image data from directory.
 * Declaration in main process because of performance, usage in render process.
 */
hakuneko.loadChapterPagesFolder = ( directory, callback ) => {
    fs.readdir( directory, ( error, files ) => {
        let pages = files.map( ( file ) => {
            file = path.join( directory, file );
            // websecurity is disabled => direct access to file links
            return 'file://' + file;
            //return 'data:image/jpeg;base64,' + fs.readFileSync( file ).toString( 'base64' );
        });
        callback( pages );
    });
}

/**
 * Helper function to get the mime time depending on the file extension of the gicen file name.
 */
function pageFileMime( file ) {
    let extension = path.extname( file );
    if( extension === '.jpg' ) {
        return 'image/jpeg';
    }
    if( extension === '.png' ) {
        return 'image/png';
    }
    if( extension === '.gif' ) {
        return 'image/gif';
    }
    if( extension === '.bmp' ) {
        return 'image/bmp';
    }
    if( extension === '.img' ) {
        return 'image/';
    }
    return 'application/octet-stream';
}

module.exports = hakuneko;<|endoftext|>


<commit_before>import React from 'react';

import { Box, Button, Form, FormField, Text, TextInput } from 'grommet';

// This example shows a way to perform validation across multiple fields.
export const AggregateValidation = () => {
  const [value, setValue] = React.useState({ name: 'a', email: 'b' });
  const message =
    value.name && value.email && value.name[0] !== value.email[0]
      ? 'Mismatched first character'
      : undefined;
  return (
    // Uncomment <Grommet> lines when using outside of storybook
    // <Grommet theme={...}>
    <Box fill align="center" justify="center">
      <Box width="medium">
        <Form
          value={value}
          onChange={(nextValue) => setValue(nextValue)}
          onSubmit={({ value: nextValue }) => console.log(nextValue)}
        >
          <FormField label="Name" name="name" required>
            <TextInput name="name" type="name" />
          </FormField>

          <FormField label="Email" name="email" required>
            <TextInput name="email" type="email" />
          </FormField>

          {message && (
            <Box pad={{ horizontal: 'small' }}>
              <Text color="status-error">{message}</Text>
            </Box>
          )}

          <Box direction="row" justify="between" margin={{ top: 'medium' }}>
            <Button
              onClick={() => setValue({ name: '', email: '' })}
              type="reset"
              label="Reset"
            />
            <Button type="submit" label="Update" primary />
          </Box>
        </Form>
      </Box>
    </Box>
    // </Grommet>
  );
};

AggregateValidation.storyName = 'Aggregate validation';

AggregateValidation.args = {
  full: true,
};

export default {
  title: 'Input/Form/Aggregate validation',
};
<commit_msg>Form/AggregateValidation label violation fixed (#6469)<commit_after>import React from 'react';

import { Box, Button, Form, FormField, Text, TextInput } from 'grommet';

// This example shows a way to perform validation across multiple fields.
export const AggregateValidation = () => {
  const [value, setValue] = React.useState({ name: 'a', email: 'b' });
  const message =
    value.name && value.email && value.name[0] !== value.email[0]
      ? 'Mismatched first character'
      : undefined;
  return (
    // Uncomment <Grommet> lines when using outside of storybook
    // <Grommet theme={...}>
    <Box fill align="center" justify="center">
      <Box width="medium">
        <Form
          value={value}
          onChange={(nextValue) => setValue(nextValue)}
          onSubmit={({ value: nextValue }) => console.log(nextValue)}
        >
          <FormField label="Name" name="name" required>
            <TextInput aria-label="name" name="name" type="name" />
          </FormField>

          <FormField label="Email" name="email" required>
            <TextInput aria-label="email" name="email" type="email" />
          </FormField>

          {message && (
            <Box pad={{ horizontal: 'small' }}>
              <Text color="status-error">{message}</Text>
            </Box>
          )}

          <Box direction="row" justify="between" margin={{ top: 'medium' }}>
            <Button
              onClick={() => setValue({ name: '', email: '' })}
              type="reset"
              label="Reset"
            />
            <Button type="submit" label="Update" primary />
          </Box>
        </Form>
      </Box>
    </Box>
    // </Grommet>
  );
};

AggregateValidation.storyName = 'Aggregate validation';

AggregateValidation.args = {
  full: true,
};

export default {
  title: 'Input/Form/Aggregate validation',
};
<|endoftext|>


<commit_before>"use strict";
var MiniMap;

/**
 * The minimap renderer. Uses passive rendering - renderes only changes from
 * the previous renderered state.
 */
MiniMap = function () {
    var tiles, container, buildingsLayer, unitsLayer, width, height, mapWidth,
            mapHeight, buildingsLayerCtx, unitsLayerCtx, xRatio, yRatio,
            tileWidth, tileHeight, changedTerrain, changedBuildings,
            changedUnits, drawTileLine, fill, buildingsLayerIndex, createIndex,
            xRatioC, yRatioC, initRenderer, renderUnitsLayer,
            renderBuildingsLayer, renderTerrainLayer, terrainLayer,
            terrainLayerCtx, map, instance, viewBordersLayer, viewBordersCtx,
            viewBordersWidth, viewBordersHeight, lastX, lastY,
            mainViewBufferWidth, mainViewBufferHeight;

    tiles = [];
    terrainLayer = document.createElement('canvas');
    terrainLayerCtx = terrainLayer.getContext('2d');
    buildingsLayer = document.createElement('canvas');
    buildingsLayerCtx = buildingsLayer.getContext('2d');
    unitsLayer = document.createElement('canvas');
    unitsLayerCtx = unitsLayer.getContext('2d');
    viewBordersLayer = document.createElement('canvas');
    viewBordersCtx = viewBordersLayer.getContext('2d');
    viewBordersCtx.lineCap = 'square';
    viewBordersCtx.lineJoin = 'bevel';
    changedTerrain = false;
    changedBuildings = false;
    changedUnits = false;
    instance = this;

    /**
     * Sets the raw map data and initializes the renderer.
     *
     * @param {Map} newMap The map data.
     */
    this.setMap = function (newMap) {
        if (!(newMap instanceof Map)) {
            throw new TypeError("An instance of the Map class is required");
        }
        map = newMap;
        tiles = newMap.getTiles();
        mapHeight = tiles.length;
        mapWidth = tiles[0].length;
        if (container && width) {
            initRenderer();
        }
    };

    /**
     * Sets the size of the main view in tiles (for displaying informational
     * rectangle informing the user about the current position of the camera
     * over the map)
     *
     * @param {Number} width Width of the main view in tiles.
     * @param {Number} height Height of the main view in tiles.
     */
    this.setMainViewSize = function (width, height) {
        viewBordersWidth = width;
        viewBordersHeight = height;
    };

    /**
     * Sets the container in which the minimap should be rendered. The renderer
     * will place additional canvases into the container that will be used to
     * render the separate layers of the minimap. Then the renderer is
     * intialized.
     *
     * @param {HTMLElement} newContainer The container which shall be used to
     *        render the minimap.
     */
    this.setContainer = function (newContainer) {
        if (!(newContainer instanceof HTMLElement)) {
            throw new Error("container must be an HTML element");
        }
        container = newContainer;
        width = container.offsetWidth;
        height = container.offsetHeight;
        terrainLayer.width = buildingsLayer.width = unitsLayer.width =
                viewBordersLayer.width = width;
        terrainLayer.height = buildingsLayer.height = unitsLayer.height =
                viewBordersLayer.height = height;
        newContainer = document.createElement('div');
        newContainer.style.height = '0px';
        newContainer.appendChild(terrainLayer);
        container.appendChild(newContainer);
        newContainer = document.createElement('div');
        newContainer.style.height = '0px';
        newContainer.appendChild(buildingsLayer);
        container.appendChild(newContainer);
        newContainer = document.createElement('div');
        newContainer.style.height = '0px';
        newContainer.appendChild(unitsLayer);
        container.appendChild(newContainer);
        container.appendChild(viewBordersLayer);
        if (mapWidth && width) {
            initRenderer();
        }
    };

    /**
     * Sets the size of the minimal view.
     *
     * @param {Number} newWidth Width of the minimap view.
     * @param {Number} newHeight Height of the minimap view.
     */
    this.setSize = function (newWidth, newHeight) {
        width = newWidth;
        height = newHeight;
        terrainLayer.width = buildingsLayer.width = unitsLayer.width =
                viewBordersLayer.width = width;
        terrainLayer.height = buildingsLayer.height = unitsLayer.height =
                viewBordersLayer.height = height;
        if (map && container) {
            initRenderer();
        }
    };

    /**
     * Event handler of change of building (creation or destruction).
     *
     * @param {Building} building The building which status has changed.
     */
    this.onBuildingChange = function (building) {
        changedBuildings.push(building);
    };

    /**
     * Event handler of change of unit (creation, destruction or movement).
     *
     * @param {Unit} unit The unit which status has changed.
     */
    this.onUnitChange = function (unit) {
        changedUnits.push(unit);
    };

    /**
     * Renders the registered changes of buildings and units. If the terrain
     * has not been rendered so far, it is rendered too.
     *
     * @param {Number} x X position of the camera over the map in pixels.
     * @param {Number} y Y position of the camera over the map in pixels.
     */
    this.render = function (x, y) {
        changedTerrain && renderTerrainLayer();
        changedBuildings.length && renderBuildingsLayer();
        changedUnits.length && renderUnitsLayer();
        if ((x !== lastX) || (y !== lastY)) {
            lastX = x;
            lastY = y;
            x = Math.round(x / mainViewBufferWidth * width);
            y = Math.round(y / mainViewBufferHeight * height);
            viewBordersCtx.strokeStyle = 'white';
            viewBordersCtx.lineWidth =
                    Math.round((tileWidth + tileHeight) / 2);
            viewBordersCtx.clearRect(0, 0, viewBordersLayer.width,
                    viewBordersLayer.height);
            viewBordersCtx.strokeRect(x, y, viewBordersWidth * xRatio,
                    viewBordersHeight * yRatio * 2);
        }
    };

    this.setMainViewBufferSize = function (dimensions) {
        mainViewBufferWidth = dimensions.width;
        mainViewBufferHeight = dimensions.height;
    };

    /**
     * Renders changes in the unit's layer.
     */
    renderUnitsLayer = function () {
        var i, unit;
        for (i = changedUnits.length; i--;) {
            unit = changedUnits[i];
            unitsLayerCtx.fillStyle = unit.color;
            switch (unit.action) {
                case 2:
                case 3:
                    unitsLayerCtx.clearRect(Math.floor(unit.lastX * xRatio),
                            Math.floor(unit.lastY * yRatio),
                            Math.ceil(xRatioC), Math.ceil(yRatioC));
                case 0:
                    unitsLayerCtx.fillRect(Math.floor(unit.x * xRatio),
                            Math.floor(unit.y * yRatio),
                            Math.ceil(xRatioC), Math.ceil(yRatioC));
                    break;
                case 1:
                    unitsLayerCtx.clearRect(Math.floor(unit.lastX * xRatio),
                            Math.floor(unit.lastY * yRatio),
                            Math.ceil(xRatioC), Math.ceil(yRatioC));
                    break;
            }
        }
        changedUnits = [];
    };

    /**
     * Renders the changes in the buildings layer.
     */
    renderBuildingsLayer = function () {
        var i, building, x1, y1, x2, y2, x3, y3, x4, y4, buildingType,
                resource, resourceType;
        for (i = changedBuildings.length; i--;) {
            building = changedBuildings[i];
            buildingsLayerCtx.globalCompositeOperation = building.type ===
                    false ? 'destination-out' : 'source-over';
            x1 = building.x;
            y1 = building.y;
            x2 = x1 + building.width;
            y2 = y1 + Math.floor(building.width / 2);
            x3 = x1 - Math.floor(building.height / 2);
            y3 = y1 + building.height;
            x4 = x3 + building.width;
            y4 = y3 + Math.floor(building.width / 2);
            buildingType = BuildingsDefinition.getType(building.type);
            if (buildingType.resource === null) {
                buildingsLayerCtx.fillStyle = building.color;
            } else {
                resource = buildingType.resource;
                resourceType = ResourcesDefinition.getType(resource);
                buildingsLayerCtx.fillStyle = resourceType.minimap;
            }
            drawTileLine(x1, y1, x2, y2, buildingsLayerCtx);
            drawTileLine(x1, y1, x3, y3, buildingsLayerCtx);
            drawTileLine(x2, y2, x4, y4, buildingsLayerCtx);
            drawTileLine(x3, y3, x4, y4, buildingsLayerCtx);
            fill(Math.round((x1 + x4) / 2), Math.round((y1 + y4) / 2),
                    buildingsLayerCtx);
        }
        changedBuildings = [];
    };

    /**
     * Renders the terrain layer.
     */
    renderTerrainLayer = function () {
        var i, j, row;
        for (i = tiles.length; i--;) {
            row = tiles[i];
            for (j = row.length; j--;) {
                terrainLayerCtx.fillStyle = row[j].minimap;
                terrainLayerCtx.fillRect(xRatio * j, yRatio * i,
                        tileWidth, tileHeight);
            }
        }
        changedTerrain = false;
    };

    /**
     * Creates index used by the renderer for storing positions of units or
     * buildings.
     *
     * @return {Array} The two-dimensional array index.
     */
    createIndex = function () {
        var index, i, j;
        index = new Array(mapWidth);
        for (i = mapWidth; i--;) {
            index[i] = new Array(mapHeight);
            for (j = mapHeight; j--;) {
                index[i][j] = false;
            }
        }
        return index;
    };

    /**
     * Fills the area of tiles on the minimap. The area is defined by the tiles
     * of the same color.
     *
     * @param {Number} x The X coordinate of the tile position where the
     *        filling should be performed.
     * @param {Number} y The Y coordinate of the tile position where the
     *        filling should be performed.
     * @param {CanvasRenderingContext2D} ctx The 2D context of the canvas for
     *        rendering.
     * @param {fillColor} fillColor The color that should be used to color the
     *        area.
     */
    fill = function (x, y, ctx, fillColor) {
        var thisColor;
        if ((x >= mapWidth) || (x < 0) || (y >= mapHeight) || (y < 0)) {
            return;
        }
        thisColor = buildingsLayerIndex[x][y];
        if (fillColor === undefined) {
            fillColor = thisColor;
        }
        if (thisColor == fillColor) {
            ctx.fillRect(x * xRatio, y * yRatio, xRatioC, yRatioC);
            buildingsLayerIndex[x][y] = !buildingsLayerIndex[x][y];
            fill(x - 1, y, ctx, fillColor);
            fill(x + 1, y, ctx, fillColor);
            fill(x, y - 1, ctx, fillColor);
            fill(x, y + 1, ctx, fillColor);
        }
    };

    /**
     * Draw a line of tiles onto the canvas.
     *
     * @param {Number} x1 The starting X coordinate.
     * @param {Number} y1 The starting Y coordinate.
     * @param {Number} x2 The ending X coordinate.
     * @param {Number} y2 The ending Y coordinate.
     * @param {CanvasRenderingContext2D} ctx The 2D context of the canvas to be
     *        used for rendering.
     */
    drawTileLine = function (x1, y1, x2, y2, ctx) {
        var len, vx, vy, rx, ry;
        vx = x2 - x1;
        vy = y2 - y1;
        len = Math.sqrt(vx * vx + vy * vy);
        vx /= len;
        vy /= len;
        ctx.fillRect(xRatio * Math.round(x1), yRatio * Math.round(y1),
                xRatioC, yRatioC);
        do {
            x1 += vx;
            y1 += vy;
            rx = Math.round(x1);
            ry = Math.round(y1);
            if (buildingsLayerIndex[rx] &&
                    (buildingsLayerIndex[rx][ry] !== undefined)) {
                buildingsLayerIndex[rx][ry] = true;
                ctx.fillRect(xRatio * rx, yRatio * ry, xRatioC, yRatioC);
            }
        } while ((Math.round(x1) != x2) && (Math.round(y1) != y2))
    };

    /**
     * Initalizes the renderer - scaling, tile sizes and private properties.
     */
    initRenderer = function () {
        var i;
        xRatio = width / mapWidth;
        yRatio = height / mapHeight;
        xRatioC = Math.ceil(xRatio);
        yRatioC = Math.ceil(yRatio);
        tileWidth = Math.ceil(xRatio);
        tileHeight = Math.ceil(yRatio);
        changedTerrain = true;
        changedBuildings = [];
        changedUnits = [];
        buildingsLayerIndex = createIndex();

        for (i = map.getBuildings().length; i--;) {
            instance.onBuildingChange(map.getBuildings()[i]);
        }
        for (i = map.getUnits().length; i--;) {
            instance.onUnitChange(map.getUnits()[i]);
        }
    };
};<commit_msg>updated code conventions in minimap<commit_after>"use strict";
var MiniMap;

/**
 * The minimap renderer. Uses passive rendering - renderes only changes from
 * the previous renderered state.
 */
MiniMap = function () {
    var tiles, container, buildingsLayer, unitsLayer, width, height, mapWidth,
            mapHeight, buildingsLayerCtx, unitsLayerCtx, xRatio, yRatio,
            tileWidth, tileHeight, changedTerrain, changedBuildings,
            changedUnits, drawTileLine, fill, buildingsLayerIndex, createIndex,
            xRatioC, yRatioC, initRenderer, renderUnitsLayer,
            renderBuildingsLayer, renderTerrainLayer, terrainLayer,
            terrainLayerCtx, map, instance, viewBordersLayer, viewBordersCtx,
            viewBordersWidth, viewBordersHeight, lastX, lastY,
            mainViewBufferWidth, mainViewBufferHeight;

    tiles = [];
    terrainLayer = document.createElement('canvas');
    terrainLayerCtx = terrainLayer.getContext('2d');
    buildingsLayer = document.createElement('canvas');
    buildingsLayerCtx = buildingsLayer.getContext('2d');
    unitsLayer = document.createElement('canvas');
    unitsLayerCtx = unitsLayer.getContext('2d');
    viewBordersLayer = document.createElement('canvas');
    viewBordersCtx = viewBordersLayer.getContext('2d');
    viewBordersCtx.lineCap = 'square';
    viewBordersCtx.lineJoin = 'bevel';
    changedTerrain = false;
    changedBuildings = false;
    changedUnits = false;
    instance = this;

    /**
     * Sets the raw map data and initializes the renderer.
     *
     * @param {Map} newMap The map data.
     */
    this.setMap = function (newMap) {
        if (!(newMap instanceof Map)) {
            throw new TypeError("An instance of the Map class is required");
        }
        map = newMap;
        tiles = newMap.getTiles();
        mapHeight = tiles.length;
        mapWidth = tiles[0].length;
        if (container && width) {
            initRenderer();
        }
    };

    /**
     * Sets the size of the main view in tiles (for displaying informational
     * rectangle informing the user about the current position of the camera
     * over the map)
     *
     * @param {Number} width Width of the main view in tiles.
     * @param {Number} height Height of the main view in tiles.
     */
    this.setMainViewSize = function (width, height) {
        viewBordersWidth = width;
        viewBordersHeight = height;
    };

    /**
     * Sets the container in which the minimap should be rendered. The renderer
     * will place additional canvases into the container that will be used to
     * render the separate layers of the minimap. Then the renderer is
     * intialized.
     *
     * @param {HTMLElement} newContainer The container which shall be used to
     *        render the minimap.
     */
    this.setContainer = function (newContainer) {
        if (!(newContainer instanceof HTMLElement)) {
            throw new Error("container must be an HTML element");
        }
        container = newContainer;
        width = container.offsetWidth;
        height = container.offsetHeight;
        terrainLayer.width = buildingsLayer.width = unitsLayer.width =
                viewBordersLayer.width = width;
        terrainLayer.height = buildingsLayer.height = unitsLayer.height =
                viewBordersLayer.height = height;
        newContainer = document.createElement('div');
        newContainer.style.height = '0px';
        newContainer.appendChild(terrainLayer);
        container.appendChild(newContainer);
        newContainer = document.createElement('div');
        newContainer.style.height = '0px';
        newContainer.appendChild(buildingsLayer);
        container.appendChild(newContainer);
        newContainer = document.createElement('div');
        newContainer.style.height = '0px';
        newContainer.appendChild(unitsLayer);
        container.appendChild(newContainer);
        container.appendChild(viewBordersLayer);
        if (mapWidth && width) {
            initRenderer();
        }
    };

    /**
     * Sets the size of the minimal view.
     *
     * @param {Number} newWidth Width of the minimap view.
     * @param {Number} newHeight Height of the minimap view.
     */
    this.setSize = function (newWidth, newHeight) {
        width = newWidth;
        height = newHeight;
        terrainLayer.width = buildingsLayer.width = unitsLayer.width =
                viewBordersLayer.width = width;
        terrainLayer.height = buildingsLayer.height = unitsLayer.height =
                viewBordersLayer.height = height;
        if (map && container) {
            initRenderer();
        }
    };

    /**
     * Event handler of change of building (creation or destruction).
     *
     * @param {Building} building The building which status has changed.
     */
    this.onBuildingChange = function (building) {
        changedBuildings.push(building);
    };

    /**
     * Event handler of change of unit (creation, destruction or movement).
     *
     * @param {Unit} unit The unit which status has changed.
     */
    this.onUnitChange = function (unit) {
        changedUnits.push(unit);
    };

    /**
     * Renders the registered changes of buildings and units. If the terrain
     * has not been rendered so far, it is rendered too.
     *
     * @param {Number} x X position of the camera over the map in pixels.
     * @param {Number} y Y position of the camera over the map in pixels.
     */
    this.render = function (x, y) {
        changedTerrain && renderTerrainLayer();
        changedBuildings.length && renderBuildingsLayer();
        changedUnits.length && renderUnitsLayer();
        if ((x !== lastX) || (y !== lastY)) {
            lastX = x;
            lastY = y;
            x = Math.round(x / mainViewBufferWidth * width);
            y = Math.round(y / mainViewBufferHeight * height);
            viewBordersCtx.strokeStyle = 'white';
            viewBordersCtx.lineWidth =
                    Math.round((tileWidth + tileHeight) / 2);
            viewBordersCtx.clearRect(0, 0, viewBordersLayer.width,
                    viewBordersLayer.height);
            viewBordersCtx.strokeRect(x, y, viewBordersWidth * xRatio,
                    viewBordersHeight * yRatio * 2);
        }
    };

    this.setMainViewBufferSize = function (dimensions) {
        mainViewBufferWidth = dimensions.width;
        mainViewBufferHeight = dimensions.height;
    };

    /**
     * Renders changes in the unit's layer.
     */
    renderUnitsLayer = function () {
        var i, unit;
        for (i = changedUnits.length; i--;) {
            unit = changedUnits[i];
            unitsLayerCtx.fillStyle = unit.color;
            switch (unit.action) {
                case 2:
                case 3:
                    unitsLayerCtx.clearRect(Math.floor(unit.lastX * xRatio),
                            Math.floor(unit.lastY * yRatio),
                            Math.ceil(xRatioC), Math.ceil(yRatioC));
                case 0:
                    unitsLayerCtx.fillRect(Math.floor(unit.x * xRatio),
                            Math.floor(unit.y * yRatio),
                            Math.ceil(xRatioC), Math.ceil(yRatioC));
                    break;
                case 1:
                    unitsLayerCtx.clearRect(Math.floor(unit.lastX * xRatio),
                            Math.floor(unit.lastY * yRatio),
                            Math.ceil(xRatioC), Math.ceil(yRatioC));
                    break;
            }
        }
        changedUnits = [];
    };

    /**
     * Renders the changes in the buildings layer.
     */
    renderBuildingsLayer = function () {
        var i, building, x1, y1, x2, y2, x3, y3, x4, y4, buildingType,
                resource, resourceType;
        for (i = changedBuildings.length; i--;) {
            building = changedBuildings[i];
            buildingsLayerCtx.globalCompositeOperation = building.type ===
                    false ? 'destination-out' : 'source-over';
            x1 = building.x;
            y1 = building.y;
            x2 = x1 + building.width;
            y2 = y1 + Math.floor(building.width / 2);
            x3 = x1 - Math.floor(building.height / 2);
            y3 = y1 + building.height;
            x4 = x3 + building.width;
            y4 = y3 + Math.floor(building.width / 2);
            buildingType = BuildingsDefinition.getType(building.type);
            if (buildingType.resource === null) {
                buildingsLayerCtx.fillStyle = building.color;
            } else {
                resource = buildingType.resource;
                resourceType = ResourcesDefinition.getType(resource);
                buildingsLayerCtx.fillStyle = resourceType.minimap;
            }
            drawTileLine(x1, y1, x2, y2, buildingsLayerCtx);
            drawTileLine(x1, y1, x3, y3, buildingsLayerCtx);
            drawTileLine(x2, y2, x4, y4, buildingsLayerCtx);
            drawTileLine(x3, y3, x4, y4, buildingsLayerCtx);
            fill(Math.round((x1 + x4) / 2), Math.round((y1 + y4) / 2),
                    buildingsLayerCtx);
        }
        changedBuildings = [];
    };

    /**
     * Renders the terrain layer.
     */
    renderTerrainLayer = function () {
        var i, j, row;
        for (i = tiles.length; i--;) {
            row = tiles[i];
            for (j = row.length; j--;) {
                terrainLayerCtx.fillStyle = row[j].minimap;
                terrainLayerCtx.fillRect(xRatio * j, yRatio * i,
                        tileWidth, tileHeight);
            }
        }
        changedTerrain = false;
    };

    /**
     * Creates index used by the renderer for storing positions of units or
     * buildings.
     *
     * @return {Array} The two-dimensional array index.
     */
    createIndex = function () {
        var index, i, j;
        index = new Array(mapWidth);
        for (i = mapWidth; i--;) {
            index[i] = new Array(mapHeight);
            for (j = mapHeight; j--;) {
                index[i][j] = false;
            }
        }
        return index;
    };

    /**
     * Fills the area of tiles on the minimap. The area is defined by the tiles
     * of the same color.
     *
     * @param {Number} x The X coordinate of the tile position where the
     *        filling should be performed.
     * @param {Number} y The Y coordinate of the tile position where the
     *        filling should be performed.
     * @param {CanvasRenderingContext2D} ctx The 2D context of the canvas for
     *        rendering.
     * @param {fillColor} fillColor The color that should be used to color the
     *        area.
     */
    fill = function (x, y, ctx, fillColor) {
        var thisColor;
        if ((x >= mapWidth) || (x < 0) || (y >= mapHeight) || (y < 0)) {
            return;
        }
        thisColor = buildingsLayerIndex[x][y];
        if (fillColor === undefined) {
            fillColor = thisColor;
        }
        if (thisColor === fillColor) {
            ctx.fillRect(x * xRatio, y * yRatio, xRatioC, yRatioC);
            buildingsLayerIndex[x][y] = !buildingsLayerIndex[x][y];
            fill(x - 1, y, ctx, fillColor);
            fill(x + 1, y, ctx, fillColor);
            fill(x, y - 1, ctx, fillColor);
            fill(x, y + 1, ctx, fillColor);
        }
    };

    /**
     * Draw a line of tiles onto the canvas.
     *
     * @param {Number} x1 The starting X coordinate.
     * @param {Number} y1 The starting Y coordinate.
     * @param {Number} x2 The ending X coordinate.
     * @param {Number} y2 The ending Y coordinate.
     * @param {CanvasRenderingContext2D} ctx The 2D context of the canvas to be
     *        used for rendering.
     */
    drawTileLine = function (x1, y1, x2, y2, ctx) {
        var len, vx, vy, rx, ry;
        vx = x2 - x1;
        vy = y2 - y1;
        len = Math.sqrt(vx * vx + vy * vy);
        vx /= len;
        vy /= len;
        ctx.fillRect(xRatio * Math.round(x1), yRatio * Math.round(y1),
                xRatioC, yRatioC);
        do {
            x1 += vx;
            y1 += vy;
            rx = Math.round(x1);
            ry = Math.round(y1);
            if (buildingsLayerIndex[rx] &&
                    (buildingsLayerIndex[rx][ry] !== undefined)) {
                buildingsLayerIndex[rx][ry] = true;
                ctx.fillRect(xRatio * rx, yRatio * ry, xRatioC, yRatioC);
            }
        } while ((Math.round(x1) !== x2) && (Math.round(y1) !== y2))
    };

    /**
     * Initalizes the renderer - scaling, tile sizes and private properties.
     */
    initRenderer = function () {
        var i;
        xRatio = width / mapWidth;
        yRatio = height / mapHeight;
        xRatioC = Math.ceil(xRatio);
        yRatioC = Math.ceil(yRatio);
        tileWidth = Math.ceil(xRatio);
        tileHeight = Math.ceil(yRatio);
        changedTerrain = true;
        changedBuildings = [];
        changedUnits = [];
        buildingsLayerIndex = createIndex();

        for (i = map.getBuildings().length; i--;) {
            instance.onBuildingChange(map.getBuildings()[i]);
        }
        for (i = map.getUnits().length; i--;) {
            instance.onUnitChange(map.getUnits()[i]);
        }
    };
};<|endoftext|>


<commit_before>import * as windows from "../ambassador/src/client/windows";
import * as tabs from "../ambassador/src/client/tabs";
import * as keys from "../ambassador/src/client/keys";
import * as scrolls from "../ambassador/src/client/scrolls";
import { CLIENT_URL } from '../web-server/url';

describe("navigate test", () => {
  let targetWindow;

  before(() => {
    return windows.create().then((win) => {
      targetWindow = win;
      return tabs.create(targetWindow.id, CLIENT_URL);
    });
  });

  after(() => {
    return windows.remove(targetWindow.id);
  });

  it('goes to parent', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a/b/c').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'u');
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a/b/');
    });
  });

  it('removes hash', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a/b/c#navigate').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'u');
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a/b/c#');
    });
  });

  it('goes to root', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a/b/c').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'U', { shiftKey: true });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/');
    });
  });

  it('goes back and forward in history', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/#navigate').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'u');
    }).then(() => {
      return keys.press(targetTab.id, 'H', { shiftKey: true });
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url, 'go back in history').to.be.equal(CLIENT_URL + '/#navigate');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return keys.press(targetTab.id, 'L', { shiftKey: true });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url, 'go next in history').to.be.equal(CLIENT_URL + '/#');
    });
  });

  it('goes previous page by <a>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a-pagenation?page=9');
    });
  })

  it('goes next page by <a>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a-pagenation?page=11');
    });
  })

  it('goes previous page by <link>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/link-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/link-pagenation?page=9');
    });
  })

  it('goes next page by <link>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/link-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/link-pagenation?page=11');
    });
  })
});
<commit_msg>Add sleep<commit_after>import * as windows from "../ambassador/src/client/windows";
import * as tabs from "../ambassador/src/client/tabs";
import * as keys from "../ambassador/src/client/keys";
import * as scrolls from "../ambassador/src/client/scrolls";
import { CLIENT_URL } from '../web-server/url';

describe("navigate test", () => {
  let targetWindow;

  before(() => {
    return windows.create().then((win) => {
      targetWindow = win;
      return tabs.create(targetWindow.id, CLIENT_URL);
    });
  });

  after(() => {
    return windows.remove(targetWindow.id);
  });

  it('goes to parent', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a/b/c').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'u');
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a/b/');
    });
  });

  it('removes hash', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a/b/c#navigate').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'u');
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a/b/c#');
    });
  });

  it('goes to root', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a/b/c').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'U', { shiftKey: true });
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/');
    });
  });

  it('goes back and forward in history', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/#navigate').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, 'g');
    }).then(() => {
      return keys.press(targetTab.id, 'u');
    }).then(() => {
      return keys.press(targetTab.id, 'H', { shiftKey: true });
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url, 'go back in history').to.be.equal(CLIENT_URL + '/#navigate');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return keys.press(targetTab.id, 'L', { shiftKey: true });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url, 'go next in history').to.be.equal(CLIENT_URL + '/#');
    });
  });

  it('goes previous page by <a>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a-pagenation?page=9');
    });
  })

  it('goes next page by <a>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/a-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/a-pagenation?page=11');
    });
  })

  it('goes previous page by <link>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/link-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return keys.press(targetTab.id, '[');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/link-pagenation?page=9');
    });
  })

  it('goes next page by <link>', () => {
    let targetTab;
    return tabs.create(targetWindow.id, CLIENT_URL + '/link-pagenation?page=10').then((tab) => {
      targetTab = tab;
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return keys.press(targetTab.id, ']');
    }).then(() => {
      return new Promise(resolve => { setTimeout(() => resolve(), 10) });
    }).then(() => {
      return tabs.get(targetTab.id);
    }).then((tab) => {
      expect(tab.url).to.be.equal(CLIENT_URL + '/link-pagenation?page=11');
    });
  })
});
<|endoftext|>


<commit_before>(function () {
  "use strict";

  function serializeForm(formid) {
    var els = [];

    function handleElement(e) {
      var name = $(e).attr('name')
        , value = $(e).val()
        ;

      if (!name || '' === value) {
        return;
      }

      console.log(value);

      els.push({
          name: name
        , value: value
      });
    }

    // TODO insert these in the array in the order
    // they appear in the form rather than by element
    $(formid + ' input').forEach(handleElement);
    $(formid + ' select').forEach(handleElement);
    $(formid + ' textarea').forEach(handleElement);

    return els;
  }

  // Note that this is a potentially lossy conversion.
  // By convention arrays are specified as `xyz[]`,
  // but objects have no such standard
  function mapFormData(data) {
    var obj = {};

    function map(datum) {
      var arr
        , name
        , len
        ;

      name = datum.name;
      len = datum.name.length;

      if ('[]' === datum.name.substr(len - 2)) {
        name = datum.name.substr(0, len - 2);
        arr = obj[name] = (obj[name] || []);
        arr.push(datum.value);
      } else {
        obj[datum.name] = datum.value;
      }
    }

    data.forEach(map);

    return obj;
  }

  function serializeFormObject() {
    return mapFormData(serializeForm.apply(null, arguments));
  }

  module.exports.serializeForm = serializeForm;
  module.exports.serializeFormArray = serializeForm;
  module.exports.serializeFormObject = serializeFormObject;
}());
<commit_msg>added serializeFormUriEncoded<commit_after>(function () {
  "use strict";

  function serializeForm(formid) {
    var els = [];

    function handleElement(e) {
      var name = $(e).attr('name')
        , value = $(e).val()
        ;

      if (!name || '' === value) {
        return;
      }

      console.log(value);

      els.push({
          name: name
        , value: value
      });
    }

    // TODO insert these in the array in the order
    // they appear in the form rather than by element
    $(formid + ' input').forEach(handleElement);
    $(formid + ' select').forEach(handleElement);
    $(formid + ' textarea').forEach(handleElement);

    return els;
  }

  // Note that this is a potentially lossy conversion.
  // By convention arrays are specified as `xyz[]`,
  // but objects have no such standard
  function mapFormData(data) {
    var obj = {};

    function map(datum) {
      var arr
        , name
        , len
        ;

      name = datum.name;
      len = datum.name.length;

      if ('[]' === datum.name.substr(len - 2)) {
        name = datum.name.substr(0, len - 2);
        arr = obj[name] = (obj[name] || []);
        arr.push(datum.value);
      } else {
        obj[datum.name] = datum.value;
      }
    }

    data.forEach(map);

    return obj;
  }

  function serializeFormObject() {
    return mapFormData(serializeForm.apply(null, arguments));
  }

  function serializeFormUriEncoded() {
    var data = serializeForm.apply(null, arguments)
      , str = ''
      ;

    data.forEach(function (obj) {
      str += '&' + encodeURIComponent(obj.name) + '=' + encodeURIComponent(obj.value);
    });

    // remove leading '&'
    str = str.substr(1);

    return str;
  }

  module.exports.serializeForm = serializeForm;
  module.exports.serializeFormUriEncoded = serializeFormUriEncoded;
  module.exports.serializeFormArray = serializeForm;
  module.exports.serializeFormObject = serializeFormObject;
}());
<|endoftext|>