<commit_before>/*
	WebPlotDigitizer - http://arohatgi.info/WebPlotDigitizer

	Copyright 2010-2013 Ankit Rohatgi <ankitrohatgi@hotmail.com>

	This file is part of WebPlotDigitizer.

    WebPlotDigitizer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WebPlotDigitizer 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WebPlotDigitizer.  If not, see <http://www.gnu.org/licenses/>.

*/

/* Autodetection variables */
var fg_color = [0,0,0];
var bg_color = [255,255,255];
var colorPickerMode = 'fg';

var testImgCanvas;
var testImgContext;

var boxCoordinates = [0,0,1,1];
var drawingBox = false;
var drawingPen = false;
var drawingEraser = false;

var binaryData;

/**
 * Opens the color picker.
 * @params {String} cmode 'fg' or 'bg'
 */
function colorPickerWindow(cmode) {
    colorPickerMode = cmode;
    if(cmode === 'fg') {
      showPopup('colorPickerFG');
    } else if(cmode === 'bg') {
       showPopup('colorPickerBG');
    }
}

/**
 * Initiate color picking on canvas.
 */
function pickColor() {
	//colorPickerMode = cmode;
	removeAllMouseEvents();
	addMouseEvent('click',colorPicker,true);
}

/**
 * Handle clicks when picking color.
 */
function colorPicker(ev) {
	xi = ev.layerX;
	yi = ev.layerY;

	iData = ctx.getImageData(cx0,cy0,currentImageWidth,currentImageHeight);
	if ((xi < currentImageWidth+cx0) && (yi < currentImageHeight+cy0) && (xi > cx0) && (yi > cy0)) {
		ii = xi - cx0;
		jj = yi - cy0;

		var index = jj*4*currentImageWidth + ii*4;
		var PickedColor = [iData.data[index], iData.data[index+1], iData.data[index+2]];
		redEl = document.getElementById('color_red');
		greenEl = document.getElementById('color_green');
		blueEl = document.getElementById('color_blue');

		removeMouseEvent('click',colorPicker,true);

		if(colorPickerMode === 'fg') {
			assignColor('fg',PickedColor);

			redEl = document.getElementById('color_red_fg');
			greenEl = document.getElementById('color_green_fg');
			blueEl = document.getElementById('color_blue_fg');
			showPopup('colorPickerFG');

		} else if (colorPickerMode === 'bg') {

		  	assignColor('bg',PickedColor);

			redEl = document.getElementById('color_red_bg');
			greenEl = document.getElementById('color_green_bg');
			blueEl = document.getElementById('color_blue_bg');
			showPopup('colorPickerBG');
		}

		redEl.value = PickedColor[0];
		greenEl.value = PickedColor[1];
		blueEl.value = PickedColor[2];
	}
}

/**
 * This function assigns the color to the global variables.
 */
function assignColor(color_mode, color_value) {

  if(color_mode === 'fg') {
    if(!color_value) {
      redEl = document.getElementById('color_red_fg');
      greenEl = document.getElementById('color_green_fg');
      blueEl = document.getElementById('color_blue_fg');
      color_value = new Array();
      color_value[0] = redEl.value;
      color_value[1] = greenEl.value;
      color_value[2] = blueEl.value;
    }
    fg_color = color_value;
    var fgbtn = document.getElementById('autoFGBtn');
    fgbtn.style.borderColor = "rgb(" + fg_color[0] +"," + fg_color[1] +"," + fg_color[2] +")";

  } else if(color_mode === 'bg') {

    if(!color_value) {
      redEl = document.getElementById('color_red_bg');
      greenEl = document.getElementById('color_green_bg');
      blueEl = document.getElementById('color_blue_bg');
      color_value = new Array();
      color_value[0] = redEl.value;
      color_value[1] = greenEl.value;
      color_value[2] = blueEl.value;
    }
    bg_color = color_value;
    var bgbtn = document.getElementById('autoBGBtn');
    bgbtn.style.borderColor = "rgb(" + bg_color[0] +"," + bg_color[1] +"," + bg_color[2] +")";

  }
}

/**
 * Enable Box painting on canvas.
 */
function boxPaint() {

	removeAllMouseEvents();
	addMouseEvent('mousedown',boxPaintMousedown,true);
	addMouseEvent('mouseup',boxPaintMouseup,true);
	addMouseEvent('mousemove',boxPaintMousedrag,true);

}

/**
 * Handle mouse clicks when painting boxes - Mouse down
 */
function boxPaintMousedown(ev) {

	boxCoordinates[0] = parseInt(ev.layerX);
	boxCoordinates[1] = parseInt(ev.layerY);
	drawingBox = true;
}

/**
 * Handle mouse clicks when painting boxes - Mouse up
 */
function boxPaintMouseup(ev) {

	boxCoordinates[2] = parseInt(ev.layerX);
	boxCoordinates[3] = parseInt(ev.layerY);

    hoverCanvas.width = hoverCanvas.width;
	dataCtx.fillStyle = "rgba(255,255,0,1)";
	dataCtx.fillRect(boxCoordinates[0], boxCoordinates[1], boxCoordinates[2]-boxCoordinates[0], boxCoordinates[3]-boxCoordinates[1]);

	drawingBox = false;
}

/**
 * Handle mouse clicks when painting boxes - Mouse drag
 */
function boxPaintMousedrag(ev) {

	if(drawingBox === true) {
		xt = parseInt(ev.layerX);
		yt = parseInt(ev.layerY);

		//putCanvasData(markedScreen);
		hoverCanvas.width = hoverCanvas.width;
		hoverCtx.strokeStyle = "rgb(0,0,0)";
		hoverCtx.strokeRect(boxCoordinates[0], boxCoordinates[1], xt-boxCoordinates[0], yt-boxCoordinates[1]);
	}
}

/**
 * Enable pen like painting on screen.
 */
function penPaint() {

	removeAllMouseEvents();
	showToolbar('paintToolbar');
	addMouseEvent('mousedown',penPaintMousedown,true);
	addMouseEvent('mouseup',penPaintMouseup,true);
	addMouseEvent('mousemove',penPaintMousedrag,true);
}

/**
 * Manage clicks when painting with pen tool - Mouse down
 */
function penPaintMousedown(ev) {

	if (drawingPen === false) {
	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    drawingPen = true;
	    ctx.strokeStyle = "rgba(255,255,0,1)";

	    thkRange = document.getElementById('paintThickness');

	    dataCtx.lineWidth = parseInt(thkRange.value);
	    dataCtx.beginPath();
	    dataCtx.moveTo(xt,yt);
	}
}

/**
 * Manage clicks when painting with pen tool - Mouse up
 */
function penPaintMouseup(ev) {

    dataCtx.closePath();
    dataCtx.lineWidth = 1;
    drawingPen = false;
}

/**
 * Manage clicks when painting with pen tool - Mouse drag
 */
function penPaintMousedrag(ev) {

    if(drawingPen === true) {
	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    dataCtx.strokeStyle = "rgba(255,255,0,1)";
	    dataCtx.lineTo(xt,yt);
	    dataCtx.stroke();
    }
}

/**
 * Initiate the eraser.
 */
function eraser() {

	removeAllMouseEvents();
	showToolbar('paintToolbar');
	addMouseEvent('mousedown',eraserMousedown,true);
	addMouseEvent('mouseup',eraserMouseup,true);
	addMouseEvent('mousemove',eraserMousedrag,true);
	dataCtx.globalCompositeOperation = "destination-out";
}

/**
 * Manage mouse events when erasing - Mouse down
 */
function eraserMousedown(ev) {

    if(drawingEraser === false) {

	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    drawingEraser = true;
	    dataCtx.globalCompositeOperation = "destination-out";
	    dataCtx.strokeStyle = "rgba(0,0,0,1)";

	    thkRange = document.getElementById('paintThickness');

	    dataCtx.lineWidth = parseInt(thkRange.value);
	    dataCtx.beginPath();
	    dataCtx.moveTo(xt,yt);
    }
}

/**
 * Manage mouse events when erasing - Mouse up - this is slow!
 */
function eraserMouseup(ev) {

    dataCtx.closePath();
    dataCtx.lineWidth = 1;
    dataCtx.globalCompositeOperation = "source-over";
    drawingEraser = false;
}

/**
 * Manage mouse events when erasing - Mouse drag
 */
function eraserMousedrag(ev) {

    if(drawingEraser === true) {
	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    dataCtx.globalCompositeOperation = "destination-out";
	    dataCtx.strokeStyle = "rgba(0,0,0,1)";
	    dataCtx.lineTo(xt,yt);
	    dataCtx.stroke();
    }
}

/**
 * Filter based on color and display a test image on the scan settings dialog.
 */
function updateTestWindow() {

  colorModeEl = document.getElementById('colorModeFG');
  colorDistanceEl = document.getElementById('colorDistance');
  if (colorModeEl.checked === true) {
    colmode = 'fg';
    chosenColor = fg_color;
  } else {
    colmode = 'bg';
    chosenColor = bg_color;
  }

  cdistance = parseInt(colorDistanceEl.value);

  //binaryData = selectFromMarkedRegion(colmode, chosenColor, cdistance);

  tempImgCanvas = document.createElement('canvas');
  tempImgCanvas.width = canvasWidth;
  tempImgCanvas.height = canvasHeight;

  tempImgContext = tempImgCanvas.getContext('2d');

  timgData = tempImgContext.getImageData(0,0,canvasWidth,canvasHeight);

  //timgData = currentScreen;

  // timgData = binaryToImageData(binaryData,timgData);

  timgData = getImageDataBasedOnSelection(timgData, colmode, chosenColor, cdistance);

  tempImgContext.putImageData(timgData,0,0);

  testImage = tempImgCanvas.toDataURL();

  var displayImage = new Image();
  displayImage.onload = function() {testImgContext.drawImage(displayImage,0,0,canvasWidth/2,canvasHeight/2); processingNote(false);};
  displayImage.src = testImage;

}

/**
 * Save the test canvas as a new image
 */
function saveTest() {
  var testImageWin = window.open();
  testImageWin.location = testImgCanvas.toDataURL();
}

/**
 * Launches the test window and initiates a color based detection.
 */
function launchTestWindow() {
  processingNote(true);
  setTimeout("updateTestWindow();showPopup('testImageWindow');",100);
}

/**
 * Select which auto extraction curve is to be triggered.
 */
function scanPlot() {

    autoStepEl = document.getElementById('autostepalgo');
    xStepEl = document.getElementById('xstepalgo');
    yStepEl = document.getElementById('ystepalgo');

	var colorModeEl = document.getElementById('colorModeFG');
	var colorDistanceEl = document.getElementById('colorDistance');
	var colmode;

	if (colorModeEl.checked === true) {
		colmode = 'fg';
		chosenColor = fg_color;
	} else {
		colmode = 'bg';
		chosenColor = bg_color;
	}

	cdistance = parseInt(colorDistanceEl.value);

    closePopup("testImageWindow");

    binaryData = selectFromMarkedRegion(colmode, chosenColor, cdistance);

    xyData = [];
    pointsPicked = 0;

    resetLayers();

    AEObject.run();

    pointsStatus(pointsPicked);

    for(var ii = 0; ii < pointsPicked; ii++) {
      dataCtx.beginPath();
      dataCtx.fillStyle = "rgb(200,0,200)";
      dataCtx.arc(xyData[ii][0],xyData[ii][1],3,0,2.0*Math.PI,true);
      dataCtx.fill();
    }

}

/**
 * Display options for the selected AE algorithm.
 */
function displayParameters() {
  // Determine the chosen algorithm
  var algoSelect = document.getElementById('curvesAlgoSelect');
  var paramZone = document.getElementById('paramZone');
  var URLinput = document.getElementById('URLinput');

  if (algoSelect.value !== 'customAlgorithm') {

    URLinput.style.display='none';
	var algo = window[algoSelect.value];
   	AEObject = algo;
    makeParameterTable();

  }

}

function makeParameterTable() {

      if (!AEObject.getParamList) { return; }
      var paramList = AEObject.getParamList();
      var paramZone = document.getElementById('paramZone');
      paramZone.innerHTML='';

      for (var ii = 0; ii < paramList.length; ii++) {// make a list of parameters.
		paramZone.innerHTML += "<p>"+paramList[ii][0]+" ("+paramList[ii][1]+") <input type='text' value='"+paramList[ii][2]+"' size=3 id='pv"+ii+"'></p>";
      }
}
<commit_msg>trying out if averaging is possible while capturing colors so that extraction is easier. Averaging in a box in the neighborhood of the point doesn't see to help much.<commit_after>/*
	WebPlotDigitizer - http://arohatgi.info/WebPlotDigitizer

	Copyright 2010-2013 Ankit Rohatgi <ankitrohatgi@hotmail.com>

	This file is part of WebPlotDigitizer.

    WebPlotDigitizer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WebPlotDigitizer 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WebPlotDigitizer.  If not, see <http://www.gnu.org/licenses/>.

*/

/* Autodetection variables */
var fg_color = [0,0,0];
var bg_color = [255,255,255];
var colorPickerMode = 'fg';

var testImgCanvas;
var testImgContext;

var boxCoordinates = [0,0,1,1];
var drawingBox = false;
var drawingPen = false;
var drawingEraser = false;

var binaryData;

/**
 * Opens the color picker.
 * @params {String} cmode 'fg' or 'bg'
 */
function colorPickerWindow(cmode) {
    colorPickerMode = cmode;
    if(cmode === 'fg') {
      showPopup('colorPickerFG');
    } else if(cmode === 'bg') {
       showPopup('colorPickerBG');
    }
}

/**
 * Initiate color picking on canvas.
 */
function pickColor() {
	//colorPickerMode = cmode;
	removeAllMouseEvents();
	addMouseEvent('click',colorPicker,true);
}

/**
 * Handle clicks when picking color.
 */
function colorPicker(ev) {
	var xi = ev.layerX;
	var yi = ev.layerY;

	var iData = ctx.getImageData(cx0,cy0,currentImageWidth,currentImageHeight);
	if ((xi < currentImageWidth+cx0) && (yi < currentImageHeight+cy0) && (xi > cx0) && (yi > cy0)) {
		var ii = xi - cx0;
		var jj = yi - cy0;

		var index = jj*4*currentImageWidth + ii*4;
		var avgColor = [iData.data[index], iData.data[index+1], iData.data[index+2]];

		// Average on a box centered at ii, jj:
		var colorBoxSize = 40,
			min_ii = (ii - colorBoxSize) > 0 ? ii - colorBoxSize : 0,
			max_ii = (ii + colorBoxSize) < currentImageWidth ? ii + colorBoxSize : currentImageWidth,
			min_jj = (jj - colorBoxSize) > 0 ? jj - colorBoxSize : 0,
			max_jj = (jj + colorBoxSize) < currentImageHeight ? jj + colorBoxSize : currentImageHeight,
			crowi, ccoli,
			colorCount = 1.0,
			pixel_r, pixel_g, pixel_b,
			colorDiff,
			PickedColor = [],
			cindex;

		/*
		for(ccoli = min_ii; ccoli < max_ii; ccoli++) {
			for(crowi = min_jj; crowi < max_jj; crowi++) {
				cindex = crowi*4*currentImageWidth + ccoli*4;

				pixel_r = iData.data[cindex]*1.0;
				pixel_g = iData.data[cindex+1]*1.0;
				pixel_b = iData.data[cindex+2]*1.0;

				colorDiff = Math.sqrt((pixel_r - avgColor[0])*(pixel_r - avgColor[0]) +
										(pixel_g - avgColor[1])*(pixel_g - avgColor[1]) +
										(pixel_b - avgColor[2])*(pixel_b - avgColor[2]));
				if(colorDiff < 40) {
					avgColor[0] = (avgColor[0]*colorCount + pixel_r)/(colorCount+1.0);
					avgColor[1] = (avgColor[1]*colorCount + pixel_g)/(colorCount+1.0);
					avgColor[2] = (avgColor[2]*colorCount + pixel_b)/(colorCount+1.0);

					colorCount = colorCount + 1.0;
				}
			}
		}
		*/

		PickedColor[0] = parseInt(avgColor[0], 10);
		PickedColor[1] = parseInt(avgColor[1], 10);
		PickedColor[2] = parseInt(avgColor[2], 10);

		var redEl = document.getElementById('color_red');
		var greenEl = document.getElementById('color_green');
		var blueEl = document.getElementById('color_blue');

		removeMouseEvent('click',colorPicker,true);

		if(colorPickerMode === 'fg') {
			assignColor('fg',PickedColor);

			redEl = document.getElementById('color_red_fg');
			greenEl = document.getElementById('color_green_fg');
			blueEl = document.getElementById('color_blue_fg');
			showPopup('colorPickerFG');

		} else if (colorPickerMode === 'bg') {

		  	assignColor('bg',PickedColor);

			redEl = document.getElementById('color_red_bg');
			greenEl = document.getElementById('color_green_bg');
			blueEl = document.getElementById('color_blue_bg');
			showPopup('colorPickerBG');
		}

		redEl.value = PickedColor[0];
		greenEl.value = PickedColor[1];
		blueEl.value = PickedColor[2];
	}
}

/**
 * This function assigns the color to the global variables.
 */
function assignColor(color_mode, color_value) {

  if(color_mode === 'fg') {
    if(!color_value) {
      redEl = document.getElementById('color_red_fg');
      greenEl = document.getElementById('color_green_fg');
      blueEl = document.getElementById('color_blue_fg');
      color_value = new Array();
      color_value[0] = redEl.value;
      color_value[1] = greenEl.value;
      color_value[2] = blueEl.value;
    }
    fg_color = color_value;
    var fgbtn = document.getElementById('autoFGBtn');
    fgbtn.style.borderColor = "rgb(" + fg_color[0] +"," + fg_color[1] +"," + fg_color[2] +")";

  } else if(color_mode === 'bg') {

    if(!color_value) {
      redEl = document.getElementById('color_red_bg');
      greenEl = document.getElementById('color_green_bg');
      blueEl = document.getElementById('color_blue_bg');
      color_value = new Array();
      color_value[0] = redEl.value;
      color_value[1] = greenEl.value;
      color_value[2] = blueEl.value;
    }
    bg_color = color_value;
    var bgbtn = document.getElementById('autoBGBtn');
    bgbtn.style.borderColor = "rgb(" + bg_color[0] +"," + bg_color[1] +"," + bg_color[2] +")";

  }
}

/**
 * Enable Box painting on canvas.
 */
function boxPaint() {

	removeAllMouseEvents();
	addMouseEvent('mousedown',boxPaintMousedown,true);
	addMouseEvent('mouseup',boxPaintMouseup,true);
	addMouseEvent('mousemove',boxPaintMousedrag,true);

}

/**
 * Handle mouse clicks when painting boxes - Mouse down
 */
function boxPaintMousedown(ev) {

	boxCoordinates[0] = parseInt(ev.layerX);
	boxCoordinates[1] = parseInt(ev.layerY);
	drawingBox = true;
}

/**
 * Handle mouse clicks when painting boxes - Mouse up
 */
function boxPaintMouseup(ev) {

	boxCoordinates[2] = parseInt(ev.layerX);
	boxCoordinates[3] = parseInt(ev.layerY);

    hoverCanvas.width = hoverCanvas.width;
	dataCtx.fillStyle = "rgba(255,255,0,1)";
	dataCtx.fillRect(boxCoordinates[0], boxCoordinates[1], boxCoordinates[2]-boxCoordinates[0], boxCoordinates[3]-boxCoordinates[1]);

	drawingBox = false;
}

/**
 * Handle mouse clicks when painting boxes - Mouse drag
 */
function boxPaintMousedrag(ev) {

	if(drawingBox === true) {
		xt = parseInt(ev.layerX);
		yt = parseInt(ev.layerY);

		//putCanvasData(markedScreen);
		hoverCanvas.width = hoverCanvas.width;
		hoverCtx.strokeStyle = "rgb(0,0,0)";
		hoverCtx.strokeRect(boxCoordinates[0], boxCoordinates[1], xt-boxCoordinates[0], yt-boxCoordinates[1]);
	}
}

/**
 * Enable pen like painting on screen.
 */
function penPaint() {

	removeAllMouseEvents();
	showToolbar('paintToolbar');
	addMouseEvent('mousedown',penPaintMousedown,true);
	addMouseEvent('mouseup',penPaintMouseup,true);
	addMouseEvent('mousemove',penPaintMousedrag,true);
}

/**
 * Manage clicks when painting with pen tool - Mouse down
 */
function penPaintMousedown(ev) {

	if (drawingPen === false) {
	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    drawingPen = true;
	    ctx.strokeStyle = "rgba(255,255,0,1)";

	    thkRange = document.getElementById('paintThickness');

	    dataCtx.lineWidth = parseInt(thkRange.value);
	    dataCtx.beginPath();
	    dataCtx.moveTo(xt,yt);
	}
}

/**
 * Manage clicks when painting with pen tool - Mouse up
 */
function penPaintMouseup(ev) {

    dataCtx.closePath();
    dataCtx.lineWidth = 1;
    drawingPen = false;
}

/**
 * Manage clicks when painting with pen tool - Mouse drag
 */
function penPaintMousedrag(ev) {

    if(drawingPen === true) {
	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    dataCtx.strokeStyle = "rgba(255,255,0,1)";
	    dataCtx.lineTo(xt,yt);
	    dataCtx.stroke();
    }
}

/**
 * Initiate the eraser.
 */
function eraser() {

	removeAllMouseEvents();
	showToolbar('paintToolbar');
	addMouseEvent('mousedown',eraserMousedown,true);
	addMouseEvent('mouseup',eraserMouseup,true);
	addMouseEvent('mousemove',eraserMousedrag,true);
	dataCtx.globalCompositeOperation = "destination-out";
}

/**
 * Manage mouse events when erasing - Mouse down
 */
function eraserMousedown(ev) {

    if(drawingEraser === false) {

	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    drawingEraser = true;
	    dataCtx.globalCompositeOperation = "destination-out";
	    dataCtx.strokeStyle = "rgba(0,0,0,1)";

	    thkRange = document.getElementById('paintThickness');

	    dataCtx.lineWidth = parseInt(thkRange.value);
	    dataCtx.beginPath();
	    dataCtx.moveTo(xt,yt);
    }
}

/**
 * Manage mouse events when erasing - Mouse up - this is slow!
 */
function eraserMouseup(ev) {

    dataCtx.closePath();
    dataCtx.lineWidth = 1;
    dataCtx.globalCompositeOperation = "source-over";
    drawingEraser = false;
}

/**
 * Manage mouse events when erasing - Mouse drag
 */
function eraserMousedrag(ev) {

    if(drawingEraser === true) {
	    xt = parseInt(ev.layerX);
	    yt = parseInt(ev.layerY);
	    dataCtx.globalCompositeOperation = "destination-out";
	    dataCtx.strokeStyle = "rgba(0,0,0,1)";
	    dataCtx.lineTo(xt,yt);
	    dataCtx.stroke();
    }
}

/**
 * Filter based on color and display a test image on the scan settings dialog.
 */
function updateTestWindow() {

  colorModeEl = document.getElementById('colorModeFG');
  colorDistanceEl = document.getElementById('colorDistance');
  if (colorModeEl.checked === true) {
    colmode = 'fg';
    chosenColor = fg_color;
  } else {
    colmode = 'bg';
    chosenColor = bg_color;
  }

  cdistance = parseInt(colorDistanceEl.value);

  //binaryData = selectFromMarkedRegion(colmode, chosenColor, cdistance);

  tempImgCanvas = document.createElement('canvas');
  tempImgCanvas.width = canvasWidth;
  tempImgCanvas.height = canvasHeight;

  tempImgContext = tempImgCanvas.getContext('2d');

  timgData = tempImgContext.getImageData(0,0,canvasWidth,canvasHeight);

  //timgData = currentScreen;

  // timgData = binaryToImageData(binaryData,timgData);

  timgData = getImageDataBasedOnSelection(timgData, colmode, chosenColor, cdistance);

  tempImgContext.putImageData(timgData,0,0);

  testImage = tempImgCanvas.toDataURL();

  var displayImage = new Image();
  displayImage.onload = function() {testImgContext.drawImage(displayImage,0,0,canvasWidth/2,canvasHeight/2); processingNote(false);};
  displayImage.src = testImage;

}

/**
 * Save the test canvas as a new image
 */
function saveTest() {
  var testImageWin = window.open();
  testImageWin.location = testImgCanvas.toDataURL();
}

/**
 * Launches the test window and initiates a color based detection.
 */
function launchTestWindow() {
  processingNote(true);
  setTimeout("updateTestWindow();showPopup('testImageWindow');",100);
}

/**
 * Select which auto extraction curve is to be triggered.
 */
function scanPlot() {

    autoStepEl = document.getElementById('autostepalgo');
    xStepEl = document.getElementById('xstepalgo');
    yStepEl = document.getElementById('ystepalgo');

	var colorModeEl = document.getElementById('colorModeFG');
	var colorDistanceEl = document.getElementById('colorDistance');
	var colmode;

	if (colorModeEl.checked === true) {
		colmode = 'fg';
		chosenColor = fg_color;
	} else {
		colmode = 'bg';
		chosenColor = bg_color;
	}

	cdistance = parseInt(colorDistanceEl.value);

    closePopup("testImageWindow");

    binaryData = selectFromMarkedRegion(colmode, chosenColor, cdistance);

    xyData = [];
    pointsPicked = 0;

    resetLayers();

    AEObject.run();

    pointsStatus(pointsPicked);

    for(var ii = 0; ii < pointsPicked; ii++) {
      dataCtx.beginPath();
      dataCtx.fillStyle = "rgb(200,0,200)";
      dataCtx.arc(xyData[ii][0],xyData[ii][1],3,0,2.0*Math.PI,true);
      dataCtx.fill();
    }

}

/**
 * Display options for the selected AE algorithm.
 */
function displayParameters() {
  // Determine the chosen algorithm
  var algoSelect = document.getElementById('curvesAlgoSelect');
  var paramZone = document.getElementById('paramZone');
  var URLinput = document.getElementById('URLinput');

  if (algoSelect.value !== 'customAlgorithm') {

    URLinput.style.display='none';
	var algo = window[algoSelect.value];
   	AEObject = algo;
    makeParameterTable();

  }

}

function makeParameterTable() {

      if (!AEObject.getParamList) { return; }
      var paramList = AEObject.getParamList();
      var paramZone = document.getElementById('paramZone');
      paramZone.innerHTML='';

      for (var ii = 0; ii < paramList.length; ii++) {// make a list of parameters.
		paramZone.innerHTML += "<p>"+paramList[ii][0]+" ("+paramList[ii][1]+") <input type='text' value='"+paramList[ii][2]+"' size=3 id='pv"+ii+"'></p>";
      }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var parseArgs = require('minimist')
var argv = parseArgs(process.argv.slice(2))

if (argv.help || argv.h) {
  console.log(`usage: graphql-ruby-client sync <options>

  Read .graphql files and push the contained
  operations to a GraphQL::Pro::OperationStore

required arguments:
  --url=<endpoint-url>    URL where data should be POSTed
  --client=<client-name>  Idetifier for this client application

optional arguments:
  --path=<path>                   Path to .graphql files (default is "./**/*.graphql")
  --outfile=<generated-js-file>   Target file for generated JS code
  --key=<key>                     HMAC authentication key
  --mode=<mode>                   Treat files like a certain kind of project:
                                    relay: treat files like relay-compiler output
                                    project: treat files like a cohesive project (fragments are shared, names must be unique)
                                    file: treat each file like a stand-alone operation

                                  By default, this flag is set to:
                                    - "relay" if "__generated__" in the path
                                    - otherwise, "project"
  --quiet                         Suppress status logging
  --help                          Print this message
`)
} else {
  var commandName = argv._[0]

  if (commandName !== "sync") {
    console.log("Only `graphql-ruby-client sync` is supported")
  } else {
    var sync = require("./sync")
    var result = sync({
      path: argv.path,
      url: argv.url,
      client: argv.client,
      outfile: argv.outfile,
      secret: argv.secret,
      mode: argv.mode,
      quiet: argv.hasOwnProperty("quiet"),
    })

    if (result instanceof Promise){
      result.then(function(res) {
        if (res === false) {
          process.exit(1)
        }
      })
    } else if (result === false) {
      process.exit(1)
    }
  }
}
<commit_msg>Fix typo in graphql-ruby-client help dialog<commit_after>#!/usr/bin/env node
var parseArgs = require('minimist')
var argv = parseArgs(process.argv.slice(2))

if (argv.help || argv.h) {
  console.log(`usage: graphql-ruby-client sync <options>

  Read .graphql files and push the contained
  operations to a GraphQL::Pro::OperationStore

required arguments:
  --url=<endpoint-url>    URL where data should be POSTed
  --client=<client-name>  Identifier for this client application

optional arguments:
  --path=<path>                   Path to .graphql files (default is "./**/*.graphql")
  --outfile=<generated-js-file>   Target file for generated JS code
  --key=<key>                     HMAC authentication key
  --mode=<mode>                   Treat files like a certain kind of project:
                                    relay: treat files like relay-compiler output
                                    project: treat files like a cohesive project (fragments are shared, names must be unique)
                                    file: treat each file like a stand-alone operation

                                  By default, this flag is set to:
                                    - "relay" if "__generated__" in the path
                                    - otherwise, "project"
  --quiet                         Suppress status logging
  --help                          Print this message
`)
} else {
  var commandName = argv._[0]

  if (commandName !== "sync") {
    console.log("Only `graphql-ruby-client sync` is supported")
  } else {
    var sync = require("./sync")
    var result = sync({
      path: argv.path,
      url: argv.url,
      client: argv.client,
      outfile: argv.outfile,
      secret: argv.secret,
      mode: argv.mode,
      quiet: argv.hasOwnProperty("quiet"),
    })

    if (result instanceof Promise){
      result.then(function(res) {
        if (res === false) {
          process.exit(1)
        }
      })
    } else if (result === false) {
      process.exit(1)
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Created by Joe on 9/2/15.
 */

var demo = new Vue({
    el: 'body',
    data: {
        positions: null,
        judChange: 0
    },
    methods: {
        displayLiving: function ( ) {
            var self = this;

            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var SCREEN_WIDTH = window.innerWidth;
            var SCREEN_HEIGHT = window.innerHeight;

            var container,stats, pointLight;

            var camera, scene, controls, renderer;

            //var judChange = 0;

            init();
            animate();

            function init() {

                container = document.getElementById('livingmap');

                //document.body.appendChild( container );

                //$('div').attr('id', 'three-canvas');

                renderer = new THREE.WebGLRenderer( { antialias: true } );

                //

                camera = new THREE.PerspectiveCamera( 45, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 25000 );
                camera.position.z = 4500;

                scene = new THREE.Scene();

                scene.fog = new THREE.Fog( 0x000000, 0.0008, 25000 );

                scene.add( new THREE.AmbientLight( 0xffffff ) );

                pointLight = new THREE.PointLight( 0x777777, 10, 1400 );
//            pointLight.position.set( 0, 40, 40 );
                scene.add( pointLight );

                // GROUND

                var maxAnisotropy = renderer.getMaxAnisotropy();

                var texture = THREE.ImageUtils.loadTexture( "img/dg.jpg" );
                var pTexture = THREE.ImageUtils.loadTexture( "img/flag.png" );

                var material = new THREE.MeshPhongMaterial( { color: 0xffffff, map: texture } );

                texture.anisotropy = maxAnisotropy;
                texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
//            texture.repeat.set( 512, 512 );

                var groundGeo = new THREE.PlaneBufferGeometry( 200, 100 );

                var mesh = new THREE.Mesh( groundGeo, material );
                mesh.rotation.x = - Math.PI / 4;
                mesh.rotation.z = 0;
                mesh.scale.set( 25, 25, 25 );

                //Particles

                var particles = 50;

                var geometry = new THREE.BufferGeometry();

                self.positions = new Float32Array( particles * 3 );
                var colors = new Float32Array( particles * 3 );

                var color = new THREE.Color();

                var n = 200, n2 = n / 2; // particles spread in the cube

                for ( var i = 0; i < self.positions.length; i += 3 ) {

                    // self.positions

                    var x = Math.random() * n - n2;
                    var y = (Math.random() * n - n2) / 2;
                    var z = 1.6;

                    self.positions[ i ]     = x;
                    self.positions[ i + 1 ] = y;
                    self.positions[ i + 2 ] = z;

                    // colors

                    var vx = ( x / n ) + 0.5;
                    var vy = ( y * 2 / n ) + 0.5;
                    var vz = 0.5;

                    color.setRGB( vx, vy, vz );

                    colors[ i ]     = color.r;
                    colors[ i + 1 ] = color.g;
                    colors[ i + 2 ] = color.b;

                    //line setting

//                var lGeo = new THREE.BufferGeometry();
//                var lMate = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors, linewidth: 0.2 });
//                var lPos = new Float32Array( 6 );
//                var lColo = new Float32Array( 6 );
//
//                var j = 0;
//                lPos[ j ]     = x;
//                lPos[ j + 1 ] = y;
//                lPos[ j + 2 ] = z;
//                lPos[ j + 3 ] = x;
//                lPos[ j + 4 ] = y;
//                lPos[ j + 5 ] = 0;
//
//                lColo[ j ]     = color.r;
//                lColo[ j + 1 ] = color.g;
//                lColo[ j + 2 ] = color.b;
//                lColo[ j + 3 ] = color.r;
//                lColo[ j + 4 ] = color.g;
//                lColo[ j + 5 ] = color.b;
//
//                //lines drawing
//
//                lGeo.addAttribute( 'position', new THREE.BufferAttribute( lPos, 3 ) );
//                lGeo.addAttribute( 'color', new THREE.BufferAttribute( lColo, 3 ) );
//
//                lGeo.computeBoundingSphere();
//
//                var lMesh = new THREE.Line( lGeo, lMate );
//                lMesh.rotation.x = - Math.PI / 4;
//                lMesh.scale.set( 25, 25, 25 );

//                scene.add( lMesh );

                }

                //particles

                geometry.addAttribute( 'position', new THREE.BufferAttribute( self.positions, 3 ) );
                geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );

                geometry.computeBoundingSphere();

                //

//            var pMate = new THREE.PointCloudMaterial( { size: 200, map: pTexture, vertexColors: THREE.VertexColors, blending: THREE.Additive, depthTest: false, transparent : true  } );
                var pMate = new THREE.PointCloudMaterial( { size: 200, map: pTexture, blending: THREE.AdditiveAlpha, depthTest: false, transparent : true  } );

                particleSystem = new THREE.PointCloud( geometry, pMate );

                particleSystem.rotation.x = - Math.PI / 4;
                particleSystem.scale.set( 25, 25, 25 );

                scene.add( particleSystem );

                //console.log(particleSystem.geometry);

                scene.add( mesh );

                object = new THREE.AxisHelper( 1000 );
                object.position.set( 0, 0, 0 );
//            scene.add( object );

                //controls

                controls = new THREE.TrackballControls( camera, container );

                controls.rotateSpeed = 1.0;
                controls.zoomSpeed = 1.2;
                controls.panSpeed = 0.8;

                controls.noZoom = false;
                controls.noPan = false;

                controls.staticMoving = true;
                controls.dynamicDampingFactor = 0.3;

                controls.keys = [ 65, 83, 68 ];

                controls.addEventListener( 'change', render );

                // RENDERER

                renderer.setClearColor( scene.fog.color );
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
                renderer.autoClear = false;

                renderer.domElement.style.position = "relative";
                container.appendChild( renderer.domElement );

                // STATS1

                stats = new Stats();

                // align top-left
                stats.domElement.style.position = 'absolute';
                stats.domElement.style.left = '0px';
                stats.domElement.style.top = '0px';

                document.body.appendChild( stats.domElement );
            }

            function animate() {
                requestAnimationFrame( animate );

                self.judChange++;

                if (self.judChange == 10) {
                    //update the living map people position data
                    self.livingUpdate();
                    self.judChange = 0;
                }

                particleSystem.geometry.attributes.position.needsUpdate = true;

                controls.update();

                render();
                stats.update();

            }

            function render() {

                renderer.enableScissorTest( false );
                renderer.clear();
                renderer.enableScissorTest( true );

                renderer.setScissor( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
                pointLight.position.set(camera.position.x, camera.position.y, camera.position.z);

                renderer.render( scene, camera );
            }
        },
        livingUpdate: function () {
            var self = this;

            for ( var i = 0; i < self.positions.length; i += 3 ) {

                // self.positions

                var x = (Math.random() - 0.5) * 2;
                var y = (Math.random() - 0.5);
                var z = 1.6;

                self.positions[ i ]     += x;
                self.positions[ i + 1 ] += y;
                self.positions[ i + 2 ]  = z;

                if ( self.positions[ i ] < -100 )
                    self.positions[ i ] += 10;
                else if ( self.positions[ i ] > 100 )
                    self.positions[ i ] -= 10;

                if ( self.positions[ i + 1 ] < -50 )
                    self.positions[ i + 1 ] += 10;
                else if ( self.positions[ i + 1 ] > 50 )
                    self.positions[ i + 1 ] -= 10;
            }

        }
    },
    compiled: function () {
        var self = this;

        self.displayLiving();
    }
});<commit_msg>update multi particlesytem<commit_after>/**
 * Created by Joe on 9/2/15.
 */

var demo = new Vue({
    el: 'body',
    data: {
        positions: null,
        judChange: 0
    },
    methods: {
        displayLiving: function ( ) {
            var self = this;

            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var SCREEN_WIDTH = window.innerWidth;
            var SCREEN_HEIGHT = window.innerHeight;

            var container,stats, pointLight;

            var camera, scene, controls, renderer;

            //var judChange = 0;

            init();
            animate();

            function init() {

                container = document.getElementById('livingmap');

                //document.body.appendChild( container );

                //$('div').attr('id', 'three-canvas');

                renderer = new THREE.WebGLRenderer( { antialias: true } );

                //

                camera = new THREE.PerspectiveCamera( 45, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 25000 );
                camera.position.z = 4500;
                camera.position.y = -3000;
                //camera.rotation.z = Math.PI / 4;

                scene = new THREE.Scene();

                scene.fog = new THREE.Fog( 0x000000, 0.0008, 25000 );

                scene.add( new THREE.AmbientLight( 0xffffff ) );

                pointLight = new THREE.PointLight( 0x777777, 10, 1400 );
//            pointLight.position.set( 0, 40, 40 );
                scene.add( pointLight );

                // GROUND

                var maxAnisotropy = renderer.getMaxAnisotropy();

                var texture = THREE.ImageUtils.loadTexture( "img/dg.jpg" );
                var pTexture = THREE.ImageUtils.loadTexture( "img/flag.png" );

                var material = new THREE.MeshPhongMaterial( { color: 0xffffff, map: texture } );

                texture.anisotropy = maxAnisotropy;
                texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
//            texture.repeat.set( 512, 512 );

                var groundGeo = new THREE.PlaneBufferGeometry( 200, 100 );

                //0907
                var mesh = new THREE.Mesh( groundGeo, material );
                //mesh.rotation.x = - Math.PI / 4;
                mesh.rotation.z = 0;
                mesh.scale.set( 25, 25, 25 );

                //Particles

                var particles = 50;

                var geometry = new THREE.BufferGeometry();

                self.positions = new Float32Array( particles * 3 );
                var colors = new Float32Array( particles * 3 );

                var color = new THREE.Color();

                var n = 200, n2 = n / 2; // particles spread in the cube

                for ( var i = 0; i < self.positions.length; i += 3 ) {

                    // self.positions

                    var x = Math.random() * n - n2;
                    var y = (Math.random() * n - n2) / 2;
                    var z = 1.6;

                    self.positions[ i ]     = x;
                    self.positions[ i + 1 ] = y;
                    self.positions[ i + 2 ] = z;

                    // colors

                    var vx = ( x / n ) + 0.5;
                    var vy = ( y * 2 / n ) + 0.5;
                    var vz = 0.5;

                    color.setRGB( vx, vy, vz );

                    colors[ i ]     = color.r;
                    colors[ i + 1 ] = color.g;
                    colors[ i + 2 ] = color.b;

                    //line setting

//                var lGeo = new THREE.BufferGeometry();
//                var lMate = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors, linewidth: 0.2 });
//                var lPos = new Float32Array( 6 );
//                var lColo = new Float32Array( 6 );
//
//                var j = 0;
//                lPos[ j ]     = x;
//                lPos[ j + 1 ] = y;
//                lPos[ j + 2 ] = z;
//                lPos[ j + 3 ] = x;
//                lPos[ j + 4 ] = y;
//                lPos[ j + 5 ] = 0;
//
//                lColo[ j ]     = color.r;
//                lColo[ j + 1 ] = color.g;
//                lColo[ j + 2 ] = color.b;
//                lColo[ j + 3 ] = color.r;
//                lColo[ j + 4 ] = color.g;
//                lColo[ j + 5 ] = color.b;
//
//                //lines drawing
//
//                lGeo.addAttribute( 'position', new THREE.BufferAttribute( lPos, 3 ) );
//                lGeo.addAttribute( 'color', new THREE.BufferAttribute( lColo, 3 ) );
//
//                lGeo.computeBoundingSphere();
//
//                var lMesh = new THREE.Line( lGeo, lMate );
//                lMesh.rotation.x = - Math.PI / 4;
//                lMesh.scale.set( 25, 25, 25 );

//                scene.add( lMesh );

                }

                //particles

                geometry.addAttribute( 'position', new THREE.BufferAttribute( self.positions, 3 ) );
                geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );

                geometry.computeBoundingSphere();

                //

//            var pMate = new THREE.PointCloudMaterial( { size: 200, map: pTexture, vertexColors: THREE.VertexColors, blending: THREE.Additive, depthTest: false, transparent : true  } );
                var pMate = new THREE.PointCloudMaterial( { size: 200, map: pTexture, blending: THREE.AdditiveAlpha, depthTest: false, transparent : true  } );

                particleSystem = new THREE.PointCloud( geometry, pMate );

                //0907
                particleSystem.position.set( 1800, -500, 0);
                particleSystem.scale.set( 5, 5, 5 );
                //particleSystem.rotation.x = - Math.PI / 4;

                particleSystem2 = new THREE.PointCloud( geometry, pMate );

                particleSystem2.position.set( -1800, 500, 0);
                particleSystem2.scale.set( 5, 5, 5 );
                particleSystem2.rotation.z = Math.PI / 4;
                //particleSystem2.rotation.x = - Math.PI / 4;

                scene.add( particleSystem2 );

                //0907 END

                scene.add( particleSystem );

                //console.log(particleSystem.geometry);

                scene.add( mesh );

                object = new THREE.AxisHelper( 1000 );
                object.position.set( 1000, 0, 0 );
                scene.add( object );

                //controls

                controls = new THREE.TrackballControls( camera, container );

                controls.rotateSpeed = 1.0;
                controls.zoomSpeed = 1.2;
                controls.panSpeed = 0.8;

                controls.noZoom = false;
                controls.noPan = false;

                controls.staticMoving = true;
                controls.dynamicDampingFactor = 0.3;

                controls.keys = [ 65, 83, 68 ];

                controls.addEventListener( 'change', render );

                // RENDERER

                renderer.setClearColor( scene.fog.color );
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
                renderer.autoClear = false;

                renderer.domElement.style.position = "relative";
                container.appendChild( renderer.domElement );

                // STATS1

                stats = new Stats();

                // align top-left
                stats.domElement.style.position = 'absolute';
                stats.domElement.style.left = '0px';
                stats.domElement.style.top = '0px';

                document.body.appendChild( stats.domElement );
            }

            function animate() {
                requestAnimationFrame( animate );

                self.judChange++;

                if (self.judChange == 10) {
                    //update the living map people position data
                    self.livingUpdate();
                    self.judChange = 0;
                }

                particleSystem.geometry.attributes.position.needsUpdate = true;

                controls.update();

                render();
                stats.update();

            }

            function render() {

                renderer.enableScissorTest( false );
                renderer.clear();
                renderer.enableScissorTest( true );

                renderer.setScissor( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
                pointLight.position.set(camera.position.x, camera.position.y, camera.position.z);

                renderer.render( scene, camera );
            }
        },
        livingUpdate: function () {
            var self = this;

            for ( var i = 0; i < self.positions.length; i += 3 ) {

                // self.positions

                var x = (Math.random() - 0.5) * 2;
                var y = (Math.random() - 0.5);
                var z = 1.6;

                self.positions[ i ]     += x;
                self.positions[ i + 1 ] += y;
                self.positions[ i + 2 ]  = z;

                if ( self.positions[ i ] < -100 )
                    self.positions[ i ] += 10;
                else if ( self.positions[ i ] > 100 )
                    self.positions[ i ] -= 10;

                if ( self.positions[ i + 1 ] < -50 )
                    self.positions[ i + 1 ] += 10;
                else if ( self.positions[ i + 1 ] > 50 )
                    self.positions[ i + 1 ] -= 10;
            }

        }
    },
    compiled: function () {
        var self = this;

        self.displayLiving();
    }
});<|endoftext|>


<commit_before><commit_msg>increase opacity on focus, animate at 700 ms<commit_after><|endoftext|>


<commit_before>// Simple pure-React component so we don't have to remember
// Bootstrap's classes
var BootstrapButton = React.createClass({
  render: function() {
    return (

    );
  }
});

var BootstrapModal = React.createClass({
  // The following two methods are the only places we need to
  // integrate with Bootstrap or jQuery!
  componentDidMount: function() {
    // When the component is added, turn it into a modal
    $(this.getDOMNode())
      .modal({backdrop: 'static', keyboard: false, show: false})
  },
  componentWillUnmount: function() {
    $(this.getDOMNode()).off('hidden', this.handleHidden);
  },
  close: function() {
    $(this.getDOMNode()).modal('hide');
  },
  open: function() {
    $(this.getDOMNode()).modal('show');
  },
  render: function() {
    var confirmButton = null;
    var cancelButton = null;

    if (this.props.confirm) {
      confirmButton = (
        <BootstrapButton
          onClick={this.handleConfirm}
          className="btn-primary">
          {this.props.confirm}
        </BootstrapButton>
      );
    }
    if (this.props.cancel) {
      cancelButton = (
        <BootstrapButton onClick={this.handleCancel} className="btn-default">
          {this.props.cancel}
        </BootstrapButton>
      );
    }

    return (

              <button
                type="button"
                className="close"
                onClick={this.handleCancel}>
                ×
              </button>

{this.props.title}

              {this.props.children}

              {cancelButton}
              {confirmButton}

    );
  },
  handleCancel: function() {
    if (this.props.onCancel) {
      this.props.onCancel();
    }
  },
  handleConfirm: function() {
    if (this.props.onConfirm) {
      this.props.onConfirm();
    }
  }
});

var Example = React.createClass({
  handleCancel: function() {
    if (confirm('Are you sure you want to cancel?')) {
      this.refs.modal.close();
    }
  },
  render: function() {
    var modal = null;
    modal = (
      <BootstrapModal
        ref="modal"
        confirm="OK"
        cancel="Cancel"
        onCancel={this.handleCancel}
        onConfirm={this.closeModal}
        title="Hello, Bootstrap!">
          This is a React component powered by jQuery and Bootstrap!
      </BootstrapModal>
    );
    return (

        {modal}
        <BootstrapButton onClick={this.openModal} className="btn-default">
          Open modal
        </BootstrapButton>

    );
  },
  openModal: function() {
    this.refs.modal.open();
  },
  closeModal: function() {
    this.refs.modal.close();
  }
});

React.render(<Example />, document.getElementById('jqueryexample'));
<commit_msg>Fix typo in comment of jquery-bootstrap example<commit_after>// Simple pure-React component so we don't have to remember
// Bootstrap's classes
var BootstrapButton = React.createClass({
  render: function() {
    return (

    );
  }
});

var BootstrapModal = React.createClass({
  // The following four methods are the only places we need to
  // integrate with Bootstrap or jQuery!
  componentDidMount: function() {
    // When the component is added, turn it into a modal
    $(this.getDOMNode())
      .modal({backdrop: 'static', keyboard: false, show: false})
  },
  componentWillUnmount: function() {
    $(this.getDOMNode()).off('hidden', this.handleHidden);
  },
  close: function() {
    $(this.getDOMNode()).modal('hide');
  },
  open: function() {
    $(this.getDOMNode()).modal('show');
  },
  render: function() {
    var confirmButton = null;
    var cancelButton = null;

    if (this.props.confirm) {
      confirmButton = (
        <BootstrapButton
          onClick={this.handleConfirm}
          className="btn-primary">
          {this.props.confirm}
        </BootstrapButton>
      );
    }
    if (this.props.cancel) {
      cancelButton = (
        <BootstrapButton onClick={this.handleCancel} className="btn-default">
          {this.props.cancel}
        </BootstrapButton>
      );
    }

    return (

              <button
                type="button"
                className="close"
                onClick={this.handleCancel}>
                ×
              </button>

{this.props.title}

              {this.props.children}

              {cancelButton}
              {confirmButton}

    );
  },
  handleCancel: function() {
    if (this.props.onCancel) {
      this.props.onCancel();
    }
  },
  handleConfirm: function() {
    if (this.props.onConfirm) {
      this.props.onConfirm();
    }
  }
});

var Example = React.createClass({
  handleCancel: function() {
    if (confirm('Are you sure you want to cancel?')) {
      this.refs.modal.close();
    }
  },
  render: function() {
    var modal = null;
    modal = (
      <BootstrapModal
        ref="modal"
        confirm="OK"
        cancel="Cancel"
        onCancel={this.handleCancel}
        onConfirm={this.closeModal}
        title="Hello, Bootstrap!">
          This is a React component powered by jQuery and Bootstrap!
      </BootstrapModal>
    );
    return (

        {modal}
        <BootstrapButton onClick={this.openModal} className="btn-default">
          Open modal
        </BootstrapButton>

    );
  },
  openModal: function() {
    this.refs.modal.open();
  },
  closeModal: function() {
    this.refs.modal.close();
  }
});

React.render(<Example />, document.getElementById('jqueryexample'));
<|endoftext|>


<commit_before>// test urls
Util.debugURL = function(url) {
	if(u.bug_force) {
		return true;
	}
	return document.domain.match(/.local$/);
}
// identify node
Util.nodeId = function(node, include_path) {
//	try {
		if(!include_path) {
			return node.id ? node.nodeName+"#"+node.id : (node.className ? node.nodeName+"."+node.className : (node.name ? node.nodeName + "["+node.name+"]" : node.nodeName));
		}
		else {
			if(node.parentNode && node.parentNode.nodeName != "HTML") {
				return u.nodeId(node.parentNode, include_path) + "->" + u.nodeId(node);
			}
			else {
				return u.nodeId(node);
			}
		}
//	}
	// catch(exception) {
	// 	u.bug("Exception ("+exception+") in u.nodeId("+node+"), called from: "+arguments.callee.caller);
	// }
	return "Unindentifiable node!";
}

// write output to screen
Util.bug = function(message, corner, color) {
	if(u.debugURL()) {

		if(!u.bug_console_only) {
			var option, options = new Array([0, "auto", "auto", 0], [0, 0, "auto", "auto"], ["auto", 0, 0, "auto"], ["auto", "auto", 0, 0]);
			if(isNaN(corner)) {
				color = corner;
				corner = 0;
			}
			if(typeof(color) != "string") {
				color = "black";
			}
			option = options[corner];

			if(!document.getElementById("debug_id_"+corner)) {
				var d_target = u.ae(document.body, "div", {"class":"debug_"+corner, "id":"debug_id_"+corner});
				d_target.style.position = u.bug_position ? u.bug_position : "absolute";
				d_target.style.zIndex = 16000;
				d_target.style.top = option[0];
				d_target.style.right = option[1];
				d_target.style.bottom = option[2];
				d_target.style.left = option[3];
				d_target.style.backgroundColor = u.bug_bg ? u.bug_bg : "#ffffff";
				d_target.style.color = "#000000";
				d_target.style.textAlign = "left";
				if(d_target.style.maxWidth) {
					d_target.style.maxWidth = u.bug_max_width ? u.bug_max_width+"px" : "auto";
				}
				d_target.style.padding = "3px";
			}

			if(typeof(message) != "string") {
				message = message.toString();
			}

			var debug_div = document.getElementById("debug_id_"+corner);
			message = message ? message.replace(/\>/g, ">").replace(/\</g, "<").replace(/<br>/g, "
") : "Util.bug with no message?";
//			alert("message:" + message + ", " + debug_div)
//			u.ae(u.qs("#debug_id_"+corner), "div", ({"style":"color: " + color})).innerHTML = message ? message.replace(/>/g, ">").replace(/</g, "<").replace(/<br>/g, "
") : "Util.bug with no message?";
			u.ae(debug_div, "div", {"style":"color: " + color, "html": message});
		}
		if(typeof(console) == "object") {
			console.log(message);
		}
	}
}

Util.xInObject = function(object) {
	if(u.debugURL()) {
		var x, s = "--- start object ---
";
		for(x in object) {
		//	u.bug(x + ":" + object[x] + ":" + typeof(object[x]));
			if(object[x] && typeof(object[x]) == "object" && typeof(object[x].nodeName) == "string") {
				s += x + "=" + object[x]+" -> " + u.nodeId(object[x], 1) + "
";
			}
			else if(object[x] && typeof(object[x]) == "function") {
				s += x + "=function
";
			}
			else {
				s += x + "=" + object[x]+"
";
			}
		}
		s += "--- end object ---"
		u.bug(s);
	}
}

<commit_msg>Added newline to output for better reading<commit_after>// test urls
Util.debugURL = function(url) {
	if(u.bug_force) {
		return true;
	}
	return document.domain.match(/.local$/);
}
// identify node
Util.nodeId = function(node, include_path) {
//	try {
		if(!include_path) {
			return node.id ? node.nodeName+"#"+node.id : (node.className ? node.nodeName+"."+node.className : (node.name ? node.nodeName + "["+node.name+"]" : node.nodeName));
		}
		else {
			if(node.parentNode && node.parentNode.nodeName != "HTML") {
				return u.nodeId(node.parentNode, include_path) + "->" + u.nodeId(node);
			}
			else {
				return u.nodeId(node);
			}
		}
//	}
	// catch(exception) {
	// 	u.bug("Exception ("+exception+") in u.nodeId("+node+"), called from: "+arguments.callee.caller);
	// }
	return "Unindentifiable node!";
}

// write output to screen
Util.bug = function(message, corner, color) {
	if(u.debugURL()) {

		if(!u.bug_console_only) {
			var option, options = new Array([0, "auto", "auto", 0], [0, 0, "auto", "auto"], ["auto", 0, 0, "auto"], ["auto", "auto", 0, 0]);
			if(isNaN(corner)) {
				color = corner;
				corner = 0;
			}
			if(typeof(color) != "string") {
				color = "black";
			}
			option = options[corner];

			if(!document.getElementById("debug_id_"+corner)) {
				var d_target = u.ae(document.body, "div", {"class":"debug_"+corner, "id":"debug_id_"+corner});
				d_target.style.position = u.bug_position ? u.bug_position : "absolute";
				d_target.style.zIndex = 16000;
				d_target.style.top = option[0];
				d_target.style.right = option[1];
				d_target.style.bottom = option[2];
				d_target.style.left = option[3];
				d_target.style.backgroundColor = u.bug_bg ? u.bug_bg : "#ffffff";
				d_target.style.color = "#000000";
				d_target.style.textAlign = "left";
				if(d_target.style.maxWidth) {
					d_target.style.maxWidth = u.bug_max_width ? u.bug_max_width+"px" : "auto";
				}
				d_target.style.padding = "3px";
			}

			if(typeof(message) != "string") {
				message = message.toString();
			}

			var debug_div = document.getElementById("debug_id_"+corner);
			message = message ? message.replace(/\>/g, ">").replace(/\</g, "<").replace(/<br>/g, "
") : "Util.bug with no message?";
//			alert("message:" + message + ", " + debug_div)
//			u.ae(u.qs("#debug_id_"+corner), "div", ({"style":"color: " + color})).innerHTML = message ? message.replace(/>/g, ">").replace(/</g, "<").replace(/<br>/g, "
") : "Util.bug with no message?";
			u.ae(debug_div, "div", {"style":"color: " + color, "html": message});
		}
		if(typeof(console) == "object") {
			console.log(message);
		}
	}
}

Util.xInObject = function(object) {
	if(u.debugURL()) {
		var x, s = "--- start object ---
";
		for(x in object) {
		//	u.bug(x + ":" + object[x] + ":" + typeof(object[x]));
			if(object[x] && typeof(object[x]) == "object" && typeof(object[x].nodeName) == "string") {
				s += x + "=" + object[x]+" -> " + u.nodeId(object[x], 1) + "
\n";
			}
			else if(object[x] && typeof(object[x]) == "function") {
				s += x + "=function
\n";
			}
			else {
				s += x + "=" + object[x]+"
\n";
			}
		}
		s += "--- end object ---"
		u.bug(s);
	}
}

<|endoftext|>


<commit_before>import indentString from 'indent-string';
import _ from 'lodash';
import qrcodeTerminal from 'qrcode-terminal';

import { Android, ProjectSettings, Simulator } from 'xdl';

import CommandError from './CommandError';

function addOptions(program) {
  program
    .option('-a, --android', 'Opens your app in Expo on a connected Android device')
    .option(
      '-i, --ios',
      'Opens your app in Expo in a currently running iOS simulator on your computer'
    )
    .option(
      '-m, --host [mode]',
      'tunnel (default), lan, localhost. Type of host to use. "tunnel" allows you to view your link on other networks'
    )
    .option('--tunnel', 'Same as --host tunnel')
    .option('--lan', 'Same as --host lan')
    .option('--localhost', 'Same as --host localhost')
    .option('--dev', 'Turns dev flag on')
    .option('--no-dev', 'Turns dev flag off')
    .option('--strict', 'Turns strict flag on')
    .option('--no-strict', 'Turns strict flag off')
    .option('--minify', 'Turns minify flag on')
    .option('--no-minify', 'Turns minify flag off');
}

function hasBooleanArg(rawArgs, argName) {
  return _.includes(rawArgs, '--' + argName) || _.includes(rawArgs, '--no-' + argName);
}

function getBooleanArg(rawArgs, argName) {
  if (_.includes(rawArgs, '--' + argName)) {
    return true;
  } else {
    return false;
  }
}

async function optsAsync(projectDir, options) {
  var opts = await ProjectSettings.readAsync(projectDir);

  if (!!options.host + !!options.lan + !!options.localhost + !!options.tunnel > 1) {
    throw CommandError(
      'BAD_ARGS',
      'Specify at most one of --host, --tunnel, --lan, and --localhost'
    );
  }

  if (options.host) {
    opts.hostType = options.host;
  }
  if (options.tunnel) {
    opts.hostType = 'tunnel';
  }
  if (options.lan) {
    opts.hostType = 'lan';
  }
  if (options.localhost) {
    opts.hostType = 'localhost';
  }

  let rawArgs = options.parent.rawArgs;
  if (hasBooleanArg(rawArgs, 'dev')) {
    opts.dev = getBooleanArg(rawArgs, 'dev');
  }
  if (hasBooleanArg(rawArgs, 'strict')) {
    opts.strict = getBooleanArg(rawArgs, 'strict');
  }
  if (hasBooleanArg(rawArgs, 'minify')) {
    opts.minify = getBooleanArg(rawArgs, 'minify');
  }

  await ProjectSettings.setAsync(projectDir, opts);

  return opts;
}

function printQRCode(url) {
  qrcodeTerminal.generate(url, code => console.log(`${indentString(code, 2)}\n`));
}

async function handleMobileOptsAsync(projectDir, options) {
  if (options.android) {
    await Android.openProjectAsync(projectDir);
  }

  if (options.ios) {
    await Simulator.openProjectAsync(projectDir);
  }

  return !!options.android || !!options.ios;
}

export default {
  addOptions,
  handleMobileOptsAsync,
  printQRCode,
  optsAsync,
};
<commit_msg>Remove `strict` project setting (#1647)<commit_after>import indentString from 'indent-string';
import _ from 'lodash';
import qrcodeTerminal from 'qrcode-terminal';

import { Android, ProjectSettings, Simulator } from 'xdl';

import CommandError from './CommandError';

function addOptions(program) {
  program
    .option('-a, --android', 'Opens your app in Expo on a connected Android device')
    .option(
      '-i, --ios',
      'Opens your app in Expo in a currently running iOS simulator on your computer'
    )
    .option(
      '-m, --host [mode]',
      'tunnel (default), lan, localhost. Type of host to use. "tunnel" allows you to view your link on other networks'
    )
    .option('--tunnel', 'Same as --host tunnel')
    .option('--lan', 'Same as --host lan')
    .option('--localhost', 'Same as --host localhost')
    .option('--dev', 'Turns dev flag on')
    .option('--no-dev', 'Turns dev flag off')
    .option('--minify', 'Turns minify flag on')
    .option('--no-minify', 'Turns minify flag off');
}

function hasBooleanArg(rawArgs, argName) {
  return _.includes(rawArgs, '--' + argName) || _.includes(rawArgs, '--no-' + argName);
}

function getBooleanArg(rawArgs, argName) {
  if (_.includes(rawArgs, '--' + argName)) {
    return true;
  } else {
    return false;
  }
}

async function optsAsync(projectDir, options) {
  var opts = await ProjectSettings.readAsync(projectDir);

  if (!!options.host + !!options.lan + !!options.localhost + !!options.tunnel > 1) {
    throw CommandError(
      'BAD_ARGS',
      'Specify at most one of --host, --tunnel, --lan, and --localhost'
    );
  }

  if (options.host) {
    opts.hostType = options.host;
  }
  if (options.tunnel) {
    opts.hostType = 'tunnel';
  }
  if (options.lan) {
    opts.hostType = 'lan';
  }
  if (options.localhost) {
    opts.hostType = 'localhost';
  }

  let rawArgs = options.parent.rawArgs;
  if (hasBooleanArg(rawArgs, 'dev')) {
    opts.dev = getBooleanArg(rawArgs, 'dev');
  }
  if (hasBooleanArg(rawArgs, 'minify')) {
    opts.minify = getBooleanArg(rawArgs, 'minify');
  }

  await ProjectSettings.setAsync(projectDir, opts);

  return opts;
}

function printQRCode(url) {
  qrcodeTerminal.generate(url, code => console.log(`${indentString(code, 2)}\n`));
}

async function handleMobileOptsAsync(projectDir, options) {
  if (options.android) {
    await Android.openProjectAsync(projectDir);
  }

  if (options.ios) {
    await Simulator.openProjectAsync(projectDir);
  }

  return !!options.android || !!options.ios;
}

export default {
  addOptions,
  handleMobileOptsAsync,
  printQRCode,
  optsAsync,
};
<|endoftext|>


<commit_before><commit_msg>Update getAnchor.js<commit_after><|endoftext|>


<commit_before>(function($,$TD){
  //
  // Constant: List of valid font size classes.
  //
  var fontSizeClasses = [ "txt-base-smallest", "txt-base-small", "txt-base-medium", "txt-base-large", "txt-base-largest" ];

  //
  // Variable: Says whether TweetDick events was initialized.
  //
  var isInitialized = false;

  //
  // Variable: Previous font size class in the  tag.
  //
  var prevFontSizeClass;

  //
  // Function: Initializes TweetDick events. Called after the website app is loaded.
  //
  var initializeTweetDick = function(){
    // Settings button hook
    $("[data-action='settings-menu']").click(function(){
      setTimeout(function(){
        var menu = $(".js-dropdown-content").children("ul").first();
        if (menu.length == 0)return;

        menu.children(".drp-h-divider").last().after('
'+$TD.brandName+'

');

        var tweetDickBtn = menu.children("[data-std]").first();

        tweetDickBtn.on("click","a",function(){
          $TD.openSettingsMenu();
        });

        tweetDickBtn.hover(function(){
          $(this).addClass("is-selected");
        },function(){
          $(this).removeClass("is-selected");
        });
      },0);
    });

    // Tweet notifications
    (function(){
      var columns = $(".js-app-columns").first();

      var refreshColumnObservers = function(){
        columns.children().each(function(){
          registerTweetObserverForColumn($(this));
        });
      };

      new MutationObserver(refreshColumnObservers).observe(columns[0],{
        childList: true
      });

      refreshColumnObservers();
    })();

    // Popup notifications
    window.TD.controller.notifications.hasNotifications = function(){
      return true;
    };

    window.TD.controller.notifications.isPermissionGranted = function(){
      return true;
    };

    // Finish init
    isInitialized = true;
  };

  //
  // Function: Registers an observer to a TweetDeck column, which reports new tweets.
  //
  var registerTweetObserverForColumn = function(column){
    if (column[0].hasAttribute("data-std-observed"))return;

    var mid = column;
    mid = mid.children().first();
    mid = mid.children().first();
    mid = mid.children(".js-column-content").first();
    mid = mid.children(".js-column-scroller").first();

    var container = mid.children(".js-chirp-container").first();
    if (container.length == 0)return;

    var scroller = container.parent();

    new MutationObserver(function(mutations){
      if (!container[0].hasAttribute("data-std-loaded")){
        container[0].setAttribute("data-std-loaded","");
        return;
      }

      var data = TD.controller.columnManager.get(column.attr("data-column"));
      if (!data.model.getHasNotification())return;

      if (scroller.scrollTop() != 0)return;

      Array.prototype.forEach.call(mutations,function(mutation){
        Array.prototype.forEach.call(mutation.addedNodes,function(node){
          if (node.tagName != "ARTICLE")return;

          onNewTweet(column,node);
        });
      });
    }).observe(container[0],{
      childList: true
    });

    column[0].setAttribute("data-std-observed","");
  };

  //
  // Function: Event callback for a new tweet.
  //
  var onNewTweet = function(column, tweet){
    var html = $(tweet.outerHTML);
    var body = html.find(".tweet-body").first();

    body.children("div.js-quote-detail").each(function(){
      $(this).html("(quoted tweet)");
    });

    body.children().not("p,div.js-quote-detail").remove();

    $TD.onTweetPopup(html.html(),html.find(".js-tweet-text:first").text().length); // TODO column & remove pic links from text()
  };

  //
  // Function: Retrieves the font size using  class attribute.
  //
  var getFontSizeClass = function(){
    for(var index = 0; index < fontSizeClasses.length; index++){
      if (document.documentElement.classList.contains(fontSizeClasses[index])){
        return fontSizeClasses[index];
      }
    }

    return fontSizeClasses[0];
  };

  //
  // Function: Retrieves the tags to be put into  for notification HTML code.
  //
  var getNotificationHeadContents = function(){
    var tags = [];

    $(document.head).children("link[rel='stylesheet'],meta[charset],meta[http-equiv]").each(function(){
      tags.push($(this)[0].outerHTML);
    });

    return tags.join("");
  };

  //
  // Block: Observe the app
 element and initialize TweetDick whenever possible.
  //
  var app = $("body").children(".js-app");

  new MutationObserver(function(mutations){
    if (isInitialized && app.hasClass("is-hidden")){
      isInitialized = false;
    }
    else if (!isInitialized && !app.hasClass("is-hidden")){
      initializeTweetDick();
    }
  }).observe(app[0],{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe changes in  class to update font size.
  //
  new MutationObserver(function(mutations){
    var fsClass = getFontSizeClass();

    if (fsClass != prevFontSizeClass){
      prevFontSizeClass = fsClass;
      $TD.loadFontSizeClass(fsClass);
    }
  }).observe(document.documentElement,{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe stylesheet swapping.
  //
  new MutationObserver(function(mutations){
    $TD.loadNotificationHeadContents(getNotificationHeadContents());
  }).observe(document.head.querySelector("[http-equiv='Default-Style']"),{
    attributes: true,
    attributeFilter: [ "content" ]
  });

  $TD.loadNotificationHeadContents(getNotificationHeadContents());

  //
  // Block: Hook into links to bypass default open function
  //
  $(document.body).delegate("a[target='_blank']","click",function(e){
    var me = $(this);

    if (!me.is(".link-complex") && !(me.attr("rel") == "mediaPreview" && me.closest("#open-modal").length == 0)){
      $TD.openBrowser(me.attr("href"));
    }

    e.preventDefault();
  });

  window.open = function(url){
    $TD.openBrowser(url);
  };
})($,$TD);
<commit_msg>Redo url hooks to avoid duplicate browser opens<commit_after>(function($,$TD){
  //
  // Constant: List of valid font size classes.
  //
  var fontSizeClasses = [ "txt-base-smallest", "txt-base-small", "txt-base-medium", "txt-base-large", "txt-base-largest" ];

  //
  // Variable: Says whether TweetDick events was initialized.
  //
  var isInitialized = false;

  //
  // Variable: Previous font size class in the  tag.
  //
  var prevFontSizeClass;

  //
  // Function: Initializes TweetDick events. Called after the website app is loaded.
  //
  var initializeTweetDick = function(){
    // Settings button hook
    $("[data-action='settings-menu']").click(function(){
      setTimeout(function(){
        var menu = $(".js-dropdown-content").children("ul").first();
        if (menu.length == 0)return;

        menu.children(".drp-h-divider").last().after('
'+$TD.brandName+'

');

        var tweetDickBtn = menu.children("[data-std]").first();

        tweetDickBtn.on("click","a",function(){
          $TD.openSettingsMenu();
        });

        tweetDickBtn.hover(function(){
          $(this).addClass("is-selected");
        },function(){
          $(this).removeClass("is-selected");
        });
      },0);
    });

    // Tweet notifications
    (function(){
      var columns = $(".js-app-columns").first();

      var refreshColumnObservers = function(){
        columns.children().each(function(){
          registerTweetObserverForColumn($(this));
        });
      };

      new MutationObserver(refreshColumnObservers).observe(columns[0],{
        childList: true
      });

      refreshColumnObservers();
    })();

    // Popup notifications
    window.TD.controller.notifications.hasNotifications = function(){
      return true;
    };

    window.TD.controller.notifications.isPermissionGranted = function(){
      return true;
    };

    // Finish init
    isInitialized = true;
  };

  //
  // Function: Registers an observer to a TweetDeck column, which reports new tweets.
  //
  var registerTweetObserverForColumn = function(column){
    if (column[0].hasAttribute("data-std-observed"))return;

    var mid = column;
    mid = mid.children().first();
    mid = mid.children().first();
    mid = mid.children(".js-column-content").first();
    mid = mid.children(".js-column-scroller").first();

    var container = mid.children(".js-chirp-container").first();
    if (container.length == 0)return;

    var scroller = container.parent();

    new MutationObserver(function(mutations){
      if (!container[0].hasAttribute("data-std-loaded")){
        container[0].setAttribute("data-std-loaded","");
        return;
      }

      var data = TD.controller.columnManager.get(column.attr("data-column"));
      if (!data.model.getHasNotification())return;

      if (scroller.scrollTop() != 0)return;

      Array.prototype.forEach.call(mutations,function(mutation){
        Array.prototype.forEach.call(mutation.addedNodes,function(node){
          if (node.tagName != "ARTICLE")return;

          onNewTweet(column,node);
        });
      });
    }).observe(container[0],{
      childList: true
    });

    column[0].setAttribute("data-std-observed","");
  };

  //
  // Function: Event callback for a new tweet.
  //
  var onNewTweet = function(column, tweet){
    var html = $(tweet.outerHTML);
    var body = html.find(".tweet-body").first();

    body.children("div.js-quote-detail").each(function(){
      $(this).html("(quoted tweet)");
    });

    body.children().not("p,div.js-quote-detail").remove();

    $TD.onTweetPopup(html.html(),html.find(".js-tweet-text:first").text().length); // TODO column & remove pic links from text()
  };

  //
  // Function: Retrieves the font size using  class attribute.
  //
  var getFontSizeClass = function(){
    for(var index = 0; index < fontSizeClasses.length; index++){
      if (document.documentElement.classList.contains(fontSizeClasses[index])){
        return fontSizeClasses[index];
      }
    }

    return fontSizeClasses[0];
  };

  //
  // Function: Retrieves the tags to be put into  for notification HTML code.
  //
  var getNotificationHeadContents = function(){
    var tags = [];

    $(document.head).children("link[rel='stylesheet'],meta[charset],meta[http-equiv]").each(function(){
      tags.push($(this)[0].outerHTML);
    });

    return tags.join("");
  };

  //
  // Block: Observe the app
 element and initialize TweetDick whenever possible.
  //
  var app = $("body").children(".js-app");

  new MutationObserver(function(mutations){
    if (isInitialized && app.hasClass("is-hidden")){
      isInitialized = false;
    }
    else if (!isInitialized && !app.hasClass("is-hidden")){
      initializeTweetDick();
    }
  }).observe(app[0],{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe changes in  class to update font size.
  //
  new MutationObserver(function(mutations){
    var fsClass = getFontSizeClass();

    if (fsClass != prevFontSizeClass){
      prevFontSizeClass = fsClass;
      $TD.loadFontSizeClass(fsClass);
    }
  }).observe(document.documentElement,{
    attributes: true,
    attributeFilter: [ "class" ]
  });

  //
  // Block: Observe stylesheet swapping.
  //
  new MutationObserver(function(mutations){
    $TD.loadNotificationHeadContents(getNotificationHeadContents());
  }).observe(document.head.querySelector("[http-equiv='Default-Style']"),{
    attributes: true,
    attributeFilter: [ "content" ]
  });

  $TD.loadNotificationHeadContents(getNotificationHeadContents());

  //
  // Block: Hook into links to bypass default open function
  //
  (function(){
    var urlWait = false;

    var onUrlOpened = function(){
      urlWait = true;
      setTimeout(function(){ urlWait = false; },0);
    };

    $(document.body).delegate("a[target='_blank']","click",function(e){
      if (urlWait)return;

      var me = $(this);

      if (!me.is(".link-complex") && !(me.attr("rel") == "mediaPreview" && me.closest("#open-modal").length == 0)){
        $TD.openBrowser(me.attr("href"));
      }

      e.preventDefault();
      onUrlOpened();
    });

    window.open = function(url){
      if (urlWait)return;

      $TD.openBrowser(url);
      onUrlOpened();
    };
  })();
})($,$TD);
<|endoftext|>


<commit_before><commit_msg>Fix dumb linting error<commit_after><|endoftext|>


<commit_before>var xhrRequest = function (url, type, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function () {
    callback(this.responseText);
  };
  xhr.open(type, url);
  xhr.send();
};

function locationSuccess(pos) {
  // Construct URL
  var url = "http://api.openweathermap.org/data/2.5/weather?lat=" +
      pos.coords.latitude + "&lon=" + pos.coords.longitude;

  // Send request to OpenWeatherMap
  xhrRequest(url, 'GET',
    function(responseText) {
      // responseText contains a JSON object with weather info
      var json = JSON.parse(responseText);

      // Temperature in Kelvin requires adjustment
      var temperature = Math.round(((json.main.temp - 273.15)*9/5)+32);
      console.log("Temperature is " + temperature);

      // Conditions
      var conditions = json.weather[0].main;
      console.log("Conditions are " + conditions);

      // Assemble dictionary using our keys
      var dictionary = {
        "KEY_TEMPERATURE": temperature,
        "KEY_CONDITIONS": conditions
      };

      // Send to Pebble
      Pebble.sendAppMessage(dictionary,
        function(e) {
          console.log("Weather info sent to Pebble successfully!");
        },
        function(e) {
          console.log("Error sending weather info to Pebble!");
        }
      );
    }
  );
}

function locationError(err) {
  console.log("Error requesting location!");
}

function getWeather() {
  navigator.geolocation.getCurrentPosition(
    locationSuccess,
    locationError,
    {timeout: 15000, maximumAge: 60000}
  );
}

// Listen for when the watchface is opened
Pebble.addEventListener('ready',
  function(e) {
    console.log("PebbleKit JS ready!");

    // Get the initial weather
    getWeather();
  }
);

// Listen for when an AppMessage is received
Pebble.addEventListener('appmessage',
  function(e) {
    console.log("AppMessage received!");
    getWeather();
  }
);
<commit_msg>Removed weather js<commit_after><|endoftext|>


<commit_before>import "./vendor"
import sound from "./sound"
import Fire from "./fire"
import DB from "./db"
import $ from "jquery"
import _ from "ramda"
import Notifications from "./notifications"
import cryptoRandomString from "crypto-random-string"
import localforage from "localforage"
import MutationSummary from "mutation-summary"
import {Kefir} from "kefir"
import {Main} from "elm/Main.elm"

const isDevelopmentMode = process.env["NODE_ENV"] === "development"
const env = process.env
const npmPackageVersion = env["npm_package_version"]

const mutationObserverFocusSelectorStream = Kefir.stream(emitter => {

  const focusableEntityListItemSelector = ".focusable-list-item[tabindex=0]"
  const autoFocusSelector = ".auto-focus"
  const observer = new MutationSummary({
    callback: summaries => {
      // console.log(summaries)

      const autoFocusSummaryAdded = summaries[0].added
      if (!_.isEmpty(autoFocusSummaryAdded)) {
        //note: delaying auto-focus to ensure that it takes priority.
        setTimeout(() => emitter.emit(".auto-focus"), 0)
      }

      const focusInEntitySummary = summaries[1]
      const focusInEntitySummaryAdded = focusInEntitySummary.added
      if (!_.isEmpty(focusInEntitySummaryAdded)) {
        // console.log("focusInEntitySummary.added", focusInEntitySummaryAdded)
        emitter.emit(".focusable-list-item[tabindex=0]")
      }
    },
    queries: [{element: autoFocusSelector},
      {element: focusableEntityListItemSelector},
    ],
  })
})

window.appBoot = async function appBoot(elmMain = Main) {

  const deviceId = getOrCreateDeviceId()
  const $elm = $("#elm-container")
  // $elm.trap();

  $elm.on("keydown", `.entity-list`, e => {
    // console.log(e.keyCode, e.key, e.target, e);

    // prevent document scrolling
    if (e.key === " " || e.key === "ArrowUp" || e.key === "ArrowDown") {
      e.preventDefault()
    }

  })

  const db = await DB()

  const store = localforage.createInstance({
    name: "SimpleGTD.com offline store",
  });

  const getOfflineStore = async () => {
    const storeKeys = await store.keys()
    const storeValues = await _.compose(
        ps => Promise.all(ps), _.map(k => store.getItem(k)),
    )(storeKeys)
    return _.zipObj(storeKeys, storeValues)
  }
  const initialOfflineStore = await getOfflineStore()
  // console.log(initialOfflineStore)

  const flags = _.merge({
    now: Date.now(),
    pouchDBRemoteSyncURI: localStorage.getItem("pouchdb.remote-sync-uri") || "",
    developmentMode: isDevelopmentMode,
    config: {
      debug: WEBPACK_DEV_SERVER,
      deviceId,
      npmPackageVersion,
      isDevelopmentMode,
      initialOfflineStore,
    },
  }, db.allDocsMap)

  const app = elmMain
      .embed(document.getElementById("elm-container"), flags)

  const fire = Fire.setup(app, _.values(db.list), deviceId)

  db.setupApp(app)

  app.ports["persistToOfflineStore"].subscribe(([key, value]) => {
    store.setItem(key, value).catch(console.error)
  });

  Notifications.setup(fire, app).catch(console.error)

  const portFocusSelectorStream =
      Kefir.stream(emitter => {
        app.ports["focusSelector"].subscribe((selector) => {
          // console.log("port: focusSelector received selector", selector)
          emitter.emit(selector)
        })
      })

  const addMetadataToFocusSelectorStream =
      (stream, streamName) => stream.map(selector => ({streamName, selector}))

  const focusSelectorStreams =
      [addMetadataToFocusSelectorStream(
          portFocusSelectorStream,
          "portFocusSelectorStream",
      ),
       addMetadataToFocusSelectorStream(
           mutationObserverFocusSelectorStream,
           "mutationObserverFocusSelectorStream",
       )]
  Kefir.merge(focusSelectorStreams)
       .observe({
         value(options) {
           const $toFocus = $(options.selector).first()

           // console.log("[Kefir] focusSelector", _.merge(options, {
           // dataKey: $toFocus.data("key"),
           // }))

           $toFocus.focus()
         },
       })

  app.ports["positionPopupMenu"].subscribe((ofSelector) => {
    requestAnimationFrame(() => {
      const $popup = $("#popup-menu")
      $popup.position({
        my: "right top",
        at: "right top",
        of: $(ofSelector),
        within: ".overlay",
        collision: "fit",
      })
      $popup.find(".auto-focus").first().focus()

      const focusableSelector = ":focusable, input:focusable"
      $popup.on("keydown", focusableSelector, function (e) {
        if (e.key !== "Tab") return
        const $focusable = $popup.find(focusableSelector)

        const first = $focusable.first().get(0)
        const last = $focusable.last().get(0)
        const dateTimeInputSelector = `input[type="date"], input[type="time"]`

        if (e.shiftKey) {

          if (this === first) {
            e.preventDefault()
            e.stopPropagation()
            last.focus()
          } else if ($(this).is(dateTimeInputSelector)) {
            e.preventDefault()
            e.stopPropagation()
            $focusable.get($.inArray(this, $focusable) - 1).focus()
          }
        }
        else {

          if (this === last) {
            e.preventDefault()
            e.stopPropagation()
            first.focus()
          } else if ($(this).is(dateTimeInputSelector)) {
            e.preventDefault()
            e.stopPropagation()
            $focusable.get($.inArray(this, $focusable) + 1).focus()
          }
        }
      })
    })
  })

  app.ports["startAlarm"].subscribe(() => {
    sound.start()
  })

  app.ports["stopAlarm"].subscribe(() => {
    sound.stop()
  })
}

function getOrCreateDeviceId() {
  let deviceId = localStorage.getItem("device-id")
  if (!deviceId) {
    deviceId = cryptoRandomString(64)
    localStorage.setItem("device-id", deviceId)
  }
  return deviceId
}

function getOrCreateFirstVisit() {
  let firstVisit = localStorage.getItem("first-visit")
  if (!firstVisit) {
    localStorage.setItem("first-visit", "false")
  }
  return !!firstVisit
}
<commit_msg>WIP: fix focus entity list<commit_after>import "./vendor"
import sound from "./sound"
import Fire from "./fire"
import DB from "./db"
import $ from "jquery"
import _ from "ramda"
import Notifications from "./notifications"
import cryptoRandomString from "crypto-random-string"
import localforage from "localforage"
import MutationSummary from "mutation-summary"
import {Kefir} from "kefir"
import {Main} from "elm/Main.elm"

const isDevelopmentMode = process.env["NODE_ENV"] === "development"
const env = process.env
const npmPackageVersion = env["npm_package_version"]

const mutationObserverFocusSelectorStream = Kefir.stream(emitter => {

  const focusableEntityListItemSelector = ".focusable-list-item[tabindex=0]"
  const autoFocusSelector = ".auto-focus"
  const observer = new MutationSummary({
    callback: summaries => {
      // console.log(summaries)

      const autoFocusSummaryAdded = summaries[0].added
      if (!_.isEmpty(autoFocusSummaryAdded)) {
        //note: delaying auto-focus to ensure that it takes priority.
        setTimeout(() => emitter.emit(".auto-focus"), 0)
      }

      const focusInEntitySummary = summaries[1]
      const focusInEntitySummaryAdded = focusInEntitySummary.added
      if (!_.isEmpty(focusInEntitySummaryAdded)) {
        // console.log("focusInEntitySummary.added", focusInEntitySummaryAdded)
        emitter.emit(".focusable-list-item[tabindex=0]")
      }
    },
    queries: [{element: autoFocusSelector},
      {element: focusableEntityListItemSelector},
    ],
  })
})

window.appBoot = async function appBoot(elmMain = Main) {

  const deviceId = getOrCreateDeviceId()
  const $elm = $("#elm-container")
  // $elm.trap();

  $elm.on("keydown", `.entity-list`, e => {
    // console.log(e.keyCode, e.key, e.target, e);

    // prevent document scrolling
    if (e.key === " " || e.key === "ArrowUp" || e.key === "ArrowDown") {
      e.preventDefault()
    }

  })

  const db = await DB()

  const store = localforage.createInstance({
    name: "SimpleGTD.com offline store",
  });

  const getOfflineStore = async () => {
    const storeKeys = await store.keys()
    const storeValues = await _.compose(
        ps => Promise.all(ps), _.map(k => store.getItem(k)),
    )(storeKeys)
    return _.zipObj(storeKeys, storeValues)
  }
  const initialOfflineStore = await getOfflineStore()
  // console.log(initialOfflineStore)

  const flags = _.merge({
    now: Date.now(),
    pouchDBRemoteSyncURI: localStorage.getItem("pouchdb.remote-sync-uri") || "",
    developmentMode: isDevelopmentMode,
    config: {
      debug: WEBPACK_DEV_SERVER,
      deviceId,
      npmPackageVersion,
      isDevelopmentMode,
      initialOfflineStore,
    },
  }, db.allDocsMap)

  const app = elmMain
      .embed(document.getElementById("elm-container"), flags)

  const fire = Fire.setup(app, _.values(db.list), deviceId)

  db.setupApp(app)

  app.ports["persistToOfflineStore"].subscribe(([key, value]) => {
    store.setItem(key, value).catch(console.error)
  });

  Notifications.setup(fire, app).catch(console.error)

  const portFocusSelectorStream =
      Kefir.stream(emitter => {
        app.ports["focusSelector"].subscribe((selector) => {
          // console.log("port: focusSelector received selector", selector)
            emitter.emit(selector)
        })
      })

  const addMetadataToFocusSelectorStream =
      (stream, streamName) => stream.map(selector => ({streamName, selector}))

  const focusSelectorStreams =
      [addMetadataToFocusSelectorStream(
          portFocusSelectorStream,
          "portFocusSelectorStream",
      ),
       addMetadataToFocusSelectorStream(
           mutationObserverFocusSelectorStream,
           "mutationObserverFocusSelectorStream",
       )]
  Kefir.merge(focusSelectorStreams)
       .observe({
         value(options) {
           // todo: adding any delay causes entity list focus to go haywire.
           // even in focus selector port.
           // we need to completely control focus on entity list.
           // can't depended on mutation observer for the same.
           // can't have
           // setTimeout(()=>{
             const $toFocus = $(options.selector).first()

             // console.log("[Kefir] focusSelector", _.merge(options, {
             // dataKey: $toFocus.data("key"),
             // }))

             $toFocus.focus()
           // },0)
         },
       })

  app.ports["positionPopupMenu"].subscribe((ofSelector) => {
    requestAnimationFrame(() => {
      const $popup = $("#popup-menu")
      $popup.position({
        my: "right top",
        at: "right top",
        of: $(ofSelector),
        within: ".overlay",
        collision: "fit",
      })
      $popup.find(".auto-focus").first().focus()

      const focusableSelector = ":focusable, input:focusable"
      $popup.on("keydown", focusableSelector, function (e) {
        if (e.key !== "Tab") return
        const $focusable = $popup.find(focusableSelector)

        const first = $focusable.first().get(0)
        const last = $focusable.last().get(0)
        const dateTimeInputSelector = `input[type="date"], input[type="time"]`

        if (e.shiftKey) {

          if (this === first) {
            e.preventDefault()
            e.stopPropagation()
            last.focus()
          } else if ($(this).is(dateTimeInputSelector)) {
            e.preventDefault()
            e.stopPropagation()
            $focusable.get($.inArray(this, $focusable) - 1).focus()
          }
        }
        else {

          if (this === last) {
            e.preventDefault()
            e.stopPropagation()
            first.focus()
          } else if ($(this).is(dateTimeInputSelector)) {
            e.preventDefault()
            e.stopPropagation()
            $focusable.get($.inArray(this, $focusable) + 1).focus()
          }
        }
      })
    })
  })

  app.ports["startAlarm"].subscribe(() => {
    sound.start()
  })

  app.ports["stopAlarm"].subscribe(() => {
    sound.stop()
  })
}

function getOrCreateDeviceId() {
  let deviceId = localStorage.getItem("device-id")
  if (!deviceId) {
    deviceId = cryptoRandomString(64)
    localStorage.setItem("device-id", deviceId)
  }
  return deviceId
}

function getOrCreateFirstVisit() {
  let firstVisit = localStorage.getItem("first-visit")
  if (!firstVisit) {
    localStorage.setItem("first-visit", "false")
  }
  return !!firstVisit
}
<|endoftext|>