<commit_before>function clearField(input) {
	if (input) {
	  input.value = "";
	}
};

function remove_post(key) {
	if (confirm("Are you sure?")) {
		var firebase_ref = firebase.database().ref().child("Posts").child(key);
	  firebase_ref.child("comments").once('value').then(function(snapshot) {
	    // console.log(snapshot.val());
	    for (var i in snapshot.val()) {
	      firebase.database().ref().child("Comments").child(i).remove();
	    }
	  });
		firebase_ref.remove();
	  // var firebase_comments = firebase.database().ref().child("Comments");
		// how to remove the html depends on whether we want it to refresh or not
		window.location.replace("main.html");
	}
};

window.onload = function() {

	var data = [];

  firebase.database().ref("Tags").on("child_added", snap => {
    data.push({ id: data.length, text: snap.child("company").val() });
    $("#selectBox").select2({
  		width: '100%',
  		data: data,
  		placeholder: "Tags",
  		allowclear: true,
  	});
  });

	/*
	 * Switching tabs
	 */

 // var ref = firebase.database().ref();
 // var authData = ref.getAuth();
 // if (authData) {
 //   console.log("Authenticated user with uid:", authData.uid);
 // }
 //  console.log(curr_user);
 var curr_user;
 firebase.auth().onAuthStateChanged(user => {
 	if (user){
 		console.log(user.uid);
 		curr_user = user.uid;
		firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
			console.log(snapshot.child("user").val());
			var tags = snapshot.child("tags").val();
			var tags_string = "";
			for (var i = 0; i < snapshot.child("tags").numChildren() - 1; i++) {
				tags_string += data[snapshot.child("tags").child(i).val()]['text'] + ", ";
			}
			if (snapshot.child("tags").numChildren() > 0) {
				tags_string += data[snapshot.child("tags").child(snapshot.child("tags").numChildren() - 1).val()]['text'];
			}
			// console.log(snapshot.val());
			var commentHTML = document.getElementById("comment");
			var commentTA = document.getElementById("comment_text");
			var user_li = document.createElement("li");
			user_li.addEventListener('click', function(e) {
				commentHTML.innerHTML = "";
				commentTA.value = "";
				window.scrollTo(0, 0);
				document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
				document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
				document.getElementById("msg_info").style.display = "block";
				outer_wrap.style.webkitFilter = "blur(3px)";
				document.getElementById("post_id").value = snapshot.key;
				//
				firebase.database().ref("Comments").off();
				firebase.database().ref("Comments").orderByChild("post").equalTo(snapshot.key).on("child_added", function(snapshot) {
					commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
				});
			}, false);
			// console.log(snapshot.key);
			user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
			document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
		});

		firebase_ref.child("Posts").on('child_removed', snap => {
			$("#" + snap.key).remove();
		});

		var logout = document.getElementById("logout");
		logout.addEventListener('click', e => {
			firebase.auth().signOut();
		});

 	} else {
 		window.location.replace("index.html");
 	}
 });

 // console.log(window.user);
  // console.log(window.user);
  // console.log(curr_user);
	// console.log(curr_user);
	var arr = document.getElementsByClassName("nav_el");
	var names = ["post", "announcement", "meeting", "user"];
	var last_active = 0;

	for (var i = arr.length-1; i >=0; --i) {
		arr[i].onclick = function() {
			arr[last_active].classList.remove("nav_active");
			document.getElementById(names[last_active]).style.display = "none";
			last_active = this.getAttribute('value');
			document.getElementById(names[this.getAttribute('value')]).style.display = "block";
			this.className += " nav_active";
		}
	}

	/*
	 * Add post functionality
	 */

	var add = document.getElementById("add");
	var add_wrap = document.getElementById("add_wrap");
	var outer_wrap = document.getElementById("outer_wrap");
	var add_exit = document.getElementById("add_exit");
	add.onclick = function() {
		add_wrap.style.display = "block";
		outer_wrap.style.webkitFilter = "blur(3px)";
	}
	add_exit.onclick = function() {
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
	}

	/*
	 *
	 * Database stuff
	 *
	 */

	/*
	 * Sending stuff to Firebase
	 */

	var firebase_ref = firebase.database().ref();
	var submit = document.getElementById("add_submit");
	submit.onclick = function() {
		var add_title = document.getElementById("add_title").value;
		var add_text = document.getElementById("add_text").value;
		var add_select = document.getElementById("add_select").value;
		var add_tags = $("#selectBox").val();
		console.log(curr_user);
		firebase_ref.child("Posts").push().set({
	    title: add_title,
	    text: add_text,
	    select: add_select,
			tags: add_tags,
			user: curr_user,
	  });

	  // Clear
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
		clearField(document.getElementById("add_title"));
		clearField(document.getElementById("add_text"));
		clearField(document.getElementById("add_tags"));
	}

  var comment_submit = document.getElementById("comment_submit");
  comment_submit.onclick = function() {
    var add_comment = document.getElementById("comment_text").value;
    var post_key = document.getElementById("post_id").value;
    var new_key = firebase_ref.child("Posts").child(post_key).child("comments").push(true).getKey();
    firebase_ref.child("Comments").child(new_key).set({
      post: post_key,
      comment: add_comment
    });
    document.getElementById("comment_text").value = "";
  };

	/*
	 * Receiving data
	 */

	// Triggers when a value changes
	// Receive snapshot which includes whole list of posts
	// firebase_ref.child("Comments").on('child_added', snap => {
  //   var post_key = snap.child("post");
  //   if (post_key.val() == document.getElementById("post_id").value) {
  //     var comments = document.getElementById("comment");
  //     // comments.innerHTML = "";
  //     comments.innerHTML += snap.child("comment").val() + "\n";
  //     // console.log(snap.val());
  //   }
	// });

  // function update_comments(snap) {
  //   var comments = snap.child("comments").val();
  //   var commentHTML = document.getElementById("comment");
  //   commentHTML.innerHTML = "";
  //   for (var key in comments) {
  //     firebase_ref.child("Comments").child(key).child("comment").once('value').then(function(snapshot) {
  //       commentHTML.innerHTML += "

" + snapshot.val() + "

";
  //     });
  //   }
  // }

	// Triggers when a post is added
	// Receive a snap which is one post
	firebase_ref.child("Posts").on('child_added', snap => {
		var title = snap.child("title").val();
		var text = snap.child("text").val();
		var select = snap.child("select").val();
		var tags = snap.child("tags").val();
    var user = snap.child("user").val();
		// console.log(tags);
		var tags_string = "";
		for (var i = 0; i < snap.child("tags").numChildren() - 1; i++) {
			tags_string += data[snap.child("tags").child(i).val()]['text'] + ", ";
		}
		if (snap.child("tags").numChildren() > 0) {
			tags_string += data[snap.child("tags").child(snap.child("tags").numChildren() - 1).val()]['text'];
		}
    var commentHTML = document.getElementById("comment");
    var commentTA = document.getElementById("comment_text");

		/********************************************************/

		// var posts_ref = firebase.database().ref("Posts");
		// var user_li = document.createElement("li");
		// firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
    //   console.log(snapshot.val());
		// 	user_li.addEventListener('click', function(e) {
    //     commentHTML.innerHTML = "";
    //     commentTA.value = "";
		// 		window.scrollTo(0, 0);
		// 		document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
		// 		document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
		// 		document.getElementById("msg_info").style.display = "block";
		// 		outer_wrap.style.webkitFilter = "blur(3px)";
    //     document.getElementById("post_id").value = snap.key;
		// 	}, false);
    //   // // console.log(title);
		// 	user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
    //   document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
		// });
		/***********************************************************/

		if (select != "post") {
			var new_msg = document.createElement("li");
			new_msg.addEventListener('click', function(e) {
        commentHTML.innerHTML = "";
        commentTA.value = "";
				window.scrollTo(0, 0);
				document.getElementById("msg_info_title").innerHTML = title;
				document.getElementById("msg_info_text").innerHTML = text;
				document.getElementById("msg_info").style.display = "block";
				outer_wrap.style.webkitFilter = "blur(3px)";
        document.getElementById("post_id").value = snap.key;
        // update_comments(snap);
        firebase.database().ref("Comments").off();
        firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
          commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
        });
			}, false);
      if (user == curr_user) {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
        var but = document.createElement("button");
        but.addEventListener('click', function(e) {
        	remove_post(snap.key);
        	e.stopPropagation();
        }, false);
        but.className += "remove_post";
        but.innerHTML = "";
        new_msg.appendChild(but);
      } else {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
      }
      document.getElementById(select).insertBefore(new_msg, document.getElementById(select).firstChild);
		}
		var new_msg = document.createElement("li");
		new_msg.addEventListener('click', function(e) {
      commentHTML.innerHTML = "";
      commentTA.value = "";
			window.scrollTo(0, 0);
			document.getElementById("msg_info_title").innerHTML = title;
			document.getElementById("msg_info_text").innerHTML = text;
			document.getElementById("msg_info").style.display = "block";
			outer_wrap.style.webkitFilter = "blur(3px)";
      document.getElementById("post_id").value = snap.key;
      // update_comments(snap);
      firebase.database().ref("Comments").off();
      firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
        commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
      });
		}, false);
    if (user == curr_user) {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
      var but = document.createElement("button");
      but.addEventListener('click', function(e) {
      	remove_post(snap.key);
      	e.stopPropagation();
      }, false);
      but.className += "remove_post";
      but.innerHTML = "";
      new_msg.appendChild(but);
    } else {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
    }
		document.getElementById("post").insertBefore(new_msg, document.getElementById("post").firstChild);
	});

	/*
	 * Shifting return
	 */
	document.getElementById("msg_info_return").onclick = function() {
		document.getElementById("msg_info").style.display = "none";
		outer_wrap.style.webkitFilter = "";
		window.scrollTo(0, 0);
	};

}
<commit_msg>user tags<commit_after>function clearField(input) {
	if (input) {
	  input.value = "";
	}
};

function remove_post(key) {
	if (confirm("Are you sure?")) {
		var firebase_ref = firebase.database().ref().child("Posts").child(key);
	  firebase_ref.child("comments").once('value').then(function(snapshot) {
	    // console.log(snapshot.val());
	    for (var i in snapshot.val()) {
	      firebase.database().ref().child("Comments").child(i).remove();
	    }
	  });
		firebase_ref.remove();
	  // var firebase_comments = firebase.database().ref().child("Comments");
		// how to remove the html depends on whether we want it to refresh or not
		window.location.replace("main.html");
	}
};

window.onload = function() {

	var data = [];

  firebase.database().ref("Tags").on("child_added", snap => {
    data.push({ id: data.length, text: snap.child("company").val() });
    $("#selectBox").select2({
  		width: '100%',
  		data: data,
  		placeholder: "Tags",
  		allowclear: true,
  	});
  });

	/*
	 * Switching tabs
	 */

 // var ref = firebase.database().ref();
 // var authData = ref.getAuth();
 // if (authData) {
 //   console.log("Authenticated user with uid:", authData.uid);
 // }
 //  console.log(curr_user);
 var curr_user;
 firebase.auth().onAuthStateChanged(user => {
 	if (user){
 		console.log(user.uid);
 		curr_user = user.uid;
		var user_li = document.createElement("li");
		firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
			console.log(snapshot.child("user").val());
			var tags = snapshot.child("tags").val();
			var tags_string = "";
			for (var i = 0; i < snapshot.child("tags").numChildren() - 1; i++) {
				tags_string += data[snapshot.child("tags").child(i).val()]['text'] + ", ";
			}
			if (snapshot.child("tags").numChildren() > 0) {
				tags_string += data[snapshot.child("tags").child(snapshot.child("tags").numChildren() - 1).val()]['text'];
			}
			// console.log(snapshot.val());
			var commentHTML = document.getElementById("comment");
			var commentTA = document.getElementById("comment_text");
			user_li.addEventListener('click', function(e) {
				commentHTML.innerHTML = "";
				commentTA.value = "";
				window.scrollTo(0, 0);
				document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
				document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
				document.getElementById("msg_info").style.display = "block";
				outer_wrap.style.webkitFilter = "blur(3px)";
				document.getElementById("post_id").value = snapshot.key;
				//
				firebase.database().ref("Comments").off();
				firebase.database().ref("Comments").orderByChild("post").equalTo(snapshot.key).on("child_added", function(snapshot) {
					commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
				});
			}, false);
			// console.log(snapshot.key);
			user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
			document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
		});

			var tag_li = document.createElement("li");
			firebase.database().ref("Posts").on("child_added", function(snapshot) {
				console.log(snapshot.child("user").val());
				var current_user_company;
				firebase.database().ref("Users/" + curr_user + "/company").once("value", function(snap) {
						current_user_company = snap.val();
						checkRest(snapshot);
					});
			});
				function checkRest(snapshot) {
					var tags = snapshot.child("tags").val();
					var tags_string = "";
					var is_tagged = false;
					for (var i = 0; i < snapshot.child("tags").numChildren() - 1; i++) {
						if(current_user_company == data[snapshot.child("tags").child(i).val()]['text']) {
							is_tagged = true;
						}
						tags_string += data[snapshot.child("tags").child(i).val()]['text'] + ", ";
					}
					if (snapshot.child("tags").numChildren() > 0) {
						if(current_user_company == data[snapshot.child("tags").child(snapshot.child("tags").numChildren() - 1).val()]['text']) {
							is_tagged = true;
						}
						tags_string += data[snapshot.child("tags").child(snapshot.child("tags").numChildren() - 1).val()]['text'];
					}
					// console.log(snapshot.val());
					var commentHTML = document.getElementById("comment");
					var commentTA = document.getElementById("comment_text");
					tag_li.addEventListener('click', function(e) {
						commentHTML.innerHTML = "";
						commentTA.value = "";
						window.scrollTo(0, 0);
						document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
						document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
						document.getElementById("msg_info").style.display = "block";
						outer_wrap.style.webkitFilter = "blur(3px)";
						document.getElementById("post_id").value = snapshot.key;
						//
						firebase.database().ref("Comments").off();
						firebase.database().ref("Comments").orderByChild("post").equalTo(snapshot.key).on("child_added", function(snapshot) {
							commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
						});
					}, false);
				// console.log(snapshot.key);
					tag_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
					if(tag_li.innerHTML != user_li.innerHTML) {
						document.getElementById("user").insertBefore(tag_li, document.getElementById("user").firstChild);
					}
			}

		firebase_ref.child("Posts").on('child_removed', snap => {
			$("#" + snap.key).remove();
		});

		var logout = document.getElementById("logout");
		logout.addEventListener('click', e => {
			firebase.auth().signOut();
		});

 	} else {
 		window.location.replace("index.html");
 	}
 });

 // console.log(window.user);
  // console.log(window.user);
  // console.log(curr_user);
	// console.log(curr_user);
	var arr = document.getElementsByClassName("nav_el");
	var names = ["post", "announcement", "meeting", "user"];
	var last_active = 0;

	for (var i = arr.length-1; i >=0; --i) {
		arr[i].onclick = function() {
			arr[last_active].classList.remove("nav_active");
			document.getElementById(names[last_active]).style.display = "none";
			last_active = this.getAttribute('value');
			document.getElementById(names[this.getAttribute('value')]).style.display = "block";
			this.className += " nav_active";
		}
	}

	/*
	 * Add post functionality
	 */

	var add = document.getElementById("add");
	var add_wrap = document.getElementById("add_wrap");
	var outer_wrap = document.getElementById("outer_wrap");
	var add_exit = document.getElementById("add_exit");
	add.onclick = function() {
		add_wrap.style.display = "block";
		outer_wrap.style.webkitFilter = "blur(3px)";
	}
	add_exit.onclick = function() {
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
	}

	/*
	 *
	 * Database stuff
	 *
	 */

	/*
	 * Sending stuff to Firebase
	 */

	var firebase_ref = firebase.database().ref();
	var submit = document.getElementById("add_submit");
	submit.onclick = function() {
		var add_title = document.getElementById("add_title").value;
		var add_text = document.getElementById("add_text").value;
		var add_select = document.getElementById("add_select").value;
		var add_tags = $("#selectBox").val();
		console.log(curr_user);
		firebase_ref.child("Posts").push().set({
	    title: add_title,
	    text: add_text,
	    select: add_select,
			tags: add_tags,
			user: curr_user,
	  });

	  // Clear
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
		clearField(document.getElementById("add_title"));
		clearField(document.getElementById("add_text"));
		clearField(document.getElementById("add_tags"));
	}

  var comment_submit = document.getElementById("comment_submit");
  comment_submit.onclick = function() {
    var add_comment = document.getElementById("comment_text").value;
    var post_key = document.getElementById("post_id").value;
    var new_key = firebase_ref.child("Posts").child(post_key).child("comments").push(true).getKey();
    firebase_ref.child("Comments").child(new_key).set({
      post: post_key,
      comment: add_comment
    });
    document.getElementById("comment_text").value = "";
  };

	/*
	 * Receiving data
	 */

	// Triggers when a value changes
	// Receive snapshot which includes whole list of posts
	// firebase_ref.child("Comments").on('child_added', snap => {
  //   var post_key = snap.child("post");
  //   if (post_key.val() == document.getElementById("post_id").value) {
  //     var comments = document.getElementById("comment");
  //     // comments.innerHTML = "";
  //     comments.innerHTML += snap.child("comment").val() + "\n";
  //     // console.log(snap.val());
  //   }
	// });

  // function update_comments(snap) {
  //   var comments = snap.child("comments").val();
  //   var commentHTML = document.getElementById("comment");
  //   commentHTML.innerHTML = "";
  //   for (var key in comments) {
  //     firebase_ref.child("Comments").child(key).child("comment").once('value').then(function(snapshot) {
  //       commentHTML.innerHTML += "

" + snapshot.val() + "

";
  //     });
  //   }
  // }

	// Triggers when a post is added
	// Receive a snap which is one post
	firebase_ref.child("Posts").on('child_added', snap => {
		var title = snap.child("title").val();
		var text = snap.child("text").val();
		var select = snap.child("select").val();
		var tags = snap.child("tags").val();
    var user = snap.child("user").val();
		// console.log(tags);
		var tags_string = "";
		for (var i = 0; i < snap.child("tags").numChildren() - 1; i++) {
			tags_string += data[snap.child("tags").child(i).val()]['text'] + ", ";
		}
		if (snap.child("tags").numChildren() > 0) {
			tags_string += data[snap.child("tags").child(snap.child("tags").numChildren() - 1).val()]['text'];
		}
    var commentHTML = document.getElementById("comment");
    var commentTA = document.getElementById("comment_text");

		/********************************************************/

		// var posts_ref = firebase.database().ref("Posts");
		// var user_li = document.createElement("li");
		// firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
    //   console.log(snapshot.val());
		// 	user_li.addEventListener('click', function(e) {
    //     commentHTML.innerHTML = "";
    //     commentTA.value = "";
		// 		window.scrollTo(0, 0);
		// 		document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
		// 		document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
		// 		document.getElementById("msg_info").style.display = "block";
		// 		outer_wrap.style.webkitFilter = "blur(3px)";
    //     document.getElementById("post_id").value = snap.key;
		// 	}, false);
    //   // // console.log(title);
		// 	user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
    //   document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
		// });
		/***********************************************************/

		if (select != "post") {
			var new_msg = document.createElement("li");
			new_msg.addEventListener('click', function(e) {
        commentHTML.innerHTML = "";
        commentTA.value = "";
				window.scrollTo(0, 0);
				document.getElementById("msg_info_title").innerHTML = title;
				document.getElementById("msg_info_text").innerHTML = text;
				document.getElementById("msg_info").style.display = "block";
				outer_wrap.style.webkitFilter = "blur(3px)";
        document.getElementById("post_id").value = snap.key;
        // update_comments(snap);
        firebase.database().ref("Comments").off();
        firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
          commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
        });
			}, false);
      if (user == curr_user) {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
        var but = document.createElement("button");
        but.addEventListener('click', function(e) {
        	remove_post(snap.key);
        	e.stopPropagation();
        }, false);
        but.className += "remove_post";
        but.innerHTML = "";
        new_msg.appendChild(but);
      } else {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
      }
      document.getElementById(select).insertBefore(new_msg, document.getElementById(select).firstChild);
		}
		var new_msg = document.createElement("li");
		new_msg.addEventListener('click', function(e) {
      commentHTML.innerHTML = "";
      commentTA.value = "";
			window.scrollTo(0, 0);
			document.getElementById("msg_info_title").innerHTML = title;
			document.getElementById("msg_info_text").innerHTML = text;
			document.getElementById("msg_info").style.display = "block";
			outer_wrap.style.webkitFilter = "blur(3px)";
      document.getElementById("post_id").value = snap.key;
      // update_comments(snap);
      firebase.database().ref("Comments").off();
      firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
        commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
      });
		}, false);
    if (user == curr_user) {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
      var but = document.createElement("button");
      but.addEventListener('click', function(e) {
      	remove_post(snap.key);
      	e.stopPropagation();
      }, false);
      but.className += "remove_post";
      but.innerHTML = "";
      new_msg.appendChild(but);
    } else {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
    }
		document.getElementById("post").insertBefore(new_msg, document.getElementById("post").firstChild);
	});

	/*
	 * Shifting return
	 */
	document.getElementById("msg_info_return").onclick = function() {
		document.getElementById("msg_info").style.display = "none";
		outer_wrap.style.webkitFilter = "";
		window.scrollTo(0, 0);
	};

}
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var config = require('config-lite');
var bodyParser = require('body-parser');
var routes = require('./routes');
var pkg = require('./package');
var passport = require('passport');

var app = express();

// 设置模板目录
app.set('views', path.join(__dirname, 'views'));
// 设置模板引擎为 ejs
app.set('view engine', 'ejs');

// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());

// API
var apiV1 = require('./api/v1');
apiV1(app);

// session 中间件
app.use(session({
  name: config.session.key,// 设置 cookie 中保存 session id 的字段名称
  secret: config.session.secret,// 通过设置 secret 来计算 hash 值并放在 cookie 中，使产生的 signedCookie 防篡改
  cookie: {
    maxAge: config.session.maxAge// 过期时间，过期后 cookie 中的 session id 自动删除
  },
  store: new MongoStore({// 将 session 存储到 mongodb
    url: config.mongodb// mongodb 地址
  })
}));

// flash 中间价，用来显示通知
app.use(flash());

// 处理表单及文件上传的中间件
app.use(require('express-formidable')({
  uploadDir: path.join(__dirname, 'public/images'),// 上传文件目录
  keepExtensions: true// 保留后缀
}));

// 设置模板全局常量
app.locals.website = {
  title: "DayCache",
  description: "A missing diary taking website."
};

// 添加模板必需的三个变量
app.use(function (req, res, next) {
  res.locals.user = req.session.user;
  res.locals.success = req.flash('success').toString();
  res.locals.error = req.flash('error').toString();
  next();
});

// 路由
routes(app);

// 监听端口，启动程序
app.listen(config.port, function () {
  console.log(`${pkg.name} listening on port ${config.port}`);
});

// 捕获 404 并定向到错误处理
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// 开发环境下的错误处理
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {

    res.status(err.status || 500);
    // 如果 path 包含 'api' 会返回 json
    if (req.path.includes('api')) {
      return res.json( {
        status: {
          code: err.status,
          message: err.message
        },
        data: { }
      });
    }

    res.render('error', {
      message: err.message,
      error: err,
    });
  });
}

// 生产环境下的错误处理
app.use(function(err, req, res, next) {
  // 设置响应状态
  res.status(err.status || 500);

  if (req.path.includes('api')) {
    return res.json( {
      status: {
        code: err.status,
        message: err.message
      },
      data: { }
    });
  }

  // 渲染错误处理页
  res.render('error', {
    message: err.message,
    error: {},
  });
});
<commit_msg>Better API Version<commit_after>var path = require('path');
var express = require('express');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var config = require('config-lite');
var bodyParser = require('body-parser');
var routes = require('./routes');
var pkg = require('./package');
var passport = require('passport');

var app = express();

// 设置模板目录
app.set('views', path.join(__dirname, 'views'));
// 设置模板引擎为 ejs
app.set('view engine', 'ejs');

// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());

/*
  // API
  如果需要新增加一个 API 的版本
  1. 把 ./api/v1 目录复制一份，改名为 v2
  2. 在下面的 API_VERSIONS 字典中加入一对 kv，如 `'Version 2': '/v2'`
  其它的事情就不需要担心啦
 */
var API_VERSIONS = {
  'Version 1': '/v1'
}
for (var v in API_VERSIONS) {
  var api = require('./api' + API_VERSIONS[v]);
  api(app);
}

// session 中间件
app.use(session({
  name: config.session.key,// 设置 cookie 中保存 session id 的字段名称
  secret: config.session.secret,// 通过设置 secret 来计算 hash 值并放在 cookie 中，使产生的 signedCookie 防篡改
  cookie: {
    maxAge: config.session.maxAge// 过期时间，过期后 cookie 中的 session id 自动删除
  },
  store: new MongoStore({// 将 session 存储到 mongodb
    url: config.mongodb// mongodb 地址
  })
}));

// flash 中间价，用来显示通知
app.use(flash());

// 处理表单及文件上传的中间件
app.use(require('express-formidable')({
  uploadDir: path.join(__dirname, 'public/images'),// 上传文件目录
  keepExtensions: true// 保留后缀
}));

// 设置模板全局常量
app.locals.website = {
  title: "DayCache",
  description: "A missing diary taking website."
};

// 添加模板必需的三个变量
app.use(function (req, res, next) {
  res.locals.user = req.session.user;
  res.locals.success = req.flash('success').toString();
  res.locals.error = req.flash('error').toString();
  next();
});

// 路由
routes(app);

// 监听端口，启动程序
app.listen(config.port, function () {
  console.log(`${pkg.name} listening on port ${config.port}`);
});

// 捕获 404 并定向到错误处理
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// 开发环境下的错误处理
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {

    res.status(err.status || 500);
    // 如果 path 包含 'api' 会返回 json
    if (req.path.includes('api')) {
      return res.json( {
        status: {
          code: err.status,
          message: err.message
        },
        data: { }
      });
    }

    res.render('error', {
      message: err.message,
      error: err,
    });
  });
}

// 生产环境下的错误处理
app.use(function(err, req, res, next) {
  // 设置响应状态
  res.status(err.status || 500);

  if (req.path.includes('api')) {
    return res.json( {
      status: {
        code: err.status,
        message: err.message
      },
      data: { }
    });
  }

  // 渲染错误处理页
  res.render('error', {
    message: err.message,
    error: {},
  });
});
<|endoftext|>


<commit_before>const tmi = require("tmi.js"),
const keyHandler = require("./keyHandler.js"),
const config = require("./config.js");

// https://github.com/tmijs/tmi.js#tmijs
// for more options
const client = new tmi.client({
  connection: {
    secure: true,
    reconnect: true,
  },
  channels: [config.channel],
});

const commandRegex =
  config.regexCommands ||
  new RegExp("^(" + config.commands.join("|") + ")$", "i");

client.on("message", function (channel, tags, message, self) {
  let isCorrectChannel = `#${config.channel}` === channel;
  let messageMatches = message.match(commandRegex);

  if (self) return;
  if (isCorrectChannel && messageMatches) {
    // print username and message to console
    console.log(`@${tags.username}: ${message}`);

    // send the message to the emulator
    keyHandler.sendKey(message.toLowerCase());
  }
});

client.addListener("connected", function (address, port) {
  console.log("Connected! Waiting for messages..");
});
client.addListener("disconnected", function (reason) {
  console.log("Disconnected from the server! Reason: " + reason);
});

client.connect();
console.log(`Connecting to /${config.channel}..`);
<commit_msg>typo fix<commit_after>const tmi = require("tmi.js");
const keyHandler = require("./keyHandler.js");
const config = require("./config.js");

// https://github.com/tmijs/tmi.js#tmijs
// for more options
const client = new tmi.client({
  connection: {
    secure: true,
    reconnect: true,
  },
  channels: [config.channel],
});

const commandRegex =
  config.regexCommands ||
  new RegExp("^(" + config.commands.join("|") + ")$", "i");

client.on("message", function (channel, tags, message, self) {
  let isCorrectChannel = `#${config.channel}` === channel;
  let messageMatches = message.match(commandRegex);

  if (self) return;
  if (isCorrectChannel && messageMatches) {
    // print username and message to console
    console.log(`@${tags.username}: ${message}`);

    // send the message to the emulator
    keyHandler.sendKey(message.toLowerCase());
  }
});

client.addListener("connected", function (address, port) {
  console.log("Connected! Waiting for messages..");
});
client.addListener("disconnected", function (reason) {
  console.log("Disconnected from the server! Reason: " + reason);
});

client.connect();
console.log(`Connecting to /${config.channel}..`);
<|endoftext|>


<commit_before>const CharSize=8;
const CharsDict = {};
for(var i=0;i<16;i++){
    CharsDict[i.toString(16)]=i;
}
function parse(guid){
    var chars = guid.toLowerCase().match(/[0-9a-f]/g);
    var numberCharsCount = 0;
    var numbers=[];
    var number=0;
    for(var i=chars.length;i-->0;){
        number<<=4;
        number|=CharsDict[chars[i]];
        numberCharsCount++;

        if(numberCharsCount===8){
            numbers.push(number);
            if(numbers.length===4){
                break;
            }

            number=0;
            numberCharsCount=0;
        }
    }

    while(numbers.length<4){
        numbers.push(0);
    }

    return numbers;
}

module.exports = parse;<commit_msg>Check null for guid<commit_after>const CharSize=8;
const CharsDict = {};
for(var i=0;i<16;i++){
    CharsDict[i.toString(16)]=i;
}
function parse(guid){
    if(!guid)guid='';

    var chars = guid.toLowerCase().match(/[0-9a-f]/g);
    var numberCharsCount = 0;
    var numbers=[];
    var number=0;
    for(var i=chars.length;i-->0;){
        number<<=4;
        number|=CharsDict[chars[i]];
        numberCharsCount++;

        if(numberCharsCount===8){
            numbers.push(number);
            if(numbers.length===4){
                break;
            }

            number=0;
            numberCharsCount=0;
        }
    }

    while(numbers.length<4){
        numbers.push(0);
    }

    return numbers;
}

module.exports = parse;<|endoftext|>


<commit_before>(function ($) {

    function Person(data) {
        _.extend(this, data);
    }
    _.extend(Person.prototype, {

        age: function (date) {
            var birth = this.birth_date;
            if (typeof birth == 'number' || /^c/.test(birth)) {
                birth += '-07-01';
                birth = birth.replace(/^c\s+/, '');
            }
            return moment(date).diff(moment(birth, 'YYYY-MM-DD'), 'd') / 365.2425;
        },

        experience: function (date, includeMayor) {
            var ymd = moment(date).format('YYYY-MM-DD'),
                regexp = new RegExp('Council' + (includeMayor ? '|Mayor' : '')),
                days = 0;
            this.positions.forEach(function (p) {
                if (p.start <= ymd && regexp.test(p.office)) {
                    var end = p.end <= ymd ? moment(p.end, 'YYYY-MM-DD') : moment(date);
                    days += end.diff(moment(p.start, 'YYYY-MM-DD'), 'd');
                }
            });
            return days / 365.2425;
        }
    });

    function Council() {
        _.extend(this, {
            members: [],
            add: [],
            remove: []
        });
    }
    _.extend(Council.prototype, {

        genderCount: function (gender) {
            return this.members.reduce(function (previousValue, currentPerson) {
                if (currentPerson.gender == gender) {
                    previousValue++;
                }
                return previousValue;
            }, 0);
        },

        women: function () {
            return this.genderCount('F');
        },

        men: function () {
            return this.genderCount('M');
        },

        ages: function (date) {
            return this.members.map(function (person) {
                return person.age(date);
            });
        },

        averageAge: function (date) {
            return this.ages(date).reduce(function (previous, current) {
                    return previous + current;
                }, 0) / this.members.length;
        },

        minAge: function (date) {
            return _.min(this.ages(date));
        },

        maxAge: function (date) {
            return _.max(this.ages(date));
        },

        totalExperience: function (date, includeMayor) {
            return this.members.reduce(function (previousValue, currentPerson) {
                return previousValue + currentPerson.experience(date, includeMayor);
            }, 0);
        }
    });

    $.getJSON('data/person.json', process);

    function process(personData) {
        var councils = {},
            members = [];
        _.each(personData, function (data) {
            var person = new Person(data);
            person.positions.forEach(function (p) {
                if (!/Council/.test(p.office)) {
                    return;
                }
                if (p.start) {
                    if (!councils[p.start]) {
                        councils[p.start] = new Council();
                        councils[p.start].date = p.start;
                    }
                    councils[p.start].add.push(person);
                }
                else {
                    throw 'Missing start in ' + person.code;
                }
                if (p.end) {
                    if (!councils[p.end]) {
                        councils[p.end] = new Council();
                        councils[p.end].date = p.end;
                    }
                    councils[p.end].remove.push(person);
                }
            });
        });
        councils = _.pick(councils, _.keys(councils).sort());
        _.each(councils, function (c, date) {
            members = _.union(_.difference(members, c.remove), c.add);
            c.members = members.slice();
        });
        draw(councils);
    }

    function dataRow(council, date) {
        return {
            date: date,
            men: council.men(),
            women: council.women(),
            experience: council.totalExperience(date),
            experienceWithMayor: council.totalExperience(date, true),
            averageAge: council.averageAge(date),
            minAge: council.minAge(date),
            maxAge: council.maxAge(date)
        };
    }

    function draw(councils) {
        var data = [],
            prevCouncil, date, now;
        _.each(councils, function (council, ymd) {
            date = new Date(ymd + 'T12:00');
            if (prevCouncil) {
                data.push(dataRow(prevCouncil, new Date(date.getTime() - 1)));
            }
            data.push(dataRow(council, date));
            prevCouncil = council;
        });
        now = new Date();
        date = moment(prevCouncil.date).add(180, 'd').toDate();
        if (now.getTime() > date.getTime()) {
            date = now;
        }
        data.push(dataRow(prevCouncil, date));
        new Dygraph(
            'women-graph',
            function () {
                return data.map(function (row) {
                    return [row.date, row.men, row.women];
                });
            },
            {
                axes: {
                    x: {
                        valueFormatter: function (millis) {
                            return moment(millis).utc().format('YYYY-MM-DD');
                        }
                    }
                },
                fillGraph: true,
                includeZero: true,
                labels: ['Date', 'Men', 'Women'],
                labelsUTC: true,
                stackedGraph: true,
                title: 'Gender Representation on DC Council'
            }
        );
        new Dygraph(
            'experience-graph',
            function () {
                return data.map(function (row) {
                    return [row.date, row.experience, row.experienceWithMayor];
                });
            },
            {
                axes: {
                    x: {
                        valueFormatter: function (millis) {
                            return moment(millis).utc().format('YYYY-MM-DD');
                        }
                    }
                },
                fillGraph: true,
                labels: ['Date', 'Experience', 'Including Mayoral'],
                labelsUTC: true,
                title: 'Total Years of Experience of DC Council'
            }
        );
        new Dygraph(
            'age-graph',
            function () {
                return data.map(function (row) {
                    return [row.date, row.averageAge, row.minAge, row.maxAge];
                });
            },
            {
                axes: {
                    x: {
                        valueFormatter: function (millis) {
                            return moment(millis).utc().format('YYYY-MM-DD');
                        }
                    }
                },
                fillGraph: true,
                labels: ['Date', 'Average Age', 'Min', 'Max'],
                labelsUTC: true,
                title: 'Average Age of DC Council'
            }
        );
    }

})(jQuery);
<commit_msg>eliminate duplication in graph options<commit_after>(function ($) {

    function Person(data) {
        _.extend(this, data);
    }
    _.extend(Person.prototype, {

        age: function (date) {
            var birth = this.birth_date;
            if (typeof birth == 'number' || /^c/.test(birth)) {
                birth += '-07-01';
                birth = birth.replace(/^c\s+/, '');
            }
            return moment(date).diff(moment(birth, 'YYYY-MM-DD'), 'd') / 365.2425;
        },

        experience: function (date, includeMayor) {
            var ymd = moment(date).format('YYYY-MM-DD'),
                regexp = new RegExp('Council' + (includeMayor ? '|Mayor' : '')),
                days = 0;
            this.positions.forEach(function (p) {
                if (p.start <= ymd && regexp.test(p.office)) {
                    var end = p.end <= ymd ? moment(p.end, 'YYYY-MM-DD') : moment(date);
                    days += end.diff(moment(p.start, 'YYYY-MM-DD'), 'd');
                }
            });
            return days / 365.2425;
        }
    });

    function Council() {
        _.extend(this, {
            members: [],
            add: [],
            remove: []
        });
    }
    _.extend(Council.prototype, {

        genderCount: function (gender) {
            return this.members.reduce(function (previousValue, currentPerson) {
                if (currentPerson.gender == gender) {
                    previousValue++;
                }
                return previousValue;
            }, 0);
        },

        women: function () {
            return this.genderCount('F');
        },

        men: function () {
            return this.genderCount('M');
        },

        ages: function (date) {
            return this.members.map(function (person) {
                return person.age(date);
            });
        },

        averageAge: function (date) {
            return this.ages(date).reduce(function (previous, current) {
                    return previous + current;
                }, 0) / this.members.length;
        },

        minAge: function (date) {
            return _.min(this.ages(date));
        },

        maxAge: function (date) {
            return _.max(this.ages(date));
        },

        totalExperience: function (date, includeMayor) {
            return this.members.reduce(function (previousValue, currentPerson) {
                return previousValue + currentPerson.experience(date, includeMayor);
            }, 0);
        }
    });

    $.getJSON('data/person.json', process);

    function process(personData) {
        var councils = {},
            members = [];
        _.each(personData, function (data) {
            var person = new Person(data);
            person.positions.forEach(function (p) {
                if (!/Council/.test(p.office)) {
                    return;
                }
                if (p.start) {
                    if (!councils[p.start]) {
                        councils[p.start] = new Council();
                        councils[p.start].date = p.start;
                    }
                    councils[p.start].add.push(person);
                }
                else {
                    throw 'Missing start in ' + person.code;
                }
                if (p.end) {
                    if (!councils[p.end]) {
                        councils[p.end] = new Council();
                        councils[p.end].date = p.end;
                    }
                    councils[p.end].remove.push(person);
                }
            });
        });
        councils = _.pick(councils, _.keys(councils).sort());
        _.each(councils, function (c, date) {
            members = _.union(_.difference(members, c.remove), c.add);
            c.members = members.slice();
        });
        draw(councils);
    }

    function dataRow(council, date) {
        return {
            date: date,
            men: council.men(),
            women: council.women(),
            experience: council.totalExperience(date),
            experienceWithMayor: council.totalExperience(date, true),
            averageAge: council.averageAge(date),
            minAge: council.minAge(date),
            maxAge: council.maxAge(date)
        };
    }

    function draw(councils) {
        var data = [],
            baseOptions = {
                axes: {
                    x: {
                        valueFormatter: function (millis) {
                            return moment(millis).utc().format('YYYY-MM-DD');
                        }
                    }
                },
                fillGraph: true,
                labelsUTC: true
            },
            prevCouncil, date, now;
        _.each(councils, function (council, ymd) {
            date = new Date(ymd + 'T12:00');
            if (prevCouncil) {
                data.push(dataRow(prevCouncil, new Date(date.getTime() - 1)));
            }
            data.push(dataRow(council, date));
            prevCouncil = council;
        });
        now = new Date();
        date = moment(prevCouncil.date).add(180, 'd').toDate();
        if (now.getTime() > date.getTime()) {
            date = now;
        }
        data.push(dataRow(prevCouncil, date));
        new Dygraph(
            'women-graph',
            function () {
                return data.map(function (row) {
                    return [row.date, row.men, row.women];
                });
            },
            _.extend({}, baseOptions, {
                includeZero: true,
                labels: ['Date', 'Men', 'Women'],
                stackedGraph: true,
                title: 'Gender Representation on DC Council'
            })
        );
        new Dygraph(
            'experience-graph',
            function () {
                return data.map(function (row) {
                    return [row.date, row.experience, row.experienceWithMayor];
                });
            },
            _.extend({}, baseOptions, {
                labels: ['Date', 'Experience', 'Including Mayoral'],
                title: 'Total Years of Experience of DC Council'
            })
        );
        new Dygraph(
            'age-graph',
            function () {
                return data.map(function (row) {
                    return [row.date, row.averageAge, row.minAge, row.maxAge];
                });
            },
            _.extend({}, baseOptions, {
                labels: ['Date', 'Average Age', 'Min', 'Max'],
                title: 'Average Age of DC Council'
            })
        );
    }

})(jQuery);
<|endoftext|>


<commit_before>module.exports = function(gulp, plugins) {
  return function () {
    return gulp.src((['./src/**/*.js', '!./src/**/*.spec.js'])
      .pipe(plugins.babel())
      .pipe(gulp.dest('lib/'));
  };
};
<commit_msg>Improvement: fixed build.<commit_after>module.exports = function(gulp, plugins) {
  return function () {
    return gulp.src(['./src/**/*.js', '!./src/**/*.spec.js'])
      .pipe(plugins.babel())
      .pipe(gulp.dest('lib/'));
  };
};
<|endoftext|>


<commit_before>var autorun = require('bonescript').autorun;
var fs = require('fs');

exports.testAutorun = function (test) {
    var ar = autorun('./autorun-test');
    var apps = ar.getApps();
    var emitter = ar.getEmitter();
    test.expect(2);

    emitter.on('start', function (file) {
        test.ok(true);
        fs.unlink('./autorun-test/autorun-test.js', onUnlink);
    });

    emitter.on('closed', function (file) {
        ar.stop();
        test.ok(true);
        test.done();
    });

    if (!fs.existsSync('./autorun-test')) {
        fs.mkdirSync('./autorun-test');
    }
    fs.writeFileSync('./autorun-test/autorun-test.js', 'console.log("got here.");');

    function onUnlink() {
        console.log('autorun-test.js deleted');
    }
};<commit_msg>Add timeout to test-autorun.js<commit_after>var autorun = require('bonescript').autorun;
var fs = require('fs');

exports.testAutorun = function (test) {
    var ar = autorun('./autorun-test');
    var apps = ar.getApps();
    var emitter = ar.getEmitter();
    test.expect(2);
    setTimeout(onTimeout, 1000);

    emitter.on('start', function (file) {
        test.ok(true);
        fs.unlink('./autorun-test/autorun-test.js', onUnlink);
    });

    emitter.on('closed', function (file) {
        ar.stop();
        test.ok(true);
    });

    if (!fs.existsSync('./autorun-test')) {
        fs.mkdirSync('./autorun-test');
    }
    fs.writeFileSync('./autorun-test/autorun-test.js', 'console.log("got here.");');

    function onUnlink() {
        console.log('autorun-test.js deleted');
    }

    function onTimeout() {
        test.done();
    }
};<|endoftext|>


<commit_before>function inputComparator (a, b) {
  var aa = new Buffer(a.txId, 'hex')
  var bb = new Buffer(b.txId, 'hex')
  Array.prototype.reverse.call(aa)
  Array.prototype.reverse.call(bb)

  return aa.compare(bb)
}

function outputComparator (a, b) {
  return a.value - b.value
}

function sortInputs (inputs) {
  return inputs.concat().sort(inputComparator)
}

function sortOutputs (outputs) {
  return outputs.concat().sort(outputComparator)
}

module.exports = function bip69 (inputs, outputs) {
  return {
    inputs: sortInputs(inputs),
    outputs: sortOutputs(outputs)
  }
}

module.exports.sortInputs = sortInputs
module.exports.sortOutputs = sortOutputs
<commit_msg>compare by vout second<commit_after>function inputComparator (a, b) {
  var aa = new Buffer(a.txId, 'hex')
  var bb = new Buffer(b.txId, 'hex')
  Array.prototype.reverse.call(aa)
  Array.prototype.reverse.call(bb)

  return aa.compare(bb) || a.vout - b.vout
}

function outputComparator (a, b) {
  return a.value - b.value
}

function sortInputs (inputs) {
  return inputs.concat().sort(inputComparator)
}

function sortOutputs (outputs) {
  return outputs.concat().sort(outputComparator)
}

module.exports = function bip69 (inputs, outputs) {
  return {
    inputs: sortInputs(inputs),
    outputs: sortOutputs(outputs)
  }
}

module.exports.sortInputs = sortInputs
module.exports.sortOutputs = sortOutputs
<|endoftext|>


<commit_before>var Hapi    = require('hapi');
var routes  = require('./routes.js');
var RaspiCam = require("raspicam");

var opts = {
  mode: "timelapse",
  output: "/home/pi/node-raspicam-web/public/img/image%06d.jpg",
  timelapse: 60 * 1000,
  timeout: 0,
  width: 800,
  height: 600
}
var camera = null;

var server  = new Hapi.Server();

data = {
  message: 'Not started',
  interval: 60,
  startedAt: null,
  lastImageTakenAt: null,
  lastImageUrl: null
};

function start(interval) {
  data.message = "Started";
  data.interval = interval;
  data.startedAt = new Date().toLocaleString();
  data.lastImageTakenAt = null;
  data.lastImageUrl = null;

  opts.timelapse = interval * 1000;
  camera = new RaspiCam( opts );

  camera.on("start", function() {
    console.log("Camera started");
  });

  camera.on("read", function(err, timestamp, filename) {
    console.log("Camera read");
    d = new Date(timestamp).toLocaleString();
    f = "/img/" + filename;
    updateLastImage(d, f);
    io.emit('image:updated', JSON.stringify(data));
  });

  camera.on("stop", function() {
    console.log("Camera stopped");
  });

  camera.on("exit", function() {
    console.log("Camera exited");
  });

  camera.start();
}

function stop() {
  data.message = "Stopped";
  camera.stop();
}

function updateLastImage(timestamp, url) {
  data.lastImageTakenAt = timestamp;
  data.lastImageUrl = url;
}

server.connection({
  port: process.env.PORT || 9090
});

var socketio = require('socket.io');

server.route(routes);

function tick() {
  console.log("tick");
  imageurl = showGiraffe ? '/img/giraffe.jpg' : '/img/leopard.jpg';
  updateLastImage(imageurl);
  io.emit('image:updated', JSON.stringify(data));
  showGiraffe = !showGiraffe;
}

function socketSetup (socket) {

  console.log("socketSetup connected!")

  socket.on("start", function(data) {
    console.log("start server.js called, data: ", data);
    start(data);
  });

  socket.on("stop", function() {
    console.log("stop server.js called");
    stop();
    io.emit('image:updated', JSON.stringify(data));
  });
}

function init (listener, callback) {
  io = socketio(listener);
  io.on('connection', socketSetup);

  callback();
}

module.exports = {
  server: server,
  init: init
};

<commit_msg>Uses UTC timestamp<commit_after>var Hapi    = require('hapi');
var routes  = require('./routes.js');
var RaspiCam = require("raspicam");

var opts = {
  mode: "timelapse",
  output: "/home/pi/node-raspicam-web/public/img/image%06d.jpg",
  timelapse: 60 * 1000,
  timeout: 0,
  width: 800,
  height: 600
}
var camera = null;

var server  = new Hapi.Server();

data = {
  message: 'Not started',
  interval: 60,
  startedAt: null,
  lastImageTakenAt: null,
  lastImageUrl: null
};

function start(interval) {
  data.message = "Started";
  data.interval = interval;
  data.startedAt = new Date().toUTCString();
  data.lastImageTakenAt = null;
  data.lastImageUrl = null;

  opts.timelapse = interval * 1000;
  camera = new RaspiCam( opts );

  camera.on("start", function() {
    console.log("Camera started");
  });

  camera.on("read", function(err, timestamp, filename) {
    console.log("Camera read");
    d = new Date(timestamp).toUTCString();
    f = "/img/" + filename;
    updateLastImage(d, f);
    io.emit('image:updated', JSON.stringify(data));
  });

  camera.on("stop", function() {
    console.log("Camera stopped");
  });

  camera.on("exit", function() {
    console.log("Camera exited");
  });

  camera.start();
}

function stop() {
  data.message = "Stopped";
  camera.stop();
}

function updateLastImage(timestamp, url) {
  data.lastImageTakenAt = timestamp;
  data.lastImageUrl = url;
}

server.connection({
  port: process.env.PORT || 9090
});

var socketio = require('socket.io');

server.route(routes);

function tick() {
  console.log("tick");
  imageurl = showGiraffe ? '/img/giraffe.jpg' : '/img/leopard.jpg';
  updateLastImage(imageurl);
  io.emit('image:updated', JSON.stringify(data));
  showGiraffe = !showGiraffe;
}

function socketSetup (socket) {

  console.log("socketSetup connected!")

  socket.on("start", function(data) {
    console.log("start server.js called, data: ", data);
    start(data);
  });

  socket.on("stop", function() {
    console.log("stop server.js called");
    stop();
    io.emit('image:updated', JSON.stringify(data));
  });
}

function init (listener, callback) {
  io = socketio(listener);
  io.on('connection', socketSetup);

  callback();
}

module.exports = {
  server: server,
  init: init
};

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'jquery',
    'backbone'
], function ($, Backbone) {
    var ContrailView = Backbone.View.extend({
        constructor: function () {
            var self = this;

            self.isMyViewRenderInProgress = false;
            self.childViewMap = {};
            self.error = false;

            self.onAllViewsRenderComplete = new Slick.Event();
            self.onAllRenderComplete = new Slick.Event();

            Backbone.View.apply(self, arguments);

            //The top view may not have any argument.
            if(arguments.length > 0) {
                self.rootView = arguments[0].rootView;
                var onAllViewsRenderCompleteCB = arguments[0].onAllViewsRenderCompleteCB,
                    onAllRenderCompleteCB = arguments[0].onAllRenderCompleteCB;

                if (contrail.checkIfFunction(onAllViewsRenderCompleteCB)) {
                    self.onAllViewsRenderComplete.subscribe(function() {
                        onAllViewsRenderCompleteCB();
                    });
                } else if (contrail.checkIfFunction(onAllRenderCompleteCB)) {
                    self.onAllRenderComplete.subscribe(function() {
                        onAllRenderCompleteCB();
                    });
                }
            }

            return self;
        },

        isAnyViewRenderInProgress: function() {
            var isChildRenderInProgress = false;

            for(var key in this.childViewMap) {
                if(this.childViewMap[key] == null || this.childViewMap[key].isAnyViewRenderInProgress()) {
                    isChildRenderInProgress = true;
                    break;
                }
            }

            return isChildRenderInProgress || this.isMyViewRenderInProgress;
        },

        isAnyRenderInProgress: function() {
            return this.isAnyViewRenderInProgress() || this.isModelRequestInProgress();
        },

        isModelRequestInProgress: function() {
            if(this.model != null && contrail.checkIfFunction(this.model.isRequestInProgress)) {
                return this.model.isRequestInProgress();
            } else {
                return false;
            }
        },

        renderView4Config: function (parentElement, model, viewObj, validation, lockEditingByDefault, modelMap, onAllViewsRenderComplete, onAllRenderComplete) {
            var viewName = viewObj['view'],
                viewPathPrefix = viewObj['viewPathPrefix'],
                elementId = viewObj[cowc.KEY_ELEMENT_ID],
                validation = (validation != null) ? validation : cowc.KEY_VALIDATION,
                viewConfig = viewObj[cowc.KEY_VIEW_CONFIG],
                viewAttributes = {viewConfig: viewConfig, elementId: elementId, validation: validation, lockEditingByDefault: lockEditingByDefault},
                app = viewObj['app'], self = this;

            self.childViewMap[elementId] = null;

            var rootView = contrail.checkIfExist(this.rootView) ? this.rootView : this,
                renderConfig = {
                    parentElement: parentElement,
                    viewName: viewName,
                    viewPathPrefix: viewPathPrefix,
                    model: model,
                    viewAttributes: viewAttributes,
                    modelMap: modelMap,
                    app: app,
                    rootView: rootView,
                    onAllViewsRenderCompleteCB: function() {return;}
                    /*
                    onAllRenderCompleteCB: function() {
                        if(!self.isAnyViewRenderInProgress()) {
                            // Notify parent the one of child's rendering is complete.
                            self.onAllRenderComplete.notify();

                            if(contrail.checkIfFunction(onAllRenderComplete)) {
                                // Call any callback associated with onViewRenderComplete of child view.
                                onAllRenderComplete();
                            }
                        }
                    }*/
                };

            //Currently we're enabling this event only in test env.
            if(globalObj['test-env'] == globalObj['env'] + "-test") {
                renderConfig.onAllViewsRenderCompleteCB = function() {
                    viewsRenderCompleteEventNotifier(self, viewName, onAllViewsRenderComplete);
                }
             }

            cowu.renderView(renderConfig, function(renderedView) {
                // Adding child view to a map in rootView
                add2RootViewMap(elementId, renderedView, rootView);

                // Adding child view to a childViewMap in current view
                add2ChildViewMap(elementId, renderedView, self);
            });
        },

        setRootView: function(childElId, rootView) {
            add2RootViewMap(childElId, this, rootView)
        },

        setParentView: function(childElId, parentView) {
            add2ChildViewMap(childElId, this, parentView);
        },

        beginMyViewRendering: function() {
            this.isMyViewRenderInProgress = true;
            this.error = false;
        },

        endMyViewRendering: function() {
            this.isMyViewRenderInProgress = false;
            if(!this.isAnyViewRenderInProgress()) {
                this.onAllViewsRenderComplete.notify();
            }

            if(!this.isAnyRenderInProgress()) {
                this.onAllRenderComplete.notify();
            }
        },

        endMyModelRendering: function() {
            if(!this.isAnyRenderInProgress()) {
                this.onAllRenderComplete.notify();
            }
        },

        endMyRendering: function() {
            this.endMyViewRendering();
            this.endMyModelRendering();
        }
    });

    function add2RootViewMap(childElId, chRenderedView, rootView) {
        if(!contrail.checkIfExist(rootView.viewMap)) {
            rootView.viewMap = {};
        }
        rootView.viewMap[childElId] = chRenderedView;
    }

    function add2ChildViewMap (childElId, chRenderedView, self) {
        self.childViewMap[childElId] = chRenderedView;
    }

    function viewsRenderCompleteEventNotifier(self, viewName, onAllViewsRenderComplete) {
        var notifyTimer = contrail.checkIfExist(globalObj.notifyTimer) ? globalObj.notifyTimer : null,
            viewNotifyTimeout = 200,
            ajaxNotifyTimeout = 200;

        function waitAndNotify(timeout) {
            if (notifyTimer != null) clearTimeout(notifyTimer);

            notifyTimer = setTimeout(function () {
                if (!self.isAnyViewRenderInProgress() && ($.active == 0)) {
                    //clear timeout.
                    clearTimeout(notifyTimer);

                    //For debugging.
                    //console.log("Render Complete: " + viewName);

                    // Notify parent the one of child's rendering is complete.
                    self.onAllViewsRenderComplete.notify();

                    if (contrail.checkIfFunction(onAllViewsRenderComplete)) {
                        // Call any callback associated with onViewRenderComplete of child view.
                        onAllViewsRenderComplete(self);
                    }
                } else if ($.active > 0) {
                    waitAndNotify(ajaxNotifyTimeout);
                } else {
                    if (notifyTimer != null) clearInterval(notifyTimer);
                }
            }, timeout);

            globalObj.notifyTimer = notifyTimer;
        }

        /**
         * before we notify the event, wait sometime for render complete and no active ajax request exist.
         */
        if (!self.isAnyViewRenderInProgress() && ($.active == 0)) {
            waitAndNotify(viewNotifyTimeout);
        } else if ($.active > 0) {
            waitAndNotify(ajaxNotifyTimeout);
        } else {
            if (notifyTimer != null) clearInterval(notifyTimer);
        }
    }

    return ContrailView;
});<commit_msg>Closes-Bug: #1553413 fix onAllRequestCompleteCB<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'jquery',
    'backbone'
], function ($, Backbone) {
    var ContrailView = Backbone.View.extend({
        constructor: function () {
            var self = this;

            self.isMyViewRenderInProgress = false;
            self.childViewMap = {};
            self.error = false;

            self.onAllViewsRenderComplete = new Slick.Event();
            self.onAllRenderComplete = new Slick.Event();

            Backbone.View.apply(self, arguments);

            //The top view may not have any argument.
            if(arguments.length > 0) {
                self.rootView = arguments[0].rootView;
                var onAllViewsRenderCompleteCB = arguments[0].onAllViewsRenderCompleteCB,
                    onAllRenderCompleteCB = arguments[0].onAllRenderCompleteCB;

                if (contrail.checkIfFunction(onAllViewsRenderCompleteCB)) {
                    self.onAllViewsRenderComplete.subscribe(function() {
                        onAllViewsRenderCompleteCB();
                    });
                } else if (contrail.checkIfFunction(onAllRenderCompleteCB)) {
                    self.onAllRenderComplete.subscribe(function() {
                        onAllRenderCompleteCB();
                    });
                }
            }

            return self;
        },

        isAnyViewRenderInProgress: function() {
            var isChildRenderInProgress = false;

            for(var key in this.childViewMap) {
                if(this.childViewMap[key] == null || this.childViewMap[key].isAnyViewRenderInProgress()) {
                    isChildRenderInProgress = true;
                    break;
                }
            }

            return isChildRenderInProgress || this.isMyViewRenderInProgress;
        },

        isAnyRenderInProgress: function() {
            return this.isAnyViewRenderInProgress() || this.isModelRequestInProgress();
        },

        isModelRequestInProgress: function() {
            if(this.model != null && contrail.checkIfFunction(this.model.isRequestInProgress)) {
                return this.model.isRequestInProgress();
            } else {
                return false;
            }
        },

        renderView4Config: function (parentElement, model, viewObj, validation, lockEditingByDefault, modelMap, onAllViewsRenderComplete, onAllRenderComplete) {
            var viewName = viewObj['view'],
                viewPathPrefix = viewObj['viewPathPrefix'],
                elementId = viewObj[cowc.KEY_ELEMENT_ID],
                validation = (validation != null) ? validation : cowc.KEY_VALIDATION,
                viewConfig = viewObj[cowc.KEY_VIEW_CONFIG],
                viewAttributes = {viewConfig: viewConfig, elementId: elementId, validation: validation, lockEditingByDefault: lockEditingByDefault},
                app = viewObj['app'], self = this;

            self.childViewMap[elementId] = null;

            var rootView = contrail.checkIfExist(this.rootView) ? this.rootView : this,
                renderConfig = {
                    parentElement: parentElement,
                    viewName: viewName,
                    viewPathPrefix: viewPathPrefix,
                    model: model,
                    viewAttributes: viewAttributes,
                    modelMap: modelMap,
                    app: app,
                    rootView: rootView,
                    onAllViewsRenderCompleteCB: function() {
                        if(!self.isAnyViewRenderInProgress()) {
                            // Notify parent the one of child's rendering is complete.
                            self.onAllViewsRenderComplete.notify();

                            if(contrail.checkIfFunction(onAllViewsRenderComplete)) {
                                // Call any callback associated with onViewRenderComplete of child view.
                                onAllViewsRenderComplete(self);
                            }
                        }

                    }
                    /*
                    onAllRenderCompleteCB: function() {
                        if(!self.isAnyViewRenderInProgress()) {
                            // Notify parent the one of child's rendering is complete.
                            self.onAllRenderComplete.notify();

                            if(contrail.checkIfFunction(onAllRenderComplete)) {
                                // Call any callback associated with onViewRenderComplete of child view.
                                onAllRenderComplete();
                            }
                        }
                    }*/
                };

            //Currently we're enabling this event only in test env.
            if(globalObj['test-env'] == globalObj['env'] + "-test") {
                renderConfig.onAllViewsRenderCompleteCB = function() {
                    viewsRenderCompleteEventNotifier(self, viewName, onAllViewsRenderComplete);
                }
             }

            cowu.renderView(renderConfig, function(renderedView) {
                // Adding child view to a map in rootView
                add2RootViewMap(elementId, renderedView, rootView);

                // Adding child view to a childViewMap in current view
                add2ChildViewMap(elementId, renderedView, self);
            });
        },

        setRootView: function(childElId, rootView) {
            add2RootViewMap(childElId, this, rootView)
        },

        setParentView: function(childElId, parentView) {
            add2ChildViewMap(childElId, this, parentView);
        },

        beginMyViewRendering: function() {
            this.isMyViewRenderInProgress = true;
            this.error = false;
        },

        endMyViewRendering: function() {
            this.isMyViewRenderInProgress = false;
            if(!this.isAnyViewRenderInProgress()) {
                this.onAllViewsRenderComplete.notify();
            }

            if(!this.isAnyRenderInProgress()) {
                this.onAllRenderComplete.notify();
            }
        },

        endMyModelRendering: function() {
            if(!this.isAnyRenderInProgress()) {
                this.onAllRenderComplete.notify();
            }
        },

        endMyRendering: function() {
            this.endMyViewRendering();
            this.endMyModelRendering();
        }
    });

    function add2RootViewMap(childElId, chRenderedView, rootView) {
        if(!contrail.checkIfExist(rootView.viewMap)) {
            rootView.viewMap = {};
        }
        rootView.viewMap[childElId] = chRenderedView;
    }

    function add2ChildViewMap (childElId, chRenderedView, self) {
        self.childViewMap[childElId] = chRenderedView;
    }

    function viewsRenderCompleteEventNotifier(self, viewName, onAllViewsRenderComplete) {
        var notifyTimer = contrail.checkIfExist(globalObj.notifyTimer) ? globalObj.notifyTimer : null,
            viewNotifyTimeout = 200,
            ajaxNotifyTimeout = 200;

        function waitAndNotify(timeout) {
            if (notifyTimer != null) clearTimeout(notifyTimer);

            notifyTimer = setTimeout(function () {
                if (!self.isAnyViewRenderInProgress() && ($.active == 0)) {
                    //clear timeout.
                    clearTimeout(notifyTimer);

                    //For debugging.
                    //console.log("Render Complete: " + viewName);

                    // Notify parent the one of child's rendering is complete.
                    self.onAllViewsRenderComplete.notify();

                    if (contrail.checkIfFunction(onAllViewsRenderComplete)) {
                        // Call any callback associated with onViewRenderComplete of child view.
                        onAllViewsRenderComplete(self);
                    }
                } else if ($.active > 0) {
                    waitAndNotify(ajaxNotifyTimeout);
                } else {
                    if (notifyTimer != null) clearInterval(notifyTimer);
                }
            }, timeout);

            globalObj.notifyTimer = notifyTimer;
        }

        /**
         * before we notify the event, wait sometime for render complete and no active ajax request exist.
         */
        if (!self.isAnyViewRenderInProgress() && ($.active == 0)) {
            waitAndNotify(viewNotifyTimeout);
        } else if ($.active > 0) {
            waitAndNotify(ajaxNotifyTimeout);
        } else {
            if (notifyTimer != null) clearInterval(notifyTimer);
        }
    }

    return ContrailView;
});<|endoftext|>


<commit_before>/*!
 * author: puronglong
 */

$(document).ready(function () {
	'use strict';
	$('.slider').slider({
		full_width: true,
		indicators: true,  // 导航标识
		interval: 8000,   // 间隔时间设置
		transition: 700    // 持续时间设置
	});

	$('.button-previous-left').on('click', function () {
		$('.slider').slider('prev');
	});

	$('.button-previous-right').on('click', function () {
		$('.slider').slider('next');
	});

	setTimeout(function () {
		$('#menu').addClass('menu animated bounceInDown');
	}, 1000);
});

<commit_msg>edit display time<commit_after>/*!
 * author: puronglong
 */

$(document).ready(function () {
	'use strict';
	$('.slider').slider({
		full_width: true,
		indicators: true,  // 导航标识
		interval: 8000,   // 间隔时间设置
		transition: 700    // 持续时间设置
	});

	$('.button-previous-left').on('click', function () {
		$('.slider').slider('prev');
	});

	$('.button-previous-right').on('click', function () {
		$('.slider').slider('next');
	});

	setTimeout(function () {
		$('#menu').addClass('menu animated bounceInDown');
	}, 700);
});

<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var es = require("event-stream")
var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
// TODO require gulp plugins normally instead of using gulp-load-plugins - makes the code easier to understand

var connect = require('gulp-connect');

function handleError(err) {
  console.error(err.toString());
  this.emit('end');
}

gulp.task('styles', ['wiredep'],  function () {
  return gulp.src([
      'src/{app,components}/**/*.less',
      '!src/{app,components}/**/_*.less'
    ])
    .pipe($.less({
      paths: [
        'src/bower_components',
        'src/app',
        'src/components'
      ]
    }))
    .on('error', handleError)
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('scripts', function () {
  var angularticsFilter = function(){
    return $.filter(function(file){
      return !file.path.endsWith('angulartics-ga.js');
    });
  };
  return gulp.src('src/{app,components}/**/*.js')
    .pipe(angularticsFilter())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.size());
});

gulp.task('partials', function () {
  return gulp.src('src/{app,components}/**/*.html')
    .pipe($.htmlmin({
      collapseWhitespace: true
    }))
    .pipe($.ngHtml2js({
      moduleName: 'civicClient'
    }))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('inject', ['styles', 'wiredep'], function(){
  var specFilter = function(){
    return $.filter(function(file){
      return !file.path.endsWith(".spec.js");
    });
  };
  var vendorFilter = function(){
    return $.filter(function(file){
      return !file.path.endsWith("app/vendor.css");
    });
  };
  var appBuilder = require("./app-builder.js");

  return gulp.src(['.tmp/index.html', 'src/404.html'])
    .pipe($.inject(
      gulp.src("src/{app,components}/**/*.js")
        .pipe(specFilter()) //filter out test files
        //now pipe through the custom angular app builder to inject the app files in the right order
        .pipe(appBuilder('civicClient',{
          'exclude' : [
            'uiResolving.js',
            'entityEditView.js',
            'GoogleAnalyticsService.js',
            'MyVariantInfoService.js',
            'EvidenceQueuesController.js',
            'authTestCtrl.js'
          ]
        })),
        {
          starttag: '<!-- inject:app -->',
          addRootSlash: false,
          ignorePath: 'src/'
        }
    ))
    .pipe($.inject(
      gulp.src(".tmp/{app,components}/**/*.css")
        .pipe(vendorFilter()),
      {
        starttag: '<!-- inject:style -->',
        addRootSlash: false,
        ignorePath: '.tmp/'
      }
    ))
    .pipe(gulp.dest('.tmp'))
})

gulp.task('html', ['partials', 'scripts', 'cdnize'], function () {
  var htmlFilter = $.filter('*.html', {restore: true});
  var jsFilter = $.filter('**/*.js', {restore: true});
  var cssFilter = $.filter('**/*.css', {restore: true});

  return gulp.src('.tmp/*.html')
    .pipe($.inject(
      // stream JS files in app/component directories
      gulp.src('.tmp/{app,components}/**/*.js'),
      {
        starttag: '<!-- inject:partials -->',
        addRootSlash: false,
        addPrefix: '../'
      }))

    // parse index.html for links to asset (scripts, html, css), group, concatenate, add to stream
    //This call to useref will parse all app assets and concatenate
    //It also filters out any remote assets which have been cdnized,
    //leaving only those which couldn't behind to be parsed into vendor files
    .pipe($.useref({
      //this function scans build:filter_cdn blocks for assets which have been cdnized
      filter_cdn: function(content, target, mode, altPath){
        var scripts = content.split(/\r?\n/gm);
        var output = "";
        //prepare the build tag for the next run of useref
        var parse = "<!-- build:"+mode+(altPath?"("+altPath+") ":' ')+target+" -->\n";
        scripts.forEach(function(line){
          if(line.search(/(cloudflare\.com|googleapis\.com|jsdelivr\.net)/g)!=-1)
          {
            output+=line+"\n";
          }
          else {
            parse+=line+"\n";
          }
        });
        parse+="<!-- endbuild -->";
        return output+"\n"+parse;
      }
    }))

    .pipe($.useref()) //Second call to useref picks up the vendor files which weren't cdnized
    //and concatenates into vendor.{js,css}

    // init asset revisioning with gulp-rev on each block
    .pipe($.if("!*.html",$.rev()))

    // pluck javascript block, store everything else
    .pipe(jsFilter)
    //.pipe($.sourcemaps.init()) // initialize sourcemap generation
    .pipe($.ngAnnotate()) // add angular dependency injection to protect from minification
    .pipe($.uglify({ // minify js
        preserveComments: $.uglifySaveLicense,
        mangle: true,
        compress: {
          drop_console: true,
          unused: true
        }
      }
    ))
    //.pipe($.sourcemaps.write('.')) // write sourcemaps
    .pipe(jsFilter.restore)
    // restore non-js blocks to stream

    // pluck CSS, store non-css files
    .pipe(cssFilter)
    .pipe($.replace('/bower_components/bootstrap/fonts','/assets/fonts')) // rewrite bootstrap font urls
    .pipe($.replace(/url\('ui-grid\.(.*?)'\)/g,'url(\'/assets/fonts/ui-grid.$1\')')) // rewrite ui-grid font urls
    .pipe($.replace(/url\('\.\.\/fonts\/fontawesome-webfont\.(.*?)'\)/g,'url(\'/assets/fonts/fontawesome-webfont.$1\')')) // rewrite font-awesome fonts
    .pipe($.csso(true)) // minify CSS
    .pipe(cssFilter.restore)
    // restore non-css blocks to stream

    // apply revisions to concatenated assets
    .pipe($.revReplace())

    // pluck HTML, store everything else
    .pipe(htmlFilter)
    .pipe($.htmlmin({
      collapseWhitespace: true
    }))
    .pipe(htmlFilter.restore)
    // restore non-HTML files to stream

    // save files
    .pipe(gulp.dest('dist'))

    // generate size report
    .pipe($.size());
});

gulp.task('images', function () {
  return gulp.src('src/assets/images/**/*')
    .pipe($.cache($.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/assets/images'))
    .pipe($.size());
});

gulp.task('fonts', function () {
  return es.concat(
    gulp.src($.mainBowerFiles()),
    gulp.src('src/assets/fonts/**/*')
    )
    .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/assets/fonts'))
    .pipe($.size());
});

gulp.task('misc', function () {
  return gulp.src(['sitemap.xml', 'src/**/*.ico'])
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('clear-cache', function() {
  $.cache.clearAll();
});

gulp.task('clean', function (done) {
  $.del(['.tmp', 'dist'], done);
});

gulp.task('e2e:build', ['html', 'images', 'fonts', 'misc']);

gulp.task('build', ['e2e:build'], function(){

  return gulp.src('dist/scripts/app*.js')
    .pipe($.replace(/window\.apiCheck\.disabled=![01]/g, 'window.apiCheck.disabled=!0'))
    .pipe($.replace(/\.debugInfoEnabled\(![01]\)/g, '.debugInfoEnabled(!1)'))
    .pipe(gulp.dest('dist/scripts'))
});
<commit_msg>semicolon<commit_after>'use strict';

var gulp = require('gulp');
var es = require("event-stream");
var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
// TODO require gulp plugins normally instead of using gulp-load-plugins - makes the code easier to understand

var connect = require('gulp-connect');

function handleError(err) {
  console.error(err.toString());
  this.emit('end');
}

gulp.task('styles', ['wiredep'],  function () {
  return gulp.src([
      'src/{app,components}/**/*.less',
      '!src/{app,components}/**/_*.less'
    ])
    .pipe($.less({
      paths: [
        'src/bower_components',
        'src/app',
        'src/components'
      ]
    }))
    .on('error', handleError)
    .pipe($.autoprefixer('last 1 version'))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('scripts', function () {
  var angularticsFilter = function(){
    return $.filter(function(file){
      return !file.path.endsWith('angulartics-ga.js');
    });
  };
  return gulp.src('src/{app,components}/**/*.js')
    .pipe(angularticsFilter())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.size());
});

gulp.task('partials', function () {
  return gulp.src('src/{app,components}/**/*.html')
    .pipe($.htmlmin({
      collapseWhitespace: true
    }))
    .pipe($.ngHtml2js({
      moduleName: 'civicClient'
    }))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

gulp.task('inject', ['styles', 'wiredep'], function(){
  var specFilter = function(){
    return $.filter(function(file){
      return !file.path.endsWith(".spec.js");
    });
  };
  var vendorFilter = function(){
    return $.filter(function(file){
      return !file.path.endsWith("app/vendor.css");
    });
  };
  var appBuilder = require("./app-builder.js");

  return gulp.src(['.tmp/index.html', 'src/404.html'])
    .pipe($.inject(
      gulp.src("src/{app,components}/**/*.js")
        .pipe(specFilter()) //filter out test files
        //now pipe through the custom angular app builder to inject the app files in the right order
        .pipe(appBuilder('civicClient',{
          'exclude' : [
            'uiResolving.js',
            'entityEditView.js',
            'GoogleAnalyticsService.js',
            'MyVariantInfoService.js',
            'EvidenceQueuesController.js',
            'authTestCtrl.js'
          ]
        })),
        {
          starttag: '<!-- inject:app -->',
          addRootSlash: false,
          ignorePath: 'src/'
        }
    ))
    .pipe($.inject(
      gulp.src(".tmp/{app,components}/**/*.css")
        .pipe(vendorFilter()),
      {
        starttag: '<!-- inject:style -->',
        addRootSlash: false,
        ignorePath: '.tmp/'
      }
    ))
    .pipe(gulp.dest('.tmp'))
})

gulp.task('html', ['partials', 'scripts', 'cdnize'], function () {
  var htmlFilter = $.filter('*.html', {restore: true});
  var jsFilter = $.filter('**/*.js', {restore: true});
  var cssFilter = $.filter('**/*.css', {restore: true});

  return gulp.src('.tmp/*.html')
    .pipe($.inject(
      // stream JS files in app/component directories
      gulp.src('.tmp/{app,components}/**/*.js'),
      {
        starttag: '<!-- inject:partials -->',
        addRootSlash: false,
        addPrefix: '../'
      }))

    // parse index.html for links to asset (scripts, html, css), group, concatenate, add to stream
    //This call to useref will parse all app assets and concatenate
    //It also filters out any remote assets which have been cdnized,
    //leaving only those which couldn't behind to be parsed into vendor files
    .pipe($.useref({
      //this function scans build:filter_cdn blocks for assets which have been cdnized
      filter_cdn: function(content, target, mode, altPath){
        var scripts = content.split(/\r?\n/gm);
        var output = "";
        //prepare the build tag for the next run of useref
        var parse = "<!-- build:"+mode+(altPath?"("+altPath+") ":' ')+target+" -->\n";
        scripts.forEach(function(line){
          if(line.search(/(cloudflare\.com|googleapis\.com|jsdelivr\.net)/g)!=-1)
          {
            output+=line+"\n";
          }
          else {
            parse+=line+"\n";
          }
        });
        parse+="<!-- endbuild -->";
        return output+"\n"+parse;
      }
    }))

    .pipe($.useref()) //Second call to useref picks up the vendor files which weren't cdnized
    //and concatenates into vendor.{js,css}

    // init asset revisioning with gulp-rev on each block
    .pipe($.if("!*.html",$.rev()))

    // pluck javascript block, store everything else
    .pipe(jsFilter)
    //.pipe($.sourcemaps.init()) // initialize sourcemap generation
    .pipe($.ngAnnotate()) // add angular dependency injection to protect from minification
    .pipe($.uglify({ // minify js
        preserveComments: $.uglifySaveLicense,
        mangle: true,
        compress: {
          drop_console: true,
          unused: true
        }
      }
    ))
    //.pipe($.sourcemaps.write('.')) // write sourcemaps
    .pipe(jsFilter.restore)
    // restore non-js blocks to stream

    // pluck CSS, store non-css files
    .pipe(cssFilter)
    .pipe($.replace('/bower_components/bootstrap/fonts','/assets/fonts')) // rewrite bootstrap font urls
    .pipe($.replace(/url\('ui-grid\.(.*?)'\)/g,'url(\'/assets/fonts/ui-grid.$1\')')) // rewrite ui-grid font urls
    .pipe($.replace(/url\('\.\.\/fonts\/fontawesome-webfont\.(.*?)'\)/g,'url(\'/assets/fonts/fontawesome-webfont.$1\')')) // rewrite font-awesome fonts
    .pipe($.csso(true)) // minify CSS
    .pipe(cssFilter.restore)
    // restore non-css blocks to stream

    // apply revisions to concatenated assets
    .pipe($.revReplace())

    // pluck HTML, store everything else
    .pipe(htmlFilter)
    .pipe($.htmlmin({
      collapseWhitespace: true
    }))
    .pipe(htmlFilter.restore)
    // restore non-HTML files to stream

    // save files
    .pipe(gulp.dest('dist'))

    // generate size report
    .pipe($.size());
});

gulp.task('images', function () {
  return gulp.src('src/assets/images/**/*')
    .pipe($.cache($.imagemin({
      optimizationLevel: 3,
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/assets/images'))
    .pipe($.size());
});

gulp.task('fonts', function () {
  return es.concat(
    gulp.src($.mainBowerFiles()),
    gulp.src('src/assets/fonts/**/*')
    )
    .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/assets/fonts'))
    .pipe($.size());
});

gulp.task('misc', function () {
  return gulp.src(['sitemap.xml', 'src/**/*.ico'])
    .pipe(gulp.dest('dist'))
    .pipe($.size());
});

gulp.task('clear-cache', function() {
  $.cache.clearAll();
});

gulp.task('clean', function (done) {
  $.del(['.tmp', 'dist'], done);
});

gulp.task('e2e:build', ['html', 'images', 'fonts', 'misc']);

gulp.task('build', ['e2e:build'], function(){

  return gulp.src('dist/scripts/app*.js')
    .pipe($.replace(/window\.apiCheck\.disabled=![01]/g, 'window.apiCheck.disabled=!0'))
    .pipe($.replace(/\.debugInfoEnabled\(![01]\)/g, '.debugInfoEnabled(!1)'))
    .pipe(gulp.dest('dist/scripts'))
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var compression = require('compression');

var app = express();

var static_path = path.join(__dirname, '/../build');

app.set('port', process.env.PORT || 3000);

app.use(compression());
app.use(express.static(static_path, { maxAge: '1y' }));

app.get('/', function (req, res) {
  res.sendFile('index.html', {
    root: static_path
  });
});

app.listen(app.get('port'), function () {
  console.log('Running at localhost:' + app.get('port'));
});
<commit_msg>Change express routing for uuids<commit_after>var express = require('express');
var path = require('path');
var compression = require('compression');

var app = express();

var static_path = path.join(__dirname, '/../build');

app.set('port', process.env.PORT || 3000);

app.use(compression());
app.use(express.static(static_path, { maxAge: '1y' }));

// Match UUIDs
app.get('/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}', function (req, res) {
  res.sendFile('index.html', {
    root: static_path
  });
});

app.listen(app.get('port'), function () {
  console.log('Running at localhost:' + app.get('port'));
});
<|endoftext|>