<commit_before>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
var map;
$(document).ready(function() {

  // create a map in the "map" div, set the view to a given place and zoom
  map = L.map('map').setView([36.778259, -119.417931], 2);
      mapLink = 'OpenStreetMap';

    // add an OpenStreetMap tile layer
      L.tileLayer(
          'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© ' + mapLink + ' Contributors',
          }).addTo(map);

  // -------------------------------- //
    // get point coordinates from db and load on map
    var coordinatesMarker = getCoordinates();  // Function is called, return value will end up in an array
    function getCoordinates() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_points/points_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["latitude"], n["longitude"] ]];
        });
        return(arr);
    }

     //Loop through the markers array
     var marker, markerArray = [];
     for (var i=0; i<coordinatesMarker.length; i++) {
        var lat = coordinatesMarker[i][0];
        var lng = coordinatesMarker[i][1];
        var markerLocation = new L.LatLng(lat, lng);
        marker = new L.Marker(markerLocation, { draggable: true }).addTo(map).bindPopup(lat +","+ lng);
        marker = new L.Marker(markerLocation, { draggable: true }).addTo(map).bindPopup(lat +","+ lng).openPopup();
        markerArray.push(marker);
     }

        marker.on('dragend', function(event){
            var chagedPos = event.target.getLatLng();
            this.bindPopup(chagedPos.toString()).openPopup();
            // $.ajax({
            //     dataType: "POST",
            //     url: "/stash_datacite/geolocation_points/update_coordinates",
            //     data: { 'latitude' : marker.getLatLng().lat, 'longitude' : marker.getLatLng().lng),
            //            'resource_id' : $.urlParam('resource_id') },
            //     success: function() {
            //       alert('Success');
            //     },
            //     error: function() {
            //       alert('Error occured');
            //     }
            //   });

        });
  // -------------------------------- //

  // -------------------------------- //
    // get bbox coordinates from db and load on map
    var coordinatesBBox = getCoordinatesBBox();  // Function is called, return value will end up in an array
    function getCoordinatesBBox() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_boxes/boxes_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["sw_latitude"], n["sw_longitude"], n["ne_latitude"], n["ne_longitude"] ]];
        });
        return(arr);
    }

     // Loop through the bbox array
     for (var i=0; i<coordinatesBBox.length; i++) {
        var sw_lat = coordinatesBBox[i][0];
        var sw_lng = coordinatesBBox[i][1];
        var ne_lat = coordinatesBBox[i][2];
        var ne_lng = coordinatesBBox[i][3];
        var bounds = [[sw_lat, sw_lng], [ne_lat, ne_lng]];
        var newRectangle = L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map).bindPopup(sw_lat + ", " + sw_lng + ", " + ne_lat + ", " + ne_lng);
        map.fitBounds(bounds);
     }
    // -------------------------------- //

    // -------------------------------- //
      // get location names from db and load on map
      var locationNames = getLocationNames();  // Function is called, return value will end up in an array
      function getLocationNames() {
        var resource_id = "", result = [], arr = [];
          $.ajax({
            type: "GET",
            dataType: "json",
            url: "/stash_datacite/geolocation_places/places_coordinates",
            data: { resource_id: $.urlParam('resource_id') },
            async: false,
            success: function(data) {
              result = data;
            },
            error: function() {
              alert('Error occured');
            }
          });
          arr = $.map(result, function(n){
             return [[ n["geo_location_place"] ]];
          });
          return(arr);
      }

       // Loop through the location names array
        for (var i=0; i<locationNames.length; i++) {
          var place = locationNames[i][0];
          MQ.geocode().search(place).on('success', function(e) {
              var best = e.result.best,
                  latlng = best.latlng;

          var newMarker = new L.marker([latlng.lat, latlng.lng], { draggable: true }).addTo(map).bindPopup('' + best.adminArea5 + ', ' + best.adminArea3 + ', ' + best.adminArea1);
          });
        }
      // -------------------------------- //

    // Initialize the FeatureGroup to store editable layers
      var drawnItems = new L.FeatureGroup();
      map.addLayer(drawnItems);

    // Initialize the draw control and pass it the FeatureGroup of editable layers
      var drawControl = new L.Control.Draw({
          position: 'topright',
          draw: {
            polyline : false,
            polygon : false,
            circle : false,
            rect: {
              shapeOptions: {
                color: 'green',
                repeatMode: true,
              },
            },
            marker: {
              shapeOptions: {
                repeatMode: true,
              },
            },
          },
          edit: {
              featureGroup: drawnItems,
              remove: true
          }
      });
      map.addControl(drawControl);

    // listen to the draw created event
      map.on('draw:created', function (e) {
        var type = e.layerType,
            layer = e.layer;
      drawnItems.addLayer(layer);

        var resource_id = $.urlParam('resource_id');
        var rectangle_coordinates = getShapes(drawnItems);
        if (type == "rectangle") {
          //obtain bounding box from the shape coordinates (for rectangle) of map
          var geoJsonData = {
                            "type": "Feature",
                            "properties": {},
                            "geometry": {
                              "type": "Polygon",
                              "coordinates": [ rectangle_coordinates ]
                            }
                          };
          var geoJsonLayer = L.geoJson(geoJsonData);
          var bounding_box_sw_lat = geoJsonLayer.getBounds().getSouthWest().lat;
          var bounding_box_sw_lng = geoJsonLayer.getBounds().getSouthWest().lng;
          var bounding_box_ne_lat = geoJsonLayer.getBounds().getNorthEast().lat;
          var bounding_box_ne_lng = geoJsonLayer.getBounds().getNorthEast().lng;
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_boxes/map_coordinates",
            data: { 'sw_latitude' : bounding_box_sw_lat, 'sw_longitude' : bounding_box_sw_lng,
                    'ne_latitude' : bounding_box_ne_lat, 'ne_longitude' : bounding_box_ne_lng,
                    'resource_id' : resource_id }
          });
        }

        if (type == "marker") {
          //obtain latlng coordinates from the shape marker of map
          var marker_coordinates = getShapes(drawnItems).toString().split(",");
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_points/map_coordinates",
            data: { 'latitude' : marker_coordinates[0], 'longitude' : marker_coordinates[1],
                    'resource_id' : resource_id }
          });
        }
      });

    // listen to the draw edited event
      map.on('draw:edited', function (e) {
          var layers = e.layers;
          layers.eachLayer(function (layer) {
              if (layer instanceof L.Marker){
                      alert(layer.getLatLng().toString());
              }
          });
      });

      var getShapes = function(drawnItems) {
        var lng, lat;

        drawnItems.eachLayer(function(layer) {
            // Note: Rectangle extends Polygon. Polygon extends Polyline.
            // Therefore, all of them are instances of Polyline
            if (layer instanceof L.Polyline) {
              coordinates = [];
              latlngs = layer.getLatLngs();
              for (var i = 0; i < latlngs.length; i++) {
                  coordinates.push([latlngs[i].lng, latlngs[i].lat])
              }
            }

            if (layer instanceof L.Marker) {
              coordinates = [];
              coordinates.push([layer.getLatLng().lat, layer.getLatLng().lng]);
            }
        });
        return coordinates;
      };

    // listen to the draw deleted event
        // map.on('draw:deleted', function () {
        //     // Update db to save latest changes.
        // });
});

$(document).ready(function() {
  $("#geolocation_box").hide();
  $("#geo_box").on('click', function(e){
    $("#geolocation_box").show();
    $("#geolocation_point").hide();
  });
});

$(document).ready(function() {
  $("#geolocation_point").show();
  $("#geo_point").on('click', function(e){
    $("#geolocation_box").hide();
    $("#geolocation_point").show();
  });
});

$(document).ready(function(){
    $("#location_section").click(function() {
        setTimeout(function() {
            map.invalidateSize();
        }, 300);
    });
});

// $(document).ready(function(){
//   $("#geo_lat_point").on('blur', function(e){
//   var lat = parseFloat($(this).val());
//   var latReg = /^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lat == '' || lat == null) {}
//   if(!latReg.test(lat)) {
//     alert("Please enter valid latitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

// $(document).ready(function(){
//   $("#geo_lng_point").on('blur', function(e){
//   var lng = parseFloat($(this).val());
//   var lngReg = /^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lng == '' || lng == null) {}
//   if(!lngReg.test(lng)) {
//     alert("Please enter valid longitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

<commit_msg>add marker id to dragend function call<commit_after>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
var map;
$(document).ready(function() {

  // create a map in the "map" div, set the view to a given place and zoom
  map = L.map('map').setView([36.778259, -119.417931], 2);
      mapLink = 'OpenStreetMap';

    // add an OpenStreetMap tile layer
      L.tileLayer(
          'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© ' + mapLink + ' Contributors',
          }).addTo(map);

  // -------------------------------- //
    // get point coordinates from db and load on map
    var coordinatesMarker = getCoordinates();  // Function is called, return value will end up in an array
    function getCoordinates() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_points/points_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["latitude"], n["longitude"], n["id"] ]];
        });
        return(arr);
    }

     //Loop through the markers array
     var marker, markerArray = [];
     for (var i=0; i<coordinatesMarker.length; i++) {
        var lat = coordinatesMarker[i][0];
        var lng = coordinatesMarker[i][1];
        var mrk_id = coordinatesMarker[i][2];
        var markerLocation = new L.LatLng(lat, lng);
        // marker = new L.Marker(markerLocation, { draggable: true }).addTo(map).bindPopup(lat +","+ lng);
        marker = new L.Marker(markerLocation, { draggable: true, id: mrk_id }).addTo(map).bindPopup(lat +","+ lng).openPopup();
        markerArray.push(marker);
     }

        marker.on('dragend', function(event){
          alert("hi");
            // var chagedPos = event.target.getLatLng();
            // this.bindPopup(chagedPos.toString()).openPopup();
            // $.ajax({
            //     dataType: "POST",
            //     url: "/stash_datacite/geolocation_points/update_coordinates",
            //     data: { 'latitude' : marker.getLatLng().lat, 'longitude' : marker.getLatLng().lng,
            //            'resource_id' : $.urlParam('resource_id'), 'id' : marker.mrk_id },
            //     success: function() {
            //       alert('Success');
            //     },
            //     error: function() {
            //       alert('Error occured');
            //     }
            //   });

        });
  // -------------------------------- //

  // -------------------------------- //
    // get bbox coordinates from db and load on map
    var coordinatesBBox = getCoordinatesBBox();  // Function is called, return value will end up in an array
    function getCoordinatesBBox() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_boxes/boxes_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["sw_latitude"], n["sw_longitude"], n["ne_latitude"], n["ne_longitude"] ]];
        });
        return(arr);
    }

     // Loop through the bbox array
     for (var i=0; i<coordinatesBBox.length; i++) {
        var sw_lat = coordinatesBBox[i][0];
        var sw_lng = coordinatesBBox[i][1];
        var ne_lat = coordinatesBBox[i][2];
        var ne_lng = coordinatesBBox[i][3];
        var bounds = [[sw_lat, sw_lng], [ne_lat, ne_lng]];
        var newRectangle = L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map).bindPopup(sw_lat + ", " + sw_lng + ", " + ne_lat + ", " + ne_lng);
        map.fitBounds(bounds);
     }
    // -------------------------------- //

    // -------------------------------- //
      // get location names from db and load on map
      var locationNames = getLocationNames();  // Function is called, return value will end up in an array
      function getLocationNames() {
        var resource_id = "", result = [], arr = [];
          $.ajax({
            type: "GET",
            dataType: "json",
            url: "/stash_datacite/geolocation_places/places_coordinates",
            data: { resource_id: $.urlParam('resource_id') },
            async: false,
            success: function(data) {
              result = data;
            },
            error: function() {
              alert('Error occured');
            }
          });
          arr = $.map(result, function(n){
             return [[ n["geo_location_place"] ]];
          });
          return(arr);
      }

       // Loop through the location names array
        for (var i=0; i<locationNames.length; i++) {
          var place = locationNames[i][0];
          MQ.geocode().search(place).on('success', function(e) {
              var best = e.result.best,
                  latlng = best.latlng;

          var newMarker = new L.marker([latlng.lat, latlng.lng], { draggable: true }).addTo(map).bindPopup('' + best.adminArea5 + ', ' + best.adminArea3 + ', ' + best.adminArea1);
          });
        }
      // -------------------------------- //

    // Initialize the FeatureGroup to store editable layers
      var drawnItems = new L.FeatureGroup();
      map.addLayer(drawnItems);

    // Initialize the draw control and pass it the FeatureGroup of editable layers
      var drawControl = new L.Control.Draw({
          position: 'topright',
          draw: {
            polyline : false,
            polygon : false,
            circle : false,
            rect: {
              shapeOptions: {
                color: 'green',
                repeatMode: true,
              },
            },
            marker: {
              shapeOptions: {
                repeatMode: true,
              },
            },
          },
          edit: {
              featureGroup: drawnItems,
              remove: true
          }
      });
      map.addControl(drawControl);

    // listen to the draw created event
      map.on('draw:created', function (e) {
        var type = e.layerType,
            layer = e.layer;
      drawnItems.addLayer(layer);

        var resource_id = $.urlParam('resource_id');
        var rectangle_coordinates = getShapes(drawnItems);
        if (type == "rectangle") {
          //obtain bounding box from the shape coordinates (for rectangle) of map
          var geoJsonData = {
                            "type": "Feature",
                            "properties": {},
                            "geometry": {
                              "type": "Polygon",
                              "coordinates": [ rectangle_coordinates ]
                            }
                          };
          var geoJsonLayer = L.geoJson(geoJsonData);
          var bounding_box_sw_lat = geoJsonLayer.getBounds().getSouthWest().lat;
          var bounding_box_sw_lng = geoJsonLayer.getBounds().getSouthWest().lng;
          var bounding_box_ne_lat = geoJsonLayer.getBounds().getNorthEast().lat;
          var bounding_box_ne_lng = geoJsonLayer.getBounds().getNorthEast().lng;
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_boxes/map_coordinates",
            data: { 'sw_latitude' : bounding_box_sw_lat, 'sw_longitude' : bounding_box_sw_lng,
                    'ne_latitude' : bounding_box_ne_lat, 'ne_longitude' : bounding_box_ne_lng,
                    'resource_id' : resource_id }
          });
        }

        if (type == "marker") {
          //obtain latlng coordinates from the shape marker of map
          var marker_coordinates = getShapes(drawnItems).toString().split(",");
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_points/map_coordinates",
            data: { 'latitude' : marker_coordinates[0], 'longitude' : marker_coordinates[1],
                    'resource_id' : resource_id }
          });
        }
      });

    // listen to the draw edited event
      map.on('draw:edited', function (e) {
          var layers = e.layers;
          layers.eachLayer(function (layer) {
              if (layer instanceof L.Marker){
                      alert(layer.getLatLng().toString());
              }
          });
      });

      var getShapes = function(drawnItems) {
        var lng, lat;

        drawnItems.eachLayer(function(layer) {
            // Note: Rectangle extends Polygon. Polygon extends Polyline.
            // Therefore, all of them are instances of Polyline
            if (layer instanceof L.Polyline) {
              coordinates = [];
              latlngs = layer.getLatLngs();
              for (var i = 0; i < latlngs.length; i++) {
                  coordinates.push([latlngs[i].lng, latlngs[i].lat])
              }
            }

            if (layer instanceof L.Marker) {
              coordinates = [];
              coordinates.push([layer.getLatLng().lat, layer.getLatLng().lng]);
            }
        });
        return coordinates;
      };

    // listen to the draw deleted event
        // map.on('draw:deleted', function () {
        //     // Update db to save latest changes.
        // });
});

$(document).ready(function() {
  $("#geolocation_box").hide();
  $("#geo_box").on('click', function(e){
    $("#geolocation_box").show();
    $("#geolocation_point").hide();
  });
});

$(document).ready(function() {
  $("#geolocation_point").show();
  $("#geo_point").on('click', function(e){
    $("#geolocation_box").hide();
    $("#geolocation_point").show();
  });
});

$(document).ready(function(){
    $("#location_section").click(function() {
        setTimeout(function() {
            map.invalidateSize();
        }, 300);
    });
});

// $(document).ready(function(){
//   $("#geo_lat_point").on('blur', function(e){
//   var lat = parseFloat($(this).val());
//   var latReg = /^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lat == '' || lat == null) {}
//   if(!latReg.test(lat)) {
//     alert("Please enter valid latitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

// $(document).ready(function(){
//   $("#geo_lng_point").on('blur', function(e){
//   var lng = parseFloat($(this).val());
//   var lngReg = /^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lng == '' || lng == null) {}
//   if(!lngReg.test(lng)) {
//     alert("Please enter valid longitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

<|endoftext|>


<commit_before>//fis config
var a111=1;
var b22222222='#ddd';
alert(222222);
<commit_msg>'test'<commit_after>//fis config
var a111=1;
var b22222222='#ddd';
alert(333);
<|endoftext|>


<commit_before>var expect = require('chai').expect;

describe("date-parser", function () {
    var dateParser;

    beforeEach(function () {
        dateParser = require('../lib/index');
    });

    describe("test()", function () {
        it("should recognize valid date by given format", function () {
            expect(dateParser.test('yyyy.MM.dd. HH:mm:ss', '2016.01.01. 01:01:01')).to.equal(true);
        });

        it("should recognize if a date is not valid by given format", function () {
            expect(dateParser.test('yyyy.MM.dd. HH:mm:ss', '2016.1.1. 01:01:01')).to.equal(false);
        });
    });

    describe("match()", function () {
        it("should match valid date by given format", function () {
            var match = dateParser.match('yyyy.MM.dd. HH:mm:ss', '2016.01.02. 03:04:05');
            expect(match[1]).to.equal('2016');
            expect(match[2]).to.equal('01');
            expect(match[3]).to.equal('02');
            expect(match[4]).to.equal('03');
            expect(match[5]).to.equal('04');
            expect(match[6]).to.equal('05');
        });

        it("should not match if a date is not valid by given format", function () {
            expect(dateParser.match('yyyy.MM.dd. HH:mm:ss', '2016.1.1. 01:01:01')).to.equal(null);
        });
    });

});<commit_msg>Added tests to loadLocale<commit_after>var expect = require('chai').expect;

describe("date-parser", function () {
    var dateParser;

    beforeEach(function () {
        dateParser = require('../lib/index');
    });

    describe("loadLocale()", function () {
        it("should throw an error if the desired locale is not exist", function () {
            var notExistingLocale = 'THERE-IS-NO-LOCALE-LIKE-THIS';
            function test() {
                dateParser.loadLocale(notExistingLocale);
            }

            expect(test).to.throw(new RegExp(notExistingLocale, 'i'));
        });
    });

    describe("test()", function () {
        it("should recognize valid date by given format", function () {
            expect(dateParser.test('yyyy.MM.dd. HH:mm:ss', '2016.01.01. 01:01:01')).to.equal(true);
        });

        it("should recognize if a date is not valid by given format", function () {
            expect(dateParser.test('yyyy.MM.dd. HH:mm:ss', '2016.1.1. 01:01:01')).to.equal(false);
        });
    });

    describe("match()", function () {
        it("should match valid date by given format", function () {
            var match = dateParser.match('yyyy.MM.dd. HH:mm:ss', '2016.01.02. 03:04:05');
            expect(match[1]).to.equal('2016');
            expect(match[2]).to.equal('01');
            expect(match[3]).to.equal('02');
            expect(match[4]).to.equal('03');
            expect(match[5]).to.equal('04');
            expect(match[6]).to.equal('05');
        });

        it("should not match if a date is not valid by given format", function () {
            expect(dateParser.match('yyyy.MM.dd. HH:mm:ss', '2016.1.1. 01:01:01')).to.equal(null);
        });
    });

});<|endoftext|>


<commit_before>/* globals window, _, VIZI, THREE */
(function() {
	"use strict";

	VIZI.Camera = function(pos) {
		VIZI.Log("Inititialising WebGL camera");

		_.extend(this, VIZI.Mediator);

		this.cameraRadius = 4100;
		this.theta = 45; // Horizontal orbit
		this.phi = 80; // Vertical oribt

		this.target = new THREE.Object3D();
		this.updateTargetPositon(pos);

		this.camera = this.createCamera();
		this.lookAtTarget();

		this.publish("addToScene", this.camera);
		this.publish("addToDat", this, {name: "Camera", properties: ["cameraRadius", "theta", "phi"]});

		this.subscribe("resize", this.resize);
		this.subscribe("zoomControl", this.zoom);
		this.subscribe("panControl", this.pan);
	};

	VIZI.Camera.prototype.createCamera = function() {
		VIZI.Log("Creating WebGL camera");

		var camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 2, 40000 );
		this.updatePosition(camera);

		return camera;
	};

	// TODO: Why is a camera object being passed in?
	VIZI.Camera.prototype.updatePosition = function(camera) {
		camera = (camera) ? camera : this.camera;
		camera.position.x = this.target.position.x + this.cameraRadius * Math.sin( this.theta * Math.PI / 360 ) * Math.cos( this.phi * Math.PI / 360 );
		camera.position.y = this.target.position.y + this.cameraRadius * Math.sin( this.phi * Math.PI / 360 );
		camera.position.z = this.target.position.z + this.cameraRadius * Math.cos( this.theta * Math.PI / 360 ) * Math.cos( this.phi * Math.PI / 360 );
		camera.updateMatrix();
	};

	VIZI.Camera.prototype.updateTargetPositon = function(pos) {
		this.target.position.x = pos[0];
		this.target.position.z = pos[1];
	};

	VIZI.Camera.prototype.lookAtTarget = function() {
		this.camera.lookAt(this.target.position);
	};

	VIZI.Camera.prototype.resize = function() {
		this.camera.aspect = window.innerWidth / window.innerHeight;
		this.camera.updateProjectionMatrix();
	};

	VIZI.Camera.prototype.zoom = function(delta) {
		this.cameraRadius += delta;

		// Cap zoom to bounds
		this.cameraRadius = Math.max(Math.min(this.cameraRadius, 5000), 1000);

		this.updatePosition();
	};

	VIZI.Camera.prototype.pan = function(delta3d) {
		// TODO: Remove if it looks like this isn't breaking anything
		// this.camera.position.x += delta3d.x;
		// this.camera.position.z += delta3d.z;
		// this.camera.updateMatrix();

		this.target.position.x += delta3d.x;
		this.target.position.z += delta3d.z;

		this.updatePosition();

		// Forced render prevents annoying glitch when panning
		// TODO: Stop this causing twice as many frames being rendered while panning
		// - Perhaps aspects of .render() can be performed without updating the display
		// - https://github.com/mrdoob/three.js/blob/master/src/renderers/WebGLRenderer.js#L3199
		// TODO: If unavoidable, think about ways to reduce the performance impact of double-rendering
		// - Removing post-processing during pan
		// - Lowering quality / upscaling during pan
		// - Enabling lower LOD during pan
		// - Removing high-detailed objects during pan (buildings)
		// - Pausing animations during pan (AI, live data, etc)
		this.publish("render");
	};

	VIZI.Camera.prototype.datChange = function() {
		this.updatePosition();
		this.lookAtTarget();
	};
}());<commit_msg>Updated zoom logic<commit_after>/* globals window, _, VIZI, THREE */
(function() {
	"use strict";

	VIZI.Camera = function(pos) {
		VIZI.Log("Inititialising WebGL camera");

		_.extend(this, VIZI.Mediator);

		this.cameraRadius = 4100;
		this.theta = 45; // Horizontal orbit
		this.phi = 80; // Vertical oribt

		this.target = new THREE.Object3D();
		this.updateTargetPositon(pos);

		this.camera = this.createCamera();
		this.lookAtTarget();

		this.publish("addToScene", this.camera);
		this.publish("addToDat", this, {name: "Camera", properties: ["cameraRadius", "theta", "phi"]});

		this.subscribe("resize", this.resize);
		this.subscribe("zoomControl", this.zoom);
		this.subscribe("panControl", this.pan);
	};

	VIZI.Camera.prototype.createCamera = function() {
		VIZI.Log("Creating WebGL camera");

		var camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 2, 40000 );
		this.updatePosition(camera);

		return camera;
	};

	// TODO: Why is a camera object being passed in?
	VIZI.Camera.prototype.updatePosition = function(camera) {
		camera = (camera) ? camera : this.camera;
		camera.position.x = this.target.position.x + this.cameraRadius * Math.sin( this.theta * Math.PI / 360 ) * Math.cos( this.phi * Math.PI / 360 );
		camera.position.y = this.target.position.y + this.cameraRadius * Math.sin( this.phi * Math.PI / 360 );
		camera.position.z = this.target.position.z + this.cameraRadius * Math.cos( this.theta * Math.PI / 360 ) * Math.cos( this.phi * Math.PI / 360 );
		camera.updateMatrix();
	};

	VIZI.Camera.prototype.updateTargetPositon = function(pos) {
		this.target.position.x = pos[0];
		this.target.position.z = pos[1];
	};

	VIZI.Camera.prototype.lookAtTarget = function() {
		this.camera.lookAt(this.target.position);
	};

	VIZI.Camera.prototype.resize = function() {
		this.camera.aspect = window.innerWidth / window.innerHeight;
		this.camera.updateProjectionMatrix();
	};

	VIZI.Camera.prototype.zoom = function(delta) {
		var oldcameraRadius = this.cameraRadius;

		this.cameraRadius += delta;

		var cameraRadiusDiff = this.cameraRadius - oldcameraRadius;

		// Cap zoom to bounds
		if (this.cameraRadius < 1000) {
			this.cameraRadius = 1000;
			cameraRadiusDiff = 1000 - oldcameraRadius;
		}

		if (this.cameraRadius > 5000) {
			this.cameraRadius = 5000;
			cameraRadiusDiff = 5000 - oldcameraRadius;
		}

		this.camera.translateZ( cameraRadiusDiff );

		this.updatePosition();

		this.publish("render");
	};

	VIZI.Camera.prototype.pan = function(delta3d) {
		// TODO: Remove if it looks like this isn't breaking anything
		// this.camera.position.x += delta3d.x;
		// this.camera.position.z += delta3d.z;
		// this.camera.updateMatrix();

		this.target.position.x += delta3d.x;
		this.target.position.z += delta3d.z;

		this.updatePosition();

		// Forced render prevents annoying glitch when panning
		// TODO: Stop this causing twice as many frames being rendered while panning
		// - Perhaps aspects of .render() can be performed without updating the display
		// - https://github.com/mrdoob/three.js/blob/master/src/renderers/WebGLRenderer.js#L3199
		// TODO: If unavoidable, think about ways to reduce the performance impact of double-rendering
		// - Removing post-processing during pan
		// - Lowering quality / upscaling during pan
		// - Enabling lower LOD during pan
		// - Removing high-detailed objects during pan (buildings)
		// - Pausing animations during pan (AI, live data, etc)
		this.publish("render");
	};

	VIZI.Camera.prototype.datChange = function() {
		this.updatePosition();
		this.lookAtTarget();
	};
}());<|endoftext|>


<commit_before>canonicalizeHtml = function(html) {
  var h = html;
  // kill IE-specific comments inserted by DomRange
  h = h.replace(/<!--IE-->/g, '');
  // ignore exact text of comments
  h = h.replace(/<!--.*?-->/g, '<!---->');
  // make all tags lowercase
  h = h.replace(/<\/?(\w+)/g, function(m) {
    return m.toLowerCase(); });
  // kill \n and \r characters
  h = h.replace(/[\n\r]/g, '');
  // make tag attributes uniform
  h = h.replace(/<(\w+)\s+(.*?)\s*>/g, function(m, tagName, attrs) {
    // Drop expando property used by Sizzle (part of jQuery) which leaks into
    // attributes in IE8. Note that its value always contains spaces.
    attrs = attrs.replace(/sizcache[0-9]+="[^"]*"/g, ' ');
    // Similarly for expando properties used by jQuery to track data.
    attrs = attrs.replace(/jQuery[0-9]+="[0-9]+"/g, ' ');
    attrs = attrs.replace(/\s*=\s*/g, '=');
    attrs = attrs.replace(/^\s+/g, '');
    attrs = attrs.replace(/\s+$/g, '');
    attrs = attrs.replace(/\s+/g, ' ');
    // for the purpose of splitting attributes in a string like
    // 'a="b" c="d"', assume they are separated by a single space
    // and values are double-quoted, but allow for spaces inside
    // the quotes.  Split on space following quote.
    var attrList = attrs.replace(/" /g, '"\u0000').split('\u0000');
    // put attributes in alphabetical order
    attrList.sort();

    var tagContents = [tagName];

    for(var i=0; i<attrList.length; i++) {
      // If there were no attrs, attrList could be `[""]`,
      // so skip falsy values.
      if (! attrList[i])
        continue;
      var a = attrList[i].split('=');
        if (a.length < 2)
          a.push(a[0]); // things like checked=checked, in theory
      var key = a[0];
      // Drop another expando property used by Sizzle.
      if (key === 'sizset')
        continue;
      var value = a[1];
      value = value.replace(/["'`]/g, '"');
      if (value.charAt(0) !== '"')
        value = '"'+value+'"';
      tagContents.push(key+'='+value);
    }
    return '<'+tagContents.join(' ')+'>';
  });
  return h;
};
<commit_msg>canonicalizeHtml: fix unquoted attribute values<commit_after>canonicalizeHtml = function(html) {
  var h = html;
  // kill IE-specific comments inserted by DomRange
  h = h.replace(/<!--IE-->/g, '');
  // ignore exact text of comments
  h = h.replace(/<!--.*?-->/g, '<!---->');
  // make all tags lowercase
  h = h.replace(/<\/?(\w+)/g, function(m) {
    return m.toLowerCase(); });
  // kill \n and \r characters
  h = h.replace(/[\n\r]/g, '');
  // make tag attributes uniform
  h = h.replace(/<(\w+)\s+(.*?)\s*>/g, function(m, tagName, attrs) {
    // Drop expando property used by Sizzle (part of jQuery) which leaks into
    // attributes in IE8. Note that its value always contains spaces.
    attrs = attrs.replace(/sizcache[0-9]+="[^"]*"/g, ' ');
    // Similarly for expando properties used by jQuery to track data.
    attrs = attrs.replace(/jQuery[0-9]+="[0-9]+"/g, ' ');
    attrs = attrs.replace(/\s*=\s*/g, '=');
    attrs = attrs.replace(/^\s+/g, '');
    attrs = attrs.replace(/\s+$/g, '');
    attrs = attrs.replace(/\s+/g, ' ');
    // quote unquoted attribute values, as in `type=checkbox`.  This
    // will do the wrong thing if there's an `=` in an attribute value.
    attrs = attrs.replace(/(\w)=([^" >/]+)/g, '$1="$2"');
    // for the purpose of splitting attributes in a string like
    // 'a="b" c="d"', assume they are separated by a single space
    // and values are double-quoted, but allow for spaces inside
    // the quotes.  Split on space following quote.
    var attrList = attrs.replace(/" /g, '"\u0000').split('\u0000');
    // put attributes in alphabetical order
    attrList.sort();

    var tagContents = [tagName];

    for(var i=0; i<attrList.length; i++) {
      // If there were no attrs, attrList could be `[""]`,
      // so skip falsy values.
      if (! attrList[i])
        continue;
      var a = attrList[i].split('=');
        if (a.length < 2)
          a.push(a[0]); // things like checked=checked, in theory
      var key = a[0];
      // Drop another expando property used by Sizzle.
      if (key === 'sizset')
        continue;
      var value = a[1];
      value = value.replace(/["'`]/g, '"');
      // this check is probably made unreachable by a regex above
      // that quotes unquoted attribute values
      if (value.charAt(0) !== '"')
        value = '"'+value+'"';
      tagContents.push(key+'='+value);
    }
    return '<'+tagContents.join(' ')+'>';
  });
  return h;
};
<|endoftext|>


<commit_before>var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var WebSocketServer = require('ws').Server
var http = require('http');

var playerID = 0;

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
	response.writeHead(200, {'Content-Type': 'text/plain'});
	  response.write("Welcome to the simple Unity game server");
	  response.end("Thanks for visiting us! \n");
});

server.listen( port, ipaddress, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wss = new WebSocketServer({
    server: server,
    autoAcceptConnections: true
});

wss.on('connection', function(client) {
  playerID++;
  var clientName = "player"+playerID;
  console.log("New connection: " + clientName);
  client.send("New connection: " + clientName);

  client.on('message', function(data) {
    client.send(data);
    var message = clientName + '> ' + data.toString();
    broadcast(client, message);
  });

});

wss.broadcast = function broadcast(sender, data) {
  wss.clients.forEach(function each(client) {
//    if ( sender == client )
//      return;
    client.send(data);
  });
};

console.log("Listening to " + ipaddress + ":" + port + "...");
<commit_msg>revert<commit_after>var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var WebSocketServer = require('ws').Server
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
	response.writeHead(200, {'Content-Type': 'text/plain'});
	  response.write("Welcome to Node.js on OpenShift!\n\n");
	  response.end("Thanks for visiting us! \n");
});

server.listen( port, ipaddress, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wss = new WebSocketServer({
    server: server,
    autoAcceptConnections: false
});
wss.on('connection', function(ws) {
  console.log("New connection");
  ws.on('message', function(message) {
    ws.send("Received: " + message);
  });
  ws.send('Welcome!');
});

console.log("Listening to " + ipaddress + ":" + port + "...");
<|endoftext|>


<commit_before>define([], function() {

    'use strict';

	return ['$scope', 'Rest', '$q', 'departmentReload', 'renewalChart', 'gettext', '$http',
            function($scope, Rest, $q, departmentReload, renewalChart, gettext, $http) {

        var collaboratorsResource;
        var calendareventsResource = Rest.user.calendarevents.getResource();

        $scope.setPageTitle($scope.company.name+' - '+gettext('Home'));

        if ($scope.sessionUser.isAccount) {

            var beneficiariesResource = Rest.account.beneficiaries.getResource();
            collaboratorsResource = Rest.account.collaborators.getResource();

            renewalChart($scope, beneficiariesResource);
        }

        if ($scope.sessionUser.isManager) {
            // load waiting requests

            var waitingRequestResource = Rest.manager.waitingrequests.getResource();
            collaboratorsResource = Rest.manager.collaborators.getResource();

            $scope.waitingrequests = waitingRequestResource.query();
        }

        var startDate = new Date();

        $scope.department = $scope.sessionUser.department;

        $scope.departmentReload = departmentReload(startDate, collaboratorsResource, calendareventsResource);
        $scope.departmentReload($scope.department, 0);

        $scope.createFirstAdmin = false;
        if (!$scope.isAuthenticated) {
            $http.get('/rest/anonymous/createfirstadmin').then(function(response) {
                $scope.createFirstAdmin = response.data.allowed;
            });
        }

	}];
});
<commit_msg>fix createfirstadmin query<commit_after>define([], function() {

    'use strict';

	return ['$scope', 'Rest', '$q', 'departmentReload', 'renewalChart', 'gettext', '$http',
            function($scope, Rest, $q, departmentReload, renewalChart, gettext, $http) {

        var collaboratorsResource;
        var calendareventsResource = Rest.user.calendarevents.getResource();

        $scope.setPageTitle($scope.company.name+' - '+gettext('Home'));

        if ($scope.sessionUser.isAccount) {

            var beneficiariesResource = Rest.account.beneficiaries.getResource();
            collaboratorsResource = Rest.account.collaborators.getResource();

            renewalChart($scope, beneficiariesResource);
        }

        if ($scope.sessionUser.isManager) {
            // load waiting requests

            var waitingRequestResource = Rest.manager.waitingrequests.getResource();
            collaboratorsResource = Rest.manager.collaborators.getResource();

            $scope.waitingrequests = waitingRequestResource.query();
        }

        var startDate = new Date();

        $scope.department = $scope.sessionUser.department;

        $scope.departmentReload = departmentReload(startDate, collaboratorsResource, calendareventsResource);
        $scope.departmentReload($scope.department, 0);

        $scope.createFirstAdmin = false;

        if ($scope.sessionUser && !$scope.sessionUser.isAuthenticated) {
            $http.get('/rest/anonymous/createfirstadmin').then(function(response) {
                $scope.createFirstAdmin = response.data.allowed;
            });
        }

	}];
});
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const Hierarchy = require('@antv/hierarchy');
const G6 = require('../../../src');

const div = document.createElement('div');
div.id = 'tree-spec';
document.body.appendChild(div);

describe('tree graph without animate', () => {
  const graph = new G6.TreeGraph({
    container: div,
    width: 500,
    height: 500,
    pixelRatio: 2,
    animate: false,
    modes: {
      default: [ 'drag-canvas' ]
    },
    layout: data => {
      return Hierarchy.dendrogram(data, {
        direction: 'LR', // H / V / LR / RL / TB / BT
        nodeSep: 50,
        rankSep: 100
      });
    }
  });
  it('layout init', () => {
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode2'
        }
      ]
    };
    graph.data(data);
    graph.render();
    graph.fitView();
    expect(Object.keys(graph.get('itemMap')).length).to.equal(9);
    const edge = graph.findById('Root:SubTreeNode1');
    expect(edge).not.to.be.undefined;
    expect(edge.get('source')).to.equal(graph.findById('Root'));
    expect(edge.get('target')).to.equal(graph.findById('SubTreeNode1'));
    expect(graph.save()).to.equal(data);
  });
  it('changeData', () => {
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode3'
        }, {
          id: 'SubTreeNode4',
          children: [{ id: 'SubTreeNode4.1' }]
        }
      ]
    };
    graph.changeData(data);
    expect(graph.save()).to.equal(data);
    expect(Object.keys(graph.get('itemMap')).length).to.equal(13);
    expect(graph.findById('SubTreeNode2')).to.be.undefined;
    expect(graph.findById('SubTreeNode3')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode4')).not.to.be.undefined;
    const edge = graph.findById('SubTreeNode4:SubTreeNode4.1');
    expect(edge).not.to.be.undefined;
    expect(edge.get('source')).to.equal(graph.findById('SubTreeNode4'));
    expect(edge.get('target')).to.equal(graph.findById('SubTreeNode4.1'));
  });
  it('add child', () => {
    const parent = graph.findById('SubTreeNode3');
    const child = { id: 'SubTreeNode3.1', x: 100, y: 100, shape: 'rect', children: [{ x: 150, y: 150, id: 'SubTreeNode3.1.1' }] };
    graph.addChild(child, parent);
    const children = parent.get('model').children;
    expect(children).not.to.be.undefined;
    expect(children.length).to.equal(1);
    expect(children[0].id).to.equal('SubTreeNode3.1');
    expect(graph.findById('SubTreeNode3.1')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode3:SubTreeNode3.1')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode3.1.1')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode3.1:SubTreeNode3.1.1')).not.to.be.undefined;
  });
  it('remove child', () => {
    graph.removeChild('SubTreeNode3.1');
    const parent = graph.findById('SubTreeNode3');
    const children = parent.get('model').children;
    expect(children.length).to.equal(0);
    expect(graph.findById('SubTreeNode3.1')).to.be.undefined;
    expect(graph.findById('SubTreeNode3:SubTreeNode3.1')).to.be.undefined;
    expect(graph.findById('SubTreeNode3.1.1')).to.be.undefined;
    expect(graph.findById('SubTreeNode3.1:SubTreeNode3.1.1')).to.be.undefined;
  });
  it('collapse & expand with layout', done => {
    const parent = graph.findById('SubTreeNode1');
    let child = graph.findById('SubTreeNode1.1');
    let collapsed = true;
    graph.on('afterrefreshlayout', () => {
      if (collapsed) {
        expect(parent.getModel().collapsed).to.be.true;
        expect(child.destroyed).to.be.true;
      } else {
        child = graph.findById('SubTreeNode1.1');
        expect(parent.getModel().collapsed).to.be.false;
        expect(child.get('model').x).not.to.equal(parent.get('model').x);
        expect(!!child.getModel().collapsed).to.be.false;
        expect(child.get('model').y).not.to.equal(parent.get('model').y);
        done();
      }
    });
    graph.addBehaviors('collapse-expand', 'default');
    graph.emit('node:click', { item: parent });
    setTimeout(() => {
      collapsed = false;
      graph.emit('node:click', { item: parent });
    }, 600);
  });
});
describe('tree graph with animate', () => {
  const graph = new G6.TreeGraph({
    container: div,
    width: 500,
    height: 500,
    pixelRatio: 2,
    modes: {
      default: [ 'drag-canvas' ]
    },
    layout: {
      type: 'dendrogram',
      direction: 'LR',
      nodeSep: 50,
      rankSep: 100
    }
  });
  it('layout init', done => {
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode2'
        }
      ]
    };
    graph.data(data);
    graph.render();
    graph.fitView();
    const layoutMethod = graph.get('layoutMethod');
    expect(layoutMethod).not.to.be.undefined;
    expect(typeof layoutMethod).to.equal('function');
    expect(Object.keys(graph.get('itemMap')).length).to.equal(9);
    const edge = graph.findById('Root:SubTreeNode1');
    expect(edge).not.to.be.undefined;
    expect(edge.get('source')).to.equal(graph.findById('Root'));
    expect(edge.get('target')).to.equal(graph.findById('SubTreeNode1'));
    expect(graph.save()).to.equal(data);
    expect(JSON.stringify(data)).not.to.throw;
    graph.on('afteranimate', () => { done(); });
  });
  it('changeData', done => {
    graph.removeEvent();
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode3'
        }, {
          id: 'SubTreeNode4',
          children: [{ id: 'SubTreeNode4.1' }]
        }
      ]
    };
    graph.changeData(data);
    expect(graph.save()).to.equal(data);
    graph.on('afteranimate', () => {
      expect(Object.keys(graph.get('itemMap')).length).to.equal(13);
      expect(graph.findById('SubTreeNode2')).to.be.undefined;
      expect(graph.findById('SubTreeNode3')).not.to.be.undefined;
      expect(graph.findById('SubTreeNode4')).not.to.be.undefined;
      const edge = graph.findById('SubTreeNode4:SubTreeNode4.1');
      expect(edge).not.to.be.undefined;
      expect(edge.get('source')).to.equal(graph.findById('SubTreeNode4'));
      expect(edge.get('target')).to.equal(graph.findById('SubTreeNode4.1'));
      done();
    });
  });
  it('collapse & expand', done => {
    graph.removeEvent();
    const parent = graph.findById('SubTreeNode1');
    let child = graph.findById('SubTreeNode1.1');
    let collapsed = true;
    graph.on('afteranimate', () => {
      if (collapsed) {
        expect(parent.getModel().collapsed).to.be.true;
        expect(child.destroyed).to.be.true;
      } else {
        child = graph.findById('SubTreeNode1.1');
        expect(parent.getModel().collapsed).to.be.false;
        expect(child.get('model').x).not.to.equal(parent.get('model').x);
        expect(!!child.getModel().collapsed).to.be.false;
        expect(child.get('model').y).not.to.equal(parent.get('model').y);
        done();
      }
    });
    graph.addBehaviors('collapse-expand', 'default');
    graph.emit('node:click', { item: parent });
    setTimeout(() => {
      collapsed = false;
      graph.emit('node:click', { item: parent });
    }, 600);
  });
});
<commit_msg>Add test case.<commit_after>const expect = require('chai').expect;
const Hierarchy = require('@antv/hierarchy');
const G6 = require('../../../src');

const div = document.createElement('div');
div.id = 'tree-spec';
document.body.appendChild(div);

describe('tree graph without animate', () => {
  const graph = new G6.TreeGraph({
    container: div,
    width: 500,
    height: 500,
    pixelRatio: 2,
    animate: false,
    modes: {
      default: [ 'drag-canvas' ]
    },
    layout: data => {
      return Hierarchy.dendrogram(data, {
        direction: 'LR', // H / V / LR / RL / TB / BT
        nodeSep: 50,
        rankSep: 100
      });
    }
  });
  it('layout init', () => {
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode2'
        }
      ]
    };
    graph.data(data);
    graph.render();
    graph.fitView();
    expect(Object.keys(graph.get('itemMap')).length).to.equal(9);
    const edge = graph.findById('Root:SubTreeNode1');
    expect(edge).not.to.be.undefined;
    expect(edge.get('source')).to.equal(graph.findById('Root'));
    expect(edge.get('target')).to.equal(graph.findById('SubTreeNode1'));
    expect(graph.save()).to.equal(data);
  });
  it('changeData', () => {
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode3'
        }, {
          id: 'SubTreeNode4',
          children: [{ id: 'SubTreeNode4.1' }]
        }
      ]
    };
    graph.changeData(data);
    expect(graph.save()).to.equal(data);
    expect(Object.keys(graph.get('itemMap')).length).to.equal(13);
    expect(graph.findById('SubTreeNode2')).to.be.undefined;
    expect(graph.findById('SubTreeNode3')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode4')).not.to.be.undefined;
    const edge = graph.findById('SubTreeNode4:SubTreeNode4.1');
    expect(edge).not.to.be.undefined;
    expect(edge.get('source')).to.equal(graph.findById('SubTreeNode4'));
    expect(edge.get('target')).to.equal(graph.findById('SubTreeNode4.1'));
  });
  it('add child', () => {
    const parent = graph.findById('SubTreeNode3');
    const child = { id: 'SubTreeNode3.1', x: 100, y: 100, shape: 'rect', children: [{ x: 150, y: 150, id: 'SubTreeNode3.1.1' }] };
    graph.addChild(child, parent);
    const children = parent.get('model').children;
    expect(children).not.to.be.undefined;
    expect(children.length).to.equal(1);
    expect(children[0].id).to.equal('SubTreeNode3.1');
    expect(graph.findById('SubTreeNode3.1')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode3:SubTreeNode3.1')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode3.1.1')).not.to.be.undefined;
    expect(graph.findById('SubTreeNode3.1:SubTreeNode3.1.1')).not.to.be.undefined;
  });
  it('remove child', () => {
    graph.removeChild('SubTreeNode3.1');
    const parent = graph.findById('SubTreeNode3');
    const children = parent.get('model').children;
    expect(children.length).to.equal(0);
    expect(graph.findById('SubTreeNode3.1')).to.be.undefined;
    expect(graph.findById('SubTreeNode3:SubTreeNode3.1')).to.be.undefined;
    expect(graph.findById('SubTreeNode3.1.1')).to.be.undefined;
    expect(graph.findById('SubTreeNode3.1:SubTreeNode3.1.1')).to.be.undefined;
  });
  it('collapse & expand with layout', done => {
    const parent = graph.findById('SubTreeNode1');
    let child = graph.findById('SubTreeNode1.1');
    let collapsed = true;
    graph.on('afterrefreshlayout', () => {
      if (collapsed) {
        expect(parent.getModel().collapsed).to.be.true;
        expect(child.destroyed).to.be.true;
      } else {
        child = graph.findById('SubTreeNode1.1');
        expect(parent.getModel().collapsed).to.be.false;
        expect(child.get('model').x).not.to.equal(parent.get('model').x);
        expect(!!child.getModel().collapsed).to.be.false;
        expect(child.get('model').y).not.to.equal(parent.get('model').y);
        done();
      }
    });
    graph.addBehaviors('collapse-expand', 'default');
    graph.emit('node:click', { item: parent });
    setTimeout(() => {
      collapsed = false;
      graph.emit('node:click', { item: parent });
    }, 600);
  });
  it('collapse & expand with layout with parameter trigger=dblclick', done => {
    graph.removeEvent();
    const parent = graph.findById('SubTreeNode1');
    let child = graph.findById('SubTreeNode1.1');
    let collapsed = true;
    graph.addBehaviors([{
      type: 'collapse-expand',
      trigger: 'dblclick'
    }], 'default');
    graph.on('afterrefreshlayout', () => {
      if (collapsed) {
        expect(parent.getModel().collapsed).to.be.true;
        expect(child.destroyed).to.be.true;
      } else {
        child = graph.findById('SubTreeNode1.1');
        expect(parent.getModel().collapsed).to.be.false;
        expect(child.get('model').x).not.to.equal(parent.get('model').x);
        expect(!!child.getModel().collapsed).to.be.false;
        expect(child.get('model').y).not.to.equal(parent.get('model').y);
        done();
      }
    });
    graph.emit('node:dblclick', { item: parent });
    setTimeout(() => {
      collapsed = false;
      graph.emit('node:dblclick', { item: parent });
    }, 600);
  });
});
describe('tree graph with animate', () => {
  const graph = new G6.TreeGraph({
    container: div,
    width: 500,
    height: 500,
    pixelRatio: 2,
    modes: {
      default: [ 'drag-canvas' ]
    },
    layout: {
      type: 'dendrogram',
      direction: 'LR',
      nodeSep: 50,
      rankSep: 100
    }
  });
  it('layout init', done => {
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode2'
        }
      ]
    };
    graph.data(data);
    graph.render();
    graph.fitView();
    const layoutMethod = graph.get('layoutMethod');
    expect(layoutMethod).not.to.be.undefined;
    expect(typeof layoutMethod).to.equal('function');
    expect(Object.keys(graph.get('itemMap')).length).to.equal(9);
    const edge = graph.findById('Root:SubTreeNode1');
    expect(edge).not.to.be.undefined;
    expect(edge.get('source')).to.equal(graph.findById('Root'));
    expect(edge.get('target')).to.equal(graph.findById('SubTreeNode1'));
    expect(graph.save()).to.equal(data);
    expect(JSON.stringify(data)).not.to.throw;
    graph.on('afteranimate', () => { done(); });
  });
  it('changeData', done => {
    graph.removeEvent();
    const data = {
      isRoot: true,
      id: 'Root',
      children: [
        {
          id: 'SubTreeNode1',
          children: [
            {
              id: 'SubTreeNode1.1'
            },
            {
              id: 'SubTreeNode1.2'
            }
          ]
        },
        {
          id: 'SubTreeNode3'
        }, {
          id: 'SubTreeNode4',
          children: [{ id: 'SubTreeNode4.1' }]
        }
      ]
    };
    graph.changeData(data);
    expect(graph.save()).to.equal(data);
    graph.on('afteranimate', () => {
      expect(Object.keys(graph.get('itemMap')).length).to.equal(13);
      expect(graph.findById('SubTreeNode2')).to.be.undefined;
      expect(graph.findById('SubTreeNode3')).not.to.be.undefined;
      expect(graph.findById('SubTreeNode4')).not.to.be.undefined;
      const edge = graph.findById('SubTreeNode4:SubTreeNode4.1');
      expect(edge).not.to.be.undefined;
      expect(edge.get('source')).to.equal(graph.findById('SubTreeNode4'));
      expect(edge.get('target')).to.equal(graph.findById('SubTreeNode4.1'));
      done();
    });
  });
  it('collapse & expand', done => {
    graph.removeEvent();
    const parent = graph.findById('SubTreeNode1');
    let child = graph.findById('SubTreeNode1.1');
    let collapsed = true;
    graph.on('afteranimate', () => {
      if (collapsed) {
        expect(parent.getModel().collapsed).to.be.true;
        expect(child.destroyed).to.be.true;
      } else {
        child = graph.findById('SubTreeNode1.1');
        expect(parent.getModel().collapsed).to.be.false;
        expect(child.get('model').x).not.to.equal(parent.get('model').x);
        expect(!!child.getModel().collapsed).to.be.false;
        expect(child.get('model').y).not.to.equal(parent.get('model').y);
        done();
      }
    });
    graph.addBehaviors('collapse-expand', 'default');
    graph.emit('node:click', { item: parent });
    setTimeout(() => {
      collapsed = false;
      graph.emit('node:click', { item: parent });
    }, 600);
  });
  it('collapse & expand with parameter trigger=dblclick', done => {
    graph.removeEvent();
    const parent = graph.findById('SubTreeNode1');
    let child = graph.findById('SubTreeNode1.1');
    let collapsed = true;
    graph.on('afteranimate', () => {
      if (collapsed) {
        expect(parent.getModel().collapsed).to.be.true;
        expect(child.destroyed).to.be.true;
      } else {
        child = graph.findById('SubTreeNode1.1');
        expect(parent.getModel().collapsed).to.be.false;
        expect(child.get('model').x).not.to.equal(parent.get('model').x);
        expect(!!child.getModel().collapsed).to.be.false;
        expect(child.get('model').y).not.to.equal(parent.get('model').y);
        done();
      }
    });
    graph.addBehaviors([{
      type: 'collapse-expand',
      trigger: 'dblclick'
    }], 'default');
    graph.emit('node:dblclick', { item: parent });
    setTimeout(() => {
      collapsed = false;
      graph.emit('node:dblclick', { item: parent });
    }, 600);
  });
});
<|endoftext|>


<commit_before>var React = require('react');
var Bootstrap = require('react-bootstrap');
var Router = require('react-router');
var parse = require('url-parse');

var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var Link = Router.Link;

var Alert = Bootstrap.Alert;
var Label = Bootstrap.Label;

var TeeTime = React.createClass({
  render: function() {
    //console.log("check",this.props.reservedBy,this.props.players)
    return (

      {this.props.time}
      {this.props.reserved}
      {this.props.players[0]}
      {this.props.players[1]}
      {this.props.players[2]}
      {this.props.players[3]}

    );
  }
});

var TeeTimes = React.createClass({

  render: function() {

    var teeTimeNodes = this.props.teeTimes.map(function(teeTime){
      return (
        <TeeTime time={teeTime.time} reserved={teeTime.reservedBy} players={teeTime.players}>
        {teeTime.players}
        </TeeTime>
      );
    });
    return (

      {teeTimeNodes}

    );
  }
});

var Course = React.createClass({

  render: function() {
    return (

      <Alert bstyle="warning">
      {this.props.name}
      </Alert>

    );
  }
});

var CourseList = React.createClass({
  handleClick: function() {
    console.log("link clicked");
  },

  render: function(){
    var courseNodes = this.props.data.map(function(course){
      return (
        <Link to="course" params={{ id: course._id }} >
        <Course name={course.name} address={course.address}>
        {course.description}
        </Course>
        </Link>
      );

    });
    return (

      {courseNodes}

    );
  }
});

//Not used
// <CourseForm onCourseSubmit={this.handleCourseSubmit} />

var CourseForm = React.createClass({
  handleSubmit: function(e){
    e.preventDefault();

    //Create refs for all input data
    var name = this.refs.name.getDOMNode().value.trim();
    var address = this.refs.address.getDOMNode().value.trim();
    var description = this.refs.description.getDOMNode().value.trim();

    //If no data exists, return
    if (!name ||  !address || !description) {
      return;
    }

    //on submit, we send a json object
    this.props.onCourseSubmit({name: name, address: address, description: description});

    //Set all dom nodes to an empty string
    this.refs.name.getDOMNode().value = '';
    this.refs.address.getDOMNode().value = '';
    this.refs.description.getDOMNode().value = '';

  },

  render: function(){
    return(
      <form className="courseForm" onSubmit={this.handleSubmit}>
      <input type="text" placeholder="Course name" ref="name"/>
      <input type="text" placeholder="Location (City, ST)" ref="address"/>
      <input type="text" placeholder="Description" ref="description"/>
      <input type="submit" value="Create new course" />
      </form>

    );
  }
});

//api/course/
//
//

var CourseBox = React.createClass({

  getInitialState: function(){
    return {data: [], teeTimes: []}
  },

  loadCoursesFromServer: function() {
    $.ajax({
      url: "/api/course",
      dataType: 'json',
      success: function(data){
        //console.log("successful course load from server", data)

        this.setState({data: data});
      }.bind(this), //why bind this?
      //Must be a react thing to set the context of the callback
      error: function(xhr, status, err){
        console.error("localhost:1337/api/course", status, err.toString());
      }.bind(this)
    });
  },

  loadTeeTimesFromServer: function() {
    //console.log("loading Tee Times", document.URL, parse(document.URL).hash);
    //console.log("path",  parse(document.URL).hash.slice(1) );

    var newQuery = parse(document.URL).hash.slice(1);

    $.ajax({
      url: newQuery,
      dataType: 'json',
      success: function(data){
        //console.log("load tee times from server", data);
        //console.log("check the teetimes property", data.teetimes);

        this.setState({teeTimes: data.teetimes});
      }.bind(this), //why bind this?
      //Must be a react thing to set the context of the callback
      error: function(xhr, status, err){
        console.error("localhost:1337/api/schedule/54f4b9efe331e4ca1e261e39/03012015", status, err.toString());
      }.bind(this)
    });
  },

  handleClick: function(){
    this.loadTeeTimesFromServer();
  },

  handleCourseSubmit: function(course){
    //before the ajax request
    //lets just render the course
    var courses = this.state.data;
    var newCourse = courses.concat([course]);
    this.setState({data: newCourse});

    $.ajax({
      url: '/api/course/',
      dataType: 'json',
      type: 'POST',
      data: JSON.stringify(course),
      headers: { 'Content-Type': 'application/json' },
      success: function(data){
        this.setState({data: data})
      }.bind(this),
      error: function(xhr, status, err){
        console.error("localhost:8080/api/course/", status, err.toString())
      }.bind(this)
    });
  },

  //TODO:
  //write a handle route function?
  //Get the course data
  //Somehow bind the course ids to the data
  //So that the course ID can be used to make an api request
  //To get tee times.

  componentWillMount: function(){
    console.log("will mount", this);
  },

  componentDidMount: function(){
    this.loadCoursesFromServer();
    this.loadTeeTimesFromServer();

    //console.log("did mount", this.state)

    //setInterval(this.loadCoursesFromServer, 20000)
    setInterval(this.loadTeeTimesFromServer, 1000)
  },

  render: function(){

    //console.log("render!!! ", this.state.teeTimes)

    return(

      <CourseList data={this.state.data}/>
      <TeeTimes teeTimes={this.state.teeTimes}/>

    );
  }
});

var routes = (
  <Route handler={CourseBox}>
    <Route name="course" path="/api/schedule/:id/03012015" handler={CourseBox} />
  </Route>
)

Router.run(routes, function(Handler){
  React.render(<Handler/>, document.getElementById('content'))
})

// React.render(
//   <CourseBox url="api/course/" pollInterval={20000} />,
//   document.getElementById('content')
// );
<commit_msg>Adds comments to react frontend<commit_after>//Import npm modules because we're using browserify to build the app
var React = require('react');
var Bootstrap = require('react-bootstrap');
var Router = require('react-router');
var parse = require('url-parse');

//Create aliases for react-router module components
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var Link = Router.Link;

//Create aliases for react-bootstrap module components
var Alert = Bootstrap.Alert;
var Label = Bootstrap.Label;

//TeeTime is the lowest level child of the detail view
//Renders each tee time, main phone number reserved, and confirmed friends

var TeeTime = React.createClass({

  render: function() {
    return (

        {this.props.time}
          //Uses react-bootstrap for styling
          {this.props.reserved}
          {this.props.players[0]}
          {this.props.players[1]}
          {this.props.players[2]}
          {this.props.players[3]}

    );
  }

});

//TeeTimes is the parent class to TeeTime
//Renders a tee time class for every teeTime on the server
var TeeTimes = React.createClass({

  render: function() {
    var teeTimeNodes = this.props.teeTimes.map(function(teeTime){
      return (
        <TeeTime time={teeTime.time} reserved={teeTime.reservedBy} players={teeTime.players}>
          {teeTime.players}
        </TeeTime>
      );
    });
    return (

        {teeTimeNodes}

    );
  }

});

//Course is the lowest level child of the master
//Renders each course on the left side of the page
var Course = React.createClass({

  render: function() {
    return (

        <Alert bstyle="warning">
          {this.props.name}
        </Alert>

    );
  }

});

//CourseList is the parent class to Course
//Renders a course for every course on the server
//Each course is rendered as a Link, from the react-router
var CourseList = React.createClass({

  render: function(){
    var courseNodes = this.props.data.map(function(course){
      return (
        <Link to="course" params={{ id: course._id }} >
          <Course name={course.name} address={course.address}>
            {course.description}
          </Course>
        </Link>
      );

    });
    return (

        {courseNodes}

    );
  }

});

//Course form is a react input field for updating the server
//This was for prototype purposes, and scope changed
//Not used, but available for future
var CourseForm = React.createClass({
  handleSubmit: function(e){
    e.preventDefault();

    //Create refs for all input data
    var name = this.refs.name.getDOMNode().value.trim();
    var address = this.refs.address.getDOMNode().value.trim();
    var description = this.refs.description.getDOMNode().value.trim();

    //If no data exists, return
    if (!name ||  !address || !description) {
      return;
    }

    //on submit, we send a json object
    this.props.onCourseSubmit({name: name, address: address, description: description});

    //Set all dom nodes to an empty string
    this.refs.name.getDOMNode().value = '';
    this.refs.address.getDOMNode().value = '';
    this.refs.description.getDOMNode().value = '';

  },

  render: function(){
    return(
      <form className="courseForm" onSubmit={this.handleSubmit}>
      <input type="text" placeholder="Course name" ref="name"/>
      <input type="text" placeholder="Location (City, ST)" ref="address"/>
      <input type="text" placeholder="Description" ref="description"/>
      <input type="submit" value="Create new course" />
      </form>

    );
  }
});

//CourseBox is the parent class for all submodules
//

var CourseBox = React.createClass({

  getInitialState: function(){
    return {data: [], teeTimes: []}
  },

  //HTTP requests to the api for courses
  loadCoursesFromServer: function() {
    $.ajax({
      url: "/api/course",
      dataType: 'json',
      success: function(data){
        this.setState({data: data});
      }.bind(this), //why bind this?
      //Must be a react thing to set the context of the callback
      error: function(xhr, status, err){
        console.error("localhost:1337/api/course", status, err.toString());
      }.bind(this)
    });
  },

  //HTTP requests to the api for courses
  loadTeeTimesFromServer: function() {
    var newQuery = parse(document.URL).hash.slice(1);

    $.ajax({
      url: newQuery,
      dataType: 'json',
      success: function(data){
        this.setState({teeTimes: data.teetimes});
      }.bind(this), //why bind this?
      //Must be a react thing to set the context of the callback
      error: function(xhr, status, err){
        console.error("localhost:1337/api/schedule/54f4b9efe331e4ca1e261e39/03012015", status, err.toString());
      }.bind(this)
    });
  },

  //Not used. Handles new course submission
  handleCourseSubmit: function(course){
    var courses = this.state.data;
    var newCourse = courses.concat([course]);
    this.setState({data: newCourse});

    $.ajax({
      url: '/api/course/',
      dataType: 'json',
      type: 'POST',
      data: JSON.stringify(course),
      headers: { 'Content-Type': 'application/json' },
      success: function(data){
        this.setState({data: data})
      }.bind(this),
      error: function(xhr, status, err){
        console.error("localhost:8080/api/course/", status, err.toString())
      }.bind(this)
    });
  },

  //Initial HTTP requests on load
  componentDidMount: function(){
    this.loadCoursesFromServer();
    this.loadTeeTimesFromServer();
    //Sets up server polling for teeTimes
    setInterval(this.loadTeeTimesFromServer, 1000)
  },

  //Renders CourseList and TeeTimes
  render: function(){
    return(

      <CourseList data={this.state.data}/>
      <TeeTimes teeTimes={this.state.teeTimes}/>

    );
  }
});

//Sets path for course links to match course ID for HTTP calls
var routes = (
  <Route handler={CourseBox}>
    <Route name="course" path="/api/schedule/:id/03012015" handler={CourseBox} />
  </Route>
)

//Runs the router
Router.run(routes, function(Handler){
  React.render(<Handler/>, document.getElementById('content'))
});
<|endoftext|>


<commit_before>import Service, { inject as service } from '@ember/service';
import { computed, get, set } from '@ember/object';
import StatefulPromise from 'shared/utils/stateful-promise';

const CONFIG_MAP_FILE_KEY = 'config.json'
const CONFIG_MAP_NAMESPACE_ID = 'security-scan';
const CONFIG_MAP_NAME = 'security-scan-cfg';
const CONFIG_MAP_ID = `${ CONFIG_MAP_NAMESPACE_ID }:${ CONFIG_MAP_NAME }`;

export default Service.extend({
  scope:        service(),
  growl:        service(),
  intl:         service(),
  projectStore: service('store'),

  FILE_KEY: CONFIG_MAP_FILE_KEY,

  report: null,

  setReport(report) {
    set(this, 'report', report);
  },

  asyncConfigMap: computed(function() {
    return StatefulPromise.wrap(get(this, 'scope.currentCluster.systemProject').followLink('configMaps'));
  }),

  configMaps: computed('asyncConfigMap.value', function() {
    return get(this, 'asyncConfigMap.value');
  }),

  defaultValue: computed('report.version', function() {
    return { skip: { [get(this, 'report.version')]: [] } };
  }),

  defaultData: computed('defaultValue', function() {
    return { [CONFIG_MAP_FILE_KEY]: JSON.stringify(get(this, 'defaultValue')) };
  }),

  securityScanConfig: computed('configMaps.@each', function() {
    return get(this, 'configMaps').findBy('id', 'security-scan:security-scan-cfg');
  }),

  parsedSecurityScanConfig: computed('securityScanConfig.data.@each', function() {
    try {
      return JSON.parse(get(this, 'securityScanConfig.data')[CONFIG_MAP_FILE_KEY]);
    } catch (error) {
      return get(this, 'defaultValue');
    }
  }).volatile(),

  validateSecurityScanConfig() {
    try {
      const data = get(this, `securityScanConfig.data`);

      if (!data) {
        return;
      }

      const configFile = data[CONFIG_MAP_FILE_KEY];

      if (!configFile) {
        return;
      }

      const parsed = JSON.parse(configFile);
      const version = get(this, 'report.version');

      if (!version) {
        return;
      }

      if (!Array.isArray(parsed.skip[version])) {
        throw new Error("Security Scan Config didin't contain the 'skip' array.");
      }
    } catch (error) {
      this.growl.fromError(this.intl.t('cis.scan.detail.error.parseConfig'), error.message);
      throw error;
    }
  },

  skipList: computed('securityScanConfig.data.@each', function() {
    const securityScanConfig = get(this, 'securityScanConfig');

    if (!securityScanConfig) {
      return [];
    }

    const version = get(this, 'report.version');
    const skip = get(this, `parsedSecurityScanConfig.skip`)[version];

    return Array.isArray(skip) ? skip : [];
  }),

  async editSecurityScanConfig(newValue) {
    const securityScanConfig = await Promise.resolve(get(this, 'securityScanConfig') || this.createAndSaveDefaultConfigMap());

    set(securityScanConfig, 'data', newValue);
    securityScanConfig.save();
  },

  async createAndSaveDefaultConfigMap() {
    try {
      const configMaps = get(this, 'configMaps');
      const systemProjectLink = get(this, 'scope.currentCluster.systemProject.links.self');
      const creationUrl =  `${ systemProjectLink }/configmap`;
      const recordLink =  `${ systemProjectLink }/configMaps/${ CONFIG_MAP_ID }`;
      const configRecord = get(this, 'projectStore').createRecord({
        type:        'configMap',
        id:          CONFIG_MAP_ID,
        namespaceId: CONFIG_MAP_NAMESPACE_ID,
        name:        CONFIG_MAP_NAME,
        data:        get(this, 'defaultData'),
        links:       {}
      });

      configMaps.pushObject(configRecord);
      await configRecord.save({
        url:    creationUrl,
        method: 'POST'
      });

      // We have to set this link after .save instead of before because .save will attempt to
      // use the self link to save the record and saving the record isn't setting the self link.
      set(configRecord, 'links.self', recordLink);

      return configRecord;
    } catch (error) {
      this.growl.fromError(this.intl.t('cis.scan.detail.error.createDefault'), error.message);
    }
  },

  editSkipList(newValue) {
    const version = get(this, 'report.version');
    const newSkipListObject = { skip: { [version]: newValue } };
    const newConfig = { [get(this, 'FILE_KEY')]: JSON.stringify(newSkipListObject) };

    this.editSecurityScanConfig(newConfig);
  }
});
<commit_msg>Give the skipList a default value if malformed<commit_after>import Service, { inject as service } from '@ember/service';
import { computed, get, set } from '@ember/object';
import StatefulPromise from 'shared/utils/stateful-promise';

const CONFIG_MAP_FILE_KEY = 'config.json'
const CONFIG_MAP_NAMESPACE_ID = 'security-scan';
const CONFIG_MAP_NAME = 'security-scan-cfg';
const CONFIG_MAP_ID = `${ CONFIG_MAP_NAMESPACE_ID }:${ CONFIG_MAP_NAME }`;

export default Service.extend({
  scope:        service(),
  growl:        service(),
  intl:         service(),
  projectStore: service('store'),

  FILE_KEY: CONFIG_MAP_FILE_KEY,

  report: null,

  setReport(report) {
    set(this, 'report', report);
  },

  asyncConfigMap: computed(function() {
    return StatefulPromise.wrap(get(this, 'scope.currentCluster.systemProject').followLink('configMaps'));
  }),

  configMaps: computed('asyncConfigMap.value', function() {
    return get(this, 'asyncConfigMap.value');
  }),

  defaultValue: computed('report.version', function() {
    return { skip: { [get(this, 'report.version')]: [] } };
  }),

  defaultData: computed('defaultValue', function() {
    return { [CONFIG_MAP_FILE_KEY]: JSON.stringify(get(this, 'defaultValue')) };
  }),

  securityScanConfig: computed('configMaps.@each', function() {
    return get(this, 'configMaps').findBy('id', 'security-scan:security-scan-cfg');
  }),

  parsedSecurityScanConfig: computed('securityScanConfig.data.@each', function() {
    try {
      return JSON.parse(get(this, 'securityScanConfig.data')[CONFIG_MAP_FILE_KEY]);
    } catch (error) {
      return get(this, 'defaultValue');
    }
  }).volatile(),

  validateSecurityScanConfig() {
    try {
      const data = get(this, `securityScanConfig.data`);

      if (!data) {
        return;
      }

      const configFile = data[CONFIG_MAP_FILE_KEY];

      if (!configFile) {
        return;
      }

      const parsed = JSON.parse(configFile);
      const version = get(this, 'report.version');

      if (!version) {
        return;
      }

      if (!Array.isArray(parsed.skip[version])) {
        throw new Error("Security Scan Config didin't contain the 'skip' array.");
      }
    } catch (error) {
      this.growl.fromError(this.intl.t('cis.scan.detail.error.parseConfig'), error.message);
      throw error;
    }
  },

  skipList: computed('securityScanConfig.data.@each', function() {
    const defaultValue = [];

    try {
      const securityScanConfig = get(this, 'securityScanConfig');

      if (!securityScanConfig) {
        return [];
      }

      const version = get(this, 'report.version');
      const skip = get(this, `parsedSecurityScanConfig.skip`)[version];

      return Array.isArray(skip) ? skip : defaultValue;
    } catch {
      return defaultValue;
    }
  }),

  async editSecurityScanConfig(newValue) {
    const securityScanConfig = await Promise.resolve(get(this, 'securityScanConfig') || this.createAndSaveDefaultConfigMap());

    set(securityScanConfig, 'data', newValue);
    securityScanConfig.save();
  },

  async createAndSaveDefaultConfigMap() {
    try {
      const configMaps = get(this, 'configMaps');
      const systemProjectLink = get(this, 'scope.currentCluster.systemProject.links.self');
      const creationUrl =  `${ systemProjectLink }/configmap`;
      const recordLink =  `${ systemProjectLink }/configMaps/${ CONFIG_MAP_ID }`;
      const configRecord = get(this, 'projectStore').createRecord({
        type:        'configMap',
        id:          CONFIG_MAP_ID,
        namespaceId: CONFIG_MAP_NAMESPACE_ID,
        name:        CONFIG_MAP_NAME,
        data:        get(this, 'defaultData'),
        links:       {}
      });

      configMaps.pushObject(configRecord);
      await configRecord.save({
        url:    creationUrl,
        method: 'POST'
      });

      // We have to set this link after .save instead of before because .save will attempt to
      // use the self link to save the record and saving the record isn't setting the self link.
      set(configRecord, 'links.self', recordLink);

      return configRecord;
    } catch (error) {
      this.growl.fromError(this.intl.t('cis.scan.detail.error.createDefault'), error.message);
    }
  },

  editSkipList(newValue) {
    const version = get(this, 'report.version');
    const newSkipListObject = { skip: { [version]: newValue } };
    const newConfig = { [get(this, 'FILE_KEY')]: JSON.stringify(newSkipListObject) };

    this.editSecurityScanConfig(newConfig);
  }
});
<|endoftext|>


<commit_before>define(['jquery', 'underscore'], function ($, _) {
    'use strict';
    function createPrototypeTodoComponent(jsonOverHttp) {
        var dom, sendAddItemRequest, counter, addButton, list, appendItemToView, respondToItemAdded, respondToRefreshItems;
        dom = $("

");
        addButton = dom.append('<button class="add">Add list item</button>');
        list = dom.append('

');
        counter = 1;
        sendAddItemRequest = function () {
            var item = {name: 'item', number: counter};
            counter++;
            jsonOverHttp({uri: 'item', method: 'POST', body: item}).then(respondToItemAdded);
        };
        appendItemToView = function (item) {
            var text = '
' + item.name + ' ' + item.number + '
';
            list.append($(text));
        };
        respondToItemAdded = function (response) {
            appendItemToView(response.body);
        };
        respondToRefreshItems = function (response) {
            _.each(response.body, appendItemToView);
        };
        addButton.on('click', sendAddItemRequest);
        jsonOverHttp({uri: 'item', method: 'GET'}).then(respondToRefreshItems);
        return dom;
    }

    return createPrototypeTodoComponent;
});
/*
 Noteworthy features
 * no hoisting, it is obvious when everything is defined
 * no anonymous functions, you can tell what each does by its name
 * multiple vars in same scope not initialized when declared, so can set breakpoint on each assignment
 * single vars in same scope initialized when declared
 * collaborator is constructor injected, so easy to fake
 * each async call names its destination, so it is easy to follow the code flow
 * no knowledge of parent element, or its location in dom, or even if it is attached to the dom
 * avoided the need to use 'this' or 'bind'
 */
<commit_msg>updated comment<commit_after>define(['jquery', 'underscore'], function ($, _) {
    'use strict';
    function createPrototypeTodoComponent(jsonOverHttp) {
        var dom, sendAddItemRequest, counter, addButton, list, appendItemToView, respondToItemAdded, respondToRefreshItems;
        dom = $("

");
        addButton = dom.append('<button class="add">Add list item</button>');
        list = dom.append('

');
        counter = 1;
        sendAddItemRequest = function () {
            var item = {name: 'item', number: counter};
            counter++;
            jsonOverHttp({uri: 'item', method: 'POST', body: item}).then(respondToItemAdded);
        };
        appendItemToView = function (item) {
            var text = '
' + item.name + ' ' + item.number + '
';
            list.append($(text));
        };
        respondToItemAdded = function (response) {
            appendItemToView(response.body);
        };
        respondToRefreshItems = function (response) {
            _.each(response.body, appendItemToView);
        };
        addButton.on('click', sendAddItemRequest);
        jsonOverHttp({uri: 'item', method: 'GET'}).then(respondToRefreshItems);
        return dom;
    }

    return createPrototypeTodoComponent;
});
/*
 Noteworthy features
 * no hoisting, it is obvious when everything is defined
 * no anonymous functions, you can tell what each does by its name
 * multiple vars in same scope not initialized when declared, so can set breakpoint on each assignment
 * single vars in same scope initialized when declared
 * collaborator is constructor injected, so easy to fake
 * each async call names its destination, so it is easy to follow the code flow
 * no knowledge of parent element, or its location in dom, or even if it is attached to the dom
 * avoided the need to use 'this' or 'bind' or 'new'
 */
<|endoftext|>