<commit_before>var mainModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $timeout, $http){
		$scope.currentProject = null;
		$scope.currentThread = null;
		$scope.show = "login";
		$scope.newProjectName = "";
		$scope.newThreadSubject = "";
		$scope.newThreadMessage = "";
		$scope.newPost = "";

		function newID(){
			return ((new Date).getTime() + "").substr(3) + Math.floor(100000 * Math.random());
		}

		$scope.openThreads = function(project){
			$scope.show = "threads";
			$scope.currentProject = project;
		}

		$scope.openPosts = function(thread){
			$scope.show = "posts";
			$scope.currentThread = thread;
		}

		$scope.createProject = function(){
			var tempID = newID();

			$scope.projects.push({id: tempID, name: $scope.newProjectName, threads: []});

			var stringifiedPost = JSON.stringify({id: tempID, name: $scope.newProjectName});
			$http({method: "POST", url: serverURL + "projects", data: stringifiedPost});

			$scope.newProjectName = "";
			$scope.show="projects";
		}

		$scope.createThread = function(){
			var threadID = newID();
			var postID = newID();

			$scope.currentProject.threads.push({
				id: $scope.currentProject.threads.length,
				subject: $scope.newThreadSubject,
				posts: [{id: threadID, userID: $scope.currentUser.id, message: $scope.newThreadMessage}]
			});

			var stringifiedThread = JSON.stringify({id: $scope.projects.length, projectID: $scope.currentProject.id, subject: $scope.newThreadSubject});
			$http({method: "POST", url: serverURL + "threads", data: stringifiedThread})

			var stringifiedPost = JSON.stringify({id: postID, userID: $scope.currentUser.id, threadID: threadID, projectID: $scope.currentProject.id, message: $scope.newThreadMessage});
			$http({method: "POST", url: serverURL + "posts", data: stringifiedPost});

			$scope.newThreadSubject = "";
			$scope.newThreadMessage = "";
			$scope.show="threads";
		}

		$scope.sendPost = function(){
			var postID = newID();

			$scope.currentThread.posts.push({
				id: postID,
				userID: $scope.currentUser.id,
				projectID: $scope.currentProject.id,
				message: $scope.newPost
			});

			var stringifiedPost = JSON.stringify({id: postID, userID: $scope.currentUser.id, threadID: $scope.currentThread.id, projectID: $scope.currentProject.id, message: $scope.newThreadMessage});
			$http({method: "POST", url: serverURL + "posts", data: stringifiedPost});

			$scope.newPost= "";
		}

		$scope.users = [];

		$scope.getItemFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return array[i];
				}
			}
			return false;
		}

		$scope.getIndexFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return i;
				}
			}
			return false;
		}

		$scope.projects = [];

		$scope.getAllPosts = functions(){
			var additionalPosts = [];
			$http({method: "GET", url: serverURL + "posts"})
				.success(function(data, status){
					additionalPosts = data;
					console.log("Additional posts: " + additionalPosts);

				for(var i = 0; i < additionalPosts.length; i++){
					var relevantProject = $scope.getItemFromID($scope.projects, additionalPosts[i].projectID);
					var relevantThreadIndex = $scope.getIndexFromID(relevantProject[$scope.getIndexFromID(relevantProject.threads, additionalPosts[i].threadID)]);
					relevantProject.threads[relevantThreadIndex].posts.push(additionalPosts[i]);
				}
			})
			.error(function(data, status){
				additionalPosts = data || "Request failed";
				console.log(additionalPosts);
			});
		}

		$scope.getAllThreads = function(){
			var additionalThreads = [];

			$http({method: "GET", url: serverURL + "threads"})
			.success(function(data, status){
				additionalThreads = data;
				console.log("Additional threads: " + additionalThreads)
				for(var i = 0; i < additionalThreads.length; i++){
					var relevantProject = $scope.getItemFromID($scope.projects, additionalThreads[i].projectID)
					.threads.push(additionalThreads[i]);
				}
				$scope.getAllPosts();
			}).error(function(data, status){
				console.log("Threads Fail");
			});
		}

		$scope.getAllData = function(){
			var additionalProjects = [];

			$http({method: "GET", url: serverURL + "projects"})
			.success(function(data, status){
				additionalProjects = data;
				console.log("Additional projects: " + additionalProjects)
				for(var i = 0; i < additionalProjects.length; i++){
					$scope.projects.push(additionalProjects[i]);
				}
				$scope.getAllThreads();
			}).error(function(data, status){
				console.log("Threads Fail");
			});
		}

		$scope.getAllData();

		$scope.currentUser = null;
		$scope.loggedIn = false;
		$scope.loginFailed = false;

		$scope.loginName = "";
		$scope.loginPass = "";

		$scope.login = function(){
			if($scope.loginName == "" || $scope.loginPass==""){ $scope.loginFailed = true; return; }

			var stringifiedPost = JSON.stringify({userName: $scope.loginName, password: $scope.loginPass});
			$http({method: "POST", url: serverURL + "login", data: stringifiedPost}).success(function(data, status){
				if(data){
					//todo: change this later to be assigned on login.
					$scope.currentUser = $scope.getItemFromID($scope.users, data.id);
					$scope.loginFailed = false;
					$scope.loggedIn = true;
					$scope.show = 'projects';
				}
				else{
					$scope.loginFailed = true;
				}

				console.log(data);
			});
		}

		$scope.logout = function(){
			$scope.currentUser = null;
			$scope.loggedIn = false;
			$scope.show = 'login';
		}

	}).directive('selectOnClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                this.select();
            });
        }
    };
});
<commit_msg>Update forum.js<commit_after>var mainModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $timeout, $http){
		$scope.currentProject = null;
		$scope.currentThread = null;
		$scope.show = "login";
		$scope.newProjectName = "";
		$scope.newThreadSubject = "";
		$scope.newThreadMessage = "";
		$scope.newPost = "";

		function newID(){
			return ((new Date).getTime() + "").substr(3) + Math.floor(100000 * Math.random());
		}

		$scope.openThreads = function(project){
			$scope.show = "threads";
			$scope.currentProject = project;
		}

		$scope.openPosts = function(thread){
			$scope.show = "posts";
			$scope.currentThread = thread;
		}

		$scope.createProject = function(){
			var tempID = newID();

			$scope.projects.push({id: tempID, name: $scope.newProjectName, threads: []});

			var stringifiedPost = JSON.stringify({id: tempID, name: $scope.newProjectName});
			$http({method: "POST", url: serverURL + "projects", data: stringifiedPost});

			$scope.newProjectName = "";
			$scope.show="projects";
		}

		$scope.createThread = function(){
			var threadID = newID();
			var postID = newID();

			$scope.currentProject.threads.push({
				id: $scope.currentProject.threads.length,
				subject: $scope.newThreadSubject,
				posts: [{id: threadID, userID: $scope.currentUser.id, message: $scope.newThreadMessage}]
			});

			var stringifiedThread = JSON.stringify({id: $scope.projects.length, projectID: $scope.currentProject.id, subject: $scope.newThreadSubject});
			$http({method: "POST", url: serverURL + "threads", data: stringifiedThread})

			var stringifiedPost = JSON.stringify({id: postID, userID: $scope.currentUser.id, threadID: threadID, projectID: $scope.currentProject.id, message: $scope.newThreadMessage});
			$http({method: "POST", url: serverURL + "posts", data: stringifiedPost});

			$scope.newThreadSubject = "";
			$scope.newThreadMessage = "";
			$scope.show="threads";
		}

		$scope.sendPost = function(){
			var postID = newID();

			$scope.currentThread.posts.push({
				id: postID,
				userID: $scope.currentUser.id,
				projectID: $scope.currentProject.id,
				message: $scope.newPost
			});

			var stringifiedPost = JSON.stringify({id: postID, userID: $scope.currentUser.id, threadID: $scope.currentThread.id, projectID: $scope.currentProject.id, message: $scope.newThreadMessage});
			$http({method: "POST", url: serverURL + "posts", data: stringifiedPost});

			$scope.newPost= "";
		}

		$scope.users = [];

		$scope.getItemFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return array[i];
				}
			}
			return false;
		};

		$scope.getIndexFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return i;
				}
			}
			return false;
		};

		$scope.projects = [];

		$scope.getAllPosts = function(){
			var additionalPosts = [];
			$http({method: "GET", url: serverURL + "posts"})
				.success(function(data, status){
					additionalPosts = data;
					console.log("Additional posts: " + additionalPosts);

				for(var i = 0; i < additionalPosts.length; i++){
					var relevantProject = $scope.getItemFromID($scope.projects, additionalPosts[i].projectID);
					var relevantThreadIndex = $scope.getIndexFromID(relevantProject[$scope.getIndexFromID(relevantProject.threads, additionalPosts[i].threadID)]);
					relevantProject.threads[relevantThreadIndex].posts.push(additionalPosts[i]);
				}
			})
			.error(function(data, status){
				additionalPosts = data || "Request failed";
				console.log(additionalPosts);
			});
		}

		$scope.getAllThreads = function(){
			var additionalThreads = [];

			$http({method: "GET", url: serverURL + "threads"})
			.success(function(data, status){
				additionalThreads = data;
				console.log("Additional threads: " + additionalThreads)
				for(var i = 0; i < additionalThreads.length; i++){
					var relevantProject = $scope.getItemFromID($scope.projects, additionalThreads[i].projectID)
					.threads.push(additionalThreads[i]);
				}
				$scope.getAllPosts();
			}).error(function(data, status){
				console.log("Threads Fail");
			});
		}

		$scope.getAllData = function(){
			var additionalProjects = [];

			$http({method: "GET", url: serverURL + "projects"})
			.success(function(data, status){
				additionalProjects = data;
				console.log("Additional projects: " + additionalProjects)
				for(var i = 0; i < additionalProjects.length; i++){
					$scope.projects.push(additionalProjects[i]);
				}
				$scope.getAllThreads();
			}).error(function(data, status){
				console.log("Threads Fail");
			});
		}

		$scope.getAllData();

		$scope.currentUser = null;
		$scope.loggedIn = false;
		$scope.loginFailed = false;

		$scope.loginName = "";
		$scope.loginPass = "";

		$scope.login = function(){
			if($scope.loginName == "" || $scope.loginPass==""){ $scope.loginFailed = true; return; }

			var stringifiedPost = JSON.stringify({userName: $scope.loginName, password: $scope.loginPass});
			$http({method: "POST", url: serverURL + "login", data: stringifiedPost}).success(function(data, status){
				if(data){
					//todo: change this later to be assigned on login.
					$scope.currentUser = $scope.getItemFromID($scope.users, data.id);
					$scope.loginFailed = false;
					$scope.loggedIn = true;
					$scope.show = 'projects';
				}
				else{
					$scope.loginFailed = true;
				}

				console.log(data);
			});
		}

		$scope.logout = function(){
			$scope.currentUser = null;
			$scope.loggedIn = false;
			$scope.show = 'login';
		}

	}).directive('selectOnClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                this.select();
            });
        }
    };
});
<|endoftext|>


<commit_before>var Vizu = Vizu || {};

Vizu.Graph = function (containerId, options) {
  this.container = document.getElementById(containerId);
  this.options = options;
}

Vizu.Graph.prototype = (function () {

  var nodes, edges;

  var getGroup = function (node, options) {
    // return default group when no configuration was defined
    return options.network.groups[node[options.data.properties.nodes.group]] ? node[options.data.properties.nodes.group] : 'default';
  };

  var setData = function(data) {
    // setting template in body
    document.body.innerHTML = "";
    var t = document.querySelector('#bodyContent');
    var clone = document.importNode(t.content, true);
    document.body.appendChild(clone);

    nodes = new vis.DataSet(); edges = new vis.DataSet();

    for (var i = 0; i < data.nodes.length; i++) {
      var n = data.nodes[i],
        group = getGroup(n, this.options),
        node;
      if (0 === n.dist) {
        this.rootId = this.options.data.properties.id ? n[this.options.data.properties.id] : i,
      }
      node = {
        // we use the count of the loop as an id if the id property setting is false
        // this is in case the edges properties "from" and "to" are referencing
        // the order of the node, not the real id.
        id: this.options.data.properties.id ? n[this.options.data.properties.id] : i,
        group: group,
        baseGroup: group,
        title: n[this.options.data.properties.nodes.title],
        shortName: n[this.options.data.properties.nodes.short],
        level: n[this.options.data.properties.nodes.level],
        tags: new Vizu.TagList(),
        value: 0 === n.dist ? 10 : 1
      };
      if (this.options.data.properties.nodes.label) {
        node['label'] = n[this.options.data.properties.nodes.label];
      }
      nodes.add(node);
    }
    for (var j = 0; j < data.links.length; j++) {
      var l = data.links[j];
      edges.add({
        from: l.source,
        to: l.target,
        data: {
          rels: l.rels,
          fromShortName: nodes.get(l.source).shortName,
          fromBaseGroup: nodes.get(l.source).baseGroup,
          toShortName: nodes.get(l.target).shortName,
          toBaseGroup: nodes.get(l.target).baseGroup,
          tags: new Vizu.TagList(),
          type: l.type
        },
        arrows: l.type === 'double' ? 'to, from' : 'to',
        color: l.color,
        title: l.rels.join('
')
      });
    }

    // create a network
    var container = document.getElementById('mynetwork');
    var networkData = {
      nodes: nodes,
      edges: edges
    };

    var networkOptions = Vizu.options.network;
    if (window.localStorage.getItem('adcpVizuOptions')) {
      networkOptions = JSON.parse(window.localStorage.getItem('adcpVizuOptions'));
      networkOptions.groups = Vizu.options.network.groups;
      networkOptions.configure = Vizu.options.network.configure;
    }
    Vizu.options.network.configure.container = document.getElementById('config');

    this.network = new vis.Network(container, networkData, networkOptions);
    // put the colorpicker in the root page so it's not limited to our fixed toolbar
    var colPicker = document.getElementsByClassName('vis-color-picker')[0];
    colPicker.parentNode.removeChild(colPicker);
    document.body.appendChild(colPicker);

    var searchBox = new Vizu.SearchBox(this, nodes);

    this.contextMenu = new Vizu.ContextMenu('contextMenu', this);

    this.network.on('oncontext', onContext.bind(this));

    this.network.on('click', function() {
      this.contextMenu.hide();
    }.bind(this));

    this.network.on('select', neighbourhoodHighlight.bind(this));

    this.network.on("stabilizationProgress", stabilizationProgressFunction);
    this.network.once("stabilizationIterationsDone", stabilizationDoneFunction);

    this.toolbar = new Vizu.Toolbar(this);
    this.statusbar = new Vizu.Statusbar(this, nodes, edges);

    this.network.on('hoverNode', this.statusbar.update);
    this.network.on('hoverEdge', this.statusbar.update);
    this.network.on('blurNode', this.statusbar.reset.bind(this.statusbar));
    this.network.on('blurEdge', this.statusbar.reset.bind(this.statusbar));

    this.network.on('selectNode', this.statusbar.selectObject);
    this.network.on('selectEdge', this.statusbar.selectObject);

    this.network.on('deselectNode', this.statusbar.deselectObject);
    this.network.on('deselectEdge', this.statusbar.deselectObject);
  };

  var onContext = function(params) {
    var node,
      edge,
      selectionNodes = [],
      selectionEdges = [];
    params.event.preventDefault();
    if (node = this.network.getNodeAt(params.pointer.DOM)) {
      if (params.event.ctrlKey) {
        selectionNodes = this.network.getSelectedNodes();
      }
      selectionNodes.push(node);
      this.network.selectNodes(selectionNodes, this.network.selectionHandler.options.selectConnectedEdges);
    } else if (edge = this.network.getEdgeAt(params.pointer.DOM)) {
      if (params.event.ctrlKey) {
        selectionEdges = this.network.getSelectedEdges();
      }
      selectionEdges.push(edge);
      this.network.selectEdges(selectionEdges);
    }
    neighbourhoodHighlight.call(this, {nodes: this.network.getSelectedNodes(), edges: this.network.getSelectedEdges()});
    this.contextMenu.show(params.pointer.DOM.x, params.pointer.DOM.y);
  };

  var  neighbourhoodHighlight = function(params) {
    this.contextMenu.hide();
    this.statusbar.updateSelectionDetails();
    // get a JSON object
    var allNodes = this.network.body.nodes;
    // if something is selected:
    if (params.nodes.length > 0 || params.edges.length > 0) {
        // mark all nodes as hard to read.
        for (var nodeId in allNodes) {
          if (allNodes.hasOwnProperty(nodeId) && allNodes[nodeId].options.baseGroup) {
            allNodes[nodeId].options.color.background = Vizu.colors['u' + allNodes[nodeId].options.baseGroup].background;
            allNodes[nodeId].options.color.border = Vizu.colors['u' + allNodes[nodeId].options.baseGroup].border;
          }
        }

        for (var i = 0; i < params.nodes.length; i++) {
          var node;
          if (this.network.isCluster(params.nodes[i])) {
            node = this.network.body.nodes[params.nodes[i]];
          } else {
            node = allNodes[params.nodes[i]];
          }
          if (node.options.baseGroup) {
            node.options.color.background = Vizu.colors['u' + node.options.baseGroup].background;
            node.options.color.border = Vizu.colors['u' + node.options.baseGroup].border;
          }
        }
//        this.network.redraw();
    }
    else {
        // reset all nodes
        resetNodeStyle(allNodes, this.network);
        this.statusbar.reset(true);
    }
  }

  var resetNodeStyle = function (allNodes) {
    for (var nodeId in allNodes) {
      if (allNodes.hasOwnProperty(nodeId)) {
        if(allNodes[nodeId].options.baseGroup) {
          allNodes[nodeId].options.color.background = Vizu.colors[allNodes[nodeId].options.baseGroup].background;
          allNodes[nodeId].options.color.border = Vizu.colors[allNodes[nodeId].options.baseGroup].border;
        }
      }
    }
  };

  // Increment loading bar length on progress event
  var stabilizationProgressFunction = function(params) {
    var maxWidth = 496;
    var minWidth = 20;
    document.getElementById('loadingBar').style.display = 'block';
    var widthFactor = params.iterations / params.total;
    var width = Math.max(minWidth, maxWidth * widthFactor);

    document.getElementById('bar').style.width = width + 'px';
    document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
  };

  // stabilization is done, remove loading bar
  var stabilizationDoneFunction = function() {
    var loadingBar = document.getElementById('loadingBar');
    document.getElementById('text').innerHTML = '100%';
    document.getElementById('bar').style.width = '496px';
    loadingBar.style.opacity = 0;
    // really clean the dom element
    setTimeout(function () {
      loadingBar.parentNode.removeChild(loadingBar);
    }, 200);
  };

  return {
    resetNodeStyle: resetNodeStyle,
    neighbourhoodHighlight: neighbourhoodHighlight,
    setData: setData
  };

})();
<commit_msg>Update Graph.js<commit_after>var Vizu = Vizu || {};

Vizu.Graph = function (containerId, options) {
  this.container = document.getElementById(containerId);
  this.options = options;
}

Vizu.Graph.prototype = (function () {

  var nodes, edges;

  var getGroup = function (node, options) {
    // return default group when no configuration was defined
    return options.network.groups[node[options.data.properties.nodes.group]] ? node[options.data.properties.nodes.group] : 'default';
  };

  var setData = function(data) {
    // setting template in body
    document.body.innerHTML = "";
    var t = document.querySelector('#bodyContent');
    var clone = document.importNode(t.content, true);
    document.body.appendChild(clone);

    nodes = new vis.DataSet(); edges = new vis.DataSet();

    for (var i = 0; i < data.nodes.length; i++) {
      var n = data.nodes[i],
        group = getGroup(n, this.options),
        node;
      if (0 === n.dist) {
        this.rootId = this.options.data.properties.id ? n[this.options.data.properties.id] : i
      }
      node = {
        // we use the count of the loop as an id if the id property setting is false
        // this is in case the edges properties "from" and "to" are referencing
        // the order of the node, not the real id.
        id: this.options.data.properties.id ? n[this.options.data.properties.id] : i,
        group: group,
        baseGroup: group,
        title: n[this.options.data.properties.nodes.title],
        shortName: n[this.options.data.properties.nodes.short],
        level: n[this.options.data.properties.nodes.level],
        tags: new Vizu.TagList(),
        value: 0 === n.dist ? 10 : 1
      };
      if (this.options.data.properties.nodes.label) {
        node['label'] = n[this.options.data.properties.nodes.label];
      }
      nodes.add(node);
    }
    for (var j = 0; j < data.links.length; j++) {
      var l = data.links[j];
      edges.add({
        from: l.source,
        to: l.target,
        data: {
          rels: l.rels,
          fromShortName: nodes.get(l.source).shortName,
          fromBaseGroup: nodes.get(l.source).baseGroup,
          toShortName: nodes.get(l.target).shortName,
          toBaseGroup: nodes.get(l.target).baseGroup,
          tags: new Vizu.TagList(),
          type: l.type
        },
        arrows: l.type === 'double' ? 'to, from' : 'to',
        color: l.color,
        title: l.rels.join('
')
      });
    }

    // create a network
    var container = document.getElementById('mynetwork');
    var networkData = {
      nodes: nodes,
      edges: edges
    };

    var networkOptions = Vizu.options.network;
    if (window.localStorage.getItem('adcpVizuOptions')) {
      networkOptions = JSON.parse(window.localStorage.getItem('adcpVizuOptions'));
      networkOptions.groups = Vizu.options.network.groups;
      networkOptions.configure = Vizu.options.network.configure;
    }
    Vizu.options.network.configure.container = document.getElementById('config');

    this.network = new vis.Network(container, networkData, networkOptions);
    // put the colorpicker in the root page so it's not limited to our fixed toolbar
    var colPicker = document.getElementsByClassName('vis-color-picker')[0];
    colPicker.parentNode.removeChild(colPicker);
    document.body.appendChild(colPicker);

    var searchBox = new Vizu.SearchBox(this, nodes);

    this.contextMenu = new Vizu.ContextMenu('contextMenu', this);

    this.network.on('oncontext', onContext.bind(this));

    this.network.on('click', function() {
      this.contextMenu.hide();
    }.bind(this));

    this.network.on('select', neighbourhoodHighlight.bind(this));

    this.network.on("stabilizationProgress", stabilizationProgressFunction);
    this.network.once("stabilizationIterationsDone", stabilizationDoneFunction);

    this.toolbar = new Vizu.Toolbar(this);
    this.statusbar = new Vizu.Statusbar(this, nodes, edges);

    this.network.on('hoverNode', this.statusbar.update);
    this.network.on('hoverEdge', this.statusbar.update);
    this.network.on('blurNode', this.statusbar.reset.bind(this.statusbar));
    this.network.on('blurEdge', this.statusbar.reset.bind(this.statusbar));

    this.network.on('selectNode', this.statusbar.selectObject);
    this.network.on('selectEdge', this.statusbar.selectObject);

    this.network.on('deselectNode', this.statusbar.deselectObject);
    this.network.on('deselectEdge', this.statusbar.deselectObject);
  };

  var onContext = function(params) {
    var node,
      edge,
      selectionNodes = [],
      selectionEdges = [];
    params.event.preventDefault();
    if (node = this.network.getNodeAt(params.pointer.DOM)) {
      if (params.event.ctrlKey) {
        selectionNodes = this.network.getSelectedNodes();
      }
      selectionNodes.push(node);
      this.network.selectNodes(selectionNodes, this.network.selectionHandler.options.selectConnectedEdges);
    } else if (edge = this.network.getEdgeAt(params.pointer.DOM)) {
      if (params.event.ctrlKey) {
        selectionEdges = this.network.getSelectedEdges();
      }
      selectionEdges.push(edge);
      this.network.selectEdges(selectionEdges);
    }
    neighbourhoodHighlight.call(this, {nodes: this.network.getSelectedNodes(), edges: this.network.getSelectedEdges()});
    this.contextMenu.show(params.pointer.DOM.x, params.pointer.DOM.y);
  };

  var  neighbourhoodHighlight = function(params) {
    this.contextMenu.hide();
    this.statusbar.updateSelectionDetails();
    // get a JSON object
    var allNodes = this.network.body.nodes;
    // if something is selected:
    if (params.nodes.length > 0 || params.edges.length > 0) {
        // mark all nodes as hard to read.
        for (var nodeId in allNodes) {
          if (allNodes.hasOwnProperty(nodeId) && allNodes[nodeId].options.baseGroup) {
            allNodes[nodeId].options.color.background = Vizu.colors['u' + allNodes[nodeId].options.baseGroup].background;
            allNodes[nodeId].options.color.border = Vizu.colors['u' + allNodes[nodeId].options.baseGroup].border;
          }
        }

        for (var i = 0; i < params.nodes.length; i++) {
          var node;
          if (this.network.isCluster(params.nodes[i])) {
            node = this.network.body.nodes[params.nodes[i]];
          } else {
            node = allNodes[params.nodes[i]];
          }
          if (node.options.baseGroup) {
            node.options.color.background = Vizu.colors['u' + node.options.baseGroup].background;
            node.options.color.border = Vizu.colors['u' + node.options.baseGroup].border;
          }
        }
//        this.network.redraw();
    }
    else {
        // reset all nodes
        resetNodeStyle(allNodes, this.network);
        this.statusbar.reset(true);
    }
  }

  var resetNodeStyle = function (allNodes) {
    for (var nodeId in allNodes) {
      if (allNodes.hasOwnProperty(nodeId)) {
        if(allNodes[nodeId].options.baseGroup) {
          allNodes[nodeId].options.color.background = Vizu.colors[allNodes[nodeId].options.baseGroup].background;
          allNodes[nodeId].options.color.border = Vizu.colors[allNodes[nodeId].options.baseGroup].border;
        }
      }
    }
  };

  // Increment loading bar length on progress event
  var stabilizationProgressFunction = function(params) {
    var maxWidth = 496;
    var minWidth = 20;
    document.getElementById('loadingBar').style.display = 'block';
    var widthFactor = params.iterations / params.total;
    var width = Math.max(minWidth, maxWidth * widthFactor);

    document.getElementById('bar').style.width = width + 'px';
    document.getElementById('text').innerHTML = Math.round(widthFactor * 100) + '%';
  };

  // stabilization is done, remove loading bar
  var stabilizationDoneFunction = function() {
    var loadingBar = document.getElementById('loadingBar');
    document.getElementById('text').innerHTML = '100%';
    document.getElementById('bar').style.width = '496px';
    loadingBar.style.opacity = 0;
    // really clean the dom element
    setTimeout(function () {
      loadingBar.parentNode.removeChild(loadingBar);
    }, 200);
  };

  return {
    resetNodeStyle: resetNodeStyle,
    neighbourhoodHighlight: neighbourhoodHighlight,
    setData: setData
  };

})();
<|endoftext|>


<commit_before>(function() {

  var app = angular.module('huewi', []);
  var MyHue = new huepi();
  MyHue.Username = '085efe879ee3ed83c04efc28a0da03d3';

   delete localStorage.MyHueBridgeIP; // Force PortalDiscoverLocalBridges

  function ToHexString(In) {
    var Result = Math.floor(In).toString(16);
    return Result.length == 1 ? "0" + Result : Result;
  }

  app.controller('HueStatusController', function($scope) {
    self = this; // Calling Async Functions looses this... Fix: Store this in self for later reference
    this.MyHue = MyHue; // to be called via 'HueStatusController'.controller().MyHue+GroupOn() in HTML
    this.BridgeIP = '';
    this.BridgeName = '';
    this.Status = '';

    this.ConnectToHueBridge = function() {
      if (!localStorage.MyHueBridgeIP) { // No Cached BridgeIP?
        self.Status = 'Trying to Discover Bridge via Portal';
        $scope.$apply();
        MyHue.PortalDiscoverLocalBridges().then(function GetBridgeConfig() {
          MyHue.BridgeGetData().then(function EnsureWhitelisting() {
            self.BridgeIP = MyHue.BridgeIP;
            if (!MyHue.BridgeUsernameWhitelisted) {
              self.Status = 'Please press connect button on Bridge';
              $scope.$apply();
              MyHue.BridgeCreateUser().then(function ReReadBridgeConfiguration() {
                return;
              }, function UnableToCreateUseronBridge() {
                self.Status = 'Unable to Create User on Bridge';
                $scope.$apply();
                return;
              });
            } else {
              localStorage.MyHueBridgeIP = MyHue.BridgeIP; // Cache BridgeIP
              self.BridgeName = MyHue.BridgeName;
              self.Status = 'Connected';
              $scope.$apply();
            }
          }, function UnableToRetreiveBridgeConfiguration() {
            self.Status = 'Unable to Retreive Bridge Configuration';
            $scope.$apply();
            return;
          });
        }, function UnableToDiscoverLocalBridgesViaPortal() {
          self.Status = 'Unable to find Local Bridge via Portal';
          $scope.$apply();
          return;
        });
      } else {
        MyHue.BridgeIP = localStorage.MyHueBridgeIP;
        self.BridgeIP = 'Cached ' + MyHue.BridgeIP;
        MyHue.BridgeGetData().then(function CheckWhitelisting() {
          if (MyHue.BridgeUsernameWhitelisted) {
            self.BridgeName = MyHue.BridgeName;
            self.Status = 'Connected';
            $scope.$apply();
          } else {
            delete localStorage.MyHueBridgeIP;
            self.Status = 'Not Whitelisted anymore';
            $scope.$apply();
            return;
          }
        }, function ErrorGettingCachedBridgeData() {
          delete localStorage.MyHueBridgeIP;
          self.Status = 'Not found anymore';
          $scope.$apply();
          return;
        });
      }
    }
  });

  app.controller('GroupController', function($scope) {
    this.Groups = [{'name': 'All available lights'}, {'name': 'Group'}];

    this.Update = function() {
      this.Groups = _.toArray(MyHue.Groups);
      this.Groups.unshift({'name': 'All available lights'});

      _.each(this.Groups, function(Group) {
        var RGB;
        if (Group.action) { // Group 0 (All available lights) doesn't have properties
          if (Group.action.colormode === 'hs') {
            RGB = huepi.HelperHueAngSatBritoRGB(Group.action.hue * 360 / 65535, Group.action.sat / 255, Group.action.bri / 255);
            var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
            RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Group.modelid, Group.action.bri / 255);
          } else if (Group.action.colormode === 'xy') {
            RGB = huepi.HelperXYtoRGBforModel(Group.action.xy[0], Group.action.xy[1], "LCT001", Group.action.bri / 255);
          } else if (Group.action.colormode === 'ct') {
            RGB = huepi.HelperColortemperaturetoRGB(Math.round(1000000 / Group.action.ct));
            var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
            RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Group.modelid, Group.action.bri / 255);
          }
          Group.HTMLColor = "#" + ToHexString(RGB.Red * 255) + ToHexString(RGB.Green * 255) + ToHexString(RGB.Blue * 255);
        } else Group.HTMLColor = "#ffcc88";
      })
      $scope.$apply();
    }
  })

  app.controller('LightController', function($scope) {
    this.Lights = [{'name': 'Light'}, {'name': 'Light'}, {'name': 'Light'}];

    this.Update = function() {
      this.Lights = _.toArray(MyHue.Lights);
      _.each(this.Lights, function(Light) {
        var RGB;
        if (Light.state.colormode === 'hs') {
          RGB = huepi.HelperHueAngSatBritoRGB(Light.state.hue * 360 / 65535, Light.state.sat / 255, Light.state.bri / 255);
          var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
          RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Light.modelid, Light.state.bri / 255);
        } else if (Light.state.colormode === 'xy') {
          RGB = huepi.HelperXYtoRGBforModel(Light.state.xy[0], Light.state.xy[1], Light.modelid, Light.state.bri / 255);
        } else if (Light.state.colormode === 'ct') {
          RGB = huepi.HelperColortemperaturetoRGB(Math.round(1000000 / Light.state.ct));
          var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
          RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Light.modelid, Light.state.bri / 255);
        }
        Light.HTMLColor = "#" + ToHexString(RGB.Red * 255) + ToHexString(RGB.Green * 255) + ToHexString(RGB.Blue * 255);
      })
      $scope.$apply();
    }

  });

})();<commit_msg>Enabled cached ip again<commit_after>(function() {

  var app = angular.module('huewi', []);
  var MyHue = new huepi();
  MyHue.Username = '085efe879ee3ed83c04efc28a0da03d3';

  //delete localStorage.MyHueBridgeIP; // Force PortalDiscoverLocalBridges

  function ToHexString(In) {
    var Result = Math.floor(In).toString(16);
    return Result.length == 1 ? "0" + Result : Result;
  }

  app.controller('HueStatusController', function($scope) {
    self = this; // Calling Async Functions looses this... Fix: Store this in self for later reference
    this.MyHue = MyHue; // to be called via angular.element(document.getElementById('HueStatusController')).controller().MyHue. in HTML
    this.BridgeIP = '';
    this.BridgeName = '';
    this.Status = '';

    this.ConnectToHueBridge = function() {
      if (!localStorage.MyHueBridgeIP) { // No Cached BridgeIP?
        self.Status = 'Trying to Discover Bridge via Portal';
        $scope.$apply();
        MyHue.PortalDiscoverLocalBridges().then(function GetBridgeConfig() {
          MyHue.BridgeGetData().then(function EnsureWhitelisting() {
            self.BridgeIP = MyHue.BridgeIP;
            if (!MyHue.BridgeUsernameWhitelisted) {
              self.Status = 'Please press connect button on Bridge';
              $scope.$apply();
              MyHue.BridgeCreateUser().then(function ReReadBridgeConfiguration() {
                return;
              }, function UnableToCreateUseronBridge() {
                self.Status = 'Unable to Create User on Bridge';
                $scope.$apply();
                return;
              });
            } else {
              localStorage.MyHueBridgeIP = MyHue.BridgeIP; // Cache BridgeIP
              self.BridgeName = MyHue.BridgeName;
              self.Status = 'Connected';
              $scope.$apply();
            }
          }, function UnableToRetreiveBridgeConfiguration() {
            self.Status = 'Unable to Retreive Bridge Configuration';
            $scope.$apply();
            return;
          });
        }, function UnableToDiscoverLocalBridgesViaPortal() {
          self.Status = 'Unable to find Local Bridge via Portal';
          $scope.$apply();
          return;
        });
      } else {
        MyHue.BridgeIP = localStorage.MyHueBridgeIP;
        self.BridgeIP = 'Cached ' + MyHue.BridgeIP;
        MyHue.BridgeGetData().then(function CheckWhitelisting() {
          if (MyHue.BridgeUsernameWhitelisted) {
            self.BridgeName = MyHue.BridgeName;
            self.Status = 'Connected';
            $scope.$apply();
          } else {
            delete localStorage.MyHueBridgeIP;
            self.Status = 'Not Whitelisted anymore';
            $scope.$apply();
            return;
          }
        }, function ErrorGettingCachedBridgeData() {
          delete localStorage.MyHueBridgeIP;
          self.Status = 'Not found anymore';
          $scope.$apply();
          return;
        });
      }
    }
  });

  app.controller('GroupController', function($scope) {
    this.Groups = [{'name': 'All available lights'}, {'name': 'Group'}];

    this.Update = function() {
      this.Groups = _.toArray(MyHue.Groups);
      this.Groups.unshift({'name': 'All available lights'});

      _.each(this.Groups, function(Group) {
        var RGB;
        if (Group.action) { // Group 0 (All available lights) doesn't have properties
          if (Group.action.colormode === 'hs') {
            RGB = huepi.HelperHueAngSatBritoRGB(Group.action.hue * 360 / 65535, Group.action.sat / 255, Group.action.bri / 255);
            var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
            RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Group.modelid, Group.action.bri / 255);
          } else if (Group.action.colormode === 'xy') {
            RGB = huepi.HelperXYtoRGBforModel(Group.action.xy[0], Group.action.xy[1], "LCT001", Group.action.bri / 255);
          } else if (Group.action.colormode === 'ct') {
            RGB = huepi.HelperColortemperaturetoRGB(Math.round(1000000 / Group.action.ct));
            var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
            RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Group.modelid, Group.action.bri / 255);
          }
          Group.HTMLColor = "#" + ToHexString(RGB.Red * 255) + ToHexString(RGB.Green * 255) + ToHexString(RGB.Blue * 255);
        } else Group.HTMLColor = "#ffcc88";
      })
      $scope.$apply();
    }
  })

  app.controller('LightController', function($scope) {
    this.Lights = [{'name': 'Light'}, {'name': 'Light'}, {'name': 'Light'}];

    this.Update = function() {
      this.Lights = _.toArray(MyHue.Lights);
      _.each(this.Lights, function(Light) {
        var RGB;
        if (Light.state.colormode === 'hs') {
          RGB = huepi.HelperHueAngSatBritoRGB(Light.state.hue * 360 / 65535, Light.state.sat / 255, Light.state.bri / 255);
          var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
          RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Light.modelid, Light.state.bri / 255);
        } else if (Light.state.colormode === 'xy') {
          RGB = huepi.HelperXYtoRGBforModel(Light.state.xy[0], Light.state.xy[1], Light.modelid, Light.state.bri / 255);
        } else if (Light.state.colormode === 'ct') {
          RGB = huepi.HelperColortemperaturetoRGB(Math.round(1000000 / Light.state.ct));
          var xy = huepi.HelperRGBtoXY(RGB.Red, RGB.Green, RGB.Blue);
          RGB = huepi.HelperXYtoRGBforModel(xy.x, xy.y, Light.modelid, Light.state.bri / 255);
        }
        Light.HTMLColor = "#" + ToHexString(RGB.Red * 255) + ToHexString(RGB.Green * 255) + ToHexString(RGB.Blue * 255);
      })
      $scope.$apply();
    }

  });

})();<|endoftext|>


<commit_before>/*eslint-env browser */
/*global require: false */
'use strict';

var React = require('react');
require('bootstrap/dist/css/bootstrap.css');
var Rx = require('rx');
var vcf = require('vcf.js');
require('rx.binding');
require('rx-dom');
require('css/custom.css');
var _ = require('underscore');
var brcaLogo = require('./img/brca_logo.png');
var ga4ghLogo = require('./img/ga4gh-logo-less.png');
var brcaLogoWithText = require('./img/BRCA-logo-with-text.png');
var hvpLogo = require('./img/hvp_logo.png');
var UNESCOLogo = require('./img/UNESCO-logo.jpg');
var ENIGMALogo = require('./img/enigma_logo.png');
var CIMBALogo = require('./img/cimba_logo.png');

var Markdown = require('react-remarkable');
var content = {
	home: require('../content/home.md'),
	'history': require('../content/history.md'),
	'brca1_2': require('../content/brca1_2.md'),
	'variation': require('../content/variationAndCancer.md')
};

var databaseUrl = require('file!../../brca-database.vcf');

var {Well, Grid, Col, Row, Input, Button, Navbar, CollapsableNav, Nav, Table,
	NavItem, DropdownButton, MenuItem, Panel} = require('react-bootstrap');

var VariantTable = require('./VariantTable');
var {Navigation, State, Link, Route, RouteHandler,
	HistoryLocation, run} = require('react-router');

var merge = (...objs) => _.extend({}, ...objs);

function mergeInfo(row) {
	var info = _.object(_.map(_.pairs(row.INFO), ([k, v]) => ['INFO$' + k, v]));
	return merge(info, _.omit(row, ['INFO']));
}

// XXX hard-coded GENE, PROB, REFS, PATH for now
function sanitize(data) {
	return _.map(data, (r, i) => merge({id: i, GENE: 'BRCA1', PROB: 0.23, REFS: 'sciencemag.org/content', PATH: 'pathogenic'}, mergeInfo(r)));
}

function readVcf(response) {
	var {header, records} = vcf.parser()(response);
	return {
		header: header,
		records: sanitize(records)
	};
}

var NavLink = React.createClass({
	render: function () {
		var {children, ...otherProps} = this.props;
		return (

				<Link {...otherProps} role='button'>
					{children}
				</Link>

		);
	}
});

var NavBarNew = React.createClass({
	close: function () {
		this.refs.about.setState({open: false});
	},
	// XXX drop the &nbsp for a css margin
	render: function () {
		return (
			<Navbar>

					   BRCA Exchange

				<CollapsableNav>

						<NavLink to='/home'>Home</NavLink>
						<DropdownButton ref='about' title='About'>
							<NavLink onClick={this.close} to='/about/history'>
								History of the BRCA Exchange
							</NavLink>
							<NavLink onClick={this.close} to='/about/brca1_2'>
								What are BRCA1 and BRCA2?
							</NavLink>
							<NavLink onClick={this.close} to='/about/variation'>
								BRCA Variation and Cancer
							</NavLink>
						</DropdownButton>
						<NavLink to='/variants'>Variants</NavLink>

						<NavItem href='#'><input placeholder="Search Variant"></input>
							<Button className='btn-xs' style={{border: 0}}>

							</Button>
						</NavItem>

				</CollapsableNav>
			</Navbar>
        );
    }
});

var Home = React.createClass({
	getInitialState() {
		return {
			index: 0,
			direction: null
		};
	},

	handleSelect(selectedIndex, selectedDirection) {
		this.setState({
			index: selectedIndex,
			direction: selectedDirection
		});
	},

	render: function() {
		return (
			<Grid>
				<Row style={{marginTop: 10}}>
					<Col md={4} mdOffset={4}>
						<Well>

								<input placeholder="Search Variant">

								</input>

						</Well>
					</Col>
				</Row>
				<Row style={{marginTop: 100}}>
					<Col md={8} mdOffset={2}>
						<Markdown options={{html: true}} source={content.home} />
					</Col>
				</Row>
				<Row className='logo-block'>
					<Col md={6} mdOffset={3}>

					</Col>
				</Row>
			</Grid>
		);
	}
});

var About = React.createClass({
	render: function() {
		var {page} = this.props.params;

		return (
			<Grid>
				<Row style={{marginTop: 100}}>
					<Col md={8} mdOffset={2}>
						<Markdown options={{html: true}} source={content[page]} />
					</Col>
				</Row>
			</Grid>
		);
	}
});

// sketch of function to filter rows on exact matches
function filterData(data, str) { //eslint-disable-line no-unused-vars
	var {records, header} = data;
	var filteredRecords = _.filter(records, row => {
		// row = {
		//   chrom: "17",
		//   pos: 1234,
		//   hgvs: "NC_0001:1234T>C"
		// }
		//
		return _.find(_.values(row), col => col.indexOf(str) !== -1);

	});
	return {
		records: filteredRecords,
		header: header
	};
}

var Database = React.createClass({
	mixins: [Navigation],
	showVariant: function ({id}) {
		this.transitionTo(`/variant/${id}`);
	},
	render: function () {
		var {show, data} = this.props;
		return (

					<Row style={{marginTop: 50, marginBottom: 50}}>

							place holder for database summary

					</Row>
					<Row style={{marginTop: 10}}>

							<input></input>

					</Row>
					<Row className="text-center" style={{fontSize: 12, color: "grey"}}>
						search for known variants
					</Row>
					<Row>
						<Col md={4} mdOffset={4}>
							<Panel header='Advanced filtering'>
								<DropdownButton title="Gene">
									<MenuItem>BRCA1</MenuItem>
									<MenuItem>BRCA2</MenuItem>
								</DropdownButton>

								<DropdownButton title="Exon">
									<MenuItem>Any</MenuItem>
									<MenuItem>1</MenuItem>
									<MenuItem>2</MenuItem>
									<MenuItem>3</MenuItem>
									<MenuItem>4</MenuItem>
									<MenuItem>5</MenuItem>
								</DropdownButton>

							</Panel>
						</Col>
						<Col md={1}>
							<Button>Download</Button>
						</Col>
					</Row>

					{data?
						<Row>
							<Col md={10} mdOffset={1}>
								<VariantTable data={data.records} onRowClick={this.showVariant}/>
							</Col>
						</Row>
						: ''}

		);
	}
});

var MyVariant = React.createClass({ //eslint-disable-line no-unused-vars
	getInitialState: function () {
		return {
			data: null
		};
	},

	render: function() {
		var {data} = this.state;
		var {show} = this.props;
		return (

					<Input ref='file' type='file' onChange={this.fileChange}/>

					{data?
						<Row>
							<Col md={10} mdOffset={1}>
								<VariantTable data={data}/>
							</Col>
						</Row>
						: ''}

		);
	},

	dataReady: function(ev) {
		this.setState({data: vcf.parser()(ev.currentTarget.result)});
	},

	fileChange: function () {
		var file = this.refs.file.getInputDOMNode().files[0],
		reader = new FileReader();
		// XXX This timeout allows the UI to update (close dialog) before loading
		// a potentially large file, which will block the UI.
		// This might also be solved by elminating the animation on Modal close,
		// which is probably the source of the problem.
		window.setTimeout(() => {
			reader.onload = this.dataReady;
			reader.readAsText(file);
		}, 100);
	}
});

var VariantDetail = React.createClass({
	render: function() {
		var {data, params: {id}} = this.props,
			variant = (data && data.records[id]) || {};

		variant = _.omit(variant, ['__HEADER__']);
		var rows = _.map(variant, (v, k) =>
{k}	{v}
);
		return (
			<Grid>
				<Row style={{marginTop: 100}}>

Variant Detail

Placeholder for a better variant details page

				</Row>
				<Row>
					<Col md={8} mdOffset={2}>

								{rows}

					</Col>
				</Row>
			</Grid>
		);
	}
});

var Application = React.createClass({
	mixins: [State],
	getInitialState: function () {
		return {data: null};
	},
	componentWillMount: function (){
		Rx.DOM.get(databaseUrl).subscribe(data =>
			this.setState({data: readVcf(data.response)}));
	},
	render: function () {
		var {data} = this.state;
		var path = this.getPath().slice(1);
		return (

				<NavBarNew />
				<RouteHandler data={data}/>
				<Database show={path === 'variants'} data={data}/>

		);
	}
});

var routes = (
	<Route handler={Application}>
		<Route path='home' handler={Home}/>
		<Route path='about/:page' handler={About}/>
		<Route path='variants' />
		<Route path='variant/:id' handler={VariantDetail}/>
	</Route>
);

var main = document.getElementById('main');

run(routes, HistoryLocation, (Root) => {
  React.render(<Root/>, main);
});
<commit_msg>Add default route.<commit_after>/*eslint-env browser */
/*global require: false */
'use strict';

var React = require('react');
require('bootstrap/dist/css/bootstrap.css');
var Rx = require('rx');
var vcf = require('vcf.js');
require('rx.binding');
require('rx-dom');
require('css/custom.css');
var _ = require('underscore');
var brcaLogo = require('./img/brca_logo.png');
var ga4ghLogo = require('./img/ga4gh-logo-less.png');
var brcaLogoWithText = require('./img/BRCA-logo-with-text.png');
var hvpLogo = require('./img/hvp_logo.png');
var UNESCOLogo = require('./img/UNESCO-logo.jpg');
var ENIGMALogo = require('./img/enigma_logo.png');
var CIMBALogo = require('./img/cimba_logo.png');

var Markdown = require('react-remarkable');
var content = {
	home: require('../content/home.md'),
	'history': require('../content/history.md'),
	'brca1_2': require('../content/brca1_2.md'),
	'variation': require('../content/variationAndCancer.md')
};

var databaseUrl = require('file!../../brca-database.vcf');

var {Well, Grid, Col, Row, Input, Button, Navbar, CollapsableNav, Nav, Table,
	NavItem, DropdownButton, MenuItem, Panel} = require('react-bootstrap');

var VariantTable = require('./VariantTable');
var {Navigation, State, Link, Route, RouteHandler,
	HistoryLocation, run, DefaultRoute} = require('react-router');

var merge = (...objs) => _.extend({}, ...objs);

function mergeInfo(row) {
	var info = _.object(_.map(_.pairs(row.INFO), ([k, v]) => ['INFO$' + k, v]));
	return merge(info, _.omit(row, ['INFO']));
}

// XXX hard-coded GENE, PROB, REFS, PATH for now
function sanitize(data) {
	return _.map(data, (r, i) => merge({id: i, GENE: 'BRCA1', PROB: 0.23, REFS: 'sciencemag.org/content', PATH: 'pathogenic'}, mergeInfo(r)));
}

function readVcf(response) {
	var {header, records} = vcf.parser()(response);
	return {
		header: header,
		records: sanitize(records)
	};
}

var NavLink = React.createClass({
	render: function () {
		var {children, ...otherProps} = this.props;
		return (

				<Link {...otherProps} role='button'>
					{children}
				</Link>

		);
	}
});

var NavBarNew = React.createClass({
	close: function () {
		this.refs.about.setState({open: false});
	},
	// XXX drop the &nbsp for a css margin
	render: function () {
		return (
			<Navbar>

					   BRCA Exchange

				<CollapsableNav>

						<NavLink to='/'>Home</NavLink>
						<DropdownButton ref='about' title='About'>
							<NavLink onClick={this.close} to='/about/history'>
								History of the BRCA Exchange
							</NavLink>
							<NavLink onClick={this.close} to='/about/brca1_2'>
								What are BRCA1 and BRCA2?
							</NavLink>
							<NavLink onClick={this.close} to='/about/variation'>
								BRCA Variation and Cancer
							</NavLink>
						</DropdownButton>
						<NavLink to='/variants'>Variants</NavLink>

						<NavItem href='#'><input placeholder="Search Variant"></input>
							<Button className='btn-xs' style={{border: 0}}>

							</Button>
						</NavItem>

				</CollapsableNav>
			</Navbar>
        );
    }
});

var Home = React.createClass({
	getInitialState() {
		return {
			index: 0,
			direction: null
		};
	},

	handleSelect(selectedIndex, selectedDirection) {
		this.setState({
			index: selectedIndex,
			direction: selectedDirection
		});
	},

	render: function() {
		return (
			<Grid>
				<Row style={{marginTop: 10}}>
					<Col md={4} mdOffset={4}>
						<Well>

								<input placeholder="Search Variant">

								</input>

						</Well>
					</Col>
				</Row>
				<Row style={{marginTop: 100}}>
					<Col md={8} mdOffset={2}>
						<Markdown options={{html: true}} source={content.home} />
					</Col>
				</Row>
				<Row className='logo-block'>
					<Col md={6} mdOffset={3}>

					</Col>
				</Row>
			</Grid>
		);
	}
});

var About = React.createClass({
	render: function() {
		var {page} = this.props.params;

		return (
			<Grid>
				<Row style={{marginTop: 100}}>
					<Col md={8} mdOffset={2}>
						<Markdown options={{html: true}} source={content[page]} />
					</Col>
				</Row>
			</Grid>
		);
	}
});

// sketch of function to filter rows on exact matches
function filterData(data, str) { //eslint-disable-line no-unused-vars
	var {records, header} = data;
	var filteredRecords = _.filter(records, row => {
		// row = {
		//   chrom: "17",
		//   pos: 1234,
		//   hgvs: "NC_0001:1234T>C"
		// }
		//
		return _.find(_.values(row), col => col.indexOf(str) !== -1);

	});
	return {
		records: filteredRecords,
		header: header
	};
}

var Database = React.createClass({
	mixins: [Navigation],
	showVariant: function ({id}) {
		this.transitionTo(`/variant/${id}`);
	},
	render: function () {
		var {show, data} = this.props;
		return (

					<Row style={{marginTop: 50, marginBottom: 50}}>

							place holder for database summary

					</Row>
					<Row style={{marginTop: 10}}>

							<input></input>

					</Row>
					<Row className="text-center" style={{fontSize: 12, color: "grey"}}>
						search for known variants
					</Row>
					<Row>
						<Col md={4} mdOffset={4}>
							<Panel header='Advanced filtering'>
								<DropdownButton title="Gene">
									<MenuItem>BRCA1</MenuItem>
									<MenuItem>BRCA2</MenuItem>
								</DropdownButton>

								<DropdownButton title="Exon">
									<MenuItem>Any</MenuItem>
									<MenuItem>1</MenuItem>
									<MenuItem>2</MenuItem>
									<MenuItem>3</MenuItem>
									<MenuItem>4</MenuItem>
									<MenuItem>5</MenuItem>
								</DropdownButton>

							</Panel>
						</Col>
						<Col md={1}>
							<Button>Download</Button>
						</Col>
					</Row>

					{data?
						<Row>
							<Col md={10} mdOffset={1}>
								<VariantTable data={data.records} onRowClick={this.showVariant}/>
							</Col>
						</Row>
						: ''}

		);
	}
});

var MyVariant = React.createClass({ //eslint-disable-line no-unused-vars
	getInitialState: function () {
		return {
			data: null
		};
	},

	render: function() {
		var {data} = this.state;
		var {show} = this.props;
		return (

					<Input ref='file' type='file' onChange={this.fileChange}/>

					{data?
						<Row>
							<Col md={10} mdOffset={1}>
								<VariantTable data={data}/>
							</Col>
						</Row>
						: ''}

		);
	},

	dataReady: function(ev) {
		this.setState({data: vcf.parser()(ev.currentTarget.result)});
	},

	fileChange: function () {
		var file = this.refs.file.getInputDOMNode().files[0],
		reader = new FileReader();
		// XXX This timeout allows the UI to update (close dialog) before loading
		// a potentially large file, which will block the UI.
		// This might also be solved by elminating the animation on Modal close,
		// which is probably the source of the problem.
		window.setTimeout(() => {
			reader.onload = this.dataReady;
			reader.readAsText(file);
		}, 100);
	}
});

var VariantDetail = React.createClass({
	render: function() {
		var {data, params: {id}} = this.props,
			variant = (data && data.records[id]) || {};

		variant = _.omit(variant, ['__HEADER__']);
		var rows = _.map(variant, (v, k) =>
{k}	{v}
);
		return (
			<Grid>
				<Row style={{marginTop: 100}}>

Variant Detail

Placeholder for a better variant details page

				</Row>
				<Row>
					<Col md={8} mdOffset={2}>

								{rows}

					</Col>
				</Row>
			</Grid>
		);
	}
});

var Application = React.createClass({
	mixins: [State],
	getInitialState: function () {
		return {data: null};
	},
	componentWillMount: function (){
		Rx.DOM.get(databaseUrl).subscribe(data =>
			this.setState({data: readVcf(data.response)}));
	},
	render: function () {
		var {data} = this.state;
		var path = this.getPath().slice(1);
		return (

				<NavBarNew />
				<RouteHandler data={data}/>
				<Database show={path === 'variants'} data={data}/>

		);
	}
});

var routes = (
	<Route handler={Application}>
		<DefaultRoute handler={Home}/>
		<Route path='about/:page' handler={About}/>
		<Route path='variants' />
		<Route path='variant/:id' handler={VariantDetail}/>
	</Route>
);

var main = document.getElementById('main');

run(routes, HistoryLocation, (Root) => {
  React.render(<Root/>, main);
});
<|endoftext|>


<commit_before>const rootVm = new Vue({
    el: '#app-sudoku',
    template: `
    <div class="boxes"
    tabindex="0"
    @keydown.delete="pointed.value = 0"
    @keydown.48="pointed.value = 0"
    @keydown.49="pointed.value = 1"
    @keydown.50="pointed.value = 2"
    @keydown.51="pointed.value = 3"
    @keydown.52="pointed.value = 4"
    @keydown.53="pointed.value = 5"
    @keydown.54="pointed.value = 6"
    @keydown.55="pointed.value = 7"
    @keydown.56="pointed.value = 8"
    @keydown.57="pointed.value = 9"
    @keydown.space="pointed && pointed.value && affected.forEach(cell => cell.memo.splice(pointed.value - 1, 1, false))"
    @mouseenter="event => event.target.focus()"
    >

                        {{ cell.value }}
                        {{ cell.value }}

 set ? i + 1 : ''), 3)">
                            {{ n }}

`,
    computed: {
        affected: function() {
            const pointed = this.cells.indexOf(this.pointed);
            return pointed === -1 ? [] : this.affectedIndices(pointed).map(index => this.cells[index]);
        },
        boxes: function() {
            const OFFSETS = [0, 3, 6, 27, 30, 33, 54, 57, 60,];
            const INDICES = [0, 1, 2, 9, 10, 11, 18, 19, 20,];
            return OFFSETS.map(offset => INDICES.map(index => this.cells[index + offset]));
        },
    },
    data: () => new Object({
        /*
        manage each number cell by the object: {
            {Boolean} given, -- true if the number is given for clue, otherwise false.
            {Number} value, -- a number between 0 to 9.
            {Array} memo, -- array of the numbers, those of which can be placed, user considers.
        }
        */
        cells: Array.from(
            '060003001200500600007090500000400090800000006010005000002010700004009003700200040' // 朝日新聞beパズル 2017/10/07 掲載分
        ).map(n => new Object({ given: Number(n), value: Number(n), memo: Array(9).fill(true), })),
        pointed: null,
    }),
    methods: {
        slice: (() => {
            const splitAt = (array, n) => [array.slice(0, n), array.slice(n)];
            const reduceConcat = a => a.length ? a.reduce((a, b) => [a].concat(reduceConcat(b))) : [];

            return (array, n) => {
                const splitted = splitAt(array, n);
                var p = splitted;
                while (p[1].length !== 0) {
                    p[1] = splitAt(p[1], n);
                    p = p[1];
                }
                return reduceConcat(splitted);
            };
        })(),
        affectedIndices: index => {
            const col = index % 9;
            const row = (index - col) / 9;
            const boxOffset = ~~(col / 3) * 3 + ~~(row / 3) * 27;
            return [
                [0, 1, 2, 3, 4, 5, 6, 7, 8].map(v => v + row * 9),
                [0, 1, 2, 3, 4, 5, 6, 7, 8].map(v => v * 9 + col),
                [0, 1, 2, 9, 10, 11, 18, 19, 20].map(v => v + boxOffset),
            ]
            .reduce((a, b) => a.concat(b)) // flatten array
            .filter((value, index, array) => array.indexOf(value) === index); // remove duplicates
        },
    },
});
<commit_msg>Remove pointed cell from affected.<commit_after>const rootVm = new Vue({
    el: '#app-sudoku',
    template: `
    <div class="boxes"
    tabindex="0"
    @keydown.delete="pointed.value = 0"
    @keydown.48="pointed.value = 0"
    @keydown.49="pointed.value = 1"
    @keydown.50="pointed.value = 2"
    @keydown.51="pointed.value = 3"
    @keydown.52="pointed.value = 4"
    @keydown.53="pointed.value = 5"
    @keydown.54="pointed.value = 6"
    @keydown.55="pointed.value = 7"
    @keydown.56="pointed.value = 8"
    @keydown.57="pointed.value = 9"
    @keydown.space="pointed && pointed.value && affected.forEach(cell => cell.memo.splice(pointed.value - 1, 1, false))"
    @mouseenter="event => event.target.focus()"
    >

                        {{ cell.value }}
                        {{ cell.value }}

 set ? i + 1 : ''), 3)">
                            {{ n }}

`,
    computed: {
        affected: function() {
            const pointed = this.cells.indexOf(this.pointed);
            return pointed === -1 ? [] : this.affectedIndices(pointed).filter(index => index !== pointed).map(index => this.cells[index]);
        },
        boxes: function() {
            const OFFSETS = [0, 3, 6, 27, 30, 33, 54, 57, 60,];
            const INDICES = [0, 1, 2, 9, 10, 11, 18, 19, 20,];
            return OFFSETS.map(offset => INDICES.map(index => this.cells[index + offset]));
        },
    },
    data: () => new Object({
        /*
        manage each number cell by the object: {
            {Boolean} given, -- true if the number is given for clue, otherwise false.
            {Number} value, -- a number between 0 to 9.
            {Array} memo, -- array of the numbers, those of which can be placed, user considers.
        }
        */
        cells: Array.from(
            '060003001200500600007090500000400090800000006010005000002010700004009003700200040' // 朝日新聞beパズル 2017/10/07 掲載分
        ).map(n => new Object({ given: Number(n), value: Number(n), memo: Array(9).fill(true), })),
        pointed: null,
    }),
    methods: {
        slice: (() => {
            const splitAt = (array, n) => [array.slice(0, n), array.slice(n)];
            const reduceConcat = a => a.length ? a.reduce((a, b) => [a].concat(reduceConcat(b))) : [];

            return (array, n) => {
                const splitted = splitAt(array, n);
                var p = splitted;
                while (p[1].length !== 0) {
                    p[1] = splitAt(p[1], n);
                    p = p[1];
                }
                return reduceConcat(splitted);
            };
        })(),
        affectedIndices: index => {
            const col = index % 9;
            const row = (index - col) / 9;
            const boxOffset = ~~(col / 3) * 3 + ~~(row / 3) * 27;
            return [
                [0, 1, 2, 3, 4, 5, 6, 7, 8].map(v => v + row * 9),
                [0, 1, 2, 3, 4, 5, 6, 7, 8].map(v => v * 9 + col),
                [0, 1, 2, 9, 10, 11, 18, 19, 20].map(v => v + boxOffset),
            ]
            .reduce((a, b) => a.concat(b)) // flatten array
            .filter((value, index, array) => array.indexOf(value) === index); // remove duplicates
        },
    },
});
<|endoftext|>


<commit_before>/*global module, require*/
module.exports = function () {
	'use strict';
	var self = this,
			RegexUtil = require('./regex-util'),
			regexUtil = new RegexUtil(),
			dash = String.fromCharCode(8211),
			tick = String.fromCharCode(10003),
			crossValueAndExpected = function (expected, actual) {
				var formatActual = '';
				if (actual !== undefined) {
					formatActual = ' ['  + actual + ']';
				}
				return '**~~' + expected + '~~'  + formatActual + '**';
			},
			crossValue = function (expected) {
				return '**~~' + expected + '~~**';
			},
			boldValue = function (expected) {
				return '**' + expected + '**';
			};
	self.formatPrimitiveResult = function (assertion) {
		var formattedValue = function () {
			if (assertion.passed) {
				return boldValue(assertion.expected);
			} else {
				return crossValueAndExpected(assertion.expected, assertion.value);
			}
		};
		return {
			index: assertion.index,
			value: formattedValue()
		};
	};
	self.formatListResult = function (listResult) {
		var tickEl = function (e) {
			return '[' + tick + '] ' + e;
		}, crossEl = function (e) {
			return '**[' + dash + '] ~~' + e + '~~**';
		}, plusEl = function (e) {
			return '**[+] ' + e + '**';
		},
			matching = (listResult.matching || []).map(tickEl),
			missing = (listResult.missing || []).map(crossEl),
			additional = (listResult.additional || []).map(plusEl);
		return matching.concat(missing, additional);
	};
	self.getTableResult = function (tableResult) {
		var tickRow = function (row) {
			return [tick].concat(row);
		}, crossRow = function (row) {
			return [dash].concat(row.map(crossValue));
		}, plusRow = function (row) {
			return ['+'].concat(row.map(boldValue));
		},
			matching = (tableResult.matching || []).map(tickRow),
			missing = (tableResult.missing || []).map(crossRow),
			additional = (tableResult.additional || []).map(plusRow);
		return matching.concat(missing, additional);

	};
	self.markResult = function (stepResult) {
		var withoutIndex = function (assertion) {
				return !assertion.index && assertion.index !== 0;
			},
			withIndex = function (assertion) {
				return assertion.index;
			},
			failed = function (assertion) {
				return !assertion.passed;
			},
			failedForAttachment = function (assertion) {
				return stepResult.attachment && stepResult.attachment.items && stepResult.attachment.items.length > 0 &&
					(assertion.expected === stepResult.attachment.items || assertion.expected == stepResult.attachment) &&
					!assertion.passed;
			},
			noIndexAssertions = stepResult.assertions.filter(withoutIndex),
			headingLine = function () {
				if (noIndexAssertions.length === 0) {
					return regexUtil.replaceMatchGroup(stepResult.stepText, stepResult.matcher, stepResult.assertions.map(self.formatPrimitiveResult));
				}
				if (noIndexAssertions.some(failed)) {
					if (regexUtil.isListItem(stepResult.stepText)) {
						return regexUtil.getListSymbol(stepResult.stepText) + '**~~' + regexUtil.stripListSymbol(stepResult.stepText) + '~~**';
					} else {
						return '**~~' + stepResult.stepText + '~~**';
					}
				}
				if (stepResult.assertions.some(failed)) {
					return regexUtil.replaceMatchGroup(stepResult.stepText, stepResult.matcher, stepResult.assertions.filter(withIndex).map(self.formatPrimitiveResult));
				}
				if (stepResult.assertions.length) {
					if (regexUtil.isListItem(stepResult.stepText)) {
						return regexUtil.getListSymbol(stepResult.stepText) + '**' + regexUtil.stripListSymbol(stepResult.stepText) + '**';
					} else {
						return '**' + stepResult.stepText + '**';
					}
				}
				return stepResult.stepText;
			},
			attachmentLines = function () {
				if (!stepResult.attachment) {
					return '';
				}
				var formatList = function () {
						if (stepResult.attachment.type !== 'list') {
							return false;
						}
						var failedListAssertions = stepResult.assertions.filter(failedForAttachment),
								values = stepResult.attachment.items;
						if (failedListAssertions && failedListAssertions.length > 0) {
							values = self.formatListResult(failedListAssertions[0].value);
						}
						return values.map(function (e) {
							return '\n* ' + e; // TODO: reuse listutil add list item to support nested lists?
						}).join(''); // TODO: deal with ordered lists
					},
					formatTableItem = function (item) {
						return '\n| ' + item.join(' | ') + ' |';
					},
					formatTable = function () {
						if (stepResult.attachment.type !== 'table') {
							return false;
						}
						var titles = '',
								resultTitles = stepResult.attachment.titles && stepResult.attachment.titles.slice(0),
								failedTableAssertions = stepResult.assertions.filter(failedForAttachment),
								values = stepResult.attachment.items;

						if (failedTableAssertions && failedTableAssertions.length > 0) {
							if (resultTitles) {
								resultTitles.unshift(' ');
							}
							values = self.getTableResult(failedTableAssertions[0].value);
						}
						if (resultTitles) {
							titles = formatTableItem(resultTitles);
							titles = titles + titles.replace(/[^|\n]/g, '-');
						}
						return titles + values.map(formatTableItem).join('');
					};
				return formatList() || formatTable();
			};
		if (stepResult.exception) {
			return '~~' + stepResult.stepText + '~~\n' + '\t' + stepResult.exception.stack; //TODO: push list as well
		}
		return headingLine() + attachmentLines();

	};
};
<commit_msg>added todo for spacing<commit_after>/*global module, require*/
module.exports = function () {
	'use strict';
	var self = this,
			RegexUtil = require('./regex-util'),
			regexUtil = new RegexUtil(),
			dash = String.fromCharCode(8211),
			tick = String.fromCharCode(10003),
			crossValueAndExpected = function (expected, actual) {
				var formatActual = '';
				if (actual !== undefined) {
					formatActual = ' ['  + actual + ']';
				}
				return '**~~' + expected + '~~'  + formatActual + '**';
			},
			crossValue = function (expected) {
				return '**~~' + expected + '~~**';
			},
			boldValue = function (expected) {
				return '**' + expected + '**';
			};
	self.formatPrimitiveResult = function (assertion) {
		var formattedValue = function () {
			if (assertion.passed) {
				return boldValue(assertion.expected);
			} else {
				return crossValueAndExpected(assertion.expected, assertion.value);
			}
		};
		return {
			index: assertion.index,
			value: formattedValue()
		};
	};
	self.formatListResult = function (listResult) {
		var tickEl = function (e) {
			return '[' + tick + '] ' + e;
		}, crossEl = function (e) {
			return '**[' + dash + '] ~~' + e + '~~**';
		}, plusEl = function (e) {
			return '**[+] ' + e + '**';
		},
			matching = (listResult.matching || []).map(tickEl),
			missing = (listResult.missing || []).map(crossEl),
			additional = (listResult.additional || []).map(plusEl);
		return matching.concat(missing, additional);
	};
	self.getTableResult = function (tableResult) {
		var tickRow = function (row) {
			return [tick].concat(row);
		}, crossRow = function (row) {
			return [dash].concat(row.map(crossValue));
		}, plusRow = function (row) {
			return ['+'].concat(row.map(boldValue));
		},
			matching = (tableResult.matching || []).map(tickRow),
			missing = (tableResult.missing || []).map(crossRow),
			additional = (tableResult.additional || []).map(plusRow);
		return matching.concat(missing, additional);

	};
	self.markResult = function (stepResult) {
		var withoutIndex = function (assertion) {
				return !assertion.index && assertion.index !== 0;
			},
			withIndex = function (assertion) {
				return assertion.index;
			},
			failed = function (assertion) {
				return !assertion.passed;
			},
			failedForAttachment = function (assertion) {
				return stepResult.attachment && stepResult.attachment.items && stepResult.attachment.items.length > 0 &&
					(assertion.expected === stepResult.attachment.items || assertion.expected == stepResult.attachment) &&
					!assertion.passed;
			},
			noIndexAssertions = stepResult.assertions.filter(withoutIndex),
			headingLine = function () {
				if (noIndexAssertions.length === 0) {
					return regexUtil.replaceMatchGroup(stepResult.stepText, stepResult.matcher, stepResult.assertions.map(self.formatPrimitiveResult));
				}
				if (noIndexAssertions.some(failed)) {
					if (regexUtil.isListItem(stepResult.stepText)) {
						return regexUtil.getListSymbol(stepResult.stepText) + '**~~' + regexUtil.stripListSymbol(stepResult.stepText) + '~~**';
					} else {
						return '**~~' + stepResult.stepText + '~~**';
					}
				}
				if (stepResult.assertions.some(failed)) {
					return regexUtil.replaceMatchGroup(stepResult.stepText, stepResult.matcher, stepResult.assertions.filter(withIndex).map(self.formatPrimitiveResult));
				}
				if (stepResult.assertions.length) {
					if (regexUtil.isListItem(stepResult.stepText)) {
						return regexUtil.getListSymbol(stepResult.stepText) + '**' + regexUtil.stripListSymbol(stepResult.stepText) + '**';
					} else {
						return '**' + stepResult.stepText + '**';
					}
				}
				return stepResult.stepText;
			},
			attachmentLines = function () {
				//TODO: investigate if we should force exactly one space between the step text and attachment
				if (!stepResult.attachment) {
					return '';
				}
				var formatList = function () {
						if (stepResult.attachment.type !== 'list') {
							return false;
						}
						var failedListAssertions = stepResult.assertions.filter(failedForAttachment),
								values = stepResult.attachment.items;
						if (failedListAssertions && failedListAssertions.length > 0) {
							values = self.formatListResult(failedListAssertions[0].value);
						}
						return values.map(function (e) {
							return '\n* ' + e; // TODO: reuse listutil add list item to support nested lists?
						}).join(''); // TODO: deal with ordered lists
					},
					formatTableItem = function (item) {
						return '\n| ' + item.join(' | ') + ' |';
					},
					formatTable = function () {
						if (stepResult.attachment.type !== 'table') {
							return false;
						}
						var titles = '',
								resultTitles = stepResult.attachment.titles && stepResult.attachment.titles.slice(0),
								failedTableAssertions = stepResult.assertions.filter(failedForAttachment),
								values = stepResult.attachment.items;

						if (failedTableAssertions && failedTableAssertions.length > 0) {
							if (resultTitles) {
								resultTitles.unshift(' ');
							}
							values = self.getTableResult(failedTableAssertions[0].value);
						}
						if (resultTitles) {
							titles = formatTableItem(resultTitles);
							titles = titles + titles.replace(/[^|\n]/g, '-');
						}
						return titles + values.map(formatTableItem).join('');
					};
				return formatList() || formatTable();
			};
		if (stepResult.exception) {
			return '~~' + stepResult.stepText + '~~\n' + '\t' + stepResult.exception.stack; //TODO: push list as well
		}
		return headingLine() + attachmentLines();

	};
};
<|endoftext|>


<commit_before>/* global document Image */

import MouseHandler from 'paraviewweb/src/Interaction/Core/MouseHandler';

import SizeHelper from 'paraviewweb/src/Common/Misc/SizeHelper';

function formatSize(memorySize) {
  if (!memorySize) {
    return '';
  }
  if (memorySize > 1000000) {
    return `${Math.round(memorySize / 10000) / 100} MB - `;
  }
  if (memorySize > 1000) {
    return `${Math.round(memorySize / 10) / 100} KB - `;
  }
  return `${memorySize} B - `;
}

export default class NativeImageRenderer {
  constructor(
    domElement,
    imageProvider,
    mouseListeners = null,
    drawFPS = true
  ) {
    this.size = domElement
      ? SizeHelper.getSize(domElement)
      : { clientWidth: 400, clientHeight: 400 };
    this.canvas = document.createElement('canvas');
    this.image = new Image();
    this.fps = '';
    this.drawFPS = drawFPS;
    this.subscriptions = [];
    this.imageProvider = imageProvider;
    this.fpsBuffer = [];
    this.fpsBufferSize = 30;

    this.image.onload = () => {
      this.updateDrawnImage();
    };

    // Update DOM
    this.setContainer(domElement);

    this.ctx = this.canvas.getContext('2d');
    this.ctx.font = '30px Arial';

    // Attach mouse listener if needed
    if (mouseListeners) {
      this.mouseHandler = new MouseHandler(this.canvas);
      this.mouseHandler.attach(mouseListeners);
    }

    // Add image listener
    this.subscriptions.push(
      imageProvider.onImageReady((data, envelope) => {
        this.image.src = data.url;
        this.fps = data.fps;
        this.memsize = data.metadata.memory || '';
        this.workTime = data.metadata.workTime;
        this.fpsBuffer.push(this.fps);
        while (this.fpsBufferSize < this.fpsBuffer.length) {
          this.fpsBuffer.shift();
        }
      })
    );

    // Add size listener
    this.subscriptions.push(
      SizeHelper.onSizeChange(() => {
        if (this.container) {
          this.size = SizeHelper.getSize(this.container);
          this.canvas.setAttribute('width', this.size.clientWidth);
          this.canvas.setAttribute('height', this.size.clientHeight);
          if (this.image.src && this.image.complete) {
            this.updateDrawnImage();
          }
        }
      })
    );
    SizeHelper.startListening();
  }

  setDrawFPS(visible) {
    this.drawFPS = visible;
  }

  getStats() {
    let min = Number.MAX_VALUE;
    let max = -Number.MAX_VALUE;
    let total = 0;
    const size = this.fpsBuffer.length;
    for (let i = 0; i < size; i++) {
      const value = Number(this.fpsBuffer[i]);
      if (value < min) {
        min = value;
      }
      if (max < value) {
        max = value;
      }
      total += value;
    }
    total /= size;
    return `${Math.round(min)}<${Math.round(total)}<${Math.round(max)}`;
  }

  setContainer(container) {
    if (this.container) {
      this.container.removeChild(this.canvas);
    }
    this.container = container;
    if (this.container) {
      this.container.appendChild(this.canvas);
    }
  }

  resize() {
    if (this.container) {
      this.size = SizeHelper.getSize(this.container);
    }
  }

  setSize(clientWidth = 400, clientHeight = 400) {
    this.size = { clientWidth, clientHeight };
    this.canvas.setAttribute('width', this.size.clientWidth);
    this.canvas.setAttribute('height', this.size.clientHeight);
  }

  destroy() {
    while (this.subscriptions.length) {
      this.subscriptions.pop().unsubscribe();
    }

    if (this.mouseHandler) {
      this.mouseHandler.destroy();
      this.mouseHandler = null;
    }

    this.container = null;
    this.imageProvider = null;
  }

  updateDrawnImage() {
    this.ctx.drawImage(
      this.image,
      0,
      0,
      this.size.clientWidth,
      this.size.clientHeight
    );
    if (this.drawFPS) {
      this.ctx.textBaseline = 'top';
      this.ctx.textAlign = 'end';
      this.ctx.fillStyle = '#888';
      this.ctx.fillText(
        `${this.workTime}ms - ${formatSize(this.memsize)}${this.image.width}x${
          this.image.height
        } - ${this.fps} FPS - ${this.getStats()}`,
        this.size.clientWidth - 5,
        5
      );
    }
  }
}
<commit_msg>fix(NativeImageRenderer): re-render when changing canvas size attr<commit_after>/* global document Image */

import MouseHandler from 'paraviewweb/src/Interaction/Core/MouseHandler';

import SizeHelper from 'paraviewweb/src/Common/Misc/SizeHelper';

function formatSize(memorySize) {
  if (!memorySize) {
    return '';
  }
  if (memorySize > 1000000) {
    return `${Math.round(memorySize / 10000) / 100} MB - `;
  }
  if (memorySize > 1000) {
    return `${Math.round(memorySize / 10) / 100} KB - `;
  }
  return `${memorySize} B - `;
}

export default class NativeImageRenderer {
  constructor(
    domElement,
    imageProvider,
    mouseListeners = null,
    drawFPS = true
  ) {
    this.size = domElement
      ? SizeHelper.getSize(domElement)
      : { clientWidth: 400, clientHeight: 400 };
    this.canvas = document.createElement('canvas');
    this.image = new Image();
    this.fps = '';
    this.drawFPS = drawFPS;
    this.subscriptions = [];
    this.imageProvider = imageProvider;
    this.fpsBuffer = [];
    this.fpsBufferSize = 30;

    this.image.onload = () => {
      this.updateDrawnImage();
    };

    // Update DOM
    this.setContainer(domElement);

    this.ctx = this.canvas.getContext('2d');
    this.ctx.font = '30px Arial';

    // Attach mouse listener if needed
    if (mouseListeners) {
      this.mouseHandler = new MouseHandler(this.canvas);
      this.mouseHandler.attach(mouseListeners);
    }

    // Add image listener
    this.subscriptions.push(
      imageProvider.onImageReady((data, envelope) => {
        this.image.src = data.url;
        this.fps = data.fps;
        this.memsize = data.metadata.memory || '';
        this.workTime = data.metadata.workTime;
        this.fpsBuffer.push(this.fps);
        while (this.fpsBufferSize < this.fpsBuffer.length) {
          this.fpsBuffer.shift();
        }
      })
    );

    // Add size listener
    this.subscriptions.push(
      SizeHelper.onSizeChange(() => {
        if (this.container) {
          this.size = SizeHelper.getSize(this.container);
          this.canvas.setAttribute('width', this.size.clientWidth);
          this.canvas.setAttribute('height', this.size.clientHeight);
          if (this.image.src && this.image.complete) {
            this.updateDrawnImage();
          }
        }
      })
    );
    SizeHelper.startListening();
  }

  setDrawFPS(visible) {
    this.drawFPS = visible;
  }

  getStats() {
    let min = Number.MAX_VALUE;
    let max = -Number.MAX_VALUE;
    let total = 0;
    const size = this.fpsBuffer.length;
    for (let i = 0; i < size; i++) {
      const value = Number(this.fpsBuffer[i]);
      if (value < min) {
        min = value;
      }
      if (max < value) {
        max = value;
      }
      total += value;
    }
    total /= size;
    return `${Math.round(min)}<${Math.round(total)}<${Math.round(max)}`;
  }

  setContainer(container) {
    if (this.container) {
      this.container.removeChild(this.canvas);
    }
    this.container = container;
    if (this.container) {
      this.container.appendChild(this.canvas);
    }
  }

  resize() {
    if (this.container) {
      this.size = SizeHelper.getSize(this.container);
    }
  }

  setSize(clientWidth = 400, clientHeight = 400) {
    this.size = { clientWidth, clientHeight };
    this.canvas.setAttribute('width', this.size.clientWidth);
    this.canvas.setAttribute('height', this.size.clientHeight);
    if (this.image.src && this.image.complete) {
      this.updateDrawnImage();
    }
  }

  destroy() {
    while (this.subscriptions.length) {
      this.subscriptions.pop().unsubscribe();
    }

    if (this.mouseHandler) {
      this.mouseHandler.destroy();
      this.mouseHandler = null;
    }

    this.container = null;
    this.imageProvider = null;
  }

  updateDrawnImage() {
    this.ctx.drawImage(
      this.image,
      0,
      0,
      this.size.clientWidth,
      this.size.clientHeight
    );
    if (this.drawFPS) {
      this.ctx.textBaseline = 'top';
      this.ctx.textAlign = 'end';
      this.ctx.fillStyle = '#888';
      this.ctx.fillText(
        `${this.workTime}ms - ${formatSize(this.memsize)}${this.image.width}x${
          this.image.height
        } - ${this.fps} FPS - ${this.getStats()}`,
        this.size.clientWidth - 5,
        5
      );
    }
  }
}
<|endoftext|>


<commit_before>const path = require('path');

module.exports = function (config) {
  // This is the default webpack config defined in the `../webpack.config.js`
  // modify as you need.

  config.module.loaders.push({
    test: /\.styl$/,
    loader: 'style-loader!css-loader!stylus-loader'
  });
  config.module.loaders.push({
    test: /\.(png|ttf|svg|jpg|gif)/,
    loader: 'url?limit=8192'
  });
  config.module.loaders.push({
    test: /\.(woff|woff2|eot)/,
    loader: 'url?limit=100000'
  });

console.log(process.env.NODE_ENV);
  if (process.env.NODE_ENV === 'production') {
	  config.module.loaders.push({
	    test: /\.jsx?$/,
	    loader: 'babel',
	    exclude: path.join(__dirname, '../../node_modules/')
	  });

    config.target = 'node';
    config.entry = path.join(__dirname, '../../src/components/index.js');
    config.output = {
      path: './dist',
      filename: 'index.js',
      library: true,
      libraryTarget: 'commonjs2'
    };
  }

  return config;
};
<commit_msg>Linting<commit_after>const path = require('path');

module.exports = function (config) {
  // This is the default webpack config defined in the `../webpack.config.js`
  // modify as you need.

  config.module.loaders.push({
    test: /\.styl$/,
    loader: 'style-loader!css-loader!stylus-loader'
  });
  config.module.loaders.push({
    test: /\.(png|ttf|svg|jpg|gif)/,
    loader: 'url?limit=8192'
  });
  config.module.loaders.push({
    test: /\.(woff|woff2|eot)/,
    loader: 'url?limit=100000'
  });

  if (process.env.NODE_ENV === 'production') {
    config.module.loaders.push({
      test: /\.jsx?$/,
      loader: 'babel',
      exclude: path.join(__dirname, '../../node_modules/')
    });

    config.target = 'node';
    config.entry = path.join(__dirname, '../../src/components/index.js');
    config.output = {
      path: './dist',
      filename: 'index.js',
      library: true,
      libraryTarget: 'commonjs2'
    };
  }

  return config;
};
<|endoftext|>


<commit_before>'use strict'
const AWS = require('aws-sdk');
const promise = require('promise');
const rp = require('request-promise');

const USERDATA_URI = 'https://raw.githubusercontent.com/hhvm/packaging/master/ng/aws/userdata/make-source-tarball.sh';

function make_source_tarball(event, user_data, callback) {
  if (!(
    event.version &&
    event.source &&
    event.source.bucket &&
    event.source.path
  )) {
    callback("Need version and source on input");
    return;
  }

  user_data =
    "#!/bin/bash\n"+
    "VERSION="+event.version+"\n"+
    "IS_NIGHTLY="+(event.nightly ? "true" : "false")+"\n"+
    "S3_BUCKET="+event.source.bucket+"\n"+
    "S3_PATH="+event.source.path+"\n"+
    user_data;

  const params = {
    ImageId: /* ubuntu 16.04 */ 'ami-6e1a0117',
    MaxCount: 1,
    MinCount: 1,
    InstanceType: 't2.micro',
    SecurityGroups: [ 'hhvm-binary-package-builders' ],
    InstanceInitiatedShutdownBehavior: 'terminate',
    IamInstanceProfile: { Arn: 'arn:aws:iam::223121549624:instance-profile/hhvm-binary-package-builder' },
    KeyName: "hhvm-package-builders",
    TagSpecifications: [
      {
        ResourceType: 'instance',
        Tags: [{
          Key: 'Name',
          Value: 'hhvm-build-'+event.version+'-source-tarball'
        }]
      }
    ],
    UserData: (new Buffer(user_data)).toString('base64')
  };

  const ec2 = new AWS.EC2();
  ec2.runInstances(params, function(err, data) {
    if (err) {
      callback(err, 'failed to schedule instance');
    } else {
      event.instances = data.Instances.map(instance => instance.InstanceId);
      callback(null, event);
    }
  });
}

exports.handler = (event, context, callback) => {
  rp(USERDATA_URI)
  .then(function(response) {
    make_source_tarball(event, response, callback);
  })
  .done();
};
<commit_msg>use a new IAM profile for source tarballs<commit_after>'use strict'
const AWS = require('aws-sdk');
const promise = require('promise');
const rp = require('request-promise');

const USERDATA_URI = 'https://raw.githubusercontent.com/hhvm/packaging/master/ng/aws/userdata/make-source-tarball.sh';

function make_source_tarball(event, user_data, callback) {
  if (!(
    event.version &&
    event.source &&
    event.source.bucket &&
    event.source.path
  )) {
    callback("Need version and source on input");
    return;
  }

  user_data =
    "#!/bin/bash\n"+
    "VERSION="+event.version+"\n"+
    "IS_NIGHTLY="+(event.nightly ? "true" : "false")+"\n"+
    "S3_BUCKET="+event.source.bucket+"\n"+
    "S3_PATH="+event.source.path+"\n"+
    user_data;

  const params = {
    ImageId: /* ubuntu 16.04 */ 'ami-6e1a0117',
    MaxCount: 1,
    MinCount: 1,
    InstanceType: 't2.micro',
    SecurityGroups: [ 'hhvm-binary-package-builders' ],
    InstanceInitiatedShutdownBehavior: 'terminate',
    IamInstanceProfile: { Arn: 'arn:aws:iam::223121549624:instance-profile/hhvm-source-tarball-builder' },
    KeyName: "hhvm-package-builders",
    TagSpecifications: [
      {
        ResourceType: 'instance',
        Tags: [{
          Key: 'Name',
          Value: 'hhvm-build-'+event.version+'-source-tarball'
        }]
      }
    ],
    UserData: (new Buffer(user_data)).toString('base64')
  };

  const ec2 = new AWS.EC2();
  ec2.runInstances(params, function(err, data) {
    if (err) {
      callback(err, 'failed to schedule instance');
    } else {
      event.instances = data.Instances.map(instance => instance.InstanceId);
      callback(null, event);
    }
  });
}

exports.handler = (event, context, callback) => {
  rp(USERDATA_URI)
  .then(function(response) {
    make_source_tarball(event, response, callback);
  })
  .done();
};
<|endoftext|>


<commit_before>
import {
  OutlinedLeaf,
  SolidLeaf,
  StripedLeaf,
  Logo,
} from "../components/leaves";

import {
  Stats,
  Leaves,
  Image,
  Body,
} from "../components/layout";

import FitText from "../components/fit-text";
import List from "../components/list";

const kidspringNumbers = [
  { count: "6,366", label: "Average Weekely Attendance" },
  { count: "13,344", label: "First Timers" },
];

const KidSpring = () => (

      <Stats>
        <FitText compressor={1.5}>

            Each week in 2015, an average of

        </FitText>

        <FitText compressor={0.3}>

            6,366

        </FitText>

        <FitText compressor={0.25}>

            Kids

        </FitText>

        <FitText compressor={1.5}>

          heard about Jesus on their level

        </FitText>
      </Stats>

      <Leaves>
        <SolidLeaf
          className="locked-bottom locked-right"
          size="200px"
          color="text-secondary"
          style={{
            transform: "rotate(-225deg)",
            marginBottom: "-50px",
            marginRight: "-150px",
          }}
        />
        <SolidLeaf
          className="locked-bottom locked-right"
          size="130px"
          color="text-tertiary"
          style={{
            transform: "rotate(-270deg)",
            marginBottom: "-100px",
            marginRight: "-10px",
          }}
        />
        <StripedLeaf
          className="locked-bottom locked-right"
          size="90px"
          color="text-tertiary"
          style={{
            transform: "rotate(180deg)",
            marginBottom: "60px",
            marginRight: "-20px",
          }}
        />

        <SolidLeaf
          className="locked-bottom locked-left"
          size="250px"
          color="text-secondary"
          style={{
            transform: "rotate(-135deg)",
            marginBottom: "-90px",
            marginLeft: "-150px",
          }}
        />

        <StripedLeaf
          className="locked-bottom locked-left"
          size="120px"
          color="text-tertiary"
          style={{
            transform: "rotate(-90deg)",
            marginBottom: "-20px",
            marginLeft: "0px",
          }}
        />

      </Leaves>

        <Image url="//s3.amazonaws.com/ns.assets/apollos/annual+report/2016.annualreport-10.jpg" />

              She wanted to know she would spend eternity with Jesus.

            "Easter 2015 was special for me because I was able to lead my daughter, who is 7, in a prayer of salvation at home that night while we were getting ready for bed. It all stemmed from what she heard at church that day. I was so thankful for the story that KidSpring shared because I knew it was on her level where she understood it, and she knew from the service she wanted to know she would spend eternity with Jesus."

            Jada and Ava Barnette, Greenville Campus

KidSpring:

Meeting Jesus on Their Level

    <List items={kidspringNumbers} />

);

export default KidSpring;
<commit_msg>lint celebrate kidspring<commit_after>
import {
  SolidLeaf,
  StripedLeaf,
} from "../components/leaves";

import {
  Stats,
  Leaves,
  Image,
  Body,
} from "../components/layout";

import FitText from "../components/fit-text";
import List from "../components/list";

const kidspringNumbers = [
  { count: "6,366", label: "Average Weekely Attendance" },
  { count: "13,344", label: "First Timers" },
];

/* eslint-disable max-len */
const KidSpring = () => (

      <Stats>
        <FitText compressor={1.5}>

            Each week in 2015, an average of

        </FitText>

        <FitText compressor={0.3}>

              6,366

        </FitText>

        <FitText compressor={0.25}>

              Kids

        </FitText>

        <FitText compressor={1.5}>

            heard about Jesus on their level

        </FitText>
      </Stats>

      <Leaves>
        <SolidLeaf
          className="locked-bottom locked-right"
          size="200px"
          color="text-secondary"
          style={{
            transform: "rotate(-225deg)",
            marginBottom: "-50px",
            marginRight: "-150px",
          }}
        />
        <SolidLeaf
          className="locked-bottom locked-right"
          size="130px"
          color="text-tertiary"
          style={{
            transform: "rotate(-270deg)",
            marginBottom: "-100px",
            marginRight: "-10px",
          }}
        />
        <StripedLeaf
          className="locked-bottom locked-right"
          size="90px"
          color="text-tertiary"
          style={{
            transform: "rotate(180deg)",
            marginBottom: "60px",
            marginRight: "-20px",
          }}
        />

        <SolidLeaf
          className="locked-bottom locked-left"
          size="250px"
          color="text-secondary"
          style={{
            transform: "rotate(-135deg)",
            marginBottom: "-90px",
            marginLeft: "-150px",
          }}
        />

        <StripedLeaf
          className="locked-bottom locked-left"
          size="120px"
          color="text-tertiary"
          style={{
            transform: "rotate(-90deg)",
            marginBottom: "-20px",
            marginLeft: "0px",
          }}
        />

      </Leaves>

        <Image url="//s3.amazonaws.com/ns.assets/apollos/annual+report/2016.annualreport-10.jpg" />

              She wanted to know she would spend eternity with Jesus.

            "Easter 2015 was special for me because I was able to lead my daughter, who is 7, in a prayer of salvation at home that night while we were getting ready for bed. It all stemmed from what she heard at church that day. I was so thankful for the story that KidSpring shared because I knew it was on her level where she understood it, and she knew from the service she wanted to know she would spend eternity with Jesus."

            Jada and Ava Barnette, Greenville Campus

KidSpring:

Meeting Jesus on Their Level

      <List items={kidspringNumbers} />

);
/* eslint-enable max-len */

export default KidSpring;
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var should = require('../')
  , assert = require('assert');

function err(fn, msg) {
  try {
    fn();
    should.fail('expected an error');
  } catch (err) {
    should.equal(msg, err.message);
  }
}

describe('should', function() {
  it('test double require', function() {
    require('../').should.equal(should);
  });

  it('test assertion', function() {
    'test'.should.be.a.String;
    should.equal('foo', 'foo');
  });

  it('test .expected and .actual', function() {
    try {
      'foo'.should.equal('bar');
    } catch (err) {
      assert('foo' == err.actual, 'err.actual');
      assert('bar' == err.expected, 'err.expected');
    }
  });

  it('test chaining', function() {
    var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'] };

    user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');

    user.should.have.ownProperty('name')
      .which.not.have.length(3)
        .and.be.equal('tj');
  });

  it('test proxy shield getters', function() {
    if(typeof Proxy == 'function') {
      err(function() {
        'abc'.should.be.string;
      }, 'Assertion has no property string');
    }
  });
});
<commit_msg>Remove proxy test<commit_after>
/**
 * Module dependencies.
 */

var should = require('../')
  , assert = require('assert');

function err(fn, msg) {
  try {
    fn();
    should.fail('expected an error');
  } catch (err) {
    should.equal(msg, err.message);
  }
}

describe('should', function() {
  it('test double require', function() {
    require('../').should.equal(should);
  });

  it('test assertion', function() {
    'test'.should.be.a.String;
    should.equal('foo', 'foo');
  });

  it('test .expected and .actual', function() {
    try {
      'foo'.should.equal('bar');
    } catch (err) {
      assert('foo' == err.actual, 'err.actual');
      assert('bar' == err.expected, 'err.expected');
    }
  });

  it('test chaining', function() {
    var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'] };

    user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');

    user.should.have.ownProperty('name')
      .which.not.have.length(3)
        .and.be.equal('tj');
  });
});
<|endoftext|>