<commit_before>function Record(ID, datetime, host, program, pid, message, priority, processed, scanned) {
    this.ID = ID;
    this.datetime = datetime;
    this.host = host;
    this.program = program;
    this.pid = pid;
    this.message = message;
    this.priority = priority;
    this.processed = processed;
    this.scanned = scanned;
}
Record.prototype.toHtmlCell = function () {
    return ("" + this.ID + "	 " +
    "" + this.datetime + "	" +
    "" + this.host + "	" +
    "" + this.program + "	" +
    "" + this.pid + "	" +
    "" + this.message + "	");
};

function renderNew(numRows) {

    if ($("#title").next().length == 0) {
        return true;
    } // Confirm the DOM isn't empty

    // First we need to find out the maximum row ID currently displayed
    // We'll use JQuery to get the first element after the title row
    var currentMaxDisplay = ($("#title").next().attr('id')).substring(3); // TODO: rewrite this with one call to jquery selector

    var oldMaxRecordSet;

    // Find where the highest undisplayed record is in the recordSet
    for (var i = (recordSet.length - 1); i > 0; i--) {
        if (recordSet[i].ID == currentMaxDisplay) {
            oldMaxRecordSet = i;
            i = 0;
        }
    }

    for (i = oldMaxRecordSet; i <= oldMaxRecordSet + numRows; i++) { // TODO: add a try...catch loop to handle the TypeError when we try to use undefined recordSets
        if (recordSet[i].priority  >= document.getElementById("threshold").value) {
            $("#title").after("
");
            $("#row" + recordSet[i].ID).append(recordSet[i].toHtmlCell());
        }
    }
}

// Requests new rows from the server and adds them to the end of the data array
function requestNew(numRows, callback) {

    // If there's no records yet, just start at 0
    var arrayMaxValue = recordSet[(recordSet.length - 1)] ? recordSet[(recordSet.length - 1)].ID : 0;
    // Storing the array length before we start modifying it
    var arrayLength = recordSet.length; // prevents interesting issues with checking the length while changing it
    $.getJSON("response.php", {
            command: "getMessagesNew",
            minID: arrayMaxValue,
            offset: numRows
        },
        function (data) {
            $.each(data, function (key, rowObject) {
                var temp = $.parseJSON(rowObject);
                recordSet[arrayLength + key] = new Record(temp.ID, temp.datetime, temp.host, temp.program, temp.pid, temp.message, temp.priority)
            });
            if (callback) {
                renderNew(50);
            } // POTENTIAL BUG! If we get more than 50 rows between the newMsgISR interval we'll have issue
            // May need to re-think limiting renderNew
        }
    );
}

// Requests old rows from the server and concatenates them to the start of the data array
function requestOld(numRows, renderOnLoad) {

    // If there's no records yet, just start at 0. If there is, start with the ID of the first record
    var arrayMinValue = recordSet[0] ? recordSet[0].ID : 0;

    if (dataInFlight == false) {
        dataInFlight = true;
        $.getJSON("response.php", {
                command: "getMessagesOld",
                maxID: arrayMinValue,
                offset: numRows
            },
            function (data) {
                var tempArray = [];
                $.each(data, function (key, rowObject) {
                    var temp = $.parseJSON(rowObject);
                    tempArray[key] = new Record(temp.ID, temp.datetime, temp.host, temp.program, temp.pid, temp.message, temp.priority)
                });
                recordSet = tempArray.concat(recordSet);
                if (renderOnLoad) {
                    renderOld(30);
                } // Yeah, yeah, this should really be a callback on complete instead of munged into th
                dataInFlight = false;
            }
        );
    }
}

// Gets rows from the data array and adds to the end of the currently shown list
function renderOld(numRows) {

    // First we need to find out the minimum row ID currently displayed
    // We'll use JQuery to get the last

    var currentMinDisplay = ($("tr").last().attr('id').substring(3));

    for (var i = 0;; i++) {

        // Two ways of doing this, throw a break or calculate ahead of time how many rows we need
        if (currentMinDisplay == recordSet[i].ID) {
            break;
        }
        if (recordSet[i].priority  >= document.getElementById("threshold").value) {
            $("#row" + currentMinDisplay).after("
"); // Add the row
            $("#row" + recordSet[i].ID).append(recordSet[i].toHtmlCell());
        }
    }
}

// Initialisation function, calls server and fills our initial table data
function initialiseTable() {
    //  Make a getJSON call asking for the DB length, and set a callback to process that
    $.getJSON("response.php", {
            command: "getDbLen"
        },
        //  Now we have the DB length, make a getJSON call for newMessages and set a callback to process them
        function (dbLength) {
            $.getJSON("response.php", {
                    command: "getMessagesNew",
                    minID: (dbLength - 30), // TODO: Fix this to support an initial non-zero threshold
                    offset: 30
                },
                // Now we have a response from newMessages, add the resulting data to the table
                function (data) {
                    //  For each element in the returned data strip the packaging JSON and put the result in the recordSet array
                    $.each(data, function (key, rowObject) {
                        // parsing the JSON once for speed
                        var temp = $.parseJSON(rowObject);
                        // Currently we're manually setting the properties of the record. Less flexible than dynamically searching the JSON for matching keys, but eh.
                        recordSet[key + 0] = new Record(temp.ID, temp.datetime, temp.host, temp.program, temp.pid, temp.message, temp.priority)
                    });
                    //  Now iterate through the recordSet array and turn each element into an HTML row
                    $.each(recordSet, function (key, data) {
                        $("#title").after("
");
                        $("#row" + recordSet[key].ID).append(recordSet[key].toHtmlCell());
                    });
                });
            //  Last but not least, now we've finished initialising the page we can enable some timed service routines
            //scrollISRInterval = window.setInterval(scrollISR,200);
            window.setInterval(scrollISR, 200);
            window.setInterval(newMsgISR, 5000);

        }
    );
}

// Removes all highlights from the document
function selectionClear(columnID){

    // Selective clearing of a single column is not yet implemented
    $("span:first-child").each(function(){  // For each cell with a span, replace its contents with plain text
        this.parentNode.innerHTML = this.parentNode.textContent;
    });
}

function selectionCommit(updownvote) {

    var regexToCommit = {       // We create the regex with the default pattern for each field, [match all]
        datetime: '.*',
        host:     '.*',
        facility: '.*',
        pid:      '.*',
        program:  '.*',
        message:  '.*',
        priority: updownvote
    };

    if (updownvote == '1') {
        $('#upArrow').height(80);
        $('#upArrow').css('background-size:', 'auto, 80px');
    }

    $("span:first-child").each(function(){                  // For each  element that's the first  in it's cell
                                                                // I.e., for each cell with a span element
        var cellHTML = this.parentNode.innerHTML;           // Grab the cell HTML
            cellHTML.replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1');    // Escape any regex characters that will mess with us later
            if (cellHTML.match(/^/)) {                  // If the selected text starts at line start
                cellHTML = cellHTML.replace(/^/,'^');   // Just remove the first tag
            } else {
                cellHTML = cellHTML.replace(/^.*?/,'^.*'); // Otherwise remove non-selected text from line start to the first span tag, including the tag
            }
            while (cellHTML.match(//)){
                cellHTML = cellHTML.replace(/<\/span>.*?/,'.*'); // As above for each middle tag
            }
            cellHTML = cellHTML.replace(/<\/span>.*$/,'.*');                  // And again for the final tag
            switch (this.parentNode.attributes['id'].value){
                case "datetime":
                    regexToCommit.datetime = cellHTML;
                    break;
                case "host":
                    regexToCommit.host = cellHTML;
                    break;
                case "facility":
                    regexToCommit.facility = cellHTML;
                    break;
                case "pid":
                    regexToCommit.pid = cellHTML;
                    break;
                case "program":
                    regexToCommit.program = cellHTML;
                    break;
                case "message":
                    regexToCommit.message = cellHTML;
                    break;
                default:
                    // Something fishy is happening - shouldn't have a  with different ID
                    console.log("Damnit, Unhygienix - value shouldn't be: "+ rangeObj.startContainer.attributes['id'].value);
            } // Using a switch statement to avoid passing a DOM ID directly
        });

        regexToCommit.command = "regexAdd";

        if (document.getElementById("debug-mode").checked) {
            console.log(regexToCommit);
        }
    $.getJSON("response.php", regexToCommit, function (response) {
                    console.log(response);
                }
        );

    }

function selectionAdd() {

        var workingRowId;
        var rangeObj;                            // The rangeObj object is used specifically when manipulating selected text, can't do it directly
        var selection = window.getSelection ();  // Get the current selected text
        if (!(selection.toString())) {  return;}  // If called when nothing is selected, exit immediately
        rangeObj = selection.getRangeAt(0);      // Create a range object from the selection
        if (rangeObj.endContainer != rangeObj.startContainer) {rangeObj.setEndAfter(rangeObj.startContainer);} // If we have multiple cells selected, adjust the range to only the first cell
        workingRowId = rangeObj.startContainer.parentNode.parentNode.firstChild.innerHTML;
        if (workingRowId != currentRegex.ID) {   // Confirm we're still highlighting the same row
            selectionClear();
            currentRegex.ID = workingRowId;
        }
        var span = document.createElement("span"); // Create a span tag so we can highlight the text for cosmetic purposes
        span.className="selection";              // Set the span to the highlight class
        rangeObj.surroundContents(span);         // Put the span tag on the selected text
        if (rangeObj.startContainer.attributes['id'].value === "ID"){
            selectionClear();
        }
     }

<commit_msg>Commit regexes in SQL like format rather than regex, re-fix incomplete id->class refactor, re-fix use of POST rather than get for adding regexes<commit_after>function Record(ID, datetime, host, program, pid, message, priority, processed, scanned) {
    this.ID = ID;
    this.datetime = datetime;
    this.host = host;
    this.program = program;
    this.pid = pid;
    this.message = message;
    this.priority = priority;
    this.processed = processed;
    this.scanned = scanned;
}
Record.prototype.toHtmlCell = function () {
    return ("" + this.ID + "	 " +
    "" + this.datetime + "	" +
    "" + this.host + "	" +
    "" + this.program + "	" +
    "" + this.pid + "	" +
    "" + this.message + "	");
};

function renderNew(numRows) {

    if ($("#title").next().length == 0) {
        return true;
    } // Confirm the DOM isn't empty

    // First we need to find out the maximum row ID currently displayed
    // We'll use JQuery to get the first element after the title row
    var currentMaxDisplay = ($("#title").next().attr('id')).substring(3); // TODO: rewrite this with one call to jquery selector

    var oldMaxRecordSet;

    // Find where the highest undisplayed record is in the recordSet
    for (var i = (recordSet.length - 1); i > 0; i--) {
        if (recordSet[i].ID == currentMaxDisplay) {
            oldMaxRecordSet = i;
            i = 0;
        }
    }

    for (i = oldMaxRecordSet; i <= oldMaxRecordSet + numRows; i++) { // TODO: add a try...catch loop to handle the TypeError when we try to use undefined recordSets
        if (recordSet[i].priority  >= document.getElementById("threshold").value) {
            $("#title").after("
");
            $("#row" + recordSet[i].ID).append(recordSet[i].toHtmlCell());
        }
    }
}

// Requests new rows from the server and adds them to the end of the data array
function requestNew(numRows, callback) {

    // If there's no records yet, just start at 0
    var arrayMaxValue = recordSet[(recordSet.length - 1)] ? recordSet[(recordSet.length - 1)].ID : 0;
    // Storing the array length before we start modifying it
    var arrayLength = recordSet.length; // prevents interesting issues with checking the length while changing it
    $.getJSON("response.php", {
            command: "getMessagesNew",
            minID: arrayMaxValue,
            offset: numRows
        },
        function (data) {
            $.each(data, function (key, rowObject) {
                var temp = $.parseJSON(rowObject);
                recordSet[arrayLength + key] = new Record(temp.ID, temp.datetime, temp.host, temp.program, temp.pid, temp.message, temp.priority)
            });
            if (callback) {
                renderNew(50);
            } // POTENTIAL BUG! If we get more than 50 rows between the newMsgISR interval we'll have issue
            // May need to re-think limiting renderNew
        }
    );
}

// Requests old rows from the server and concatenates them to the start of the data array
function requestOld(numRows, renderOnLoad) {

    // If there's no records yet, just start at 0. If there is, start with the ID of the first record
    var arrayMinValue = recordSet[0] ? recordSet[0].ID : 0;

    if (dataInFlight == false) {
        dataInFlight = true;
        $.getJSON("response.php", {
                command: "getMessagesOld",
                maxID: arrayMinValue,
                offset: numRows
            },
            function (data) {
                var tempArray = [];
                $.each(data, function (key, rowObject) {
                    var temp = $.parseJSON(rowObject);
                    tempArray[key] = new Record(temp.ID, temp.datetime, temp.host, temp.program, temp.pid, temp.message, temp.priority)
                });
                recordSet = tempArray.concat(recordSet);
                if (renderOnLoad) {
                    renderOld(30);
                } // Yeah, yeah, this should really be a callback on complete instead of munged into th
                dataInFlight = false;
            }
        );
    }
}

// Gets rows from the data array and adds to the end of the currently shown list
function renderOld(numRows) {

    // First we need to find out the minimum row ID currently displayed
    // We'll use JQuery to get the last

    var currentMinDisplay = ($("tr").last().attr('id').substring(3));

    for (var i = 0;; i++) {

        // Two ways of doing this, throw a break or calculate ahead of time how many rows we need
        if (currentMinDisplay == recordSet[i].ID) {
            break;
        }
        if (recordSet[i].priority  >= document.getElementById("threshold").value) {
            $("#row" + currentMinDisplay).after("
"); // Add the row
            $("#row" + recordSet[i].ID).append(recordSet[i].toHtmlCell());
        }
    }
}

// Initialisation function, calls server and fills our initial table data
function initialiseTable() {
    //  Make a getJSON call asking for the DB length, and set a callback to process that
    $.getJSON("response.php", {
            command: "getDbLen"
        },
        //  Now we have the DB length, make a getJSON call for newMessages and set a callback to process them
        function (dbLength) {
            $.getJSON("response.php", {
                    command: "getMessagesNew",
                    minID: (dbLength - 30), // TODO: Fix this to support an initial non-zero threshold
                    offset: 30
                },
                // Now we have a response from newMessages, add the resulting data to the table
                function (data) {
                    //  For each element in the returned data strip the packaging JSON and put the result in the recordSet array
                    $.each(data, function (key, rowObject) {
                        // parsing the JSON once for speed
                        var temp = $.parseJSON(rowObject);
                        // Currently we're manually setting the properties of the record. Less flexible than dynamically searching the JSON for matching keys, but eh.
                        recordSet[key + 0] = new Record(temp.ID, temp.datetime, temp.host, temp.program, temp.pid, temp.message, temp.priority)
                    });
                    //  Now iterate through the recordSet array and turn each element into an HTML row
                    $.each(recordSet, function (key, data) {
                        $("#title").after("
");
                        $("#row" + recordSet[key].ID).append(recordSet[key].toHtmlCell());
                    });
                });
            //  Last but not least, now we've finished initialising the page we can enable some timed service routines
            //scrollISRInterval = window.setInterval(scrollISR,200);
            window.setInterval(scrollISR, 200);
            window.setInterval(newMsgISR, 5000);

        }
    );
}

// Removes all highlights from the document
function selectionClear(columnID){

    // Selective clearing of a single column is not yet implemented
    $("span:first-child").each(function(){  // For each cell with a span, replace its contents with plain text
        this.parentNode.innerHTML = this.parentNode.textContent;
    });
}

function selectionCommit(updownvote) {

    var regexToCommit = {       // We create the regex with the default pattern for each field, [match all]
        datetime: '%',
        host:     '%',
        facility: '%',
        pid:      '%',
        program:  '%',
        message:  '%',
        priority: updownvote
    };

    if (updownvote == '1') {
        $('#upArrow').height(80);
        $('#upArrow').css('background-size:', 'auto, 80px');
    }

    $("span:first-child").each(function(){                  // For each  element that's the first  in it's cell
                                                                // I.e., for each cell with a span element
        var cellHTML = this.parentNode.innerHTML;           // Grab the cell HTML
            cellHTML.replace(/([%_\\])/, '\$1');            // Escape %, _ and \ by adding a \
            if (cellHTML.match(/^/)) {                  // If the selected text starts at line start
                cellHTML = cellHTML.replace(/^/,'');   // Just remove the first tag
            } else {
                cellHTML = cellHTML.replace(/^.*?/,'%'); // Otherwise remove non-selected text from line start to the first span tag, including the tag
            }
            while (cellHTML.match(//)){
                cellHTML = cellHTML.replace(/<\/span>.*?/,'%'); // As above for each middle tag
            }
            cellHTML = cellHTML.replace(/<\/span>.*$/,'%');                  // And again for the final tag
            switch (this.parentNode.attributes['class'].value){
                case "datetime":
                    regexToCommit.datetime = cellHTML;
                    break;
                case "host":
                    regexToCommit.host = cellHTML;
                    break;
                case "facility":
                    regexToCommit.facility = cellHTML;
                    break;
                case "pid":
                    regexToCommit.pid = cellHTML;
                    break;
                case "program":
                    regexToCommit.program = cellHTML;
                    break;
                case "message":
                    regexToCommit.message = cellHTML;
                    break;
                default:
                    // Something fishy is happening - shouldn't have a  with different ID
                    console.log("Damnit, Unhygienix - value shouldn't be: "+ rangeObj.startContainer.attributes['class'].value);
            } // Using a switch statement to avoid passing a DOM ID directly
        });

        regexToCommit.command = "regexAdd";

        if (document.getElementById("debug-mode").checked) {
            console.log(regexToCommit);
        }
    $.post("response.php", regexToCommit, function (response) {
                    console.log(response);
                }
        );

    }

function selectionAdd() {

        var workingRowId;
        var rangeObj;                            // The rangeObj object is used specifically when manipulating selected text, can't do it directly
        var selection = window.getSelection ();  // Get the current selected text
        if (!(selection.toString())) {  return;}  // If called when nothing is selected, exit immediately
        rangeObj = selection.getRangeAt(0);      // Create a range object from the selection
        if (rangeObj.endContainer != rangeObj.startContainer) {rangeObj.setEndAfter(rangeObj.startContainer);} // If we have multiple cells selected, adjust the range to only the first cell
        workingRowId = rangeObj.startContainer.parentNode.parentNode.firstChild.innerHTML;
        if (workingRowId != currentRegex.ID) {   // Confirm we're still highlighting the same row
            selectionClear();
            currentRegex.ID = workingRowId;
        }
        var span = document.createElement("span"); // Create a span tag so we can highlight the text for cosmetic purposes
        span.className="selection";              // Set the span to the highlight class
        rangeObj.surroundContents(span);         // Put the span tag on the selected text
        if (rangeObj.startContainer.attributes['class'].value === "ID"){
            selectionClear();
        }
     }

<|endoftext|>


<commit_before>'use strict';

var ejs = require('elastic.js');

var legacyParams = function (params, q, limit) {
  var err;
  var supported_query_re = new RegExp('^[0-9a-zA-Z#\*\.\_\:\(\)\"\\[\\]\{\}\\-\\+\>\<\= ]+$');

  if (params.search) {
    if (!supported_query_re.test(params.search)) {
      err = Boom.create(400, 'Search not supported: ' + params.search, { timestamp: Date.now() });
      throw err;
    }

    q.query(ejs.QueryStringQuery(params.search));
  } else if (params.count) {
    q.facet(ejs.TermsFacet('count').fields([params.count]).size(limit));
  }

  return q;
};

module.exports = function (params, q, limit) {

  var query = ejs.BoolQuery();

  // Do legacy search
  if (params.search || params.count) {
    return legacyParams(params, q, limit);
  };

  if (params.contains) {
    var correct_query = new RegExp('[0-9\.\,\-]+$');
    if (correct_query.test(params.contains)) {
      var coordinates = params.contains.split(',');
      var coordinates = coordinates.map(parseFloat);

      console.log(coordinates);

      var shape = ejs.Shape('circle', coordinates).radius('1km');

      query = query.should(ejs.GeoShapeQuery()
                              .field('boundingBox')
                              .shape(shape));
      console.log(query);
    }
  }

  return q.query(query);

};
<commit_msg>added intersects parameter<commit_after>'use strict';

var ejs = require('elastic.js');
var Boom = require('boom');
var gjv = require("geojson-validation");

var legacyParams = function (params, q, limit) {
  var err;
  var supported_query_re = new RegExp('^[0-9a-zA-Z#\*\.\_\:\(\)\"\\[\\]\{\}\\-\\+\>\<\= ]+$');

  if (params.search) {
    if (!supported_query_re.test(params.search)) {
      err = Boom.create(400, 'Search not supported: ' + params.search, { timestamp: Date.now() });
      throw err;
    }

    q.query(ejs.QueryStringQuery(params.search));
  } else if (params.count) {
    q.facet(ejs.TermsFacet('count').fields([params.count]).size(limit));
  }

  return q;
};

module.exports = function (params, q, limit) {
  var err;
  var query = ejs.BoolQuery();

  // Do legacy search
  if (params.search || params.count) {
    return legacyParams(params, q, limit);
  };

  if (params.contains) {
    var correct_query = new RegExp('^[0-9\.\,\-]+$');
    if (correct_query.test(params.contains)) {
      var coordinates = params.contains.split(',');
      coordinates = coordinates.map(parseFloat);

      var shape = ejs.Shape('circle', coordinates).radius('1km');

      query = query.should(ejs.GeoShapeQuery()
                              .field('boundingBox')
                              .shape(shape));
    } else {
      err = Boom.create(
        400,
        'Incorrect coordinates: ' + params.contains + '. Only digits, dot, minus and comma are allowd.',
        { timestamp: Date.now() }
      );
      throw err;
    }
  }

  if (params.intersects) {
    var geojson = JSON.parse(params.intersects);
    if (gjv.valid(geojson)) {

      if (geojson.type === 'FeatureCollection') {
        for (var i=0; i < geojson.features.length; i++) {
          var feature = geojson.features[i];
          var shape = ejs.Shape(feature.geometry.type, feature.geometry.coordinates);
          query = query.should(ejs.GeoShapeQuery()
                                  .field('boundingBox')
                                  .shape(shape));
        }
      } else {
        var shape = ejs.Shape(geojson.geometry.type, geojson.geometry.coordinates);
        query = query.should(ejs.GeoShapeQuery()
                                .field('boundingBox')
                                .shape(shape));
      }
    }
  }

  return q.query(query);
};
<|endoftext|>


<commit_before>function maidenhead(_latitude, _longitude)
{
	// http://en.wikipedia.org/wiki/Maidenhead_Locator_System
	// Hacks to avoid negative numbers...

	var longitude = _longitude;
	longitude += 180;
	longitude /= 2;

	var latitude = _latitude;
	latitude += 90;

	function goat(start, offset)
	{
		return String.fromCharCode(start.charCodeAt() + offset);
	}

	var long1 = goat('A', Math.floor(longitude / 10));
	var lat1 = goat('A', Math.floor(latitude / 10));

	var long2 = goat('0', Math.floor(longitude % 10));
	var lat2 = goat('0', Math.floor(latitude % 10));

	var long3 = goat('a', Math.floor((longitude % 1) * 24));
	var lat3 = goat('a', Math.floor((latitude % 1) * 24));

	return {
		maidenhead: long1 + lat1 + long2 + lat2 + long3 + lat3,
		maidenhead_coordinates: {latitude: latitude, longitude: longitude},
		coordinates: {latitude: _latitude, longitude: _longitude},
	};
}

function success(position)
{
	show_location(position.coords.latitude, position.coords.longitude);
}

function show_location(latitude, longitude)
{
	var MAP_ZOOM = 16;
	var location = maidenhead(latitude, longitude);

	$("#waiting").hide();
	$("#geocoder").hide();
	$("#success").show();
	$("#maidenhead").html(location.maidenhead);
	$("#coordinates").html(location.coordinates.latitude + ", " + location.coordinates.longitude);
	$("#maidenhead_coordinates").html(location.maidenhead_coordinates.latitude + ", " + location.maidenhead_coordinates.longitude);
	//$.get("stats", {maidenhead: location.maidenhead}); // TODO Sort privacy implications etc.

	var latlng = new google.maps.LatLng(latitude, longitude);

	var myOptions = {
		zoom: MAP_ZOOM,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var marker = new google.maps.Marker({
		map: map,
		position: latlng,
		title: location.maidenhead,
	});
}

function failure(error)
{
	$("#waiting").hide();
	$("#failure").show();
	$("#error_message").html(error.message);
}

function show_geocoder()
{
	$("#waiting").hide();
	$("#failure").hide();
	$("#success").hide();
	$("#geocoder").show();
}

$(function() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(success, failure);
	} else {
		failure("Your browser does not support Geolocation"); //TODO Improve this failure message
	}

	$(".show_geocoder").click(show_geocoder);

	var geocoder_search_input = document.getElementById("geocoder_search_input");
	var options = {types: ["geocode"]};

	autocomplete = new google.maps.places.Autocomplete(geocoder_search_input, options);

	google.maps.event.addListener(autocomplete, 'place_changed', function() {
		var place = autocomplete.getPlace();
		show_location(place.geometry.location.lat(), place.geometry.location.lng());
	});

	$("footer a").attr("target", "_blank");
});
<commit_msg>Click event tracking<commit_after>function maidenhead(_latitude, _longitude)
{
	// http://en.wikipedia.org/wiki/Maidenhead_Locator_System
	// Hacks to avoid negative numbers...

	var longitude = _longitude;
	longitude += 180;
	longitude /= 2;

	var latitude = _latitude;
	latitude += 90;

	function goat(start, offset)
	{
		return String.fromCharCode(start.charCodeAt() + offset);
	}

	var long1 = goat('A', Math.floor(longitude / 10));
	var lat1 = goat('A', Math.floor(latitude / 10));

	var long2 = goat('0', Math.floor(longitude % 10));
	var lat2 = goat('0', Math.floor(latitude % 10));

	var long3 = goat('a', Math.floor((longitude % 1) * 24));
	var lat3 = goat('a', Math.floor((latitude % 1) * 24));

	return {
		maidenhead: long1 + lat1 + long2 + lat2 + long3 + lat3,
		maidenhead_coordinates: {latitude: latitude, longitude: longitude},
		coordinates: {latitude: _latitude, longitude: _longitude},
	};
}

function success(position)
{
	show_location(position.coords.latitude, position.coords.longitude);
}

function show_location(latitude, longitude)
{
	var MAP_ZOOM = 16;
	var location = maidenhead(latitude, longitude);

	$("#waiting").hide();
	$("#geocoder").hide();
	$("#success").show();
	$("#maidenhead").html(location.maidenhead);
	$("#coordinates").html(location.coordinates.latitude + ", " + location.coordinates.longitude);
	$("#maidenhead_coordinates").html(location.maidenhead_coordinates.latitude + ", " + location.maidenhead_coordinates.longitude);
	//$.get("stats", {maidenhead: location.maidenhead}); // TODO Sort privacy implications etc.

	var latlng = new google.maps.LatLng(latitude, longitude);

	var myOptions = {
		zoom: MAP_ZOOM,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var marker = new google.maps.Marker({
		map: map,
		position: latlng,
		title: location.maidenhead,
	});
}

function failure(error)
{
	$("#waiting").hide();
	$("#failure").show();
	$("#error_message").html(error.message);
}

function show_geocoder()
{
	$("#waiting").hide();
	$("#failure").hide();
	$("#success").hide();
	$("#geocoder").show();
}

$(function() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(success, failure);
	} else {
		failure("Your browser does not support Geolocation"); //TODO Improve this failure message
	}

	$(".show_geocoder").click(show_geocoder);

	var geocoder_search_input = document.getElementById("geocoder_search_input");
	var options = {types: ["geocode"]};

	autocomplete = new google.maps.places.Autocomplete(geocoder_search_input, options);

	google.maps.event.addListener(autocomplete, 'place_changed', function() {
		var place = autocomplete.getPlace();
		show_location(place.geometry.location.lat(), place.geometry.location.lng());
	});

	$("footer a").click(function(e) {
		$.get("click_event", {href: $(this).attr("href")});
	});
	$("footer a").attr("target", "_blank");
});
<|endoftext|>


<commit_before>/**
 * Terminal Module for the Cloud9
 *
 * @copyright 2012, Ajax.org B.V.
 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
 */

define(function(require, exports, module) {
    "use strict";

    module.exports = function(c9) {

        var prefix = 'Cloud9 Help ';
        var wrongPortIP = "You may be using the wrong PORT & IP for your server application.";

        var messages = {
            generic: {
                wrongPortIP: prefix + wrongPortIP + "Try passing $PORT and $IP to properly launch your application. You can find more information in our docs.",
                appRunning: prefix + "Your code is running at https://" + c9.hostname + "",
                bindToInternalIP: prefix + wrongPortIP + "Only binding to the internal IP configured in $IP is supported.",
                noLiveReload: prefix + "We currently only support listening on one port. Opening up a second port for live-reloading is currently not possible.",
                addressInUse: prefix + "There are issues starting your app. Please make sure you are using the correct $IP and $PORT, run as the correct user or kill any processes which might be conflicting. You can find more information in our docs."
            },
            rails: {
                wrongPortIP: prefix + wrongPortIP + "For rails, use: 'rails s -p $PORT -b $IP'. For Sinatra, use: ruby app.rb -p $PORT -o $IP'."
            },
            node: {
                wrongPortIP: prefix + wrongPortIP + " Use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts or refer to the documentation for more information."
            },
            django: {
                wrongPortIP: prefix + wrongPortIP + " Use './manage.py runserver $IP:$PORT' to run your Django application."
            }
        };

        var matchers = [
            {
                // Generic
                pattern: /^(?!reload )server(?: is | )(?:listening|running) (?:at|on)((?!0\.0\.0\.0:8080).)*$/i,
                message: messages.generic.wrongPortIP
            },
            {
                // Generic correct port
                pattern: /^(?!reload )server(?: is | )(?:listening|running) (?:at|on).*?(?=0\.0\.0\.0:8080)/i,
                message: messages.generic.appRunning
            },
            {
                // grunt-serve correct port
                pattern: /Server is running on port (?!8080)/i,
                message: messages.generic.wrongPortIP
            },
            {
                // grunt-serve correct port
                pattern: /Server is running on port 8080/i,
                message: messages.generic.appRunning
            },
            {
                // grunt-reload
                pattern: /^Proxying http:\/\/(?!0\.0\.0\.0:8080)/i,
                message: messages.generic.wrongPortIP
            },
            {
                // grunt-reload
                pattern: /^Proxying http:\/\/(?=0\.0\.0\.0:8080)/i,
                message: messages.generic.appRunning
            },
            {
                // grunt no support for live-reload
                pattern: /^reload server running at http:\/\/.*?:\d{4,5}/i,
                message: messages.generic.noLiveReload
            },
            {
                // Meteor wrong port
                pattern: /(App running at:)((?!0\.0\.0\.0:8080).)*$/,
                message: messages.generic.wrongPortIP
            },
            {
                // Meteor correct port
                pattern: /(App running at:).*?(?=0\.0\.0\.0:8080)/,
                message: messages.generic.appRunning
            },
            {
                // Ionic wrong port
                pattern: /(Running dev server:)((?!\d+\.\d+\.\d+\.\d+:8080).)*$/,
                message: messages.generic.wrongPortIP
            },
            {
                // Ionic correct port
                pattern: /(Running dev server:).*?(?=\d+\.\d+\.\d+\.\d+:8080)/,
                message: messages.generic.appRunning
            },
            {
                // WEBrick correct port
                pattern: /INFO\ \ WEBrick::HTTPServer#start: pid=\d+ port=8080/,
                message: messages.generic.appRunning
            },
            {
                // WEBrick wrong port
                pattern: /INFO\ \ WEBrick::HTTPServer#start: pid=\d+ port=(?!8080)/,
                message: messages.rails.wrongPortIP
            },
            {
                // Rails or Sinatra
                pattern: /WARN {1,2}TCPServer Error: (?:Address already in use|Permission denied) - bind\(2\)/,
                message: messages.rails.wrongPortIP
            },
            {
                // Node app
                pattern: /Error: listen (?:EACCES|EADDRNOTAVAIL)/,
                message: messages.node.wrongPortIP
            },
            {
                // Node address in use
                pattern: /Error: listen EADDRINUSE/,
                message: messages.node.wrongPortIP,
                action: {
                    cmd: "kill -9 $(lsof -i:$PORT -t)",
                    label: "Kill processes"
                }
            },
            {
                // Django correct port
                pattern: /Starting development server at.*?(?=0.0.0.0:8080)/i,
                message: messages.generic.appRunning
            },
            {
                // Django app wrong port
                pattern: /Error: You don't have permission to access that port./,
                message: messages.django.wrongPortIP
            },
            {
                // Django app wrong port
                pattern: /Error: That port is already in use./,
                message: messages.django.wrongPortIP,
                action: {
                    cmd: "kill -9 $(lsof -i:$PORT -t)",
                    label: "Kill processes"
                }
            }
        ];
        return {
            matchers: matchers,
            messages: messages
        };
    };
});
<commit_msg>Fix tests<commit_after>/**
 * Terminal Module for the Cloud9
 *
 * @copyright 2012, Ajax.org B.V.
 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>
 */

define(function(require, exports, module) {
    "use strict";

    module.exports = function(c9) {

        var prefix = 'Cloud9 Help ';
        var wrongPortIP = "You may be using the wrong PORT & IP for your server application.";

        var messages = {
            generic: {
                wrongPortIP: prefix + wrongPortIP + "Try passing $PORT and $IP to properly launch your application. You can find more information in our docs.",
                appRunning: prefix + "Your code is running at https://" + c9.hostname + "",
                bindToInternalIP: prefix + wrongPortIP + "Only binding to the internal IP configured in $IP is supported.",
                noLiveReload: prefix + "We currently only support listening on one port. Opening up a second port for live-reloading is currently not possible.",
                addressInUse: prefix + "There are issues starting your app. Please make sure you are using the correct $IP and $PORT, run as the correct user or kill any processes which might be conflicting. You can find more information in our docs."
            },
            rails: {
                wrongPortIP: prefix + wrongPortIP + "For rails, use: 'rails s -p $PORT -b $IP'. For Sinatra, use: ruby app.rb -p $PORT -o $IP'."
            },
            node: {
                wrongPortIP: prefix + wrongPortIP + " Use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts or refer to the documentation for more information."
            },
            django: {
                wrongPortIP: prefix + wrongPortIP + " Use './manage.py runserver $IP:$PORT' to run your Django application."
            }
        };

        var matchers = [
            {
                // Generic
                pattern: /^(?!reload )server(?: is | )(?:listening|running) (?:at|on)((?!0\.0\.0\.0:8080).)*$/i,
                message: messages.generic.wrongPortIP
            },
            {
                // Generic correct port
                pattern: /^(?!reload )server(?: is | )(?:listening|running) (?:at|on).*?(?=0\.0\.0\.0:8080)/i,
                message: messages.generic.appRunning
            },
            {
                // grunt-serve correct port
                pattern: /Server is running on port (?!8080)/i,
                message: messages.generic.wrongPortIP
            },
            {
                // grunt-serve correct port
                pattern: /Server is running on port 8080/i,
                message: messages.generic.appRunning
            },
            {
                // grunt-reload
                pattern: /^Proxying http:\/\/(?!0\.0\.0\.0:8080)/i,
                message: messages.generic.wrongPortIP
            },
            {
                // grunt-reload
                pattern: /^Proxying http:\/\/(?=0\.0\.0\.0:8080)/i,
                message: messages.generic.appRunning
            },
            {
                // grunt no support for live-reload
                pattern: /^reload server running at http:\/\/.*?:\d{4,5}/i,
                message: messages.generic.noLiveReload
            },
            {
                // Meteor wrong port
                pattern: /(App running at:)((?!0\.0\.0\.0:8080).)*$/,
                message: messages.generic.wrongPortIP
            },
            {
                // Meteor correct port
                pattern: /(App running at:).*?(?=0\.0\.0\.0:8080)/,
                message: messages.generic.appRunning
            },
            {
                // Ionic wrong port
                pattern: /(Running dev server:)((?!\d+\.\d+\.\d+\.\d+:8080).)*$/,
                message: messages.generic.wrongPortIP
            },
            {
                // Ionic correct port
                pattern: /(Running dev server:).*?(?=\d+\.\d+\.\d+\.\d+:8080)/,
                message: messages.generic.appRunning
            },
            {
                // WEBrick correct port
                pattern: /INFO\ \ WEBrick::HTTPServer#start: pid=\d+ port=8080/,
                message: messages.generic.appRunning
            },
            {
                // WEBrick wrong port
                pattern: /INFO\ \ WEBrick::HTTPServer#start: pid=\d+ port=(?!8080)/,
                message: messages.rails.wrongPortIP
            },
            {
                // Rails or Sinatra
                pattern: /WARN {1,2}TCPServer Error: (?:Address already in use|Permission denied) - bind\(2\)/,
                message: messages.rails.wrongPortIP
            },
            {
                // Node app
                pattern: /Error: listen (?:EACCES|EADDRNOTAVAIL)/,
                message: messages.generic.addressInUse
            },
            {
                // Node address in use
                pattern: /Error: listen EADDRINUSE/,
                message: messages.generic.addressInUse,
                action: {
                    cmd: "kill -9 $(lsof -i:$PORT -t)",
                    label: "Kill processes"
                }
            },
            {
                // Django correct port
                pattern: /Starting development server at.*?(?=0.0.0.0:8080)/i,
                message: messages.generic.appRunning
            },
            {
                // Django app wrong port
                pattern: /Error: You don't have permission to access that port./,
                message: messages.django.wrongPortIP
            },
            {
                // Django app wrong port
                pattern: /Error: That port is already in use/,
                message: messages.generic.addressInUse,
                action: {
                    cmd: "kill -9 $(lsof -i:$PORT -t)",
                    label: "Kill processes"
                }
            }
        ];
        return {
            matchers: matchers,
            messages: messages
        };
    };
});
<|endoftext|>


<commit_before>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*eslint no-console: ["error", { allow: ["warn"] }] */

const path = require('path');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const compression = require('compression');

module.exports = function initMiddleware(app, express, config, dirname, redisClient, initializationError) {
  if (!initializationError) {
    if (config.allowHttp) {
      console.warn('WARNING: Allowing HTTP for local debugging');
    } else {
      app.use(require('./sslify'));
      app.use(require('./hsts'));
    }
    require('./appInsights')(app, config);
  }

  app.set('views', path.join(dirname, 'views'));
  app.set('view engine', 'pug');
  app.set('view cache', false);

  app.use(favicon(dirname + '/public/favicon.ico'));

  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(compression());

  app.use(express.static(path.join(dirname, 'public')));

  var passport;
  if (!initializationError) {
    app.use(require('./session')(config, redisClient));
    try {
      passport = require('./passport-config')(app, config);
    } catch (passportError) {
      initializationError = passportError;
    }
  }

  app.use(require('./scrubbedUrl'));
  app.use(require('./logger')(config));
  if (!initializationError && config.websiteSku && !config.allowHttp) {
    app.use(require('./requireSecureAppService'));
  }
  app.use(require('./correlationId'));
  app.use(require('./locals'));

  if (!initializationError) {
    require('./passport-routes')(app, passport, config);
    if (config.onboarding && config.onboarding.length && config.onboarding.length > 0) {
      require('./onboarding')(app, config);
    }
  }

  if (initializationError) {
    throw initializationError;
  }
};
<commit_msg>Move correlation ID assignment higher in stack<commit_after>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*eslint no-console: ["error", { allow: ["warn"] }] */

const path = require('path');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const compression = require('compression');

module.exports = function initMiddleware(app, express, config, dirname, redisClient, initializationError) {
  if (!initializationError) {
    if (config.allowHttp) {
      console.warn('WARNING: Allowing HTTP for local debugging');
    } else {
      app.use(require('./sslify'));
      app.use(require('./hsts'));
    }
    app.use(require('./correlationId'));
    require('./appInsights')(app, config);
  }

  app.set('views', path.join(dirname, 'views'));
  app.set('view engine', 'pug');
  app.set('view cache', false);

  app.use(favicon(dirname + '/public/favicon.ico'));

  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(compression());

  app.use(express.static(path.join(dirname, 'public')));

  var passport;
  if (!initializationError) {
    app.use(require('./session')(config, redisClient));
    try {
      passport = require('./passport-config')(app, config);
    } catch (passportError) {
      initializationError = passportError;
    }
  }

  app.use(require('./scrubbedUrl'));
  app.use(require('./logger')(config));
  if (!initializationError && config.websiteSku && !config.allowHttp) {
    app.use(require('./requireSecureAppService'));
  }
  app.use(require('./locals'));

  if (!initializationError) {
    require('./passport-routes')(app, passport, config);
    if (config.onboarding && config.onboarding.length && config.onboarding.length > 0) {
      require('./onboarding')(app, config);
    }
  }

  if (initializationError) {
    throw initializationError;
  }
};
<|endoftext|>


<commit_before>export default [
    '(business|client|community|culture|customer|data|goal|intelligence|market' +
        '|process|quality|results|role|sales|subject|service|user)' +
        '.(centric(ity)?|facing|oriented|driven|focused|assessment|service|process)',
    '24/7',
    'ai',
    'agile',
    'artificial intelligence',
    'at (your|their) fingertips',
    'autonomous',
    'a[-/]b testing',
    'acquisition',
    'action items?',
    'act in time',
    'advantages?',
    'agents?',
    'aggregate',
    'accelerate',
    'all.in.one',
    'all.new',
    'analytics?',
    'application service providers?',
    'as a service',
    'assets?',
    'authoritative',
    'automated',
    'augmented',
    'extended reality',
    'award.winning',
    'b2(b|c)',
    'back to the drawing board',
    'ball.?park',
    'band.aid',
    'bandwidth',
    '(benefit|gap) analysis',
    'bespoke',
    'best.in.class',
    'best.of.breed',
    'best.practice',
    'big.data',
    'big picture',
    'big thinkers?',
    'block.?chain',
    'blazing(ly)? fast',
    'bottom.line',
    'bottom.up',
    'boost(s|ing)?',
    'brain.?storm(ing)?',
    'brain.?dump',
    'brand(s?|ing|ed)',
    'bright',
    'building.trust',
    'bulletproof',
    'burn.rates?',
    'business( cases| plans)',
    'buzz',
    'call to action',
    'capacity',
    'capabilit(y|ies)',
    'capitali(s|z)e',
    'centers? of excellence',
    'challenges?',
    'change agents?',
    'circle the wagons',
    'client-centered',
    'client-centric',
    'client-focused',
    'cloud',
    'cloud native',
    'cloudify',
    'collaborat(e|ion|ive)s?',
    'committee',
    'communicat(e|ion)s?',
    'company-employee.fit',
    'compelling',
    'competitive( advantage)?',
    'connected systems?',
    'complex(ity)?',
    'comprehensive',
    'connect the dots',
    'container orchestration',
    'containerizat(e|ion|ing)',
    'content management',
    'contextual(ly)?',
    'contingency plans?',
    'control groups?',
    'control plane',
    'convergence',
    'convergent',
    'conversions?',
    'core business',
    'core competenc(y|ies)',
    'core.to.edge',
    'cosmic',
    'cost-effective',
    'cost/benefit',
    'cost control',
    'craftsmanship',
    'critical path',
    'crypto.currency',
    'crypto(?!graphy).\\w+',
    'crm',
    'cross.sell',
    'crowd.?(fund(s?|ed|ing)|sourc(ed|e|ing))',
    'customer obsession',
    'cutting.edge',
    'cyber',
    'dashboards?',
    'dashboarding',
    'data mining',
    'decentrali(s|z)ed',
    'de-?dupe',
    'deep dive',
    'deep learning',
    'delight',
    'deliverables?',
    'demographic',
    'demystify',
    'demystifying',
    'deployless',
    'devops',
    'digital transformation',
    'discovery',
    'distributed ledgers?',
    'disrupt(ive|tor)?',
    'dollar.productive',
    'downsi(s|z)e',
    'drill down',
    'drink the kool-aid',
    'drop.?in',
    'drop the ball',
    'due dilligence',
    'dynamic(s|ally)?',
    'e-?(business|commerce|tailers)',
    'early.stage',
    'eas(y|ily)',
    'ecosystems?',
    'efficien(t|cy)',
    'effortless(ly)?',
    'elastic',
    'elaboration',
    'elephant in the room',
    'elevator pitch',
    'enabl(e|ing)',
    'emerging markets?',
    'empower(ing|ment|s)?',
    'enablement',
    'end of the day',
    'end.to.end',
    'engulf',
    'engag(e|ing)',
    'enhanced?',
    'enterprise',
    'erp',
    'estimate',
    'eta',
    'etched in stone',
    'evolution',
    'exceed expectations',
    'exclusive(ly)?',
    'exhaustive',
    'expedite',
    'experiences',
    'experts?',
    'expertise',
    'exposure',
    'extraordinary',
    'facilitat(e|or)',
    'fast track',
    'fault.tolerant',
    'first.to.market',
    'flexibility',
    'flux',
    'foot view',
    'forward-thinking',
    'four pillars',
    'frictionless',
    'front lines',
    'frustration[- ]free',
    'functional',
    'futurist',
    'full benefit',
    'future.proof',
    'game changer',
    'game plan',
    'behavioral',
    'global(ly)?',
    'go public',
    'go.to.market',
    'goals?',
    'god-speed',
    'going forward',
    'granular',
    'ground.?breaking',
    'growth',
    'grow',
    'guidance',
    'guru',
    'hackathon',
    'hacker( mindset)?',
    'happiness manage(ment|rs?)',
    'hardball',
    'heavy.lifting',
    'herding cats',
    'hidden.gem',
    'hidden.meaning',
    'high.level',
    '(high|mass).impact',
    'highly.scalable',
    'hive ?mind',
    'hybrid environments?',
    'hyper.personalization',
    'hyperconverged',
    'holistic',
    'impactful',
    'impeccable',
    'in a nutshell',
    'incent',
    'incentivi(s|z)e',
    'increase the odds',
    'incredibl(e|y)',
    '(inflat|redeem)able value',
    'influencers?',
    'influx',
    'innovat(e|ed|ion|ive|ing|or)s?',
    'inspir(e|ing|ation)',
    'insights?',
    'integrat(e|ed|ion)s?',
    'internet of things',
    'intellectual property',
    'intuitive',
    'iot',
    'key results?',
    'kickstart(er|ed)?s?',
    'killjoy',
    'knowledge.(base|transfer|sharing)',
    'kpis?',
    'landing pages?',
    'lead the field',
    'leading',
    'leaders?',
    'leadership',
    'learnings',
    'legacy',
    'lessons learned',
    'level (the )? playing field',
    'level set',
    'leverag(e|ing)',
    'lifecycle',
    'low.hanging fruit',
    'look.(&|and).feel',
    'm2m',
    'machine learning',
    'made simple',
    'magical',
    'market (chang(er|ing)|leader|window|simplified)',
    'market.ready',
    'marketing collateral',
    'maximi(s|z)e',
    'meaningful( client | )interactions?',
    'measurements?',
    'methodolog(y|ies)',
    'metrics',
    'middleware',
    'milestone',
    'military.grade encryption',
    'mind ?share',
    'mind ?shower',
    'mind-boggling',
    'mindset',
    '(mission|time).critical',
    'ml',
    'moneti(s|z)e',
    'mov(e|ing) (fast|forward)',
    'multitask(ing?)',
    'multifaceted',
    'multi-?tenant(ed)?',
    'negotiated',
    'networking',
    'new.economy',
    'new.breed',
    '(new|next|second).(level|gen|generation)',
    'niches?',
    'ninja',
    'no-brainer',
    'non-traditional management',
    'objectives',
    'occupy the field',
    'off.site',
    'off.the.(radar|shelf)',
    'on board',
    'on.premises?',
    'on the (back end|radar screen|same page|house)',
    'one to one',
    'opportunit(y|ies)',
    'outperform',
    'optimal',
    'orthogonal',
    'outstanding',
    'out(side)?.of.the.(box|loop)',
    'outsourc(e|ed|ing)',
    '(total cost of )?ownership',
    'paradigms?( shift)?',
    'partner(ships?)?',
    'patents?',
    'performance indicators',
    'personaliz(e|ed|ation)',
    'perspective',
    'phases?',
    'phased approach',
    'pipeline',
    'pioneers',
    'pivot',
    'planning horizon',
    'platforms?',
    'plug.?in',
    'potentials?',
    'powerful',
    'prioriti(s|z)ed?',
    'proactive',
    'problem space',
    'processes',
    'profit(ability)?',
    'promotion',
    'promotional collateral',
    'prominent',
    'proprietary',
    'proof.of.concept',
    'purpose.built',
    'push the envelope',
    'push.back',
    'production.ready',
    'productivity',
    'pushing on open doors',
    'quick wins?',
    'rais(e|ing) the bar',
    'ramp.up',
    'ravishing',
    'relationship management',
    'responsive',
    'engage(ments?)?',
    'reach out',
    'reactivation',
    'real.time',
    'real.world',
    'reconfigure',
    'redefin(e|ed|ing)',
    'red flags?',
    'reengineering',
    'reinvent(ing)? the(.square)? wheel',
    'reinvigorate',
    'relevance',
    'repurpose',
    'resilien(ce|cy|t)',
    'resource allocation',
    'restructuring',
    'retention',
    'return on investment',
    'results',
    'reus(e|ability)',
    'revenue',
    'reverse.engineer',
    'revisit',
    'revolution',
    'rich',
    'road ?map',
    'robust',
    'rock.?star',
    'roi',
    'run the numbers',
    '(s|p)aas',
    'sacrific(e|es|ing)',
    'scal(e|es|ing|ability)',
    'high availability',
    'scenarios?',
    'scope',
    'scrum( master)?',
    'seamless',
    'secret sauce',
    'search engine optimization',
    'segments?',
    'self-managed team',
    'seo',
    '(serial )?entrepreneurs?',
    'serverless',
    'service mesh',
    'shareholder value',
    'significant(ly)?',
    'single-source responsibility',
    'skill ?sets?',
    'smart(er)?',
    'smoke (&|and) mirrors',
    'social(.media|.gaming|.networks?)',
    'solidality',
    'solutions?',
    'sophisticated',
    'soup to nuts',
    'sow',
    'spatial.computing',
    'stakeholders?',
    'start.up?',
    'statement of work',
    'state.of.the.art',
    'step.changes?',
    'sticky-?ness',
    'strateg(y|ic|ize|ise)',
    'streamlin(ed|e|ing)',
    'story points?',
    'success(ful)?',
    'super(critical|star|nova)',
    'sustainab(le|ility)',
    'synerg(y|ies|ized|i)',
    'systems?',
    'tailwinds?',
    'talented',
    'take offline',
    'talking points',
    'target (audience|group)',
    'targeted',
    'tasked',
    'tco',
    'team.building',
    'team.player',
    'teamwork',
    'technolog(y|ies)',
    'that being said',
    'throughput',
    'time.to.awesome',
    'time.to.market',
    'timelines?',
    'top.down',
    'top.of.the.game',
    'total quality',
    'touch.base',
    'touchpoints?',
    'traction',
    'transfor(m|ming)',
    'trends?',
    'true',
    'truths?',
    'turnkey',
    'ultimate',
    'up.to.speed',
    'up-?sell',
    'upside',
    'user.friendly',
    'user funnels?',
    'user.experience',
    'utili(s|z)(e|ation)',
    'uncover',
    'unicorn',
    'unique approach',
    'unlimited.holidays',
    'values?',
    'valueable',
    'value.add(ed)?',
    'venture',
    'venturing',
    'vertical market',
    'viral',
    'virtual(ization|isation)?',
    'visibility',
    'visio(n|nary)',
    'walk the talk',
    'wearable',
    'web.enabled',
    'win-win',
    'wisdom of crowds',
    'with due respect',
    'with ease',
    'wizards?',
    'workflows?',
    'workloads?',
    'world.?class',
    'world a better place',
    'wow.factor',
    'you\'ve never seen (a|an) \\w+',
];
<commit_msg>Added some astonishing bullshit (#125)<commit_after>export default [
    '(business|client|community|culture|customer|data|goal|intelligence|market' +
        '|process|quality|results|role|sales|subject|service|user)' +
        '.(centric(ity)?|facing|oriented|driven|focused|assessment|service|process)',
    '24/7',
    'ai',
    'agile',
    'artificial intelligence',
    'at (your|their) fingertips',
    'autonomous',
    'a[-/]b testing',
    'acquisition',
    'action items?',
    'act in time',
    'advantages?',
    'agents?',
    'aggregat(e|ion)',
    'accelerate',
    'all.in.one',
    'all.new',
    'amazing',
    'analytics?',
    'application service providers?',
    'as a service',
    'assets?',
    'astonishing',
    'authoritative',
    'automated',
    'augmented',
    'extended reality',
    'award.winning',
    'b2(b|c)',
    'back to the drawing board',
    'ball.?park',
    'band.aid',
    'bandwidth',
    '(benefit|gap) analysis',
    'bespoke',
    'best.in.class',
    'best.of.breed',
    'best.practice',
    'big.data',
    'big picture',
    'big thinkers?',
    'block.?chain',
    'blazing(ly)? fast',
    'bottom.line',
    'bottom.up',
    'boost(s|ing)?',
    'brain.?storm(ing)?',
    'brain.?dump',
    'brand(s?|ing|ed)',
    'bright',
    'building.trust',
    'bulletproof',
    'burn.rates?',
    'business( cases| plans)',
    'buzz',
    'call to action',
    'capacity',
    'capabilit(y|ies)',
    'capitali(s|z)e',
    'centers? of excellence',
    'challenges?',
    'change agents?',
    'circle the wagons',
    'client-centered',
    'client-centric',
    'client-focused',
    'cloud',
    'cloud native',
    'cloudify',
    'collaborat(e|ion|ive)s?',
    'committee',
    'communicat(e|ion)s?',
    'company-employee.fit',
    'compelling',
    'competitive( advantage)?',
    'connected systems?',
    'complex(ity)?',
    'comprehensive',
    'connect the dots',
    'container orchestration',
    'containerizat(e|ion|ing)',
    'content management',
    'contextual(ly)?',
    'contingency plans?',
    'control groups?',
    'control plane',
    'convergence',
    'convergent',
    'conversions?',
    'core business',
    'core competenc(y|ies)',
    'core.to.edge',
    'cosmic',
    'cost-effective',
    'cost/benefit',
    'cost control',
    'craftsmanship',
    'critical path',
    'crypto.currency',
    'crypto(?!graphy).\\w+',
    'crm',
    'cross.sell',
    'crowd.?(fund(s?|ed|ing)|sourc(ed|e|ing))',
    'customer obsession',
    'cutting.edge',
    'cyber',
    'dashboards?',
    'dashboarding',
    'data mining',
    'decentrali(s|z)ed',
    'de-?dupe',
    'deep dive',
    'deep learning',
    'delight',
    'deliverables?',
    'demographic',
    'demystify',
    'demystifying',
    'deployless',
    'devops',
    'digital transformation',
    'discovery',
    'distributed ledgers?',
    'disrupt(ive|tor)?',
    'dollar.productive',
    'downsi(s|z)e',
    'drill down',
    'drink the kool-aid',
    'drop.?in',
    'drop the ball',
    'due dilligence',
    'dynamic(s|ally)?',
    'e-?(business|commerce|tailers)',
    'early.stage',
    'eas(y|ily)',
    'ecosystems?',
    'efficien(t|cy)',
    'effortless(ly)?',
    'elastic',
    'elaboration',
    'elephant in the room',
    'elevator pitch',
    'enabl(e|ing)',
    'emerging markets?',
    'empower(ing|ment|s)?',
    'enablement',
    'end of the day',
    'end.to.end',
    'engulf',
    'engag(e|ing)',
    'enhanced?',
    'enterprise',
    'erp',
    'estimate',
    'eta',
    'etched in stone',
    'evolution',
    'exceed expectations',
    'exclusive(ly)?',
    'exhaustive',
    'expedite',
    'experiences',
    'experts?',
    'expertise',
    'exposure',
    'extraordinary',
    'facilitat(e|or)',
    'fast track',
    'fault.tolerant',
    'first.to.market',
    'flexibility',
    'flux',
    'foot view',
    'forward-thinking',
    'four pillars',
    'frictionless',
    'front lines',
    'frustration[- ]free',
    'functional',
    'futurist',
    'full benefit',
    'future.proof',
    'game changer',
    'game plan',
    'behavioral',
    'global(ly)?',
    'go public',
    'go.to.market',
    'goals?',
    'god-speed',
    'going forward',
    'granular',
    'ground.?breaking',
    'growth',
    'grow',
    'guidance',
    'guru',
    'hackathon',
    'hacker( mindset)?',
    'happiness manage(ment|rs?)',
    'hardball',
    'heavy.lifting',
    'herding cats',
    'hidden.gem',
    'hidden.meaning',
    'high.level',
    '(high|mass).impact',
    'highly.scalable',
    'hive ?mind',
    'hybrid environments?',
    'hyper.personalization',
    'hyperconverged',
    'holistic',
    'impactful',
    'impeccable',
    'in a nutshell',
    'incent',
    'incentivi(s|z)e',
    'increase the odds',
    'incredibl(e|y)',
    '(inflat|redeem)able value',
    'influencers?',
    'influx',
    'innovat(e|ed|ion|ive|ing|or)s?',
    'inspir(e|ing|ation)',
    'insights?',
    'integrat(e|ed|ion)s?',
    'internet of things',
    'intellectual property',
    'intuitive',
    'iot',
    'key results?',
    'kickstart(er|ed)?s?',
    'killjoy',
    'knowledge.(base|transfer|sharing)',
    'kpis?',
    'landing pages?',
    'lead the field',
    'leading',
    'leaders?',
    'leadership',
    'learnings',
    'legacy',
    'lessons learned',
    'level (the )? playing field',
    'level set',
    'leverag(e|ing)',
    'lifecycle',
    'low.hanging fruit',
    'look.(&|and).feel',
    'm2m',
    'machine learning',
    'made simple',
    'magical',
    'market (chang(er|ing)|leader|window|simplified|fit)',
    'market.ready',
    'marketing collateral',
    'maximi(s|z)e',
    'meaningful( client | )interactions?',
    'measurements?',
    'methodolog(y|ies)',
    'metrics',
    'middleware',
    'milestone',
    'military.grade encryption',
    'mind ?share',
    'mind ?shower',
    'mind-boggling',
    'mindset',
    '(mission|time).critical',
    'ml',
    'moneti(s|z)e',
    'mov(e|ing) (fast|forward)',
    'multitask(ing?)',
    'multifaceted',
    'multi-?tenant(ed)?',
    'mvp',
    'negotiated',
    'networking',
    'new.economy',
    'new.breed',
    '(new|next|second).(level|gen|generation)',
    'niches?',
    'ninja',
    'no-brainer',
    'non-traditional management',
    'objectives',
    'occupy the field',
    'off.site',
    'off.the.(radar|shelf)',
    'on board',
    'on.premises?',
    'on the (back end|radar screen|same page|house)',
    'one to one',
    'opportunit(y|ies)',
    'outperform',
    'optimal',
    'orthogonal',
    'outstanding',
    'out(side)?.of.the.(box|loop)',
    'outsourc(e|ed|ing)',
    '(total cost of )?ownership',
    'paradigms?( shift)?',
    'partner(ships?)?',
    'patents?',
    'performance indicators',
    'personaliz(e|ed|ation)',
    'perspective',
    'phases?',
    'phased approach',
    'pipeline',
    'pioneers',
    'pivot',
    'planning horizon',
    'platforms?',
    'plug.?in',
    'potentials?',
    'powerful',
    'prioriti(s|z)ed?',
    'proactive',
    'problem space',
    'processes',
    'profit(ability)?',
    'promotion',
    'promotional collateral',
    'prominent',
    'proprietary',
    'proof.of.concept',
    'purpose.built',
    'push the envelope',
    'push.back',
    'production.ready',
    'productivity',
    'pushing on open doors',
    'quick wins?',
    'rais(e|ing) the bar',
    'ramp.up',
    'ravishing',
    'relationship management',
    'responsive',
    'engage(ments?)?',
    'reach out',
    'reactivation',
    'real.time',
    'real.world',
    'reconfigure',
    'redefin(e|ed|ing)',
    'red flags?',
    'reengineering',
    'reinvent(ing)? the(.square)? wheel',
    'reinvigorate',
    'relevance',
    'repurpose',
    'resilien(ce|cy|t)',
    'resource allocation',
    'restructuring',
    'retention',
    'return on investment',
    'results',
    'reus(e|ability)',
    'revenue',
    'reverse.engineer',
    'revisit',
    'revolution',
    'rich',
    'road ?map',
    'robust',
    'rock.?star',
    'roi',
    'run the numbers',
    '(s|p)aas',
    'sacrific(e|es|ing)',
    'scal(e|es|ing|ability)',
    'high availability',
    'scenarios?',
    'scope',
    'scrum( master)?',
    'seamless',
    'secret sauce',
    'search engine optimization',
    'segments?',
    'self-managed team',
    'seo',
    '(serial )?entrepreneurs?',
    'serverless',
    'service mesh',
    'shareholder value',
    'significant(ly)?',
    'single-source responsibility',
    'skill ?sets?',
    'smart(er)?',
    'smoke (&|and) mirrors',
    'social(.media|.gaming|.networks?)',
    'solidality',
    'solutions?',
    'sophisticated',
    'soup to nuts',
    'sow',
    'spatial.computing',
    'stakeholders?',
    'start.up?',
    'statement of work',
    'state.of.the.art',
    'step.changes?',
    'sticky-?ness',
    'strateg(y|ic|ize|ise)',
    'streamlin(ed|e|ing)',
    'story points?',
    'success(ful)?',
    'super(critical|star|nova)',
    'sustainab(le|ility)',
    'synerg(y|ies|ized|i)',
    'systems?',
    'tailwinds?',
    'talented',
    'take offline',
    'talking points',
    'target (audience|group)',
    'targeted',
    'tasked',
    'tco',
    'team.building',
    'team.player',
    'teamwork',
    'technolog(y|ies)',
    'that being said',
    'throughput',
    'time.to.awesome',
    'time.to.market',
    'timelines?',
    'top.down',
    'top.of.the.game',
    'total quality',
    'touch.base',
    'touchpoints?',
    'traction',
    'transfor(m|ming)',
    'trends?',
    'true',
    'truths?',
    'turnkey',
    'ultimate',
    'up.to.speed',
    'up-?sell',
    'upside',
    'user.friendly',
    'user funnels?',
    'user.experience',
    'utili(s|z)(e|ation)',
    'uncover',
    'unicorn',
    'unique approach',
    'unlimited.holidays',
    'values?',
    'valueable',
    'value.add(ed)?',
    'venture',
    'venturing',
    'vertical market',
    'viral',
    'virtual(ization|isation)?',
    'visibility',
    'visio(n|nary)',
    'walk the talk',
    'wearable',
    'web.enabled',
    'win-win',
    'wisdom of crowds',
    'with due respect',
    'with ease',
    'wizards?',
    'workflows?',
    'workloads?',
    'workspace',
    'world.?class',
    'world a better place',
    'wow.factor',
    'you\'ve never seen (a|an) \\w+',
];
<|endoftext|>


<commit_before>// Copyright (c) 2012 UX Productivity Pty Ltd. All rights reserved.

var CONTAINER_ELEMENTS = new Array(HTML_COUNT);
CONTAINER_ELEMENTS[HTML_DOCUMENT] = true;
CONTAINER_ELEMENTS[HTML_HTML] = true;
CONTAINER_ELEMENTS[HTML_BODY] = true;
CONTAINER_ELEMENTS[HTML_UL] = true;
CONTAINER_ELEMENTS[HTML_OL] = true,
CONTAINER_ELEMENTS[HTML_LI] = true;
CONTAINER_ELEMENTS[HTML_TABLE] = true;
CONTAINER_ELEMENTS[HTML_CAPTION] = true;
CONTAINER_ELEMENTS[HTML_THEAD] = true;
CONTAINER_ELEMENTS[HTML_TFOOT] = true;
CONTAINER_ELEMENTS[HTML_TBODY] = true;
CONTAINER_ELEMENTS[HTML_TR] = true;
CONTAINER_ELEMENTS[HTML_TH] = true;
CONTAINER_ELEMENTS[HTML_TD] = true;
CONTAINER_ELEMENTS[HTML_COL] = true;
CONTAINER_ELEMENTS[HTML_FIGURE] = true;
CONTAINER_ELEMENTS[HTML_FIGCAPTION] = true;
CONTAINER_ELEMENTS[HTML_NAV] = true;

var PARAGRAPH_ELEMENTS = new Array(HTML_COUNT);
PARAGRAPH_ELEMENTS[HTML_P] = true;
PARAGRAPH_ELEMENTS[HTML_H1] = true;
PARAGRAPH_ELEMENTS[HTML_H2] = true;
PARAGRAPH_ELEMENTS[HTML_H3] = true;
PARAGRAPH_ELEMENTS[HTML_H4] = true;
PARAGRAPH_ELEMENTS[HTML_H5] = true;
PARAGRAPH_ELEMENTS[HTML_H6] = true;
PARAGRAPH_ELEMENTS[HTML_DIV] = true;
PARAGRAPH_ELEMENTS[HTML_PRE] = true;
PARAGRAPH_ELEMENTS[HTML_BLOCKQUOTE] = true;

var BLOCK_ELEMENTS = new Array(HTML_COUNT);
for (var i = 0; i < HTML_COUNT; i++)
    BLOCK_ELEMENTS[i] = (CONTAINER_ELEMENTS[i] || PARAGRAPH_ELEMENTS[i]);

var INLINE_ELEMENTS = new Array(HTML_COUNT);
for (var i = 0; i < HTML_COUNT; i++)
    INLINE_ELEMENTS[i] = !BLOCK_ELEMENTS[i];

var HEADING_ELEMENTS = new Array(HTML_COUNT);
HEADING_ELEMENTS[HTML_H1] = true;
HEADING_ELEMENTS[HTML_H2] = true;
HEADING_ELEMENTS[HTML_H3] = true;
HEADING_ELEMENTS[HTML_H4] = true;
HEADING_ELEMENTS[HTML_H5] = true;
HEADING_ELEMENTS[HTML_H6] = true;

var CONTAINERS_ALLOWING_CHILDREN = new Array(HTML_COUNT);
CONTAINERS_ALLOWING_CHILDREN[HTML_BODY] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_LI] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_CAPTION] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_TH] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_TD] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_FIGURE] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_FIGCAPTION] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_NAV] = true;

var OUTLINE_TITLE_ELEMENTS = new Array(HTML_COUNT);
OUTLINE_TITLE_ELEMENTS[HTML_H1] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H2] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H3] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H4] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H5] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H6] = true;
OUTLINE_TITLE_ELEMENTS[HTML_FIGCAPTION] = true;
OUTLINE_TITLE_ELEMENTS[HTML_CAPTION] = true;

var Keys = {
    HEADING_NUMBER: "uxwrite-heading-number",
    FIGURE_NUMBER: "uxwrite-figure-number",
    TABLE_NUMBER: "uxwrite-table-number",
    SECTION_TOC: "tableofcontents",
    FIGURE_TOC: "listoffigures",
    TABLE_TOC: "listoftables",
    SELECTION_HIGHLIGHT: "uxwrite-selection-highlight",
    AUTOCORRECT_ENTRY: "uxwrite-autocorrect-entry",
    UXWRITE_PREFIX: "uxwrite-",
    NONE_STYLE: "__none",
    AUTOCORRECT_CLASS: "uxwrite-autocorrect",
    SELECTION_CLASS: "uxwrite-selection",
    ABSTRACT_ELEMENT: "uxwrite-abstract",
};

var ITEM_NUMBER_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
};

var OPAQUE_NODE_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
    "tableofcontents": true,
    "listoffigures": true,
    "listoftables": true,
    "uxwrite-selection-highlight": true,
};

function isContainerNode(node)
{
    return CONTAINER_ELEMENTS[node._type];
}

function isParagraphNode(node)
{
    return PARAGRAPH_ELEMENTS[node._type];
}

function isHeadingNode(node)
{
    return HEADING_ELEMENTS[node._type];
}

function isBlockNode(node)
{
    return BLOCK_ELEMENTS[node._type];
}

function isInlineNode(node)
{
    return INLINE_ELEMENTS[node._type];
}

function isListNode(node)
{
    var type = node._type;
    return ((type == HTML_UL) || (type == HTML_OL));
}

function isTableCell(node)
{
    switch (node._type) {
    case HTML_TD:
    case HTML_TH:
        return true;
    default:
        return false;
    }
}

function isRefNode(node)
{
    return ((node._type == HTML_A) &&
            node.hasAttribute("href") &&
            node.getAttribute("href").charAt(0) == "#");
}

function isItemNumber(node)
{
    if (node.nodeType == Node.TEXT_NODE) {
        return isItemNumber(node.parentNode);
    }
    else if (node.nodeType == Node.ELEMENT_NODE) {
        if ((node._type == HTML_SPAN) && node.hasAttribute("class")) {
            return ITEM_NUMBER_CLASSES[node.getAttribute("class")];
        }
    }
    return false;
}

function isOpaqueNode(node)
{
    if (node == null)
        return false;

    switch (node._type) {
    case HTML_TEXT:
    case HTML_COMMENT:
        return isOpaqueNode(node.parentNode);
    case HTML_IMG:
        return true;
    case HTML_A:
        return node.hasAttribute("href");
    case HTML_DOCUMENT:
        return false;
    default:
        if (node.hasAttribute("class") && OPAQUE_NODE_CLASSES[node.getAttribute("class")])
            return true;
        else
            return isOpaqueNode(node.parentNode);
    }
}

function isAutoCorrectNode(node)
{
    return ((node._type == HTML_SPAN) &&
            (node.getAttribute("class") == Keys.AUTOCORRECT_CLASS));
}

function isSelectionHighlight(node)
{
    return ((node.nodeType == Node.ELEMENT_NODE) &&
            node.getAttribute("class") == Keys.SELECTION_CLASS);
}

function isTOCNode(node)
{
    if (node._type == HTML_NAV) {
        var cls = node.getAttribute("class");
        if ((cls == Keys.SECTION_TOC) ||
            (cls == Keys.FIGURE_TOC) ||
            (cls == Keys.TABLE_TOC))
            return true;
    }
    return false;
}

function isInTOC(node)
{
    if (isTOCNode(node))
        return true;
    if (node.parentNode != null)
        return isInTOC(node.parentNode);
    return false;
}

function isSpecialBlockNode(node)
{
    switch (node._type) {
    case HTML_TABLE:
    case HTML_FIGURE:
        return true;
    case HTML_NAV:
        return isTOCNode(node);
    default:
        return false;
    }
}

function isAbstractSpan(node)
{
    return ((node._type == HTML_SPAN) && node.hasAttribute(Keys.ABSTRACT_ELEMENT));
}
<commit_msg>Treat elements with class uxwrite-field as opaque<commit_after>// Copyright (c) 2012 UX Productivity Pty Ltd. All rights reserved.

var CONTAINER_ELEMENTS = new Array(HTML_COUNT);
CONTAINER_ELEMENTS[HTML_DOCUMENT] = true;
CONTAINER_ELEMENTS[HTML_HTML] = true;
CONTAINER_ELEMENTS[HTML_BODY] = true;
CONTAINER_ELEMENTS[HTML_UL] = true;
CONTAINER_ELEMENTS[HTML_OL] = true,
CONTAINER_ELEMENTS[HTML_LI] = true;
CONTAINER_ELEMENTS[HTML_TABLE] = true;
CONTAINER_ELEMENTS[HTML_CAPTION] = true;
CONTAINER_ELEMENTS[HTML_THEAD] = true;
CONTAINER_ELEMENTS[HTML_TFOOT] = true;
CONTAINER_ELEMENTS[HTML_TBODY] = true;
CONTAINER_ELEMENTS[HTML_TR] = true;
CONTAINER_ELEMENTS[HTML_TH] = true;
CONTAINER_ELEMENTS[HTML_TD] = true;
CONTAINER_ELEMENTS[HTML_COL] = true;
CONTAINER_ELEMENTS[HTML_FIGURE] = true;
CONTAINER_ELEMENTS[HTML_FIGCAPTION] = true;
CONTAINER_ELEMENTS[HTML_NAV] = true;

var PARAGRAPH_ELEMENTS = new Array(HTML_COUNT);
PARAGRAPH_ELEMENTS[HTML_P] = true;
PARAGRAPH_ELEMENTS[HTML_H1] = true;
PARAGRAPH_ELEMENTS[HTML_H2] = true;
PARAGRAPH_ELEMENTS[HTML_H3] = true;
PARAGRAPH_ELEMENTS[HTML_H4] = true;
PARAGRAPH_ELEMENTS[HTML_H5] = true;
PARAGRAPH_ELEMENTS[HTML_H6] = true;
PARAGRAPH_ELEMENTS[HTML_DIV] = true;
PARAGRAPH_ELEMENTS[HTML_PRE] = true;
PARAGRAPH_ELEMENTS[HTML_BLOCKQUOTE] = true;

var BLOCK_ELEMENTS = new Array(HTML_COUNT);
for (var i = 0; i < HTML_COUNT; i++)
    BLOCK_ELEMENTS[i] = (CONTAINER_ELEMENTS[i] || PARAGRAPH_ELEMENTS[i]);

var INLINE_ELEMENTS = new Array(HTML_COUNT);
for (var i = 0; i < HTML_COUNT; i++)
    INLINE_ELEMENTS[i] = !BLOCK_ELEMENTS[i];

var HEADING_ELEMENTS = new Array(HTML_COUNT);
HEADING_ELEMENTS[HTML_H1] = true;
HEADING_ELEMENTS[HTML_H2] = true;
HEADING_ELEMENTS[HTML_H3] = true;
HEADING_ELEMENTS[HTML_H4] = true;
HEADING_ELEMENTS[HTML_H5] = true;
HEADING_ELEMENTS[HTML_H6] = true;

var CONTAINERS_ALLOWING_CHILDREN = new Array(HTML_COUNT);
CONTAINERS_ALLOWING_CHILDREN[HTML_BODY] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_LI] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_CAPTION] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_TH] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_TD] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_FIGURE] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_FIGCAPTION] = true;
CONTAINERS_ALLOWING_CHILDREN[HTML_NAV] = true;

var OUTLINE_TITLE_ELEMENTS = new Array(HTML_COUNT);
OUTLINE_TITLE_ELEMENTS[HTML_H1] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H2] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H3] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H4] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H5] = true;
OUTLINE_TITLE_ELEMENTS[HTML_H6] = true;
OUTLINE_TITLE_ELEMENTS[HTML_FIGCAPTION] = true;
OUTLINE_TITLE_ELEMENTS[HTML_CAPTION] = true;

var Keys = {
    HEADING_NUMBER: "uxwrite-heading-number",
    FIGURE_NUMBER: "uxwrite-figure-number",
    TABLE_NUMBER: "uxwrite-table-number",
    SECTION_TOC: "tableofcontents",
    FIGURE_TOC: "listoffigures",
    TABLE_TOC: "listoftables",
    SELECTION_HIGHLIGHT: "uxwrite-selection-highlight",
    AUTOCORRECT_ENTRY: "uxwrite-autocorrect-entry",
    UXWRITE_PREFIX: "uxwrite-",
    NONE_STYLE: "__none",
    AUTOCORRECT_CLASS: "uxwrite-autocorrect",
    SELECTION_CLASS: "uxwrite-selection",
    ABSTRACT_ELEMENT: "uxwrite-abstract",
};

var ITEM_NUMBER_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
};

var OPAQUE_NODE_CLASSES = {
    "uxwrite-heading-number": true,
    "uxwrite-figure-number": true,
    "uxwrite-table-number": true,
    "tableofcontents": true,
    "listoffigures": true,
    "listoftables": true,
    "uxwrite-selection-highlight": true,
    "uxwrite-field": true,
};

function isContainerNode(node)
{
    return CONTAINER_ELEMENTS[node._type];
}

function isParagraphNode(node)
{
    return PARAGRAPH_ELEMENTS[node._type];
}

function isHeadingNode(node)
{
    return HEADING_ELEMENTS[node._type];
}

function isBlockNode(node)
{
    return BLOCK_ELEMENTS[node._type];
}

function isInlineNode(node)
{
    return INLINE_ELEMENTS[node._type];
}

function isListNode(node)
{
    var type = node._type;
    return ((type == HTML_UL) || (type == HTML_OL));
}

function isTableCell(node)
{
    switch (node._type) {
    case HTML_TD:
    case HTML_TH:
        return true;
    default:
        return false;
    }
}

function isRefNode(node)
{
    return ((node._type == HTML_A) &&
            node.hasAttribute("href") &&
            node.getAttribute("href").charAt(0) == "#");
}

function isItemNumber(node)
{
    if (node.nodeType == Node.TEXT_NODE) {
        return isItemNumber(node.parentNode);
    }
    else if (node.nodeType == Node.ELEMENT_NODE) {
        if ((node._type == HTML_SPAN) && node.hasAttribute("class")) {
            return ITEM_NUMBER_CLASSES[node.getAttribute("class")];
        }
    }
    return false;
}

function isOpaqueNode(node)
{
    if (node == null)
        return false;

    switch (node._type) {
    case HTML_TEXT:
    case HTML_COMMENT:
        return isOpaqueNode(node.parentNode);
    case HTML_IMG:
        return true;
    case HTML_A:
        return node.hasAttribute("href");
    case HTML_DOCUMENT:
        return false;
    default:
        if (node.hasAttribute("class") && OPAQUE_NODE_CLASSES[node.getAttribute("class")])
            return true;
        else
            return isOpaqueNode(node.parentNode);
    }
}

function isAutoCorrectNode(node)
{
    return ((node._type == HTML_SPAN) &&
            (node.getAttribute("class") == Keys.AUTOCORRECT_CLASS));
}

function isSelectionHighlight(node)
{
    return ((node.nodeType == Node.ELEMENT_NODE) &&
            node.getAttribute("class") == Keys.SELECTION_CLASS);
}

function isTOCNode(node)
{
    if (node._type == HTML_NAV) {
        var cls = node.getAttribute("class");
        if ((cls == Keys.SECTION_TOC) ||
            (cls == Keys.FIGURE_TOC) ||
            (cls == Keys.TABLE_TOC))
            return true;
    }
    return false;
}

function isInTOC(node)
{
    if (isTOCNode(node))
        return true;
    if (node.parentNode != null)
        return isInTOC(node.parentNode);
    return false;
}

function isSpecialBlockNode(node)
{
    switch (node._type) {
    case HTML_TABLE:
    case HTML_FIGURE:
        return true;
    case HTML_NAV:
        return isTOCNode(node);
    default:
        return false;
    }
}

function isAbstractSpan(node)
{
    return ((node._type == HTML_SPAN) && node.hasAttribute(Keys.ABSTRACT_ELEMENT));
}
<|endoftext|>


<commit_before>/**
 * ownCloud
 *
 * @author Robin Appelman
 * @copyright 2012 Robin Appelman icewind1991@gmail.com
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * wrapper for server side events (http://en.wikipedia.org/wiki/Server-sent_events)
 * includes a fallback for older browsers and IE
 *
 * use server side events with causion, to many open requests can hang the server
 */

OC.EventSource=function(src){
	if(!this.useFallBack && typeof EventSource !='undefined'){
		this.source=new EventSource(src);
		this.source.onmessage=function(e){
			for(var i=0;i<this.typelessListeners.length;i++){
				this.typelessListeners[i](JSON.parse(e.data));
			}
		}
	}else{
		iframeId='oc_eventsource_iframe_'+OC.EventSource.iframeCount;
		OC.EventSource.fallBackSources[OC.EventSource.iframeCount]=this;
		this.iframe=$('<iframe/>');
		this.iframe.attr('id',iframeId);
		this.iframe.hide();
		this.iframe.attr('src',src+'?fallback=true&fallback_id='+OC.EventSource.iframeCount);
		$('body').append(this.iframe);
		this.useFallBack=true;
		OC.EventSource.iframeCount++
	}
	//add close listener
	this.listen('__internal__',function(data){
		if(data=='close'){
			this.close();
		}
	}.bind(this));
}
OC.EventSource.fallBackSources=[];
OC.EventSource.iframeCount=0;//number of fallback iframes
OC.EventSource.fallBackCallBack=function(id,type,data){
	OC.EventSource.fallBackSources[id].fallBackCallBack(type,JSON.parse(data));
}
OC.EventSource.prototype={
	typelessListeners:[],
	iframe:null,
	listeners:{},//only for fallback
	useFallBack:false,
	fallBackCallBack:function(type,data){
		if(type){
			for(var i=0;i<this.listeners[type].length;i++){
				this.listeners[type][i](data);
			}
		}else{
			for(var i=0;i<this.typelessListeners.length;i++){
				this.typelessListeners[i](data);
			}
		}
	},
	lastLength:0,//for fallback
	listen:function(type,callback){
		if(callback && callback.call){

			if(type){
				if(this.useFallBack){
					if(!this.listeners[type]){
						this.listeners[type]=[];
					}
					this.listeners[type].push(callback);
				}else{
					this.source.addEventListener(type,function(e){
						callback(JSON.parse(e.data));
					},false);
				}
			}else{
				typelessListeners.push(callback);
			}
		}
	},
	close:function(){
		this.source.close();
	}
}
<commit_msg>add option to send get data along with an eventsource request<commit_after>/**
 * ownCloud
 *
 * @author Robin Appelman
 * @copyright 2012 Robin Appelman icewind1991@gmail.com
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * wrapper for server side events (http://en.wikipedia.org/wiki/Server-sent_events)
 * includes a fallback for older browsers and IE
 *
 * use server side events with causion, to many open requests can hang the server
 */

/**
 * create a new event source
 * @param string src
 * @param object data to be send as GET
 */
OC.EventSource=function(src,data){
	var dataStr='';
	for(name in data){
		dataStr+=name+'='+encodeURIComponent(data[name])+'&';
	}
	if(!this.useFallBack && typeof EventSource !='undefined'){
		this.source=new EventSource(src+'?'+dataStr);
		this.source.onmessage=function(e){
			for(var i=0;i<this.typelessListeners.length;i++){
				this.typelessListeners[i](JSON.parse(e.data));
			}
		}
	}else{
		iframeId='oc_eventsource_iframe_'+OC.EventSource.iframeCount;
		OC.EventSource.fallBackSources[OC.EventSource.iframeCount]=this;
		this.iframe=$('<iframe/>');
		this.iframe.attr('id',iframeId);
		this.iframe.hide();
		this.iframe.attr('src',src+'?fallback=true&fallback_id='+OC.EventSource.iframeCount+'&'+dataStr);
		$('body').append(this.iframe);
		this.useFallBack=true;
		OC.EventSource.iframeCount++
	}
	//add close listener
	this.listen('__internal__',function(data){
		if(data=='close'){
			this.close();
		}
	}.bind(this));
}
OC.EventSource.fallBackSources=[];
OC.EventSource.iframeCount=0;//number of fallback iframes
OC.EventSource.fallBackCallBack=function(id,type,data){
	OC.EventSource.fallBackSources[id].fallBackCallBack(type,JSON.parse(data));
}
OC.EventSource.prototype={
	typelessListeners:[],
	iframe:null,
	listeners:{},//only for fallback
	useFallBack:false,
	fallBackCallBack:function(type,data){
		if(type){
			for(var i=0;i<this.listeners[type].length;i++){
				this.listeners[type][i](data);
			}
		}else{
			for(var i=0;i<this.typelessListeners.length;i++){
				this.typelessListeners[i](data);
			}
		}
	},
	lastLength:0,//for fallback
	listen:function(type,callback){
		if(callback && callback.call){

			if(type){
				if(this.useFallBack){
					if(!this.listeners[type]){
						this.listeners[type]=[];
					}
					this.listeners[type].push(callback);
				}else{
					this.source.addEventListener(type,function(e){
						callback(JSON.parse(e.data));
					},false);
				}
			}else{
				typelessListeners.push(callback);
			}
		}
	},
	close:function(){
		this.source.close();
	}
}
<|endoftext|>