<commit_before>var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = 760 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 2000)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

var selectedList = ['pm','school','mandarin','up','chinese','strike','new',
      'bomb','blast','attack','die'];

drawGraph(selectedList);

function drawGraph(selectedList){

  d3.csv("cooccurrenceMatrixData.csv", function(data){

    totallist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, totallist) < 0){
          totallist.push(data[i].word1);
        }
        if ($.inArray(data[i].word2, totallist) < 0){
          totallist.push(data[i].word2);
        }
      }

    data1 = $.map(data, function(element){
          return ($.inArray(element.word1,selectedList)>-1?element:null);
        });
        data = $.map(data1, function(element){
          return ($.inArray(element.word2,selectedList)>-1?element:null);
        });

        graphDict = {};
        graphDict['nodes'] = [];
        graphDict['links'] = [];
        entrylist = [];
        for (i=0; i<data.length; i++){
          if ($.inArray(data[i].word1, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word1
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word1);
          };
          if ($.inArray(data[i].word2, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word2
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word2);
          };
          dict = {};
          dict['source'] = entrylist.indexOf(data[i].word1);
          dict['target'] = entrylist.indexOf(data[i].word2);
          dict['value'] = +data[i].size
          graphDict['links'].push(dict);
        };

    graph = graphDict;

    var term_label = forceListSvg.selectAll('.force_item')
            .data(totallist)
            .enter()
          .append('text')
            .attr('class', 'force_item')
            .attr("x", 50)
            .attr("y", function(d,i){ return i+"9.5px"; })
            .style("text-anchor", "middle")
            .style("font-size", "15px")
            .style("fill", "#53565A")
            .transition()
            .duration(750)
            //.style('fill', function(d){ return line_color(d.term); })
            .text(function(d){ return d; })
            .on('click', function(d){ return console.log(d); });

      //data = prepData(selectedList);

        force
          .nodes(graph.nodes)
          .links(graph.links)
          .start();

        var graphMin = d3.min(graph.links, function(d){ return d.size; });
        var graphMax = d3.max(graph.links, function(d){ return d.size; });

        var fill = d3.scale.ordinal()
            .domain([graphMin, graphMax])
            .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
              "#41ae76","#238b45","#006d2c","#00441b"]);

        var div = d3.select('div#chord_chart').append('div')
                .attr('class', 'tooltip')
                .style('opacity', 0);

        var link = forceSvg.selectAll(".link")
            .data(graph.links);

        link
          .enter().append("line")
            .attr("class", "link")
            .style('stroke-width', 1)
            .style('stroke', function(d){ return fill(d.value); });
            //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

        var node = forceSvg.selectAll(".node")
            .data(graph.nodes);

        node
          .enter().append("circle")
            .attr("class", "node")
            .attr("r", 5)
            .style("fill", function(d) { return color(d.group); })
            .on('dblclick', releasenode)
            .on('click', connectedNodes)
            .call(node_drag);
            //.call(force.drag);

        node
            .on('mouseover', function(d,i,j){
                d3.select(this).transition().duration(600)
                  .attr('r', 8).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 1);
                div.html(d.name)
                  .style('left', '300px')
                  .style('top', '10px');
                  //.style('left', (d3.event.pageX) + 10 + "px")
                  //.style('top', (d3.event.pageY) + 2 + "px")
                  //.style('color', line_color(used_data[j].term));
            })
            .on('mouseout', function(d){
                d3.select(this).transition().duration(600)
                  .attr('r', 5).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 0);
            });
        node.append("title")
            .text(function(d) { return d.name; });

        force.on("tick", function() {
          link.attr("x1", function(d) { return d.source.x; })
              .attr("y1", function(d) { return d.source.y; })
              .attr("x2", function(d) { return d.target.x; })
              .attr("y2", function(d) { return d.target.y; });

          node.attr("cx", function(d) { return d.x; })
              .attr("cy", function(d) { return d.y; });
        });

        //Toggle stores whether the highlighting is on
        var toggle = 0;

        //Create an array logging what is connected to what
        var linkedByIndex = {};
        for (i = 0; i < graph.nodes.length; i++) {
            linkedByIndex[i + "," + i] = 1;
        };
        graph.links.forEach(function (d) {
            linkedByIndex[d.source.index + "," + d.target.index] = 1;
        });

        //This function looks up whether a pair are neighbours
        function neighboring(a, b) {
            return linkedByIndex[a.index + "," + b.index];
        }

        function connectedNodes() {

          if (toggle == 0) {
              //Reduce the opacity of all but the neighbouring nodes
              d = d3.select(this).node().__data__;
              node.style("opacity", function (o) {
                  return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
              });

              link.style("opacity", function (o) {
                  return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
              });

              //Reduce the op

              toggle = 1;
          } else {
              //Put them back to opacity=1
              node.style("opacity", 1);
              link.style("opacity", 1);
              toggle = 0;
          }
        }

  });

};

function prepData(data, list){

      data1 = $.map(data, function(element){
        return ($.inArray(element.word1,list)>-1?element:null);
      });
      data = $.map(data1, function(element){
        return ($.inArray(element.word2,list)>-1?element:null);
      });

      graphDict = {};
      graphDict['nodes'] = [];
      graphDict['links'] = [];
      entrylist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word1
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word1);
        };
        if ($.inArray(data[i].word2, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word2
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word2);
        };
        dict = {};
        dict['source'] = entrylist.indexOf(data[i].word1);
        dict['target'] = entrylist.indexOf(data[i].word2);
        dict['value'] = +data[i].size
        graphDict['links'].push(dict);
      };
      //return graphDict;
    };

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<commit_msg>update data<commit_after>var margin = {top: 20, right: 20, bottom: 30, left: 140},
  width = 760 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-80)
    .linkDistance(200)
    .friction(0.9)
    .size([width, height]);

var forceSvg = d3.select("div#chord_chart").append("svg")
    .attr("width", width)
    .attr("height", height);

var forceListSvg = d3.select('div#force_list').append('svg')
    .attr('width', 200)
    .attr('height', 2000)
    .append('g')
      .attr("transform", "translate(" + margin.right + "," + margin.top + ")");;

var node_drag = d3.behavior.drag()
    .on("dragstart", dragstart)
    .on("drag", dragmove)
    .on("dragend", dragend);
    function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you start dragging
    }
    function dragmove(d, i) {
        d.px += d3.event.dx;
        d.py += d3.event.dy;
        d.x += d3.event.dx;
        d.y += d3.event.dy;
    }
    function dragend(d, i) {
        d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        force.resume();
    }
    function releasenode(d) {
        d.fixed = false; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
        //force.resume();
    };

var selectedList = ['pm','school','mandarin','up','chinese','strike','new',
      'bomb','blast','attack','die'];

drawGraph(selectedList);

function drawGraph(selectedList){

  d3.csv("cooccurrenceMatrixData.csv", function(data){

    totallist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, totallist) < 0){
          totallist.push(data[i].word1);
        }
        if ($.inArray(data[i].word2, totallist) < 0){
          totallist.push(data[i].word2);
        }
      }

    data1 = $.map(data, function(element){
          return ($.inArray(element.word1,selectedList)>-1?element:null);
        });
        data = $.map(data1, function(element){
          return ($.inArray(element.word2,selectedList)>-1?element:null);
        });

        graphDict = {};
        graphDict['nodes'] = [];
        graphDict['links'] = [];
        entrylist = [];
        for (i=0; i<data.length; i++){
          if ($.inArray(data[i].word1, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word1
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word1);
          };
          if ($.inArray(data[i].word2, entrylist) < 0){
            dict = {};
            dict['name'] = data[i].word2
            dict['group'] = 0
            graphDict['nodes'].push(dict)
            entrylist.push(data[i].word2);
          };
          dict = {};
          dict['source'] = entrylist.indexOf(data[i].word1);
          dict['target'] = entrylist.indexOf(data[i].word2);
          dict['value'] = +data[i].size
          graphDict['links'].push(dict);
        };

    graph = graphDict;

    var term_label = forceListSvg.selectAll('.force_item')
            .data(totallist)
            .enter()
          .append('text')
            .attr('class', 'force_item')
            .attr("x", 50)
            .attr("y", function(d,i){ return i+"9.5px"; })
            .style("text-anchor", "middle")
            .style("font-size", "15px")
            .style("fill", "#53565A")
            .transition()
            .duration(750)
            //.style('fill', function(d){ return line_color(d.term); })
            .text(function(d){ return d; });

    term_label.on('click', function(d){ return console.log(d); });

      //data = prepData(selectedList);

        force
          .nodes(graph.nodes)
          .links(graph.links)
          .start();

        var graphMin = d3.min(graph.links, function(d){ return d.size; });
        var graphMax = d3.max(graph.links, function(d){ return d.size; });

        var fill = d3.scale.ordinal()
            .domain([graphMin, graphMax])
            .range(["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4",
              "#41ae76","#238b45","#006d2c","#00441b"]);

        var div = d3.select('div#chord_chart').append('div')
                .attr('class', 'tooltip')
                .style('opacity', 0);

        var link = forceSvg.selectAll(".link")
            .data(graph.links);

        link
          .enter().append("line")
            .attr("class", "link")
            .style('stroke-width', 1)
            .style('stroke', function(d){ return fill(d.value); });
            //.style("stroke-width", function(d) { return Math.sqrt(d.value); });

        var node = forceSvg.selectAll(".node")
            .data(graph.nodes);

        node
          .enter().append("circle")
            .attr("class", "node")
            .attr("r", 5)
            .style("fill", function(d) { return color(d.group); })
            .on('dblclick', releasenode)
            .on('click', connectedNodes)
            .call(node_drag);
            //.call(force.drag);

        node
            .on('mouseover', function(d,i,j){
                d3.select(this).transition().duration(600)
                  .attr('r', 8).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 1);
                div.html(d.name)
                  .style('left', '300px')
                  .style('top', '10px');
                  //.style('left', (d3.event.pageX) + 10 + "px")
                  //.style('top', (d3.event.pageY) + 2 + "px")
                  //.style('color', line_color(used_data[j].term));
            })
            .on('mouseout', function(d){
                d3.select(this).transition().duration(600)
                  .attr('r', 5).style('opacity', 1);
                div.transition()
                  .duration(500)
                  .style('opacity', 0);
            });
        node.append("title")
            .text(function(d) { return d.name; });

        force.on("tick", function() {
          link.attr("x1", function(d) { return d.source.x; })
              .attr("y1", function(d) { return d.source.y; })
              .attr("x2", function(d) { return d.target.x; })
              .attr("y2", function(d) { return d.target.y; });

          node.attr("cx", function(d) { return d.x; })
              .attr("cy", function(d) { return d.y; });
        });

        //Toggle stores whether the highlighting is on
        var toggle = 0;

        //Create an array logging what is connected to what
        var linkedByIndex = {};
        for (i = 0; i < graph.nodes.length; i++) {
            linkedByIndex[i + "," + i] = 1;
        };
        graph.links.forEach(function (d) {
            linkedByIndex[d.source.index + "," + d.target.index] = 1;
        });

        //This function looks up whether a pair are neighbours
        function neighboring(a, b) {
            return linkedByIndex[a.index + "," + b.index];
        }

        function connectedNodes() {

          if (toggle == 0) {
              //Reduce the opacity of all but the neighbouring nodes
              d = d3.select(this).node().__data__;
              node.style("opacity", function (o) {
                  return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
              });

              link.style("opacity", function (o) {
                  return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
              });

              //Reduce the op

              toggle = 1;
          } else {
              //Put them back to opacity=1
              node.style("opacity", 1);
              link.style("opacity", 1);
              toggle = 0;
          }
        }

  });

};

function prepData(data, list){

      data1 = $.map(data, function(element){
        return ($.inArray(element.word1,list)>-1?element:null);
      });
      data = $.map(data1, function(element){
        return ($.inArray(element.word2,list)>-1?element:null);
      });

      graphDict = {};
      graphDict['nodes'] = [];
      graphDict['links'] = [];
      entrylist = [];
      for (i=0; i<data.length; i++){
        if ($.inArray(data[i].word1, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word1
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word1);
        };
        if ($.inArray(data[i].word2, entrylist) < 0){
          dict = {};
          dict['name'] = data[i].word2
          dict['group'] = 0
          graphDict['nodes'].push(dict)
          entrylist.push(data[i].word2);
        };
        dict = {};
        dict['source'] = entrylist.indexOf(data[i].word1);
        dict['target'] = entrylist.indexOf(data[i].word2);
        dict['value'] = +data[i].size
        graphDict['links'].push(dict);
      };
      //return graphDict;
    };

/*
d3.json("newsGraph.json", function(error, graph) {
  testGraph = JSON.parse(JSON.stringify(graph))

  selectedList = ['up','police','china','labor','union'];
  selectedData1 = $.map(testGraph.nodes, function(element){
      return ($.inArray(element.name,selectedList)>-1?element:null);
    });

  selectedData2 = $.map(testGraph.links, function(element){
      return ($.inArray(element['name1'],selectedList)>-1?element:null);
    });

  selectedData3 = $.map(selectedData2, function(element){
      return ($.inArray(element.name2,selectedList)>-1?element:null);
    });

  new_graph = {};
  new_graph['nodes'] = graph.nodes;
  new_graph['links'] = selectedData3;

  //drawGraph(graph, selectedData1, selectedData3);
  drawGraph(graph);

});
*/

<|endoftext|>


<commit_before>commSphereApp.controller('dashDraftsCtrl', ['$scope', '$modal','$routeParams','ngEvents','$http','$route','$window','$filter','$log', function($scope, $modal,$routeParams,ngEvents,$http,$route,$window,$filter,$log) {

$scope.$parent.activeMenu='drafts';
$scope.sortReverse=false;
$scope.sortType = "dateCreated";
$scope.totalInstances = 0;
$scope.itemsPerPage = 15;
$scope.currentPage = 1;

$http.get('/api/events/drafts').then(function(res){
// retrieve all draft instances from the database
     $log.debug(res.data);
     if(res.data) {
         $scope.instances=res.data;
         //$scope.filteredInstances = $filter('searchAll')($scope.instances,'');
         $scope.totalInstances = $scope.instances.length;
          $scope.beginItem = (($scope.currentPage - 1) * $scope.itemsPerPage);
          $scope.endItem = $scope.beginItem + $scope.itemsPerPage;
  //      $scope.filteredInstances = $scope.instances.slice(beginItem,endItem);
         //$scope.filteredInstances = $filter('searchAll')($scope.instances,'').slice(beginItem,endItem);
         $scope.sortInstances();
         } else {
             alert('no data received, assign new id');
         }
    });

$scope.editDraft = function (size,draftInstance,isNew,showOverrideCheckbox) {
// activate the modal for edit draft
        var modalInstance = $modal.open({
        templateUrl: '/partials/createEventModal',
        controller: DraftEventModalInstanceCtrl,
        size: size,
        keyboard: false,
        backdrop: 'static',
        resolve: {
         draftInstance: function () {
           return draftInstance;
         },
         isNew : function() {
           return isNew;
         },
         showOverrideCheckbox : function() {
           return showOverrideCheckbox;
         }
       }
      });
    };

$scope.deleteDraft = function (draftInstance) {
  // delete the passed in draft instance
    var draftDate = $filter('date')(draftInstance.dateCreated,'MM/dd/yyyy - hh:mm:ss');
    var deleteConfirm = $window.confirm('Are you absolutely sure you want to delete draft:' + draftInstance.eventName +' created on ' + draftDate + '? ');

    if (deleteConfirm) {

       $http.post('/api/events/drafts/delete/'+draftInstance._id).then(function(res){
       if(res.data) {
            // delete success
            $route.reload();
         }
         else {
             alert('delete failed');
         }
    });

    }
    };

// $scope.$watch('$scope.sortType',function() {
//     console.log('sorting fired');
//     if ($scope.sortType !== '') {
//              $scope.instances = $filter('orderBy')($scope.instances,$scope.sortType, $scope.sortReverse);
//           }
// });

// $scope.$watch('$parent.searchText', function (searchText) {
//         if (!searchText){
//           searchText = '';
//         }
//           if ($scope.instances) {
//              $scope.currentPage = 1;
//              var beginItem = (($scope.currentPage - 1) * $scope.itemsPerPage);
//              var endItem = beginItem + $scope.itemsPerPage;
//              $scope.filteredInstances = $filter('searchAll')($scope.instances,searchText).slice(beginItem,endItem);
//             if (searchText =='') {
//                $scope.totalInstances = $scope.instances.length;
//             }
//             else {
//                $scope.totalInstances = $scope.filteredInstances.length;
//             }

//         }
//  });

$scope.sortInstances = function(sortType) {
  if($scope.sortReverse)
  {
    $scope.instances.sort(compareAsc);
  }
  else
  {
    $scope.instances.sort(compareDesc);
  }

}

function compareAsc(a,b) {
  if($scope.sortType=="coordinatorAssign")
  {
    if ((a.userCreated.displayName).toString().toLowerCase() < (b.userCreated.displayName).toString().toLowerCase())
      return -1;
    if ((a.userCreated.displayName).toString().toLowerCase() > (b.userCreated.displayName).toString().toLowerCase())
      return 1;
    return 0;
  }
  else
  {
    if ((a[$scope.sortType]).toString().toLowerCase() < (b[$scope.sortType]).toString().toLowerCase())
      return -1;
    if ((a[$scope.sortType]).toString().toLowerCase() > (b[$scope.sortType]).toString().toLowerCase())
      return 1;
    return 0;
  }
}

function compareDesc(a,b) {
  if($scope.sortType=="coordinatorAssign")
  {
    if ((a.userCreated.displayName).toString().toLowerCase() > (b.userCreated.displayName).toString().toLowerCase())
      return -1;
    if ((a.userCreated.displayName).toString().toLowerCase() < (b.userCreated.displayName).toString().toLowerCase())
      return 1;
    return 0;
  }
  else
  {
    if ((a[$scope.sortType]).toString().toLowerCase() > (b[$scope.sortType]).toString().toLowerCase())
      return -1;
    if ((a[$scope.sortType]).toString().toLowerCase() < (b[$scope.sortType]).toString().toLowerCase())
      return 1;
    return 0;
  }
}

$scope.pageCount = function () {
    return Math.ceil($scope.totalInstances / $scope.itemsPerPage);
  };

$scope.setPage = function (pageNo) {
    $scope.currentPage = pageNo;
  };

$scope.pageChanged = function(searchText) {
    $scope.beginItem = (($scope.currentPage - 1) * $scope.itemsPerPage);
    $scope.endItem = $scope.beginItem + $scope.itemsPerPage;
    console.log($scope.beginItem, $scope.endItem);
//    $scope.filteredInstances = $filter('searchAll')($scope.instances,searchText).slice(beginItem,endItem);
  };

}]);

var DraftEventModalInstanceCtrl = function ($scope, $route, $modalInstance,draftInstance,isNew,$log) {
// controller for draft edit modal screen
 $scope.draftInstance = draftInstance;
 $scope.isNew = isNew;

  $scope.ok = function () {
    $log.debug("ok");
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $log.debug("canceled");
    $modalInstance.dismiss();
  };
};

<commit_msg>[fix]  allowed user to get back to draft mode as saved (either from create from existing event mode or new event)<commit_after>commSphereApp.controller('dashDraftsCtrl', ['$scope', '$modal','$routeParams','ngEvents','$http','$route','$window','$filter','$log', function($scope, $modal,$routeParams,ngEvents,$http,$route,$window,$filter,$log) {

$scope.$parent.activeMenu='drafts';
$scope.sortReverse=false;
$scope.sortType = "dateCreated";
$scope.totalInstances = 0;
$scope.itemsPerPage = 15;
$scope.currentPage = 1;

$http.get('/api/events/drafts').then(function(res){
// retrieve all draft instances from the database
     $log.debug(res.data);
     if(res.data) {
         $scope.instances=res.data;
         //$scope.filteredInstances = $filter('searchAll')($scope.instances,'');
         $scope.totalInstances = $scope.instances.length;
          $scope.beginItem = (($scope.currentPage - 1) * $scope.itemsPerPage);
          $scope.endItem = $scope.beginItem + $scope.itemsPerPage;
  //      $scope.filteredInstances = $scope.instances.slice(beginItem,endItem);
         //$scope.filteredInstances = $filter('searchAll')($scope.instances,'').slice(beginItem,endItem);
         $scope.sortInstances();
         } else {
             alert('no data received, assign new id');
         }
    });

$scope.editDraft = function (size,draftInstance,isNew,showOverrideCheckbox) {
// activate the modal for edit draft
        var modalInstance = $modal.open({
        templateUrl: '/partials/createEventModal',
        controller: DraftEventModalInstanceCtrl,
        size: size,
        keyboard: false,
        backdrop: 'static',
        resolve: {
         draftInstance: function () {
           return draftInstance;
         },
         isNew : function() {
          // check if eventInstanceId populated.  if yes, then the instance was saved while in creating from existing event mode
            if (draftInstance.eventInstanceId !== ''){
              isNew = false;
            }
           return isNew;
         },
         showOverrideCheckbox : function() {
           return showOverrideCheckbox;
         }
       }
      });
    };

$scope.deleteDraft = function (draftInstance) {
  // delete the passed in draft instance
    var draftDate = $filter('date')(draftInstance.dateCreated,'MM/dd/yyyy - hh:mm:ss');
    var deleteConfirm = $window.confirm('Are you absolutely sure you want to delete draft:' + draftInstance.eventName +' created on ' + draftDate + '? ');

    if (deleteConfirm) {

       $http.post('/api/events/drafts/delete/'+draftInstance._id).then(function(res){
       if(res.data) {
            // delete success
            $route.reload();
         }
         else {
             alert('delete failed');
         }
    });

    }
    };

// $scope.$watch('$scope.sortType',function() {
//     console.log('sorting fired');
//     if ($scope.sortType !== '') {
//              $scope.instances = $filter('orderBy')($scope.instances,$scope.sortType, $scope.sortReverse);
//           }
// });

// $scope.$watch('$parent.searchText', function (searchText) {
//         if (!searchText){
//           searchText = '';
//         }
//           if ($scope.instances) {
//              $scope.currentPage = 1;
//              var beginItem = (($scope.currentPage - 1) * $scope.itemsPerPage);
//              var endItem = beginItem + $scope.itemsPerPage;
//              $scope.filteredInstances = $filter('searchAll')($scope.instances,searchText).slice(beginItem,endItem);
//             if (searchText =='') {
//                $scope.totalInstances = $scope.instances.length;
//             }
//             else {
//                $scope.totalInstances = $scope.filteredInstances.length;
//             }

//         }
//  });

$scope.sortInstances = function(sortType) {
  if($scope.sortReverse)
  {
    $scope.instances.sort(compareAsc);
  }
  else
  {
    $scope.instances.sort(compareDesc);
  }

}

function compareAsc(a,b) {
  if($scope.sortType=="coordinatorAssign")
  {
    if ((a.userCreated.displayName).toString().toLowerCase() < (b.userCreated.displayName).toString().toLowerCase())
      return -1;
    if ((a.userCreated.displayName).toString().toLowerCase() > (b.userCreated.displayName).toString().toLowerCase())
      return 1;
    return 0;
  }
  else
  {
    if ((a[$scope.sortType]).toString().toLowerCase() < (b[$scope.sortType]).toString().toLowerCase())
      return -1;
    if ((a[$scope.sortType]).toString().toLowerCase() > (b[$scope.sortType]).toString().toLowerCase())
      return 1;
    return 0;
  }
}

function compareDesc(a,b) {
  if($scope.sortType=="coordinatorAssign")
  {
    if ((a.userCreated.displayName).toString().toLowerCase() > (b.userCreated.displayName).toString().toLowerCase())
      return -1;
    if ((a.userCreated.displayName).toString().toLowerCase() < (b.userCreated.displayName).toString().toLowerCase())
      return 1;
    return 0;
  }
  else
  {
    if ((a[$scope.sortType]).toString().toLowerCase() > (b[$scope.sortType]).toString().toLowerCase())
      return -1;
    if ((a[$scope.sortType]).toString().toLowerCase() < (b[$scope.sortType]).toString().toLowerCase())
      return 1;
    return 0;
  }
}

$scope.pageCount = function () {
    return Math.ceil($scope.totalInstances / $scope.itemsPerPage);
  };

$scope.setPage = function (pageNo) {
    $scope.currentPage = pageNo;
  };

$scope.pageChanged = function(searchText) {
    $scope.beginItem = (($scope.currentPage - 1) * $scope.itemsPerPage);
    $scope.endItem = $scope.beginItem + $scope.itemsPerPage;
    console.log($scope.beginItem, $scope.endItem);
//    $scope.filteredInstances = $filter('searchAll')($scope.instances,searchText).slice(beginItem,endItem);
  };

}]);

var DraftEventModalInstanceCtrl = function ($scope, $route, $modalInstance,draftInstance,isNew,showOverrideCheckbox,$log) {
// controller for draft edit modal screen
 $scope.draftInstance = draftInstance;
 $scope.isNew = isNew;
 $scope.showOverrideCheckbox = showOverrideCheckbox;
  $scope.ok = function () {
    $log.debug("ok");
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $log.debug("canceled");
    $modalInstance.dismiss();
  };
};

<|endoftext|>


<commit_before>// Globals
var helper_suffix;
var clip;

$(document).ready(function(){
  $('#search-routes').focus();
  helper_suffix = '_path';
  clip = new ZeroClipboard($(".clip-button"));
});

$(document).on('click', '.path-helper', function(e) {
  e.preventDefault();
  var suffix = $(this).data('route-helper'),
      clip = '';

  // Return, nothing todo here
  if (helper_suffix === suffix) { return; }

  // Update!
  $('span.helper').html(suffix);
  // Update buttons

  $('.clip-button').each(function(){
    clip = $(this).attr('data-clipboard-text').replace(helper_suffix, suffix);
    $(this).attr('data-clipboard-text', clip);
  });
  helper_suffix = suffix;
});

// Listener to search
$(document).on('input', '#search-routes', function(){
  var $el = $(this),
      value = $el.val(),
      found_count = 0;

  if(value.length < 2) {
    $('#route_table tbody tr').show();
    $('tr.empty').hide();
    $('span.highlight').each(function(){
      $(this).replaceWith($(this).text());
    });
    return;
  }

  $('#route_table tbody tr.route_row').each(function(index) {
    var $row = $(this),
        found = false;

    $row.find('td').each(function(){
      var $col = $(this);

      if (!$col.hasClass('verb') && !$col.hasClass('constraints')) {
        var text = $col.data('value');

        if(text.indexOf(value) > -1){
          text = text.replace(value, '' + value + '');
          found = true;
        }

        if($col.hasClass('helper') && text !== ''){
          text = text + helper_suffix;
          $col.find('.helper-alias').html(text)
        } else {
          // Add text
          $col.html(text);
        }
      }

    });

    if (found) {
      $row.show();
      found_count++;
    } else {
      $row.hide();
    }

  });

  // Check if found_count
  if (found_count == 0) {
    $('tr.empty td').html('There are not any coincidence for ' + value + '');
    $('tr.empty').show();
  } else {
    $('tr.empty').hide();
  }
});
<commit_msg>#1 Fixed an error when to copy helpers after search<commit_after>// Globals
var helper_suffix;
var clip;

$(document).ready(function(){
  $('#search-routes').focus();
  helper_suffix = '_path';
  clip = new ZeroClipboard($(".clip-button"));
});

$(document).on('click', '.path-helper', function(e) {
  e.preventDefault();
  var suffix = $(this).data('route-helper'),
      clip = '';

  // Return, nothing todo here
  if (helper_suffix === suffix) { return; }

  // Update!
  $('span.helper').html(suffix);
  // Update buttons

  $('.clip-button').each(function(){
    clip = $(this).attr('data-clipboard-text').replace(helper_suffix, suffix);
    $(this).attr('data-clipboard-text', clip);
  });
  helper_suffix = suffix;
});

// Listener to search
$(document).on('input', '#search-routes', function(){
  var $el = $(this),
      value = $el.val(),
      found_count = 0;

  if(value.length < 2) {
    $('#route_table tbody tr').show();
    $('tr.empty').hide();
    $('span.highlight').each(function(){
      $(this).replaceWith($(this).text());
    });
    return;
  }

  $('#route_table tbody tr.route_row').each(function(index) {
    var $row = $(this),
        found = false;

    $row.find('td').each(function(){
      var $col = $(this);

      if (!$col.hasClass('verb') && !$col.hasClass('constraints')) {
        var text = $col.data('value');

        if(text.indexOf(value) > -1){
          text = text.replace(value, '' + value + '');
          found = true;
        }

        if($col.hasClass('helper') && text !== ''){
          text = text + '' + helper_suffix + '';
          $col.find('.helper-alias').html(text)
        } else {
          // Add text
          $col.html(text);
        }
      }

    });

    if (found) {
      $row.show();
      found_count++;
    } else {
      $row.hide();
    }

  });

  // Check if found_count
  if (found_count == 0) {
    $('tr.empty td').html('There are not any coincidence for ' + value + '');
    $('tr.empty').show();
  } else {
    $('tr.empty').hide();
  }
});
<|endoftext|>


<commit_before>const axios=require('axios');
const Terminal=require('./util').Terminal;
const LanguagePack=require('./util').LanguagePack;
const LANGUAGE_PACK_DATA={
	'zh-cn':{
		'Flight Control Center':'飞控中心',
		'Loading':'加载中……',
        KEYBOARD_HELP_IDLE:'Esc：退出',
		KEYBOARD_HELP:'Esc：退出    s:开启/关闭声音    p:暂停/继续',
		'No Flight Mission':'没有飞行任务。',
        'Aircraft Model:':'机种：',
		'Longitude':'经度：',
        'Latitude':'纬度：',
        'Flight Time':'飞行时间：',
        'Remaining Time':'剩余时间：',
        'Total Distance':'总里程：',
        'Remaining Distance':'剩余里程：',
        'Elapsed Distance':'飞行里程：',
        'In Flight':'飞行中',
        'Paused':'暂停',
        'Crashed':'已坠毁'
    },
	'ja':{
		'Flight Control Center':'飛行制御センター',
		'Loading':'Loading...',
		KEYBOARD_HELP_IDLE:'Esc：終了',
		KEYBOARD_HELP:'Esc：終了    s:ｻｳﾝﾄﾞｵﾝ/ｵﾌ    p:一時停止/再開',
		'No Flight Mission':'飛行任務がありません。',
		'Aircraft Model:':'機種：',
		'Longitude':'経度：',
        'Latitude':'緯度：',
        'Flight Time':'飛行時間：',
        'Remaining Time':'残り時間：',
        'Total Distance':'総距離：',
        'Remaining Distance':'残り距離：',
        'Elapsed Distance':'飛行距離：',
        'In Flight':'飛行中',
        'Paused':'一時停止',
        'Crashed':'墜落しました'
    }
}
module.exports=class{
    data=undefined;
    running=true;
    constructor(stream,_exit,param={}){
        this._exit=_exit;

        this.terminal=new Terminal(stream,{
            outputEncoding:param.encoding
        });
        this.lang=new LanguagePack(LANGUAGE_PACK_DATA,param.language);

        this.FGFS_HOST=param.FGFS_HOST;
        this.terminal.pc98SetBottomLine(false);
        this.terminal.clrscr();
        this.terminal.locate(0,0);
        this.terminal.setcursor(false);
        this.terminal.print(this.lang.t('Loading'));
        this.refresh();
    }
    drawFrame(){
        this.terminal.clrscr();
        this.terminal.locate(0,1);
        this.terminal.setattr(1,7,36);
        this.terminal.print(' '.repeat(80));
        let title=this.lang.t('Flight Control Center');
        this.terminal.locate(Math.round((80-Terminal.strlen(title))/2),1);
        this.terminal.print(title);

        this.terminal.locate(0,25);
        this.terminal.setattr(7,36);
        this.terminal.print(' '.repeat(80));
        this.terminal.locate(2,25);
        this.terminal.print(this.lang.t(this.data ? 'KEYBOARD_HELP' : 'KEYBOARD_HELP_IDLE'));
        this.terminal.setattr(0);
    }
    async refresh(){
        setTimeout(()=>{
            if(this.running){
                this.refresh();
            }
        },1000);

        let data=null;
        try{
            data=await axios({
                method:'GET',
                url:this.FGFS_HOST+'/json/fgreport'
            });
        }catch(e){
            if(null!==this.data){
                this.data=null;
                this.drawFrame();
                let text=this.lang.t('Flight Control Center');
                this.terminal.locate(Math.floor((80-Terminal.strlen(text))/2),12);
                this.terminal.print(text);
            }
            return;
        }

        try{
            let fgreport={};
            for(let item of data.data.children){
                fgreport[item.name]=item.value;
            }

            if(!this.data){
                this.data=fgreport;
                this.drawFrame();
            }
            fgreport['longitude'] = Math.abs(fgreport['longitude-deg']).toFixed(6)+(fgreport['longitude-deg']>=0 ? 'E' : 'W');
            fgreport['latitude'] = Math.abs(fgreport['latitude-deg']).toFixed(6)+(fgreport['latitude-deg']>=0 ? 'N' : 'S');
            let pad=Terminal.rpad, padSize=11;
            this.terminal.locate(0,3);
            this.terminal.print(pad(this.lang.t('Aircraft Model'),padSize)+fgreport.aircraft+'        ');
            this.terminal.locate(0,4);
            this.terminal.print(pad(this.lang.t('Longitude'),padSize)+fgreport['longitude']+'        ');
            this.terminal.locate(0,5);
            this.terminal.print(pad(this.lang.t('Latitude'),padSize)+fgreport['latitude']+'        ');
            this.terminal.locate(0,6);
            this.terminal.print(pad(this.lang.t('Flight Time'),padSize)+fgreport['flight-time-string']+'        ');
            this.terminal.locate(0,7);
            this.terminal.print(pad(this.lang.t('Remaining Time'),padSize)+fgreport['ete-string']+'        ');
            this.terminal.locate(0,8);
            this.terminal.print(pad(this.lang.t('Total Distance'),padSize)+fgreport['total-distance'].toFixed(1)+'nm        ');
            this.terminal.locate(0,9);
            this.terminal.print(pad(this.lang.t('Remaining Distance'),padSize)+fgreport['distance-remaining-nm'].toFixed(1)+'nm        ');
            this.terminal.locate(0,10);
            this.terminal.print(pad(this.lang.t('Flight Distance'),padSize)+(Number(fgreport['total-distance'])-Number(fgreport['distance-remaining-nm'])).toFixed(1)+'nm        ');

            this.terminal.locate(0,24);
            if(fgreport['crashed']){
                this.terminal.setattr(1,5,33,41);
                this.terminal.print(this.lang.t('Crashed'));
            }else if(fgreport['paused']){
                this.terminal.setattr(33);
                this.terminal.print(this.lang.t('Paused'));
            }else{
                this.terminal.setattr(32);
                this.terminal.print(this.lang.t('In Flight'));
            }
            this.terminal.setattr(0);
            this.terminal.print(' '.repeat(20));
        }catch(e){
            console.error(e);
        }
    }
    destroy(){
        try{
            this.running=false;
        }catch(e){
            console.error(e);
        }finally{
            this._exit();
        }
    }
    async toggleSound(){
        let {data}=await axios({
            method:'GET',
            url:this.FGFS_HOST+'/json/sim/sound/enabled'
        });
        await axios({
            method:'GET',
            url:this.FGFS_HOST+`/props/sim/sound?submit=set&enabled=${data.value ? 'false' : 'true'}`
        });
    }
    async togglePause(){
        await axios({
            method:'GET',
            url:this.FGFS_HOST+'/run.cgi?value=pause'
        });
    }
    ondata(data){
        try{
            switch(data[0]){
                case 0x1b:
                    this.terminal.reset();
                    this.destroy();
                    return;
                break;
                case 0x73:
                    this.toggleSound();
                break;
                case 0x70:
                    this.togglePause();
                break;
            }
        }catch(e){
            console.error(e);
        }
    }
}<commit_msg>fgfs-tools updated<commit_after>const axios=require('axios');
const Terminal=require('./util').Terminal;
const LanguagePack=require('./util').LanguagePack;
const LANGUAGE_PACK_DATA={
	'zh-cn':{
		'Flight Control Center':'飞控中心',
		'Loading':'加载中……',
        KEYBOARD_HELP_IDLE:'Esc：退出',
		KEYBOARD_HELP:'Esc：退出    s:开启/关闭声音    p:暂停/继续',
		'No Flight Mission':'没有飞行任务。',
        'Aircraft Model:':'机种',
		'Longitude':'经度',
        'Latitude':'纬度',
        'Flight Time':'飞行时间',
        'Remaining Time':'剩余时间',
        'Total Distance':'总里程',
        'Remaining Distance':'剩余里程',
        'Elapsed Distance':'飞行里程',
        'In Flight':'飞行中',
        'Paused':'已暂停',
        'Crashed':'已坠毁',
        'Direction':'方向',
        'AGL':'相对高度',
        'Altitude':'海拔高度',
        'Vertical Speed':'垂直速度',
        'Speed':'速度',
        'Airspeed':'空速',
        'Groundspeed':'地速',
        'Mach':'马赫数',
        'Fuel':'燃料'
    },
	'ja':{
		'Flight Control Center':'飛行制御センター',
		'Loading':'Loading...',
		KEYBOARD_HELP_IDLE:'Esc：終了',
		KEYBOARD_HELP:'Esc：終了    s:ｻｳﾝﾄﾞｵﾝ/ｵﾌ    p:一時停止/再開',
		'No Flight Mission':'飛行任務がありません。',
		'Aircraft Model:':'機種：',
		'Longitude':'経度',
        'Latitude':'緯度',
        'Flight Time':'飛行時間',
        'Remaining Time':'残り時間',
        'Total Distance':'総距離',
        'Remaining Distance':'残り距離',
        'Elapsed Distance':'飛行距離',
        'In Flight':'飛行中',
        'Paused':'一時停止',
        'Crashed':'墜落しました',
        'Direction':'方向',
        'AGL':'対地高度',
        'Altitude':'海抜高度',
        'Vertical Speed':'垂直速度',
        'Speed':'速度',
        'Airspeed':'対気速度',
        'Groundspeed':'対地速度',
        'Mach':'マッハ数',
        'Fuel':'燃料'
    }
}
module.exports=class{
    data=undefined;
    running=true;
    constructor(stream,_exit,param={}){
        this._exit=_exit;

        this.terminal=new Terminal(stream,{
            outputEncoding:param.encoding
        });
        this.lang=new LanguagePack(LANGUAGE_PACK_DATA,param.language);

        this.FGFS_HOST=param.FGFS_HOST;
        this.terminal.pc98SetBottomLine(false);
        this.terminal.clrscr();
        this.terminal.locate(0,0);
        this.terminal.setcursor(false);
        this.terminal.print(this.lang.t('Loading'));
        this.refresh();
    }
    drawFrame(){
        this.terminal.clrscr();
        this.terminal.locate(0,1);
        this.terminal.setattr(1,7,36);
        this.terminal.print(' '.repeat(80));
        let title=this.lang.t('Flight Control Center');
        this.terminal.locate(Math.round((80-Terminal.strlen(title))/2),1);
        this.terminal.print(title);

        this.terminal.locate(0,25);
        this.terminal.setattr(7,36);
        this.terminal.print(' '.repeat(80));
        this.terminal.locate(2,25);
        this.terminal.print(this.lang.t(this.data ? 'KEYBOARD_HELP' : 'KEYBOARD_HELP_IDLE'));
        this.terminal.setattr(0);
    }
    async refresh(){
        setTimeout(()=>{
            if(this.running){
                this.refresh();
            }
        },1000);

        let data=null;
        try{
            data=await axios({
                method:'GET',
                url:this.FGFS_HOST+'/json/fgreport'
            });
        }catch(e){
            if(null!==this.data){
                this.data=null;
                this.drawFrame();
                let text=this.lang.t('Flight Control Center');
                this.terminal.locate(Math.floor((80-Terminal.strlen(text))/2),12);
                this.terminal.print(text);
            }
            return;
        }

        try{
            let fgreport={};
            for(let item of data.data.children){
                fgreport[item.name]=item.value;
            }

            if(!this.data){
                this.data=fgreport;
                this.drawFrame();
            }
            fgreport['longitude'] = Math.abs(fgreport['longitude-deg']).toFixed(6)+(fgreport['longitude-deg']>=0 ? 'E' : 'W');
            fgreport['latitude'] = Math.abs(fgreport['latitude-deg']).toFixed(6)+(fgreport['latitude-deg']>=0 ? 'N' : 'S');
            let pad=Terminal.rpad, padSize=11;
            this.terminal.locate(0,3);
            this.terminal.print(pad(this.lang.t('Aircraft Model'),padSize)+fgreport.aircraft+'        ');
            this.terminal.locate(0,4);
            this.terminal.print(pad(this.lang.t('Longitude'),padSize)+fgreport['longitude']+'        ');
            this.terminal.locate(0,5);
            this.terminal.print(pad(this.lang.t('Latitude'),padSize)+fgreport['latitude']+'        ');
            this.terminal.locate(0,6);
            this.terminal.print(pad(this.lang.t('Flight Time'),padSize)+fgreport['flight-time-string']+'        ');
            this.terminal.locate(0,7);
            this.terminal.print(pad(this.lang.t('Remaining Time'),padSize)+fgreport['ete-string']+'        ');
            this.terminal.locate(0,8);
            this.terminal.print(pad(this.lang.t('Total Distance'),padSize)+fgreport['total-distance'].toFixed(1)+'nm        ');
            this.terminal.locate(0,9);
            this.terminal.print(pad(this.lang.t('Remaining Distance'),padSize)+fgreport['distance-remaining-nm'].toFixed(1)+'nm        ');
            this.terminal.locate(0,10);
            this.terminal.print(pad(this.lang.t('Flight Distance'),padSize)+(Number(fgreport['total-distance'])-Number(fgreport['distance-remaining-nm'])).toFixed(1)+'nm        ');

            this.terminal.locate(40,4);
            this.terminal.print(pad(this.lang.t('Direction'),padSize)+(Number(fgreport['heading-deg'])).toFixed(2)+'°        ');
            this.terminal.locate(40,5);
            this.terminal.print(pad(this.lang.t('Altitude'),padSize)+(Number(fgreport['altitude-ft'])).toFixed(1)+'ft        ');
            this.terminal.locate(40,6);
            this.terminal.print(pad(this.lang.t('AGL'),padSize)+(Number(fgreport['altitude-agl-ft'])).toFixed(1)+'ft        ');
            this.terminal.locate(40,7);
            this.terminal.print(pad(this.lang.t('Vertical Speed'),padSize)+(Number(fgreport['vertical-speed-fps'])).toFixed(1)+'ft/s        ');
            if('ufo'==fgreport['flight-model']){
                this.terminal.locate(40,8);
                this.terminal.print(pad(this.lang.t('Speed'),padSize)+(Number(fgreport['vertical-speed-fps'])).toFixed(1)+'kts        ');
            }else{
                this.terminal.locate(40,8);
                this.terminal.print(pad(this.lang.t('Airspeed'),padSize)+(Number(fgreport['airspeed-kt'])).toFixed(1)+'kts        ');
                this.terminal.locate(40,9);
                this.terminal.print(pad(this.lang.t('Groundspeed'),padSize)+(Number(fgreport['groundspeed-kt'])).toFixed(1)+'kts        ');
                this.terminal.locate(40,10);
                this.terminal.print(pad(this.lang.t('Mach'),padSize)+(Number(fgreport['mach'])).toFixed(4)+'     ');
                this.terminal.locate(40,11);
                let fuelPercentage=Number(fgreport['remain-fuel'])/Number(fgreport['initial-fuel'])*100;
                this.terminal.print(pad(this.lang.t('Fuel'),padSize)+fuelPercentage.toFixed(2)+%     ');
            }

            this.terminal.locate(0,24);
            if(fgreport['crashed']){
                this.terminal.setattr(1,5,33,41);
                this.terminal.print(this.lang.t('Crashed'));
            }else if(fgreport['paused']){
                this.terminal.setattr(33);
                this.terminal.print(this.lang.t('Paused'));
            }else{
                this.terminal.setattr(32);
                this.terminal.print(this.lang.t('In Flight'));
            }
            this.terminal.setattr(0);
            this.terminal.print(' '.repeat(20));
        }catch(e){
            console.error(e);
        }
    }
    destroy(){
        try{
            this.running=false;
        }catch(e){
            console.error(e);
        }finally{
            this._exit();
        }
    }
    async toggleSound(){
        let {data}=await axios({
            method:'GET',
            url:this.FGFS_HOST+'/json/sim/sound/enabled'
        });
        await axios({
            method:'GET',
            url:this.FGFS_HOST+`/props/sim/sound?submit=set&enabled=${data.value ? 'false' : 'true'}`
        });
    }
    async togglePause(){
        await axios({
            method:'GET',
            url:this.FGFS_HOST+'/run.cgi?value=pause'
        });
    }
    ondata(data){
        try{
            switch(data[0]){
                case 0x1b:
                    this.terminal.reset();
                    this.destroy();
                    return;
                break;
                case 0x73:
                    this.toggleSound();
                break;
                case 0x70:
                    this.togglePause();
                break;
            }
        }catch(e){
            console.error(e);
        }
    }
}<|endoftext|>


<commit_before>//
// Author: Nuno Aguiar

// VARIABLES
// ---------
var requirements = {
  "javaversion": [ "^1.7" ]
};
var extraArgsForJava9 = "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=java.management/com.sun.jmx.mbeanserver=ALL-UNNAMED --add-exports=jdk.internal.jvmstat/sun.jvmstat.monitor=ALL-UNNAMED --add-exports=java.base/sun.reflect.generics.reflectiveObjects=ALL-UNNAMED --illegal-access=permit";
var extraArgsForJava10 = " ";
var extraArgsForJava12 = "-Xshare:off";
var DEFAULT_SH = "/bin/sh";
var noopacks = false;

var javaargs = "";
for(var i in __args) {
	if (__args[i].match(/^args=/i)) javaargs = __args[i].replaceAll("^args=", "");
}
if (javaargs != "") log("Java arguments to use = '" + javaargs + "'");

for(var j in __args) {
   if (__args[j].matches("--noopacks")) noopacks = true;
}

// FUNCTIONS
// ---------
function checkRequirements() {
  var bFoundJavaVer = 0;

  for(i in requirements.javaversion) {
     if(javaVer.match(requirements.javaversion[i])) bFoundJavaVer = 1;
  }

  if(bFoundJavaVer) logErr("Current java version '" + javaVer + "' is not supported");
}

function generateWinBat() {
  var s;

  s = "@echo off\n\n";
  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% %*";
  return s;
}

function generateWinPackBat() {
  var s;

  s = "@echo off\n\n";
  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% --opack -e \"%*\"";
  return s;
}

function generateWinJobBat() {
	  var s;

	  s = "@echo off\n\n";
	  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
	  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
	  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
	  s = s + "\n";
	  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% --ojob -e \"%*\"";
	  return s;
	}

function generateWinConsoleBat() {
  var s;

  s = "@echo off\n\n";
  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% --console %*";
  return s;
}

function generateWinConsolePSBat() {
  var s;

  s = "@echo off\n\n";
  //s = s + "powershell -ExecutionPolicy Unrestricted -command \"&{ [Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding('1252'); $pshost = get-host; $console = $pshost.UI.RawUI; $console.WindowTitle = 'OpenAF-console'; $console.ForegroundColor = 'black'; $console.BackgroundColor = 'white'; $newsize = $console.windowsize; $newsize.width = 120; $newsize.height = 55; $console.windowsize = $newsize; $newsize = $console.buffersize; $newsize.width = 120; $newsize.height = 3000; $console.buffersize = $newsize; Clear-Host; $JAVA_HOME = '" + javaHome + "'; $OPENAF_DIR = '" + classPath + "'; $cmd = '&\\\"' + $JAVA_HOME + '\\bin\\java\\\" " + javaargs + " -D\\\"java.system.class.loader=openaf.OAFdCL\\\" -jar \"' + $OPENAF_DIR + '\" --console'; iex $cmd; }\"";
  s = s + "powershell -ExecutionPolicy Unrestricted -command \"&{ $pshost = get-host; $console = $pshost.UI.RawUI; $console.WindowTitle = 'OpenAF-console'; $console.ForegroundColor = 'black'; $console.BackgroundColor = 'white'; $newsize = $console.windowsize; $newsize.width = 120; $newsize.height = 55; $console.windowsize = $newsize; $newsize = $console.buffersize; $newsize.width = 120; $newsize.height = 3000; $console.buffersize = $newsize; Clear-Host; $JAVA_HOME = '" + javaHome + "'; $OPENAF_DIR = '" + classPath + "'; $cmd = '&\\\"' + $JAVA_HOME + '\\bin\\java\\\" " + javaargs + " -D\\\"java.system.class.loader=openaf.OAFdCL\\\" -jar \"' + $OPENAF_DIR + '\" --console'; iex $cmd; }\"";
  return s;
}

function generateUnixScript(options){
  var s;

  if (typeof shLocation === 'undefined') {
    if (windows == 1) {
      // for cygwin
      shLocation = DEFAULT_SH;
      javaHome = javaHome.replace(/\\/g, "/");
      javaHome = javaHome.replace(/(\w)\:/,"/cygdrive/$1").toLowerCase();
    } else {
      try {
        if (io.fileExists(DEFAULT_SH)) {
          shLocation = DEFAULT_SH;
        } else {
          shLocation = af.sh("which sh", "", null, false);
        }
      } catch (e) {
        logErr("Couldn't determine path for sh, assuming " + DEFAULT_SH + ": " + e.message);
        shLocation = DEFAULT_SH;
      }
    }

    log("sh located in "+ shLocation);
  }

  s = "#!" + shLocation + "\n\n";
  s = s + "stty -icanon min 1 -echo 2>/dev/null\n";
  s = s + "#if [ -z \"${JAVA_HOME}\" ]; then \nJAVA_HOME=\"" + javaHome + "\"\n#fi\n";
  s = s + "OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "\"$JAVA_HOME\"/bin/java " + javaargs + " -Djava.system.class.loader=openaf.OAFdCL -Djline.terminal=jline.UnixTerminal -jar $OPENAF_DIR " + options + "\n";
  s = s + "EXITCODE=$?\n";
  s = s + "stty icanon echo 2>/dev/null\n";
  s = s + "exit $EXITCODE\n";
  return s;
}

// MAIN
// ----

log("Generate scripts");

// Variables
var os        = "";
var curDir    = "";
var javaVer   = "";
var javaHome  = "";
var classPath = "";

var windows = 0;
var shLocation;

try {
  var os        = java.lang.System.getProperty("os.name") + "";
  var curDir    = java.lang.System.getProperty("user.dir") + "";
  var javaVer   = String(java.lang.System.getProperty("java.version")).replace(/^1\./, "").replace(/(\d+).*/, "$1");
  var javaHome  = java.lang.System.getProperty("java.home") + "";
  var classPath = java.lang.System.getProperty("java.class.path") + "";

  classPath = (new java.io.File(classPath)).getAbsoluteFile();
} catch (e) {
  logErr("Couldn't retrieve system properties: " + e.message);
  java.lang.System.exit(0);
}

if(os.match(/Windows/)) {
	log("Identified system as Windows = '" + os + "'");
  windows = 1;
} else {
	log("Identified system as a Unix flavour = '" + os + "'");
  windows = 0;
}

log("Current directory = '" + curDir + "'");
log("Running java version = '" + javaVer + "'");
log("Current classpath = '" + classPath + "'");
log("Java home = '" + javaHome + "'");
log("Checking requirements");

if (Number(javaVer) != null && Number(javaVer) > 8) javaargs += " " + extraArgsForJava9;
if (Number(javaVer) != null && Number(javaVer) > 9) javaargs += " " + extraArgsForJava10;
if (Number(javaVer) != null && Number(javaVer) > 11) javaargs += " " + extraArgsForJava12;

var winBat = generateWinBat();
var winPackBat = generateWinPackBat();
var winJobBat = generateWinJobBat();
var winConsoleBat = generateWinConsoleBat();
var winConsolePSBat = generateWinConsolePSBat();
var unixScript = generateUnixScript("\"$@\"");
var unixSB = generateUnixScript("-s -i script -f \"$@\"");
var unixPackScript = generateUnixScript("--opack -e \"$*\"");
var unixJobScript = generateUnixScript("--ojob -e \"$*\"");
var unixConsoleScript = generateUnixScript("--console \"$@\"");

try {
  if (windows == 1) io.writeFileString(curDir + "\\openaf.bat", winBat);
  if (windows == 1) io.writeFileString(curDir + "\\opack.bat", winPackBat);
  if (windows == 1) io.writeFileString(curDir + "\\ojob.bat", winJobBat);
  if (windows == 1) io.writeFileString(curDir + "\\openaf-console.bat", winConsoleBat);
  if (windows == 1) io.writeFileString(curDir + "\\openaf-console-ps.bat", winConsolePSBat);
  if (windows == 1) {
    io.writeFileBytes(curDir + "\\openaf.ico", io.readFileBytes(getOpenAFJar() + "::fonts/openaf.ico"));
    sh("powershell \"$sh=New-Object -COM WScript.Shell;$s=$sh.CreateShortcut('" + curDir + "\\OpenAF CONSOLE.lnk');$s.TargetPath='" + curDir + "\\openaf-console-ps.bat';$s.Description='OpenAF-console';$s.IconLocation='" + curDir + "\\openaf.ico';$s.WorkingDirectory='" + curDir + "';$s.save()\"", undefined, undefined, true);
  }
  io.writeFileString(curDir + "/openaf", unixScript);
  io.writeFileString(curDir + "/openaf-sb", unixSB);
  io.writeFileString(curDir + "/opack", unixPackScript);
  io.writeFileString(curDir + "/ojob", unixJobScript);
  io.writeFileString(curDir + "/openaf-console", unixConsoleScript);
} catch (e) {
  logErr("Couldn't write file: " + e.message);
  java.lang.System.exit(0);
}

if (windows == 0) {
  try {
	  sh("chmod u+x " + curDir + "/openaf", "", null, false);
	  sh("chmod u+x " + curDir + "/openaf-sb", "", null, false);
	  sh("chmod u+x " + curDir + "/opack", "", null, false);
	  sh("chmod u+x " + curDir + "/ojob", "", null, false);
	  sh("chmod u+x " + curDir + "/openaf-console", "", null, false);
  }	catch(e) {
	  logErr("Couldn't change permissions: " + e.message);
  }
}

log("Verify the generated scripts and change the JAVA_HOME and/or OPENAF variables accordingly");

if (!noopacks) {
  $from(io.listFiles(curDir).files).ends("filename", ".opack").select(function(r) {
     log("Trying to install " + r.filename + "...");
     oPack("install " + r.filepath);
  });
}

// Checking opack list
log("Checking oPacks...");
ow.loadObj();
loadLodash();
_.uniq(ow.obj.fromObj2Array(getOPackLocalDB(), "path").map(r => {
  return { name: r.name, path: r.path }
})).map(r => {
  if (r.name != "OpenAF" && !io.fileExists(r.path)) {
    oPack("remove4db " + r.name);
    oPack("add2db " + getOpenAFPath() + r.name);
  }
});

log("Removing old paths...");
var o = getOPackLocalDB();
var p = {};
Object.keys(o).map(r => {
  if (r != "OpenAF" && (io.fileExists(r + "/" + PACKAGEYAML) || io.fileExists(r + "/" + PACKAGEJSON))) p[r] = o[r];
});
log("Rewriting local oPacks db...");
plugin("ZIP");
var zip = new ZIP();
zip.streamPutFile(getOpenAFPath() + "/.opack.db", "packages.json", af.fromString2Bytes(stringify(p)));

// Checking if reinstall script can be built
var jh = ow.format.getJavaHome().replace(/\\/g, "/");
if (jh.substring(0, jh.lastIndexOf("/")+1) == getOpenAFPath()) {
  if (windows == 1) {
    log("Generating reinstall.bat...");
    io.writeFileString(curDir + "/reinstall.bat", "@echo off\n\n" +  jh.substring(jh.lastIndexOf("/")+1) + "\\bin\\java -jar openaf.jar --install\n");
  } else {
    log("Generating reinstall.sh...");
    io.writeFileString(curDir + "/reinstall.sh", "#!" + shLocation + "\n\n" +  jh.substring(jh.lastIndexOf("/")+1) + "/bin/java -jar openaf.jar --install\n");
    sh("chmod u+x " + curDir + "/reinstall.sh", "", null, false);
  }
}

log("Done installing scripts");

af.load(classPath + "::js/repack.js");
<commit_msg>oaf/oafc scripts<commit_after>//
// Author: Nuno Aguiar

// VARIABLES
// ---------
var requirements = {
  "javaversion": [ "^1.7" ]
};
var extraArgsForJava9 = "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=java.management/com.sun.jmx.mbeanserver=ALL-UNNAMED --add-exports=jdk.internal.jvmstat/sun.jvmstat.monitor=ALL-UNNAMED --add-exports=java.base/sun.reflect.generics.reflectiveObjects=ALL-UNNAMED --illegal-access=permit";
var extraArgsForJava10 = " ";
var extraArgsForJava12 = "-Xshare:off";
var DEFAULT_SH = "/bin/sh";
var noopacks = false;

var javaargs = "";
for(var i in __args) {
	if (__args[i].match(/^args=/i)) javaargs = __args[i].replaceAll("^args=", "");
}
if (javaargs != "") log("Java arguments to use = '" + javaargs + "'");

for(var j in __args) {
   if (__args[j].matches("--noopacks")) noopacks = true;
}

// FUNCTIONS
// ---------
function checkRequirements() {
  var bFoundJavaVer = 0;

  for(i in requirements.javaversion) {
     if(javaVer.match(requirements.javaversion[i])) bFoundJavaVer = 1;
  }

  if(bFoundJavaVer) logErr("Current java version '" + javaVer + "' is not supported");
}

function generateWinBat() {
  var s;

  s = "@echo off\n\n";
  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% %*";
  return s;
}

function generateWinPackBat() {
  var s;

  s = "@echo off\n\n";
  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% --opack -e \"%*\"";
  return s;
}

function generateWinJobBat() {
	  var s;

	  s = "@echo off\n\n";
	  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
	  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
	  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
	  s = s + "\n";
	  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% --ojob -e \"%*\"";
	  return s;
	}

function generateWinConsoleBat() {
  var s;

  s = "@echo off\n\n";
  s = s + "rem if not %JAVA_HOME% == \"\" set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set JAVA_HOME=\"" + javaHome + "\"\n";
  s = s + "set OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "%JAVA_HOME%\\bin\\java " + javaargs + " -D\"java.system.class.loader=openaf.OAFdCL\" -jar %OPENAF_DIR% --console %*";
  return s;
}

function generateWinConsolePSBat() {
  var s;

  s = "@echo off\n\n";
  //s = s + "powershell -ExecutionPolicy Unrestricted -command \"&{ [Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding('1252'); $pshost = get-host; $console = $pshost.UI.RawUI; $console.WindowTitle = 'OpenAF-console'; $console.ForegroundColor = 'black'; $console.BackgroundColor = 'white'; $newsize = $console.windowsize; $newsize.width = 120; $newsize.height = 55; $console.windowsize = $newsize; $newsize = $console.buffersize; $newsize.width = 120; $newsize.height = 3000; $console.buffersize = $newsize; Clear-Host; $JAVA_HOME = '" + javaHome + "'; $OPENAF_DIR = '" + classPath + "'; $cmd = '&\\\"' + $JAVA_HOME + '\\bin\\java\\\" " + javaargs + " -D\\\"java.system.class.loader=openaf.OAFdCL\\\" -jar \"' + $OPENAF_DIR + '\" --console'; iex $cmd; }\"";
  s = s + "powershell -ExecutionPolicy Unrestricted -command \"&{ $pshost = get-host; $console = $pshost.UI.RawUI; $console.WindowTitle = 'OpenAF-console'; $console.ForegroundColor = 'black'; $console.BackgroundColor = 'white'; $newsize = $console.windowsize; $newsize.width = 120; $newsize.height = 55; $console.windowsize = $newsize; $newsize = $console.buffersize; $newsize.width = 120; $newsize.height = 3000; $console.buffersize = $newsize; Clear-Host; $JAVA_HOME = '" + javaHome + "'; $OPENAF_DIR = '" + classPath + "'; $cmd = '&\\\"' + $JAVA_HOME + '\\bin\\java\\\" " + javaargs + " -D\\\"java.system.class.loader=openaf.OAFdCL\\\" -jar \"' + $OPENAF_DIR + '\" --console'; iex $cmd; }\"";
  return s;
}

function generateUnixScript(options){
  var s;

  if (typeof shLocation === 'undefined') {
    if (windows == 1) {
      // for cygwin
      shLocation = DEFAULT_SH;
      javaHome = javaHome.replace(/\\/g, "/");
      javaHome = javaHome.replace(/(\w)\:/,"/cygdrive/$1").toLowerCase();
    } else {
      try {
        if (io.fileExists(DEFAULT_SH)) {
          shLocation = DEFAULT_SH;
        } else {
          shLocation = af.sh("which sh", "", null, false);
        }
      } catch (e) {
        logErr("Couldn't determine path for sh, assuming " + DEFAULT_SH + ": " + e.message);
        shLocation = DEFAULT_SH;
      }
    }

    log("sh located in "+ shLocation);
  }

  s = "#!" + shLocation + "\n\n";
  s = s + "stty -icanon min 1 -echo 2>/dev/null\n";
  s = s + "#if [ -z \"${JAVA_HOME}\" ]; then \nJAVA_HOME=\"" + javaHome + "\"\n#fi\n";
  s = s + "OPENAF_DIR=\"" + classPath + "\"\n";
  s = s + "\n";
  s = s + "\"$JAVA_HOME\"/bin/java " + javaargs + " -Djava.system.class.loader=openaf.OAFdCL -Djline.terminal=jline.UnixTerminal -jar $OPENAF_DIR " + options + "\n";
  s = s + "EXITCODE=$?\n";
  s = s + "stty icanon echo 2>/dev/null\n";
  s = s + "exit $EXITCODE\n";
  return s;
}

// MAIN
// ----

log("Generate scripts");

// Variables
var os        = "";
var curDir    = "";
var javaVer   = "";
var javaHome  = "";
var classPath = "";

var windows = 0;
var shLocation;

try {
  var os        = java.lang.System.getProperty("os.name") + "";
  var curDir    = java.lang.System.getProperty("user.dir") + "";
  var javaVer   = String(java.lang.System.getProperty("java.version")).replace(/^1\./, "").replace(/(\d+).*/, "$1");
  var javaHome  = java.lang.System.getProperty("java.home") + "";
  var classPath = java.lang.System.getProperty("java.class.path") + "";

  classPath = (new java.io.File(classPath)).getAbsoluteFile();
} catch (e) {
  logErr("Couldn't retrieve system properties: " + e.message);
  java.lang.System.exit(0);
}

if(os.match(/Windows/)) {
	log("Identified system as Windows = '" + os + "'");
  windows = 1;
} else {
	log("Identified system as a Unix flavour = '" + os + "'");
  windows = 0;
}

log("Current directory = '" + curDir + "'");
log("Running java version = '" + javaVer + "'");
log("Current classpath = '" + classPath + "'");
log("Java home = '" + javaHome + "'");
log("Checking requirements");

if (Number(javaVer) != null && Number(javaVer) > 8) javaargs += " " + extraArgsForJava9;
if (Number(javaVer) != null && Number(javaVer) > 9) javaargs += " " + extraArgsForJava10;
if (Number(javaVer) != null && Number(javaVer) > 11) javaargs += " " + extraArgsForJava12;

var winBat = generateWinBat();
var winPackBat = generateWinPackBat();
var winJobBat = generateWinJobBat();
var winConsoleBat = generateWinConsoleBat();
var winConsolePSBat = generateWinConsolePSBat();
var unixScript = generateUnixScript("\"$@\"");
var unixSB = generateUnixScript("-s -i script -f \"$@\"");
var unixPackScript = generateUnixScript("--opack -e \"$*\"");
var unixJobScript = generateUnixScript("--ojob -e \"$*\"");
var unixConsoleScript = generateUnixScript("--console \"$@\"");

try {
  if (windows == 1) io.writeFileString(curDir + "\\openaf.bat", winBat);
  if (windows == 1) io.writeFileString(curDir + "\\oaf.bat", winBat);
  if (windows == 1) io.writeFileString(curDir + "\\opack.bat", winPackBat);
  if (windows == 1) io.writeFileString(curDir + "\\ojob.bat", winJobBat);
  if (windows == 1) io.writeFileString(curDir + "\\openaf-console.bat", winConsoleBat);
  if (windows == 1) io.writeFileString(curDir + "\\oafc.bat", winConsoleBat);
  if (windows == 1) io.writeFileString(curDir + "\\openaf-console-ps.bat", winConsolePSBat);
  if (windows == 1) {
    io.writeFileBytes(curDir + "\\openaf.ico", io.readFileBytes(getOpenAFJar() + "::fonts/openaf.ico"));
    sh("powershell \"$sh=New-Object -COM WScript.Shell;$s=$sh.CreateShortcut('" + curDir + "\\OpenAF CONSOLE.lnk');$s.TargetPath='" + curDir + "\\openaf-console-ps.bat';$s.Description='OpenAF-console';$s.IconLocation='" + curDir + "\\openaf.ico';$s.WorkingDirectory='" + curDir + "';$s.save()\"", undefined, undefined, true);
  }
  io.writeFileString(curDir + "/openaf", unixScript);
  io.writeFileString(curDir + "/oaf", unixScript);
  io.writeFileString(curDir + "/openaf-sb", unixSB);
  io.writeFileString(curDir + "/opack", unixPackScript);
  io.writeFileString(curDir + "/ojob", unixJobScript);
  io.writeFileString(curDir + "/openaf-console", unixConsoleScript);
  io.writeFileString(curDir + "/oafc", unixConsoleScript);
} catch (e) {
  logErr("Couldn't write file: " + e.message);
  java.lang.System.exit(0);
}

if (windows == 0) {
  try {
	  sh("chmod u+x " + curDir + "/openaf", "", null, false);
	  sh("chmod u+x " + curDir + "/oaf", "", null, false);
	  sh("chmod u+x " + curDir + "/openaf-sb", "", null, false);
	  sh("chmod u+x " + curDir + "/opack", "", null, false);
	  sh("chmod u+x " + curDir + "/ojob", "", null, false);
	  sh("chmod u+x " + curDir + "/openaf-console", "", null, false);
	  sh("chmod u+x " + curDir + "/oafc", "", null, false);
  }	catch(e) {
	  logErr("Couldn't change permissions: " + e.message);
  }
}

log("Verify the generated scripts and change the JAVA_HOME and/or OPENAF variables accordingly");

if (!noopacks) {
  $from(io.listFiles(curDir).files).ends("filename", ".opack").select(function(r) {
     log("Trying to install " + r.filename + "...");
     oPack("install " + r.filepath);
  });
}

// Checking opack list
log("Checking oPacks...");
ow.loadObj();
loadLodash();
_.uniq(ow.obj.fromObj2Array(getOPackLocalDB(), "path").map(r => {
  return { name: r.name, path: r.path }
})).map(r => {
  if (r.name != "OpenAF" && !io.fileExists(r.path)) {
    oPack("remove4db " + r.name);
    oPack("add2db " + getOpenAFPath() + r.name);
  }
});

log("Removing old paths...");
var o = getOPackLocalDB();
var p = {};
Object.keys(o).map(r => {
  if (r != "OpenAF" && (io.fileExists(r + "/" + PACKAGEYAML) || io.fileExists(r + "/" + PACKAGEJSON))) p[r] = o[r];
});
log("Rewriting local oPacks db...");
plugin("ZIP");
var zip = new ZIP();
zip.streamPutFile(getOpenAFPath() + "/.opack.db", "packages.json", af.fromString2Bytes(stringify(p)));

// Checking if reinstall script can be built
var jh = ow.format.getJavaHome().replace(/\\/g, "/");
if (jh.substring(0, jh.lastIndexOf("/")+1) == getOpenAFPath()) {
  if (windows == 1) {
    log("Generating reinstall.bat...");
    io.writeFileString(curDir + "/reinstall.bat", "@echo off\n\n" +  jh.substring(jh.lastIndexOf("/")+1) + "\\bin\\java -jar openaf.jar --install\n");
  } else {
    log("Generating reinstall.sh...");
    io.writeFileString(curDir + "/reinstall.sh", "#!" + shLocation + "\n\n" +  jh.substring(jh.lastIndexOf("/")+1) + "/bin/java -jar openaf.jar --install\n");
    sh("chmod u+x " + curDir + "/reinstall.sh", "", null, false);
  }
}

log("Done installing scripts");

af.load(classPath + "::js/repack.js");
<|endoftext|>


<commit_before>(function() {
  window.shared || (window.shared = {});
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var HelpBubble = window.shared.HelpBubble = React.createClass({
    propTypes: {
      title: React.PropTypes.string.isRequired,
      content_id: React.PropTypes.string.isRequired
    },

    getInitialState: function(){ return {modalIsOpen: false}; },
    closeModal: function(e){
      this.setState({modalIsOpen: false}); e.preventDefault();
    },
    openModal: function(e){ this.setState({modalIsOpen: true}); },
    componentWillMount: function(){
      // This needs to be called for some reason, and we need to do it by the time the DOM exists.
      ReactModal.setAppElement(document.body);
    },

    render: function(){
      return dom.div({style: {display: 'inline'}},
        dom.span({className: 'HelpBubble', onClick: this.openModal}, '?'),
        this.renderModal() // The modal is not logically here, but even while not displayed it needs a location in the DOM.
      );
    },

    renderModal: function(){
      return createEl(ReactModal, {
        isOpen: this.state.modalIsOpen,
        onRequestClose: this.closeModal
      },
        dom.div({className: 'modal-help'},
          dom.div({style: {borderBottom: '1px solid #333', paddingBottom: 10, marginBottom: 20}},
            dom.h1({style: {display: 'inline-block'}}, this.props.title),
            dom.a({href: '#', onClick: this.closeModal, style: {float: 'right', cursor: 'pointer'}}, '(ESC)')
          ),
          dom.div({
            dangerouslySetInnerHTML: {__html: $("#" + this.props.content_id).html()}
          }),
          dom.div({}, dom.a({
            href: '#', onClick: this.closeModal,
            style: {cursor: 'pointer', position: 'absolute', bottom: 20, left: 20},
          }, '(close)'))
        )
      );
    }
  });
})();
<commit_msg>Added comments.<commit_after>(function() {
  window.shared || (window.shared = {});
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var HelpBubble = window.shared.HelpBubble = React.createClass({
    //
    //
    propTypes: {
      title: React.PropTypes.string.isRequired, // e.g. 'What is a Note?'
      content_id: React.PropTypes.string.isRequired // id attribute of the hidden div we grab the content from, e.g. 'notes-help'
    },

    getInitialState: function(){ return {modalIsOpen: false}; },
    closeModal: function(e){
      this.setState({modalIsOpen: false});
      e.preventDefault();
    },
    openModal: function(e){ this.setState({modalIsOpen: true}); },
    componentWillMount: function(){
      // This needs to be called for some reason, and we need to do it by the time the DOM exists.
      ReactModal.setAppElement(document.body);
    },

    render: function(){
      return dom.div({style: {display: 'inline'}},
        dom.span({className: 'HelpBubble', onClick: this.openModal}, '?'),
        this.renderModal() // The modal is not logically here, but even while not displayed it needs a location in the DOM.
      );
    },

    renderModal: function(){
      // There are three ways to close a modal dialog: click on one of the close buttons,
      // click outside the bounds, or press Escape.
      return createEl(ReactModal, {
        isOpen: this.state.modalIsOpen,
        onRequestClose: this.closeModal
      },
      // Every help box has a title and two close buttons. The content is free-form HTML.
        dom.div({className: 'modal-help'},
          dom.div({style: {borderBottom: '1px solid #333', paddingBottom: 10, marginBottom: 20}},
            dom.h1({style: {display: 'inline-block'}}, this.props.title),
            dom.a({href: '#', onClick: this.closeModal, style: {float: 'right', cursor: 'pointer'}}, '(ESC)')
          ),
          dom.div({
            // We grab the content from a display-none div stored in <head></head> on every page.
            // React says this is 'dangerous' because rendering an untrusted string can allow an
            // XSS attack; however, we generated this string, so we trust it.
            dangerouslySetInnerHTML: {__html: $("#" + this.props.content_id).html()}
          }),
          dom.div({}, dom.a({
            href: '#', onClick: this.closeModal,
            style: {cursor: 'pointer', position: 'absolute', bottom: 20, left: 20},
          }, '(close)'))
        )
      );
    }
  });
})();
<|endoftext|>


<commit_before>// Copyright 2015, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
/* eslint-env node */
'use strict';

// modules
var assert = require( 'assert' );
var eslint = require( 'eslint' );

// constants
var CLIEngine = eslint.CLIEngine;

/**
 * Gets the relative path for the given repo.
 * @param {string} repo
 * @returns {string}
 */
var GET_PATH = function( repo ) { return '../' + repo; };

/**
 * @param grunt - the grunt instance
 * @param {string} target - 'dir'|'all'|'everything'
 * @param {Object} buildConfig
 */
module.exports = function( grunt, target, buildConfig ) {

  assert && assert( target === 'dir' || target === 'all' || target === 'everything', 'Bad lint target: ' + target );
  var repositoryName = buildConfig.name;

  // --disable-eslint-cache disables the cache, useful for developing rules
  var cache = !grunt.option( 'disable-eslint-cache' );

  var cli = new CLIEngine( {

    // Rules are specified in the .eslintrc file
    configFile: '../chipper/eslint/.eslintrc',

    // Caching only checks changed files or when the list of rules is changed.  Changing the implementation of a
    // custom rule does not invalidate the cache.  Caches are declared in .eslintcache files in the directory where
    // grunt was run from.
    cache: cache,

    // Our custom rules live here
    rulePaths: [ '../chipper/eslint/rules' ],

    // Where to store the target-specific cache file
    cacheFile: '../chipper/eslint/cache/' + repositoryName + '-' + target + '.eslintcache',

    // Files to skip for linting
    ignorePattern: [
      '**/.git',
      '**/build',
      '**/node_modules',
      '**/snapshots',
      '../sherpa/**',
      '**/js/parser/svgPath.js',
      // grunt lint-all from chipper and other repositories requires slightly different path references to things in
      // chipper. When in chipper, the '../chipper' does not function properly. Both are included here.
      'templates/sim-config.js',
      '../chipper/templates/sim-config.js',
      '../phet-io-website/root/assets/js/ua-parser-0.7.12.min.js',
      '../phet-io-website/root/assets/js/jquery-1.12.3.min.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js',
      '../phet-io-website/root/assets/js/phet-io-ga.js',
      '../installer-builder/temp/**'
    ]
  } );

  // Identify the repos to be linted
  var files = target === 'dir' ? [ repositoryName ] :
              target === 'all' ? buildConfig.phetLibs :
              grunt.file.read( '../chipper/data/active-repos' ).trim().split( /\r?\n/ );
  grunt.verbose.writeln( 'linting: ' + files );

  // Use the correct relative paths
  files = files.map( GET_PATH );

  // run the eslint step
  var report = cli.executeOnFiles( files );

  // pretty print results to console if any
  (report.warningCount || report.errorCount) && grunt.log.write( cli.getFormatter()( report.results ) );

  report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' );
  report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' );
};<commit_msg>Switching to one-line ignore for templates/sim-config.js, see https://github.com/phetsims/chipper/issues/580<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
/* eslint-env node */
'use strict';

// modules
var assert = require( 'assert' );
var eslint = require( 'eslint' );

// constants
var CLIEngine = eslint.CLIEngine;

/**
 * Gets the relative path for the given repo.
 * @param {string} repo
 * @returns {string}
 */
var GET_PATH = function( repo ) { return '../' + repo; };

/**
 * @param grunt - the grunt instance
 * @param {string} target - 'dir'|'all'|'everything'
 * @param {Object} buildConfig
 */
module.exports = function( grunt, target, buildConfig ) {

  assert && assert( target === 'dir' || target === 'all' || target === 'everything', 'Bad lint target: ' + target );
  var repositoryName = buildConfig.name;

  // --disable-eslint-cache disables the cache, useful for developing rules
  var cache = !grunt.option( 'disable-eslint-cache' );

  var cli = new CLIEngine( {

    // Rules are specified in the .eslintrc file
    configFile: '../chipper/eslint/.eslintrc',

    // Caching only checks changed files or when the list of rules is changed.  Changing the implementation of a
    // custom rule does not invalidate the cache.  Caches are declared in .eslintcache files in the directory where
    // grunt was run from.
    cache: cache,

    // Our custom rules live here
    rulePaths: [ '../chipper/eslint/rules' ],

    // Where to store the target-specific cache file
    cacheFile: '../chipper/eslint/cache/' + repositoryName + '-' + target + '.eslintcache',

    // Files to skip for linting
    ignorePattern: [
      '**/.git',
      '**/build',
      '**/node_modules',
      '**/snapshots',
      '../sherpa/**',
      '**/js/parser/svgPath.js',
      '**/templates/sim-config.js',
      '../phet-io-website/root/assets/js/ua-parser-0.7.12.min.js',
      '../phet-io-website/root/assets/js/jquery-1.12.3.min.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js',
      '../phet-io-website/root/assets/highlight.js-9.1.0/highlight.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js',
      '../phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js',
      '../phet-io-website/root/assets/js/phet-io-ga.js',
      '../installer-builder/temp/**'
    ]
  } );

  // Identify the repos to be linted
  var files = target === 'dir' ? [ repositoryName ] :
              target === 'all' ? buildConfig.phetLibs :
              grunt.file.read( '../chipper/data/active-repos' ).trim().split( /\r?\n/ );
  grunt.verbose.writeln( 'linting: ' + files );

  // Use the correct relative paths
  files = files.map( GET_PATH );

  // run the eslint step
  var report = cli.executeOnFiles( files );

  // pretty print results to console if any
  (report.warningCount || report.errorCount) && grunt.log.write( cli.getFormatter()( report.results ) );

  report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' );
  report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' );
};<|endoftext|>