<commit_before>/**
 * @fileOverview Nepi Jano Google Chrome extension
 * @author Miroslav Magda, http://blog.ejci.net
 * @version 0.10.0
 */

(function() {
	/**
	 * some utils
	 */
	var utils = {};

	/**
	 * Get parameter from url (if exists)
	 */
	utils.urlParam = function(name, url) {
		url = (url) ? url : window.location.href;
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(url);
		if (results === null) {
			return false;
		} else {
			return results[1];
		}
		return false;
	};

	/**
	 * Remove elemtns with selector from document
	 */
	utils.removeSelector = function(doc, selector) {
		var elements = doc.querySelectorAll(selector);
		var i = elements.length;
		while (i--) {
			elements[i].parentNode.removeChild(elements[i]);
		}
		return doc;
	};

	/**
	 * Fix urls in anchors
	 */
	utils.fixAnchors = function(doc) {
		var elements = doc.querySelectorAll('a');
		var i = elements.length;
		while (i--) {
			var url = elements[i].getAttribute('href');
			var articleId = utils.urlParam('c', url);
			var galleryId = utils.urlParam('g', url);
			if (/s.sme.sk\//i.test(url) && articleId) {
				elements[i].setAttribute('href', document.location.protocol + '//' + document.location.hostname + '/c/' + articleId + '/');
			}
			if (/s.sme.sk\//i.test(url) && galleryId) {
				elements[i].setAttribute('href', document.location.protocol + '//' + document.location.hostname + '/galeria/' + galleryId + '/' + Math.random().toString(36).substr(2, length) + '/');
			}

		}
		return doc;
	};
	/**
	 * Fix video tags
	 */
	utils.fixVideos = function(doc) {
		var elements = doc.querySelectorAll('.iosvideo');
		var i = elements.length;
		while (i--) {
			var videoUrl = elements[i].querySelector('a[href$=mp4]').getAttribute('href');
			var videoPosterUrl = elements[i].querySelector('.videoimg').getAttribute('src');
			elements[i].innerHTML = '<video src="' + videoUrl + '" controls poster="' + videoPosterUrl + '" width="100%" preload="none">';
		}
		return doc;
	};
	/**
	 * Get article id from url
	 */
	utils.articleId = function() {
		var articleId = document.location.pathname.split('/')[2];
		if (parseInt(articleId, 10) == articleId) {
			return articleId;
		} else {
			return false;
		}
		return false;
	};

	/**
	 * Get mobile version article
	 */
	utils.getArticle = function(cb) {
		var articleId = utils.articleId();
		request = new XMLHttpRequest();
		request.open('GET', 'http://s.sme.sk/export/ma/?c=' + articleId, true);
		request.onload = function() {
			if (request.status >= 200 && request.status < 400) {
				//				try {
				var doc = (new DOMParser()).parseFromString(request.responseText, "text/html");
				doc = utils.removeSelector(doc, 'script');
				doc = utils.removeSelector(doc, 'link');
				doc = utils.removeSelector(doc, 'style');
				doc = utils.removeSelector(doc, '.button-bar');
				doc = utils.fixAnchors(doc);
				doc = utils.fixVideos(doc);
// check for article tag from new format and if it exists send it back
                		if(document.getElementsByTagName("article")[0]){
                    			cb(doc.getElementsByTagName("article")[0]);
// if article tag is not found continue "the old way"
		                } else {
                	    		cb(doc.querySelector('.articlewrap'));
                		}
				//				} catch(e) {

				//				}
			}
		};
		request.send();
	};

	/**
	 * Get article id from url
	 */
	utils.isPiano = function() {
		var ret = false;
		var selectors = [];
		selectors.push('#article-box #itext_content .art-perex-piano');
		selectors.push('#article-box #itext_content .art-nexttext-piano');
// check for new format article containers
        	selectors.push('#article-box #itext_content .sme_piano_art_promo');
        	selectors.push('#js-article .sme_piano_art_promo');
        	selectors.push('.piano-teaser-wrapper');
		selectors.push('#article-box div[id^=pianoArticle]');
		for (var i = 0, l = selectors.length; i < l; i++) {
			ret = ret || (document.querySelectorAll(selectors[i]).length != 0);
		}
		return ret;
	};

	if (/sme.sk\/c\//i.test(document.location)) {
		if (utils.isPiano()) {
			utils.getArticle(function(html) {
                		if(html){
// check if the old format of the page is used and replace the content
                    			if(document.querySelector('#article-box #itext_content')){
                        			document.querySelector('#article-box #itext_content').innerHTML = html.innerHTML;
// if not look for the new container
                      			} else if(document.getElementsByTagName('article')){
                        			document.getElementsByTagName('article')[0].innerHTML = html.innerHTML;
                 			}
                		}
			});
		}
	}
})();
<commit_msg>Document refference fix and a minor clean up<commit_after>/**
 * @fileOverview Nepi Jano Google Chrome extension
 * @author Miroslav Magda, http://blog.ejci.net
 * @version 0.10.0
 */

(function() {
	/**
	 * some utils
	 */
	var utils = {};

	/**
	 * Get parameter from url (if exists)
	 */
	utils.urlParam = function(name, url) {
		url = (url) ? url : window.location.href;
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(url);
		if (results === null) {
			return false;
		} else {
			return results[1];
		}
		return false;
	};

	/**
	 * Remove elemtns with selector from document
	 */
	utils.removeSelector = function(doc, selector) {
		var elements = doc.querySelectorAll(selector);
		var i = elements.length;
		while (i--) {
			elements[i].parentNode.removeChild(elements[i]);
		}
		return doc;
	};

	/**
	 * Fix urls in anchors
	 */
	utils.fixAnchors = function(doc) {
		var elements = doc.querySelectorAll('a');
		var i = elements.length;
		while (i--) {
			var url = elements[i].getAttribute('href');
			var articleId = utils.urlParam('c', url);
			var galleryId = utils.urlParam('g', url);
			if (/s.sme.sk\//i.test(url) && articleId) {
				elements[i].setAttribute('href', document.location.protocol + '//' + document.location.hostname + '/c/' + articleId + '/');
			}
			if (/s.sme.sk\//i.test(url) && galleryId) {
				elements[i].setAttribute('href', document.location.protocol + '//' + document.location.hostname + '/galeria/' + galleryId + '/' + Math.random().toString(36).substr(2, length) + '/');
			}

		}
		return doc;
	};
	/**
	 * Fix video tags
	 */
	utils.fixVideos = function(doc) {
		var elements = doc.querySelectorAll('.iosvideo');
		var i = elements.length;
		while (i--) {
			var videoUrl = elements[i].querySelector('a[href$=mp4]').getAttribute('href');
			var videoPosterUrl = elements[i].querySelector('.videoimg').getAttribute('src');
			elements[i].innerHTML = '<video src="' + videoUrl + '" controls poster="' + videoPosterUrl + '" width="100%" preload="none">';
		}
		return doc;
	};
	/**
	 * Get article id from url
	 */
	utils.articleId = function() {
		var articleId = document.location.pathname.split('/')[2];
		if (parseInt(articleId, 10) == articleId) {
			return articleId;
		} else {
			return false;
		}
		return false;
	};

	/**
	 * Get mobile version article
	 */
	utils.getArticle = function(cb) {
		var articleId = utils.articleId();
		request = new XMLHttpRequest();
		request.open('GET', 'http://s.sme.sk/export/ma/?c=' + articleId, true);
		request.onload = function() {
			if (request.status >= 200 && request.status < 400) {
				//				try {
				var doc = (new DOMParser()).parseFromString(request.responseText, "text/html");
				doc = utils.removeSelector(doc, 'script');
				doc = utils.removeSelector(doc, 'link');
				doc = utils.removeSelector(doc, 'style');
				doc = utils.removeSelector(doc, '.button-bar');
				doc = utils.fixAnchors(doc);
				doc = utils.fixVideos(doc);
// check for article tag from new format and if it exists send it back
                		if(doc.getElementsByTagName("article")[0]){
                    			cb(doc.getElementsByTagName("article")[0]);
// if article tag is not found continue "the old way"
		                } else {
                	    		cb(doc.querySelector('.articlewrap'));
                		}
				//				} catch(e) {

				//				}
			}
		};
		request.send();
	};

	/**
	 * Get article id from url
	 */
	utils.isPiano = function() {
		var ret = false;
		var selectors = [];
		selectors.push('#article-box #itext_content .art-perex-piano');
		selectors.push('#article-box #itext_content .art-nexttext-piano');
// check for new format article containers
        	selectors.push('.piano-teaser-wrapper');
        	selectors.push('#pianoSmePromoBox');
        	selectors.push('.sme_piano_art_promo');
		selectors.push('#article-box div[id^=pianoArticle]');
		for (var i = 0, l = selectors.length; i < l; i++) {
			ret = ret || (document.querySelectorAll(selectors[i]).length != 0);
		}
		return ret;
	};

	if (/sme.sk\/c\//i.test(document.location)) {
		if (utils.isPiano()) {
			utils.getArticle(function(html) {
                		if(html){
// check if the old format of the page is used and replace the content
                    			if(document.querySelector('#article-box #itext_content')){
                        			document.querySelector('#article-box #itext_content').innerHTML = html.innerHTML;
// if not look for the new container
                      			} else if(document.getElementsByTagName('article')){
                        			document.getElementsByTagName('article')[0].innerHTML = html.innerHTML;
                 			}
                		}
			});
		}
	}
})();
<|endoftext|>


<commit_before>
// Construct map, center if no location provided
var map = L.map('map', { maxZoom: 13 } );
var hash = new L.Hash(map);
if (!window.location.hash) {
    map.setView([37.958, -120.976], 8);
}

// Make the base map; a raster tile relief map from ESRI
var esriRelief = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}';

var basemap = L.tileLayer(esriRelief, {
  attribution: 'ESRI shaded relief, NHDPlus v2',
  maxZoom: 13
});
basemap.addTo(map);

// Add a single GeoJSON vector file for state boundaries
// This was loaded statically as a script; could also be AJAX
var stateLayer = new L.geoJson(usStates);
stateLayer.setStyle({ "color": "#444",
                      "weight": 1,
                      "fill": false,
                      "opacity": 1.0 });
stateLayer.addTo(map);

var nlcdlayer = L.tileLayer('/nlcd/{z}/{x}/{y}.png',{tms:true}).addTo(map);

var requestsPool = {
  requests: {}, //list of urls
  timeouts: {},
  timeout:  1000*60*10, //In milliseconds
  fetch: function(url) {
    if(requestsPool.exists(url))
      return requestsPool.requests[url];

    requestsPool.timeouts[url] = setTimeout(function(u) {
        requestsPool.remove(u);
    }.bind(this, url), requestsPool.timeout); //Defining the timeout

    requestsPool.requests[url] = $.getJSON(url);
    return requestsPool.requests[url];
  },
  exists: function(url) {
    return requestsPool.requests.hasOwnProperty(url); //Return the Timeout ID if present or undefined
  },
  remove: function(url) {
    requestsPool.cancel(url);
    delete requestsPool.requests[url];
  },
  cancel: function(url) {
    clearTimeout(requestsPool.timeouts[url]); //cancel the timeout
    delete requestsPool.timeouts[url];
  }
}

var riverinfo = {};

function StyleTheRivers(feature){
  requestsPool.fetch('/gauges/reachflow/'+feature.properties.huc8)
  .done(function(val){
    riverinfo[feature.properties.huc8]=val;
    $('.h'+feature.properties.huc8).css('stroke', (val.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*val.drank)]:'#FF00DE' );
    $('.h'+feature.properties.huc8).css('stroke-width', ((val.drank!==null)?(6*val.drank+2).toString():'2')+'px' );
  });
}
//$.getJSON('/gauges/reachflow/'+feature.properties.huc8, function(data){

// Style the river lines; width depends on its Strahler number
function riverStyle(feature) {
  return "stroke-width: " + feature.properties.strahler * map.getZoom()/13 + "px;stroke:#FF00DE;";
}

function riverClass(feature){
  StyleTheRivers(feature);
  return "river h" + feature.properties.huc8;
}

// Make the river overlay layer, vector tiles from our TileStache/Gunicorn server
var geojsonURL = "/rivers/{z}/{x}/{y}.json";
var riverLayer = new L.TileLayer.d3_geoJSON(geojsonURL, {
  class: riverClass,
  style: riverStyle
});
map.addLayer(riverLayer);

map.on('dragend', function(e) {
  //$('#spinnerBox').fadeIn();
  getStations();
});

map.on('zoomend', function() {
  getStations();
});

var markers = new L.FeatureGroup();
map.addLayer(markers);

var grad_colours = ['#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac']

var baseLayers = {
  "Terrain": basemap,
};

var overlays = {
  "NLCD":           nlcdlayer,
  "Rivers":         riverLayer,
  "Gauge Stations": markers
};

L.control.layers(baseLayers, overlays).addTo(map);

function getStations() {
  // Clear markers before getting new ones
  markers.clearLayers();

  // Get map bounds from Leaflet.  getBounds() returns an object
  var bbox = map.getBounds();

  var addy = "/gauges/list/xmin/ymin/xmax/ymax";
  addy     = addy.replace("xmin",bbox._southWest.lng);
  addy     = addy.replace("ymin",bbox._southWest.lat);
  addy     = addy.replace("xmax",bbox._northEast.lng);
  addy     = addy.replace("ymax",bbox._northEast.lat);

  //use jQuery's getJSON() to call the SODA API for NYC 311
  $.getJSON(addy, function(data) {
    //iterate over each 311 complaint, add a marker to the map
    _.each(data, function(marker){
      var markerItem = L.circleMarker(
        [marker.lat,marker.lng],
        {
          radius:      5,
          color:       'black',
          fillColor:   (marker.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*marker.drank)]:'#FF00DE',
          fillOpacity: 1
        }
      );
      markerItem.on('mouseover', function(){
        $('#headerbar').html(marker.name);
        $('#bottomright').html(
          'Stage: ' + marker.svalue + ' ft
' +
          ''+marker.sdt+'
' +
          'Discharge: ' + marker.dvalue + ' cfs
' +
          ''+marker.ddt+'
' +
          'Rank: ' + marker.drank.toFixed(2) + '
' +
          'More info here'
          );
        console.log(marker);
      });

      // markerItem.bindPopup(
      //   '
' + marker.complaint_type + '
'
      //   + (new Date(marker.created_date)).toDateString()
      //   + ((marker.incident_address != null) ? '
' + marker.incident_address : '')
      // );

      markers.addLayer(markerItem);
    });
    map.addLayer(markers);
  });
}

$('.nlcdgrad').hover(function(e){
  var classname = $(e.target).data('classname');
  $('#nlcdexplanation').html(classname);
}, function(){
  $('#nlcdexplanation').html('NLCD Legend (hover over colours for details)');
})

/*var counties = new L.geoJson();
counties.addTo(map);
$.getJSON({
  dataType: "json",
  url:      "counties.json",
  success:  function(data) {
    $(data.features).each(function(key, data) {
        counties.addData(data);
    });
}
}).error(function() {});
*/
<commit_msg>Gauges on load<commit_after>
// Construct map, center if no location provided
var map = L.map('map', { maxZoom: 13 } );
var hash = new L.Hash(map);
if (!window.location.hash) {
    map.setView([37.958, -120.976], 8);
}

// Make the base map; a raster tile relief map from ESRI
var esriRelief = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}';

var basemap = L.tileLayer(esriRelief, {
  attribution: 'ESRI shaded relief, NHDPlus v2',
  maxZoom: 13
});
basemap.addTo(map);

// Add a single GeoJSON vector file for state boundaries
// This was loaded statically as a script; could also be AJAX
var stateLayer = new L.geoJson(usStates);
stateLayer.setStyle({ "color": "#444",
                      "weight": 1,
                      "fill": false,
                      "opacity": 1.0 });
stateLayer.addTo(map);

var nlcdlayer = L.tileLayer('/nlcd/{z}/{x}/{y}.png',{tms:true}).addTo(map);

var requestsPool = {
  requests: {}, //list of urls
  timeouts: {},
  timeout:  1000*60*10, //In milliseconds
  fetch: function(url) {
    if(requestsPool.exists(url))
      return requestsPool.requests[url];

    requestsPool.timeouts[url] = setTimeout(function(u) {
        requestsPool.remove(u);
    }.bind(this, url), requestsPool.timeout); //Defining the timeout

    requestsPool.requests[url] = $.getJSON(url);
    return requestsPool.requests[url];
  },
  exists: function(url) {
    return requestsPool.requests.hasOwnProperty(url); //Return the Timeout ID if present or undefined
  },
  remove: function(url) {
    requestsPool.cancel(url);
    delete requestsPool.requests[url];
  },
  cancel: function(url) {
    clearTimeout(requestsPool.timeouts[url]); //cancel the timeout
    delete requestsPool.timeouts[url];
  }
}

var riverinfo = {};

function StyleTheRivers(feature){
  requestsPool.fetch('/gauges/reachflow/'+feature.properties.huc8)
  .done(function(val){
    riverinfo[feature.properties.huc8]=val;
    $('.h'+feature.properties.huc8).css('stroke', (val.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*val.drank)]:'#FF00DE' );
    $('.h'+feature.properties.huc8).css('stroke-width', ((val.drank!==null)?(6*val.drank+2).toString():'2')+'px' );
  });
}
//$.getJSON('/gauges/reachflow/'+feature.properties.huc8, function(data){

// Style the river lines; width depends on its Strahler number
function riverStyle(feature) {
  return "stroke-width: " + feature.properties.strahler * map.getZoom()/13 + "px;stroke:#FF00DE;";
}

function riverClass(feature){
  StyleTheRivers(feature);
  return "river h" + feature.properties.huc8;
}

// Make the river overlay layer, vector tiles from our TileStache/Gunicorn server
var geojsonURL = "/rivers/{z}/{x}/{y}.json";
var riverLayer = new L.TileLayer.d3_geoJSON(geojsonURL, {
  class: riverClass,
  style: riverStyle
});
map.addLayer(riverLayer);

map.on('dragend', function(e) {
  //$('#spinnerBox').fadeIn();
  getStations();
});

map.on('zoomend', function() {
  getStations();
});

var markers = new L.FeatureGroup();
map.addLayer(markers);

var grad_colours = ['#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac']

var baseLayers = {
  "Terrain": basemap,
};

var overlays = {
  "NLCD":           nlcdlayer,
  "Rivers":         riverLayer,
  "Gauge Stations": markers
};

L.control.layers(baseLayers, overlays).addTo(map);

function getStations() {
  // Clear markers before getting new ones
  markers.clearLayers();

  // Get map bounds from Leaflet.  getBounds() returns an object
  var bbox = map.getBounds();

  var addy = "/gauges/list/xmin/ymin/xmax/ymax";
  addy     = addy.replace("xmin",bbox._southWest.lng);
  addy     = addy.replace("ymin",bbox._southWest.lat);
  addy     = addy.replace("xmax",bbox._northEast.lng);
  addy     = addy.replace("ymax",bbox._northEast.lat);

  //use jQuery's getJSON() to call the SODA API for NYC 311
  $.getJSON(addy, function(data) {
    //iterate over each 311 complaint, add a marker to the map
    _.each(data, function(marker){
      var markerItem = L.circleMarker(
        [marker.lat,marker.lng],
        {
          radius:      5,
          color:       'black',
          fillColor:   (marker.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*marker.drank)]:'#FF00DE',
          fillOpacity: 1
        }
      );
      markerItem.on('mouseover', function(){
        $('#headerbar').html(marker.name);
        $('#bottomright').html(
          'Stage: ' + marker.svalue + ' ft
' +
          ''+marker.sdt+'
' +
          'Discharge: ' + marker.dvalue + ' cfs
' +
          ''+marker.ddt+'
' +
          'Rank: ' + marker.drank.toFixed(2) + '
' +
          'More info here'
          );
        console.log(marker);
      });

      // markerItem.bindPopup(
      //   '
' + marker.complaint_type + '
'
      //   + (new Date(marker.created_date)).toDateString()
      //   + ((marker.incident_address != null) ? '
' + marker.incident_address : '')
      // );

      markers.addLayer(markerItem);
    });
    map.addLayer(markers);
  });
}

$('.nlcdgrad').hover(function(e){
  var classname = $(e.target).data('classname');
  $('#nlcdexplanation').html(classname);
}, function(){
  $('#nlcdexplanation').html('NLCD Legend (hover over colours for details)');
})

$(document).ready(function(){
  getStations();
});

/*var counties = new L.geoJson();
counties.addTo(map);
$.getJSON({
  dataType: "json",
  url:      "counties.json",
  success:  function(data) {
    $(data.features).each(function(key, data) {
        counties.addData(data);
    });
}
}).error(function() {});
*/
<|endoftext|>


<commit_before>/*
  options = {
    uploadURL: string,
    getImageURL: function(xhr, file) {},
    postData: object (optional),
    chunkSize: string (optional, default "1MiB")
  }
*/
$.fn.markDownImageHandler = function(options) {
    $(this).each(function(t, target) {
        var $textarea = $(target);

        $textarea.imageDropZone(handleFiles);

        $textarea.on('paste', function (event) {
            for (var i = event.originalEvent.clipboardData.items.length - 1; i >= 0; i--) {
                var item = event.originalEvent.clipboardData.items[i];
                if (item.kind === "file") {
                    var file = item.getAsFile();
                    switch (item.type) {
                    case "image/png":
                        var ext = ".png";
                        break;
                    case "image/jpeg":
                        var ext = ".jpeg";
                        break;
                    case "image/gif":
                        var ext = ".gif";
                        break;
                    default:
                        var ext = '';
                    }
                    file.name = guidGenerate() + ext;
                    handleFiles([file], $textarea, options);
                }
            };
        });
    });
    return this;

    function handleFiles(fileList, $textarea, options) {
        $.each(fileList, function (i, file) {
            var index = $textarea.textrange('get').selectionStart;
            var head = $textarea.val().slice(0, index);
            var tail = $textarea.val().slice(index);

            var tag = "![Uploading " + file.name + " 0%]()";
            var tagPattern = new RegExp('!\\[Uploading ' + file.name + ' [0-9]+%\\]\\(\\)');
            $textarea.val(head + tag + tail);

            var uploader = new qcode.Uploader({
                file: file,
                chunkSize: options.chunkSize,
                url: options.uploadURL,
                postData: options.postData
            });

            $(uploader)
                    .on('progress', function(event) {
                        var perct = parseInt((event.loaded / event.total) * 100);
                        $textarea.val(
                            $textarea.val().replace(tagPattern, "![Uploading " + file.name + " " + perct + "%]()")
                        );
                    })
                    .on('complete', function(event, xhr) {
                        var url = options.getImageURL(xhr, file);
                        $textarea.val(
                            $textarea.val().replace(tagPattern, '![image](' + url + ')')
                        );
                    })
                    .on('error', function(event, xhr) {
                        $textarea.val(
                            $textarea.val().replace(tagPattern, '![Error uploading ' + file.name + ']()')
                        );
                        $textarea.trigger('error', [xhr]);
                    });
            uploader.start();
        });
    };
};<commit_msg>bug fix<commit_after>/*
  options = {
    uploadURL: string,
    getImageURL: function(xhr, file) {},
    postData: object (optional),
    chunkSize: string (optional, default "1MiB")
  }
*/
$.fn.markDownImageHandler = function(options) {
    $(this).each(function(t, target) {
        var $textarea = $(target);

        $textarea.imageDropZone(handleFiles);

        $textarea.on('paste', function (event) {
            for (var i = event.originalEvent.clipboardData.items.length - 1; i >= 0; i--) {
                var item = event.originalEvent.clipboardData.items[i];
                if (item.kind === "file") {
                    var file = item.getAsFile();
                    switch (item.type) {
                    case "image/png":
                        var ext = ".png";
                        break;
                    case "image/jpeg":
                        var ext = ".jpeg";
                        break;
                    case "image/gif":
                        var ext = ".gif";
                        break;
                    default:
                        var ext = '';
                    }
                    file.name = guidGenerate() + ext;
                    handleFiles([file]);
                }
            };
        });

        function handleFiles(fileList) {
            var index = $textarea.textrange('get').selectionStart;
            $.each(fileList, function (i, file) {
                var head = $textarea.val().slice(0, index);
                var tail = $textarea.val().slice(index);

                var tag = "![Uploading " + file.name + " 0%]()";
                var tagPattern = new RegExp('!\\[Uploading ' + file.name + ' [0-9]+%\\]\\(\\)');
                $textarea.val(head + tag + tail);

                var uploader = new qcode.Uploader({
                    file: file,
                    chunkSize: options.chunkSize,
                    url: options.uploadURL,
                    postData: options.postData
                });

                $(uploader)
                        .on('progress', function(event) {
                            var perct = parseInt((event.loaded / event.total) * 100);
                            $textarea.val(
                                $textarea.val().replace(tagPattern, "![Uploading " + file.name + " " + perct + "%]()")
                            );
                        })
                        .on('complete', function(event, xhr) {
                            var url = options.getImageURL(xhr, file);
                            $textarea.val(
                                $textarea.val().replace(tagPattern, '![image](' + url + ')')
                            );
                        })
                        .on('error', function(event, xhr) {
                            $textarea.val(
                                $textarea.val().replace(tagPattern, '![Error uploading ' + file.name + ']()')
                            );
                            $textarea.trigger('error', [xhr]);
                        });
                uploader.start();
            });
        };
    });
    return this;
};<|endoftext|>


<commit_before>import Joi from 'joi';
import union from 'lodash.union';

export default joiOptions => {
  return {
    validate: function(data = {}, joiSchema = {}, key, callback = () => {}) {
      const options = {
        abortEarly: false,
        allowUnknown: true,
        ...joiOptions,
      };
      const errors = this._format(Joi.validate(data, joiSchema, options));
      if (key === undefined) {
        union(Object.keys(joiSchema), Object.keys(data)).forEach(function(error) {
          errors[error] = errors[error] || [];
        });
        callback(errors);
      }
      const result = {};
      result[key] = errors[key];
      callback(result);
    },
    _format: function(joiResult) {
      if (joiResult.error !== null) {
        return joiResult.error.details.reduce(function(memo, detail) {
          if (!Array.isArray(memo[detail.path])) {
            memo[detail.path] = [];
          }
          memo[detail.path].push(detail.message);
          return memo;
        }, {});
      }
      return {};
    },
  };
};
<commit_msg>fixed issue react-validation-mixin#40<commit_after>import Joi from 'joi';
import union from 'lodash.union';

export default joiOptions => {
  return {
    validate: function(data = {}, joiSchema = {}, key, callback = () => {}) {
      const options = {
        abortEarly: false,
        allowUnknown: true,
        ...joiOptions,
      };
      const errors = this._format(Joi.validate(data, joiSchema, options));
      if (key === undefined) {
        union(Object.keys(joiSchema), Object.keys(data)).forEach(function(error) {
          errors[error] = errors[error] || [];
        });
        return callback(errors);
      }
      const result = {};
      result[key] = errors[key];
      return callback(result);
    },
    _format: function(joiResult) {
      if (joiResult.error !== null) {
        return joiResult.error.details.reduce(function(memo, detail) {
          if (!Array.isArray(memo[detail.path])) {
            memo[detail.path] = [];
          }
          memo[detail.path].push(detail.message);
          return memo;
        }, {});
      }
      return {};
    },
  };
};
<|endoftext|>


<commit_before>(function (exports) {

	exports.Wall = Wall;

	var JSUS = node.JSUS;

	Wall.id = 'wall';
	Wall.name = 'Wall';
	Wall.version = '0.3';
	Wall.description = 'Intercepts all LOG events and prints them ';
	Wall.description += 'into a DIV element with an ordinal number and a timestamp.';

	Wall.dependencies = {
		JSUS: {}
	};

	function Wall (options) {
		this.id = options.id || Wall.id;
		this.name = options.name || this.name;
		this.buffer = [];
		this.counter = 0;

		this.wall = node.window.getElement('pre', this.id);

		this.fieldset = {
			legend: 'Game Log',
			id: this.id
		};
	}

	Wall.prototype.init = function (options) {
		options = options || {};
		this.counter = options.counter || this.counter;
	};

	Wall.prototype.append = function (root) {
		return root.appendChild(this.wall);
	};

	Wall.prototype.getRoot = function () {
		return this.wall;
	};

	Wall.prototype.listeners = function() {
		var that = this;
		node.on('LOG', function (msg) {
			that.debuffer();
			that.write(msg);
		});
	};

	Wall.prototype.write = function (text) {
		if (document.readyState !== 'complete') {
			this.buffer.push(s);
		} else {
	    	var mark = this.counter++ + ') ' + JSUS.getTime() + ' ';
	    	this.wall.innerHTML = mark + text + "\n" + this.wall.innerHTML;
	    }
	};

	Wall.prototype.debuffer = function () {
		if (document.readyState === 'complete' && this.buffer.length > 0) {
			for (var i=0; i < this.buffer.length; i++) {
				this.write(this.buffer[i]);
			}
			this.buffer = [];
		}
	};

})(node.window.widgets);<commit_msg>Beutified code<commit_after>(function (exports) {

	exports.Wall = Wall;

	var JSUS = node.JSUS;

	Wall.id = 'wall';
	Wall.name = 'Wall';
	Wall.version = '0.3';
	Wall.description = 'Intercepts all LOG events and prints them ';
	Wall.description += 'into a DIV element with an ordinal number and a timestamp.';

	Wall.dependencies = {
		JSUS: {}
	};

	function Wall (options) {
		this.id = options.id || Wall.id;
		this.name = options.name || this.name;
		this.buffer = [];
		this.counter = 0;

		this.wall = node.window.getElement('pre', this.id);

		this.fieldset = {
			legend: 'Game Log',
			id: this.id
		};
	}

	Wall.prototype.init = function (options) {
		options = options || {};
		this.counter = options.counter || this.counter;
	};

	Wall.prototype.append = function (root) {
		return root.appendChild(this.wall);
	};

	Wall.prototype.getRoot = function () {
		return this.wall;
	};

	Wall.prototype.listeners = function() {
		var that = this;
		node.on('LOG', function (msg) {
			that.debuffer();
			that.write(msg);
		});
	};

	Wall.prototype.write = function (text) {
		if (document.readyState !== 'complete') {
			this.buffer.push(s);
		} else {
			var mark = this.counter++ + ') ' + JSUS.getTime() + ' ';
			this.wall.innerHTML = mark + text + "\n" + this.wall.innerHTML;
		}
	};

	Wall.prototype.debuffer = function () {
		if (document.readyState === 'complete' && this.buffer.length > 0) {
			for (var i=0; i < this.buffer.length; i++) {
				this.write(this.buffer[i]);
			}
			this.buffer = [];
		}
	};

})(node.window.widgets);<|endoftext|>


<commit_before>/**
 * Copyright (C) 2015 Wasabeef
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 "use strict";

var RE = {};

window.onload = function() {
    RE.callback("ready");
};

RE.editor = document.getElementById('editor');

// Not universally supported, but seems to work in iOS 7 and 8
document.addEventListener("selectionchange", function() {
    RE.backuprange();
});

//looks specifically for a Range selection and not a Caret selection
RE.rangeSelectionExists = function() {
    //!! coerces a null to bool
    var sel = document.getSelection();
    if (sel && sel.type == "Range") {
        return true;
    }
    return false;
};

RE.rangeOrCaretSelectionExists = function() {
    //!! coerces a null to bool
    var sel = document.getSelection();
    if (sel && (sel.type == "Range" || sel.type == "Caret")) {
        return true;
    }
    return false;
};

RE.editor.addEventListener("input", function() {
    RE.updatePlaceholder();
    RE.backuprange();
    RE.callback("input");
});

RE.editor.addEventListener("focus", function() {
    RE.backuprange();
    RE.callback("focus");
});

RE.editor.addEventListener("blur", function() {
    RE.callback("blur");
});

RE.customAction = function(action) {
    RE.callback("action/" + action);
};

RE.updateHeight = function() {
    RE.callback("updateHeight");
}

RE.callbackQueue = [];
RE.runCallbackQueue = function() {
    if (RE.callbackQueue.length === 0) {
        return;
    }

    setTimeout(function() {
        window.location.href = "re-callback://";
    }, 0);
};

RE.getCommandQueue = function() {
    var commands = JSON.stringify(RE.callbackQueue);
    RE.callbackQueue = [];
    return commands;
};

RE.callback = function(method) {
    RE.callbackQueue.push(method);
    RE.runCallbackQueue();
};

RE.setHtml = function(contents) {
    var tempWrapper = document.createElement('div');
    tempWrapper.innerHTML = contents;
    var images = tempWrapper.querySelectorAll("img");

    for (var i = 0; i < images.length; i++) {
        images[i].onload = RE.updateHeight;
    }

    RE.editor.innerHTML = tempWrapper.innerHTML;
    RE.updatePlaceholder();
};

RE.getHtml = function() {
    return RE.editor.innerHTML;
};

RE.getText = function() {
    return RE.editor.innerText;
};

RE.setPlaceholderText = function(text) {
    RE.editor.setAttribute("placeholder", text);
};

RE.updatePlaceholder = function() {
    if (RE.editor.textContent.length > 0) {
        RE.editor.classList.remove("placeholder");
    } else {
        RE.editor.classList.add("placeholder");
    }
};

RE.removeFormat = function() {
    document.execCommand('removeFormat', false, null);
};

RE.setFontSize = function(size) {
    RE.editor.style.fontSize = size;
};

RE.setBackgroundColor = function(color) {
    RE.editor.style.backgroundColor = color;
};

RE.setHeight = function(size) {
    RE.editor.style.height = size;
};

RE.undo = function() {
    document.execCommand('undo', false, null);
};

RE.redo = function() {
    document.execCommand('redo', false, null);
};

RE.setBold = function() {
    document.execCommand('bold', false, null);
};

RE.setItalic = function() {
    document.execCommand('italic', false, null);
};

RE.setSubscript = function() {
    document.execCommand('subscript', false, null);
};

RE.setSuperscript = function() {
    document.execCommand('superscript', false, null);
};

RE.setStrikeThrough = function() {
    document.execCommand('strikeThrough', false, null);
};

RE.setUnderline = function() {
    document.execCommand('underline', false, null);
};

RE.setTextColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('foreColor', false, color);
    document.execCommand("styleWithCSS", null, false);
};

RE.setTextBackgroundColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('hiliteColor', false, color);
    document.execCommand("styleWithCSS", null, false);
};

RE.setHeading = function(heading) {
    document.execCommand('formatBlock', false, '<h' + heading + '>');
};

RE.setIndent = function() {
    document.execCommand('indent', false, null);
};

RE.setOutdent = function() {
    document.execCommand('outdent', false, null);
};

RE.setOrderedList = function() {
    document.execCommand('insertOrderedList', false, null);
};

RE.setUnorderedList = function() {
    document.execCommand('insertUnorderedList', false, null);
};

RE.setJustifyLeft = function() {
    document.execCommand('justifyLeft', false, null);
};

RE.setJustifyCenter = function() {
    document.execCommand('justifyCenter', false, null);
};

RE.setJustifyRight = function() {
    document.execCommand('justifyRight', false, null);
};

RE.insertImage = function(url, alt) {
    var img = document.createElement('img');
    img.setAttribute("src", url);
    img.setAttribute("alt", alt);
    img.onload = RE.updateHeight;

    RE.insertHTML(img.outerHTML);
    RE.callback("input");
};

RE.setBlockquote = function() {
    document.execCommand('formatBlock', false, '<blockquote>');
};

RE.insertHTML = function(html) {
    RE.restorerange();
    document.execCommand('insertHTML', false, html);
};

RE.insertLink = function(url, title) {
    RE.restorerange();
    var sel = document.getSelection();
    if (sel.toString().length !== 0) {
        if (sel.rangeCount) {

            var el = document.createElement("a");
            el.setAttribute("href", url);
            el.setAttribute("title", title);

            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    RE.callback("input");
};

RE.prepareInsert = function() {
    RE.backuprange();
};

RE.backuprange = function() {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        RE.currentSelection = {
            "startContainer": range.startContainer,
            "startOffset": range.startOffset,
            "endContainer": range.endContainer,
            "endOffset": range.endOffset
        };
    }
};

RE.addRangeToSelection = function(selection, range) {
    if (selection) {
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

// Programatically select a DOM element
RE.selectElementContents = function(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    // this.createSelectionFromRange sel, range
    RE.addRangeToSelection(sel, range);
};

RE.restorerange = function() {
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
    range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
    selection.addRange(range);
};

RE.focus = function() {
    var range = document.createRange();
    range.selectNodeContents(RE.editor);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.editor.focus();
};

RE.blurFocus = function() {
    RE.editor.blur();
};

/**
Recursively search element ancestors to find a element nodeName e.g. A
**/
var _findNodeByNameInContainer = function(element, nodeName, rootElementId) {
    if (element.nodeName == nodeName) {
        return element;
    } else {
        if (element.id === rootElementId) {
            return null;
        }
        _findNodeByNameInContainer(element.parentElement, nodeName, rootElementId);
    }
};

var isAnchorNode = function(node) {
    return ("A" == node.nodeName);
};

RE.getAnchorTagsInNode = function(node) {
    var links = [];

    while (node.nextSibling !== null && node.nextSibling !== undefined) {
        node = node.nextSibling;
        if (isAnchorNode(node)) {
            links.push(node.getAttribute('href'));
        }
    }
    return links;
};

RE.countAnchorTagsInNode = function(node) {
    return RE.getAnchorTagsInNode(node).length;
};

/**
 * If the current selection's parent is an anchor tag, get the href.
 * @returns {string}
 */
RE.getSelectedHref = function() {
    var href, sel;
    href = '';
    sel = window.getSelection();
    if (!RE.rangeOrCaretSelectionExists()) {
        return null;
    }

    var tags = RE.getAnchorTagsInNode(sel.anchorNode);
    //if more than one link is there, return null
    if (tags.length > 1) {
        return null;
    } else if (tags.length == 1) {
        href = tags[0];
    } else {
        var node = _findNodeByNameInContainer(sel.anchorNode.parentElement, 'A', 'editor');
        href = node.href;
    }

    return href ? href : null;
};

/* retrieve caret vertical position */

RE.getCaretPosition = function() {
    var x=0, y=0;
    var sel=window.getSelection();
    if (sel.rangeCount) {
        var range = sel.getRangeAt(0);
        var needsWorkAround = (range.startContainer.nodeName.toLowerCase() == 'div' && range.startOffset == 0);
        if (needsWorkAround) {
            x=range.startContainer.offsetLeft;
            y=range.startContainer.offsetTop + range.startContainer.clientHeight;
        } else {
            if (range.getClientRects) {
                var rects=range.getClientRects();
                if (rects.length > 0) {
                    x = rects[0].left;
                    y = rects[0].bottom;
                }
            }
        }
    }
    return y;
};
<commit_msg>add method to wrap all text nodes in divs, add new-line boolean<commit_after>/**
 * Copyright (C) 2015 Wasabeef
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 "use strict";

var RE = {};

window.onload = function() {
    RE.callback("ready");
};

RE.editor = document.getElementById('editor');

// Not universally supported, but seems to work in iOS 7 and 8
document.addEventListener("selectionchange", function() {
    RE.backuprange();
});

//looks specifically for a Range selection and not a Caret selection
RE.rangeSelectionExists = function() {
    //!! coerces a null to bool
    var sel = document.getSelection();
    if (sel && sel.type == "Range") {
        return true;
    }
    return false;
};

RE.rangeOrCaretSelectionExists = function() {
    //!! coerces a null to bool
    var sel = document.getSelection();
    if (sel && (sel.type == "Range" || sel.type == "Caret")) {
        return true;
    }
    return false;
};

RE.editor.addEventListener("input", function() {
    RE.updatePlaceholder();
    RE.backuprange();
    RE.wrapTextNodes();
    RE.callback("input");
});

RE.editor.addEventListener("focus", function() {
    RE.backuprange();
    RE.callback("focus");
});

RE.editor.addEventListener("blur", function() {
    RE.callback("blur");
});

RE.customAction = function(action) {
    RE.callback("action/" + action);
};

RE.updateHeight = function() {
    RE.callback("updateHeight");
}

RE.callbackQueue = [];
RE.runCallbackQueue = function() {
    if (RE.callbackQueue.length === 0) {
        return;
    }

    setTimeout(function() {
        window.location.href = "re-callback://";
    }, 0);
};

RE.getCommandQueue = function() {
    var commands = JSON.stringify(RE.callbackQueue);
    RE.callbackQueue = [];
    return commands;
};

RE.callback = function(method) {
    RE.callbackQueue.push(method);
    RE.runCallbackQueue();
};

RE.setHtml = function(contents) {
    var tempWrapper = document.createElement('div');
    tempWrapper.innerHTML = contents;
    var images = tempWrapper.querySelectorAll("img");

    for (var i = 0; i < images.length; i++) {
        images[i].onload = RE.updateHeight;
    }

    RE.editor.innerHTML = tempWrapper.innerHTML;
    RE.updatePlaceholder();
};

RE.getHtml = function() {
    return RE.editor.innerHTML;
};

RE.getText = function() {
    return RE.editor.innerText;
};

RE.setPlaceholderText = function(text) {
    RE.editor.setAttribute("placeholder", text);
};

RE.updatePlaceholder = function() {
    if (RE.editor.textContent.length > 0) {
        RE.editor.classList.remove("placeholder");
    } else {
        RE.editor.classList.add("placeholder");
    }
};

RE.removeFormat = function() {
    document.execCommand('removeFormat', false, null);
};

RE.setFontSize = function(size) {
    RE.editor.style.fontSize = size;
};

RE.setBackgroundColor = function(color) {
    RE.editor.style.backgroundColor = color;
};

RE.setHeight = function(size) {
    RE.editor.style.height = size;
};

RE.undo = function() {
    document.execCommand('undo', false, null);
};

RE.redo = function() {
    document.execCommand('redo', false, null);
};

RE.setBold = function() {
    document.execCommand('bold', false, null);
};

RE.setItalic = function() {
    document.execCommand('italic', false, null);
};

RE.setSubscript = function() {
    document.execCommand('subscript', false, null);
};

RE.setSuperscript = function() {
    document.execCommand('superscript', false, null);
};

RE.setStrikeThrough = function() {
    document.execCommand('strikeThrough', false, null);
};

RE.setUnderline = function() {
    document.execCommand('underline', false, null);
};

RE.setTextColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('foreColor', false, color);
    document.execCommand("styleWithCSS", null, false);
};

RE.setTextBackgroundColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('hiliteColor', false, color);
    document.execCommand("styleWithCSS", null, false);
};

RE.setHeading = function(heading) {
    document.execCommand('formatBlock', false, '<h' + heading + '>');
};

RE.setIndent = function() {
    document.execCommand('indent', false, null);
};

RE.setOutdent = function() {
    document.execCommand('outdent', false, null);
};

RE.setOrderedList = function() {
    document.execCommand('insertOrderedList', false, null);
};

RE.setUnorderedList = function() {
    document.execCommand('insertUnorderedList', false, null);
};

RE.setJustifyLeft = function() {
    document.execCommand('justifyLeft', false, null);
};

RE.setJustifyCenter = function() {
    document.execCommand('justifyCenter', false, null);
};

RE.setJustifyRight = function() {
    document.execCommand('justifyRight', false, null);
};

RE.insertImage = function(url, alt) {
    var img = document.createElement('img');
    img.setAttribute("src", url);
    img.setAttribute("alt", alt);
    img.onload = RE.updateHeight;

    RE.insertHTML(img.outerHTML);
    RE.callback("input");
};

RE.setBlockquote = function() {
    document.execCommand('formatBlock', false, '<blockquote>');
};

RE.insertHTML = function(html) {
    RE.restorerange();
    document.execCommand('insertHTML', false, html);
};

RE.insertLink = function(url, title) {
    RE.restorerange();
    var sel = document.getSelection();
    if (sel.toString().length !== 0) {
        if (sel.rangeCount) {

            var el = document.createElement("a");
            el.setAttribute("href", url);
            el.setAttribute("title", title);

            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    RE.callback("input");
};

RE.prepareInsert = function() {
    RE.backuprange();
};

RE.backuprange = function() {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        RE.currentSelection = {
            "startContainer": range.startContainer,
            "startOffset": range.startOffset,
            "endContainer": range.endContainer,
            "endOffset": range.endOffset
        };
    }
};

RE.addRangeToSelection = function(selection, range) {
    if (selection) {
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

// Programatically select a DOM element
RE.selectElementContents = function(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    // this.createSelectionFromRange sel, range
    RE.addRangeToSelection(sel, range);
};

RE.restorerange = function() {
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
    range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
    selection.addRange(range);
};

RE.focus = function() {
    var range = document.createRange();
    range.selectNodeContents(RE.editor);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.editor.focus();
};

RE.blurFocus = function() {
    RE.editor.blur();
};

/**
Recursively search element ancestors to find a element nodeName e.g. A
**/
var _findNodeByNameInContainer = function(element, nodeName, rootElementId) {
    if (element.nodeName == nodeName) {
        return element;
    } else {
        if (element.id === rootElementId) {
            return null;
        }
        _findNodeByNameInContainer(element.parentElement, nodeName, rootElementId);
    }
};

var isAnchorNode = function(node) {
    return ("A" == node.nodeName);
};

RE.getAnchorTagsInNode = function(node) {
    var links = [];

    while (node.nextSibling !== null && node.nextSibling !== undefined) {
        node = node.nextSibling;
        if (isAnchorNode(node)) {
            links.push(node.getAttribute('href'));
        }
    }
    return links;
};

RE.countAnchorTagsInNode = function(node) {
    return RE.getAnchorTagsInNode(node).length;
};

/**
 * If the current selection's parent is an anchor tag, get the href.
 * @returns {string}
 */
RE.getSelectedHref = function() {
    var href, sel;
    href = '';
    sel = window.getSelection();
    if (!RE.rangeOrCaretSelectionExists()) {
        return null;
    }

    var tags = RE.getAnchorTagsInNode(sel.anchorNode);
    //if more than one link is there, return null
    if (tags.length > 1) {
        return null;
    } else if (tags.length == 1) {
        href = tags[0];
    } else {
        var node = _findNodeByNameInContainer(sel.anchorNode.parentElement, 'A', 'editor');
        href = node.href;
    }

    return href ? href : null;
};

/* Make sure all text nodes are wrapped in divs! */

RE.wrapTextNodes = function() {
    var contents = RE.editor.childNodes;
    for (var i = 0; i < contents.length; i++) {
        if (contents[i].nodeType === 3) {
            var newNode = document.createElement('div');
            RE.createWrapper(contents[i], newNode);
            RE.focus();
        }
    }
}

RE.createWrapper = function(elms, node) {
    var child = node.cloneNode(true);
    var el    = elms;

    var parent  = el.parentNode;
    var sibling = el.nextSibling;

    child.appendChild(el);

    if (sibling) {
        parent.insertBefore(child, sibling);
    } else {
        parent.appendChild(child);
    }

};

/* retrieve caret vertical position */

RE.getCaretPosition = function() {
    var x=0, y=0;
    var newLine = false;
    var result = [];
    var sel=window.getSelection();
    if (sel.rangeCount) {
        var range = sel.getRangeAt(0);
        var needsWorkAround = (range.startContainer.nodeName.toLowerCase() == 'div' && range.startOffset == 0);
        if (needsWorkAround) {
            console.log(range);
            x=range.startContainer.offsetLeft;
            y=range.startContainer.offsetTop; // add range.startContainer.clientHeight if want bottom of caret;
            newLine = true; // position is on new line with no content
        } else {
            if (range.getClientRects) {
                var rects=range.getClientRects();
                if (rects.length > 0) {
                    x = rects[0].left;
                    y = rects[0].top;
                    newLine = false;
                }
            }
        }
    }
    var json = JSON.stringify({height: y, newLine: newLine});
    console.log(json);
    return json;
};
<|endoftext|>


<commit_before>'use strict'
exports.TrackerGroup = require('./tracker-group.js')
exports.Tracker = require('./tracker.js')
exports.TrackerStream = require('./tracker-stream.js')
<commit_msg>Delete index.js<commit_after><|endoftext|>


<commit_before>/**
 * GeoKnow Generator
 *    Configuration management
 *
 * @author Vadim Zaslawski
 *
 * ISQL:
 *   GRANT SPARQL_UPDATE TO "SPARQL"
 *   GRANT EXECUTE ON DB.DBA.L_O_LOOK TO "SPARQL"
 *
 * usage:
 *   CONFIG.setEndpoint(url)          - set SPARQL endpoint, should be called initially
 *   CONFIG.getEndpoint()             - get SPARQL endpoint
 *   CONFIG.getNS()                   - get base namespace
 *   CONFIG.getGraph()                - get graph name
 *   CONFIG.read([success(settings)]) - load settings
 *   CONFIG.getSettings()             - get loaded settings
 *   CONFIG.write()                   - save settings after editing CONFIG.getSettings() result
 *   CONFIG.select(property, value)   - select settings, e.g.: CONFIG.select("rdf:type", "lds:StackComponent")
 *   CONFIG.createGraph(name)         - create graph
 *   CONFIG.dropGraph(name)           - delete graph
 */

"use strict";

var CONFIG = CONFIG || (function()
{
	var endpoint  = "http://http://144.76.166.111:8890/sparql"
	,	NS        = "http://generator.geoknow.eu/"
	,	GRAPH_URI = NS + "settingsGraph";

	var namespaces =
	{
		"http://dbpedia.org/resource/"                     : "dbpedia:"
	,	"http://purl.org/dc/elements/1.1/"                 : "dc:"
	,	"http://xmlns.com/foaf/0.1/"                       : "foaf:"
	,	"http://linkeddata.org/integrated-stack-schema/"   : "lds:"
	,	"http://www.w3.org/1999/02/22-rdf-syntax-ns#"      : "rdf:"
	,	"http://www.w3.org/2000/01/rdf-schema#"            : "rdfs:"
	,	"http://www.w3.org/ns/sparql-service-description#" : "sd:"
	};
	namespaces[NS] = ":";

	var NAMESPACES = "PREFIX : <" + NS + ">"
	,	GRAPH      = "<" + GRAPH_URI + ">"
	,	FORMAT     = "application/sparql-results+json"
	,	EOL        = "\r\n";

	var settings = {};

	var isLoaded = false;

	var ns = function(v)
	{
		var value = v.value || v;

		if (!v.type || v.type == "uri")
		{
			var namespace = /.*[#\/]/.exec(value);
			if (namespace)
			{
				var prefix = namespaces[namespace = namespace[0]];
				if (prefix)
					return prefix + value.slice(namespace.length);
			}
		}

		return value;
	}

	return {
		setEndpoint: function(url)
		{
			endpoint = url;
		}
	,
		getEndpoint: function()
		{
			return endpoint;
		}

	,	getNS: function()
		{
			return NS;
		}

	,	getGraph: function()
		{
			return GRAPH;
		}

	,	getSettings: function()
		{
			return settings;
		}

	,	select: function(property, value)
		{
			property = ns(property);
			value    = ns(value);

			var elements = {};

			for (var resource in settings)
			{
				var element = settings[resource];
				var prop = element[property];
				if (prop)
					for (var i in prop)
						if (prop[i] == value)
						{
							elements[resource] = element;
							break;
						}
			}

			return elements;
		}

	,	read: function(success)
		{
			if (isLoaded)
			{
				if (success)
					try
					{
						success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				return;
			}

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "SELECT * FROM " + GRAPH + EOL
				+	"WHERE { ?s ?p ?o }" + EOL
				+	"ORDER BY ?s ?p ?o"
				}
			,	function(data)
				{
					try
					{
						var bindings = data.results.bindings
						,	triples  = [];

						for (var i in bindings)
						{
							var binding = bindings[i];
							triples.push([ ns(binding.s), ns(binding.p), ns(binding.o) ]);
						}

						settings = {};

						var bnodes = {};

						for (var i in triples)
						{
							var triple = triples[i]
							,	s = triple[0]
							,	p = triple[1]
							,	o = triple[2];

							if (/^nodeID:\/\//.test(s))
							{
								var id = s.slice(9);
								var map = bnodes[id] = bnodes[id] || {};
							}
							else
							{
								var map = settings[s] || (settings[s] = {});

								if (/^nodeID:\/\//.test(o))
								{
									var id = o.slice(9);
									o = bnodes[id] = bnodes[id] || {};
								}
							}

							(map[p] || (map[p] = [])).push(o);
						}

						isLoaded = true;

						if (success)
							success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	write: function()
		{
			var wrap = function(s)
			{
				return /^http:\/\//.test(s) ? "<" + s + ">" : !/^\w*:/.test(s) ? '"' + s + '"' : s;
			}

			var data = "",
				bnodeIndex = 0;

			var walk = function(s, map)
			{
				for (var p in map)
				{
					var arr = map[p];
					for (var i in arr)
					{
						var o = arr[i];
						if (typeof o === "string")
							data += wrap(s) + " " + wrap(p) + " " + wrap(o) + " ." + EOL;
						else
						{
							var bnode = "_:b" + ++bnodeIndex;
							data += wrap(s) + " " + wrap(p) + " " + bnode + " ." + EOL;
							walk(bnode, o);
						}
					}
				}
			}

			for (var s in settings)
				walk(s, settings[s]);

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: NAMESPACES + EOL
					+	"DROP SILENT GRAPH "   + GRAPH + EOL
					+	"CREATE SILENT GRAPH " + GRAPH + EOL
					+	"INSERT INTO "         + GRAPH + EOL
					+	"{" + EOL
					+	data
					+	"}"
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	createGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "CREATE SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	dropGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "DROP SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}
	};
})();
<commit_msg>lds namespace added.<commit_after>/**
 * GeoKnow Generator
 *    Configuration management
 *
 * @author Vadim Zaslawski
 *
 * ISQL:
 *   GRANT SPARQL_UPDATE TO "SPARQL"
 *   GRANT EXECUTE ON DB.DBA.L_O_LOOK TO "SPARQL"
 *
 * usage:
 *   CONFIG.setEndpoint(url)          - set SPARQL endpoint, should be called initially
 *   CONFIG.getEndpoint()             - get SPARQL endpoint
 *   CONFIG.getNS()                   - get base namespace
 *   CONFIG.getGraph()                - get graph name
 *   CONFIG.read([success(settings)]) - load settings
 *   CONFIG.getSettings()             - get loaded settings
 *   CONFIG.write()                   - save settings after editing CONFIG.getSettings() result
 *   CONFIG.select(property, value)   - select settings, e.g.: CONFIG.select("rdf:type", "lds:StackComponent")
 *   CONFIG.createGraph(name)         - create graph
 *   CONFIG.dropGraph(name)           - delete graph
 */

"use strict";

var CONFIG = CONFIG || (function()
{
	var endpoint  = "http://http://144.76.166.111:8890/sparql"
	,	NS        = "http://generator.geoknow.eu/"
	,	GRAPH_URI = NS + "settingsGraph";

	var namespaces =
	{
		"http://dbpedia.org/resource/"                     : "dbpedia:"
	,	"http://purl.org/dc/elements/1.1/"                 : "dc:"
	,	"http://xmlns.com/foaf/0.1/"                       : "foaf:"
	,	"http://linkeddata.org/integrated-stack-schema/"   : "lds:"
	,	"http://www.w3.org/1999/02/22-rdf-syntax-ns#"      : "rdf:"
	,	"http://www.w3.org/2000/01/rdf-schema#"            : "rdfs:"
	,	"http://www.w3.org/ns/sparql-service-description#" : "sd:"
	};
	namespaces[NS] = ":";

	var GRAPH      = "<" + GRAPH_URI + ">"
	,	FORMAT     = "application/sparql-results+json"
	,	EOL        = "\r\n"
	,	NAMESPACES = "PREFIX : <" + NS + ">" + EOL
				   + "PREFIX lds: <http://linkeddata.org/integrated-stack-schema/>";

	var settings = {};

	var isLoaded = false;

	var ns = function(v)
	{
		var value = v.value || v;

		if (!v.type || v.type == "uri")
		{
			var namespace = /.*[#\/]/.exec(value);
			if (namespace)
			{
				var prefix = namespaces[namespace = namespace[0]];
				if (prefix)
					return prefix + value.slice(namespace.length);
			}
		}

		return value;
	}

	return {
		setEndpoint: function(url)
		{
			endpoint = url;
		}
	,
		getEndpoint: function()
		{
			return endpoint;
		}

	,	getNS: function()
		{
			return NS;
		}

	,	getGraph: function()
		{
			return GRAPH;
		}

	,	getSettings: function()
		{
			return settings;
		}

	,	select: function(property, value)
		{
			property = ns(property);
			value    = ns(value);

			var elements = {};

			for (var resource in settings)
			{
				var element = settings[resource];
				var prop = element[property];
				if (prop)
					for (var i in prop)
						if (prop[i] == value)
						{
							elements[resource] = element;
							break;
						}
			}

			return elements;
		}

	,	read: function(success)
		{
			if (isLoaded)
			{
				if (success)
					try
					{
						success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				return;
			}

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "SELECT * FROM " + GRAPH + EOL
				+	"WHERE { ?s ?p ?o }" + EOL
				+	"ORDER BY ?s ?p ?o"
				}
			,	function(data)
				{
					try
					{
						var bindings = data.results.bindings
						,	triples  = [];

						for (var i in bindings)
						{
							var binding = bindings[i];
							triples.push([ ns(binding.s), ns(binding.p), ns(binding.o) ]);
						}

						settings = {};

						var bnodes = {};

						for (var i in triples)
						{
							var triple = triples[i]
							,	s = triple[0]
							,	p = triple[1]
							,	o = triple[2];

							if (/^nodeID:\/\//.test(s))
							{
								var id = s.slice(9);
								var map = bnodes[id] = bnodes[id] || {};
							}
							else
							{
								var map = settings[s] || (settings[s] = {});

								if (/^nodeID:\/\//.test(o))
								{
									var id = o.slice(9);
									o = bnodes[id] = bnodes[id] || {};
								}
							}

							(map[p] || (map[p] = [])).push(o);
						}

						isLoaded = true;

						if (success)
							success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	write: function()
		{
			var wrap = function(s)
			{
				return /^http:\/\//.test(s) ? "<" + s + ">" : !/^\w*:/.test(s) ? '"' + s + '"' : s;
			}

			var data = "",
				bnodeIndex = 0;

			var walk = function(s, map)
			{
				for (var p in map)
				{
					var arr = map[p];
					for (var i in arr)
					{
						var o = arr[i];
						if (typeof o === "string")
							data += wrap(s) + " " + wrap(p) + " " + wrap(o) + " ." + EOL;
						else
						{
							var bnode = "_:b" + ++bnodeIndex;
							data += wrap(s) + " " + wrap(p) + " " + bnode + " ." + EOL;
							walk(bnode, o);
						}
					}
				}
			}

			for (var s in settings)
				walk(s, settings[s]);

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: NAMESPACES + EOL
					+	"DROP SILENT GRAPH "   + GRAPH + EOL
					+	"CREATE SILENT GRAPH " + GRAPH + EOL
					+	"INSERT INTO "         + GRAPH + EOL
					+	"{" + EOL
					+	data
					+	"}"
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	createGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "CREATE SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	dropGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "DROP SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}
	};
})();
<|endoftext|>


<commit_before>/**
 * jQuery plugin for selection and replacement of text in input and textarea
 *
 * @version 0.1
 * @author Oleg Slobodskoi (jsui.de)
 */

(function($, document) {

/**
 * Extend jQuery's prototype
 * @param {string} [text]
 */
$.fn.fieldSelection = function( text ) {
    var ret;
    this.each(function(){
        this.focus();
        ret = text ? replace(this, text||'') : get(this);
    });
    return ret || this;
};

/**
 * Get selection
 * @param {Object} elem
 */
function get( elem ) {
    var data = {start: 0, end: elem.value.length, length: 0};

    // dom 3
    if ( elem.selectionStart >= 0 ) {
        data.start = elem.selectionStart;
        data.end = elem.selectionEnd;
        data.length = data.end - data.start;
        data.text = elem.value.substr(data.start, data.length);
    // IE
    } else if ( elem.ownerDocument.selection ) {
        var r = elem.ownerDocument.selection.createRange();
        if ( !r ) return data;
        var tr = elem.createTextRange(),
            ctr = tr.duplicate();

        tr.moveToBookmark(r.getBookmark());
        ctr.setEndPoint('EndToStart', tr);
        data.start = ctr.text.length;
        data.end = ctr.text.length + r.text.length;
        data.text = r.text;
        data.length = r.text.length;
    }

    return data;
}

/**
 * Replace selection
 * @param {Object} elem
 * @param {string} text
 */
function replace( elem, text ) {
    // dom 3
    if ( elem.selectionStart >= 0 ) {
        var start = elem.selectionStart,
            end = elem.selectionEnd;
        elem.value = elem.value.substr(0, start) + text + elem.value.substr(end);
        var pos = start + text.length;
        elem.selectionStart = pos;
        elem.selectionEnd = pos;
    // IE
    } else if ( elem.ownerDocument.selection ) {
        var range = elem.ownerDocument.selection.createRange();
        range.text = text;
        range.move('character', 0);
        range.select();
    } else {
        // browser not supported - set at the end
        elem.value += text;
        // scroll to the end of textarea to show inserted
        elem.scrollTop = 100000;
    }
}

})(jQuery);

<commit_msg>remove not needed var<commit_after>/**
 * jQuery plugin for selection and replacement of text in input and textarea
 *
 * @version 0.1
 * @author Oleg Slobodskoi (jsui.de)
 */

(function($) {

/**
 * Extend jQuery's prototype
 * @param {string} [text]
 */
$.fn.fieldSelection = function( text ) {
    var ret;
    this.each(function(){
        this.focus();
        ret = text ? replace(this, text||'') : get(this);
    });
    return ret || this;
};

/**
 * Get selection
 * @param {Object} elem
 */
function get( elem ) {
    var data = {start: 0, end: elem.value.length, length: 0};

    // dom 3
    if ( elem.selectionStart >= 0 ) {
        data.start = elem.selectionStart;
        data.end = elem.selectionEnd;
        data.length = data.end - data.start;
        data.text = elem.value.substr(data.start, data.length);
    // IE
    } else if ( elem.ownerDocument.selection ) {
        var r = elem.ownerDocument.selection.createRange();
        if ( !r ) return data;
        var tr = elem.createTextRange(),
            ctr = tr.duplicate();

        tr.moveToBookmark(r.getBookmark());
        ctr.setEndPoint('EndToStart', tr);
        data.start = ctr.text.length;
        data.end = ctr.text.length + r.text.length;
        data.text = r.text;
        data.length = r.text.length;
    }

    return data;
}

/**
 * Replace selection
 * @param {Object} elem
 * @param {string} text
 */
function replace( elem, text ) {
    // dom 3
    if ( elem.selectionStart >= 0 ) {
        var start = elem.selectionStart,
            end = elem.selectionEnd;
        elem.value = elem.value.substr(0, start) + text + elem.value.substr(end);
        var pos = start + text.length;
        elem.selectionStart = pos;
        elem.selectionEnd = pos;
    // IE
    } else if ( elem.ownerDocument.selection ) {
        var range = elem.ownerDocument.selection.createRange();
        range.text = text;
        range.move('character', 0);
        range.select();
    } else {
        // browser not supported - set at the end
        elem.value += text;
        // scroll to the end of textarea to show inserted
        elem.scrollTop = 100000;
    }
}

})(jQuery);

<|endoftext|>


<commit_before>;(function () {

// 1. create iframe pointing to script on jsconsole.com domain
// 2. create console object with: log, dir, etc?
// 3. console.log runs postMessage with json.stringified content
// 4. jsconsole.com/remote/?id.onMessage = send to server, and wait for response.

function sortci(a, b) {
  return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
}

// from console.js
function stringify(o, simple) {
  var json = '', i, type = ({}).toString.call(o), parts = [], names = [];

  if (type == '[object String]') {
    json = '"' + o.replace(/\n/g, '\\n').replace(/"/g, '\\"') + '"';
  } else if (type == '[object Array]') {
    json = '[';
    for (i = 0; i < o.length; i++) {
      parts.push(stringify(o[i], simple));
    }
    json += parts.join(', ') + ']';
    json;
  } else if (type == '[object Object]') {
    json = '{';
    for (i in o) {
      names.push(i);
    }
    names.sort(sortci);
    for (i = 0; i < names.length; i++) {
      parts.push(stringify(names[i]) + ': ' + stringify(o[names[i] ], simple));
    }
    json += parts.join(', ') + '}';
  } else if (type == '[object Number]') {
    json = o+'';
  } else if (type == '[object Boolean]') {
    json = o ? 'true' : 'false';
  } else if (type == '[object Function]') {
    json = o.toString();
  } else if (o === null) {
    json = 'null';
  } else if (o === undefined) {
    json = 'undefined';
  } else if (simple == undefined) {
    json = type + '{\n';
    for (i in o) {
      names.push(i);
    }
    names.sort(sortci);
    for (i = 0; i < names.length; i++) {
      parts.push(names[i] + ': ' + stringify(o[names[i]], true)); // safety from max stack
    }
    json += parts.join(',\n') + '\n}';
  } else {
    try {
      json = o+''; // should look like an object
    } catch (e) {}
  }
  return json;
}

// Plugins that inject are screwing this up :(
// function getLastChild(el) {
//   return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;
// }

function getRemoteScript() {
  var scripts = document.getElementsByTagName('script'),
      remoteScript = null;
  for (var i = 0; i < scripts.length; i++) {
    if (/jsconsole.com(:\d+)?\/remote.js/.test(scripts[i].src)) {
      remoteScript = scripts[i];
      break;
    }
  }

  return remoteScript;
}

var last = getRemoteScript();

// if (last.getAttribute('id') == '_firebugConsole') { // if Firebug is open, this all goes to crap
//   last = last.previousElementSibling;
// }

var lastSrc = last.getAttribute('src'),
    id = lastSrc.replace(/.*\?/, ''),
    origin = 'http://' + lastSrc.substr(7).replace(/\/.*$/, ''),
    remoteWindow = null,
    queue = [],
    msgType = '';

var remoteFrame = document.createElement('iframe');
remoteFrame.style.display = 'none';
remoteFrame.src = origin + '/remote.html?' + id;

// this is new - in an attempt to allow this code to be included in the head element
document.documentElement.appendChild(remoteFrame);

window.addEventListener('message', function (event) {
  if (event.origin != origin) return;

  // eval the event.data command
  try {
    if (event.data.indexOf('console.log') == 0) {
      eval('remote.echo(' + event.data.match(/console.log\((.*)\);?/)[1] + ', "' + event.data + '", true)');
    } else {
      remote.echo(eval(event.data), event.data, undefined); // must be undefined to work
    }
  } catch (e) {
    remote.error(e, event.data);
  }
}, false);

var remote = {
  log: function () {
    var argsObj = stringify(arguments.length == 1 ? arguments[0] : [].slice.call(arguments, 0));
    var response = [];
    [].forEach.call(arguments, function (args) {
      response.push(stringify(args, true));
    });

	var msg = JSON.stringify({ response: response, cmd: 'remote console.log', type: msgType });

    if (remoteWindow) {
      remoteWindow.postMessage(msg, origin);
    } else {
      queue.push(msg);
    }

    msgType = '';
  },
  info: function () {
    msgType = 'info';
    remote.log.apply(this, arguments);
  },
  echo: function () {
    var args = [].slice.call(arguments, 0),
        plain = args.pop(),
        cmd = args.pop(),
        response = args;

    var argsObj = stringify(response, plain),
        msg = JSON.stringify({ response: argsObj, cmd: cmd });
    if (remoteWindow) {
      remoteWindow.postMessage(msg, origin);
    } else {
      queue.push(msg);
    }
  },
  error: function (error, cmd) {
    var msg = JSON.stringify({ response: error.message, cmd: cmd, type: 'error' });
    if (remoteWindow) {
      remoteWindow.postMessage(msg, origin);
    } else {
      queue.push(msg);
    }
  }
};

// just for extra support
remote.debug = remote.dir = remote.log;
remote.warn = remote.info;

remoteFrame.onload = function () {
  remoteWindow = remoteFrame.contentWindow;
  remoteWindow.postMessage('__init__', origin);

  remoteWindow.postMessage(stringify({ response: 'Connection established with ' + window.location.toString() + '\n' + navigator.userAgent, type: 'info' }), origin);

  for (var i = 0; i < queue.length; i++) {
    remoteWindow.postMessage(queue[i], origin);
  }
};

window.remote = remote;

window.addEventListner('error', function (event) {
  remote.error(event.message, event.filename + ':' + event.lineno);
}, false);

try {
  window.console = remote;
} catch (e) {
  console.log('cannot overwrite existing console object');
}

})();
<commit_msg>flippin typo<commit_after>;(function () {

// 1. create iframe pointing to script on jsconsole.com domain
// 2. create console object with: log, dir, etc?
// 3. console.log runs postMessage with json.stringified content
// 4. jsconsole.com/remote/?id.onMessage = send to server, and wait for response.

function sortci(a, b) {
  return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
}

// from console.js
function stringify(o, simple) {
  var json = '', i, type = ({}).toString.call(o), parts = [], names = [];

  if (type == '[object String]') {
    json = '"' + o.replace(/\n/g, '\\n').replace(/"/g, '\\"') + '"';
  } else if (type == '[object Array]') {
    json = '[';
    for (i = 0; i < o.length; i++) {
      parts.push(stringify(o[i], simple));
    }
    json += parts.join(', ') + ']';
    json;
  } else if (type == '[object Object]') {
    json = '{';
    for (i in o) {
      names.push(i);
    }
    names.sort(sortci);
    for (i = 0; i < names.length; i++) {
      parts.push(stringify(names[i]) + ': ' + stringify(o[names[i] ], simple));
    }
    json += parts.join(', ') + '}';
  } else if (type == '[object Number]') {
    json = o+'';
  } else if (type == '[object Boolean]') {
    json = o ? 'true' : 'false';
  } else if (type == '[object Function]') {
    json = o.toString();
  } else if (o === null) {
    json = 'null';
  } else if (o === undefined) {
    json = 'undefined';
  } else if (simple == undefined) {
    json = type + '{\n';
    for (i in o) {
      names.push(i);
    }
    names.sort(sortci);
    for (i = 0; i < names.length; i++) {
      parts.push(names[i] + ': ' + stringify(o[names[i]], true)); // safety from max stack
    }
    json += parts.join(',\n') + '\n}';
  } else {
    try {
      json = o+''; // should look like an object
    } catch (e) {}
  }
  return json;
}

// Plugins that inject are screwing this up :(
// function getLastChild(el) {
//   return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;
// }

function getRemoteScript() {
  var scripts = document.getElementsByTagName('script'),
      remoteScript = null;
  for (var i = 0; i < scripts.length; i++) {
    if (/jsconsole.com(:\d+)?\/remote.js/.test(scripts[i].src)) {
      remoteScript = scripts[i];
      break;
    }
  }

  return remoteScript;
}

var last = getRemoteScript();

// if (last.getAttribute('id') == '_firebugConsole') { // if Firebug is open, this all goes to crap
//   last = last.previousElementSibling;
// }

var lastSrc = last.getAttribute('src'),
    id = lastSrc.replace(/.*\?/, ''),
    origin = 'http://' + lastSrc.substr(7).replace(/\/.*$/, ''),
    remoteWindow = null,
    queue = [],
    msgType = '';

var remoteFrame = document.createElement('iframe');
remoteFrame.style.display = 'none';
remoteFrame.src = origin + '/remote.html?' + id;

// this is new - in an attempt to allow this code to be included in the head element
document.documentElement.appendChild(remoteFrame);

window.addEventListener('message', function (event) {
  if (event.origin != origin) return;

  // eval the event.data command
  try {
    if (event.data.indexOf('console.log') == 0) {
      eval('remote.echo(' + event.data.match(/console.log\((.*)\);?/)[1] + ', "' + event.data + '", true)');
    } else {
      remote.echo(eval(event.data), event.data, undefined); // must be undefined to work
    }
  } catch (e) {
    remote.error(e, event.data);
  }
}, false);

var remote = {
  log: function () {
    var argsObj = stringify(arguments.length == 1 ? arguments[0] : [].slice.call(arguments, 0));
    var response = [];
    [].forEach.call(arguments, function (args) {
      response.push(stringify(args, true));
    });

	var msg = JSON.stringify({ response: response, cmd: 'remote console.log', type: msgType });

    if (remoteWindow) {
      remoteWindow.postMessage(msg, origin);
    } else {
      queue.push(msg);
    }

    msgType = '';
  },
  info: function () {
    msgType = 'info';
    remote.log.apply(this, arguments);
  },
  echo: function () {
    var args = [].slice.call(arguments, 0),
        plain = args.pop(),
        cmd = args.pop(),
        response = args;

    var argsObj = stringify(response, plain),
        msg = JSON.stringify({ response: argsObj, cmd: cmd });
    if (remoteWindow) {
      remoteWindow.postMessage(msg, origin);
    } else {
      queue.push(msg);
    }
  },
  error: function (error, cmd) {
    var msg = JSON.stringify({ response: error.message, cmd: cmd, type: 'error' });
    if (remoteWindow) {
      remoteWindow.postMessage(msg, origin);
    } else {
      queue.push(msg);
    }
  }
};

// just for extra support
remote.debug = remote.dir = remote.log;
remote.warn = remote.info;

remoteFrame.onload = function () {
  remoteWindow = remoteFrame.contentWindow;
  remoteWindow.postMessage('__init__', origin);

  remoteWindow.postMessage(stringify({ response: 'Connection established with ' + window.location.toString() + '\n' + navigator.userAgent, type: 'info' }), origin);

  for (var i = 0; i < queue.length; i++) {
    remoteWindow.postMessage(queue[i], origin);
  }
};

window.remote = remote;

window.addEventListener && window.addEventListener('error', function (event) {
  remote.error(event.message, event.filename + ':' + event.lineno);
}, false);

try {
  window.console = remote;
} catch (e) {
  console.log('cannot overwrite existing console object');
}

})();
<|endoftext|>


<commit_before>// Note: You must restart bin/webpack-dev-server for changes to take effect

/* eslint global-require: 0 */
/* eslint import/no-dynamic-require: 0 */

const webpack = require('webpack')
const merge = require('webpack-merge')
const { basename, dirname, join, relative, resolve } = require('path')
const { sync } = require('glob')
const ManifestPlugin = require('webpack-manifest-plugin')
const extname = require('path-complete-extname')
const { env, settings, output, engines } = require('./configuration.js')
const loaders = require('./loaders.js')

const extensionGlob = `**/*{${settings.extensions.join(',')}}*` // */
const entryPath = join(settings.source_path, settings.source_entry_path)

let packPaths = {}

Object.keys(engines).forEach(function(k) {
  let root = engines[k]
  let glob = join(root, entryPath, extensionGlob)
  packPaths[k] = sync(glob)
})

module.exports = {
  entry: Object.keys(packPaths).reduce(
    (map, pluginName) => {
      packPaths[pluginName].forEach(function(entry) {
        map[join(pluginName, basename(entry, extname(entry)))] = resolve(entry)
      })
      return map
    }, {}
  ),

  output: {
    filename: '[name].js',
    path: output.path,
    publicPath: output.publicPath
  },

  module: {
    rules: loaders,
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV || 'development'),
    }),

    // Workaround for graphql/graphql-language-service#128
    new webpack.ContextReplacementPlugin(
      /graphql-language-service-interface[\\\/]dist$/,
      /\.js$/
    ),

    new ManifestPlugin({
      publicPath: output.publicPath,
      writeToFileEmit: true,
    }),
  ],

  optimization: {
    splitChunks: {
      minChunks: 1,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /node_modules/,
          name: 'vendor',
          chunks: 'all',
        },
      },
    },
  },

  resolve: {
    extensions: settings.extensions,
    modules: [resolve(settings.source_path)].concat(
      Object.keys(engines).map(key => engines[key]).map(engine => `${engine}/node_modules`)
    ),
  },

  resolveLoader: {
    modules: ['node_modules']
  }
}
<commit_msg>webpack - resolveLoader - only load loaders from ui-classic<commit_after>// Note: You must restart bin/webpack-dev-server for changes to take effect

/* eslint global-require: 0 */
/* eslint import/no-dynamic-require: 0 */

const webpack = require('webpack')
const merge = require('webpack-merge')
const { basename, dirname, join, relative, resolve } = require('path')
const { sync } = require('glob')
const ManifestPlugin = require('webpack-manifest-plugin')
const extname = require('path-complete-extname')
const { env, settings, output, engines } = require('./configuration.js')
const loaders = require('./loaders.js')

const extensionGlob = `**/*{${settings.extensions.join(',')}}*` // */
const entryPath = join(settings.source_path, settings.source_entry_path)

let packPaths = {}

Object.keys(engines).forEach(function(k) {
  let root = engines[k]
  let glob = join(root, entryPath, extensionGlob)
  packPaths[k] = sync(glob)
})

module.exports = {
  entry: Object.keys(packPaths).reduce(
    (map, pluginName) => {
      packPaths[pluginName].forEach(function(entry) {
        map[join(pluginName, basename(entry, extname(entry)))] = resolve(entry)
      })
      return map
    }, {}
  ),

  output: {
    filename: '[name].js',
    path: output.path,
    publicPath: output.publicPath
  },

  module: {
    rules: loaders,
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV || 'development'),
    }),

    // Workaround for graphql/graphql-language-service#128
    new webpack.ContextReplacementPlugin(
      /graphql-language-service-interface[\\\/]dist$/,
      /\.js$/
    ),

    new ManifestPlugin({
      publicPath: output.publicPath,
      writeToFileEmit: true,
    }),
  ],

  optimization: {
    splitChunks: {
      minChunks: 1,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /node_modules/,
          name: 'vendor',
          chunks: 'all',
        },
      },
    },
  },

  resolve: {
    extensions: settings.extensions,
    modules: [resolve(settings.source_path)].concat(
      Object.keys(engines).map(key => engines[key]).map(engine => `${engine}/node_modules`)
    ),
  },

  resolveLoader: {
    // only read loaders from ui-classic
    modules: [`${engines['manageiq-ui-classic']}/node_modules`],
  },
}
<|endoftext|>